diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..dab52b85 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,23 @@ +# EditorConfig is awesome: http://visualstudiogallery.msdn.microsoft.com/c8bccfe2-650c-4b42-bc5c-845e21f96328 + +# top-most EditorConfig file +root = true + +# Windows-style newlines +[*] +end_of_line = crlf + +# 4 space indentation +[*.py] +indent_style = space +indent_size = 4 + +# 4 space indentation +[*.{c,cpp,h}] +indent_style = space +indent_size = 4 + +# 2 space indentation +[*.iss] +indent_style = space +indent_size = 2 \ No newline at end of file diff --git a/.gitignore b/.gitignore index 2a0399ac..ccfba2e0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,22 @@ -Debug -Release -C?Debug -CPP?Debug -*.ncb -*.suo -*.vcproj.*.*.user -*setup.exe \ No newline at end of file +obj/ +Debug/ +Debug (Unicode)/ +Release/ +Release (Unicode)/ +Win32/ +x64/ +*.vcxproj.user +*.*sdf +*.suo +ipch/ +setup/vld-*-setup.exe +setup/Output/ +lib/gtest/msvc/bin/ +_ReSharper.Caches/ +lib/cppformat/bin/ +src/bin/vld.ini +/src/tests/vld_ComTest/ComTest_i.h +/src/tests/vld_ComTest/ComTest_p.c +/src/tests/vld_ComTest/ComTest_i.c +*.VC.opendb +*.VC.db diff --git a/.mailmap b/.mailmap new file mode 100644 index 00000000..78547429 --- /dev/null +++ b/.mailmap @@ -0,0 +1,5 @@ +Arkadiy Shapkin KindDragon +Arkadiy Shapkin +Dan Moulding +Dan Moulding +Dan Moulding diff --git a/.teamcity/Vld/buildTypes/Vld_CompileAll.xml b/.teamcity/Vld/buildTypes/Vld_CompileAll.xml new file mode 100644 index 00000000..164e0d6c --- /dev/null +++ b/.teamcity/Vld/buildTypes/Vld_CompileAll.xml @@ -0,0 +1,22 @@ + + + Compile All + + + + + + + + + + + + + + + + + + + diff --git a/.teamcity/Vld/buildTypes/Vld_DebugCrtDllWin32.xml b/.teamcity/Vld/buildTypes/Vld_DebugCrtDllWin32.xml new file mode 100644 index 00000000..1cfae2f5 --- /dev/null +++ b/.teamcity/Vld/buildTypes/Vld_DebugCrtDllWin32.xml @@ -0,0 +1,60 @@ + + + Debug CrtDll Win32 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.teamcity/Vld/pluginData/plugin-settings.xml b/.teamcity/Vld/pluginData/plugin-settings.xml new file mode 100644 index 00000000..7ab93ea0 --- /dev/null +++ b/.teamcity/Vld/pluginData/plugin-settings.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/.teamcity/Vld/project-config.xml b/.teamcity/Vld/project-config.xml new file mode 100644 index 00000000..8e6d17f5 --- /dev/null +++ b/.teamcity/Vld/project-config.xml @@ -0,0 +1,7 @@ + + + VLD + + + + diff --git a/.teamcity/Vld/vcsRoots/Vld_HttpsGithubComKindDragonVldGitRefsHeadsMaster.xml b/.teamcity/Vld/vcsRoots/Vld_HttpsGithubComKindDragonVldGitRefsHeadsMaster.xml new file mode 100644 index 00000000..799b8d3a --- /dev/null +++ b/.teamcity/Vld/vcsRoots/Vld_HttpsGithubComKindDragonVldGitRefsHeadsMaster.xml @@ -0,0 +1,16 @@ + + + https://github.com/KindDragon/vld.git#refs/heads/master + + + + + + + + + + + + + diff --git a/AUTHORS.txt b/AUTHORS.txt new file mode 100644 index 00000000..c2a92336 --- /dev/null +++ b/AUTHORS.txt @@ -0,0 +1,25 @@ +------------------------------------------------ +KindDragon http://www.codeplex.com/site/users/view/KindDragon +chrisJohnson http://www.codeplex.com/site/users/view/chrisJohnson + +Contributors: (listed alphabetically) +------------------------------------------------ +akaStiX +benpmorgan +Eric Bissonnette +geordi +ioannis-e +jerker_back +jlddodger +Kristian Paradis +Laurent Lessieux (llessieux) +mnissl +snakefoot +VictorKharkov +xpol + +Many thanks to everyone who supported development without having +git push access. + +Based on the original version (C) 2005-2009 by Dan Moulding (e-mail dmoulding@gmail.com) +http://sites.google.com/site/dmoulding/vld diff --git a/CHANGES.txt b/CHANGES.txt index 649d62cf..0a820a8a 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,390 +1,565 @@ -Visual Leak Detector (VLD) Version 1.9h (beta) - - Change Log / Release Notes - -1.9h beta (24 February 2009) ----------------------------- - Enhancements: - + Added support to work with Visual Studio 2008. - - Known Bugs/Restrictions: - + Same bugs/restrictions as version 1.9f. - - -1.9g beta (16 April 2008) ----------------------------- - Bugs Fixed: - + Another deadlock condition may occur when loading DLLs into the process - being debugged. Special thanks to Eric Bissonnette and Kristian Paradis for - contributing this patch. - - Known Bugs/Restrictions: - + Same bugs/restrictions as version 1.9f. - - -1.9f beta (18 November 2006) ----------------------------- - Bugs Fixed: - + Deadlocks or access violations may occur when loading DLLs into - multithreaded processes. - - + In multithreaded programs, if the main thread terminates before other - threads in the process, then Visual Leak Detector may cause an access - violation while generating the memory leak report. - - Known Bugs/Restrictions: - + Memory allocations made through calls to functions loaded from a DLL using - delayed loading may not be detected. - - + Support for programs that use MFC 7.0 or MFC 7.1 is not complete yet. Some - memory leaks from such MFC-based programs may not be detected. - - + Visual Leak Detector may report leaks internal to Visual Leak Detector - if the main thread of the process terminates while other threads are still - running. - - + If more than one copy of the same C Runtime DLL is loaded in the process at - the same time, then some leaks may go undetected (note that loading more - than one copy of the C Runtime DLL into a process at the same time is - probably a bad idea to begin with). - - -1.9e beta (16 November 2006) ----------------------------- - New Features/Enhancements: - + Added a master on/off switch configuration option to vld.ini that can be - used to completely disable Visual Leak Detector. - - Bugs Fixed: - + Numerous deadlock situations. The multithread synchronization scheme has - been completely re-written which should make deadlocks in VLD much less - likey to happen. - - + An access violation will occur in VLD if GetProcAddress is called to obtain - an export's address by ordinal, for certain libraries. - - + Problems may potentially occur when the program being debugged exits due to - the Debug Help Library having been detached from the process too early. - Symptoms might include access violation exceptions or other erratic behavior - just as the program exits and while VLD is generating the leak report. - - + The copy of vld.ini installed in VLD's installation directory overrides any - other copies of vld.ini that are created, even copies placed in the - working directory of the program being debugged. - - Known Bugs/Restrictions: - + Memory allocations made through calls to functions loaded from a DLL using - delayed loading may not be detected. - - + Support for programs that use MFC 7.0 or MFC 7.1 is not complete yet. Some - memory leaks from such MFC-based programs may not be detected. - - + If more than one copy of the same C Runtime DLL is loaded in the process at - the same time, then some leaks may go undetected (note that loading more - than one copy of the C Runtime DLL into a process at the same time is - probably a bad idea to begin with). - - -1.9d beta (12 November 2006) ----------------------------- - Bugs Fixed: - + Failed assertion "freed == TRUE" pops up when running a program with VLD - without the debugger attached. - - + Some, but not all, multithreaded programs that dynamically load and unload - many DLLs have been known to experience problems, such as deadlocks or - exceptions, when used with VLD. - - + Failed assertion "exportmodule != NULL" pops up when running some programs - with VLD. - - + VLD fails to show file names or function names in the memory leak report for - some programs that are linked with the dynamic CRT library. - - + Access violation exceptions are thrown, but caught by the operating system, - when running some programs with VLD. - - -1.9c beta (6 November 2006) ---------------------------- - New Features/Enhancments: - + New NSIS installer makes setting up and using VLD much easier. - - + No need to manually copy dbghelp.dll to the right location, VLD will always - find the right version. - - + MFC 8.0 is now fully supported. - - + The memory leak report is now written to the output window much faster. - Support has been added, through a new configuration option, to slow down - the report output for older versions of Visual Studio that have trouble - when it is written too quickly. - - Bugs Fixed: - + All known compatibilities with Visual Studio 2005 have been eliminated. - - + Leaks from calloc may go undetected. - - + Leaks from vector new operator may go undetected. - - + VLDDisable and VLDEnable do not work as expected; some memory leaks that - should be ignored by VLD due to a previous call to VLDDisable are still - reported. - - + Unloading and reloading a previously loaded module may cause leaks that - occur in the module after it was reloaded to go undetected. - - + If vld.h is included in a release build, then the compiler will generate - errors if the VLDEnable or VLDDisable APIs have been used. - - -1.9b beta (26 October 2006) ---------------------------- - Bugs Fixed: - + Source compiles under Visual Studio 2005 and the binaries are compatible - with applications that link with the Visual Studio 2005 C Runtime Library - (msvcr80d.dll). - - Known Restrictions in this Release: - + Memory allocations made through calls to functions loaded from a DLL using - delayed loading may not be detected. - - + Support for programs that use MFC 7.0, MFC 7.1, or MFC 8.0 is not complete - yet. Some memory leaks from such MFC-based programs may not be detected. A - workaround for this restriction is to forcefully include the MFC DLLs in - memory leak detection, by setting the "ForceIncludeModules" configuration - option to: "mfc70d.dll mfc71d.dll mfc80d.dll" and explicitly adding vld.lib - as an input file on the linker command line (can be added through project - settings by adding it to the list of library modules in the linker options). - This restriction does not apply to programs that use MFC 4.2, which is fully - supported. - - -1.9a beta (9 March 2006) ------------------------- - New Features/Enhancments: - + All new leak detection engine detects most, if not all, in-process memory - leaks, not just leaks from "new" or "malloc", including COM-based leaks. - - + Packaged as an easier-to-use DLL. There's no longer any need to carefully - decide which modules should be linked with the VLD library. Instead, you - just include the vld.h header file in at least one source file from each - module (DLL or EXE) to be included in memory leak detection. - - + Configuration is done from an INI file instead of using preprocessor macros. - This allows VLD's configuration to be changed without needing to recompile - the program. - - + Many new configuration options have been added. One of the most often - requested option that has been added is the option to save the leak report - to a file instead of, or in addition to, the debugger. - - Bugs Fixed: - + The improved design of the new leak detection engine has resolved all of the - previously known restrictions in version 1.0. - - Known Restrictions in this Release: - + Memory allocations made through calls to functions loaded from a DLL using - delayed loading may not be detected. - - + Support for programs that use MFC 7.0, MFC 7.1, or MFC 8.0 is not complete - yet. Some memory leaks from such MFC-based programs may not be detected. A - workaround for this restriction is to forcefully include the MFC DLLs in - memory leak detection, by setting the "ForceIncludeModules" configuration - option to: "mfc70d.dll mfc71d.dll mfc80d.dll" and explicitly adding vld.lib - as an input file on the linker command line (can be added through project - settings by adding it to the list of library modules in the linker options). - This restriction does not apply to programs that use MFC 4.2, which is fully - supported. - - -1.0 (5 August 2005) -------------------- - New Features/Enhancements: - + Memory leak detection can now be selectively disabled and enabled at - runtime, using provided APIs. This provides a straightforward way of - allowing VLD to selectively "ignore" certain allocations. It can also be - used to disable VLD altogether at runtime, improving application performance - without needing to recompile. - - + If there are multiple identical memory leaks (i.e. leaks that originate from - the same call stack and that leak the same size memory block) then VLD can - optionally aggregate all of the repeated leaks, showing only the first such - leaked block in detail in the memory leak report. A tally of the total - number of leaks that match that particular size and call stack accompanies - the information for that leak. - - + When VLD is initialized at program startup, the library type which was - linked-in is displayed. This can help verify that the expected VLD library - (either single-threaded static, multithreaded static, or multithreaded DLL) - is being linked with your program. - - + The Visual Leak Detector name is displayed on most messages output to the - debugger to easily differentiate VLD's output from the output produced by - the built-in memory leak detector. - - + If any of the compile-time configuration options have been changed from - their default values, then the current state of the option is displayed in - the debugger when VLD is initialized. - - + VLD's memory leak self-checking capability (checking for leaks in VLD - itself) can be verified using a new preprocessor macro that allows VLD to - perform a self-test at runtime. - - Bugs Fixed: - + If the MFC libraries are statically linked to the program being debugged, - then MFC will erroneously report memory leaks in the Visual Leak Detector - code and may cause an access violation while attempting to report the false - memory leaks. These bogus leaks are always reported as "client block at -
, subtype bf42" and are claimed to be "invalid objects". - - + VLD will leak a fixed-sized block of memory when the program exits if VLD - failed to initialize because the Debug Help library (dbghelp.dll) could not - be loaded. - - + In multithreaded programs, if the program's main thread terminates before - other threads in the same process, then VLD may cause an access violation - while freeing resources used internally by VLD. - - -0.9i beta (30 April 2005) -------------------------- - New Features/Enhancements: - + Added support in the source code for x64 architecture. The pre-built - libraries will continue to support 32-bit only. If you need 64-bit support - you'll need to build 64-bit versions of the libraries from source. Note that - x64 is the only 64-bit architecture supported at this time. Itanium (aka - IA-64) is NOT currently supported. - - Bugs Fixed: - + VLD does not report memory leaks that are the result of a failure to free - memory allocated via a call to realloc(). - + In multithreaded programs, if the program's main thread terminates before - other threads in the same process, then VLD may cause an access violation - while checking for memory leaks. - + If VLD cannot find the source file and line number information for a program - address, the last known file and line number will be repeated in the call - stack section of the memory leak report. The correct behavior should be for - VLD to print "File and line number not available" for that call stack entry. - - -0.9h beta (22 April 2005) -------------------------- - Bugs Fixed: - + Access Violations occur at random places within the VLD code when using - VLD version 0.9g. - + When using VLD version 0.9g, VLD may fail to report some memory leaks. - - -0.9g beta (22 April 2005) -------------------------- - New Features/Enhancements: - + Replaced the temporary internal search algorithm with a permanent search - algorithm that is much faster. Programs that dynamically allocate a large - number of memory blocks (tens of thousands or more) will see the most - significant performance boost from this version of VLD versus the previous - version. Overall, this is the fastest version of VLD released to date. - - -0.9f beta (13 April 2005) -------------------------- - New Features/Enhancements: - + Changed the internal search algorithm to a temporary simpler, but - more stable algorithm. A permanent algorithm which should be much - more efficient will be in a forthcoming release. - - Bugs Fixed: - + Access Violation at line 319 in vldutil.cpp may occur when running a - program linked with the VLD library. - - -0.9e beta (12 April 2005) -------------------------- - New Features/Enhancements: - + VLD no longer uses any STL containers or STL strings. This solves all of the - compatibility problems with Visual Studio .NET when using the pre-built - VLD libraries. - - + The configuration preprocessor macros now work with C programs without the - need to call VLDConfigure from within the program being debugged. - Because VLDConfigure is now obsolete, it has been removed. - - + One new source file (vldutil.cpp) and one new header (vldutil.h) have been - added. They contain utility functions and utility classes that replace - functionality previously performed by STL containers and strings. - - + The VisualLeakDetector global class object is now constructed at C runtime - initialization (i.e. it resides in the "compiler" initialization area). - Because VLD no longer uses any STL components, there is no longer the risk - that VLD will conflict with any STL libraries that also are constructed at - C runtime initialization. The end result is that VLD starts running earlier - and is destroyed later, which leads to more accurate leak detection. - - Bugs Fixed: - + Linking to the VLD 0.9d libraries from the VLD distribution under Visual - Studio .NET results in a number of linker "unresolved external symbol" - errors. Unresolved symbols include "__declspec(dllimport) void __cdecl - std::_Xran(void)" and "__declspec(dllimport) private: void __thiscall - std::basic_string,class std::allocator >::_Eos(unsigned int)", among others. - - + Call stacks do not appear in the memory leak report when linking against - release VLD libraries built from source with Visual Studio .NET. - - + If the preprocessor macro VLD_MAX_DATA_DUMP is defined as 0 (zero), then VLD - will get stuck in an infinite loop, repeatedly printing the same information - while attempting to display the memory leak report in the debugger's output - window. - - -0.9d beta (30 March 2005) -------------------------- - New Features/Enhancements: - + This version of VLD brings with it some major changes to the way VLD - interfaces with programs that use it. Instead of requiring that VLD be built - from source and then linked with the application, VLD is now packaged as a - pre-built static library. For those who just want to use VLD and are not - interested in modifying the source, this eliminates the complexities of - building VLD from source. A single header file, vld.h, has been added. To - link with the static library, this header needs to be included in one of the - program's source files. Please see the README.txt file for details on how - these changes affect how to use Visual Leak Detector. - - + The Microsoft Debug Help Library (dbghelp.dll) version 6.3 is now included - with the VLD distribution. - - -0.9c beta (17 March 2005) -------------------------- - Bugs Fixed: - + Compile error, "error C2039: 'size' : is not a member of '_CrtMemBlockHeader'" - occurs at line 644 of vld.cpp when building VLD with the VLD_MAX_DATA_DUMP - preprocessor macro defined. - - -0.9b beta (15 March 2005) -------------------------- - Bugs Fixed: - + VLD fails to detect memory leaks in class constructors if the objects - constructed are global objects. - - + If a debug executable is built with certain compiler optimizations turned on, - specifically frame pointer omission optimization or automatic inlining, then - theoretically VLD may produce incomplete or inaccurate stack traces or might - fail to produce stack traces altogether. - - -0.9a beta (12 March 2005) -------------------------- - Initial Public Release - - - - - - - - - - - - +Visual Leak Detector (VLD) Version 2.5.1 + + + Change Log / Release Notes + +2.5.1 (30 January 2017) +---------------------------- + Enhancements: + + PDB added to installer. + + Bugs Fixed: + + Fix ntdll loader patch for Windows 10 (1607) Anniversary Update causing crashes (thanks to ioannis-e). + + Vld dll loading order fixed with MFC. + + Supressible msgboxes in setup with cmdline /silent /suppressmsgboxes. + +2.5 (09 January 2016) +---------------------------- + Enhancements: + + VS2015 support added. + + Windows 10 support added. + + Support MFC 12 MBCS (thanks to mnissl). + + VLD config through env. vars (thanks to akaStiX). + + Support detection DllMain allocations (thanks to ioannis-e). + + Add option to skip reporting crt startup allocations as memory leaks (thanks to ioannis-e). + + Improve the vld.ini searching from additional locations (thanks to ioannis-e). + + Changed implementation of FastCallStack::getStackTrace for 32-bit code. + + Bugs Fixed: + + Fix #9519, #9859, #10544, use LoaderLock to serialize any calls which load additional libraries or require access to the Loader Lock (thanks to ioannis-e). + + Fix #6359, #10553, fix crashes and failure to register COM dlls where Visual Leak Detector is unloaded before IMalloc interface is released (thanks to ioannis-e). + + Fix #10548, vld.ini search path (thanks to ioannis-e). + + Fix #10587, Visual Leak Detector reporting strange leaks in CRT module of VC++ (thanks to ioannis-e). + + Fix #10588, false positives from CRT in VS2013 with /MTd (thanks to ioannis-e). + + Deadlock fixed with StackWalkMethod=safe. + +2.4RC2 (07 April 2014) +---------------------------- + Enhancements: + + VLD will display last internal frame. + + Installer also add path for static library. + + Bugs Fixed: + + Internal memory leak fixed. + +2.4RC (23 March 2014) +---------------------------- + Enhancements: + + VS2013 support added. + + Improved usage in C code. + + Setup rewrited to InnoSetup, autopatching common props implemented for VS2008-2013. + + Called allocation function added to printed callstack. + ! Memory leaks count fixed for case static/dynamic linked MFC. + ! Release static linked CRT detection improved (VLD_OPT_RELEASE_CRT_RUNTIME define removed). + + Bugs Fixed: + + Memory leaks with static linked CRT fixed for VS2012/2013. + + Deadlock fixed and missed memory leaks when dll loading (first appear in version 2.2.2). + +2.3 (29 April 2013) +---------------------------- + Enhancements: + + Windows 8 support added. + + Bugs Fixed: + + Memory leaks with duplicate thread id fixed (thanks to jlddodger). + +2.2.3 (15 Febrary 2012) +---------------------------- + Enhancements: + + New option VLD_OPT_RELEASE_CRT_RUNTIME added. Useful only with define VLD_FORCE_ENABLE. + + Bugs Fixed: + + Memory leaks with static linking fixed finally. + +2.2.2 (18 December 2011) +---------------------------- + Bugs Fixed: + + Memory leaks with static linking fixed. + + Visual Studio C++ 2008/2010 Express Edition compilation fixed. + + Hang fixed with GetOpenFileName(). + +2.2.1 (22 November 2011) +---------------------------- + Enhancements: + + strdup and _wcsdup functions support added. + + Preliminary support for VS 11 added. + + Bugs Fixed: + + Low performance after upgrading from VLD v2.1. + + Runtime error R6002 fixed because of wrong memory dump format. + + version.h fixed in installer. + + Some PVS studio warning fixed. + +2.2 (21 Jule 2011) +---------------------------- + Enhancements: + + New functions added: VLDSetReportHook. + + Bugs Fixed: + + Resolved call stack printing fixed. + +2.2b (8 Jule 2011) +---------------------------- + Enhancements: + + New functions added: VLDGetLeaksCount, VLDMarkAllLeaksAsReported (see vld.h). + + Introduced define called VLD_FORCE_ENABLE that allows one to active VLD even if not running in DEBUG. + + Adding Heap Validation. + + _aligned... functions and _recalloc support added. + + Memory leaks additional statistic added. + + Bugs Fixed: + + Issue fixed with loading wrong version of dbghelp.dll on Windows XP and bellow. + + VLDReportLeaks with aggregate duplicate links fixed. + + CoTaskMemAlloc memory leak detection fixed. + + Rare crash at exit on some platforms fixed. + + Asserts in release build disabled. + + LoaderLock fixed. + + LoadLibrary crash fixed with some applications like regsrv32. + + Callstack hash fixed with ASLR. + + VLDGlobalEnable fixed with new threads. + + Option VLD_OPT_MODULE_LIST_INCLUDE fixed. + +2.1 (26 March 2011) +---------------------------- + Enhancements: + + New functions added: VLDGlobalDisable, VLDGlobalEnable, VLDGetOptions, + VLDGetReportFilename, VLDSetOptions, VLDSetModulesList, + VLDGetModulesList, VLDResolveCallstacks (see vld.h). + + Option VLD_OPT_SKIP_HEAPFREE_LEAKS added. + + Hash for each leak added + + Supported loading symbols from Visual Studio symbol cache directory + + Bugs Fixed: + + Improved LdrLoadDll, GetProcAddress hooking on Windows 7. + + "HMODULE not founded" bug fixed. + + Bugs fixed when VLD off. + + Problem fixed with GetModuleHandleW for SxS dll's (mfc*.dll, msvcr*.dll). + + Unicode-to-multibyte conversion fixed. + +2.1 (26 March 2011) +---------------------------- + Enhancements: + + New functions added: VLDGlobalDisable, VLDGlobalEnable, VLDGetOptions, + VLDGetReportFilename, VLDSetOptions, VLDSetModulesList, + VLDGetModulesList, VLDResolveCallstacks (see vld.h). + + Option VLD_OPT_SKIP_HEAPFREE_LEAKS added. + + Hash for each leak added + + Supported loading symbols from Visual Studio symbol cache directory + + Bugs Fixed: + + Improved LdrLoadDll, GetProcAddress hooking on Windows 7. + + "HMODULE not founded" bug fixed. + + Bugs fixed when VLD off. + + Problem fixed with GetModuleHandleW for SxS dll's (mfc*.dll, msvcr*.dll). + + Unicode-to-multibyte conversion fixed. + +2.0b (24 August 2010) +---------------------------- + Enhancements: + + Added new commands: VLDReportLeaks, VLDRefreshModules, VLDEnableModule, + VLDDisableModule, VLDSetReportOptions (see vld.h). + + Bugs Fixed: + + Problems with MSVC 2008 SP1 fixed. Thanks to Laurent Lessieux for contributing this patch. + +2.0a (13 May 2010) +---------------------------- + Enhancements: + + Renamed vld dll files. + + Bugs Fixed: + + Problem with MSVC 2010 Unicode library fixed. + +2.0 (25 April 2010) +---------------------------- + Enhancements: + + Added support to work with 64-bit applications + + Added support to work with Visual Studio 2010 + +1.9h beta (24 February 2009) +---------------------------- + Enhancements: + + Added support to work with Visual Studio 2008. + + Known Bugs/Restrictions: + + Same bugs/restrictions as version 1.9f. + + +1.9g beta (16 April 2008) +---------------------------- + Bugs Fixed: + + Another deadlock condition may occur when loading DLLs into the process + being debugged. Special thanks to Eric Bissonnette and Kristian Paradis for + contributing this patch. + + Known Bugs/Restrictions: + + Same bugs/restrictions as version 1.9f. + + +1.9f beta (18 November 2006) +---------------------------- + Bugs Fixed: + + Deadlocks or access violations may occur when loading DLLs into + multithreaded processes. + + + In multithreaded programs, if the main thread terminates before other + threads in the process, then Visual Leak Detector may cause an access + violation while generating the memory leak report. + + Known Bugs/Restrictions: + + Memory allocations made through calls to functions loaded from a DLL using + delayed loading may not be detected. + + + Support for programs that use MFC 7.0 or MFC 7.1 is not complete yet. Some + memory leaks from such MFC-based programs may not be detected. + + + Visual Leak Detector may report leaks internal to Visual Leak Detector + if the main thread of the process terminates while other threads are still + running. + + + If more than one copy of the same C Runtime DLL is loaded in the process at + the same time, then some leaks may go undetected (note that loading more + than one copy of the C Runtime DLL into a process at the same time is + probably a bad idea to begin with). + + +1.9e beta (16 November 2006) +---------------------------- + New Features/Enhancements: + + Added a master on/off switch configuration option to vld.ini that can be + used to completely disable Visual Leak Detector. + + Bugs Fixed: + + Numerous deadlock situations. The multithread synchronization scheme has + been completely re-written which should make deadlocks in VLD much less + likely to happen. + + + An access violation will occur in VLD if GetProcAddress is called to obtain + an export's address by ordinal, for certain libraries. + + + Problems may potentially occur when the program being debugged exits due to + the Debug Help Library having been detached from the process too early. + Symptoms might include access violation exceptions or other erratic behavior + just as the program exits and while VLD is generating the leak report. + + + The copy of vld.ini installed in VLD's installation directory overrides any + other copies of vld.ini that are created, even copies placed in the + working directory of the program being debugged. + + Known Bugs/Restrictions: + + Memory allocations made through calls to functions loaded from a DLL using + delayed loading may not be detected. + + + Support for programs that use MFC 7.0 or MFC 7.1 is not complete yet. Some + memory leaks from such MFC-based programs may not be detected. + + + If more than one copy of the same C Runtime DLL is loaded in the process at + the same time, then some leaks may go undetected (note that loading more + than one copy of the C Runtime DLL into a process at the same time is + probably a bad idea to begin with). + + +1.9d beta (12 November 2006) +---------------------------- + Bugs Fixed: + + Failed assertion "freed == TRUE" pops up when running a program with VLD + without the debugger attached. + + + Some, but not all, multithreaded programs that dynamically load and unload + many DLLs have been known to experience problems, such as deadlocks or + exceptions, when used with VLD. + + + Failed assertion "exportmodule != NULL" pops up when running some programs + with VLD. + + + VLD fails to show file names or function names in the memory leak report for + some programs that are linked with the dynamic CRT library. + + + Access violation exceptions are thrown, but caught by the operating system, + when running some programs with VLD. + + +1.9c beta (6 November 2006) +--------------------------- + New Features/Enhancements: + + New NSIS installer makes setting up and using VLD much easier. + + + No need to manually copy dbghelp.dll to the right location, VLD will always + find the right version. + + + MFC 8.0 is now fully supported. + + + The memory leak report is now written to the output window much faster. + Support has been added, through a new configuration option, to slow down + the report output for older versions of Visual Studio that have trouble + when it is written too quickly. + + Bugs Fixed: + + All known compatibilities with Visual Studio 2005 have been eliminated. + + + Leaks from calloc may go undetected. + + + Leaks from vector new operator may go undetected. + + + VLDDisable and VLDEnable do not work as expected; some memory leaks that + should be ignored by VLD due to a previous call to VLDDisable are still + reported. + + + Unloading and reloading a previously loaded module may cause leaks that + occur in the module after it was reloaded to go undetected. + + + If vld.h is included in a release build, then the compiler will generate + errors if the VLDEnable or VLDDisable APIs have been used. + + +1.9b beta (26 October 2006) +--------------------------- + Bugs Fixed: + + Source compiles under Visual Studio 2005 and the binaries are compatible + with applications that link with the Visual Studio 2005 C Runtime Library + (msvcr80d.dll). + + Known Restrictions in this Release: + + Memory allocations made through calls to functions loaded from a DLL using + delayed loading may not be detected. + + + Support for programs that use MFC 7.0, MFC 7.1, or MFC 8.0 is not complete + yet. Some memory leaks from such MFC-based programs may not be detected. A + workaround for this restriction is to forcefully include the MFC DLLs in + memory leak detection, by setting the "ForceIncludeModules" configuration + option to: "mfc70d.dll mfc71d.dll mfc80d.dll" and explicitly adding vld.lib + as an input file on the linker command line (can be added through project + settings by adding it to the list of library modules in the linker options). + This restriction does not apply to programs that use MFC 4.2, which is fully + supported. + + +1.9a beta (9 March 2006) +------------------------ + New Features/Enhancements: + + All new leak detection engine detects most, if not all, in-process memory + leaks, not just leaks from "new" or "malloc", including COM-based leaks. + + + Packaged as an easier-to-use DLL. There's no longer any need to carefully + decide which modules should be linked with the VLD library. Instead, you + just include the vld.h header file in at least one source file from each + module (DLL or EXE) to be included in memory leak detection. + + + Configuration is done from an INI file instead of using preprocessor macros. + This allows VLD's configuration to be changed without needing to recompile + the program. + + + Many new configuration options have been added. One of the most often + requested option that has been added is the option to save the leak report + to a file instead of, or in addition to, the debugger. + + Bugs Fixed: + + The improved design of the new leak detection engine has resolved all of the + previously known restrictions in version 1.0. + + Known Restrictions in this Release: + + Memory allocations made through calls to functions loaded from a DLL using + delayed loading may not be detected. + + + Support for programs that use MFC 7.0, MFC 7.1, or MFC 8.0 is not complete + yet. Some memory leaks from such MFC-based programs may not be detected. A + workaround for this restriction is to forcefully include the MFC DLLs in + memory leak detection, by setting the "ForceIncludeModules" configuration + option to: "mfc70d.dll mfc71d.dll mfc80d.dll" and explicitly adding vld.lib + as an input file on the linker command line (can be added through project + settings by adding it to the list of library modules in the linker options). + This restriction does not apply to programs that use MFC 4.2, which is fully + supported. + + +1.0 (5 August 2005) +------------------- + New Features/Enhancements: + + Memory leak detection can now be selectively disabled and enabled at + runtime, using provided APIs. This provides a straightforward way of + allowing VLD to selectively "ignore" certain allocations. It can also be + used to disable VLD altogether at runtime, improving application performance + without needing to recompile. + + + If there are multiple identical memory leaks (i.e. leaks that originate from + the same call stack and that leak the same size memory block) then VLD can + optionally aggregate all of the repeated leaks, showing only the first such + leaked block in detail in the memory leak report. A tally of the total + number of leaks that match that particular size and call stack accompanies + the information for that leak. + + + When VLD is initialized at program startup, the library type which was + linked-in is displayed. This can help verify that the expected VLD library + (either single-threaded static, multithreaded static, or multithreaded DLL) + is being linked with your program. + + + The Visual Leak Detector name is displayed on most messages output to the + debugger to easily differentiate VLD's output from the output produced by + the built-in memory leak detector. + + + If any of the compile-time configuration options have been changed from + their default values, then the current state of the option is displayed in + the debugger when VLD is initialized. + + + VLD's memory leak self-checking capability (checking for leaks in VLD + itself) can be verified using a new preprocessor macro that allows VLD to + perform a self-test at runtime. + + Bugs Fixed: + + If the MFC libraries are statically linked to the program being debugged, + then MFC will erroneously report memory leaks in the Visual Leak Detector + code and may cause an access violation while attempting to report the false + memory leaks. These bogus leaks are always reported as "client block at +
, subtype bf42" and are claimed to be "invalid objects". + + + VLD will leak a fixed-sized block of memory when the program exits if VLD + failed to initialize because the Debug Help library (dbghelp.dll) could not + be loaded. + + + In multithreaded programs, if the program's main thread terminates before + other threads in the same process, then VLD may cause an access violation + while freeing resources used internally by VLD. + + +0.9i beta (30 April 2005) +------------------------- + New Features/Enhancements: + + Added support in the source code for x64 architecture. The pre-built + libraries will continue to support 32-bit only. If you need 64-bit support + you'll need to build 64-bit versions of the libraries from source. Note that + x64 is the only 64-bit architecture supported at this time. Itanium (aka + IA-64) is NOT currently supported. + + Bugs Fixed: + + VLD does not report memory leaks that are the result of a failure to free + memory allocated via a call to realloc(). + + In multithreaded programs, if the program's main thread terminates before + other threads in the same process, then VLD may cause an access violation + while checking for memory leaks. + + If VLD cannot find the source file and line number information for a program + address, the last known file and line number will be repeated in the call + stack section of the memory leak report. The correct behavior should be for + VLD to print "File and line number not available" for that call stack entry. + + +0.9h beta (22 April 2005) +------------------------- + Bugs Fixed: + + Access Violations occur at random places within the VLD code when using + VLD version 0.9g. + + When using VLD version 0.9g, VLD may fail to report some memory leaks. + + +0.9g beta (22 April 2005) +------------------------- + New Features/Enhancements: + + Replaced the temporary internal search algorithm with a permanent search + algorithm that is much faster. Programs that dynamically allocate a large + number of memory blocks (tens of thousands or more) will see the most + significant performance boost from this version of VLD versus the previous + version. Overall, this is the fastest version of VLD released to date. + + +0.9f beta (13 April 2005) +------------------------- + New Features/Enhancements: + + Changed the internal search algorithm to a temporary simpler, but + more stable algorithm. A permanent algorithm which should be much + more efficient will be in a forthcoming release. + + Bugs Fixed: + + Access Violation at line 319 in vldutil.cpp may occur when running a + program linked with the VLD library. + + +0.9e beta (12 April 2005) +------------------------- + New Features/Enhancements: + + VLD no longer uses any STL containers or STL strings. This solves all of the + compatibility problems with Visual Studio .NET when using the pre-built + VLD libraries. + + + The configuration preprocessor macros now work with C programs without the + need to call VLDConfigure from within the program being debugged. + Because VLDConfigure is now obsolete, it has been removed. + + + One new source file (vldutil.cpp) and one new header (vldutil.h) have been + added. They contain utility functions and utility classes that replace + functionality previously performed by STL containers and strings. + + + The VisualLeakDetector global class object is now constructed at C runtime + initialization (i.e. it resides in the "compiler" initialization area). + Because VLD no longer uses any STL components, there is no longer the risk + that VLD will conflict with any STL libraries that also are constructed at + C runtime initialization. The end result is that VLD starts running earlier + and is destroyed later, which leads to more accurate leak detection. + + Bugs Fixed: + + Linking to the VLD 0.9d libraries from the VLD distribution under Visual + Studio .NET results in a number of linker "unresolved external symbol" + errors. Unresolved symbols include "__declspec(dllimport) void __cdecl + std::_Xran(void)" and "__declspec(dllimport) private: void __thiscall + std::basic_string,class std::allocator >::_Eos(unsigned int)", among others. + + + Call stacks do not appear in the memory leak report when linking against + release VLD libraries built from source with Visual Studio .NET. + + + If the preprocessor macro VLD_MAX_DATA_DUMP is defined as 0 (zero), then VLD + will get stuck in an infinite loop, repeatedly printing the same information + while attempting to display the memory leak report in the debugger's output + window. + + +0.9d beta (30 March 2005) +------------------------- + New Features/Enhancements: + + This version of VLD brings with it some major changes to the way VLD + interfaces with programs that use it. Instead of requiring that VLD be built + from source and then linked with the application, VLD is now packaged as a + pre-built static library. For those who just want to use VLD and are not + interested in modifying the source, this eliminates the complexities of + building VLD from source. A single header file, vld.h, has been added. To + link with the static library, this header needs to be included in one of the + program's source files. Please see the README.txt file for details on how + these changes affect how to use Visual Leak Detector. + + + The Microsoft Debug Help Library (dbghelp.dll) version 6.3 is now included + with the VLD distribution. + + +0.9c beta (17 March 2005) +------------------------- + Bugs Fixed: + + Compile error, "error C2039: 'size' : is not a member of '_CrtMemBlockHeader'" + occurs at line 644 of vld.cpp when building VLD with the VLD_MAX_DATA_DUMP + preprocessor macro defined. + + +0.9b beta (15 March 2005) +------------------------- + Bugs Fixed: + + VLD fails to detect memory leaks in class constructors if the objects + constructed are global objects. + + + If a debug executable is built with certain compiler optimizations turned on, + specifically frame pointer omission optimization or automatic inlining, then + theoretically VLD may produce incomplete or inaccurate stack traces or might + fail to produce stack traces altogether. + + +0.9a beta (12 March 2005) +------------------------- + Initial Public Release + + + + + + + + + + + + diff --git a/COPYING.txt b/COPYING.txt index a6bd700d..073dd57f 100644 --- a/COPYING.txt +++ b/COPYING.txt @@ -1,458 +1,458 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/README.html b/README.html deleted file mode 100644 index 1eac0e8c..00000000 --- a/README.html +++ /dev/null @@ -1,780 +0,0 @@ - - - - - - - - - - Visual Leak Detector (Beta) - - - - - - - - -
- -

Visual Leak Detector 1.9h (Beta)

- -

Enhanced Memory Leak Detection for Visual C++

- -
- - - - -
- - - - - - -

Introduction

- -

Visual C++ provides built-in memory leak detection, but its capabilities are minimal at best. This memory leak - detector was created as a free alternative to the built-in memory leak detector provided with Visual C++. Here - are some of Visual Leak Detector's features, none of which exist in the built-in detector:

- -
    -
  • Provides a complete stack trace for each leaked block, including source file and line number information when - available.
  • - -
  • Detects most, if not all, types of in-process memory leaks including COM-based leaks, and pure Win32 heap-based - leaks.
  • - -
  • Selected modules (DLLs or even the main EXE) can be excluded from leak detection.
  • - -
  • Provides complete data dumps (in hex and ASCII) of leaked blocks.
  • - -
  • Customizable memory leak report: can be saved to a file or sent to the debugger and can include a variable level - of detail.
  • -
- -

Other after-market leak detectors for Visual C++ are already available. But most of the really popular ones, - like Purify and BoundsChecker, are very expensive. A few free alternatives exist, but they're often too intrusive, - restrictive, or unreliable. Visual Leak Detector is currently the only freely available memory leak - detector for Visual C++ that provides all of the above professional-level features packaged neatly in an easy-to-use - library.

- -

Visual Leak Detector is licensed free of charge as a service to the Windows developer - community. If you find it to be useful and would like to just say "Thanks!", or you think it stinks and would like to - say "This thing sucks!", please feel free to drop me a note. Or, if you'd - prefer, you can contribute a small donation. Both are very appreciated.

- - - - -

Using Visual Leak Detector

- -

This section briefly describes the basics of using Visual Leak Detector (VLD).

- -

Important! : Before using VLD with any Visual C++ project, you must first add the Visual Leak - Detector include and library directories to the Visual C++ include and library directory search paths:

- -
    -
  • Visual C++ 8 and 9: Go to Tools -> Options -> Projects and Solutions -> VC++ Directories. - Select "Include files" from the "Show Directories For" drop-down menu. Add the - include subdirectory from the Visual Leak Detector installation directory. Move it - to the bottom of the list. Then select "Library files" from the drop-down menu and add the - lib subdirectory from the Visual Leak Detector installation directory. Again, move - it to the bottom of the list.
  • - -
  • Visual C++ 7: Go to Project Properties -> C/C++ -> General -> Additional Include - Directories and add the include subdirectory from the Visual Leak Detector - installation directory. Move it to the bottom of the list. Then select Additional Library Directories and add - the lib subdirectory from the Visual Leak Detector installation directory. Again, - move it to the bottom of the list.
  • - -
  • Visual C++ 6: Go to Tools -> Options -> Directories. Select "Include files" from - the "Show Directories For" drop-down menu. Add the include subdirectory - from the Visual Leak Detector installation directory. Move it to the bottom of the list. Then select "Library - files" from the drop-down menu and add the lib subdirectory from the Visual Leak - Detector installation directory. Again, move it to the bottom of the list.
  • -
- -

To use VLD with your project, follow these simple steps:

- -
    -
  1. In at least one C/C++ source file from your program, include the vld.h header - file. It should not matter which file you add the include statement to. It also should not matter in what order - the header is included in relation to other headers. The only exception is - stdafx.h (or any other precompiled header). A precompiled header, such as - stdafx.h, must always be the first header included in a source file, so - vld.h must be included after any precompiled headers.
  2. - -
  3. If your program contains one or more DLLs that you would also like to check for memory leaks, then also include - vld.h in at least one source file from each DLL to be included in leak - detection.
  4. - -
  5. Build the debug version of your program.
  6. -
- -

Note: Unlike earlier (pre-1.9) versions of VLD, it is now acceptable to include - vld.h in every source file, or to include it in a common header that is included by - many or all source files. Only one copy of the VLD code will be loaded into the process, regardless of how many - source files include vld.h.

- -

VLD will detect memory leaks in your program whenever you run the debug version. When you run the program under the - Visual C++ debugger, a report of all the memory leaks detected will be displayed in the debugger's output window - when your program exits (the report can optionally be saved to a file instead, see - ReportFile under Configuration Options). Double-clicking on a - source file's line number in the memory leak report will take you to that file and line in the editor window, - allowing easy navigation of the code path leading up to the allocation that resulted in the memory leak.

- -

Note: When you build release versions of your program, VLD will not be linked into the - executable. So it is safe to leave vld.h included in your source files when doing - release builds. Doing so will not result in any performance degradation or any other undesirable overhead.

- - - - -

Configuration Options

- -

There are a several configuration options that control specific aspects of VLD's operation. These configuration - options are stored in the vld.ini configuration file. By default, the configuration - file should be in the Visual Leak Detector installation directory. However, the configuration file can be copied to - the program's working directory, in which case the configuration settings in that copy of - vld.ini will apply only when debugging that one program.

- -
-
VLD
-
-

This option acts as a master on/off switch. By default, this option is set to "on". To completely - disable Visual Leak Detector at runtime, set this option to "off". When VLD is turned off using this - option, it will do nothing but print a message to the debugger indicating that it has been turned off.

-
- -
AggregateDuplicates
-
-

Normally, VLD displays each individual leaked block in detail. Setting this option to "yes" will make VLD - aggregate all leaks that share the same size and call stack under a single entry in the memory leak report. - Only the first leaked block will be reported in detail. No other identical leaks will be displayed. Instead, - a tally showing the total number of leaks matching that size and call stack will be shown. This can be useful - if there are only a few sources of leaks, but those few sources are repeatedly leaking a very large number of - memory blocks.

-
- -
ForceIncludeModules
-
-

In some rare cases, it may be necessary to include a module in leak detection, but it may not be possible to - include vld.h in any of the module's sources. In such cases, this option can be - used to force VLD to include those modules in leak detection. List the names of the modules (DLLs) to be - forcefully included in leak detection. If you do use this option, it's advisable to also add - vld.lib to the list of library modules in the linker options of your project's - settings.

- -

Caution: Use this option only when absolutely necessary. In some situations, - use of this option may result in unpredictable behavior including false leak reports and/or crashes. It's - best to stay away from this option unless you are sure you understand what you are doing.

-
- -
MaxDataDump
-
-

Set this option to an integer value to limit the amount of data displayed in memory block data dumps. When - this number of bytes of data have been dumped, the dump will stop. This can be useful if any of the leaked - blocks are very large and the debugger's output window becomes too cluttered. You can set this option to 0 - (zero) if you want to suppress data dumps altogether.

-
- -
MaxTraceFrames
-
-

By default, VLD will trace the call stack for each allocated block as far back as possible. Each frame traced - adds additional overhead (in both CPU time and memory usage) to your debug executable. If you'd like to limit - this overhead, you can define this macro to an integer value. The stack trace will stop when it has traced - this number of frames. The frame count may include some of the "internal" frames which, by default, are not - displayed in the debugger's output window (see TraceInternalFrames below). In - some cases there may be about three or four "internal" frames at the beginning of the call stack. Keep this - in mind when using this macro, or you may not see the number of frames you expect.

-
- -
ReportEncoding
-
-

When the memory leak report is saved to a file, the report may optionally be Unicode encoded instead of using - the default ASCII encoding. This might be useful if the data contained in leaked blocks is likely to consist - of Unicode text. Set this option to "unicode" to generate a Unicode encoded report.

-
- -
ReportFile
-
-

Use this option to specify the name and location of the file in which to save the memory leak report when - using a file as the report destination, as specified by the ReportTo option. If - no file is specified here, then VLD will save the report in a file named "memory_leak_report.txt" in the - working directory of the program.

-
- -
ReportTo
-
-

The memory leak report may be sent to a file in addition to, or instead of, the debugger. Use this option to - specify which type of destination to use. Specify one of "debugger" (the default), "file", or "both".

-
- -
SelfTest
-
-

VLD has the ability to check itself for memory leaks. This feature is always active. Every time you run VLD, - in addition to checking your own program for memory leaks, it is also checking itself for leaks. Setting this - option to "on" forces VLD to intentionally leak a small amount of memory: a 21-character block filled with - the text "Memory Leak Self-Test". This provides a way to test VLD's ability to check itself for memory leaks - and verify that this capability is working correctly. This option is usually only useful for debugging VLD - itself.

-
- -
SlowDebuggerDump
-
-

If enabled, this option causes Visual Leak Detector to write the memory leak report to the debugger's output - window at a slower than normal rate. This option is specifically designed to work around a known issue with - some older versions of Visual Studio where some data sent to the output window might be lost if it is sent - too quickly. If you notice that some information seems to be missing from the memory leak report, try turning - this on.

-
- -
StackWalkMethod
-
-

Selects the method to be used for walking the stack to obtain call stacks for allocated memory blocks. The - default "fast" method may not always be able to successfully trace completely through all call stacks. In - such cases, the "safe" method may prove to be more reliable in obtaining the full stack trace. The - disadvantage with the "safe" method is that it is significantly slower than the "fast" method and will - probably result in very noticeable performance degradation of the program being debugged. In most cases it - should be okay to leave this option set to "fast". If you experience problems getting VLD to show call - stacks, you can try setting this option to "safe".

- -

If you do use the "safe" method, and notice a significant performance decrease, you may want to consider - using the MaxTraceFrames option to limit the number of frames traced to a - relatively small number. This can reduce the amount of time spent tracing the stack by a very large - amount.

-
- -
StartDisabled
-
-

Set this option to "yes" to disable memory leak detection initially. This can be useful if you need to be - able to selectively enable memory leak detection from runtime, without needing to rebuild the executable; - however, this option should be used with caution. Any memory leaks that may occur before memory leak - detection is enabled at runtime will go undetected. For example, if the constructor of some global variable - allocates memory before execution reaches a subsequent call to VLDEnable, then - VLD will not be able to detect if the memory allocated by the global variable is never freed. Refer to the - following section on controlling leak detection at runtime for details on using the - runtime APIs which can be useful in conjunction with this option.

-
- -
TraceInternalFrames
-
-

This option determines whether or not all frames of the call stack, including frames internal to the heap, - are traced. There will always be a number of frames on the call stack which are internal to Visual Leak - Detector and C/C++ or Win32 heap APIs that aren't generally useful for determining the cause of a leak. - Normally these frames are skipped during the stack trace, which somewhat reduces the time spent tracing and - amount of data collected and stored in memory. Including all frames in the stack trace, all the way down into - VLD's own code can, however, be useful for debugging VLD itself.

-
-
- - - - -

Controlling Leak Detection at Runtime

- -

Using the default configuration, VLD's memory leak detection will be enabled during the entire run of your program. - In certain scenarios it may be desirable to selectively disable memory leak detection in certain segments of your - code. VLD provides simple APIs for controlling the state of memory leak detection at runtime. To access these APIs, - include vld.h in the source file that needs to use them.

- -
-
VLDDisable
-
-

This function disables memory leak detection. After calling this function, memory leak detection will remain - disabled until it is explicitly re-enabled via a call to VLDEnable.

- -
void VLDDisable (void);
- -

Arguments:

- -

This function accepts no arguments.

- -

Return Value:

- -

None (this function always succeeds).

- -

Notes:

- -

This function controls memory leak detection on a per-thread basis. In other words, calling this function - disables memory leak detection for only the thread that called the function. Memory leak detection will - remain enabled for any other threads in the same process. This insulates the programmer from having to - synchronize multiple threads that disable and enable memory leak detection. However, note also that this - means that in order to disable memory leak detection process-wide, this function must be called from every - thread in the process.

-
- - -
VLDEnable
-
-

This function enables memory leak detection if it was previously disabled. After calling this function, - memory leak detection will remain enabled unless it is explicitly disabled again via a call to - VLDDisable().

- -
void VLDEnable (void);
- -

Arguments:

- -

This function accepts no arguments.

- -

Return Value:

- -

None (this function always succeeds).

- -

Notes:

- -

This function controls memory leak detection on a per-thread basis. See the remarks for - VLDDisable regarding multithreading and memory leak detection for details. - Those same concepts also apply to this function.

-
-
- - - - -

Building Visual Leak Detector from Source

- -

Because Visual Leak Detector is open source, it can be built from source if you want to tweak it to your - liking. As of Visual Studio 2008, the source can usually be built out-of-the-box without downloading or installing - any other tools. If you are using Visual Studio 2008 (or later), you can skip ahead to - Executing Your Built vld.dll. - -

Users with older versions of Visual Studio should continue reading here and follow the instructions in the next - subsection.

- -

For Older Versions of Visual Studio

- -

The most difficult part about building VLD from source is getting your build environment correctly set up. - But if you follow these instructions carefully, the process should be fairly painless.

- -
    -
  1. VLD depends on the Debug Help Library. This library is part of - Debugging Tools for Windows (DTfW). - Download and install DTfW in order to install the required headers and libraries. I recommend installing version - 6.5 of DTfW, or later. Newer versions tend to work fine, but older versions will probably not work. Be sure to - manually select to install the SDK files during the DTfW installation or the headers and libraries will not be - installed (they are not always installed with a default installation).
  2. - -
  3. Visual C++ will need to be made aware of where it can find the Debug Help Library header and library files. - Add the sdk\inc and sdk\lib subdirectories from the - DTfW installation directory to the include and library search paths in Visual C++. (See the section above - on using Visual Leak Detector on instructions for adding to these search paths). -
  4. - -
  5. VLD also requires a reasonably up-to-date Platform SDK. It is known to work with the latest SDK (as of this - writing) which is the Windows Server 2003 R2 SDK. It should also work with earlier SDKs, such as the Windows XP - SP2 SDK or may even work with SDKs as old as the February 2003 SDK. If in doubt, - update - your Platform SDK to the latest version.
  6. - -
  7. Again, Visual C++ will need to know where to find the Platform SDK headers and libraries. Add the - Include and Lib subdirectories from the - Platform SDK installation directory to the Include and Library search paths, respectively. The - Platform SDK directories should be placed just after the DTfW directories.
  8. -
- -

To summarize, your Visual C++ include search path should look something like this:

- -
    -
  • C:\Program Files\Debugging Tools for Windows\sdk\inc
  • - -
  • C:\Program Files\Microsoft Platform SDK\Include
  • - -
  • C:\Program Files\Microsoft Visual Studio\VCx\Include
  • - -
  • ...
  • -
- -

And your Visual C++ library search path should look like this:

- -
    -
  • C:\Program Files\Debugging Tools for Windows\sdk\lib
  • - -
  • C:\Program Files\Microsoft Platform SDK\Lib
  • - -
  • C:\Program Files\Microsoft Visual Studio\VCx\Lib
  • - -
  • ...
  • -
- -

In the above examples, "VCx" could be "VC", "VC7", or "VC98" (or possibly other values) depending on which version of - Visual Studio you have installed. Also, the name of your Platform SDK directory will probably be different from - the example depending on which version of the Platform SDK you have installed.

- -

Once you have completed all of the above steps, your build environment should be ready. To build VLD, just open the - vld.sln solution file and do a full build.

- -

Executing Your Built vld.dll

- -

When actually running the built project, vld.dll will expect to find the Debug Help - Library as a private assembly. The private assembly must be located in the same directory as - vld.dll (either the Release or - Debug directory by default). Otherwise, when VLD is loaded, an error message will pop - up indicating that the program failed to initialize, and you will see a message similar to the following in the - debugger's output window:

-

LDR: LdrpWalkImportDescriptor() failed to probe C:\Projects\vld\Release\vld.dll for its manifest, - ntstatus 0xc0150002

- -

To ensure that vld.dll finds the required private assembly, you need to copy - dbghelp.dll and Microsoft.DTfW.DHL.manifest to the - same directory that vld.dll is in.

- - - - -

Windows x64 Support

- -

Currently VLD will not build on x64 due to limitations of the x64 compiler. Some efforts have been undertaken to - get it working in a 64-bit environment, but have not yet been successful. If you need 64-bit support and run into - problems trying to build the source in 64-bit mode, please let me know. - I'll be glad to assist in getting the 64-bit code working properly, if at all possible.

- - - - -

Frequently Asked Questions

- -
-
When I try to compile my program with VLD, it fails and the compiler gives this error: Cannot open include file: - 'vld.h': No such file or directory.
-
-

The compiler can't find the header file that VLD installed. This probably means that VLD's include - subdirectory has not been added to the Visual C++ include search path. See the section above about - Using Visual Leak Detector for instructions on how to add VLD's directories to the search - path.

-
-
In the memory leak report, the callstack contains many lines that say - "File and line number unvailable" or "Function name unavailable".
-
-

This may mean that VLD couldn't find the symbol database for your program. The symbol database is ususally in - a file named [my-program-name].pdb. If this file is not located in the same - directory as the program itself, then VLD will probably not find it and can't show any file or function - names.

-
-
- - - - -

Known Restrictions

- -

Known restrictions/limitations in this version of VLD include:

- -
    -
  • Memory allocations made through calls to functions loaded from a DLL using delayed loading may not be - detected.
  • - -
  • Support for programs that use MFC 7.0 or MFC 7.1 is not complete yet. Some memory leaks from such MFC-based - programs may not be detected. A possible workaround for this restriction is to try forcefully including the MFC - DLLs in memory leak detection, by setting the ForceIncludeModules configuration - option to: "mfc70d.dll mfc71d.dll" and explicitly adding vld.lib as an input file - on the linker command line (can be added through project settings by adding it to the list of library modules in - the linker options). This restriction does not apply to programs that use MFC 4.2, MFC 8.0, or MFC 9.0, which are - all fully supported.
  • - -
  • Visual Leak Detector may report leaks internal to Visual Leak Detector if the main thread of the process - terminates while other threads are still running.
  • - -
  • On Windows 2000 and earlier operating systems, you may need to manually add the - bin subdirectory from the Visual Leak Detector installation directory to the system - PATH environment variable. Also, dbghelp.dll will probably need to be manually copied - to the directory where the program being debugged resides. Otherwise the system may not find the required DLLs when - running VLD.
  • - -
  • If more than one copy of the same C Runtime DLL is loaded in the process at the same time, then some leaks may - go undetected (note that loading more than one copy of the C Runtime DLL at the same time is probably a bad idea - to begin with).
  • -
- - - -

Contributing

- -

I encourage developers who've added their own features, or fixed bugs they've found, to contribute to the project. - The full version-controlled source tree is available publicly via Git at the URL below. Feel free to clone from this - URL and submit patches for consideration for inclusion in future versions. You can also hop onto - GitHub (accounts are free) and issue pull requests for changes that you've made and - would like to share.

- -

Git Repository URL: git://github.com/dmoulding/vld.git

- -

License

- -

Visual Leak Detector is distributed under the terms of the - GNU Lesser General Public License. This license allows you to - use the VLD library with your own programs without restriction. However, if you build a program (or another library) - that is based on the VLD source code, or uses parts of the VLD source code in it, then some restrictions - will apply. What this means is that you are free to ship and use the distributed version of the VLD DLL with regular - commercial programs. But if you create a modified version of VLD, that modified version must remain "free software". - See the COPYING.txt file for details.

- -

The Debug Help Library (dbghelp.dll) and Microsoft C Runtime Library - (msvcr80.dll) distributed with this software are not part of - Visual Leak Detector and are not covered under the terms of the GNU Lesser General Public License. They are - separately copyrighted works of Microsoft Corporation. Microsoft reserves all its rights to its copyrights in the - Debug Help Library and Microsoft C Runtime Library. Neither your use of the Visual Leak Detector software, - nor your license under the GNU Lesser General Public license grant you any rights to use the Debug Help Library or - Microsoft C Runtime Library in ANY WAY (for example, redistributing them) that would infringe upon - Microsoft Corporation's copyright in the Debug Help Library or Microsoft C Runtime Library.

- -

NO WARRANTY

- -

BECAUSE VISUAL LEAK DETECTOR ("THE SOFTWARE") IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO - THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER - PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE - QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL - NECESSARY SERVICING, REPAIR OR CORRECTION.

- -

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY - WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE LICENSING TERMS SET FORTH ABOVE, BE LIABLE TO YOU - FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY - TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED - BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR - OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

- - - - -

Contacting the Author

- -

Please forward any bug reports, questions, comments or suggestions to me at -dmoulding@gmail.com.

- -

Donations to help support ongoing development of Visual Leak Detector are very appreciated!

- -
-
- - - -
-
- - - -

Additional Developers Wanted

- -

This project is looking for additional developers who have the time, knowledge, and talent, to help make VLD continue - to be a useful utility for the Windows developer community. If you feel that you or someone you know would be - interested in becoming an active member of the Visual Leak Detector development team, please let me know.

- - - -

- Valid XHTML 1.0! - Valid CSS! -

- - - - - -
- - - - \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 00000000..ec0e6239 --- /dev/null +++ b/README.md @@ -0,0 +1,37 @@ +# Visual Leak Detector [![Build status](https://ci.appveyor.com/api/projects/status/0kvft8un16e80toj/branch/master?svg=true)](https://ci.appveyor.com/project/KindDragon/vld/branch/master) PayPal donate button + +## ⚠️ Project Status: Inactive ⚠️ + +**This project is currently not in active development. The author is focusing on Linux development and is not maintaining this project at the moment.** + +**🔍 Seeking Maintainers: If you are interested in becoming a maintainer and contributing to this project, please feel free to reach out. Your contributions would be greatly appreciated!** + +## Introduction + +Visual C++ provides built-in memory leak detection, but its capabilities are minimal at best. This memory leak detector was created as a free alternative to the built-in memory leak detector provided with Visual C++. Here are some of Visual Leak Detector's features, none of which exist in the built-in detector: + +* Provides a complete stack trace for each leaked block, including source file and line number information when available. +* Detects most, if not all, types of in-process memory leaks including COM-based leaks, and pure Win32 heap-based leaks. +* Selected modules (DLLs or even the main EXE) can be excluded from leak detection. +* Provides complete data dumps (in hex and ASCII) of leaked blocks. +* Customizable memory leak report: can be saved to a file or sent to the debugger and can include a variable level of detail. + +Other after-market leak detectors for Visual C++ are already available. But most of the really popular ones, like Purify and BoundsChecker, are very expensive. A few free alternatives exist, but they're often too intrusive, restrictive, or unreliable. Visual Leak Detector is currently the only freely available memory leak detector for Visual C++ that provides all of the above professional-level features packaged neatly in an easy-to-use library. + +Visual Leak Detector is [licensed][3] free of charge as a service to the Windows developer community. If you find it to be useful and would like to just say "Thanks!", or you think it stinks and would like to say "This thing sucks!", please feel free to [drop us a note][1]. Or, if you'd prefer, you can [contribute a small donation][2]. Both are very appreciated. + +## Documentation + +Read the documentation at [https://github.com/KindDragon/vld/wiki](https://github.com/KindDragon/vld/wiki) + +## Contributing + +We encourage developers who've added their own features, or fixed bugs they've found, to contribute to the project. The full version-controlled source tree is available publicly via Git at the URL below. Feel free to clone from this URL and submit patches for consideration for inclusion in future versions. You can also issue pull requests for changes that you've made and would like to share. + +* [Source code](https://github.com/KindDragon/vld) + +Copyright © 2005-2017 VLD Team + + [1]: https://github.com/KindDragon/vld/wiki + [2]: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=N3QTYHP9LH6UY&lc=GB&item_name=Visual%20Leak%20Detector¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted + [3]: https://github.com/KindDragon/vld/blob/master/COPYING.txt diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 00000000..e1621f8c --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,158 @@ +version: '{build}' + +branches: + # blacklist + except: + - gh-pages + +os: Visual Studio 2015 + +environment: + GTEST_REPEAT: 1 + + matrix: + - VldStackWalkMethod: safe + Toolset: v90 + Solution: vld_vs14_wo_mfc.sln + GTEST_FILTER: -*.Mfc* + - VldStackWalkMethod: safe + Toolset: v100 + Solution: vld_vs14_wo_mfc.sln + GTEST_FILTER: -*.Mfc* + - VldStackWalkMethod: safe + Toolset: v110 + Solution: vld_vs14_wo_mfc.sln + GTEST_FILTER: -*.Mfc* + - VldStackWalkMethod: safe + Toolset: v120_xp + Solution: vld_vs14.sln + - VldStackWalkMethod: safe + Toolset: v140_xp + Solution: vld_vs14.sln + + - VldStackWalkMethod: fast + Toolset: v90 + Solution: vld_vs14_wo_mfc.sln + GTEST_FILTER: -*.Mfc* + - VldStackWalkMethod: fast + Toolset: v100 + Solution: vld_vs14_wo_mfc.sln + GTEST_FILTER: -*.Mfc* + - VldStackWalkMethod: fast + Toolset: v110 + Solution: vld_vs14_wo_mfc.sln + GTEST_FILTER: -*.Mfc* + - VldStackWalkMethod: fast + Toolset: v120_xp + Solution: vld_vs14.sln + - VldStackWalkMethod: fast + Toolset: v140_xp + Solution: vld_vs14.sln + +platform: + - Win32 + - x64 + +configuration: + - Debug_VldRelease + - Debug_VldRelease_StaticCrt + - Release + - Release_StaticCrt + +matrix: + fast_finish: false + +nuget: + project_feed: true + disable_publish_on_pr: true + +notifications: +- provider: Webhook + url: https://webhooks.gitter.im/e/f26eac97358590c8feca + on_build_success: true + on_build_failure: true + on_build_status_changed: true + +build_script: +- ps: | + Write-Output "Configuration: $env:CONFIGURATION" + Write-Output "Platform: $env:PLATFORM" + if (($env:Toolset -eq "v100") -and ($env:PLATFORM -eq "x64")) + { + return + } + & .\change_toolset.ps1 $env:Toolset + msbuild /v:m /p:"Configuration=$env:CONFIGURATION" /p:Platform="$env:PLATFORM" "$env:Solution" /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" + +test_script: +- ps: | + if (($env:Toolset -eq "v100") -and ($env:PLATFORM -eq "x64")) + { + return + } + cd src\ + + function Add-GTest-Result($testResult) + { + $testsuites = ([xml](get-content $testResult)).testsuites + $testsCount = 0 + $anyFailures = $FALSE + + foreach ($testsuite in $testsuites.testsuite) { + foreach ($testcase in $testsuite.testcase) { + $testsCount++ + if ($testcase.failure) { + $time = ([double]$testcase.time * 1000) + Add-AppveyorTest $testcase.name -Outcome Failed -FileName $testsuite.name -Duration $time -ErrorMessage $testcase.failure.message + Add-AppveyorMessage "$($testcase.name) failed" -Category Error + $anyFailures = $TRUE + } + elseif ($testcase.skipped) { + Add-AppveyorTest $testcase.name -Outcome Ignored -Filename $testsuite.name + } + else { + $time = ([double]$testcase.time * 1000) + Add-AppveyorTest $testcase.name -Outcome Passed -FileName $testsuite.name -Duration $time + } + } + } + return $testsCount, $anyFailures + } + + function Run-Tests($platform, $configuration, $correctTestCount) + { + $testsCount = 0 + $anyFailures = $FALSE + $tests_path = ".\bin\$platform\$configuration\" + + # Run tests and upload results to AppVeyor one by one + Get-ChildItem "$tests_path\*.exe" | foreach { + $testfile = "$($_.FullName).xml" + & $_.FullName "--gtest_output=`"xml:$testfile`"" + if (Test-Path $testfile) + { + $count, $testsResult = Add-GTest-Result $testfile + Write-Output "Found $testfile with $count tests" + $testsCount = $testsCount + $count + $anyFailures = $anyFailures -or $testsResult + } + } + + if ($anyFailures -eq $TRUE){ + Write-Output "Failing build as there are broken tests" + $host.SetShouldExit(1) + } + + if ($testsCount -lt $correctTestCount){ + Write-Output "Failing build as there the number of tests decreased from $correctTestCount" + $host.SetShouldExit(2) + } + } + + $pos = $env:Toolset.IndexOf("_") + if ($pos -eq -1) { $pos = $env:Toolset.length } + $suffix = $env:Toolset.Substring(0, $pos ) + $folders = @{"Debug_VldRelease" = "Debug(Release)-$suffix"; "Debug_VldRelease_StaticCrt" = "Debug(Release)_StaticCrt-$suffix"; + "Release" = "Release-$suffix"; "Release_StaticCrt" = "Release_StaticCrt-$suffix"} + $correctTestCount = if ($env:GTEST_FILTER -like '*Mfc*') { 49 } else { 53 } + Run-Tests "$env:PLATFORM" "$($folders[$env:CONFIGURATION])" $correctTestCount diff --git a/callstack.cpp b/callstack.cpp deleted file mode 100644 index 73962113..00000000 --- a/callstack.cpp +++ /dev/null @@ -1,442 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - CallStack Class Implementations -// Copyright (c) 2005-2009 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#include -#include -#ifndef __out_xcount -#define __out_xcount(x) // Workaround for the specstrings.h bug in the Platform SDK. -#endif -#define DBGHELP_TRANSLATE_TCHAR -#include // Provides symbol handling services. -#define VLDBUILD -#include "callstack.h" // This class' header. -#include "utility.h" // Provides various utility functions. -#include "vldheap.h" // Provides internal new and delete operators. -#include "vldint.h" // Provides access to VLD internals. - -#define MAXSYMBOLNAMELENGTH 256 - -// Imported global variables. -extern HANDLE currentprocess; -extern HANDLE currentthread; -extern CRITICAL_SECTION stackwalklock; -extern CRITICAL_SECTION symbollock; - -// Constructor - Initializes the CallStack with an initial size of zero and one -// Chunk of capacity. -// -CallStack::CallStack () -{ - m_capacity = CALLSTACKCHUNKSIZE; - m_size = 0; - m_status = 0x0; - m_store.next = NULL; - m_topchunk = &m_store; - m_topindex = 0; -} - -// Copy Constructor - For efficiency, we want to avoid ever making copies of -// CallStacks (only pointer passing or reference passing should be performed). -// The sole purpose of this copy constructor is to ensure that no copying is -// being done inadvertently. -// -CallStack::CallStack (const CallStack &) -{ - // Don't make copies of CallStacks! - assert(FALSE); -} - -// Destructor - Frees all memory allocated to the CallStack. -// -CallStack::~CallStack () -{ - CallStack::chunk_t *chunk = m_store.next; - CallStack::chunk_t *temp; - - while (chunk) { - temp = chunk; - chunk = temp->next; - delete temp; - } -} - -// operator = - Assignment operator. For efficiency, we want to avoid ever -// making copies of CallStacks (only pointer passing or reference passing -// should be performed). The sole purpose of this assignment operator is to -// ensure that no copying is being done inadvertently. -// -CallStack& CallStack::operator = (const CallStack &) -{ - // Don't make copies of CallStacks! - assert(FALSE); - return *this; -} - -// operator == - Equality operator. Compares the CallStack to another CallStack -// for equality. Two CallStacks are equal if they are the same size and if -// every frame in each is identical to the corresponding frame in the other. -// -// other (IN) - Reference to the CallStack to compare the current CallStack -// against for equality. -// -// Return Value: -// -// Returns true if the two CallStacks are equal. Otherwise returns false. -// -BOOL CallStack::operator == (const CallStack &other) const -{ - const CallStack::chunk_t *chunk = &m_store; - UINT32 index; - const CallStack::chunk_t *otherchunk = &other.m_store; - const CallStack::chunk_t *prevchunk = NULL; - - if (m_size != other.m_size) { - // They can't be equal if the sizes are different. - return FALSE; - } - - // Walk the chunk list and within each chunk walk the frames array until we - // either find a mismatch, or until we reach the end of the call stacks. - while (prevchunk != m_topchunk) { - for (index = 0; index < ((chunk == m_topchunk) ? m_topindex : CALLSTACKCHUNKSIZE); index++) { - if (chunk->frames[index] != otherchunk->frames[index]) { - // Found a mismatch. They are not equal. - return FALSE; - } - } - prevchunk = chunk; - chunk = chunk->next; - otherchunk = otherchunk->next; - } - - // Reached the end of the call stacks. They are equal. - return TRUE; -} - -// operator [] - Random access operator. Retrieves the frame at the specified -// index. -// -// Note: We give up a bit of efficiency here, in favor of efficiency of push -// operations. This is because walking of a CallStack is done infrequently -// (only if a leak is found), whereas pushing is done very frequently (for -// each frame in the program's call stack when the program allocates some -// memory). -// -// - index (IN): Specifies the index of the frame to retrieve. -// -// Return Value: -// -// Returns the program counter for the frame at the specified index. If the -// specified index is out of range for the CallStack, the return value is -// undefined. -// -SIZE_T CallStack::operator [] (UINT32 index) const -{ - UINT32 count; - const CallStack::chunk_t *chunk = &m_store; - UINT32 chunknumber = index / CALLSTACKCHUNKSIZE; - - for (count = 0; count < chunknumber; count++) { - chunk = chunk->next; - } - - return chunk->frames[index % CALLSTACKCHUNKSIZE]; -} - -// clear - Resets the CallStack, returning it to a state where no frames have -// been pushed onto it, readying it for reuse. -// -// Note: Calling this function does not release any memory allocated to the -// CallStack. We give up a bit of memory-usage efficiency here in favor of -// performance of push operations. -// -// Return Value: -// -// None. -// -VOID CallStack::clear () -{ - m_size = 0; - m_topchunk = &m_store; - m_topindex = 0; -} - -// dump - Dumps a nicely formatted rendition of the CallStack, including -// symbolic information (function names and line numbers) if available. -// -// Note: The symbol handler must be initialized prior to calling this -// function. -// -// - showinternalframes (IN): If true, then all frames in the CallStack will be -// dumped. Otherwise, frames internal to the heap will not be dumped. -// -// Return Value: -// -// None. -// -VOID CallStack::dump (BOOL showinternalframes) const -{ - DWORD displacement; - DWORD64 displacement64; - BOOL foundline; - UINT32 frame; - SYMBOL_INFO *functioninfo; - LPWSTR functionname; - SIZE_T programcounter; - IMAGEHLP_LINE64 sourceinfo = { 0 }; - BYTE symbolbuffer [sizeof(SYMBOL_INFO) + (MAXSYMBOLNAMELENGTH * sizeof(WCHAR)) - 1] = { 0 }; - - if (m_status & CALLSTACK_STATUS_INCOMPLETE) { - // This call stack appears to be incomplete. Using StackWalk64 may be - // more reliable. - report(L" HINT: The following call stack may be incomplete. Setting \"StackWalkMethod\"\n" - L" in the vld.ini file to \"safe\" instead of \"fast\" may result in a more\n" - L" complete stack trace.\n"); - } - - // Initialize structures passed to the symbol handler. - functioninfo = (SYMBOL_INFO*)&symbolbuffer; - functioninfo->SizeOfStruct = sizeof(SYMBOL_INFO); - functioninfo->MaxNameLen = MAXSYMBOLNAMELENGTH; - sourceinfo.SizeOfStruct = sizeof(IMAGEHLP_LINE64); - - // Iterate through each frame in the call stack. - for (frame = 0; frame < m_size; frame++) { - // Try to get the source file and line number associated with - // this program counter address. - programcounter = (*this)[frame]; - EnterCriticalSection(&symbollock); - if ((foundline = SymGetLineFromAddrW64(currentprocess, programcounter, &displacement, &sourceinfo)) == TRUE) { - if (!showinternalframes) { - _wcslwr_s(sourceinfo.FileName, wcslen(sourceinfo.FileName) + 1); - if (wcsstr(sourceinfo.FileName, L"afxmem.cpp") || - wcsstr(sourceinfo.FileName, L"dbgheap.c") || - wcsstr(sourceinfo.FileName, L"malloc.c") || - wcsstr(sourceinfo.FileName, L"new.cpp") || - wcsstr(sourceinfo.FileName, L"newaop.cpp")) { - // Don't show frames in files internal to the heap. - continue; - } - } - } - - // Try to get the name of the function containing this program - // counter address. - if (SymFromAddrW(currentprocess, (*this)[frame], &displacement64, functioninfo)) { - functionname = functioninfo->Name; - } - else { - functionname = L"(Function name unavailable)"; - } - LeaveCriticalSection(&symbollock); - - // Display the current stack frame's information. - if (foundline) { - report(L" %s (%d): %s\n", sourceinfo.FileName, sourceinfo.LineNumber, functionname); - } - else { - report(L" " ADDRESSFORMAT L" (File and line number not available): ", (*this)[frame]); - report(L"%s\n", functionname); - } - } -} - -// push_back - Pushes a frame's program counter onto the CallStack. Pushes are -// always appended to the back of the chunk list (aka the "top" chunk). -// -// Note: This function will allocate additional memory as necessary to make -// room for new program counter addresses. -// -// - programcounter (IN): The program counter address of the frame to be pushed -// onto the CallStack. -// -// Return Value: -// -// None. -// -VOID CallStack::push_back (const SIZE_T programcounter) -{ - CallStack::chunk_t *chunk; - - if (m_size == m_capacity) { - // At current capacity. Allocate additional storage. - chunk = new CallStack::chunk_t; - chunk->next = NULL; - m_topchunk->next = chunk; - m_topchunk = chunk; - m_topindex = 0; - m_capacity += CALLSTACKCHUNKSIZE; - } - else if (m_topindex == CALLSTACKCHUNKSIZE) { - // There is more capacity, but not in this chunk. Go to the next chunk. - // Note that this only happens if this CallStack has previously been - // cleared (clearing resets the data, but doesn't give up any allocated - // space). - m_topchunk = m_topchunk->next; - m_topindex = 0; - } - - m_topchunk->frames[m_topindex++] = programcounter; - m_size++; -} - -// getstacktrace - Traces the stack as far back as possible, or until 'maxdepth' -// frames have been traced. Populates the CallStack with one entry for each -// stack frame traced. -// -// Note: This function uses a very efficient method to walk the stack from -// frame to frame, so it is quite fast. However, unconventional stack frames -// (such as those created when frame pointer omission optimization is used) -// will not be successfully walked by this function and will cause the -// stack trace to terminate prematurely. -// -// - maxdepth (IN): Maximum number of frames to trace back. -// -// - framepointer (IN): Frame (base) pointer at which to begin the stack trace. -// If NULL, then the stack trace will begin at this function. -// -// Return Value: -// -// None. -// -VOID FastCallStack::getstacktrace (UINT32 maxdepth, SIZE_T *framepointer) -{ - UINT32 count = 0; - - if (framepointer == NULL) { - // Begin the stack trace with the current frame. Obtain the current - // frame pointer. - FRAMEPOINTER(framepointer); - } - - while (count < maxdepth) { - if ((SIZE_T*)*framepointer < framepointer) { - if ((SIZE_T*)*framepointer == NULL) { - // Looks like we reached the end of the stack. - break; - } - else { - // Invalid frame pointer. Frame pointer addresses should always - // increase as we move up the stack. - m_status |= CALLSTACK_STATUS_INCOMPLETE; - break; - } - } - if ((SIZE_T)*framepointer & (sizeof(SIZE_T*) - 1)) { - // Invalid frame pointer. Frame pointer addresses should always - // be aligned to the size of a pointer. This probably means that - // we've encountered a frame that was created by a module built with - // frame pointer omission (FPO) optimization turned on. - m_status |= CALLSTACK_STATUS_INCOMPLETE; - break; - } - if (IsBadReadPtr((SIZE_T*)*framepointer, sizeof(SIZE_T*))) { - // Bogus frame pointer. Again, this probably means that we've - // encountered a frame built with FPO optimization. - m_status |= CALLSTACK_STATUS_INCOMPLETE; - break; - } - count++; - push_back(*(framepointer + 1)); - framepointer = (SIZE_T*)*framepointer; - } -} - -// getstacktrace - Traces the stack as far back as possible, or until 'maxdepth' -// frames have been traced. Populates the CallStack with one entry for each -// stack frame traced. -// -// Note: This function uses a documented Windows API to walk the stack. This -// API is supposed to be the most reliable way to walk the stack. It claims -// to be able to walk stack frames that do not follow the conventional stack -// frame layout. However, this robustness comes at a cost: it is *extremely* -// slow compared to walking frames by following frame (base) pointers. -// -// - maxdepth (IN): Maximum number of frames to trace back. -// -// - framepointer (IN): Frame (base) pointer at which to begin the stack trace. -// If NULL, then the stack trace will begin at this function. -// -// Return Value: -// -// None. -// -VOID SafeCallStack::getstacktrace (UINT32 maxdepth, SIZE_T *framepointer) -{ - DWORD architecture; - CONTEXT context; - UINT32 count = 0; - STACKFRAME64 frame; - SIZE_T programcounter; - SIZE_T stackpointer; - - if (framepointer == NULL) { - // Begin the stack trace with the current frame. Obtain the current - // frame pointer. - FRAMEPOINTER(framepointer); - } - - // Get the required values for initialization of the STACKFRAME64 structure - // to be passed to StackWalk64(). Required fields are AddrPC and AddrFrame. -#if defined(_M_IX86) || defined(_M_X64) - architecture = X86X64ARCHITECTURE; - programcounter = *(framepointer + 1); - stackpointer = *framepointer; // An approximation. - context.BPREG = *framepointer; - context.IPREG = programcounter; - context.SPREG = stackpointer; -#else -// If you want to retarget Visual Leak Detector to another processor -// architecture then you'll need to provide architecture-specific code to -// obtain the program counter and stack pointer from the given frame pointer. -#error "Visual Leak Detector is not supported on this architecture." -#endif // _M_IX86 || _M_X64 - - // Initialize the STACKFRAME64 structure. - memset(&frame, 0x0, sizeof(frame)); - frame.AddrFrame.Offset = *framepointer; - frame.AddrFrame.Mode = AddrModeFlat; - frame.AddrPC.Offset = programcounter; - frame.AddrPC.Mode = AddrModeFlat; - frame.AddrStack.Offset = stackpointer; - frame.AddrStack.Mode = AddrModeFlat; - - // Walk the stack. - EnterCriticalSection(&stackwalklock); - while (count < maxdepth) { - count++; - if (!StackWalk64(architecture, currentprocess, currentthread, &frame, &context, NULL, - SymFunctionTableAccess64, SymGetModuleBase64, NULL)) { - // Couldn't trace back through any more frames. - break; - } - if (frame.AddrFrame.Offset == 0) { - // End of stack. - break; - } - - // Push this frame's program counter onto the CallStack. - push_back((SIZE_T)frame.AddrPC.Offset); - } - LeaveCriticalSection(&stackwalklock); -} diff --git a/callstack.h b/callstack.h deleted file mode 100644 index 68aa6094..00000000 --- a/callstack.h +++ /dev/null @@ -1,116 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - CallStack Class Definitions -// Copyright (c) 2005-2006 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef VLDBUILD -#error \ -"This header should only be included by Visual Leak Detector when building it from source. \ -Applications should never include this header." -#endif - -#include - -#define CALLSTACKCHUNKSIZE 32 // Number of frame slots in each CallStack chunk. - -//////////////////////////////////////////////////////////////////////////////// -// -// The CallStack Class -// -// CallStack objects can be used for obtaining, storing, and displaying the -// call stack at a given point during program execution. -// -// The primary data structure used by the CallStack is similar in concept to -// a STL vector, but is specifically tailored for use by VLD, making it more -// efficient than a standard STL vector. -// -// Inside the CallStack are a number of "chunks" which are arranged in a -// linked list. Each chunk contains an array of frames (each frame is -// represented by a program counter address). If we run out of space when -// pushing new frames onto an existing chunk in the CallStack chunk list, -// then a new chunk is allocated and appended to the end of the list. In this -// way, the CallStack can grow dynamically as needed. New frames are always -// pushed onto the chunk at the end of the list known as the "top" chunk. -// -class CallStack -{ -public: - CallStack (); - CallStack (const CallStack &other); - ~CallStack (); - - // Public APIs - see each function definition for details. - VOID clear (); - VOID dump (BOOL showinternalframes) const; - virtual VOID getstacktrace (UINT32 maxdepth, SIZE_T *framepointer) = 0; - CallStack& operator = (const CallStack &other); - BOOL operator == (const CallStack &other) const; - SIZE_T operator [] (UINT32 index) const; - VOID push_back (const SIZE_T programcounter); - -protected: - // Protected data. - UINT32 m_status; // Status flags: -#define CALLSTACK_STATUS_INCOMPLETE 0x1 // If set, the stack trace stored in this CallStack appears to be incomplete. - -private: - // The chunk list is made of a linked list of Chunks. - typedef struct chunk_s { - struct chunk_s *next; // Pointer to the next chunk in the chunk list. - SIZE_T frames [CALLSTACKCHUNKSIZE]; // Pushed frames (program counter addresses) are stored in this array. - } chunk_t; - - // Private data. - UINT32 m_capacity; // Current capacity limit (in frames) - UINT32 m_size; // Current size (in frames) - CallStack::chunk_t m_store; // Pointer to the underlying data store (i.e. head of the chunk list) - CallStack::chunk_t *m_topchunk; // Pointer to the chunk at the top of the stack - UINT32 m_topindex; // Index, within the top chunk, of the top of the stack -}; - - -//////////////////////////////////////////////////////////////////////////////// -// -// The FastCallStack Class -// -// This class is a specialization of the CallStack class which provides a -// very fast stack tracing function. -// -class FastCallStack : public CallStack -{ -public: - VOID getstacktrace (UINT32 maxdepth, SIZE_T *framepointer); -}; - -//////////////////////////////////////////////////////////////////////////////// -// -// The SafeCallStack Class -// -// This class is a specialization of the CallStack class which provides a -// more robust, but quite slow, stack tracing function. -// -class SafeCallStack : public CallStack -{ -public: - VOID getstacktrace (UINT32 maxdepth, SIZE_T *framepointer); -}; diff --git a/change_toolset.ps1 b/change_toolset.ps1 new file mode 100644 index 00000000..7dad60a5 --- /dev/null +++ b/change_toolset.ps1 @@ -0,0 +1,45 @@ +Param( + [Parameter(Mandatory=$True,Position=1)] + [string]$toolset, + [switch]$force +) + +$files = Get-ChildItem -path . -filter *.vcxproj -recurse +foreach ($file in $files) { + if (!$force.IsPresent -and (($file.basename -eq "vld") -or ($file.basename -eq "format"))) + { + "Skip $($file.name)" + continue + } + $content = gc $file.fullname + $regex = [regex]"(v[\d\w_]+)<\/PlatformToolset>" + $oldtoolset = $regex.matches($content) + if ($oldtoolset.groups.count -ge 1) + { + " $($file.name) ($($oldtoolset.groups[1].value) - $toolset)" + $content = $content -replace "(v[\d\w_]+)<\/PlatformToolset>","$toolset" + $content | sc $file.fullname + } + else + { + "Toolset not set for $($file.name)" + } +} + +$commonProps = ".\src\tests\Common.props" +if ($force.IsPresent -and (Test-Path $commonProps)) +{ + $content = gc $commonProps + $regex = [regex]"(v[\d\w_]+)<\/VldToolset>" + $oldtoolset = $regex.matches($content) + if ($oldtoolset.groups.count -ge 1) + { + " Common.props ($($oldtoolset.groups[1].value) - $toolset)" + $content = $content -replace "(v[\d\w_]+)<\/VldToolset>","$toolset" + $content | sc $commonProps + } + else + { + "Toolset not set for $commonProps" + } +} \ No newline at end of file diff --git a/codeproject-article.html b/codeproject-article.html deleted file mode 100644 index 21e4343c..00000000 --- a/codeproject-article.html +++ /dev/null @@ -1,334 +0,0 @@ - - - -

Please choose 'View Source' in your browser to view the HTML, or -File | Save to save this file to your hard drive for editing.

-
- - - - - - -

Screenshot of Visual Studio 6.0 
with Visual Leak Detector's memory leak report displayed.

-

Table of Contents

- -

Introduction

-

Visual C++ provides built-in memory leak detection, but its capabilities are minimal at best. This memory leak detector was created as a free alternative to the built-in memory leak detector provided with Visual C++. Here are some of Visual Leak Detector's features, none of which exist in the built-in detector:

-
    -
  • Provides a complete stack trace for each leaked block, including source file and line number information when available. -
  • Provides complete data dumps (in hex and ASCII) of leaked blocks. -
  • Customizable level of detail in the memory leak report.
-

Other after-market leak detectors for Visual C++ are already available. But most of the really popular ones, like Purify and BoundsChecker, are very expensive. A few free alternatives exist, but they're often too intrusive, restrictive, or unreliable. Here are some key advantages that Visual Leak Detector has over many other free alternatives:

-
    -
  • Visual Leak Detector is cleanly packaged as an easy-to-use library. You don't need to compile its source code to use it. And you only need to make minor additions to your own source code to integrate it with your program. -
  • In addition to providing stack traces with source files, line numbers, and function names, Visual Leak Detector also provides data dumps. -
  • It works with both C++ and C programs (compatible with both new/delete and malloc/free). -
  • The full source code to the library is included and it is well documented, so it is easy to customize it to suit your needs.
-

Visual Leak Detector is licensed free of charge as a service to the Windows developer community.

-

What's New?

-

14 November 2006: A new beta version of has been posted. This version fixes a few bugs, most notably a deadlock bug and a couple of failed assertion bugs, that were identified in the 1.9c beta.

-

Note that the beta version does not have the same limitations of the 1.0 version. Whereas 1.0 can only detect leaks resulting from new or malloc, the beta can detect many different classes of leaks.

-

Please also note that the article below describes the inner workings of the 1.0 version. Because the beta version might change significantly before the next official release, the article will not be updated to reflect the design of the beta version until the official release is complete.

-

Using Visual Leak Detector

-

This section briefly describes the basics of using Visual Leak Detector (VLD). For a more in-depth discussion of the configuration options, runtime APIs, and a discussion of the more advanced usage scenarios (such as using VLD with DLLs), please see the full documentation included in the downloadable Zip files.

-

To use VLD with your project, follow these simple steps:

-
    -
  1. Copy the VLD library (*.lib) files to your Visual C++ installation's "lib" subdirectory. -
  2. Copy the VLD header files (vld.h and vldapi.h) to your Visual C++ installation's "include" subdirectory. -
  3. In the source file containing your program's main entry point, include the vld.h header file. It's best, but not absolutely required, to include this header before any other header files, except for stdafx.h. If the source file, include stdafx.h, then vld.h should be included after it. -
  4. If you are running Windows 2000 or earlier, then you will need to copy dbghelp.dll to the directory where the executable being debugged resides. -
  5. Build the debug version of your project.
-

VLD will detect memory leaks in your program whenever you run the debug version under the Visual C++ debugger. A report of all the memory leaks detected will be displayed in the debugger's output window when your program exits. Double-clicking on a source file's line number in the memory leak report will take you to that file and line in the editor window, allowing easy navigation of the code path leading up to the allocation that resulted in a memory leak.

-

Note: When you build release versions of your program, VLD will not be linked into the executable. So it is safe to leave vld.h included in your source files when doing release builds. Doing so will not result in any performance degradation or any other undesirable overhead.

-

Making a Memory Leak Detector

-

The goal of Visual Leak Detector was to build a better replacement for the memory leak detector built-in to Visual C++. With that in mind, I set out to use the same method used by the built-in detector, namely the CRT Debug Heap. But this new detector would provide enhancements -- primarily full stack traces, which can be extremely helpful for finding and fixing leaks.

-

The Built-In Detector

-

The built-in detector is pretty simple really. When a program is exiting, the CRT runs a bunch of cleanup code after main returns. If the built-in detector is enabled, then it runs a memory leak check as part of the cleanup procedure. The memory leak check simply looks at the debug heap: if there are any user blocks still allocated on the debug heap, then they must be memory leaks. The debug version of malloc stores the file and line number that allocated each block in the block's header at the time it is allocated. When the built-in detector identifies a memory leak, it simply peers inside the block header to get the file and line number. It then reports that information to the debugger where it is displayed.

-

Note that the built-in detector detects leaks without doing any monitoring of allocations or frees. It simply takes a snapshot of the heap just before the process terminates and determines if there are any leaks based on that snapshot. A snapshot of the heap only tells us if there are leaks; it does not tell us how they were leaked. Clearly, to determine the "how" we also need to obtain a stack trace. But to obtain a stack trace, we need to be able to monitor every allocation on-the-fly at runtime. This is what will distinguish our leak detector from the built-in one.

-

Allocation Hooking

-

Luckily for us, Microsoft has provided an easy way to monitor every allocation made from the debug heap: allocation hooks. An allocation hook is simply a user-supplied callback function that will be called just before each allocation is made from the debug heap. Microsoft has provided a function, _CrtSetAllocHook, which registers the allocation hook function with the debug heap. When the debug heap calls the allocation hook, one of the arguments passed is an ID number that uniquely identifies each allocation -- it's basically a serial number for each memory block allocated. There's not enough room in the memory block header for us to record any information directly in it, but we can use this unique ID number as a key to map each block to any data that we want to record.

-

Walking the Stack

-

Now that we have a way to be notified every time a block is allocated, as well as a way to uniquely identify each allocation, all that's left to do is to record the call stack each time an allocation occurs. We could conceivably attempt to unwind the stack ourselves using inline assembly. But stack frames can be organized in different ways, depending on compiler optimizations and calling conventions, so it could become complicated to do it that way. Once again, Microsoft has provided us with a tool to help us out. This time it is a function that we can call iteratively to walk the stack, frame by frame. That function is StackWalk64. It is part of the Debug Help Library (dbghelp.dll). As long as we provide it with the information that it needs to establish a starting "frame of reference", so to speak, it can examine our stack from there and reliably unwind it for us. Each time StackWalk64 is called, it gives back a STACKFRAME64 structure that can be reused as input for the next call to StackWalk64. It can be repeatedly called this way until the end of the stack is reached.

-

Initializing the Memory Leak Detector

-

We now have the beginnings of a better memory leak detector. We can monitor every allocation, and for each allocation monitored, we can obtain and record a stack trace. The only challenge that remains is to ensure that the allocation hook function is registered with the debug heap as soon as the program starts executing. This can be very simply solved by creating a global instance of a C++ class object. The constructor will run when the program is initialized. From the constructor, we can call _CrtSetAllocHook to register our allocation hook function. But wait, what if the program we are debugging already has other global C++ class objects that allocate memory? How can we ensure that our constructor will be called first, and that our allocation hook function will be installed before any other global objects are constructed? Unfortunately, the C++ specification does not spell out any rules for deciding in which order to construct global objects. So there are no absolute guarantees that our constructor will be called first. But we can come very close to guaranteeing it. We can leverage a compiler-specific preprocessor directive that explicitly tells the compiler to ensure that our global variable is constructed as soon as possible: #pragma init_seg (compiler). This directive tells the compiler to place our global object in the "compiler" initialization segment. Objects in this segment are the first to be constructed. Next, objects in the "library" segment are constructed, and objects in the "user" segment are constructed last. The "user" segment is the default segment for global objects. Generally speaking, no normal user objects should ever be placed in the "compiler" segment, so this provides a reasonable amount of certainty that our global object will be constructed before any user objects.

-

Detecting Memory Leaks

-

Because global objects are destroyed in the inverse order they are constructed, our global object will be destroyed after any user objects. We can then examine the heap, just like the built-in detector does. If we find a block on the heap that has not been freed, it is a leak and we can look up its call stack using the unique ID number recorded by our allocation hook function. An STL map would work fine here for mapping the ID number to the call stacks. I didn't use an STL map because I wanted my library to be compatible with both new and old versions of Visual C++. The STL from older versions is incompatible with the newer versions, so I couldn't use STL components. But the good news is that this gave me the opportunity to create a data structure similar in concept to the STL map, but with specific optimizations for use with my memory leak detector.

-

Do you remember that the built-in leak detector peers inside the memory block to get the name of the file and the line number where the block was allocated? Well, all we have for our call stack is a bunch of program addresses. Dumping all those hex numbers to the debugger wouldn't be of much use. To make those addresses more meaningful, we need to translate them to human readable information: files and line numbers (and function names too). Once again, Microsoft comes through with the tools that will help us do our job: the symbol handler APIs. Like StackWalk64, they also happen to be part of the Debug Help Library. I won't dwell on them in detail here, because there are a lot of them and they're pretty simple to use. They don't require as much ingenuity to use as StackWalk64 does. We can use two of the symbol handler APIs to get the filenames, line numbers, and function names that we want. The aptly named SymGetLineFromAddr64 translates addresses into source filenames and line numbers. Its sister API, SymFromAddr translates addresses into symbol names. For program addresses, which are what we have, the corresponding symbol name will be the name of the function containing that program address.

-

Key Parts of the Source Code

-

In case you got bored with the above section and skipped ahead, I'll summarize it here. In a nutshell, this memory leak detector works like this:

-
    -
  1. A global object is automatically constructed. It is the first object constructed. The constructor registers our allocation hook function. -
  2. Every allocation eventually calls our allocation hook function. The allocation hook function obtains and records the call stack for each allocation. The call stack information is recorded in a specialized STL-like map. -
  3. When the program terminates, the global object is the last object destroyed. It examines the heap and identifies leaks. Leaked blocks are looked up in the map and matched with their corresponding call stack. The resulting data is sent to the debugger to be displayed.
-

Step 1: Registering the Allocation Hook

-

Here is the VisualLeakDetector class constructor. Note the call to _CrtSetAllocHook. This is where our callback function, allochook, is registered with the debug heap. The call to linkdebughelplibrary performs an explicit dynamic link with the Debug Help Library (dbghelp.dll). Because VLD is itself a library, implicitly linking with the Debug Help Library through the import library dbghelp.lib is undesirable; it would make the VLD library dependent on dbghelp.lib at link-time. dbghelp.lib will not be present on many Windows computers and it's not redistributable, so we need to link with the DLL at runtime in order to bypass the import library. There is a lot of other stuff going on in here as well, but most of it has to do with custom configuration options that VLD supports.

// Constructor - Dynamically links with the Debug Help Library and installs the
-//   allocation hook function so that the C runtime's debug heap manager will
-//   call the hook function for every heap request.
-//
-VisualLeakDetector::VisualLeakDetector ()
-{
-    // Initialize private data.
-    m_mallocmap    = new BlockMap;
-    m_process      = GetCurrentProcess();
-    m_selftestfile = __FILE__;
-    m_status       = 0x0;
-    m_thread       = GetCurrentThread();
-    m_tlsindex     = TlsAlloc();
-
-    if (_VLD_configflags & VLD_CONFIG_SELF_TEST) {
-        // Self-test mode has been enabled.
-        // Intentionally leak a small amount of
-        // memory so that memory leak self-checking can be verified.
-        strncpy(new char [21], "Memory Leak Self-Test", 21);
-        m_selftestline = __LINE__;
-    }
-
-    if (m_tlsindex == TLS_OUT_OF_INDEXES) {
-        report("ERROR: Visual Leak Detector:" 
-               " Couldn't allocate thread local storage.\n");
-    }
-    else if (linkdebughelplibrary()) {
-        // Register our allocation hook function with the debug heap.
-        m_poldhook = _CrtSetAllocHook(allochook);
-        report("Visual Leak Detector " 
-               "Version "VLD_VERSION" installed ("VLD_LIBTYPE").\n");
-        reportconfig();
-        if (_VLD_configflags & VLD_CONFIG_START_DISABLED) {
-            // Memory leak detection will initially be disabled.
-            m_status |= VLD_STATUS_NEVER_ENABLED;
-        }
-
-        m_status |= VLD_STATUS_INSTALLED;
-        return;
-    }
-    
-    report("Visual Leak Detector is NOT installed!\n");
-}
-

Step 2: Walking the Stack

-

Here is the function responsible for obtaining call stacks. This is perhaps the trickiest part of the entire program. Setting up for the first call to StackWalk64 is where the tricky bit is. To start the stack trace, StackWalk64 needs to know exactly where on the stack to begin walking. It never assumes that we want to start tracing from the current stack frame. This requires that we provide it with the address of the current frame, as well as the current program address. I've seen other examples that attempt to get this information by calling GetThreadContext to retrieve the current thread's context, which would contain both of the required addresses. But, as its documentation clearly states, GetThreadContext can't be relied upon to get valid information for a running thread. By definition, this means that GetThreadContext can't get a valid context for the current thread. A better approach is to get the required addresses directly, and the only way to do that is with inline assembly.

-

Obtaining the address of the current frame is easy: it's stored in a CPU register (EBP) that we can directly read it from. The program address is a little harder to obtain. Though there is a CPU register (EIP) that always contains the current program address, on Intel x86 CPUs, it can't be read by software. But we can get the same address in a round-about way, by calling another function and from within that function obtaining the return address. The return address is the same as the program address that called the function. For this, I've created a separate function, getprogramcounterx86x64. Since we're already doing inline assembly, we could write a simple function call in assembly, instead of writing another C++ function, but to keep it easier to understand, I've used C++ wherever it's possible to do so.

-

In the following code, pStackWalk64, pSymFunctionTableAccess64 and pSymGetModuleBase64 are all pointers to the functions exported by dbghelp.dll.

// getstacktrace - Traces the stack, starting from this function, as far
-//   back as possible.
-//
-//  - callstack (OUT): Pointer to an empty CallStack to be populated with
-//    entries from the stack trace.
-//
-//  Return Value:
-//
-//    None.
-//
-void VisualLeakDetector::getstacktrace (CallStack *callstack)
-{
-    DWORD        architecture;
-    CONTEXT      context;
-    unsigned int count = 0;
-    STACKFRAME64 frame;
-    DWORD_PTR    framepointer;
-    DWORD_PTR    programcounter;
-
-    // Get the required values for initialization of the STACKFRAME64 structure
-    // to be passed to StackWalk64(). Required fields are AddrPC and AddrFrame.
-#if defined(_M_IX86) || defined(_M_X64)
-    architecture = X86X64ARCHITECTURE;
-    programcounter = getprogramcounterx86x64();
-    __asm mov [framepointer], BPREG // Get the frame pointer (aka base pointer)
-#else
-// If you want to retarget Visual Leak Detector to another processor
-// architecture then you'll need to provide architecture-specific code to
-// retrieve the current frame pointer and program counter in order to initialize
-// the STACKFRAME64 structure below.
-#error "Visual Leak Detector is not supported on this architecture."
-#endif // defined(_M_IX86) || defined(_M_X64)
-
-    // Initialize the STACKFRAME64 structure.
-    memset(&frame, 0x0, sizeof(frame));
-    frame.AddrPC.Offset    = programcounter;
-    frame.AddrPC.Mode      = AddrModeFlat;
-    frame.AddrFrame.Offset = framepointer;
-    frame.AddrFrame.Mode   = AddrModeFlat;
-
-    // Walk the stack.
-    while (count < _VLD_maxtraceframes) {
-        count++;
-        if (!pStackWalk64(architecture, m_process, m_thread, 
-             &frame, &context, NULL, pSymFunctionTableAccess64, 
-             pSymGetModuleBase64, NULL)) {
-            // Couldn't trace back through any more frames.
-            break;
-        }
-        if (frame.AddrFrame.Offset == 0) {
-            // End of stack.
-            break;
-        }
-
-        // Push this frame's program counter onto the provided CallStack.
-        callstack->push_back((DWORD_PTR)frame.AddrPC.Offset);
-    }
-}
-

And here is the function that retrieves the EIP register. Again, this has to be done as a separate function call because there is no way for the software to directly read the EIP register. But the same value can be obtained by making a function call, and then from within the called function getting the return address. The return address is the program address that made the function call, and it is pushed onto the stack when the function call is made. We get it by copying it from the stack.

// getprogramcounterx86x64 - Helper function that retrieves the program counter
-//   for getstacktrace() on Intel x86 or x64 architectures.
-//
-//  Note: Inlining of this function must be disabled. The whole purpose of this
-//    function's existence depends upon it being a *called* function.
-//
-//  Return Value:
-//
-//    Returns the caller's program address.
-//
-#if defined(_M_IX86) || defined(_M_X64)
-#pragma auto_inline(off)
-DWORD_PTR VisualLeakDetector::getprogramcounterx86x64 ()
-{
-    DWORD_PTR programcounter;
-
-    // Get the return address out of the current stack frame
-    __asm mov AXREG, [BPREG + SIZEOFPTR]
-    // Put the return address into the variable we'll return
-    __asm mov [programcounter], AXREG
-
-    return programcounter;
-}
-#pragma auto_inline(on)
-#endif // defined(_M_IX86) || defined(_M_X64)
-

Step 3: Generating a Better Memory Leak Report

-

Finally, here is the function that converts the program addresses obtained while walking the stack into useful symbol names. Note that the address-to-symbol conversion code is only run if memory leaks are detected. This avoids having to do symbol lookups on-the-fly while the program is running, which would add considerable additional overhead. Not to mention that it just doesn't make sense to store (large) symbol names for later retrieval when you can store (small) addresses instead.

-

The CRT doesn't expose any documented method for gaining access to its internal linked-list of allocated memory blocks. This linked list is what is used by the built-in detector for taking a "snapshot" of the heap to determine if there are any memory leaks. I've come up with a very simple trick to gain access to the list. Any time a new memory block is allocated, it happens to be placed at the beginning of the linked-list. So, to get a pointer to the head of the list, I just allocate a temporary memory block. That block's address can be converted to the address of the containing _CrtMemBlockHeader structure and now I have a pointer to the beginning of the linked list.

-

In the following code, pSymSetOptions, pSymInitialize, pSymGetLineFromAddr64, and pSymFromAddr are all pointers to the functions exported by dbghelp.dll. The report function is just a custom wrapper around OutputDebugString which sends messages to the debugger for display in the debugger's output window.

-

This function is quite long. To cut down on clutter, I've removed all of the uninteresting and trivial parts. To see this function in its entirety, please download the source ZIP file.

// reportleaks - Generates a memory leak report when the program terminates if
-//   leaks were detected. The report is displayed in the debug output window.
-//
-//  Return Value:
-//
-//    None.
-//
-void VisualLeakDetector::reportleaks ()
-{
-
-    ...
-
-    // Initialize the symbol handler. We use it for obtaining source file/line
-    // number information and function names for the memory leak report.
-    symbolpath = buildsymbolsearchpath();
-    pSymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS | SYMOPT_UNDNAME);
-    if (!pSymInitialize(m_process, symbolpath, TRUE)) {
-        report("WARNING: Visual Leak Detector: The symbol handler" 
-               " failed to initialize (error=%lu).\n"
-               "    Stack traces will probably not be available" 
-               " for leaked blocks.\n", GetLastError());
-    }
-
-    ...
-
-#ifdef _MT
-    _mlock(_HEAP_LOCK);
-#endif // _MT
-    pheap = new char;
-    pheader = pHdr(pheap)->pBlockHeaderNext;
-    delete pheap;
-    while (pheader) {
-
-        ...
-
-        callstack = m_mallocmap->find(pheader->lRequest);
-        if (callstack) {
-
-            ...
-
-            // Iterate through each frame in the call stack.
-            for (frame = 0; frame < callstack->size(); frame++) {
-                // Try to get the source file and line number associated with
-                // this program counter address.
-                if (pSymGetLineFromAddr64(m_process, 
-                   (*callstack)[frame], &displacement, &sourceinfo)) {
-
-                    ...
-
-                }
-
-                // Try to get the name of the function containing this program
-                // counter address.
-                if (pSymFromAddr(m_process, (*callstack)[frame], 
-                    &displacement64, pfunctioninfo)) {
-                    functionname = pfunctioninfo->Name;
-                }
-                else {
-                    functionname = "(Function name unavailable)";
-                }
-
-                ...
-
-            }
-
-            ...
-
-        }
-        pheader = pheader->pBlockHeaderNext;
-    }
-#ifdef _MT
-    _munlock(_HEAP_LOCK);
-#endif // _MT
-
-    ...
-
-}
-

Known Bugs and Restrictions

-

There are currently no known bugs in the latest release, but there are some known restrictions:

-
    -
  • VLD does not detect COM leaks, out-of-process resource leaks, or any other types of memory leaks that are not associated with the CRT heap. In simpler terms, VLD only detects memory leaks that are the result of calls to new or malloc. Keep in mind that VLD was created as an alternative to the built-in memory leak detector, which also only detects leaks from new and malloc. -
  • VLD is not compatible with version 6.5 of the Debug Help Library (dbghelp.dll). The recommended version of dbghelp.dll to use with VLD is 6.3. Version 6.3 is included in the VLD distribution. -
  • The pre-compiled libraries included in the VLD distribution may not be compatible with Visual Studio 2005. If you need to use VLD with Visual Studio 2005, building VLD from source in Visual Studio 2005 should create compatible libraries.
-

Credits

-
    -
  • Thanks to Alexandre Nikolov for quickly discovering the bug in 0.9e and helping to slap together a quick fix. -
  • Credit for the idea of how to make VLD's global class VisualLeakDetector object get constructed before any other user global objects goes to cmk. Thanks cmk! -
  • Thanks to Nitrogenycs (aka Matthias) for discovering the VLD_MAX_DATA_DUMP infinite loop bug. -
  • Thanks to hsvcs (aka Holger) for discovering the VLD_MAX_DATA_DUMP compilation bug. -
  • Thanks to Don Clugston for pointing out to me that people sometimes do build optimized debug executables, and that I need to watch out for that.
-

References

-

Here are some links to useful related articles and resources:

- -

License

-

Visual Leak Detector is distributed under the terms of the GNU Lesser General Public License. See the documentation included in the downloadable ZIP files for detailed licensing information.

-

History

-

This list gives a brief overview of the changes made from release to release. For a detailed description of changes made in each release, please see the change log, CHANGES.txt, in the downloadable ZIP files.

-
    -
  • 14 November 2006: Version 1.9d beta - Fixed a deadlock bug that may occur in multithreaded programs. Also fixed a two failed assertion bugs.
  • -
  • 6 November 2006: Version 1.9c beta - New installer to make starting out with VLD easier. All known incompatibilities with Visual Studio 2005 have been fixed. -
  • 9 March 2006: Version 1.9a beta - Entirely new leak detection engine detects most, if not all, in-process memory leaks not just leaks from new or malloc. Added many other new convenience features as well. -
  • 5 August 2005: Version 1.0 - A couple of new features have been added, and a few bugs have been fixed. Major revisions have been made to this article to bring it up to date with respect to the 1.0 release. -
  • 2 May 2005: Version 0.9i beta - This release fixed several bugs. It also includes support for Windows x64. -
  • 22 April 2005: Version 0.9h beta - This release contains a crucial fix for an internal logic bug in version 0.9g. -
  • 22 April 2005: Version 0.9g beta - This release contains a vastly improved internal search/sort algorithm that results in a significant overall performance boost. -
  • 13 April 2005: Version 0.9f beta - This provides a quick fix for a bug in 0.9e that can cause crashes. -
  • 12 April 2005: Version 0.9e beta - Solves compatibility problems between the pre-built libraries and Visual Studio .NET by removing the use of STL components (the pre-built libraries are built in Visual Studio 6.0 and the STL is not compatible between .NET and 6.0). -
  • 30 March 2005: Version 0.9d beta - First release of VLD as a set of pre-built libraries. -
  • 17 March 2005: Version 0.9c beta - Fixed a compilation error if VLD_MAX_DATA_DUMP is defined. -
  • 15 March 2005: Version 0.9b beta - Improved ability to detect leaks in global C++ object constructors. -
  • 12 March 2005: Version 0.9a beta - Initial public release.
- - - - \ No newline at end of file diff --git a/console/vldconsole.vcproj b/console/vldconsole.vcproj deleted file mode 100755 index 86b2ed57..00000000 --- a/console/vldconsole.vcproj +++ /dev/null @@ -1,267 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/crtmfcpatch.h b/crtmfcpatch.h deleted file mode 100755 index 22a61eb3..00000000 --- a/crtmfcpatch.h +++ /dev/null @@ -1,954 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - CRT and MFC IAT Patch Functions Header -// Copyright (c) 2009 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef VLDBUILD -#error \ -"This header should only be included by Visual Leak Detector when building it from source. \ -Applications should never include this header." -#endif - -#include "vldint.h" -extern __declspec(dllexport) VisualLeakDetector vld; - -#define TEMPLATE_HEADER \ -template - -#define TEMPLATE_ARGS \ - crtddll, mfcddll, mfcuddll,\ - crtd_vector_new_name, crtd_vector_new_dbg_name,\ - crtd_scalar_new_name, crtd_scalar_new_dbg_name,\ - mfcd_vector_new_ordinal, mfcd_vector_new_dbg_4p_ordinal, mfcd_vector_new_dbg_3p_ordinal,\ - mfcd_scalar_new_ordinal, mfcd_scalar_new_dbg_4p_ordinal, mfcd_scalar_new_dbg_3p_ordinal,\ - mfcud_vector_new_ordinal, mfcud_vector_new_dbg_4p_ordinal, mfcud_vector_new_dbg_3p_ordinal,\ - mfcud_scalar_new_ordinal, mfcud_scalar_new_dbg_4p_ordinal, mfcud_scalar_new_dbg_3p_ordinal - -TEMPLATE_HEADER -class CrtMfcPatch -{ -public: - static void* __cdecl crtd__calloc_dbg (size_t num, size_t size, int type, char const *file, int line); - static void* __cdecl crtd__malloc_dbg (size_t size, int type, const char *file, int line); - static void* __cdecl crtd__realloc_dbg (void *mem, size_t size, int type, char const *file, int line); - static void* __cdecl crtd__scalar_new_dbg (size_t size, int type, char const *file, int line); - static void* __cdecl crtd__vector_new_dbg (size_t size, int type, char const *file, int line); - static void* __cdecl crtd_calloc (size_t num, size_t size); - static void* __cdecl crtd_malloc (size_t size); - static void* __cdecl crtd_realloc (void *mem, size_t size); - static void* __cdecl crtd_scalar_new (size_t size); - static void* __cdecl crtd_vector_new (size_t size); - - template - static void* __cdecl crtd_new_dbg (SIZE_T fp, size_t size, int type, char const *file, int line); - template - static void* __cdecl crtd_new (SIZE_T fp, size_t size); - - static void* __cdecl mfcd_vector_new (size_t size); - static void* __cdecl mfcd__vector_new_dbg_4p (size_t size, int type, char const *file, int line); - static void* __cdecl mfcd__vector_new_dbg_3p (size_t size, char const *file, int line); - static void* __cdecl mfcd_scalar_new (size_t size); - static void* __cdecl mfcd__scalar_new_dbg_4p (size_t size, int type, char const *file, int line); - static void* __cdecl mfcd__scalar_new_dbg_3p (size_t size, char const *file, int line); - static void* __cdecl mfcud_vector_new (size_t size); - static void* __cdecl mfcud__vector_new_dbg_4p (size_t size, int type, char const *file, int line); - static void* __cdecl mfcud__vector_new_dbg_3p (size_t size, char const *file, int line); - static void* __cdecl mfcud_scalar_new (size_t size); - static void* __cdecl mfcud__scalar_new_dbg_4p (size_t size, int type, char const *file, int line); - static void* __cdecl mfcud__scalar_new_dbg_3p (size_t size, char const *file, int line); - - template - static void* __cdecl mfcd_new_dbg (SIZE_T fp, size_t size, int type, char const *file, int line); - template - static void* __cdecl mfcd_new_dbg (SIZE_T fp, size_t size, char const *file, int line); - template - static void* __cdecl mfcd_new (SIZE_T fp, size_t size); -}; - - -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Studio DLLs -// -//////////////////////////////////////////////////////////////////////////////// - -// crtd__calloc_dbg - Calls to _calloc_dbg from msvcrXXd.dll are patched -// through to this function. -// -// - mem (IN): Pointer to the memory block to be reallocated. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - type (IN): The CRT "use type" of the block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by _calloc_dbg. -// -TEMPLATE_HEADER -void* CrtMfcPatch::crtd__calloc_dbg (size_t num, - size_t size, - int type, - char const *file, - int line) -{ - static _calloc_dbg_t pcrtxxd__calloc_dbg = NULL; - - SIZE_T fp; - HMODULE msvcrxxd; - - FRAMEPOINTER(fp); - - if (pcrtxxd__calloc_dbg == NULL) { - // This is the first call to this function. Link to the real - // _calloc_dbg. - msvcrxxd = GetModuleHandle(crtddll); - pcrtxxd__calloc_dbg = (_calloc_dbg_t)GetProcAddress(msvcrxxd, "_calloc_dbg"); - } - - return vld.__calloc_dbg(pcrtxxd__calloc_dbg, fp, num, size, type, file, line); -} - -// crtd__malloc_dbg - Calls to _malloc_dbg from msvcrXXd.dll are patched -// through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - type (IN): The CRT "use type" of the block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by _malloc_dbg. -// -TEMPLATE_HEADER -void* CrtMfcPatch::crtd__malloc_dbg (size_t size, - int type, - char const *file, - int line) -{ - static _malloc_dbg_t pcrtxxd__malloc_dbg = NULL; - - SIZE_T fp; - HMODULE msvcrxxd; - - FRAMEPOINTER(fp); - - if (pcrtxxd__malloc_dbg == NULL) { - // This is the first call to this function. Link to the real - // _malloc_dbg. - msvcrxxd = GetModuleHandle(crtddll); - pcrtxxd__malloc_dbg = (_malloc_dbg_t)GetProcAddress(msvcrxxd, "_malloc_dbg"); - } - - return vld.__malloc_dbg(pcrtxxd__malloc_dbg, fp, size, type, file, line); -} - -// crtd__realloc_dbg - Calls to _realloc_dbg from msvcrXXd.dll are patched -// through to this function. -// -// - mem (IN): Pointer to the memory block to be reallocated. -// -// - size (IN): The size of the memory block to reallocate. -// -// - type (IN): The CRT "use type" of the block to be reallocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by _realloc_dbg. -// -TEMPLATE_HEADER -void* CrtMfcPatch::crtd__realloc_dbg (void *mem, - size_t size, - int type, - char const *file, - int line) -{ - static _realloc_dbg_t pcrtxxd__realloc_dbg = NULL; - - SIZE_T fp; - HMODULE msvcrxxd; - - FRAMEPOINTER(fp); - - if (pcrtxxd__realloc_dbg == NULL) { - // This is the first call to this function. Link to the real - // _realloc_dbg. - msvcrxxd = GetModuleHandle(crtddll); - pcrtxxd__realloc_dbg = (_realloc_dbg_t)GetProcAddress(msvcrxxd, "_realloc_dbg"); - } - - return vld.__realloc_dbg(pcrtxxd__realloc_dbg, fp, mem, size, type, file, line); -} - -// crtd__scalar_new_dbg - Calls to the CRT's debug scalar new operator from -// msvcrXXd.dll are patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - type (IN): The CRT "use type" of the block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the CRT debug scalar new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::crtd__scalar_new_dbg (size_t size, - int type, - char const *file, - int line) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return crtd_new_dbg(fp, size, type, file, line); -} - -// crtd__vector_new_dbg - Calls to the CRT's debug vector new operator from -// msvcrXXd.dll are patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - type (IN): The CRT "use type" of the block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the CRT debug vector new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::crtd__vector_new_dbg (size_t size, - int type, - char const *file, - int line) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return crtd_new_dbg(fp, size, type, file, line); -} - -// crtd_calloc - Calls to calloc from msvcrXXd.dll are patched through to -// this function. -// -// - dll (IN): The name of the dll -// -// - num (IN): The number of blocks, of size 'size', to be allocated. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// Return Value: -// -// Returns the valued returned from calloc. -// -TEMPLATE_HEADER -void* CrtMfcPatch::crtd_calloc (size_t num, size_t size) -{ - static calloc_t pcrtxxd_calloc = NULL; - - SIZE_T fp; - HMODULE msvcrxxd; - - FRAMEPOINTER(fp); - - if (pcrtxxd_calloc == NULL) { - // This is the first call to this function. Link to the real malloc. - msvcrxxd = GetModuleHandle(crtddll); - pcrtxxd_calloc = (calloc_t)GetProcAddress(msvcrxxd, "calloc"); - } - - return vld._calloc(pcrtxxd_calloc, fp, num, size); -} - -// crtd_malloc - Calls to malloc from msvcrXXd.dll are patched through to -// this function. -// -// - dll (IN): The name of the dll -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// Return Value: -// -// Returns the valued returned from malloc. -// -TEMPLATE_HEADER -void* CrtMfcPatch::crtd_malloc (size_t size) -{ - static malloc_t pcrtxxd_malloc = NULL; - - SIZE_T fp; - HMODULE msvcrxxd; - - FRAMEPOINTER(fp); - - if (pcrtxxd_malloc == NULL) { - // This is the first call to this function. Link to the real malloc. - msvcrxxd = GetModuleHandle(crtddll); - pcrtxxd_malloc = (malloc_t)GetProcAddress(msvcrxxd, "malloc"); - } - - return vld._malloc(pcrtxxd_malloc, fp, size); -} - -// crtd_realloc - Calls to realloc from msvcrXXd.dll are patched through to -// this function. -// -// - dll (IN): The name of the dll -// -// - mem (IN): Pointer to the memory block to reallocate. -// -// - size (IN): Size of the memory block to reallocate. -// -// Return Value: -// -// Returns the value returned from realloc. -// -TEMPLATE_HEADER -void* CrtMfcPatch::crtd_realloc (void *mem, size_t size) -{ - static realloc_t pcrtxxd_realloc = NULL; - - SIZE_T fp; - HMODULE msvcrxxd; - - FRAMEPOINTER(fp); - - if (pcrtxxd_realloc == NULL) { - // This is the first call to this function. Link to the real realloc. - msvcrxxd = GetModuleHandle(crtddll); - pcrtxxd_realloc = (realloc_t)GetProcAddress(msvcrxxd, "realloc"); - } - - return vld._realloc(pcrtxxd_realloc, fp, mem, size); -} - -// crtd_scalar_new - Calls to the CRT's scalar new operator from msvcrXXd.dll -// are patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// Return Value: -// -// Returns the value returned by the CRT scalar new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::crtd_scalar_new (size_t size) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return crtd_new(fp, size); -} - -// crtd_vector_new - Calls to the CRT's vector new operator from msvcrXXd.dll -// are patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// Return Value: -// -// Returns the value returned by the CRT vector new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::crtd_vector_new (size_t size) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return crtd_new(fp, size); -} - -// crtd_new_dbg - A template function for implementation of patch functions to -// the CRT's debug new operator from msvcrXXd.dll -// -// - procname (IN): The debug new operator's name -// -// - fp (IN): Frame pointer from the call that initiated this allocation. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - type (IN): The CRT "use type" of the block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the CRT debug new operator. -// -TEMPLATE_HEADER -template -void* CrtMfcPatch::crtd_new_dbg (SIZE_T fp, - size_t size, - int type, - char const *file, - int line) -{ - static new_dbg_crt_t pcrtxxd_new_dbg = NULL; - - HMODULE msvcrxxd; - - if (pcrtxxd_new_dbg == NULL) { - // This is the first call to this function. Link to the real CRT debug - // new operator. - msvcrxxd = GetModuleHandle(crtddll); - pcrtxxd_new_dbg = (new_dbg_crt_t)GetProcAddress(msvcrxxd, procname); - } - - return vld.new_dbg_crt(pcrtxxd_new_dbg, fp, size, type, file, line); -} - -// crt_new - A template function for implementing patch functions to the -// CRT's new operator from msvcrXXd.dll -// -// - dll (IN): The name of the dll -// -// - procname (IN): The debug new operator's name -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// Return Value: -// -// Returns the value returned by the CRT new operator. -// -TEMPLATE_HEADER -template -void* CrtMfcPatch::crtd_new (SIZE_T fp, size_t size) -{ - static new_t pcrtxxd_scalar_new = NULL; - - HMODULE msvcrxxd; - - if (pcrtxxd_scalar_new == NULL) { - // This is the first call to this function. Link to the real CRT new - // operator. - msvcrxxd = GetModuleHandle(crtddll); - pcrtxxd_scalar_new = (new_t)GetProcAddress(msvcrxxd, procname); - } - - return vld._new(pcrtxxd_scalar_new, fp, size); -} - -//////////////////////////////////////////////////////////////////////////////// -// -// MFC DLLs -// -//////////////////////////////////////////////////////////////////////////////// - -// mfcd__scalar_new_dbg_3p - Calls to the MFC debug scalar new operator from -// mfcXXd.dll are patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - type (IN): The "use type" of the block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the MFC debug scalar new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::mfcd__scalar_new_dbg_4p (size_t size, - int type, - char const *file, - int line) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return mfcd_new_dbg - (fp, size, type, file, line); -} - -// mfcd__scalar_new_dbg_3p - Calls to the MFC debug scalar new operator from -// mfcXXd.dll are patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the MFC debug scalar new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::mfcd__scalar_new_dbg_3p (size_t size, - char const *file, - int line) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return mfcd_new_dbg - (fp, size, file, line); -} - -// mfcd__vector_new_dbg_4p - Calls to the MFC debug vector new operator from -// mfcXXd.dll are patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - type (IN): The "use type" of the block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the MFC debug vector new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::mfcd__vector_new_dbg_4p (size_t size, - int type, - char const *file, - int line) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return mfcd_new_dbg - (fp, size, type, file, line); -} - -// mfcd__vector_new_dbg_3p - Calls to the MFC debug vector new operator from -// mfcXXd.dll are patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the MFC debug vector new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::mfcd__vector_new_dbg_3p (size_t size, - char const *file, - int line) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return mfcd_new_dbg - (fp, size, file, line); -} - -// mfcd_scalar_new - Calls to the MFC scalar new operator from mfcXXd.dll are -// patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// Return Value: -// -// Returns the value returned by the MFC scalar new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::mfcd_scalar_new (size_t size) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return mfcd_new(fp, size); -} - -// mfcd_vector_new - Calls to the MFC vector new operator from mfcXXd.dll are -// patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// Return Value: -// -// Returns the value returned by the MFC vector new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::mfcd_vector_new (size_t size) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return mfcd_new(fp, size); -} - -// mfcud__scalar_new_dbg_4p - Calls to the MFC debug scalar new operator from -// mfcXXud.dll are patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - type (IN): The "use type" of the block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the MFC debug scalar new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::mfcud__scalar_new_dbg_4p (size_t size, - int type, - char const *file, - int line) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return mfcd_new_dbg - (fp, size, type, file, line); -} - -// mfcud__scalar_new_dbg_3p - Calls to the MFC debug scalar new operator from -// mfcXXud.dll are patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the MFC debug scalar new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::mfcud__scalar_new_dbg_3p (size_t size, - char const *file, - int line) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return mfcd_new_dbg - (fp, size, file, line); -} - -// mfcud__vector_new_dbg_4p - Calls to the MFC debug vector new operator from -// mfcXXud.dll are patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - type (IN): The "use type" of the block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the MFC debug vector new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::mfcud__vector_new_dbg_4p (size_t size, - int type, - char const *file, - int line) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return mfcd_new_dbg - (fp, size, type, file, line); -} - -// mfcud__vector_new_dbg_3p - Calls to the MFC debug vector new operator from -// mfcXXud.dll are patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the MFC debug vector new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::mfcud__vector_new_dbg_3p (size_t size, - char const *file, - int line) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return mfcd_new_dbg - (fp, size, file, line); -} - -// mfcud_scalar_new - Calls to the MFC scalar new operator from mfcXXud.dll are -// patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// Return Value: -// -// Returns the value returned by the MFC scalar new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::mfcud_scalar_new (size_t size) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return mfcd_new(fp, size); -} - -// mfcud_vector_new - Calls to the MFC vector new operator from mfcXXud.dll are -// patched through to this function. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// Return Value: -// -// Returns the value returned by the MFC vector new operator. -// -TEMPLATE_HEADER -void* CrtMfcPatch::mfcud_vector_new (size_t size) -{ - SIZE_T fp; - FRAMEPOINTER(fp); - - return mfcd_new(fp, size); -} - -// mfcd_new_dbg - A generic function for implementing patch functions to the MFC -// debug new operators: -// void* __cdecl operator new[](size_t size, int type, char const *file, int line) -// void* __cdecl operator new(size_t size, int type, char const *file, int line) -// -// - mfcdll (IN): The name of the MFC DLL -// -// - ordinal (IN): The debug new operator's ordinal value -// -// - type (IN): The "use type" of the block to be allocated. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the MFC debug new operator. -// -TEMPLATE_HEADER -template -void* CrtMfcPatch::mfcd_new_dbg (SIZE_T fp, - size_t size, - int type, - char const *file, - int line) -{ - static new_dbg_crt_t pmfcxxd__new_dbg = NULL; - - HMODULE mfcxxd; - - if (pmfcxxd__new_dbg == NULL) { - // This is the first call to this function. Link to the real MFC debug - // new operator. - mfcxxd = GetModuleHandle(mfcdll); - pmfcxxd__new_dbg = (new_dbg_crt_t)GetProcAddress(mfcxxd, (LPCSTR)ordinal); - } - - return vld.new_dbg_mfc(pmfcxxd__new_dbg, fp, size, type, file, line); -} - -// mfcd_new_dbg - A generic function for implementing patch functions to the MFC -// debug new operators: -// void* __cdecl operator new[](size_t size, char const *file, int line) -// void* __cdecl operator new(size_t size, char const *file, int line) -// -// - mfcdll (IN): The name of the MFC DLL -// -// - ordinal (IN): The debug new operator's ordinal value -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the MFC debug new operator. -// -TEMPLATE_HEADER -template -void* CrtMfcPatch::mfcd_new_dbg (SIZE_T fp, - size_t size, - char const *file, - int line) -{ - static new_dbg_mfc_t pmfcxxd__new_dbg = NULL; - - HMODULE mfcxxd; - - if (pmfcxxd__new_dbg == NULL) { - // This is the first call to this function. Link to the real MFC debug - // new operator. - mfcxxd = GetModuleHandle(mfcdll); - pmfcxxd__new_dbg = (new_dbg_mfc_t)GetProcAddress(mfcxxd, (LPCSTR)ordinal); - } - - return vld.new_dbg_mfc(pmfcxxd__new_dbg, fp, size, file, line); -} - -// mfcd_new - A generic function for implementing patch functions to the MFC new -// operators. -// -// - mfcdll (IN): The name of the MFC DLL -// -// - ordinal (IN): The new operator's ordinal value -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// Return Value: -// -// Returns the value returned by the MFC new operator. -// -TEMPLATE_HEADER -template -void* CrtMfcPatch::mfcd_new (SIZE_T fp, size_t size) -{ - static new_t pmfcxxd_new = NULL; - - HMODULE mfcxxd; - - if (pmfcxxd_new == NULL) { - // This is the first call to this function. Link to the real CRT new - // operator. - mfcxxd = GetModuleHandle(mfcdll); - pmfcxxd_new = (new_t)GetProcAddress(mfcxxd, (LPCSTR)ordinal); - } - - return vld._new(pmfcxxd_new, fp, size); -} - -#undef TEMPLATE_HEADER -#undef TEMPLATE_ARGS - -const extern char scalar_new_dbg_name[] = "??2@YAPAXIHPBDH@Z"; -const extern char vector_new_dbg_name[] = "??_U@YAPAXIHPBDH@Z"; -const extern char scalar_new_name[] = "??2@YAPAXI@Z"; -const extern char vector_new_name[] = "??_U@YAPAXI@Z"; -const extern wchar_t msvcrtd_dll[] = L"msvcrtd.dll"; -const extern wchar_t mfc42d_dll[] = L"mfc42d.dll"; -const extern wchar_t mfc42ud_dll[] = L"mfc42ud.dll"; -const extern wchar_t msvcr70d_dll[] = L"msvcr70d.dll"; -const extern wchar_t mfc70d_dll[] = L"mfc70d.dll"; -const extern wchar_t mfc70ud_dll[] = L"mfc70ud.dll"; -const extern wchar_t msvcr71d_dll[] = L"msvcr71d.dll"; -const extern wchar_t mfc71d_dll[] = L"mfc71d.dll"; -const extern wchar_t mfc71ud_dll[] = L"mfc71ud.dll"; -const extern wchar_t msvcr80d_dll[] = L"msvcr80d.dll"; -const extern wchar_t mfc80d_dll[] = L"mfc80d.dll"; -const extern wchar_t mfc80ud_dll[] = L"mfc80ud.dll"; -const extern wchar_t msvcr90d_dll[] = L"msvcr90d.dll"; -const extern wchar_t mfc90d_dll[] = L"mfc90d.dll"; -const extern wchar_t mfc90ud_dll[] = L"mfc90ud.dll"; - -// Visual Studio 6.0 -typedef CrtMfcPatch - VS60; -// Visual Studio .NET 2002 -typedef CrtMfcPatch - VS70; -// Visual Studio .NET 2003 -typedef CrtMfcPatch - VS71; -// Visual Studio 2005 -typedef CrtMfcPatch - VS80; -// Visual Studio 2008 -typedef CrtMfcPatch - VS90; diff --git a/lib/cppformat/ChangeLog.rst b/lib/cppformat/ChangeLog.rst new file mode 100644 index 00000000..fe780ae0 --- /dev/null +++ b/lib/cppformat/ChangeLog.rst @@ -0,0 +1,335 @@ +1.1.0 - 2015-03-06 +------------------ + +* Added ``BasicArrayWriter``, a class template that provides operations for + formatting and writing data into a fixed-size array + (`#105 `_ and + `#122 `_): + + .. code:: c++ + + char buffer[100]; + fmt::ArrayWriter w(buffer); + w.write("The answer is {}", 42); + +* Added `0 A.D. `_ and `PenUltima Online (POL) + `_ to the list of notable projects using C++ Format. + +* C++ Format now uses MSVC intrinsics for better formatting performance + (`#115 `_, + `#116 `_, + `#118 `_ and + `#121 `_). + Previously these optimizations where only used on GCC and Clang. + Thanks to `@CarterLi `_ and + `@objectx `_. + +* CMake install target (`#119 `_). + Thanks to `@TrentHouliston `_. + + You can now install C++ Format with ``make install`` command. + +* Improved `Biicode `_ support + (`#98 `_ and + `#104 `_). Thanks to + `@MariadeAnton `_ and + `@franramirez688 `_. + +* Improved support for bulding with `Android NDK + `_ + (`#107 `_). + Thanks to `@newnon `_. + + The `android-ndk-example `_ + repository provides and example of using C++ Format with Android NDK: + + .. image:: https://raw.githubusercontent.com/cppformat/android-ndk-example/ + master/screenshot.png + +* Improved documentation of ``SystemError`` and ``WindowsError`` + (`#54 `_). + +* Various code improvements + (`#110 `_, + `#111 `_ + `#112 `_). + Thanks to `@CarterLi `_. + +* Improved compile-time errors when formatting wide into narrow strings + (`#117 `_). + +* Fixed ``BasicWriter::write`` without formatting arguments when C++11 support + is disabled (`#109 `_). + +* Fixed header-only build on OS X with GCC 4.9 + (`#124 `_). + +* Fixed packaging issues (`#94 `_). + +* Fixed warnings in GCC, MSVC and Xcode/Clang + (`#95 `_, + `#96 `_ and + `#114 `_). + +* Added `changelog `_ + (`#103 `_). + +1.0.0 - 2015-02-05 +------------------ + +* Add support for a header-only configuration when ``FMT_HEADER_ONLY`` is + defined before including ``format.h``: + + .. code:: c++ + + #define FMT_HEADER_ONLY + #include "format.h" + +* Compute string length in the constructor of ``BasicStringRef`` + instead of the ``size`` method + (`#79 `_). + This eliminates size computation for string literals on reasonable optimizing + compilers. + +* Fix formatting of types with overloaded ``operator <<`` for ``std::wostream`` + (`#86 `_): + + .. code:: c++ + + fmt::format(L"The date is {0}", Date(2012, 12, 9)); + +* Fix linkage of tests on Arch Linux + (`#89 `_). + +* Allow precision specifier for non-float arguments + (`#90 `_): + + .. code:: c++ + + fmt::print("{:.3}\n", "Carpet"); // prints "Car" + +* Fix build on Android NDK + (`#93 `_) + +* Improvements to documentation build procedure. + +* Remove ``FMT_SHARED`` CMake variable in favor of standard `BUILD_SHARED_LIBS + `_. + +* Fix error handling in ``fmt::fprintf``. + +* Fix a number of warnings. + +0.12.0 - 2014-10-25 +------------------- + +* [Breaking] Improved separation between formatting and buffer management. + ``Writer`` is now a base class that cannot be instantiated directly. + The new ``MemoryWriter`` class implements the default buffer management + with small allocations done on stack. So ``fmt::Writer`` should be replaced + with ``fmt::MemoryWriter`` in variable declarations. + + Old code: + + .. code:: c++ + + fmt::Writer w; + + New code: + + .. code:: c++ + + fmt::MemoryWriter w; + + If you pass ``fmt::Writer`` by reference, you can continue to do so: + + .. code:: c++ + + void f(fmt::Writer &w); + + This doesn't affect the formatting API. + +* Support for custom memory allocators + (`#69 `_) + +* Formatting functions now accept `signed char` and `unsigned char` strings as + arguments (`#73 `_): + + .. code:: c++ + + auto s = format("GLSL version: {}", glGetString(GL_VERSION)); + +* Reduced code bloat. According to the new `benchmark results + `_, + cppformat is close to ``printf`` and by the order of magnitude better than + Boost Format in terms of compiled code size. + +* Improved appearance of the documentation on mobile by using the `Sphinx + Bootstrap theme `_: + + .. |old| image:: https://cloud.githubusercontent.com/assets/576385/4792130/ + cd256436-5de3-11e4-9a62-c077d0c2b003.png + + .. |new| image:: https://cloud.githubusercontent.com/assets/576385/4792131/ + cd29896c-5de3-11e4-8f59-cac952942bf0.png + + +-------+-------+ + | Old | New | + +-------+-------+ + | |old| | |new| | + +-------+-------+ + +0.11.0 - 2014-08-21 +------------------- + +* Safe printf implementation with a POSIX extension for positional arguments: + + .. code:: c++ + + fmt::printf("Elapsed time: %.2f seconds", 1.23); + fmt::printf("%1$s, %3$d %2$s", weekday, month, day); + +* Arguments of ``char`` type can now be formatted as integers + (Issue `#55 `_): + + .. code:: c++ + + fmt::format("0x{0:02X}", 'a'); + +* Deprecated parts of the API removed. + +* The library is now built and tested on MinGW with Appveyor in addition to + existing test platforms Linux/GCC, OS X/Clang, Windows/MSVC. + +0.10.0 - 2014-07-01 +------------------- + +**Improved API** + +* All formatting methods are now implemented as variadic functions instead + of using ``operator<<`` for feeding arbitrary arguments into a temporary + formatter object. This works both with C++11 where variadic templates are + used and with older standards where variadic functions are emulated by + providing lightweight wrapper functions defined with the ``FMT_VARIADIC`` + macro. You can use this macro for defining your own portable variadic + functions: + + .. code:: c++ + + void report_error(const char *format, const fmt::ArgList &args) { + fmt::print("Error: {}"); + fmt::print(format, args); + } + FMT_VARIADIC(void, report_error, const char *) + + report_error("file not found: {}", path); + + Apart from a more natural syntax, this also improves performance as there + is no need to construct temporary formatter objects and control arguments' + lifetimes. Because the wrapper functions are very ligthweight, this doesn't + cause code bloat even in pre-C++11 mode. + +* Simplified common case of formatting an ``std::string``. Now it requires a + single function call: + + .. code:: c++ + + std::string s = format("The answer is {}.", 42); + + Previously it required 2 function calls: + + .. code:: c++ + + std::string s = str(Format("The answer is {}.") << 42); + + Instead of unsafe ``c_str`` function, ``fmt::Writer`` should be used directly + to bypass creation of ``std::string``: + + .. code:: c++ + + fmt::Writer w; + w.write("The answer is {}.", 42); + w.c_str(); // returns a C string + + This doesn't do dynamic memory allocation for small strings and is less error + prone as the lifetime of the string is the same as for ``std::string::c_str`` + which is well understood (hopefully). + +* Improved consistency in naming functions that are a part of the public API. + Now all public functions are lowercase following the standard library + conventions. Previously it was a combination of lowercase and + CapitalizedWords. + Issue `#50 `_. + +* Old functions are marked as deprecated and will be removed in the next + release. + +**Other Changes** + +* Experimental support for printf format specifications (work in progress): + + .. code:: c++ + + fmt::printf("The answer is %d.", 42); + std::string s = fmt::sprintf("Look, a %s!", "string"); + +* Support for hexadecimal floating point format specifiers ``a`` and ``A``: + + .. code:: c++ + + print("{:a}", -42.0); // Prints -0x1.5p+5 + print("{:A}", -42.0); // Prints -0X1.5P+5 + +* CMake option ``FMT_SHARED`` that specifies whether to build format as a + shared library (off by default). + +0.9.0 - 2014-05-13 +------------------ + +* More efficient implementation of variadic formatting functions. + +* ``Writer::Format`` now has a variadic overload: + + .. code:: c++ + + Writer out; + out.Format("Look, I'm {}!", "variadic"); + +* For efficiency and consistency with other overloads, variadic overload of + the ``Format`` function now returns ``Writer`` instead of ``std::string``. + Use the ``str`` function to convert it to ``std::string``: + + .. code:: c++ + + std::string s = str(Format("Look, I'm {}!", "variadic")); + +* Replaced formatter actions with output sinks: ``NoAction`` -> ``NullSink``, + ``Write`` -> ``FileSink``, ``ColorWriter`` -> ``ANSITerminalSink``. + This improves naming consistency and shouldn't affect client code unless + these classes are used directly which should be rarely needed. + +* Added ``ThrowSystemError`` function that formats a message and throws + ``SystemError`` containing the formatted message and system-specific error + description. For example, the following code + + .. code:: c++ + + FILE *f = fopen(filename, "r"); + if (!f) + ThrowSystemError(errno, "Failed to open file '{}'") << filename; + + will throw ``SystemError`` exception with description + "Failed to open file '': No such file or directory" if file + doesn't exist. + +* Support for AppVeyor continuous integration platform. + +* ``Format`` now throws ``SystemError`` in case of I/O errors. + +* Improve test infrastructure. Print functions are now tested by redirecting + the output to a pipe. + +0.8.0 - 2014-04-14 +------------------ + +* Initial release diff --git a/lib/cppformat/LICENSE.rst b/lib/cppformat/LICENSE.rst new file mode 100644 index 00000000..b1c96ca0 --- /dev/null +++ b/lib/cppformat/LICENSE.rst @@ -0,0 +1,23 @@ +Copyright (c) 2012 - 2015, Victor Zverovich + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/lib/cppformat/format.cc b/lib/cppformat/format.cc new file mode 100644 index 00000000..13474980 --- /dev/null +++ b/lib/cppformat/format.cc @@ -0,0 +1,1169 @@ +/* + Formatting library for C++ + + Copyright (c) 2012 - 2015, Victor Zverovich + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "format.h" + +#include + +#include +#include +#include +#include +#include + +#ifdef _WIN32 +# ifdef __MINGW32__ +# include +# endif +# include +#endif + +using fmt::internal::Arg; + +// Check if exceptions are disabled. +#if __GNUC__ && !__EXCEPTIONS +# define FMT_EXCEPTIONS 0 +#endif +#if _MSC_VER && !_HAS_EXCEPTIONS +# define FMT_EXCEPTIONS 0 +#endif +#ifndef FMT_EXCEPTIONS +# define FMT_EXCEPTIONS 1 +#endif + +#if FMT_EXCEPTIONS +# define FMT_TRY try +# define FMT_CATCH(x) catch (x) +#else +# define FMT_TRY if (true) +# define FMT_CATCH(x) if (false) +#endif + +#ifndef FMT_THROW +# if FMT_EXCEPTIONS +# define FMT_THROW(x) throw x +# define FMT_RETURN_AFTER_THROW(x) +# else +# define FMT_THROW(x) assert(false) +# define FMT_RETURN_AFTER_THROW(x) return x +# endif +#endif + +#ifdef FMT_HEADER_ONLY +# define FMT_FUNC inline +#else +# define FMT_FUNC +#endif + +#if _MSC_VER +# pragma warning(push) +# pragma warning(disable: 4127) // conditional expression is constant +# pragma warning(disable: 4702) // unreachable code +#endif + +namespace { + +#ifndef _MSC_VER +# define FMT_SNPRINTF snprintf +#else // _MSC_VER +inline int fmt_snprintf(char *buffer, size_t size, const char *format, ...) { + va_list args; + va_start(args, format); + int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args); + va_end(args); + return result; +} +# define FMT_SNPRINTF fmt_snprintf +#endif // _MSC_VER + +// Checks if a value fits in int - used to avoid warnings about comparing +// signed and unsigned integers. +template +struct IntChecker { + template + static bool fits_in_int(T value) { + unsigned max = INT_MAX; + return value <= max; + } +}; + +template <> +struct IntChecker { + template + static bool fits_in_int(T value) { + return value >= INT_MIN && value <= INT_MAX; + } +}; + +const char RESET_COLOR[] = "\x1b[0m"; + +typedef void (*FormatFunc)(fmt::Writer &, int, fmt::StringRef); + +// Portable thread-safe version of strerror. +// Sets buffer to point to a string describing the error code. +// This can be either a pointer to a string stored in buffer, +// or a pointer to some static immutable string. +// Returns one of the following values: +// 0 - success +// ERANGE - buffer is not large enough to store the error message +// other - failure +// Buffer should be at least of size 1. +int safe_strerror( + int error_code, char *&buffer, std::size_t buffer_size) FMT_NOEXCEPT { + assert(buffer != 0 && buffer_size != 0); + int result = 0; +#if ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE) || __ANDROID__ + // XSI-compliant version of strerror_r. + result = strerror_r(error_code, buffer, buffer_size); + if (result != 0) + result = errno; +#elif _GNU_SOURCE + // GNU-specific version of strerror_r. + char *message = strerror_r(error_code, buffer, buffer_size); + // If the buffer is full then the message is probably truncated. + if (message == buffer && strlen(buffer) == buffer_size - 1) + result = ERANGE; + buffer = message; +#elif __MINGW32__ + errno = 0; + (void)buffer_size; + buffer = strerror(error_code); + result = errno; +#elif _WIN32 + result = strerror_s(buffer, buffer_size, error_code); + // If the buffer is full then the message is probably truncated. + if (result == 0 && std::strlen(buffer) == buffer_size - 1) + result = ERANGE; +#else + result = strerror_r(error_code, buffer, buffer_size); + if (result == -1) + result = errno; // glibc versions before 2.13 return result in errno. +#endif + return result; +} + +void format_error_code(fmt::Writer &out, int error_code, + fmt::StringRef message) FMT_NOEXCEPT { + // Report error code making sure that the output fits into + // INLINE_BUFFER_SIZE to avoid dynamic memory allocation and potential + // bad_alloc. + out.clear(); + static const char SEP[] = ": "; + static const char ERR[] = "error "; + fmt::internal::IntTraits::MainType ec_value = error_code; + // Subtract 2 to account for terminating null characters in SEP and ERR. + std::size_t error_code_size = + sizeof(SEP) + sizeof(ERR) + fmt::internal::count_digits(ec_value) - 2; + if (message.size() <= fmt::internal::INLINE_BUFFER_SIZE - error_code_size) + out << message << SEP; + out << ERR << error_code; + assert(out.size() <= fmt::internal::INLINE_BUFFER_SIZE); +} + +void report_error(FormatFunc func, + int error_code, fmt::StringRef message) FMT_NOEXCEPT { + fmt::MemoryWriter full_message; + func(full_message, error_code, message); + // Use Writer::data instead of Writer::c_str to avoid potential memory + // allocation. + std::fwrite(full_message.data(), full_message.size(), 1, stderr); + std::fputc('\n', stderr); +} + +// IsZeroInt::visit(arg) returns true iff arg is a zero integer. +class IsZeroInt : public fmt::internal::ArgVisitor { + public: + template + bool visit_any_int(T value) { return value == 0; } +}; + +// Parses an unsigned integer advancing s to the end of the parsed input. +// This function assumes that the first character of s is a digit. +template +int parse_nonnegative_int(const Char *&s) { + assert('0' <= *s && *s <= '9'); + unsigned value = 0; + do { + unsigned new_value = value * 10 + (*s++ - '0'); + // Check if value wrapped around. + if (new_value < value) { + value = UINT_MAX; + break; + } + value = new_value; + } while ('0' <= *s && *s <= '9'); + if (value > INT_MAX) + FMT_THROW(fmt::FormatError("number is too big")); + return value; +} + +inline void require_numeric_argument(const Arg &arg, char spec) { + if (arg.type > Arg::LAST_NUMERIC_TYPE) { + std::string message = + fmt::format("format specifier '{}' requires numeric argument", spec); + FMT_THROW(fmt::FormatError(message)); + } +} + +template +void check_sign(const Char *&s, const Arg &arg) { + char sign = static_cast(*s); + require_numeric_argument(arg, sign); + if (arg.type == Arg::UINT || arg.type == Arg::ULONG_LONG) { + FMT_THROW(fmt::FormatError(fmt::format( + "format specifier '{}' requires signed argument", sign))); + } + ++s; +} + +// Checks if an argument is a valid printf width specifier and sets +// left alignment if it is negative. +class WidthHandler : public fmt::internal::ArgVisitor { + private: + fmt::FormatSpec &spec_; + + FMT_DISALLOW_COPY_AND_ASSIGN(WidthHandler); + + public: + explicit WidthHandler(fmt::FormatSpec &spec) : spec_(spec) {} + + unsigned visit_unhandled_arg() { + FMT_THROW(fmt::FormatError("width is not integer")); + FMT_RETURN_AFTER_THROW(0); + } + + template + unsigned visit_any_int(T value) { + typedef typename fmt::internal::IntTraits::MainType UnsignedType; + UnsignedType width = value; + if (fmt::internal::is_negative(value)) { + spec_.align_ = fmt::ALIGN_LEFT; + width = 0 - width; + } + if (width > INT_MAX) + FMT_THROW(fmt::FormatError("number is too big")); + return static_cast(width); + } +}; + +class PrecisionHandler : + public fmt::internal::ArgVisitor { + public: + unsigned visit_unhandled_arg() { + FMT_THROW(fmt::FormatError("precision is not integer")); + FMT_RETURN_AFTER_THROW(0); + } + + template + int visit_any_int(T value) { + if (!IntChecker::is_signed>::fits_in_int(value)) + FMT_THROW(fmt::FormatError("number is too big")); + return static_cast(value); + } +}; + +// Converts an integer argument to an integral type T for printf. +template +class ArgConverter : public fmt::internal::ArgVisitor, void> { + private: + fmt::internal::Arg &arg_; + wchar_t type_; + + FMT_DISALLOW_COPY_AND_ASSIGN(ArgConverter); + + public: + ArgConverter(fmt::internal::Arg &arg, wchar_t type) + : arg_(arg), type_(type) {} + + template + void visit_any_int(U value) { + bool is_signed = type_ == 'd' || type_ == 'i'; + using fmt::internal::Arg; + if (sizeof(T) <= sizeof(int)) { + // Extra casts are used to silence warnings. + if (is_signed) { + arg_.type = Arg::INT; + arg_.int_value = static_cast(static_cast(value)); + } else { + arg_.type = Arg::UINT; + arg_.uint_value = static_cast( + static_cast::Type>(value)); + } + } else { + if (is_signed) { + arg_.type = Arg::LONG_LONG; + arg_.long_long_value = + static_cast::Type>(value); + } else { + arg_.type = Arg::ULONG_LONG; + arg_.ulong_long_value = + static_cast::Type>(value); + } + } + } +}; + +// Converts an integer argument to char for printf. +class CharConverter : public fmt::internal::ArgVisitor { + private: + fmt::internal::Arg &arg_; + + FMT_DISALLOW_COPY_AND_ASSIGN(CharConverter); + + public: + explicit CharConverter(fmt::internal::Arg &arg) : arg_(arg) {} + + template + void visit_any_int(T value) { + arg_.type = Arg::CHAR; + arg_.int_value = static_cast(value); + } +}; + +// This function template is used to prevent compile errors when handling +// incompatible string arguments, e.g. handling a wide string in a narrow +// string formatter. +template +Arg::StringValue ignore_incompatible_str(Arg::StringValue); + +template <> +inline Arg::StringValue ignore_incompatible_str( + Arg::StringValue) { return Arg::StringValue(); } + +template <> +inline Arg::StringValue ignore_incompatible_str( + Arg::StringValue s) { return s; } +} // namespace + +FMT_FUNC void fmt::SystemError::init( + int err_code, StringRef format_str, ArgList args) { + error_code_ = err_code; + MemoryWriter w; + internal::format_system_error(w, err_code, format(format_str, args)); + std::runtime_error &base = *this; + base = std::runtime_error(w.str()); +} + +template +int fmt::internal::CharTraits::format_float( + char *buffer, std::size_t size, const char *format, + unsigned width, int precision, T value) { + if (width == 0) { + return precision < 0 ? + FMT_SNPRINTF(buffer, size, format, value) : + FMT_SNPRINTF(buffer, size, format, precision, value); + } + return precision < 0 ? + FMT_SNPRINTF(buffer, size, format, width, value) : + FMT_SNPRINTF(buffer, size, format, width, precision, value); +} + +template +int fmt::internal::CharTraits::format_float( + wchar_t *buffer, std::size_t size, const wchar_t *format, + unsigned width, int precision, T value) { + if (width == 0) { + return precision < 0 ? + swprintf(buffer, size, format, value) : + swprintf(buffer, size, format, precision, value); + } + return precision < 0 ? + swprintf(buffer, size, format, width, value) : + swprintf(buffer, size, format, width, precision, value); +} + +template +const char fmt::internal::BasicData::DIGITS[] = + "0001020304050607080910111213141516171819" + "2021222324252627282930313233343536373839" + "4041424344454647484950515253545556575859" + "6061626364656667686970717273747576777879" + "8081828384858687888990919293949596979899"; + +#define FMT_POWERS_OF_10(factor) \ + factor * 10, \ + factor * 100, \ + factor * 1000, \ + factor * 10000, \ + factor * 100000, \ + factor * 1000000, \ + factor * 10000000, \ + factor * 100000000, \ + factor * 1000000000 + +template +const uint32_t fmt::internal::BasicData::POWERS_OF_10_32[] = { + 0, FMT_POWERS_OF_10(1) +}; + +template +const uint64_t fmt::internal::BasicData::POWERS_OF_10_64[] = { + 0, + FMT_POWERS_OF_10(1), + FMT_POWERS_OF_10(fmt::ULongLong(1000000000)), + // Multiply several constants instead of using a single long long constant + // to avoid warnings about C++98 not supporting long long. + fmt::ULongLong(1000000000) * fmt::ULongLong(1000000000) * 10 +}; + +FMT_FUNC void fmt::internal::report_unknown_type(char code, const char *type) { + if (std::isprint(static_cast(code))) { + FMT_THROW(fmt::FormatError( + fmt::format("unknown format code '{}' for {}", code, type))); + } + FMT_THROW(fmt::FormatError( + fmt::format("unknown format code '\\x{:02x}' for {}", + static_cast(code), type))); +} + +#ifdef _WIN32 + +FMT_FUNC fmt::internal::UTF8ToUTF16::UTF8ToUTF16(fmt::StringRef s) { + int length = MultiByteToWideChar( + CP_UTF8, MB_ERR_INVALID_CHARS, s.c_str(), -1, 0, 0); + static const char ERROR_MSG[] = "cannot convert string from UTF-8 to UTF-16"; + if (length == 0) + FMT_THROW(WindowsError(GetLastError(), ERROR_MSG)); + buffer_.resize(length); + length = MultiByteToWideChar( + CP_UTF8, MB_ERR_INVALID_CHARS, s.c_str(), -1, &buffer_[0], length); + if (length == 0) + FMT_THROW(WindowsError(GetLastError(), ERROR_MSG)); +} + +FMT_FUNC fmt::internal::UTF16ToUTF8::UTF16ToUTF8(fmt::WStringRef s) { + if (int error_code = convert(s)) { + FMT_THROW(WindowsError(error_code, + "cannot convert string from UTF-16 to UTF-8")); + } +} + +FMT_FUNC int fmt::internal::UTF16ToUTF8::convert(fmt::WStringRef s) { + int length = WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, 0, 0, 0, 0); + if (length == 0) + return GetLastError(); + buffer_.resize(length); + length = WideCharToMultiByte( + CP_UTF8, 0, s.c_str(), -1, &buffer_[0], length, 0, 0); + if (length == 0) + return GetLastError(); + return 0; +} + +FMT_FUNC void fmt::WindowsError::init( + int err_code, StringRef format_str, ArgList args) { + error_code_ = err_code; + MemoryWriter w; + internal::format_windows_error(w, err_code, format(format_str, args)); + std::runtime_error &base = *this; + base = std::runtime_error(w.str()); +} + +#endif + +FMT_FUNC void fmt::internal::format_system_error( + fmt::Writer &out, int error_code, + fmt::StringRef message) FMT_NOEXCEPT { + FMT_TRY { + MemoryBuffer buffer; + buffer.resize(INLINE_BUFFER_SIZE); + for (;;) { + char *system_message = &buffer[0]; + int result = safe_strerror(error_code, system_message, buffer.size()); + if (result == 0) { + out << message << ": " << system_message; + return; + } + if (result != ERANGE) + break; // Can't get error message, report error code instead. + buffer.resize(buffer.size() * 2); + } + } FMT_CATCH(...) {} + format_error_code(out, error_code, message); +} + +#ifdef _WIN32 +FMT_FUNC void fmt::internal::format_windows_error( + fmt::Writer &out, int error_code, + fmt::StringRef message) FMT_NOEXCEPT { + class String { + private: + LPWSTR str_; + + public: + String() : str_() {} + ~String() { LocalFree(str_); } + LPWSTR *ptr() { return &str_; } + LPCWSTR c_str() const { return str_; } + }; + FMT_TRY { + String system_message; + if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, + error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + reinterpret_cast(system_message.ptr()), 0, 0)) { + UTF16ToUTF8 utf8_message; + if (utf8_message.convert(system_message.c_str()) == ERROR_SUCCESS) { + out << message << ": " << utf8_message; + return; + } + } + } FMT_CATCH(...) {} + format_error_code(out, error_code, message); +} +#endif + +// An argument formatter. +template +class fmt::internal::ArgFormatter : + public fmt::internal::ArgVisitor, void> { + private: + fmt::BasicFormatter &formatter_; + fmt::BasicWriter &writer_; + fmt::FormatSpec &spec_; + const Char *format_; + + FMT_DISALLOW_COPY_AND_ASSIGN(ArgFormatter); + + public: + ArgFormatter( + fmt::BasicFormatter &f,fmt::FormatSpec &s, const Char *fmt) + : formatter_(f), writer_(f.writer()), spec_(s), format_(fmt) {} + + template + void visit_any_int(T value) { writer_.write_int(value, spec_); } + + template + void visit_any_double(T value) { writer_.write_double(value, spec_); } + + void visit_char(int value) { + if (spec_.type_ && spec_.type_ != 'c') { + spec_.flags_ |= CHAR_FLAG; + writer_.write_int(value, spec_); + return; + } + if (spec_.align_ == ALIGN_NUMERIC || spec_.flags_ != 0) + FMT_THROW(FormatError("invalid format specifier for char")); + typedef typename fmt::BasicWriter::CharPtr CharPtr; + Char fill = static_cast(spec_.fill()); + if (spec_.precision_ == 0) { + std::fill_n(writer_.grow_buffer(spec_.width_), spec_.width_, fill); + return; + } + CharPtr out = CharPtr(); + if (spec_.width_ > 1) { + out = writer_.grow_buffer(spec_.width_); + if (spec_.align_ == fmt::ALIGN_RIGHT) { + std::fill_n(out, spec_.width_ - 1, fill); + out += spec_.width_ - 1; + } else if (spec_.align_ == fmt::ALIGN_CENTER) { + out = writer_.fill_padding(out, spec_.width_, 1, fill); + } else { + std::fill_n(out + 1, spec_.width_ - 1, fill); + } + } else { + out = writer_.grow_buffer(1); + } + *out = static_cast(value); + } + + void visit_string(Arg::StringValue value) { + writer_.write_str(value, spec_); + } + void visit_wstring(Arg::StringValue value) { + writer_.write_str(ignore_incompatible_str(value), spec_); + } + + void visit_pointer(const void *value) { + if (spec_.type_ && spec_.type_ != 'p') + fmt::internal::report_unknown_type(spec_.type_, "pointer"); + spec_.flags_ = fmt::HASH_FLAG; + spec_.type_ = 'x'; + writer_.write_int(reinterpret_cast(value), spec_); + } + + void visit_custom(Arg::CustomValue c) { + c.format(&formatter_, c.value, &format_); + } +}; + +template +void fmt::internal::FixedBuffer::grow(std::size_t) { + FMT_THROW(std::runtime_error("buffer overflow")); +} + +template +template +void fmt::BasicWriter::write_str( + const Arg::StringValue &s, const FormatSpec &spec) { + // Check if StrChar is convertible to Char. + internal::CharTraits::convert(StrChar()); + if (spec.type_ && spec.type_ != 's') + internal::report_unknown_type(spec.type_, "string"); + const StrChar *str_value = s.value; + std::size_t str_size = s.size; + if (str_size == 0) { + if (!str_value) + FMT_THROW(FormatError("string pointer is null")); + if (*str_value) + str_size = std::char_traits::length(str_value); + } + std::size_t precision = spec.precision_; + if (spec.precision_ >= 0 && precision < str_size) + str_size = spec.precision_; + write_str(str_value, str_size, spec); +} + +template +inline Arg fmt::BasicFormatter::parse_arg_index(const Char *&s) { + const char *error = 0; + Arg arg = *s < '0' || *s > '9' ? + next_arg(error) : get_arg(parse_nonnegative_int(s), error); + if (error) { + FMT_THROW(FormatError( + *s != '}' && *s != ':' ? "invalid format string" : error)); + } + return arg; +} + +FMT_FUNC Arg fmt::internal::FormatterBase::do_get_arg( + unsigned arg_index, const char *&error) { + Arg arg = args_[arg_index]; + if (arg.type == Arg::NONE) + error = "argument index out of range"; + return arg; +} + +inline Arg fmt::internal::FormatterBase::next_arg(const char *&error) { + if (next_arg_index_ >= 0) + return do_get_arg(next_arg_index_++, error); + error = "cannot switch from manual to automatic argument indexing"; + return Arg(); +} + +inline Arg fmt::internal::FormatterBase::get_arg( + unsigned arg_index, const char *&error) { + if (next_arg_index_ <= 0) { + next_arg_index_ = -1; + return do_get_arg(arg_index, error); + } + error = "cannot switch from automatic to manual argument indexing"; + return Arg(); +} + +template +void fmt::internal::PrintfFormatter::parse_flags( + FormatSpec &spec, const Char *&s) { + for (;;) { + switch (*s++) { + case '-': + spec.align_ = ALIGN_LEFT; + break; + case '+': + spec.flags_ |= SIGN_FLAG | PLUS_FLAG; + break; + case '0': + spec.fill_ = '0'; + break; + case ' ': + spec.flags_ |= SIGN_FLAG; + break; + case '#': + spec.flags_ |= HASH_FLAG; + break; + default: + --s; + return; + } + } +} + +template +Arg fmt::internal::PrintfFormatter::get_arg( + const Char *s, unsigned arg_index) { + const char *error = 0; + Arg arg = arg_index == UINT_MAX ? + next_arg(error) : FormatterBase::get_arg(arg_index - 1, error); + if (error) + FMT_THROW(FormatError(!*s ? "invalid format string" : error)); + return arg; +} + +template +unsigned fmt::internal::PrintfFormatter::parse_header( + const Char *&s, FormatSpec &spec) { + unsigned arg_index = UINT_MAX; + Char c = *s; + if (c >= '0' && c <= '9') { + // Parse an argument index (if followed by '$') or a width possibly + // preceded with '0' flag(s). + unsigned value = parse_nonnegative_int(s); + if (*s == '$') { // value is an argument index + ++s; + arg_index = value; + } else { + if (c == '0') + spec.fill_ = '0'; + if (value != 0) { + // Nonzero value means that we parsed width and don't need to + // parse it or flags again, so return now. + spec.width_ = value; + return arg_index; + } + } + } + parse_flags(spec, s); + // Parse width. + if (*s >= '0' && *s <= '9') { + spec.width_ = parse_nonnegative_int(s); + } else if (*s == '*') { + ++s; + spec.width_ = WidthHandler(spec).visit(get_arg(s)); + } + return arg_index; +} + +template +void fmt::internal::PrintfFormatter::format( + BasicWriter &writer, BasicStringRef format_str, + const ArgList &args) { + const Char *start = format_str.c_str(); + set_args(args); + const Char *s = start; + while (*s) { + Char c = *s++; + if (c != '%') continue; + if (*s == c) { + write(writer, start, s); + start = ++s; + continue; + } + write(writer, start, s - 1); + + FormatSpec spec; + spec.align_ = ALIGN_RIGHT; + + // Parse argument index, flags and width. + unsigned arg_index = parse_header(s, spec); + + // Parse precision. + if (*s == '.') { + ++s; + if ('0' <= *s && *s <= '9') { + spec.precision_ = parse_nonnegative_int(s); + } else if (*s == '*') { + ++s; + spec.precision_ = PrecisionHandler().visit(get_arg(s)); + } + } + + Arg arg = get_arg(s, arg_index); + if (spec.flag(HASH_FLAG) && IsZeroInt().visit(arg)) + spec.flags_ &= ~HASH_FLAG; + if (spec.fill_ == '0') { + if (arg.type <= Arg::LAST_NUMERIC_TYPE) + spec.align_ = ALIGN_NUMERIC; + else + spec.fill_ = ' '; // Ignore '0' flag for non-numeric types. + } + + // Parse length and convert the argument to the required type. + switch (*s++) { + case 'h': + if (*s == 'h') + ArgConverter(arg, *++s).visit(arg); + else + ArgConverter(arg, *s).visit(arg); + break; + case 'l': + if (*s == 'l') + ArgConverter(arg, *++s).visit(arg); + else + ArgConverter(arg, *s).visit(arg); + break; + case 'j': + ArgConverter(arg, *s).visit(arg); + break; + case 'z': + ArgConverter(arg, *s).visit(arg); + break; + case 't': + ArgConverter(arg, *s).visit(arg); + break; + case 'L': + // printf produces garbage when 'L' is omitted for long double, no + // need to do the same. + break; + default: + --s; + ArgConverter(arg, *s).visit(arg); + } + + // Parse type. + if (!*s) + FMT_THROW(FormatError("invalid format string")); + spec.type_ = static_cast(*s++); + if (arg.type <= Arg::LAST_INTEGER_TYPE) { + // Normalize type. + switch (spec.type_) { + case 'i': case 'u': + spec.type_ = 'd'; + break; + case 'c': + // TODO: handle wchar_t + CharConverter(arg).visit(arg); + break; + } + } + + start = s; + + // Format argument. + switch (arg.type) { + case Arg::INT: + writer.write_int(arg.int_value, spec); + break; + case Arg::UINT: + writer.write_int(arg.uint_value, spec); + break; + case Arg::LONG_LONG: + writer.write_int(arg.long_long_value, spec); + break; + case Arg::ULONG_LONG: + writer.write_int(arg.ulong_long_value, spec); + break; + case Arg::CHAR: { + if (spec.type_ && spec.type_ != 'c') + writer.write_int(arg.int_value, spec); + typedef typename BasicWriter::CharPtr CharPtr; + CharPtr out = CharPtr(); + if (spec.width_ > 1) { + Char fill = ' '; + out = writer.grow_buffer(spec.width_); + if (spec.align_ != ALIGN_LEFT) { + std::fill_n(out, spec.width_ - 1, fill); + out += spec.width_ - 1; + } else { + std::fill_n(out + 1, spec.width_ - 1, fill); + } + } else { + out = writer.grow_buffer(1); + } + *out = static_cast(arg.int_value); + break; + } + case Arg::DOUBLE: + writer.write_double(arg.double_value, spec); + break; + case Arg::LONG_DOUBLE: + writer.write_double(arg.long_double_value, spec); + break; + case Arg::CSTRING: + arg.string.size = 0; + writer.write_str(arg.string, spec); + break; + case Arg::STRING: + writer.write_str(arg.string, spec); + break; + case Arg::WSTRING: + writer.write_str(ignore_incompatible_str(arg.wstring), spec); + break; + case Arg::POINTER: + if (spec.type_ && spec.type_ != 'p') + internal::report_unknown_type(spec.type_, "pointer"); + spec.flags_= HASH_FLAG; + spec.type_ = 'x'; + writer.write_int(reinterpret_cast(arg.pointer), spec); + break; + case Arg::CUSTOM: { + if (spec.type_) + internal::report_unknown_type(spec.type_, "object"); + const void *str_format = "s"; + arg.custom.format(&writer, arg.custom.value, &str_format); + break; + } + default: + assert(false); + break; + } + } + write(writer, start, s); +} + +template +const Char *fmt::BasicFormatter::format( + const Char *&format_str, const Arg &arg) { + const Char *s = format_str; + FormatSpec spec; + if (*s == ':') { + if (arg.type == Arg::CUSTOM) { + arg.custom.format(this, arg.custom.value, &s); + return s; + } + ++s; + // Parse fill and alignment. + if (Char c = *s) { + const Char *p = s + 1; + spec.align_ = ALIGN_DEFAULT; + do { + switch (*p) { + case '<': + spec.align_ = ALIGN_LEFT; + break; + case '>': + spec.align_ = ALIGN_RIGHT; + break; + case '=': + spec.align_ = ALIGN_NUMERIC; + break; + case '^': + spec.align_ = ALIGN_CENTER; + break; + } + if (spec.align_ != ALIGN_DEFAULT) { + if (p != s) { + if (c == '}') break; + if (c == '{') + FMT_THROW(FormatError("invalid fill character '{'")); + s += 2; + spec.fill_ = c; + } else ++s; + if (spec.align_ == ALIGN_NUMERIC) + require_numeric_argument(arg, '='); + break; + } + } while (--p >= s); + } + + // Parse sign. + switch (*s) { + case '+': + check_sign(s, arg); + spec.flags_ |= SIGN_FLAG | PLUS_FLAG; + break; + case '-': + check_sign(s, arg); + spec.flags_ |= MINUS_FLAG; + break; + case ' ': + check_sign(s, arg); + spec.flags_ |= SIGN_FLAG; + break; + } + + if (*s == '#') { + require_numeric_argument(arg, '#'); + spec.flags_ |= HASH_FLAG; + ++s; + } + + // Parse width and zero flag. + if ('0' <= *s && *s <= '9') { + if (*s == '0') { + require_numeric_argument(arg, '0'); + spec.align_ = ALIGN_NUMERIC; + spec.fill_ = '0'; + } + // Zero may be parsed again as a part of the width, but it is simpler + // and more efficient than checking if the next char is a digit. + spec.width_ = parse_nonnegative_int(s); + } + + // Parse precision. + if (*s == '.') { + ++s; + spec.precision_ = 0; + if ('0' <= *s && *s <= '9') { + spec.precision_ = parse_nonnegative_int(s); + } else if (*s == '{') { + ++s; + const Arg &precision_arg = parse_arg_index(s); + if (*s++ != '}') + FMT_THROW(FormatError("invalid format string")); + ULongLong value = 0; + switch (precision_arg.type) { + case Arg::INT: + if (precision_arg.int_value < 0) + FMT_THROW(FormatError("negative precision")); + value = precision_arg.int_value; + break; + case Arg::UINT: + value = precision_arg.uint_value; + break; + case Arg::LONG_LONG: + if (precision_arg.long_long_value < 0) + FMT_THROW(FormatError("negative precision")); + value = precision_arg.long_long_value; + break; + case Arg::ULONG_LONG: + value = precision_arg.ulong_long_value; + break; + default: + FMT_THROW(FormatError("precision is not integer")); + } + if (value > INT_MAX) + FMT_THROW(FormatError("number is too big")); + spec.precision_ = static_cast(value); + } else { + FMT_THROW(FormatError("missing precision specifier")); + } + if (arg.type < Arg::LAST_INTEGER_TYPE || arg.type == Arg::POINTER) { + FMT_THROW(FormatError( + fmt::format("precision not allowed in {} format specifier", + arg.type == Arg::POINTER ? "pointer" : "integer"))); + } + } + + // Parse type. + if (*s != '}' && *s) + spec.type_ = static_cast(*s++); + } + + if (*s++ != '}') + FMT_THROW(FormatError("missing '}' in format string")); + start_ = s; + + // Format argument. + internal::ArgFormatter(*this, spec, s - 1).visit(arg); + return s; +} + +template +void fmt::BasicFormatter::format( + BasicStringRef format_str, const ArgList &args) { + const Char *s = start_ = format_str.c_str(); + set_args(args); + while (*s) { + Char c = *s++; + if (c != '{' && c != '}') continue; + if (*s == c) { + write(writer_, start_, s); + start_ = ++s; + continue; + } + if (c == '}') + FMT_THROW(FormatError("unmatched '}' in format string")); + write(writer_, start_, s - 1); + Arg arg = parse_arg_index(s); + s = format(s, arg); + } + write(writer_, start_, s); +} + +FMT_FUNC void fmt::report_system_error( + int error_code, fmt::StringRef message) FMT_NOEXCEPT { + report_error(internal::format_system_error, error_code, message); +} + +#ifdef _WIN32 +FMT_FUNC void fmt::report_windows_error( + int error_code, fmt::StringRef message) FMT_NOEXCEPT { + report_error(internal::format_windows_error, error_code, message); +} +#endif + +FMT_FUNC void fmt::print(std::FILE *f, StringRef format_str, ArgList args) { + MemoryWriter w; + w.write(format_str, args); + std::fwrite(w.data(), 1, w.size(), f); +} + +FMT_FUNC void fmt::print(StringRef format_str, ArgList args) { + print(stdout, format_str, args); +} + +FMT_FUNC void fmt::print(std::ostream &os, StringRef format_str, ArgList args) { + MemoryWriter w; + w.write(format_str, args); + os.write(w.data(), w.size()); +} + +FMT_FUNC void fmt::print_colored(Color c, StringRef format, ArgList args) { + char escape[] = "\x1b[30m"; + escape[3] = '0' + static_cast(c); + std::fputs(escape, stdout); + print(format, args); + std::fputs(RESET_COLOR, stdout); +} + +FMT_FUNC int fmt::fprintf(std::FILE *f, StringRef format, ArgList args) { + MemoryWriter w; + printf(w, format, args); + std::size_t size = w.size(); + return std::fwrite(w.data(), 1, size, f) < size ? -1 : static_cast(size); +} + +#ifndef FMT_HEADER_ONLY + +// Explicit instantiations for char. + +template void fmt::internal::FixedBuffer::grow(std::size_t); + +template const char *fmt::BasicFormatter::format( + const char *&format_str, const fmt::internal::Arg &arg); + +template void fmt::BasicFormatter::format( + BasicStringRef format, const ArgList &args); + +template void fmt::internal::PrintfFormatter::format( + BasicWriter &writer, BasicStringRef format, const ArgList &args); + +template int fmt::internal::CharTraits::format_float( + char *buffer, std::size_t size, const char *format, + unsigned width, int precision, double value); + +template int fmt::internal::CharTraits::format_float( + char *buffer, std::size_t size, const char *format, + unsigned width, int precision, long double value); + +// Explicit instantiations for wchar_t. + +template void fmt::internal::FixedBuffer::grow(std::size_t); + +template const wchar_t *fmt::BasicFormatter::format( + const wchar_t *&format_str, const fmt::internal::Arg &arg); + +template void fmt::BasicFormatter::format( + BasicStringRef format, const ArgList &args); + +template void fmt::internal::PrintfFormatter::format( + BasicWriter &writer, BasicStringRef format, + const ArgList &args); + +template int fmt::internal::CharTraits::format_float( + wchar_t *buffer, std::size_t size, const wchar_t *format, + unsigned width, int precision, double value); + +template int fmt::internal::CharTraits::format_float( + wchar_t *buffer, std::size_t size, const wchar_t *format, + unsigned width, int precision, long double value); + +#endif // FMT_HEADER_ONLY + +#if _MSC_VER +# pragma warning(pop) +#endif diff --git a/lib/cppformat/format.h b/lib/cppformat/format.h new file mode 100644 index 00000000..9c6bc906 --- /dev/null +++ b/lib/cppformat/format.h @@ -0,0 +1,2649 @@ +/* + Formatting library for C++ + + Copyright (c) 2012 - 2015, Victor Zverovich + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef FMT_FORMAT_H_ +#define FMT_FORMAT_H_ + +#include + +#include +#include +#include // for std::ptrdiff_t +#include +#include +#include +#include +#include +#include + +#if _SECURE_SCL +# include +#endif + +#ifdef _MSC_VER +# include // _BitScanReverse, _BitScanReverse64 + +namespace fmt { +namespace internal { +# pragma intrinsic(_BitScanReverse) +inline uint32_t clz(uint32_t x) { + unsigned long r = 0; + _BitScanReverse(&r, x); + return 31 - r; +} +# define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n) + +# ifdef _WIN64 +# pragma intrinsic(_BitScanReverse64) +# endif + +inline uint32_t clzll(uint64_t x) { + unsigned long r = 0; +# ifdef _WIN64 + _BitScanReverse64(&r, x); +# else + // Scan the high 32 bits. + if (_BitScanReverse(&r, static_cast(x >> 32))) + return 63 - (r + 32); + + // Scan the low 32 bits. + _BitScanReverse(&r, static_cast(x)); +# endif + return 63 - r; +} +# define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n) +} +} +#endif + +#ifdef __GNUC__ +# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +# define FMT_GCC_EXTENSION __extension__ +# if FMT_GCC_VERSION >= 406 +# pragma GCC diagnostic push +// Disable the warning about "long long" which is sometimes reported even +// when using __extension__. +# pragma GCC diagnostic ignored "-Wlong-long" +// Disable the warning about declaration shadowing because it affects too +// many valid cases. +# pragma GCC diagnostic ignored "-Wshadow" +# endif +# if __cplusplus >= 201103L || defined __GXX_EXPERIMENTAL_CXX0X__ +# define FMT_HAS_GXX_CXX11 1 +# endif +#else +# define FMT_GCC_EXTENSION +#endif + +#ifdef __clang__ +# pragma clang diagnostic ignored "-Wdocumentation" +#endif + +#ifdef __GNUC_LIBSTD__ +# define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__) +#endif + +#ifdef __has_feature +# define FMT_HAS_FEATURE(x) __has_feature(x) +#else +# define FMT_HAS_FEATURE(x) 0 +#endif + +#ifdef __has_builtin +# define FMT_HAS_BUILTIN(x) __has_builtin(x) +#else +# define FMT_HAS_BUILTIN(x) 0 +#endif + +#ifdef __has_cpp_attribute +# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +# define FMT_HAS_CPP_ATTRIBUTE(x) 0 +#endif + +#ifndef FMT_USE_VARIADIC_TEMPLATES +// Variadic templates are available in GCC since version 4.4 +// (http://gcc.gnu.org/projects/cxx0x.html) and in Visual C++ +// since version 2013. +# define FMT_USE_VARIADIC_TEMPLATES \ + (FMT_HAS_FEATURE(cxx_variadic_templates) || \ + (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1800) +#endif + +#ifndef FMT_USE_RVALUE_REFERENCES +// Don't use rvalue references when compiling with clang and an old libstdc++ +// as the latter doesn't provide std::move. +# if defined(FMT_GNUC_LIBSTD_VERSION) && FMT_GNUC_LIBSTD_VERSION <= 402 +# define FMT_USE_RVALUE_REFERENCES 0 +# else +# define FMT_USE_RVALUE_REFERENCES \ + (FMT_HAS_FEATURE(cxx_rvalue_references) || \ + (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1600) +# endif +#endif + +#if FMT_USE_RVALUE_REFERENCES +# include // for std::move +#endif + +// Define FMT_USE_NOEXCEPT to make C++ Format use noexcept (C++11 feature). +#if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \ + (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) +# define FMT_NOEXCEPT noexcept +#else +# define FMT_NOEXCEPT throw() +#endif + +// A macro to disallow the copy constructor and operator= functions +// This should be used in the private: declarations for a class +#if FMT_USE_DELETED_FUNCTIONS || FMT_HAS_FEATURE(cxx_deleted_functions) || \ + (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1800 +# define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName&) = delete; \ + TypeName& operator=(const TypeName&) = delete +#else +# define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName&); \ + TypeName& operator=(const TypeName&) +#endif + +namespace fmt { + +// Fix the warning about long long on older versions of GCC +// that don't support the diagnostic pragma. +FMT_GCC_EXTENSION typedef long long LongLong; +FMT_GCC_EXTENSION typedef unsigned long long ULongLong; + +#if FMT_USE_RVALUE_REFERENCES +using std::move; +#endif + +template +class BasicWriter; + +typedef BasicWriter Writer; +typedef BasicWriter WWriter; + +template +class BasicFormatter; + +template +void format(BasicFormatter &f, const Char *&format_str, const T &value); + +/** + \rst + A string reference. It can be constructed from a C string or + ``std::string``. + + You can use one of the following typedefs for common character types: + + +------------+-------------------------+ + | Type | Definition | + +============+=========================+ + | StringRef | BasicStringRef | + +------------+-------------------------+ + | WStringRef | BasicStringRef | + +------------+-------------------------+ + + This class is most useful as a parameter type to allow passing + different types of strings to a function, for example:: + + template + std::string format(StringRef format_str, const Args & ... args); + + format("{}", 42); + format(std::string("{}"), 42); + \endrst + */ +template +class BasicStringRef { + private: + const Char *data_; + std::size_t size_; + + public: + /** + Constructs a string reference object from a C string and a size. + */ + BasicStringRef(const Char *s, std::size_t size) : data_(s), size_(size) {} + + /** + Constructs a string reference object from a C string computing + the size with ``std::char_traits::length``. + */ + BasicStringRef(const Char *s) + : data_(s), size_(std::char_traits::length(s)) {} + + /** + Constructs a string reference from an `std::string` object. + */ + BasicStringRef(const std::basic_string &s) + : data_(s.c_str()), size_(s.size()) {} + + /** + Converts a string reference to an `std::string` object. + */ + operator std::basic_string() const { + return std::basic_string(data_, size()); + } + + /** + Returns the pointer to a C string. + */ + const Char *c_str() const { return data_; } + + /** + Returns the string size. + */ + std::size_t size() const { return size_; } + + friend bool operator==(BasicStringRef lhs, BasicStringRef rhs) { + return lhs.data_ == rhs.data_; + } + friend bool operator!=(BasicStringRef lhs, BasicStringRef rhs) { + return lhs.data_ != rhs.data_; + } +}; + +typedef BasicStringRef StringRef; +typedef BasicStringRef WStringRef; + +/** + A formatting error such as invalid format string. +*/ +class FormatError : public std::runtime_error { + public: + explicit FormatError(StringRef message) + : std::runtime_error(message.c_str()) {} +}; + +namespace internal { + +// The number of characters to store in the MemoryBuffer object itself +// to avoid dynamic memory allocation. +enum { INLINE_BUFFER_SIZE = 500 }; + +#if _SECURE_SCL +// Use checked iterator to avoid warnings on MSVC. +template +inline stdext::checked_array_iterator make_ptr(T *ptr, std::size_t size) { + return stdext::checked_array_iterator(ptr, size); +} +#else +template +inline T *make_ptr(T *ptr, std::size_t) { return ptr; } +#endif + +// A buffer for POD types. It supports a subset of std::vector's operations. +template +class Buffer { + private: + FMT_DISALLOW_COPY_AND_ASSIGN(Buffer); + + protected: + T *ptr_; + std::size_t size_; + std::size_t capacity_; + + Buffer(T *ptr = 0, std::size_t capacity = 0) + : ptr_(ptr), size_(0), capacity_(capacity) {} + + virtual void grow(std::size_t size) = 0; + + public: + virtual ~Buffer() {} + + // Returns the size of this buffer. + std::size_t size() const { return size_; } + + // Returns the capacity of this buffer. + std::size_t capacity() const { return capacity_; } + + // Resizes the buffer. If T is a POD type new elements are not initialized. + void resize(std::size_t new_size) { + if (new_size > capacity_) + grow(new_size); + size_ = new_size; + } + + // Reserves space to store at least capacity elements. + void reserve(std::size_t capacity) { + if (capacity > capacity_) + grow(capacity); + } + + void clear() FMT_NOEXCEPT { size_ = 0; } + + void push_back(const T &value) { + if (size_ == capacity_) + grow(size_ + 1); + ptr_[size_++] = value; + } + + // Appends data to the end of the buffer. + void append(const T *begin, const T *end); + + T &operator[](std::size_t index) { return ptr_[index]; } + const T &operator[](std::size_t index) const { return ptr_[index]; } +}; + +template +void Buffer::append(const T *begin, const T *end) { + std::ptrdiff_t num_elements = end - begin; + if (size_ + num_elements > capacity_) + grow(size_ + num_elements); + std::copy(begin, end, make_ptr(ptr_, capacity_) + size_); + size_ += num_elements; +} + +// A memory buffer for POD types with the first SIZE elements stored in +// the object itself. +template > +class MemoryBuffer : private Allocator, public Buffer { + private: + T data_[SIZE]; + + // Free memory allocated by the buffer. + void free() { + if (this->ptr_ != data_) this->deallocate(this->ptr_, this->capacity_); + } + + protected: + void grow(std::size_t size); + + public: + explicit MemoryBuffer(const Allocator &alloc = Allocator()) + : Allocator(alloc), Buffer(data_, SIZE) {} + ~MemoryBuffer() { free(); } + +#if FMT_USE_RVALUE_REFERENCES + private: + // Move data from other to this buffer. + void move(MemoryBuffer &other) { + Allocator &this_alloc = *this, &other_alloc = other; + this_alloc = std::move(other_alloc); + this->size_ = other.size_; + this->capacity_ = other.capacity_; + if (other.ptr_ == other.data_) { + this->ptr_ = data_; + std::copy(other.data_, + other.data_ + this->size_, make_ptr(data_, this->capacity_)); + } else { + this->ptr_ = other.ptr_; + // Set pointer to the inline array so that delete is not called + // when freeing. + other.ptr_ = other.data_; + } + } + + public: + MemoryBuffer(MemoryBuffer &&other) { + move(other); + } + + MemoryBuffer &operator=(MemoryBuffer &&other) { + assert(this != &other); + free(); + move(other); + return *this; + } +#endif + + // Returns a copy of the allocator associated with this buffer. + Allocator get_allocator() const { return *this; } +}; + +template +void MemoryBuffer::grow(std::size_t size) { + std::size_t new_capacity = + (std::max)(size, this->capacity_ + this->capacity_ / 2); + T *new_ptr = this->allocate(new_capacity); + // The following code doesn't throw, so the raw pointer above doesn't leak. + std::copy(this->ptr_, + this->ptr_ + this->size_, make_ptr(new_ptr, new_capacity)); + std::size_t old_capacity = this->capacity_; + T *old_ptr = this->ptr_; + this->capacity_ = new_capacity; + this->ptr_ = new_ptr; + // deallocate may throw (at least in principle), but it doesn't matter since + // the buffer already uses the new storage and will deallocate it in case + // of exception. + if (old_ptr != data_) + this->deallocate(old_ptr, old_capacity); +} + +// A fixed-size buffer. +template +class FixedBuffer : public fmt::internal::Buffer { + public: + FixedBuffer(Char *array, std::size_t size) + : fmt::internal::Buffer(array, size) {} + + protected: + void grow(std::size_t size); +}; + +#ifndef _MSC_VER +// Portable version of signbit. +inline int getsign(double x) { + // When compiled in C++11 mode signbit is no longer a macro but a function + // defined in namespace std and the macro is undefined. +# ifdef signbit + return signbit(x); +# else + return std::signbit(x); +# endif +} + +// Portable version of isinf. +# ifdef isinf +inline int isinfinity(double x) { return isinf(x); } +inline int isinfinity(long double x) { return isinf(x); } +# else +inline int isinfinity(double x) { return std::isinf(x); } +inline int isinfinity(long double x) { return std::isinf(x); } +# endif +#else +inline int getsign(double value) { + if (value < 0) return 1; + if (value == value) return 0; + int dec = 0, sign = 0; + char buffer[2]; // The buffer size must be >= 2 or _ecvt_s will fail. + _ecvt_s(buffer, sizeof(buffer), value, 0, &dec, &sign); + return sign; +} +inline int isinfinity(double x) { return !_finite(x); } +inline int isinfinity(long double x) { return !_finite(static_cast(x)); } +#endif + +template +class BasicCharTraits { + public: +#if _SECURE_SCL + typedef stdext::checked_array_iterator CharPtr; +#else + typedef Char *CharPtr; +#endif +}; + +template +class CharTraits; + +template <> +class CharTraits : public BasicCharTraits { + private: + // Conversion from wchar_t to char is not allowed. + static char convert(wchar_t); + +public: + static char convert(char value) { return value; } + + // Formats a floating-point number. + template + static int format_float(char *buffer, std::size_t size, + const char *format, unsigned width, int precision, T value); +}; + +template <> +class CharTraits : public BasicCharTraits { + public: + static wchar_t convert(char value) { return value; } + static wchar_t convert(wchar_t value) { return value; } + + template + static int format_float(wchar_t *buffer, std::size_t size, + const wchar_t *format, unsigned width, int precision, T value); +}; + +// Checks if a number is negative - used to avoid warnings. +template +struct SignChecker { + template + static bool is_negative(T value) { return value < 0; } +}; + +template <> +struct SignChecker { + template + static bool is_negative(T) { return false; } +}; + +// Returns true if value is negative, false otherwise. +// Same as (value < 0) but doesn't produce warnings if T is an unsigned type. +template +inline bool is_negative(T value) { + return SignChecker::is_signed>::is_negative(value); +} + +// Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise. +template +struct TypeSelector { typedef uint32_t Type; }; + +template <> +struct TypeSelector { typedef uint64_t Type; }; + +template +struct IntTraits { + // Smallest of uint32_t and uint64_t that is large enough to represent + // all values of T. + typedef typename + TypeSelector::digits <= 32>::Type MainType; +}; + +// MakeUnsigned::Type gives an unsigned type corresponding to integer type T. +template +struct MakeUnsigned { typedef T Type; }; + +#define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \ + template <> \ + struct MakeUnsigned { typedef U Type; } + +FMT_SPECIALIZE_MAKE_UNSIGNED(char, unsigned char); +FMT_SPECIALIZE_MAKE_UNSIGNED(signed char, unsigned char); +FMT_SPECIALIZE_MAKE_UNSIGNED(short, unsigned short); +FMT_SPECIALIZE_MAKE_UNSIGNED(int, unsigned); +FMT_SPECIALIZE_MAKE_UNSIGNED(long, unsigned long); +FMT_SPECIALIZE_MAKE_UNSIGNED(LongLong, ULongLong); + +void report_unknown_type(char code, const char *type); + +// Static data is placed in this class template to allow header-only +// configuration. +template +struct BasicData { + static const uint32_t POWERS_OF_10_32[]; + static const uint64_t POWERS_OF_10_64[]; + static const char DIGITS[]; +}; + +typedef BasicData<> Data; + +#if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz) +# define FMT_BUILTIN_CLZ(n) __builtin_clz(n) +#endif + +#if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll) +# define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) +#endif + +#ifdef FMT_BUILTIN_CLZLL +// Returns the number of decimal digits in n. Leading zeros are not counted +// except for n == 0 in which case count_digits returns 1. +inline unsigned count_digits(uint64_t n) { + // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10 + // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits. + unsigned t = (64 - FMT_BUILTIN_CLZLL(n | 1)) * 1233 >> 12; + return t - (n < Data::POWERS_OF_10_64[t]) + 1; +} +#else +// Fallback version of count_digits used when __builtin_clz is not available. +inline unsigned count_digits(uint64_t n) { + unsigned count = 1; + for (;;) { + // Integer division is slow so do it for a group of four digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + if (n < 10) return count; + if (n < 100) return count + 1; + if (n < 1000) return count + 2; + if (n < 10000) return count + 3; + n /= 10000u; + count += 4; + } +} +#endif + +#ifdef FMT_BUILTIN_CLZ +// Optional version of count_digits for better performance on 32-bit platforms. +inline unsigned count_digits(uint32_t n) { + uint32_t t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12; + return t - (n < Data::POWERS_OF_10_32[t]) + 1; +} +#endif + +// Formats a decimal unsigned integer value writing into buffer. +template +inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) { + --num_digits; + while (value >= 100) { + // Integer division is slow so do it for a group of two digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + unsigned index = (value % 100) * 2; + value /= 100; + buffer[num_digits] = Data::DIGITS[index + 1]; + buffer[num_digits - 1] = Data::DIGITS[index]; + num_digits -= 2; + } + if (value < 10) { + *buffer = static_cast('0' + value); + return; + } + unsigned index = static_cast(value * 2); + buffer[1] = Data::DIGITS[index + 1]; + buffer[0] = Data::DIGITS[index]; +} + +#ifdef _WIN32 +// A converter from UTF-8 to UTF-16. +// It is only provided for Windows since other systems support UTF-8 natively. +class UTF8ToUTF16 { + private: + MemoryBuffer buffer_; + + public: + explicit UTF8ToUTF16(StringRef s); + operator WStringRef() const { return WStringRef(&buffer_[0], size()); } + size_t size() const { return buffer_.size() - 1; } + const wchar_t *c_str() const { return &buffer_[0]; } + std::wstring str() const { return std::wstring(&buffer_[0], size()); } +}; + +// A converter from UTF-16 to UTF-8. +// It is only provided for Windows since other systems support UTF-8 natively. +class UTF16ToUTF8 { + private: + MemoryBuffer buffer_; + + public: + UTF16ToUTF8() {} + explicit UTF16ToUTF8(WStringRef s); + operator StringRef() const { return StringRef(&buffer_[0], size()); } + size_t size() const { return buffer_.size() - 1; } + const char *c_str() const { return &buffer_[0]; } + std::string str() const { return std::string(&buffer_[0], size()); } + + // Performs conversion returning a system error code instead of + // throwing exception on conversion error. This method may still throw + // in case of memory allocation error. + int convert(WStringRef s); +}; +#endif + +void format_system_error(fmt::Writer &out, int error_code, + fmt::StringRef message) FMT_NOEXCEPT; + +#ifdef _WIN32 +void format_windows_error(fmt::Writer &out, int error_code, + fmt::StringRef message) FMT_NOEXCEPT; +#endif + +// Computes max(Arg, 1) at compile time. It is used to avoid errors about +// allocating an array of 0 size. +template +struct NonZero { + enum { VALUE = Arg }; +}; + +template <> +struct NonZero<0> { + enum { VALUE = 1 }; +}; + +// The value of a formatting argument. It is a POD type to allow storage in +// internal::MemoryBuffer. +struct Value { + template + struct StringValue { + const Char *value; + std::size_t size; + }; + + typedef void (*FormatFunc)( + void *formatter, const void *arg, void *format_str_ptr); + + struct CustomValue { + const void *value; + FormatFunc format; + }; + + union { + int int_value; + unsigned uint_value; + LongLong long_long_value; + ULongLong ulong_long_value; + double double_value; + long double long_double_value; + const void *pointer; + StringValue string; + StringValue sstring; + StringValue ustring; + StringValue wstring; + CustomValue custom; + }; +}; + +struct Arg : Value { + enum Type { + NONE, + // Integer types should go first, + INT, UINT, LONG_LONG, ULONG_LONG, CHAR, LAST_INTEGER_TYPE = CHAR, + // followed by floating-point types. + DOUBLE, LONG_DOUBLE, LAST_NUMERIC_TYPE = LONG_DOUBLE, + CSTRING, STRING, WSTRING, POINTER, CUSTOM + }; + Type type; +}; + +template +struct None {}; + +// A helper class template to enable or disable overloads taking wide +// characters and strings in MakeValue. +template +struct WCharHelper { + typedef None Supported; + typedef T Unsupported; +}; + +template +struct WCharHelper { + typedef T Supported; + typedef None Unsupported; +}; + +// Makes a Value object from any type. +template +class MakeValue : public Value { + private: + // The following two methods are private to disallow formatting of + // arbitrary pointers. If you want to output a pointer cast it to + // "void *" or "const void *". In particular, this forbids formatting + // of "[const] volatile char *" which is printed as bool by iostreams. + // Do not implement! + template + MakeValue(const T *value); + template + MakeValue(T *value); + + // The following methods are private to disallow formatting of wide + // characters and strings into narrow strings as in + // fmt::format("{}", L"test"); + // To fix this, use a wide format string: fmt::format(L"{}", L"test"). + MakeValue(typename WCharHelper::Unsupported); + MakeValue(typename WCharHelper::Unsupported); + MakeValue(typename WCharHelper::Unsupported); + MakeValue(typename WCharHelper::Unsupported); + MakeValue(typename WCharHelper::Unsupported); + + void set_string(StringRef str) { + string.value = str.c_str(); + string.size = str.size(); + } + + void set_string(WStringRef str) { + wstring.value = str.c_str(); + wstring.size = str.size(); + } + + // Formats an argument of a custom type, such as a user-defined class. + template + static void format_custom_arg( + void *formatter, const void *arg, void *format_str_ptr) { + format(*static_cast*>(formatter), + *static_cast(format_str_ptr), + *static_cast(arg)); + } + + public: + MakeValue() {} + +#define FMT_MAKE_VALUE(Type, field, TYPE) \ + MakeValue(Type value) { field = value; } \ + static uint64_t type(Type) { return Arg::TYPE; } + + FMT_MAKE_VALUE(bool, int_value, INT) + FMT_MAKE_VALUE(short, int_value, INT) + FMT_MAKE_VALUE(unsigned short, uint_value, UINT) + FMT_MAKE_VALUE(int, int_value, INT) + FMT_MAKE_VALUE(unsigned, uint_value, UINT) + + MakeValue(long value) { + // To minimize the number of types we need to deal with, long is + // translated either to int or to long long depending on its size. + if (sizeof(long) == sizeof(int)) + int_value = static_cast(value); + else + long_long_value = value; + } + static uint64_t type(long) { + return sizeof(long) == sizeof(int) ? Arg::INT : Arg::LONG_LONG; + } + + MakeValue(unsigned long value) { + if (sizeof(unsigned long) == sizeof(unsigned)) + uint_value = static_cast(value); + else + ulong_long_value = value; + } + static uint64_t type(unsigned long) { + return sizeof(unsigned long) == sizeof(unsigned) ? + Arg::UINT : Arg::ULONG_LONG; + } + + FMT_MAKE_VALUE(LongLong, long_long_value, LONG_LONG) + FMT_MAKE_VALUE(ULongLong, ulong_long_value, ULONG_LONG) + FMT_MAKE_VALUE(float, double_value, DOUBLE) + FMT_MAKE_VALUE(double, double_value, DOUBLE) + FMT_MAKE_VALUE(long double, long_double_value, LONG_DOUBLE) + FMT_MAKE_VALUE(signed char, int_value, CHAR) + FMT_MAKE_VALUE(unsigned char, int_value, CHAR) + FMT_MAKE_VALUE(char, int_value, CHAR) + + MakeValue(typename WCharHelper::Supported value) { + int_value = value; + } + static uint64_t type(wchar_t) { return Arg::CHAR; } + +#define FMT_MAKE_STR_VALUE(Type, TYPE) \ + MakeValue(Type value) { set_string(value); } \ + static uint64_t type(Type) { return Arg::TYPE; } + + FMT_MAKE_VALUE(char *, string.value, CSTRING) + FMT_MAKE_VALUE(const char *, string.value, CSTRING) + FMT_MAKE_VALUE(const signed char *, sstring.value, CSTRING) + FMT_MAKE_VALUE(const unsigned char *, ustring.value, CSTRING) + FMT_MAKE_STR_VALUE(const std::string &, STRING) + FMT_MAKE_STR_VALUE(StringRef, STRING) + +#define FMT_MAKE_WSTR_VALUE(Type, TYPE) \ + MakeValue(typename WCharHelper::Supported value) { \ + set_string(value); \ + } \ + static uint64_t type(Type) { return Arg::TYPE; } + + FMT_MAKE_WSTR_VALUE(wchar_t *, WSTRING) + FMT_MAKE_WSTR_VALUE(const wchar_t *, WSTRING) + FMT_MAKE_WSTR_VALUE(const std::wstring &, WSTRING) + FMT_MAKE_WSTR_VALUE(WStringRef, WSTRING) + + FMT_MAKE_VALUE(void *, pointer, POINTER) + FMT_MAKE_VALUE(const void *, pointer, POINTER) + + template + MakeValue(const T &value) { + custom.value = &value; + custom.format = &format_custom_arg; + } + template + static uint64_t type(const T &) { return Arg::CUSTOM; } +}; + +#define FMT_DISPATCH(call) static_cast(this)->call + +// An argument visitor. +// To use ArgVisitor define a subclass that implements some or all of the +// visit methods with the same signatures as the methods in ArgVisitor, +// for example, visit_int(int). +// Specify the subclass name as the Impl template parameter. Then calling +// ArgVisitor::visit for some argument will dispatch to a visit method +// specific to the argument type. For example, if the argument type is +// double then visit_double(double) method of a subclass will be called. +// If the subclass doesn't contain a method with this signature, then +// a corresponding method of ArgVisitor will be called. +// +// Example: +// class MyArgVisitor : public ArgVisitor { +// public: +// void visit_int(int value) { print("{}", value); } +// void visit_double(double value) { print("{}", value ); } +// }; +// +// ArgVisitor uses the curiously recurring template pattern: +// http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern +template +class ArgVisitor { + public: + Result visit_unhandled_arg() { return Result(); } + + Result visit_int(int value) { + return FMT_DISPATCH(visit_any_int(value)); + } + Result visit_long_long(LongLong value) { + return FMT_DISPATCH(visit_any_int(value)); + } + Result visit_uint(unsigned value) { + return FMT_DISPATCH(visit_any_int(value)); + } + Result visit_ulong_long(ULongLong value) { + return FMT_DISPATCH(visit_any_int(value)); + } + Result visit_char(int value) { + return FMT_DISPATCH(visit_any_int(value)); + } + template + Result visit_any_int(T) { + return FMT_DISPATCH(visit_unhandled_arg()); + } + + Result visit_double(double value) { + return FMT_DISPATCH(visit_any_double(value)); + } + Result visit_long_double(long double value) { + return FMT_DISPATCH(visit_any_double(value)); + } + template + Result visit_any_double(T) { + return FMT_DISPATCH(visit_unhandled_arg()); + } + + Result visit_string(Arg::StringValue) { + return FMT_DISPATCH(visit_unhandled_arg()); + } + Result visit_wstring(Arg::StringValue) { + return FMT_DISPATCH(visit_unhandled_arg()); + } + Result visit_pointer(const void *) { + return FMT_DISPATCH(visit_unhandled_arg()); + } + Result visit_custom(Arg::CustomValue) { + return FMT_DISPATCH(visit_unhandled_arg()); + } + + Result visit(const Arg &arg) { + switch (arg.type) { + default: + assert(false); + return Result(); + case Arg::INT: + return FMT_DISPATCH(visit_int(arg.int_value)); + case Arg::UINT: + return FMT_DISPATCH(visit_uint(arg.uint_value)); + case Arg::LONG_LONG: + return FMT_DISPATCH(visit_long_long(arg.long_long_value)); + case Arg::ULONG_LONG: + return FMT_DISPATCH(visit_ulong_long(arg.ulong_long_value)); + case Arg::DOUBLE: + return FMT_DISPATCH(visit_double(arg.double_value)); + case Arg::LONG_DOUBLE: + return FMT_DISPATCH(visit_long_double(arg.long_double_value)); + case Arg::CHAR: + return FMT_DISPATCH(visit_char(arg.int_value)); + case Arg::CSTRING: { + Value::StringValue str = arg.string; + str.size = 0; + return FMT_DISPATCH(visit_string(str)); + } + case Arg::STRING: + return FMT_DISPATCH(visit_string(arg.string)); + case Arg::WSTRING: + return FMT_DISPATCH(visit_wstring(arg.wstring)); + case Arg::POINTER: + return FMT_DISPATCH(visit_pointer(arg.pointer)); + case Arg::CUSTOM: + return FMT_DISPATCH(visit_custom(arg.custom)); + } + } +}; + +class RuntimeError : public std::runtime_error { + protected: + RuntimeError() : std::runtime_error("") {} +}; + +template +class ArgFormatter; +} // namespace internal + +/** + An argument list. + */ +class ArgList { + private: + uint64_t types_; + const internal::Value *values_; + + public: + // Maximum number of arguments that can be passed in ArgList. + enum { MAX_ARGS = 16 }; + + ArgList() : types_(0) {} + ArgList(ULongLong types, const internal::Value *values) + : types_(types), values_(values) {} + + /** + Returns the argument at specified index. + */ + internal::Arg operator[](unsigned index) const { + using internal::Arg; + Arg arg; + if (index >= MAX_ARGS) { + arg.type = Arg::NONE; + return arg; + } + unsigned shift = index * 4; + uint64_t mask = 0xf; + Arg::Type type = + static_cast((types_ & (mask << shift)) >> shift); + arg.type = type; + if (type != Arg::NONE) { + internal::Value &value = arg; + value = values_[index]; + } + return arg; + } +}; + +struct FormatSpec; + +namespace internal { + +class FormatterBase { + private: + ArgList args_; + int next_arg_index_; + + // Returns the argument with specified index. + Arg do_get_arg(unsigned arg_index, const char *&error); + + protected: + void set_args(const ArgList &args) { + args_ = args; + next_arg_index_ = 0; + } + + // Returns the next argument. + Arg next_arg(const char *&error); + + // Checks if manual indexing is used and returns the argument with + // specified index. + Arg get_arg(unsigned arg_index, const char *&error); + + template + void write(BasicWriter &w, const Char *start, const Char *end) { + if (start != end) + w << BasicStringRef(start, end - start); + } +}; + +// A printf formatter. +template +class PrintfFormatter : private FormatterBase { + private: + void parse_flags(FormatSpec &spec, const Char *&s); + + // Returns the argument with specified index or, if arg_index is equal + // to the maximum unsigned value, the next argument. + Arg get_arg(const Char *s, + unsigned arg_index = (std::numeric_limits::max)()); + + // Parses argument index, flags and width and returns the argument index. + unsigned parse_header(const Char *&s, FormatSpec &spec); + + public: + void format(BasicWriter &writer, + BasicStringRef format_str, const ArgList &args); +}; +} // namespace internal + +// A formatter. +template +class BasicFormatter : private internal::FormatterBase { + private: + BasicWriter &writer_; + const Char *start_; + + FMT_DISALLOW_COPY_AND_ASSIGN(BasicFormatter); + + // Parses argument index and returns corresponding argument. + internal::Arg parse_arg_index(const Char *&s); + + public: + explicit BasicFormatter(BasicWriter &w) : writer_(w) {} + + BasicWriter &writer() { return writer_; } + + void format(BasicStringRef format_str, const ArgList &args); + + const Char *format(const Char *&format_str, const internal::Arg &arg); +}; + +enum Alignment { + ALIGN_DEFAULT, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER, ALIGN_NUMERIC +}; + +// Flags. +enum { + SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8, + CHAR_FLAG = 0x10 // Argument has char type - used in error reporting. +}; + +// An empty format specifier. +struct EmptySpec {}; + +// A type specifier. +template +struct TypeSpec : EmptySpec { + Alignment align() const { return ALIGN_DEFAULT; } + unsigned width() const { return 0; } + int precision() const { return -1; } + bool flag(unsigned) const { return false; } + char type() const { return TYPE; } + char fill() const { return ' '; } +}; + +// A width specifier. +struct WidthSpec { + unsigned width_; + // Fill is always wchar_t and cast to char if necessary to avoid having + // two specialization of WidthSpec and its subclasses. + wchar_t fill_; + + WidthSpec(unsigned width, wchar_t fill) : width_(width), fill_(fill) {} + + unsigned width() const { return width_; } + wchar_t fill() const { return fill_; } +}; + +// An alignment specifier. +struct AlignSpec : WidthSpec { + Alignment align_; + + AlignSpec(unsigned width, wchar_t fill, Alignment align = ALIGN_DEFAULT) + : WidthSpec(width, fill), align_(align) {} + + Alignment align() const { return align_; } + + int precision() const { return -1; } +}; + +// An alignment and type specifier. +template +struct AlignTypeSpec : AlignSpec { + AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) {} + + bool flag(unsigned) const { return false; } + char type() const { return TYPE; } +}; + +// A full format specifier. +struct FormatSpec : AlignSpec { + unsigned flags_; + int precision_; + char type_; + + FormatSpec( + unsigned width = 0, char type = 0, wchar_t fill = ' ') + : AlignSpec(width, fill), flags_(0), precision_(-1), type_(type) {} + + bool flag(unsigned f) const { return (flags_ & f) != 0; } + int precision() const { return precision_; } + char type() const { return type_; } +}; + +// An integer format specifier. +template , typename Char = char> +class IntFormatSpec : public SpecT { + private: + T value_; + + public: + IntFormatSpec(T val, const SpecT &spec = SpecT()) + : SpecT(spec), value_(val) {} + + T value() const { return value_; } +}; + +// A string format specifier. +template +class StrFormatSpec : public AlignSpec { + private: + const T *str_; + + public: + StrFormatSpec(const T *str, unsigned width, wchar_t fill) + : AlignSpec(width, fill), str_(str) {} + + const T *str() const { return str_; } +}; + +/** + Returns an integer format specifier to format the value in base 2. + */ +IntFormatSpec > bin(int value); + +/** + Returns an integer format specifier to format the value in base 8. + */ +IntFormatSpec > oct(int value); + +/** + Returns an integer format specifier to format the value in base 16 using + lower-case letters for the digits above 9. + */ +IntFormatSpec > hex(int value); + +/** + Returns an integer formatter format specifier to format in base 16 using + upper-case letters for the digits above 9. + */ +IntFormatSpec > hexu(int value); + +/** + \rst + Returns an integer format specifier to pad the formatted argument with the + fill character to the specified width using the default (right) numeric + alignment. + + **Example**:: + + MemoryWriter out; + out << pad(hex(0xcafe), 8, '0'); + // out.str() == "0000cafe" + + \endrst + */ +template +IntFormatSpec, Char> pad( + int value, unsigned width, Char fill = ' '); + +#define FMT_DEFINE_INT_FORMATTERS(TYPE) \ +inline IntFormatSpec > bin(TYPE value) { \ + return IntFormatSpec >(value, TypeSpec<'b'>()); \ +} \ + \ +inline IntFormatSpec > oct(TYPE value) { \ + return IntFormatSpec >(value, TypeSpec<'o'>()); \ +} \ + \ +inline IntFormatSpec > hex(TYPE value) { \ + return IntFormatSpec >(value, TypeSpec<'x'>()); \ +} \ + \ +inline IntFormatSpec > hexu(TYPE value) { \ + return IntFormatSpec >(value, TypeSpec<'X'>()); \ +} \ + \ +template \ +inline IntFormatSpec > pad( \ + IntFormatSpec > f, unsigned width) { \ + return IntFormatSpec >( \ + f.value(), AlignTypeSpec(width, ' ')); \ +} \ + \ +/* For compatibility with older compilers we provide two overloads for pad, */ \ +/* one that takes a fill character and one that doesn't. In the future this */ \ +/* can be replaced with one overload making the template argument Char */ \ +/* default to char (C++11). */ \ +template \ +inline IntFormatSpec, Char> pad( \ + IntFormatSpec, Char> f, \ + unsigned width, Char fill) { \ + return IntFormatSpec, Char>( \ + f.value(), AlignTypeSpec(width, fill)); \ +} \ + \ +inline IntFormatSpec > pad( \ + TYPE value, unsigned width) { \ + return IntFormatSpec >( \ + value, AlignTypeSpec<0>(width, ' ')); \ +} \ + \ +template \ +inline IntFormatSpec, Char> pad( \ + TYPE value, unsigned width, Char fill) { \ + return IntFormatSpec, Char>( \ + value, AlignTypeSpec<0>(width, fill)); \ +} + +FMT_DEFINE_INT_FORMATTERS(int) +FMT_DEFINE_INT_FORMATTERS(long) +FMT_DEFINE_INT_FORMATTERS(unsigned) +FMT_DEFINE_INT_FORMATTERS(unsigned long) +FMT_DEFINE_INT_FORMATTERS(LongLong) +FMT_DEFINE_INT_FORMATTERS(ULongLong) + +/** + \rst + Returns a string formatter that pads the formatted argument with the fill + character to the specified width using the default (left) string alignment. + + **Example**:: + + std::string s = str(MemoryWriter() << pad("abc", 8)); + // s == "abc " + + \endrst + */ +template +inline StrFormatSpec pad( + const Char *str, unsigned width, Char fill = ' ') { + return StrFormatSpec(str, width, fill); +} + +inline StrFormatSpec pad( + const wchar_t *str, unsigned width, char fill = ' ') { + return StrFormatSpec(str, width, fill); +} + +// Generates a comma-separated list with results of applying f to +// numbers 0..n-1. +# define FMT_GEN(n, f) FMT_GEN##n(f) +# define FMT_GEN1(f) f(0) +# define FMT_GEN2(f) FMT_GEN1(f), f(1) +# define FMT_GEN3(f) FMT_GEN2(f), f(2) +# define FMT_GEN4(f) FMT_GEN3(f), f(3) +# define FMT_GEN5(f) FMT_GEN4(f), f(4) +# define FMT_GEN6(f) FMT_GEN5(f), f(5) +# define FMT_GEN7(f) FMT_GEN6(f), f(6) +# define FMT_GEN8(f) FMT_GEN7(f), f(7) +# define FMT_GEN9(f) FMT_GEN8(f), f(8) +# define FMT_GEN10(f) FMT_GEN9(f), f(9) +# define FMT_GEN11(f) FMT_GEN10(f), f(10) +# define FMT_GEN12(f) FMT_GEN11(f), f(11) +# define FMT_GEN13(f) FMT_GEN12(f), f(12) +# define FMT_GEN14(f) FMT_GEN13(f), f(13) +# define FMT_GEN15(f) FMT_GEN14(f), f(14) + +namespace internal { +inline uint64_t make_type() { return 0; } + +template +inline uint64_t make_type(const T &arg) { return MakeValue::type(arg); } + +#if FMT_USE_VARIADIC_TEMPLATES +template +inline uint64_t make_type(const Arg &first, const Args & ... tail) { + return make_type(first) | (make_type(tail...) << 4); +} +#else + +struct ArgType { + uint64_t type; + + ArgType() : type(0) {} + + template + ArgType(const T &arg) : type(make_type(arg)) {} +}; + +# define FMT_ARG_TYPE_DEFAULT(n) ArgType t##n = ArgType() + +inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) { + return t0.type | (t1.type << 4) | (t2.type << 8) | (t3.type << 12) | + (t4.type << 16) | (t5.type << 20) | (t6.type << 24) | (t7.type << 28) | + (t8.type << 32) | (t9.type << 36) | (t10.type << 40) | (t11.type << 44) | + (t12.type << 48) | (t13.type << 52) | (t14.type << 56); +} +#endif +} // namespace internal + +# define FMT_MAKE_TEMPLATE_ARG(n) typename T##n +# define FMT_MAKE_ARG_TYPE(n) T##n +# define FMT_MAKE_ARG(n) const T##n &v##n +# define FMT_MAKE_REF_char(n) fmt::internal::MakeValue(v##n) +# define FMT_MAKE_REF_wchar_t(n) fmt::internal::MakeValue(v##n) + +#if FMT_USE_VARIADIC_TEMPLATES +// Defines a variadic function returning void. +# define FMT_VARIADIC_VOID(func, arg_type) \ + template \ + void func(arg_type arg1, const Args & ... args) { \ + const fmt::internal::Value values[ \ + fmt::internal::NonZero::VALUE] = { \ + fmt::internal::MakeValue(args)... \ + }; \ + func(arg1, ArgList(fmt::internal::make_type(args...), values)); \ + } + +// Defines a variadic constructor. +# define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ + template \ + ctor(arg0_type arg0, arg1_type arg1, const Args & ... args) { \ + using fmt::internal::MakeValue; \ + const fmt::internal::Value values[ \ + fmt::internal::NonZero::VALUE] = { \ + MakeValue(args)... \ + }; \ + func(arg0, arg1, ArgList(fmt::internal::make_type(args...), values)); \ + } + +#else + +# define FMT_MAKE_REF(n) fmt::internal::MakeValue(v##n) +# define FMT_MAKE_REF2(n) v##n + +// Defines a wrapper for a function taking one argument of type arg_type +// and n additional arguments of arbitrary types. +# define FMT_WRAP1(func, arg_type, n) \ + template \ + inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \ + const fmt::internal::Value vals[] = {FMT_GEN(n, FMT_MAKE_REF)}; \ + func(arg1, fmt::ArgList( \ + fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), vals)); \ + } + +// Emulates a variadic function returning void on a pre-C++11 compiler. +# define FMT_VARIADIC_VOID(func, arg_type) \ + inline void func(arg_type arg) { func(arg, fmt::ArgList()); } \ + FMT_WRAP1(func, arg_type, 1) FMT_WRAP1(func, arg_type, 2) \ + FMT_WRAP1(func, arg_type, 3) FMT_WRAP1(func, arg_type, 4) \ + FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) \ + FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) \ + FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10) + +# define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \ + template \ + ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \ + const fmt::internal::Value vals[] = {FMT_GEN(n, FMT_MAKE_REF)}; \ + func(arg0, arg1, fmt::ArgList( \ + fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), vals)); \ + } + +// Emulates a variadic constructor on a pre-C++11 compiler. +# define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 1) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 2) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 3) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 4) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 5) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 6) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 7) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 8) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 9) \ + FMT_CTOR(ctor, func, arg0_type, arg1_type, 10) +#endif + +// Generates a comma-separated list with results of applying f to pairs +// (argument, index). +#define FMT_FOR_EACH1(f, x0) f(x0, 0) +#define FMT_FOR_EACH2(f, x0, x1) \ + FMT_FOR_EACH1(f, x0), f(x1, 1) +#define FMT_FOR_EACH3(f, x0, x1, x2) \ + FMT_FOR_EACH2(f, x0 ,x1), f(x2, 2) +#define FMT_FOR_EACH4(f, x0, x1, x2, x3) \ + FMT_FOR_EACH3(f, x0, x1, x2), f(x3, 3) +#define FMT_FOR_EACH5(f, x0, x1, x2, x3, x4) \ + FMT_FOR_EACH4(f, x0, x1, x2, x3), f(x4, 4) +#define FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5) \ + FMT_FOR_EACH5(f, x0, x1, x2, x3, x4), f(x5, 5) +#define FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6) \ + FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5), f(x6, 6) +#define FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7) \ + FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6), f(x7, 7) +#define FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8) \ + FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7), f(x8, 8) +#define FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) \ + FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8), f(x9, 9) + +/** + An error returned by an operating system or a language runtime, + for example a file opening error. +*/ +class SystemError : public internal::RuntimeError { + private: + void init(int err_code, StringRef format_str, ArgList args); + + protected: + int error_code_; + + typedef char Char; // For FMT_VARIADIC_CTOR. + + SystemError() {} + + public: + /** + \rst + Constructs a :class:`fmt::SystemError` object with the description + of the form + + .. parsed-literal:: + **: ** + + where ** is the formatted message and ** is + the system message corresponding to the error code. + *error_code* is a system error code as given by ``errno``. + If *error_code* is not a valid error code such as -1, the system message + may look like "Unknown error -1" and is platform-dependent. + + **Example**:: + + // This throws a SystemError with the description + // cannot open file 'madeup': No such file or directory + // or similar (system message may vary). + const char *filename = "madeup"; + std::FILE *file = std::fopen(filename, "r"); + if (!file) + throw fmt::SystemError(errno, "cannot open file '{}'", filename); + \endrst + */ + SystemError(int error_code, StringRef message) { + init(error_code, message, ArgList()); + } + FMT_VARIADIC_CTOR(SystemError, init, int, StringRef) + + int error_code() const { return error_code_; } +}; + +/** + \rst + This template provides operations for formatting and writing data into + a character stream. The output is stored in a buffer provided by a subclass + such as :class:`fmt::BasicMemoryWriter`. + + You can use one of the following typedefs for common character types: + + +---------+----------------------+ + | Type | Definition | + +=========+======================+ + | Writer | BasicWriter | + +---------+----------------------+ + | WWriter | BasicWriter | + +---------+----------------------+ + + \endrst + */ +template +class BasicWriter { + private: + // Output buffer. + internal::Buffer &buffer_; + + FMT_DISALLOW_COPY_AND_ASSIGN(BasicWriter); + + typedef typename internal::CharTraits::CharPtr CharPtr; + +#if _SECURE_SCL + // Returns pointer value. + static Char *get(CharPtr p) { return p.base(); } +#else + static Char *get(Char *p) { return p; } +#endif + + // Fills the padding around the content and returns the pointer to the + // content area. + static CharPtr fill_padding(CharPtr buffer, + unsigned total_size, std::size_t content_size, wchar_t fill); + + // Grows the buffer by n characters and returns a pointer to the newly + // allocated area. + CharPtr grow_buffer(std::size_t n) { + std::size_t size = buffer_.size(); + buffer_.resize(size + n); + return internal::make_ptr(&buffer_[size], n); + } + + // Prepare a buffer for integer formatting. + CharPtr prepare_int_buffer(unsigned num_digits, + const EmptySpec &, const char *prefix, unsigned prefix_size) { + unsigned size = prefix_size + num_digits; + CharPtr p = grow_buffer(size); + std::copy(prefix, prefix + prefix_size, p); + return p + size - 1; + } + + template + CharPtr prepare_int_buffer(unsigned num_digits, + const Spec &spec, const char *prefix, unsigned prefix_size); + + // Formats an integer. + template + void write_int(T value, Spec spec); + + // Formats a floating-point number (double or long double). + template + void write_double(T value, const FormatSpec &spec); + + // Writes a formatted string. + template + CharPtr write_str( + const StrChar *s, std::size_t size, const AlignSpec &spec); + + template + void write_str( + const internal::Arg::StringValue &str, const FormatSpec &spec); + + // This following methods are private to disallow writing wide characters + // and strings to a char stream. If you want to print a wide string as a + // pointer as std::ostream does, cast it to const void*. + // Do not implement! + void operator<<(typename internal::WCharHelper::Unsupported); + void operator<<( + typename internal::WCharHelper::Unsupported); + + // Appends floating-point length specifier to the format string. + // The second argument is only used for overload resolution. + void append_float_length(Char *&format_ptr, long double) { + *format_ptr++ = 'L'; + } + + template + void append_float_length(Char *&, T) {} + + friend class internal::ArgFormatter; + friend class internal::PrintfFormatter; + + protected: + /** + Constructs a ``BasicWriter`` object. + */ + explicit BasicWriter(internal::Buffer &b) : buffer_(b) {} + + public: + /** + Destroys a ``BasicWriter`` object. + */ + virtual ~BasicWriter() {} + + /** + Returns the total number of characters written. + */ + std::size_t size() const { return buffer_.size(); } + + /** + Returns a pointer to the output buffer content. No terminating null + character is appended. + */ + const Char *data() const FMT_NOEXCEPT { return &buffer_[0]; } + + /** + Returns a pointer to the output buffer content with terminating null + character appended. + */ + const Char *c_str() const { + std::size_t size = buffer_.size(); + buffer_.reserve(size + 1); + buffer_[size] = '\0'; + return &buffer_[0]; + } + + /** + Returns the content of the output buffer as an `std::string`. + */ + std::basic_string str() const { + return std::basic_string(&buffer_[0], buffer_.size()); + } + + /** + \rst + Writes formatted data. + + *args* is an argument list representing arbitrary arguments. + + **Example**:: + + MemoryWriter out; + out.write("Current point:\n"); + out.write("({:+f}, {:+f})", -3.14, 3.14); + + This will write the following output to the ``out`` object: + + .. code-block:: none + + Current point: + (-3.140000, +3.140000) + + The output can be accessed using :func:`data()`, :func:`c_str` or + :func:`str` methods. + + See also :ref:`syntax`. + \endrst + */ + void write(BasicStringRef format, ArgList args) { + BasicFormatter(*this).format(format, args); + } + FMT_VARIADIC_VOID(write, BasicStringRef) + + BasicWriter &operator<<(int value) { + return *this << IntFormatSpec(value); + } + BasicWriter &operator<<(unsigned value) { + return *this << IntFormatSpec(value); + } + BasicWriter &operator<<(long value) { + return *this << IntFormatSpec(value); + } + BasicWriter &operator<<(unsigned long value) { + return *this << IntFormatSpec(value); + } + BasicWriter &operator<<(LongLong value) { + return *this << IntFormatSpec(value); + } + + /** + Formats *value* and writes it to the stream. + */ + BasicWriter &operator<<(ULongLong value) { + return *this << IntFormatSpec(value); + } + + BasicWriter &operator<<(double value) { + write_double(value, FormatSpec()); + return *this; + } + + /** + Formats *value* using the general format for floating-point numbers + (``'g'``) and writes it to the stream. + */ + BasicWriter &operator<<(long double value) { + write_double(value, FormatSpec()); + return *this; + } + + /** + Writes a character to the stream. + */ + BasicWriter &operator<<(char value) { + buffer_.push_back(value); + return *this; + } + + BasicWriter &operator<<( + typename internal::WCharHelper::Supported value) { + buffer_.push_back(value); + return *this; + } + + /** + Writes *value* to the stream. + */ + BasicWriter &operator<<(fmt::BasicStringRef value) { + const Char *str = value.c_str(); + buffer_.append(str, str + value.size()); + return *this; + } + + template + BasicWriter &operator<<(IntFormatSpec spec) { + internal::CharTraits::convert(FillChar()); + write_int(spec.value(), spec); + return *this; + } + + template + BasicWriter &operator<<(const StrFormatSpec &spec) { + const StrChar *s = spec.str(); + // TODO: error if fill is not convertible to Char + write_str(s, std::char_traits::length(s), spec); + return *this; + } + + void clear() FMT_NOEXCEPT { buffer_.clear(); } +}; + +template +template +typename BasicWriter::CharPtr BasicWriter::write_str( + const StrChar *s, std::size_t size, const AlignSpec &spec) { + CharPtr out = CharPtr(); + if (spec.width() > size) { + out = grow_buffer(spec.width()); + Char fill = static_cast(spec.fill()); + if (spec.align() == ALIGN_RIGHT) { + std::fill_n(out, spec.width() - size, fill); + out += spec.width() - size; + } else if (spec.align() == ALIGN_CENTER) { + out = fill_padding(out, spec.width(), size, fill); + } else { + std::fill_n(out + size, spec.width() - size, fill); + } + } else { + out = grow_buffer(size); + } + std::copy(s, s + size, out); + return out; +} + +template +typename BasicWriter::CharPtr + BasicWriter::fill_padding( + CharPtr buffer, unsigned total_size, + std::size_t content_size, wchar_t fill) { + std::size_t padding = total_size - content_size; + std::size_t left_padding = padding / 2; + Char fill_char = static_cast(fill); + std::fill_n(buffer, left_padding, fill_char); + buffer += left_padding; + CharPtr content = buffer; + std::fill_n(buffer + content_size, padding - left_padding, fill_char); + return content; +} + +template +template +typename BasicWriter::CharPtr + BasicWriter::prepare_int_buffer( + unsigned num_digits, const Spec &spec, + const char *prefix, unsigned prefix_size) { + unsigned width = spec.width(); + Alignment align = spec.align(); + Char fill = static_cast(spec.fill()); + if (spec.precision() > static_cast(num_digits)) { + // Octal prefix '0' is counted as a digit, so ignore it if precision + // is specified. + if (prefix_size > 0 && prefix[prefix_size - 1] == '0') + --prefix_size; + unsigned number_size = prefix_size + spec.precision(); + AlignSpec subspec(number_size, '0', ALIGN_NUMERIC); + if (number_size >= width) + return prepare_int_buffer(num_digits, subspec, prefix, prefix_size); + buffer_.reserve(width); + unsigned fill_size = width - number_size; + if (align != ALIGN_LEFT) { + CharPtr p = grow_buffer(fill_size); + std::fill(p, p + fill_size, fill); + } + CharPtr result = prepare_int_buffer( + num_digits, subspec, prefix, prefix_size); + if (align == ALIGN_LEFT) { + CharPtr p = grow_buffer(fill_size); + std::fill(p, p + fill_size, fill); + } + return result; + } + unsigned size = prefix_size + num_digits; + if (width <= size) { + CharPtr p = grow_buffer(size); + std::copy(prefix, prefix + prefix_size, p); + return p + size - 1; + } + CharPtr p = grow_buffer(width); + CharPtr end = p + width; + if (align == ALIGN_LEFT) { + std::copy(prefix, prefix + prefix_size, p); + p += size; + std::fill(p, end, fill); + } else if (align == ALIGN_CENTER) { + p = fill_padding(p, width, size, fill); + std::copy(prefix, prefix + prefix_size, p); + p += size; + } else { + if (align == ALIGN_NUMERIC) { + if (prefix_size != 0) { + p = std::copy(prefix, prefix + prefix_size, p); + size -= prefix_size; + } + } else { + std::copy(prefix, prefix + prefix_size, end - size); + } + std::fill(p, end - size, fill); + p = end; + } + return p - 1; +} + +template +template +void BasicWriter::write_int(T value, Spec spec) { + unsigned prefix_size = 0; + typedef typename internal::IntTraits::MainType UnsignedType; + UnsignedType abs_value = value; + char prefix[4] = ""; + if (internal::is_negative(value)) { + prefix[0] = '-'; + ++prefix_size; + abs_value = 0 - abs_value; + } else if (spec.flag(SIGN_FLAG)) { + prefix[0] = spec.flag(PLUS_FLAG) ? '+' : ' '; + ++prefix_size; + } + switch (spec.type()) { + case 0: case 'd': { + unsigned num_digits = internal::count_digits(abs_value); + CharPtr p = prepare_int_buffer( + num_digits, spec, prefix, prefix_size) + 1 - num_digits; + internal::format_decimal(get(p), abs_value, num_digits); + break; + } + case 'x': case 'X': { + UnsignedType n = abs_value; + if (spec.flag(HASH_FLAG)) { + prefix[prefix_size++] = '0'; + prefix[prefix_size++] = spec.type(); + } + unsigned num_digits = 0; + do { + ++num_digits; + } while ((n >>= 4) != 0); + Char *p = get(prepare_int_buffer( + num_digits, spec, prefix, prefix_size)); + n = abs_value; + const char *digits = spec.type() == 'x' ? + "0123456789abcdef" : "0123456789ABCDEF"; + do { + *p-- = digits[n & 0xf]; + } while ((n >>= 4) != 0); + break; + } + case 'b': case 'B': { + UnsignedType n = abs_value; + if (spec.flag(HASH_FLAG)) { + prefix[prefix_size++] = '0'; + prefix[prefix_size++] = spec.type(); + } + unsigned num_digits = 0; + do { + ++num_digits; + } while ((n >>= 1) != 0); + Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); + n = abs_value; + do { + *p-- = '0' + (n & 1); + } while ((n >>= 1) != 0); + break; + } + case 'o': { + UnsignedType n = abs_value; + if (spec.flag(HASH_FLAG)) + prefix[prefix_size++] = '0'; + unsigned num_digits = 0; + do { + ++num_digits; + } while ((n >>= 3) != 0); + Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); + n = abs_value; + do { + *p-- = '0' + (n & 7); + } while ((n >>= 3) != 0); + break; + } + default: + internal::report_unknown_type( + spec.type(), spec.flag(CHAR_FLAG) ? "char" : "integer"); + break; + } +} + +template +template +void BasicWriter::write_double( + T value, const FormatSpec &spec) { + // Check type. + char type = spec.type(); + bool upper = false; + switch (type) { + case 0: + type = 'g'; + break; + case 'e': case 'f': case 'g': case 'a': + break; + case 'F': +#ifdef _MSC_VER + // MSVC's printf doesn't support 'F'. + type = 'f'; +#endif + // Fall through. + case 'E': case 'G': case 'A': + upper = true; + break; + default: + internal::report_unknown_type(type, "double"); + break; + } + + char sign = 0; + // Use getsign instead of value < 0 because the latter is always + // false for NaN. + if (internal::getsign(static_cast(value))) { + sign = '-'; + value = -value; + } else if (spec.flag(SIGN_FLAG)) { + sign = spec.flag(PLUS_FLAG) ? '+' : ' '; + } + + if (value != value) { + // Format NaN ourselves because sprintf's output is not consistent + // across platforms. + std::size_t nan_size = 4; + const char *nan = upper ? " NAN" : " nan"; + if (!sign) { + --nan_size; + ++nan; + } + CharPtr out = write_str(nan, nan_size, spec); + if (sign) + *out = sign; + return; + } + + if (internal::isinfinity(value)) { + // Format infinity ourselves because sprintf's output is not consistent + // across platforms. + std::size_t inf_size = 4; + const char *inf = upper ? " INF" : " inf"; + if (!sign) { + --inf_size; + ++inf; + } + CharPtr out = write_str(inf, inf_size, spec); + if (sign) + *out = sign; + return; + } + + std::size_t offset = buffer_.size(); + unsigned width = spec.width(); + if (sign) { + buffer_.reserve(buffer_.size() + (std::max)(width, 1u)); + if (width > 0) + --width; + ++offset; + } + + // Build format string. + enum { MAX_FORMAT_SIZE = 10}; // longest format: %#-*.*Lg + Char format[MAX_FORMAT_SIZE]; + Char *format_ptr = format; + *format_ptr++ = '%'; + unsigned width_for_sprintf = width; + if (spec.flag(HASH_FLAG)) + *format_ptr++ = '#'; + if (spec.align() == ALIGN_CENTER) { + width_for_sprintf = 0; + } else { + if (spec.align() == ALIGN_LEFT) + *format_ptr++ = '-'; + if (width != 0) + *format_ptr++ = '*'; + } + if (spec.precision() >= 0) { + *format_ptr++ = '.'; + *format_ptr++ = '*'; + } + + append_float_length(format_ptr, value); + *format_ptr++ = type; + *format_ptr = '\0'; + + // Format using snprintf. + Char fill = static_cast(spec.fill()); + for (;;) { + std::size_t buffer_size = buffer_.capacity() - offset; +#if _MSC_VER + // MSVC's vsnprintf_s doesn't work with zero size, so reserve + // space for at least one extra character to make the size non-zero. + // Note that the buffer's capacity will increase by more than 1. + if (buffer_size == 0) { + buffer_.reserve(offset + 1); + buffer_size = buffer_.capacity() - offset; + } +#endif + Char *start = &buffer_[offset]; + int n = internal::CharTraits::format_float( + start, buffer_size, format, width_for_sprintf, spec.precision(), value); + if (n >= 0 && offset + n < buffer_.capacity()) { + if (sign) { + if ((spec.align() != ALIGN_RIGHT && spec.align() != ALIGN_DEFAULT) || + *start != ' ') { + *(start - 1) = sign; + sign = 0; + } else { + *(start - 1) = fill; + } + ++n; + } + if (spec.align() == ALIGN_CENTER && + spec.width() > static_cast(n)) { + width = spec.width(); + CharPtr p = grow_buffer(width); + std::copy(p, p + n, p + (width - n) / 2); + fill_padding(p, spec.width(), n, fill); + return; + } + if (spec.fill() != ' ' || sign) { + while (*start == ' ') + *start++ = fill; + if (sign) + *(start - 1) = sign; + } + grow_buffer(n); + return; + } + // If n is negative we ask to increase the capacity by at least 1, + // but as std::vector, the buffer grows exponentially. + buffer_.reserve(n >= 0 ? offset + n + 1 : buffer_.capacity() + 1); + } +} + +/** + \rst + This class template provides operations for formatting and writing data + into a character stream. The output is stored in a memory buffer that grows + dynamically. + + You can use one of the following typedefs for common character types + and the standard allocator: + + +---------------+-----------------------------------------------------+ + | Type | Definition | + +===============+=====================================================+ + | MemoryWriter | BasicMemoryWriter> | + +---------------+-----------------------------------------------------+ + | WMemoryWriter | BasicMemoryWriter> | + +---------------+-----------------------------------------------------+ + + **Example**:: + + MemoryWriter out; + out << "The answer is " << 42 << "\n"; + out.write("({:+f}, {:+f})", -3.14, 3.14); + + This will write the following output to the ``out`` object: + + .. code-block:: none + + The answer is 42 + (-3.140000, +3.140000) + + The output can be converted to an ``std::string`` with ``out.str()`` or + accessed as a C string with ``out.c_str()``. + \endrst + */ +template > +class BasicMemoryWriter : public BasicWriter { + private: + internal::MemoryBuffer buffer_; + + public: + explicit BasicMemoryWriter(const Allocator& alloc = Allocator()) + : BasicWriter(buffer_), buffer_(alloc) {} + +#if FMT_USE_RVALUE_REFERENCES + /** + \rst + Constructs a :class:`fmt::BasicMemoryWriter` object moving the content + of the other object to it. + \endrst + */ + BasicMemoryWriter(BasicMemoryWriter &&other) + : BasicWriter(buffer_), buffer_(std::move(other.buffer_)) { + } + + /** + \rst + Moves the content of the other ``BasicMemoryWriter`` object to this one. + \endrst + */ + BasicMemoryWriter &operator=(BasicMemoryWriter &&other) { + buffer_ = std::move(other.buffer_); + return *this; + } +#endif +}; + +typedef BasicMemoryWriter MemoryWriter; +typedef BasicMemoryWriter WMemoryWriter; + +/** + \rst + This class template provides operations for formatting and writing data + into a fixed-size array. For writing into a dynamically growing buffer + use :class:`fmt::BasicMemoryWriter`. + + Any write method will throw ``std::runtime_error`` if the output doesn't fit + into the array. + + You can use one of the following typedefs for common character types: + + +--------------+---------------------------+ + | Type | Definition | + +==============+===========================+ + | ArrayWriter | BasicArrayWriter | + +--------------+---------------------------+ + | WArrayWriter | BasicArrayWriter | + +--------------+---------------------------+ + \endrst + */ +template +class BasicArrayWriter : public BasicWriter { + private: + internal::FixedBuffer buffer_; + + public: + /** + \rst + Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the + given size. + \endrst + */ + BasicArrayWriter(Char *array, std::size_t size) + : BasicWriter(buffer_), buffer_(array, size) {} + + // FIXME: this is temporary undocumented due to a bug in Sphinx + /* + \rst + Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the + size known at compile time. + \endrst + */ + template + explicit BasicArrayWriter(Char (&array)[SIZE]) + : BasicWriter(buffer_), buffer_(array, SIZE) {} +}; + +typedef BasicArrayWriter ArrayWriter; +typedef BasicArrayWriter WArrayWriter; + +// Formats a value. +template +void format(BasicFormatter &f, const Char *&format_str, const T &value) { + std::basic_ostringstream os; + os << value; + internal::Arg arg; + internal::Value &arg_value = arg; + std::basic_string str = os.str(); + arg_value = internal::MakeValue(str); + arg.type = static_cast( + internal::MakeValue::type(str)); + format_str = f.format(format_str, arg); +} + +// Reports a system error without throwing an exception. +// Can be used to report errors from destructors. +void report_system_error(int error_code, StringRef message) FMT_NOEXCEPT; + +#ifdef _WIN32 + +/** A Windows error. */ +class WindowsError : public SystemError { + private: + void init(int error_code, StringRef format_str, ArgList args); + + public: + /** + \rst + Constructs a :class:`fmt::WindowsError` object with the description + of the form + + .. parsed-literal:: + **: ** + + where ** is the formatted message and ** is the + system message corresponding to the error code. + *error_code* is a Windows error code as given by ``GetLastError``. + If *error_code* is not a valid error code such as -1, the system message + will look like "error -1". + + **Example**:: + + // This throws a WindowsError with the description + // cannot open file 'madeup': The system cannot find the file specified. + // or similar (system message may vary). + const char *filename = "madeup"; + LPOFSTRUCT of = LPOFSTRUCT(); + HFILE file = OpenFile(filename, &of, OF_READ); + if (file == HFILE_ERROR) { + throw fmt::WindowsError(GetLastError(), + "cannot open file '{}'", filename); + } + \endrst + */ + WindowsError(int error_code, StringRef message) { + init(error_code, message, ArgList()); + } + FMT_VARIADIC_CTOR(WindowsError, init, int, StringRef) +}; + +// Reports a Windows error without throwing an exception. +// Can be used to report errors from destructors. +void report_windows_error(int error_code, StringRef message) FMT_NOEXCEPT; + +#endif + +enum Color { BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE }; + +/** + Formats a string and prints it to stdout using ANSI escape sequences + to specify color (experimental). + Example: + PrintColored(fmt::RED, "Elapsed time: {0:.2f} seconds") << 1.23; + */ +void print_colored(Color c, StringRef format, ArgList args); + +/** + \rst + Formats arguments and returns the result as a string. + + **Example**:: + + std::string message = format("The answer is {}", 42); + \endrst +*/ +inline std::string format(StringRef format_str, ArgList args) { + MemoryWriter w; + w.write(format_str, args); + return w.str(); +} + +inline std::wstring format(WStringRef format_str, ArgList args) { + WMemoryWriter w; + w.write(format_str, args); + return w.str(); +} + +/** + \rst + Prints formatted data to the file *f*. + + **Example**:: + + print(stderr, "Don't {}!", "panic"); + \endrst + */ +void print(std::FILE *f, StringRef format_str, ArgList args); + +/** + \rst + Prints formatted data to ``stdout``. + + **Example**:: + + print("Elapsed time: {0:.2f} seconds", 1.23); + \endrst + */ +void print(StringRef format_str, ArgList args); + +/** + \rst + Prints formatted data to the stream *os*. + + **Example**:: + + print(cerr, "Don't {}!", "panic"); + \endrst + */ +void print(std::ostream &os, StringRef format_str, ArgList args); + +template +void printf(BasicWriter &w, BasicStringRef format, ArgList args) { + internal::PrintfFormatter().format(w, format, args); +} + +/** + \rst + Formats arguments and returns the result as a string. + + **Example**:: + + std::string message = fmt::sprintf("The answer is %d", 42); + \endrst +*/ +inline std::string sprintf(StringRef format, ArgList args) { + MemoryWriter w; + printf(w, format, args); + return w.str(); +} + +/** + \rst + Prints formatted data to the file *f*. + + **Example**:: + + fmt::fprintf(stderr, "Don't %s!", "panic"); + \endrst + */ +int fprintf(std::FILE *f, StringRef format, ArgList args); + +/** + \rst + Prints formatted data to ``stdout``. + + **Example**:: + + fmt::printf("Elapsed time: %.2f seconds", 1.23); + \endrst + */ +inline int printf(StringRef format, ArgList args) { + return fprintf(stdout, format, args); +} + +/** + Fast integer formatter. + */ +class FormatInt { + private: + // Buffer should be large enough to hold all digits (digits10 + 1), + // a sign and a null character. + enum {BUFFER_SIZE = std::numeric_limits::digits10 + 3}; + mutable char buffer_[BUFFER_SIZE]; + char *str_; + + // Formats value in reverse and returns the number of digits. + char *format_decimal(ULongLong value) { + char *buffer_end = buffer_ + BUFFER_SIZE - 1; + while (value >= 100) { + // Integer division is slow so do it for a group of two digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + unsigned index = (value % 100) * 2; + value /= 100; + *--buffer_end = internal::Data::DIGITS[index + 1]; + *--buffer_end = internal::Data::DIGITS[index]; + } + if (value < 10) { + *--buffer_end = static_cast('0' + value); + return buffer_end; + } + unsigned index = static_cast(value * 2); + *--buffer_end = internal::Data::DIGITS[index + 1]; + *--buffer_end = internal::Data::DIGITS[index]; + return buffer_end; + } + + void FormatSigned(LongLong value) { + ULongLong abs_value = static_cast(value); + bool negative = value < 0; + if (negative) + abs_value = 0 - abs_value; + str_ = format_decimal(abs_value); + if (negative) + *--str_ = '-'; + } + + public: + explicit FormatInt(int value) { FormatSigned(value); } + explicit FormatInt(long value) { FormatSigned(value); } + explicit FormatInt(LongLong value) { FormatSigned(value); } + explicit FormatInt(unsigned value) : str_(format_decimal(value)) {} + explicit FormatInt(unsigned long value) : str_(format_decimal(value)) {} + explicit FormatInt(ULongLong value) : str_(format_decimal(value)) {} + + /** + Returns the number of characters written to the output buffer. + */ + std::size_t size() const { return buffer_ - str_ + BUFFER_SIZE - 1; } + + /** + Returns a pointer to the output buffer content. No terminating null + character is appended. + */ + const char *data() const { return str_; } + + /** + Returns a pointer to the output buffer content with terminating null + character appended. + */ + const char *c_str() const { + buffer_[BUFFER_SIZE - 1] = '\0'; + return str_; + } + + /** + Returns the content of the output buffer as an `std::string`. + */ + std::string str() const { return std::string(str_, size()); } +}; + +// Formats a decimal integer value writing into buffer and returns +// a pointer to the end of the formatted string. This function doesn't +// write a terminating null character. +template +inline void format_decimal(char *&buffer, T value) { + typename internal::IntTraits::MainType abs_value = value; + if (internal::is_negative(value)) { + *buffer++ = '-'; + abs_value = 0 - abs_value; + } + if (abs_value < 100) { + if (abs_value < 10) { + *buffer++ = static_cast('0' + abs_value); + return; + } + unsigned index = static_cast(abs_value * 2); + *buffer++ = internal::Data::DIGITS[index]; + *buffer++ = internal::Data::DIGITS[index + 1]; + return; + } + unsigned num_digits = internal::count_digits(abs_value); + internal::format_decimal(buffer, abs_value, num_digits); + buffer += num_digits; +} +} + +#if FMT_GCC_VERSION +// Use the system_header pragma to suppress warnings about variadic macros +// because suppressing -Wvariadic-macros with the diagnostic pragma doesn't +// work. It is used at the end because we want to suppress as little warnings +// as possible. +# pragma GCC system_header +#endif + +// This is used to work around VC++ bugs in handling variadic macros. +#define FMT_EXPAND(args) args + +// Returns the number of arguments. +// Based on https://groups.google.com/forum/#!topic/comp.std.c/d-6Mj5Lko_s. +#define FMT_NARG(...) FMT_NARG_(__VA_ARGS__, FMT_RSEQ_N()) +#define FMT_NARG_(...) FMT_EXPAND(FMT_ARG_N(__VA_ARGS__)) +#define FMT_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N +#define FMT_RSEQ_N() 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 + +#define FMT_CONCAT(a, b) a##b +#define FMT_FOR_EACH_(N, f, ...) \ + FMT_EXPAND(FMT_CONCAT(FMT_FOR_EACH, N)(f, __VA_ARGS__)) +#define FMT_FOR_EACH(f, ...) \ + FMT_EXPAND(FMT_FOR_EACH_(FMT_NARG(__VA_ARGS__), f, __VA_ARGS__)) + +#define FMT_ADD_ARG_NAME(type, index) type arg##index +#define FMT_GET_ARG_NAME(type, index) arg##index + +#if FMT_USE_VARIADIC_TEMPLATES +# define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \ + template \ + ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ + const Args & ... args) { \ + using fmt::internal::Value; \ + const Value values[fmt::internal::NonZero::VALUE] = { \ + fmt::internal::MakeValue(args)... \ + }; \ + call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList( \ + fmt::internal::make_type(args...), values)); \ + } +#else +// Defines a wrapper for a function taking __VA_ARGS__ arguments +// and n additional arguments of arbitrary types. +# define FMT_WRAP(Char, ReturnType, func, call, n, ...) \ + template \ + inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ + FMT_GEN(n, FMT_MAKE_ARG)) { \ + const fmt::internal::Value vals[] = {FMT_GEN(n, FMT_MAKE_REF_##Char)}; \ + call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList( \ + fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), vals)); \ + } + +# define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \ + inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) { \ + call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList()); \ + } \ + FMT_WRAP(Char, ReturnType, func, call, 1, __VA_ARGS__) \ + FMT_WRAP(Char, ReturnType, func, call, 2, __VA_ARGS__) \ + FMT_WRAP(Char, ReturnType, func, call, 3, __VA_ARGS__) \ + FMT_WRAP(Char, ReturnType, func, call, 4, __VA_ARGS__) \ + FMT_WRAP(Char, ReturnType, func, call, 5, __VA_ARGS__) \ + FMT_WRAP(Char, ReturnType, func, call, 6, __VA_ARGS__) \ + FMT_WRAP(Char, ReturnType, func, call, 7, __VA_ARGS__) \ + FMT_WRAP(Char, ReturnType, func, call, 8, __VA_ARGS__) \ + FMT_WRAP(Char, ReturnType, func, call, 9, __VA_ARGS__) \ + FMT_WRAP(Char, ReturnType, func, call, 10, __VA_ARGS__) \ + FMT_WRAP(Char, ReturnType, func, call, 11, __VA_ARGS__) \ + FMT_WRAP(Char, ReturnType, func, call, 12, __VA_ARGS__) \ + FMT_WRAP(Char, ReturnType, func, call, 13, __VA_ARGS__) \ + FMT_WRAP(Char, ReturnType, func, call, 14, __VA_ARGS__) \ + FMT_WRAP(Char, ReturnType, func, call, 15, __VA_ARGS__) +#endif // FMT_USE_VARIADIC_TEMPLATES + +/** + \rst + Defines a variadic function with the specified return type, function name + and argument types passed as variable arguments to this macro. + + **Example**:: + + void print_error(const char *file, int line, const char *format, + fmt::ArgList args) { + fmt::print("{}: {}: ", file, line); + fmt::print(format, args); + } + FMT_VARIADIC(void, print_error, const char *, int, const char *) + + ``FMT_VARIADIC`` is used for compatibility with legacy C++ compilers that + don't implement variadic templates. You don't have to use this macro if + you don't need legacy compiler support and can use variadic templates + directly:: + + template + void print_error(const char *file, int line, const char *format, + const Args & ... args) { + fmt::print("{}: {}: ", file, line); + fmt::print(format, args...); + } + \endrst + */ +#define FMT_VARIADIC(ReturnType, func, ...) \ + FMT_VARIADIC_(char, ReturnType, func, return func, __VA_ARGS__) + +#define FMT_VARIADIC_W(ReturnType, func, ...) \ + FMT_VARIADIC_(wchar_t, ReturnType, func, return func, __VA_ARGS__) + +namespace fmt { +FMT_VARIADIC(std::string, format, StringRef) +FMT_VARIADIC_W(std::wstring, format, WStringRef) +FMT_VARIADIC(void, print, StringRef) +FMT_VARIADIC(void, print, std::FILE *, StringRef) +FMT_VARIADIC(void, print, std::ostream &, StringRef) +FMT_VARIADIC(void, print_colored, Color, StringRef) +FMT_VARIADIC(std::string, sprintf, StringRef) +FMT_VARIADIC(int, printf, StringRef) +FMT_VARIADIC(int, fprintf, std::FILE *, StringRef) +} + +// Restore warnings. +#if FMT_GCC_VERSION >= 406 +# pragma GCC diagnostic pop +#endif + +#ifdef __clang__ +# pragma clang diagnostic pop +#endif + +#ifdef FMT_HEADER_ONLY +# include "format.cc" +#endif + +#endif // FMT_FORMAT_H_ diff --git a/lib/cppformat/format.vcxproj b/lib/cppformat/format.vcxproj new file mode 100644 index 00000000..64e3a81c --- /dev/null +++ b/lib/cppformat/format.vcxproj @@ -0,0 +1,100 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17} + Win32Proj + Win32 + libformat + 8.1 + libformat + + + + StaticLibrary + MultiByte + v140_xp + + + + + + + + + + <_ProjectFileVersion>10.0.20506.1 + $(SolutionDir)src\bin\$(Platform)\$(Configuration)-v$(PlatformToolsetVersion)\ + $(SolutionDir)src\obj\$(Platform)\$(Configuration)-v$(PlatformToolsetVersion)\$(ProjectName)\ + + + + EnableFastChecks + CompileAsCpp + Sync + MultiThreadedDebug + true + Level3 + WIN32;_WINDOWS;_DEBUG;FMT_USE_FILE_DESCRIPTORS=1;GTEST_LANG_CXX11=0;%(PreprocessorDefinitions) + Disabled + + + + + EnableFastChecks + CompileAsCpp + Sync + MultiThreadedDebug + true + Level3 + WIN32;_WINDOWS;_DEBUG;FMT_USE_FILE_DESCRIPTORS=1;GTEST_LANG_CXX11=0;%(PreprocessorDefinitions) + Disabled + + + + + CompileAsCpp + Sync + MultiThreaded + true + Level3 + WIN32;_WINDOWS;NDEBUG;FMT_USE_FILE_DESCRIPTORS=1;GTEST_LANG_CXX11=0;%(PreprocessorDefinitions) + + + + + CompileAsCpp + Sync + MultiThreaded + true + Level3 + WIN32;_WINDOWS;NDEBUG;FMT_USE_FILE_DESCRIPTORS=1;GTEST_LANG_CXX11=0;%(PreprocessorDefinitions) + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/cppformat/format.vcxproj.filters b/lib/cppformat/format.vcxproj.filters new file mode 100644 index 00000000..7d1e3d30 --- /dev/null +++ b/lib/cppformat/format.vcxproj.filters @@ -0,0 +1,27 @@ + + + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + + + {915FED9B-B1C3-4F90-BF61-CF9EE0706F01} + + + {FB559997-0E66-467B-B839-27310F735431} + + + \ No newline at end of file diff --git a/lib/cppformat/posix.cc b/lib/cppformat/posix.cc new file mode 100644 index 00000000..4c086af6 --- /dev/null +++ b/lib/cppformat/posix.cc @@ -0,0 +1,242 @@ +/* + A C++ interface to POSIX functions. + + Copyright (c) 2014 - 2015, Victor Zverovich + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Disable bogus MSVC warnings. +#ifndef _CRT_SECURE_NO_WARNINGS +# define _CRT_SECURE_NO_WARNINGS +#endif + +#include "posix.h" + +#include +#include +#include + +#ifndef _WIN32 +# include +#else +# include +# include + +# define O_CREAT _O_CREAT +# define O_TRUNC _O_TRUNC + +#ifndef S_IRUSR +# define S_IRUSR _S_IREAD +#endif + +#ifndef S_IWUSR +# define S_IWUSR _S_IWRITE +#endif + +# ifdef __MINGW32__ +# define _SH_DENYNO 0x40 +# endif + +#endif // _WIN32 + +namespace { +#ifdef _WIN32 +// Return type of read and write functions. +typedef int RWResult; + +// On Windows the count argument to read and write is unsigned, so convert +// it from size_t preventing integer overflow. +inline unsigned convert_rwcount(std::size_t count) { + return count <= UINT_MAX ? static_cast(count) : UINT_MAX; +} +#else +// Return type of read and write functions. +typedef ssize_t RWResult; + +inline std::size_t convert_rwcount(std::size_t count) { return count; } +#endif +} + +fmt::BufferedFile::~BufferedFile() FMT_NOEXCEPT { + if (file_ && FMT_SYSTEM(fclose(file_)) != 0) + fmt::report_system_error(errno, "cannot close file"); +} + +fmt::BufferedFile::BufferedFile(fmt::StringRef filename, fmt::StringRef mode) { + FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())), 0); + if (!file_) + throw SystemError(errno, "cannot open file {}", filename); +} + +void fmt::BufferedFile::close() { + if (!file_) + return; + int result = FMT_SYSTEM(fclose(file_)); + file_ = 0; + if (result != 0) + throw SystemError(errno, "cannot close file"); +} + +int fmt::BufferedFile::fileno() const { + int fd = FMT_POSIX_CALL(fileno(file_)); + if (fd == -1) + throw SystemError(errno, "cannot get file descriptor"); + return fd; +} + +fmt::File::File(fmt::StringRef path, int oflag) { + int mode = S_IRUSR | S_IWUSR; +#ifdef _WIN32 + fd_ = -1; + FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode)); +#else + FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode))); +#endif + if (fd_ == -1) + throw SystemError(errno, "cannot open file {}", path); +} + +fmt::File::~File() FMT_NOEXCEPT { + // Don't retry close in case of EINTR! + // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html + if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0) + fmt::report_system_error(errno, "cannot close file"); +} + +void fmt::File::close() { + if (fd_ == -1) + return; + // Don't retry close in case of EINTR! + // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html + int result = FMT_POSIX_CALL(close(fd_)); + fd_ = -1; + if (result != 0) + throw SystemError(errno, "cannot close file"); +} + +fmt::LongLong fmt::File::size() const { +#ifdef _WIN32 + LARGE_INTEGER filesize = {}; + HANDLE handle = reinterpret_cast(_get_osfhandle(fd_)); + if (!FMT_SYSTEM(GetFileSizeEx(handle, &filesize))) + throw WindowsError(GetLastError(), "cannot get file size"); + FMT_STATIC_ASSERT(sizeof(fmt::LongLong) >= sizeof(filesize.QuadPart), + "return type of File::size is not large enough"); + return filesize.QuadPart; +#else + typedef struct stat Stat; + Stat file_stat = Stat(); + if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1) + throw SystemError(errno, "cannot get file attributes"); + FMT_STATIC_ASSERT(sizeof(fmt::LongLong) >= sizeof(file_stat.st_size), + "return type of File::size is not large enough"); + return file_stat.st_size; +#endif +} + +std::size_t fmt::File::read(void *buffer, std::size_t count) { + RWResult result = 0; + FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count)))); + if (result < 0) + throw SystemError(errno, "cannot read from file"); + return result; +} + +std::size_t fmt::File::write(const void *buffer, std::size_t count) { + RWResult result = 0; + FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count)))); + if (result < 0) + throw SystemError(errno, "cannot write to file"); + return result; +} + +fmt::File fmt::File::dup(int fd) { + // Don't retry as dup doesn't return EINTR. + // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html + int new_fd = FMT_POSIX_CALL(dup(fd)); + if (new_fd == -1) + throw SystemError(errno, "cannot duplicate file descriptor {}", fd); + return File(new_fd); +} + +void fmt::File::dup2(int fd) { + int result = 0; + FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd))); + if (result == -1) { + throw SystemError(errno, + "cannot duplicate file descriptor {} to {}", fd_, fd); + } +} + +void fmt::File::dup2(int fd, ErrorCode &ec) FMT_NOEXCEPT { + int result = 0; + FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd))); + if (result == -1) + ec = ErrorCode(errno); +} + +void fmt::File::pipe(File &read_end, File &write_end) { + // Close the descriptors first to make sure that assignments don't throw + // and there are no leaks. + read_end.close(); + write_end.close(); + int fds[2] = {}; +#ifdef _WIN32 + // Make the default pipe capacity same as on Linux 2.6.11+. + enum { DEFAULT_CAPACITY = 65536 }; + int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY)); +#else + // Don't retry as the pipe function doesn't return EINTR. + // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html + int result = FMT_POSIX_CALL(pipe(fds)); +#endif + if (result != 0) + throw SystemError(errno, "cannot create pipe"); + // The following assignments don't throw because read_fd and write_fd + // are closed. + read_end = File(fds[0]); + write_end = File(fds[1]); +} + +fmt::BufferedFile fmt::File::fdopen(const char *mode) { + // Don't retry as fdopen doesn't return EINTR. + FILE *f = FMT_POSIX_CALL(fdopen(fd_, mode)); + if (!f) + throw SystemError(errno, "cannot associate stream with file descriptor"); + BufferedFile file(f); + fd_ = -1; + return file; +} + +long fmt::getpagesize() { +#ifdef _WIN32 + SYSTEM_INFO si; + GetSystemInfo(&si); + return si.dwPageSize; +#else + long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE)); + if (size < 0) + throw SystemError(errno, "cannot get memory page size"); + return size; +#endif +} diff --git a/lib/cppformat/posix.h b/lib/cppformat/posix.h new file mode 100644 index 00000000..e16ac521 --- /dev/null +++ b/lib/cppformat/posix.h @@ -0,0 +1,337 @@ +/* + A C++ interface to POSIX functions. + + Copyright (c) 2014 - 2015, Victor Zverovich + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef FMT_POSIX_H_ +#define FMT_POSIX_H_ + +#include +#include // for O_RDONLY +#include + +#include + +#include "format.h" + +#ifdef FMT_INCLUDE_POSIX_TEST +# include "test/posix-test.h" +#endif + +#ifndef FMT_POSIX +# ifdef _WIN32 +// Fix warnings about deprecated symbols. +# define FMT_POSIX(call) _##call +# else +# define FMT_POSIX(call) call +# endif +#endif + +// Calls to system functions are wrapped in FMT_SYSTEM for testability. +#ifdef FMT_SYSTEM +# define FMT_POSIX_CALL(call) FMT_SYSTEM(call) +#else +# define FMT_SYSTEM(call) call +# ifdef _WIN32 +// Fix warnings about deprecated symbols. +# define FMT_POSIX_CALL(call) ::_##call +# else +# define FMT_POSIX_CALL(call) ::call +# endif +#endif + +#if FMT_GCC_VERSION >= 407 +# define FMT_UNUSED __attribute__((unused)) +#else +# define FMT_UNUSED +#endif + +#if FMT_USE_STATIC_ASSERT || FMT_HAS_CPP_ATTRIBUTE(cxx_static_assert) || \ + (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1600 +# define FMT_STATIC_ASSERT(cond, message) static_assert(cond, message) +#else +# define FMT_CONCAT_(a, b) FMT_CONCAT(a, b) +# define FMT_STATIC_ASSERT(cond, message) \ + typedef int FMT_CONCAT_(Assert, __LINE__)[(cond) ? 1 : -1] FMT_UNUSED +#endif + +// Retries the expression while it evaluates to error_result and errno +// equals to EINTR. +#ifndef _WIN32 +# define FMT_RETRY_VAL(result, expression, error_result) \ + do { \ + result = (expression); \ + } while (result == error_result && errno == EINTR) +#else +# define FMT_RETRY_VAL(result, expression, error_result) result = (expression) +#endif + +#define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1) + +namespace fmt { + +// An error code. +class ErrorCode { + private: + int value_; + + public: + explicit ErrorCode(int value = 0) FMT_NOEXCEPT : value_(value) {} + + int get() const FMT_NOEXCEPT { return value_; } +}; + +// A buffered file. +class BufferedFile { + private: + FILE *file_; + + friend class File; + + explicit BufferedFile(FILE *f) : file_(f) {} + + public: + // Constructs a BufferedFile object which doesn't represent any file. + BufferedFile() FMT_NOEXCEPT : file_(0) {} + + // Destroys the object closing the file it represents if any. + ~BufferedFile() FMT_NOEXCEPT; + +#if !FMT_USE_RVALUE_REFERENCES + // Emulate a move constructor and a move assignment operator if rvalue + // references are not supported. + + private: + // A proxy object to emulate a move constructor. + // It is private to make it impossible call operator Proxy directly. + struct Proxy { + FILE *file; + }; + +public: + // A "move constructor" for moving from a temporary. + BufferedFile(Proxy p) FMT_NOEXCEPT : file_(p.file) {} + + // A "move constructor" for for moving from an lvalue. + BufferedFile(BufferedFile &f) FMT_NOEXCEPT : file_(f.file_) { + f.file_ = 0; + } + + // A "move assignment operator" for moving from a temporary. + BufferedFile &operator=(Proxy p) { + close(); + file_ = p.file; + return *this; + } + + // A "move assignment operator" for moving from an lvalue. + BufferedFile &operator=(BufferedFile &other) { + close(); + file_ = other.file_; + other.file_ = 0; + return *this; + } + + // Returns a proxy object for moving from a temporary: + // BufferedFile file = BufferedFile(...); + operator Proxy() FMT_NOEXCEPT { + Proxy p = {file_}; + file_ = 0; + return p; + } + +#else + private: + FMT_DISALLOW_COPY_AND_ASSIGN(BufferedFile); + + public: + BufferedFile(BufferedFile &&other) FMT_NOEXCEPT : file_(other.file_) { + other.file_ = 0; + } + + BufferedFile& operator=(BufferedFile &&other) { + close(); + file_ = other.file_; + other.file_ = 0; + return *this; + } +#endif + + // Opens a file. + BufferedFile(fmt::StringRef filename, fmt::StringRef mode); + + // Closes the file. + void close(); + + // Returns the pointer to a FILE object representing this file. + FILE *get() const FMT_NOEXCEPT { return file_; } + + int fileno() const; + + void print(fmt::StringRef format_str, const ArgList &args) { + fmt::print(file_, format_str, args); + } + FMT_VARIADIC(void, print, fmt::StringRef) +}; + +// A file. Closed file is represented by a File object with descriptor -1. +// Methods that are not declared with FMT_NOEXCEPT may throw +// fmt::SystemError in case of failure. Note that some errors such as +// closing the file multiple times will cause a crash on Windows rather +// than an exception. You can get standard behavior by overriding the +// invalid parameter handler with _set_invalid_parameter_handler. +class File { + private: + int fd_; // File descriptor. + + // Constructs a File object with a given descriptor. + explicit File(int fd) : fd_(fd) {} + + public: + // Possible values for the oflag argument to the constructor. + enum { + RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only. + WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only. + RDWR = FMT_POSIX(O_RDWR) // Open for reading and writing. + }; + + // Constructs a File object which doesn't represent any file. + File() FMT_NOEXCEPT : fd_(-1) {} + + // Opens a file and constructs a File object representing this file. + File(fmt::StringRef path, int oflag); + +#if !FMT_USE_RVALUE_REFERENCES + // Emulate a move constructor and a move assignment operator if rvalue + // references are not supported. + + private: + // A proxy object to emulate a move constructor. + // It is private to make it impossible call operator Proxy directly. + struct Proxy { + int fd; + }; + + public: + // A "move constructor" for moving from a temporary. + File(Proxy p) FMT_NOEXCEPT : fd_(p.fd) {} + + // A "move constructor" for for moving from an lvalue. + File(File &other) FMT_NOEXCEPT : fd_(other.fd_) { + other.fd_ = -1; + } + + // A "move assignment operator" for moving from a temporary. + File &operator=(Proxy p) { + close(); + fd_ = p.fd; + return *this; + } + + // A "move assignment operator" for moving from an lvalue. + File &operator=(File &other) { + close(); + fd_ = other.fd_; + other.fd_ = -1; + return *this; + } + + // Returns a proxy object for moving from a temporary: + // File file = File(...); + operator Proxy() FMT_NOEXCEPT { + Proxy p = {fd_}; + fd_ = -1; + return p; + } + +#else + private: + FMT_DISALLOW_COPY_AND_ASSIGN(File); + + public: + File(File &&other) FMT_NOEXCEPT : fd_(other.fd_) { + other.fd_ = -1; + } + + File& operator=(File &&other) { + close(); + fd_ = other.fd_; + other.fd_ = -1; + return *this; + } +#endif + + // Destroys the object closing the file it represents if any. + ~File() FMT_NOEXCEPT; + + // Returns the file descriptor. + int descriptor() const FMT_NOEXCEPT { return fd_; } + + // Closes the file. + void close(); + + // Returns the file size. + fmt::LongLong size() const; + + // Attempts to read count bytes from the file into the specified buffer. + std::size_t read(void *buffer, std::size_t count); + + // Attempts to write count bytes from the specified buffer to the file. + std::size_t write(const void *buffer, std::size_t count); + + // Duplicates a file descriptor with the dup function and returns + // the duplicate as a file object. + static File dup(int fd); + + // Makes fd be the copy of this file descriptor, closing fd first if + // necessary. + void dup2(int fd); + + // Makes fd be the copy of this file descriptor, closing fd first if + // necessary. + void dup2(int fd, ErrorCode &ec) FMT_NOEXCEPT; + + // Creates a pipe setting up read_end and write_end file objects for reading + // and writing respectively. + static void pipe(File &read_end, File &write_end); + + // Creates a BufferedFile object associated with this file and detaches + // this File object from the file. + BufferedFile fdopen(const char *mode); +}; + +// Returns the memory page size. +long getpagesize(); +} // namespace fmt + +#if !FMT_USE_RVALUE_REFERENCES +namespace std { +// For compatibility with C++98. +inline fmt::BufferedFile &move(fmt::BufferedFile &f) { return f; } +inline fmt::File &move(fmt::File &f) { return f; } +} +#endif + +#endif // FMT_POSIX_H_ diff --git a/lib/dbghelp/include/DbgHelp.h b/lib/dbghelp/include/DbgHelp.h new file mode 100644 index 00000000..cfd863b7 --- /dev/null +++ b/lib/dbghelp/include/DbgHelp.h @@ -0,0 +1,4594 @@ +/*++ BUILD Version: 0000 Increment this if a change has global effects + +Copyright (c) Microsoft Corporation. All rights reserved. + +Module Name: + + dbghelp.h + +Abstract: + + This module defines the prototypes and constants required for the image + help routines. + + Contains debugging support routines that are redistributable. + +Revision History: + +--*/ + +#ifndef _DBGHELP_ +#define _DBGHELP_ + +#if _MSC_VER > 1020 +#pragma once +#endif + + +// As a general principal always call the 64 bit version +// of every API, if a choice exists. The 64 bit version +// works great on 32 bit platforms, and is forward +// compatible to 64 bit platforms. + +#ifdef _WIN64 +#ifndef _IMAGEHLP64 +#define _IMAGEHLP64 +#endif +#endif + +#include + +// For those without specstrings.h +// Since there are different versions of this header, I need to +// individually test each item and define it if it is not around. + +#ifndef __in + #define __in +#endif +#ifndef __out + #define __out +#endif +#ifndef __inout + #define __inout +#endif +#ifndef __in_opt + #define __in_opt +#endif +#ifndef __out_opt + #define __out_opt +#endif +#ifndef __inout_opt + #define __inout_opt +#endif +#ifndef __in_ecount + #define __in_ecount(x) +#endif +#ifndef __out_ecount + #define __out_ecount(x) +#endif +#ifndef __inout_ecount + #define __inout_ecount(x) +#endif +#ifndef __in_bcount + #define __in_bcount(x) +#endif +#ifndef __out_bcount + #define __out_bcount(x) +#endif +#ifndef __inout_bcount + #define __inout_bcount(x) +#endif +#ifndef __out_xcount + #define __out_xcount(x) +#endif +#ifndef __deref_opt_out + #define __deref_opt_out +#endif +#ifndef __deref_out + #define __deref_out +#endif +#ifndef __out_ecount_opt + #define __out_ecount_opt(x) +#endif +#ifndef __in_bcount_opt + #define __in_bcount_opt(x) +#endif +#ifndef __out_bcount_opt + #define __out_bcount_opt(x) +#endif +#ifndef __deref_out_opt + #define __deref_out_opt +#endif + + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef _IMAGEHLP_SOURCE_ + #define IMAGEAPI __stdcall + #define DBHLP_DEPRECIATED +#else + #define IMAGEAPI DECLSPEC_IMPORT __stdcall + #if (_MSC_VER >= 1300) && !defined(MIDL_PASS) + #define DBHLP_DEPRECIATED __declspec(deprecated) + #else + #define DBHLP_DEPRECIATED + #endif +#endif + +#define DBHLPAPI IMAGEAPI + +#define IMAGE_SEPARATION (64*1024) + +// Observant readers may notice that 2 new fields, +// 'fReadOnly' and 'Version' have been added to +// the LOADED_IMAGE structure after 'fDOSImage'. +// This does not change the size of the structure +// from previous headers. That is because while +// 'fDOSImage' is a byte, it is padded by the +// compiler to 4 bytes. So the 2 new fields are +// slipped into the extra space. + +typedef struct _LOADED_IMAGE { + PSTR ModuleName; + HANDLE hFile; + PUCHAR MappedAddress; +#ifdef _IMAGEHLP64 + PIMAGE_NT_HEADERS64 FileHeader; +#else + PIMAGE_NT_HEADERS32 FileHeader; +#endif + PIMAGE_SECTION_HEADER LastRvaSection; + ULONG NumberOfSections; + PIMAGE_SECTION_HEADER Sections; + ULONG Characteristics; + BOOLEAN fSystemImage; + BOOLEAN fDOSImage; + BOOLEAN fReadOnly; + UCHAR Version; + LIST_ENTRY Links; + ULONG SizeOfImage; +} LOADED_IMAGE, *PLOADED_IMAGE; + +#define MAX_SYM_NAME 2000 + + +// Error codes set by dbghelp functions. Call GetLastError +// to see them. +// Dbghelp also sets error codes found in winerror.h + +#define ERROR_IMAGE_NOT_STRIPPED 0x8800 // the image is not stripped. No dbg file available. +#define ERROR_NO_DBG_POINTER 0x8801 // image is stripped but there is no pointer to a dbg file +#define ERROR_NO_PDB_POINTER 0x8802 // image does not point to a pdb file + +typedef BOOL +(CALLBACK *PFIND_DEBUG_FILE_CALLBACK)( + __in HANDLE FileHandle, + __in PCSTR FileName, + __in PVOID CallerData + ); + +HANDLE +IMAGEAPI +SymFindDebugInfoFile( + __in HANDLE hProcess, + __in PCSTR FileName, + __out_ecount(MAX_PATH + 1) PSTR DebugFilePath, + __in_opt PFIND_DEBUG_FILE_CALLBACK Callback, + __in_opt PVOID CallerData + ); + +typedef BOOL +(CALLBACK *PFIND_DEBUG_FILE_CALLBACKW)( + __in HANDLE FileHandle, + __in PCWSTR FileName, + __in PVOID CallerData + ); + +HANDLE +IMAGEAPI +SymFindDebugInfoFileW( + __in HANDLE hProcess, + __in PCWSTR FileName, + __out_ecount(MAX_PATH + 1) PWSTR DebugFilePath, + __in_opt PFIND_DEBUG_FILE_CALLBACKW Callback, + __in_opt PVOID CallerData + ); + +HANDLE +IMAGEAPI +FindDebugInfoFile ( + __in PCSTR FileName, + __in PCSTR SymbolPath, + __out_ecount(MAX_PATH + 1) PSTR DebugFilePath + ); + +HANDLE +IMAGEAPI +FindDebugInfoFileEx ( + __in PCSTR FileName, + __in PCSTR SymbolPath, + __out_ecount(MAX_PATH + 1) PSTR DebugFilePath, + __in_opt PFIND_DEBUG_FILE_CALLBACK Callback, + __in_opt PVOID CallerData + ); + +HANDLE +IMAGEAPI +FindDebugInfoFileExW ( + __in PCWSTR FileName, + __in PCWSTR SymbolPath, + __out_ecount(MAX_PATH + 1) PWSTR DebugFilePath, + __in_opt PFIND_DEBUG_FILE_CALLBACKW Callback, + __in_opt PVOID CallerData + ); + +typedef BOOL +(CALLBACK *PFINDFILEINPATHCALLBACK)( + __in PCSTR filename, + __in PVOID context + ); + +BOOL +IMAGEAPI +SymFindFileInPath( + __in HANDLE hprocess, + __in_opt PCSTR SearchPath, + __in PCSTR FileName, + __in_opt PVOID id, + __in DWORD two, + __in DWORD three, + __in DWORD flags, + __out_ecount(MAX_PATH + 1) PSTR FoundFile, + __in_opt PFINDFILEINPATHCALLBACK callback, + __in_opt PVOID context + ); + +typedef BOOL +(CALLBACK *PFINDFILEINPATHCALLBACKW)( + __in PCWSTR filename, + __in PVOID context + ); + +BOOL +IMAGEAPI +SymFindFileInPathW( + __in HANDLE hprocess, + __in_opt PCWSTR SearchPath, + __in PCWSTR FileName, + __in_opt PVOID id, + __in DWORD two, + __in DWORD three, + __in DWORD flags, + __out_ecount(MAX_PATH + 1) PWSTR FoundFile, + __in_opt PFINDFILEINPATHCALLBACKW callback, + __in_opt PVOID context + ); + +typedef BOOL +(CALLBACK *PFIND_EXE_FILE_CALLBACK)( + __in HANDLE FileHandle, + __in PCSTR FileName, + __in_opt PVOID CallerData + ); + +HANDLE +IMAGEAPI +SymFindExecutableImage( + __in HANDLE hProcess, + __in PCSTR FileName, + __out_ecount(MAX_PATH + 1) PSTR ImageFilePath, + __in PFIND_EXE_FILE_CALLBACK Callback, + __in PVOID CallerData + ); + +typedef BOOL +(CALLBACK *PFIND_EXE_FILE_CALLBACKW)( + __in HANDLE FileHandle, + __in PCWSTR FileName, + __in_opt PVOID CallerData + ); + +HANDLE +IMAGEAPI +SymFindExecutableImageW( + __in HANDLE hProcess, + __in PCWSTR FileName, + __out_ecount(MAX_PATH + 1) PWSTR ImageFilePath, + __in PFIND_EXE_FILE_CALLBACKW Callback, + __in PVOID CallerData + ); + +HANDLE +IMAGEAPI +FindExecutableImage( + __in PCSTR FileName, + __in PCSTR SymbolPath, + __out_ecount(MAX_PATH + 1) PSTR ImageFilePath + ); + +HANDLE +IMAGEAPI +FindExecutableImageEx( + __in PCSTR FileName, + __in PCSTR SymbolPath, + __out_ecount(MAX_PATH + 1) PSTR ImageFilePath, + __in_opt PFIND_EXE_FILE_CALLBACK Callback, + __in_opt PVOID CallerData + ); + +HANDLE +IMAGEAPI +FindExecutableImageExW( + __in PCWSTR FileName, + __in PCWSTR SymbolPath, + __out_ecount(MAX_PATH + 1) PWSTR ImageFilePath, + __in_opt PFIND_EXE_FILE_CALLBACKW Callback, + __in PVOID CallerData + ); + +PIMAGE_NT_HEADERS +IMAGEAPI +ImageNtHeader ( + __in PVOID Base + ); + +PVOID +IMAGEAPI +ImageDirectoryEntryToDataEx ( + __in PVOID Base, + __in BOOLEAN MappedAsImage, + __in USHORT DirectoryEntry, + __out PULONG Size, + __out_opt PIMAGE_SECTION_HEADER *FoundHeader + ); + +PVOID +IMAGEAPI +ImageDirectoryEntryToData ( + __in PVOID Base, + __in BOOLEAN MappedAsImage, + __in USHORT DirectoryEntry, + __out PULONG Size + ); + +PIMAGE_SECTION_HEADER +IMAGEAPI +ImageRvaToSection( + __in PIMAGE_NT_HEADERS NtHeaders, + __in PVOID Base, + __in ULONG Rva + ); + +PVOID +IMAGEAPI +ImageRvaToVa( + __in PIMAGE_NT_HEADERS NtHeaders, + __in PVOID Base, + __in ULONG Rva, + __in_opt OUT PIMAGE_SECTION_HEADER *LastRvaSection + ); + +#ifndef _WIN64 +// This api won't be ported to Win64 - Fix your code. + +typedef struct _IMAGE_DEBUG_INFORMATION { + LIST_ENTRY List; + DWORD ReservedSize; + PVOID ReservedMappedBase; + USHORT ReservedMachine; + USHORT ReservedCharacteristics; + DWORD ReservedCheckSum; + DWORD ImageBase; + DWORD SizeOfImage; + + DWORD ReservedNumberOfSections; + PIMAGE_SECTION_HEADER ReservedSections; + + DWORD ReservedExportedNamesSize; + PSTR ReservedExportedNames; + + DWORD ReservedNumberOfFunctionTableEntries; + PIMAGE_FUNCTION_ENTRY ReservedFunctionTableEntries; + DWORD ReservedLowestFunctionStartingAddress; + DWORD ReservedHighestFunctionEndingAddress; + + DWORD ReservedNumberOfFpoTableEntries; + PFPO_DATA ReservedFpoTableEntries; + + DWORD SizeOfCoffSymbols; + PIMAGE_COFF_SYMBOLS_HEADER CoffSymbols; + + DWORD ReservedSizeOfCodeViewSymbols; + PVOID ReservedCodeViewSymbols; + + PSTR ImageFilePath; + PSTR ImageFileName; + PSTR ReservedDebugFilePath; + + DWORD ReservedTimeDateStamp; + + BOOL ReservedRomImage; + PIMAGE_DEBUG_DIRECTORY ReservedDebugDirectory; + DWORD ReservedNumberOfDebugDirectories; + + DWORD ReservedOriginalFunctionTableBaseAddress; + + DWORD Reserved[ 2 ]; + +} IMAGE_DEBUG_INFORMATION, *PIMAGE_DEBUG_INFORMATION; + + +PIMAGE_DEBUG_INFORMATION +IMAGEAPI +MapDebugInformation( + __in_opt HANDLE FileHandle, + __in PCSTR FileName, + __in_opt PCSTR SymbolPath, + __in ULONG ImageBase + ); + +BOOL +IMAGEAPI +UnmapDebugInformation( + __out_xcount(unknown) PIMAGE_DEBUG_INFORMATION DebugInfo + ); + +#endif + +BOOL +IMAGEAPI +SearchTreeForFile( + __in PCSTR RootPath, + __in PCSTR InputPathName, + __out_ecount(MAX_PATH + 1) PSTR OutputPathBuffer + ); + +BOOL +IMAGEAPI +SearchTreeForFileW( + __in PCWSTR RootPath, + __in PCWSTR InputPathName, + __out_ecount(MAX_PATH + 1) PWSTR OutputPathBuffer + ); + +typedef BOOL +(CALLBACK *PENUMDIRTREE_CALLBACK)( + __in PCSTR FilePath, + __in_opt PVOID CallerData + ); + +BOOL +IMAGEAPI +EnumDirTree( + __in_opt HANDLE hProcess, + __in PCSTR RootPath, + __in PCSTR InputPathName, + __out_ecount_opt(MAX_PATH + 1) PSTR OutputPathBuffer, + __in_opt PENUMDIRTREE_CALLBACK cb, + __in_opt PVOID data + ); + +typedef BOOL +(CALLBACK *PENUMDIRTREE_CALLBACKW)( + __in PCWSTR FilePath, + __in_opt PVOID CallerData + ); + +BOOL +IMAGEAPI +EnumDirTreeW( + __in_opt HANDLE hProcess, + __in PCWSTR RootPath, + __in PCWSTR InputPathName, + __out_ecount_opt(MAX_PATH + 1) PWSTR OutputPathBuffer, + __in_opt PENUMDIRTREE_CALLBACKW cb, + __in_opt PVOID data + ); + +BOOL +IMAGEAPI +MakeSureDirectoryPathExists( + __in PCSTR DirPath + ); + +// +// UnDecorateSymbolName Flags +// + +#define UNDNAME_COMPLETE (0x0000) // Enable full undecoration +#define UNDNAME_NO_LEADING_UNDERSCORES (0x0001) // Remove leading underscores from MS extended keywords +#define UNDNAME_NO_MS_KEYWORDS (0x0002) // Disable expansion of MS extended keywords +#define UNDNAME_NO_FUNCTION_RETURNS (0x0004) // Disable expansion of return type for primary declaration +#define UNDNAME_NO_ALLOCATION_MODEL (0x0008) // Disable expansion of the declaration model +#define UNDNAME_NO_ALLOCATION_LANGUAGE (0x0010) // Disable expansion of the declaration language specifier +#define UNDNAME_NO_MS_THISTYPE (0x0020) // NYI Disable expansion of MS keywords on the 'this' type for primary declaration +#define UNDNAME_NO_CV_THISTYPE (0x0040) // NYI Disable expansion of CV modifiers on the 'this' type for primary declaration +#define UNDNAME_NO_THISTYPE (0x0060) // Disable all modifiers on the 'this' type +#define UNDNAME_NO_ACCESS_SPECIFIERS (0x0080) // Disable expansion of access specifiers for members +#define UNDNAME_NO_THROW_SIGNATURES (0x0100) // Disable expansion of 'throw-signatures' for functions and pointers to functions +#define UNDNAME_NO_MEMBER_TYPE (0x0200) // Disable expansion of 'static' or 'virtual'ness of members +#define UNDNAME_NO_RETURN_UDT_MODEL (0x0400) // Disable expansion of MS model for UDT returns +#define UNDNAME_32_BIT_DECODE (0x0800) // Undecorate 32-bit decorated names +#define UNDNAME_NAME_ONLY (0x1000) // Crack only the name for primary declaration; + // return just [scope::]name. Does expand template params +#define UNDNAME_NO_ARGUMENTS (0x2000) // Don't undecorate arguments to function +#define UNDNAME_NO_SPECIAL_SYMS (0x4000) // Don't undecorate special names (v-table, vcall, vector xxx, metatype, etc) + +DWORD +IMAGEAPI +WINAPI +UnDecorateSymbolName( + __in PCSTR name, + __out_ecount(maxStringLength) PSTR outputString, + __in DWORD maxStringLength, + __in DWORD flags + ); + +DWORD +IMAGEAPI +WINAPI +UnDecorateSymbolNameW( + __in PCWSTR name, + __out_ecount(maxStringLength) PWSTR outputString, + __in DWORD maxStringLength, + __in DWORD flags + ); + +// +// these values are used for synthesized file types +// that can be passed in as image headers instead of +// the standard ones from ntimage.h +// + +#define DBHHEADER_DEBUGDIRS 0x1 +#define DBHHEADER_CVMISC 0x2 +#define DBHHEADER_PDBGUID 0x3 +typedef struct _MODLOAD_DATA { + DWORD ssize; // size of this struct + DWORD ssig; // signature identifying the passed data + PVOID data; // pointer to passed data + DWORD size; // size of passed data + DWORD flags; // options +} MODLOAD_DATA, *PMODLOAD_DATA; + +typedef struct _MODLOAD_CVMISC { + DWORD oCV; // ofset to the codeview record + size_t cCV; // size of the codeview record + DWORD oMisc; // offset to the misc record + size_t cMisc; // size of the misc record + DWORD dtImage; // datetime stamp of the image + DWORD cImage; // size of the image +} MODLOAD_CVMISC, *PMODLOAD_CVMISC; + +typedef struct _MODLOAD_PDBGUID_PDBAGE { + GUID PdbGuid; // Pdb Guid + DWORD PdbAge; // Pdb Age +} MODLOAD_PDBGUID_PDBAGE, *PMODLOAD_PDBGUID_PDBAGE; + +// +// StackWalking API +// + +typedef enum { + AddrMode1616, + AddrMode1632, + AddrModeReal, + AddrModeFlat +} ADDRESS_MODE; + +typedef struct _tagADDRESS64 { + DWORD64 Offset; + WORD Segment; + ADDRESS_MODE Mode; +} ADDRESS64, *LPADDRESS64; + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define ADDRESS ADDRESS64 +#define LPADDRESS LPADDRESS64 +#else +typedef struct _tagADDRESS { + DWORD Offset; + WORD Segment; + ADDRESS_MODE Mode; +} ADDRESS, *LPADDRESS; + +__inline +void +Address32To64( + __in LPADDRESS a32, + __out LPADDRESS64 a64 + ) +{ + a64->Offset = (ULONG64)(LONG64)(LONG)a32->Offset; + a64->Segment = a32->Segment; + a64->Mode = a32->Mode; +} + +__inline +void +Address64To32( + __in LPADDRESS64 a64, + __out LPADDRESS a32 + ) +{ + a32->Offset = (ULONG)a64->Offset; + a32->Segment = a64->Segment; + a32->Mode = a64->Mode; +} +#endif + +// +// This structure is included in the STACKFRAME structure, +// and is used to trace through usermode callbacks in a thread's +// kernel stack. The values must be copied by the kernel debugger +// from the DBGKD_GET_VERSION and WAIT_STATE_CHANGE packets. +// + +// +// New KDHELP structure for 64 bit system support. +// This structure is preferred in new code. +// +typedef struct _KDHELP64 { + + // + // address of kernel thread object, as provided in the + // WAIT_STATE_CHANGE packet. + // + DWORD64 Thread; + + // + // offset in thread object to pointer to the current callback frame + // in kernel stack. + // + DWORD ThCallbackStack; + + // + // offset in thread object to pointer to the current callback backing + // store frame in kernel stack. + // + DWORD ThCallbackBStore; + + // + // offsets to values in frame: + // + // address of next callback frame + DWORD NextCallback; + + // address of saved frame pointer (if applicable) + DWORD FramePointer; + + + // + // Address of the kernel function that calls out to user mode + // + DWORD64 KiCallUserMode; + + // + // Address of the user mode dispatcher function + // + DWORD64 KeUserCallbackDispatcher; + + // + // Lowest kernel mode address + // + DWORD64 SystemRangeStart; + + // + // Address of the user mode exception dispatcher function. + // Added in API version 10. + // + DWORD64 KiUserExceptionDispatcher; + + // + // Stack bounds, added in API version 11. + // + DWORD64 StackBase; + DWORD64 StackLimit; + + DWORD64 Reserved[5]; + +} KDHELP64, *PKDHELP64; + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define KDHELP KDHELP64 +#define PKDHELP PKDHELP64 +#else +typedef struct _KDHELP { + + // + // address of kernel thread object, as provided in the + // WAIT_STATE_CHANGE packet. + // + DWORD Thread; + + // + // offset in thread object to pointer to the current callback frame + // in kernel stack. + // + DWORD ThCallbackStack; + + // + // offsets to values in frame: + // + // address of next callback frame + DWORD NextCallback; + + // address of saved frame pointer (if applicable) + DWORD FramePointer; + + // + // Address of the kernel function that calls out to user mode + // + DWORD KiCallUserMode; + + // + // Address of the user mode dispatcher function + // + DWORD KeUserCallbackDispatcher; + + // + // Lowest kernel mode address + // + DWORD SystemRangeStart; + + // + // offset in thread object to pointer to the current callback backing + // store frame in kernel stack. + // + DWORD ThCallbackBStore; + + // + // Address of the user mode exception dispatcher function. + // Added in API version 10. + // + DWORD KiUserExceptionDispatcher; + + // + // Stack bounds, added in API version 11. + // + DWORD StackBase; + DWORD StackLimit; + + DWORD Reserved[5]; + +} KDHELP, *PKDHELP; + +__inline +void +KdHelp32To64( + __in PKDHELP p32, + __out PKDHELP64 p64 + ) +{ + p64->Thread = p32->Thread; + p64->ThCallbackStack = p32->ThCallbackStack; + p64->NextCallback = p32->NextCallback; + p64->FramePointer = p32->FramePointer; + p64->KiCallUserMode = p32->KiCallUserMode; + p64->KeUserCallbackDispatcher = p32->KeUserCallbackDispatcher; + p64->SystemRangeStart = p32->SystemRangeStart; + p64->KiUserExceptionDispatcher = p32->KiUserExceptionDispatcher; + p64->StackBase = p32->StackBase; + p64->StackLimit = p32->StackLimit; +} +#endif + +typedef struct _tagSTACKFRAME64 { + ADDRESS64 AddrPC; // program counter + ADDRESS64 AddrReturn; // return address + ADDRESS64 AddrFrame; // frame pointer + ADDRESS64 AddrStack; // stack pointer + ADDRESS64 AddrBStore; // backing store pointer + PVOID FuncTableEntry; // pointer to pdata/fpo or NULL + DWORD64 Params[4]; // possible arguments to the function + BOOL Far; // WOW far call + BOOL Virtual; // is this a virtual frame? + DWORD64 Reserved[3]; + KDHELP64 KdHelp; +} STACKFRAME64, *LPSTACKFRAME64; + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define STACKFRAME STACKFRAME64 +#define LPSTACKFRAME LPSTACKFRAME64 +#else +typedef struct _tagSTACKFRAME { + ADDRESS AddrPC; // program counter + ADDRESS AddrReturn; // return address + ADDRESS AddrFrame; // frame pointer + ADDRESS AddrStack; // stack pointer + PVOID FuncTableEntry; // pointer to pdata/fpo or NULL + DWORD Params[4]; // possible arguments to the function + BOOL Far; // WOW far call + BOOL Virtual; // is this a virtual frame? + DWORD Reserved[3]; + KDHELP KdHelp; + ADDRESS AddrBStore; // backing store pointer +} STACKFRAME, *LPSTACKFRAME; +#endif + + +typedef +BOOL +(__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)( + __in HANDLE hProcess, + __in DWORD64 qwBaseAddress, + __out_bcount(nSize) PVOID lpBuffer, + __in DWORD nSize, + __out LPDWORD lpNumberOfBytesRead + ); + +typedef +PVOID +(__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)( + __in HANDLE ahProcess, + __in DWORD64 AddrBase + ); + +typedef +DWORD64 +(__stdcall *PGET_MODULE_BASE_ROUTINE64)( + __in HANDLE hProcess, + __in DWORD64 Address + ); + +typedef +DWORD64 +(__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)( + __in HANDLE hProcess, + __in HANDLE hThread, + __in LPADDRESS64 lpaddr + ); + +BOOL +IMAGEAPI +StackWalk64( + __in DWORD MachineType, + __in HANDLE hProcess, + __in HANDLE hThread, + __inout LPSTACKFRAME64 StackFrame, + __inout PVOID ContextRecord, + __in_opt PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, + __in_opt PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, + __in_opt PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, + __in_opt PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) + +#define PREAD_PROCESS_MEMORY_ROUTINE PREAD_PROCESS_MEMORY_ROUTINE64 +#define PFUNCTION_TABLE_ACCESS_ROUTINE PFUNCTION_TABLE_ACCESS_ROUTINE64 +#define PGET_MODULE_BASE_ROUTINE PGET_MODULE_BASE_ROUTINE64 +#define PTRANSLATE_ADDRESS_ROUTINE PTRANSLATE_ADDRESS_ROUTINE64 + +#define StackWalk StackWalk64 + +#else + +typedef +BOOL +(__stdcall *PREAD_PROCESS_MEMORY_ROUTINE)( + __in HANDLE hProcess, + __in DWORD lpBaseAddress, + __out_bcount(nSize) PVOID lpBuffer, + __in DWORD nSize, + __out PDWORD lpNumberOfBytesRead + ); + +typedef +PVOID +(__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE)( + __in HANDLE hProcess, + __in DWORD AddrBase + ); + +typedef +DWORD +(__stdcall *PGET_MODULE_BASE_ROUTINE)( + __in HANDLE hProcess, + __in DWORD Address + ); + +typedef +DWORD +(__stdcall *PTRANSLATE_ADDRESS_ROUTINE)( + __in HANDLE hProcess, + __in HANDLE hThread, + __out LPADDRESS lpaddr + ); + +BOOL +IMAGEAPI +StackWalk( + DWORD MachineType, + __in HANDLE hProcess, + __in HANDLE hThread, + __inout LPSTACKFRAME StackFrame, + __inout PVOID ContextRecord, + __in_opt PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine, + __in_opt PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine, + __in_opt PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine, + __in_opt PTRANSLATE_ADDRESS_ROUTINE TranslateAddress + ); + +#endif + + +#define API_VERSION_NUMBER 11 + +typedef struct API_VERSION { + USHORT MajorVersion; + USHORT MinorVersion; + USHORT Revision; + USHORT Reserved; +} API_VERSION, *LPAPI_VERSION; + +LPAPI_VERSION +IMAGEAPI +ImagehlpApiVersion( + VOID + ); + +LPAPI_VERSION +IMAGEAPI +ImagehlpApiVersionEx( + __in LPAPI_VERSION AppVersion + ); + +DWORD +IMAGEAPI +GetTimestampForLoadedLibrary( + __in HMODULE Module + ); + +// +// typedefs for function pointers +// +typedef BOOL +(CALLBACK *PSYM_ENUMMODULES_CALLBACK64)( + __in PCSTR ModuleName, + __in DWORD64 BaseOfDll, + __in_opt PVOID UserContext + ); + +typedef BOOL +(CALLBACK *PSYM_ENUMMODULES_CALLBACKW64)( + __in PCWSTR ModuleName, + __in DWORD64 BaseOfDll, + __in_opt PVOID UserContext + ); + +typedef BOOL +(CALLBACK *PENUMLOADED_MODULES_CALLBACK64)( + __in PCSTR ModuleName, + __in DWORD64 ModuleBase, + __in ULONG ModuleSize, + __in_opt PVOID UserContext + ); + +typedef BOOL +(CALLBACK *PENUMLOADED_MODULES_CALLBACKW64)( + __in PCWSTR ModuleName, + __in DWORD64 ModuleBase, + __in ULONG ModuleSize, + __in_opt PVOID UserContext + ); + +typedef BOOL +(CALLBACK *PSYM_ENUMSYMBOLS_CALLBACK64)( + __in PCSTR SymbolName, + __in DWORD64 SymbolAddress, + __in ULONG SymbolSize, + __in_opt PVOID UserContext + ); + +typedef BOOL +(CALLBACK *PSYM_ENUMSYMBOLS_CALLBACK64W)( + __in PCWSTR SymbolName, + __in DWORD64 SymbolAddress, + __in ULONG SymbolSize, + __in_opt PVOID UserContext + ); + +typedef BOOL +(CALLBACK *PSYMBOL_REGISTERED_CALLBACK64)( + __in HANDLE hProcess, + __in ULONG ActionCode, + __in_opt ULONG64 CallbackData, + __in_opt ULONG64 UserContext + ); + +typedef +PVOID +(CALLBACK *PSYMBOL_FUNCENTRY_CALLBACK)( + __in HANDLE hProcess, + __in DWORD AddrBase, + __in_opt PVOID UserContext + ); + +typedef +PVOID +(CALLBACK *PSYMBOL_FUNCENTRY_CALLBACK64)( + __in HANDLE hProcess, + __in ULONG64 AddrBase, + __in ULONG64 UserContext + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) + +#define PSYM_ENUMMODULES_CALLBACK PSYM_ENUMMODULES_CALLBACK64 +#define PSYM_ENUMSYMBOLS_CALLBACK PSYM_ENUMSYMBOLS_CALLBACK64 +#define PSYM_ENUMSYMBOLS_CALLBACKW PSYM_ENUMSYMBOLS_CALLBACK64W +#define PENUMLOADED_MODULES_CALLBACK PENUMLOADED_MODULES_CALLBACK64 +#define PSYMBOL_REGISTERED_CALLBACK PSYMBOL_REGISTERED_CALLBACK64 +#define PSYMBOL_FUNCENTRY_CALLBACK PSYMBOL_FUNCENTRY_CALLBACK64 + +#else + +typedef BOOL +(CALLBACK *PSYM_ENUMMODULES_CALLBACK)( + __in PCSTR ModuleName, + __in ULONG BaseOfDll, + __in_opt PVOID UserContext + ); + +typedef BOOL +(CALLBACK *PSYM_ENUMSYMBOLS_CALLBACK)( + __in PCSTR SymbolName, + __in ULONG SymbolAddress, + __in ULONG SymbolSize, + __in_opt PVOID UserContext + ); + +typedef BOOL +(CALLBACK *PSYM_ENUMSYMBOLS_CALLBACKW)( + __in PCWSTR SymbolName, + __in ULONG SymbolAddress, + __in ULONG SymbolSize, + __in_opt PVOID UserContext + ); + +typedef BOOL +(CALLBACK *PENUMLOADED_MODULES_CALLBACK)( + __in PCSTR ModuleName, + __in ULONG ModuleBase, + __in ULONG ModuleSize, + __in_opt PVOID UserContext + ); + +typedef BOOL +(CALLBACK *PSYMBOL_REGISTERED_CALLBACK)( + __in HANDLE hProcess, + __in ULONG ActionCode, + __in_opt PVOID CallbackData, + __in_opt PVOID UserContext + ); + +#endif + + +// values found in SYMBOL_INFO.Tag +// +// This was taken from cvconst.h and should +// not override any values found there. +// +// #define _NO_CVCONST_H_ if you don't +// have access to that file... + +#ifdef _NO_CVCONST_H + +// DIA enums + +enum SymTagEnum +{ + SymTagNull, + SymTagExe, + SymTagCompiland, + SymTagCompilandDetails, + SymTagCompilandEnv, + SymTagFunction, + SymTagBlock, + SymTagData, + SymTagAnnotation, + SymTagLabel, + SymTagPublicSymbol, + SymTagUDT, + SymTagEnum, + SymTagFunctionType, + SymTagPointerType, + SymTagArrayType, + SymTagBaseType, + SymTagTypedef, + SymTagBaseClass, + SymTagFriend, + SymTagFunctionArgType, + SymTagFuncDebugStart, + SymTagFuncDebugEnd, + SymTagUsingNamespace, + SymTagVTableShape, + SymTagVTable, + SymTagCustom, + SymTagThunk, + SymTagCustomType, + SymTagManagedType, + SymTagDimension, + SymTagMax +}; + +#endif + +// +// flags found in SYMBOL_INFO.Flags +// + +#define SYMFLAG_VALUEPRESENT 0x00000001 +#define SYMFLAG_REGISTER 0x00000008 +#define SYMFLAG_REGREL 0x00000010 +#define SYMFLAG_FRAMEREL 0x00000020 +#define SYMFLAG_PARAMETER 0x00000040 +#define SYMFLAG_LOCAL 0x00000080 +#define SYMFLAG_CONSTANT 0x00000100 +#define SYMFLAG_EXPORT 0x00000200 +#define SYMFLAG_FORWARDER 0x00000400 +#define SYMFLAG_FUNCTION 0x00000800 +#define SYMFLAG_VIRTUAL 0x00001000 +#define SYMFLAG_THUNK 0x00002000 +#define SYMFLAG_TLSREL 0x00004000 +#define SYMFLAG_SLOT 0x00008000 +#define SYMFLAG_ILREL 0x00010000 +#define SYMFLAG_METADATA 0x00020000 +#define SYMFLAG_CLR_TOKEN 0x00040000 + +// this resets SymNext/Prev to the beginning +// of the module passed in the address field + +#define SYMFLAG_RESET 0x80000000 + +// +// symbol type enumeration +// +typedef enum { + SymNone = 0, + SymCoff, + SymCv, + SymPdb, + SymExport, + SymDeferred, + SymSym, // .sym file + SymDia, + SymVirtual, + NumSymTypes +} SYM_TYPE; + +// +// symbol data structure +// + +typedef struct _IMAGEHLP_SYMBOL64 { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_SYMBOL64) + DWORD64 Address; // virtual address including dll base address + DWORD Size; // estimated size of symbol, can be zero + DWORD Flags; // info about the symbols, see the SYMF defines + DWORD MaxNameLength; // maximum size of symbol name in 'Name' + CHAR Name[1]; // symbol name (null terminated string) +} IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64; + +typedef struct _IMAGEHLP_SYMBOL64_PACKAGE { + IMAGEHLP_SYMBOL64 sym; + CHAR name[MAX_SYM_NAME + 1]; +} IMAGEHLP_SYMBOL64_PACKAGE, *PIMAGEHLP_SYMBOL64_PACKAGE; + +typedef struct _IMAGEHLP_SYMBOLW64 { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_SYMBOLW64) + DWORD64 Address; // virtual address including dll base address + DWORD Size; // estimated size of symbol, can be zero + DWORD Flags; // info about the symbols, see the SYMF defines + DWORD MaxNameLength; // maximum size of symbol name in 'Name' + WCHAR Name[1]; // symbol name (null terminated string) +} IMAGEHLP_SYMBOLW64, *PIMAGEHLP_SYMBOLW64; + +typedef struct _IMAGEHLP_SYMBOLW64_PACKAGE { + IMAGEHLP_SYMBOLW64 sym; + WCHAR name[MAX_SYM_NAME + 1]; +} IMAGEHLP_SYMBOLW64_PACKAGE, *PIMAGEHLP_SYMBOLW64_PACKAGE; + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) + + #define IMAGEHLP_SYMBOL IMAGEHLP_SYMBOL64 + #define PIMAGEHLP_SYMBOL PIMAGEHLP_SYMBOL64 + #define IMAGEHLP_SYMBOL_PACKAGE IMAGEHLP_SYMBOL64_PACKAGE + #define PIMAGEHLP_SYMBOL_PACKAGE PIMAGEHLP_SYMBOL64_PACKAGE + #define IMAGEHLP_SYMBOLW IMAGEHLP_SYMBOLW64 + #define PIMAGEHLP_SYMBOLW PIMAGEHLP_SYMBOLW64 + #define IMAGEHLP_SYMBOLW_PACKAGE IMAGEHLP_SYMBOLW64_PACKAGE + #define PIMAGEHLP_SYMBOLW_PACKAGE PIMAGEHLP_SYMBOLW64_PACKAGE + +#else + + typedef struct _IMAGEHLP_SYMBOL { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_SYMBOL) + DWORD Address; // virtual address including dll base address + DWORD Size; // estimated size of symbol, can be zero + DWORD Flags; // info about the symbols, see the SYMF defines + DWORD MaxNameLength; // maximum size of symbol name in 'Name' + CHAR Name[1]; // symbol name (null terminated string) + } IMAGEHLP_SYMBOL, *PIMAGEHLP_SYMBOL; + + typedef struct _IMAGEHLP_SYMBOL_PACKAGE { + IMAGEHLP_SYMBOL sym; + CHAR name[MAX_SYM_NAME + 1]; + } IMAGEHLP_SYMBOL_PACKAGE, *PIMAGEHLP_SYMBOL_PACKAGE; + + typedef struct _IMAGEHLP_SYMBOLW { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_SYMBOLW) + DWORD Address; // virtual address including dll base address + DWORD Size; // estimated size of symbol, can be zero + DWORD Flags; // info about the symbols, see the SYMF defines + DWORD MaxNameLength; // maximum size of symbol name in 'Name' + WCHAR Name[1]; // symbol name (null terminated string) + } IMAGEHLP_SYMBOLW, *PIMAGEHLP_SYMBOLW; + + typedef struct _IMAGEHLP_SYMBOLW_PACKAGE { + IMAGEHLP_SYMBOLW sym; + WCHAR name[MAX_SYM_NAME + 1]; + } IMAGEHLP_SYMBOLW_PACKAGE, *PIMAGEHLP_SYMBOLW_PACKAGE; + +#endif + +// +// module data structure +// + +typedef struct _IMAGEHLP_MODULE64 { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_MODULE64) + DWORD64 BaseOfImage; // base load address of module + DWORD ImageSize; // virtual size of the loaded module + DWORD TimeDateStamp; // date/time stamp from pe header + DWORD CheckSum; // checksum from the pe header + DWORD NumSyms; // number of symbols in the symbol table + SYM_TYPE SymType; // type of symbols loaded + CHAR ModuleName[32]; // module name + CHAR ImageName[256]; // image name + CHAR LoadedImageName[256]; // symbol file name + // new elements: 07-Jun-2002 + CHAR LoadedPdbName[256]; // pdb file name + DWORD CVSig; // Signature of the CV record in the debug directories + CHAR CVData[MAX_PATH * 3]; // Contents of the CV record + DWORD PdbSig; // Signature of PDB + GUID PdbSig70; // Signature of PDB (VC 7 and up) + DWORD PdbAge; // DBI age of pdb + BOOL PdbUnmatched; // loaded an unmatched pdb + BOOL DbgUnmatched; // loaded an unmatched dbg + BOOL LineNumbers; // we have line number information + BOOL GlobalSymbols; // we have internal symbol information + BOOL TypeInfo; // we have type information + // new elements: 17-Dec-2003 + BOOL SourceIndexed; // pdb supports source server + BOOL Publics; // contains public symbols +} IMAGEHLP_MODULE64, *PIMAGEHLP_MODULE64; + +typedef struct _IMAGEHLP_MODULEW64 { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_MODULE64) + DWORD64 BaseOfImage; // base load address of module + DWORD ImageSize; // virtual size of the loaded module + DWORD TimeDateStamp; // date/time stamp from pe header + DWORD CheckSum; // checksum from the pe header + DWORD NumSyms; // number of symbols in the symbol table + SYM_TYPE SymType; // type of symbols loaded + WCHAR ModuleName[32]; // module name + WCHAR ImageName[256]; // image name + // new elements: 07-Jun-2002 + WCHAR LoadedImageName[256]; // symbol file name + WCHAR LoadedPdbName[256]; // pdb file name + DWORD CVSig; // Signature of the CV record in the debug directories + WCHAR CVData[MAX_PATH * 3]; // Contents of the CV record + DWORD PdbSig; // Signature of PDB + GUID PdbSig70; // Signature of PDB (VC 7 and up) + DWORD PdbAge; // DBI age of pdb + BOOL PdbUnmatched; // loaded an unmatched pdb + BOOL DbgUnmatched; // loaded an unmatched dbg + BOOL LineNumbers; // we have line number information + BOOL GlobalSymbols; // we have internal symbol information + BOOL TypeInfo; // we have type information + // new elements: 17-Dec-2003 + BOOL SourceIndexed; // pdb supports source server + BOOL Publics; // contains public symbols +} IMAGEHLP_MODULEW64, *PIMAGEHLP_MODULEW64; + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define IMAGEHLP_MODULE IMAGEHLP_MODULE64 +#define PIMAGEHLP_MODULE PIMAGEHLP_MODULE64 +#define IMAGEHLP_MODULEW IMAGEHLP_MODULEW64 +#define PIMAGEHLP_MODULEW PIMAGEHLP_MODULEW64 +#else +typedef struct _IMAGEHLP_MODULE { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_MODULE) + DWORD BaseOfImage; // base load address of module + DWORD ImageSize; // virtual size of the loaded module + DWORD TimeDateStamp; // date/time stamp from pe header + DWORD CheckSum; // checksum from the pe header + DWORD NumSyms; // number of symbols in the symbol table + SYM_TYPE SymType; // type of symbols loaded + CHAR ModuleName[32]; // module name + CHAR ImageName[256]; // image name + CHAR LoadedImageName[256]; // symbol file name +} IMAGEHLP_MODULE, *PIMAGEHLP_MODULE; + +typedef struct _IMAGEHLP_MODULEW { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_MODULE) + DWORD BaseOfImage; // base load address of module + DWORD ImageSize; // virtual size of the loaded module + DWORD TimeDateStamp; // date/time stamp from pe header + DWORD CheckSum; // checksum from the pe header + DWORD NumSyms; // number of symbols in the symbol table + SYM_TYPE SymType; // type of symbols loaded + WCHAR ModuleName[32]; // module name + WCHAR ImageName[256]; // image name + WCHAR LoadedImageName[256]; // symbol file name +} IMAGEHLP_MODULEW, *PIMAGEHLP_MODULEW; +#endif + +// +// source file line data structure +// + +typedef struct _IMAGEHLP_LINE64 { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_LINE64) + PVOID Key; // internal + DWORD LineNumber; // line number in file + PCHAR FileName; // full filename + DWORD64 Address; // first instruction of line +} IMAGEHLP_LINE64, *PIMAGEHLP_LINE64; + +typedef struct _IMAGEHLP_LINEW64 { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_LINE64) + PVOID Key; // internal + DWORD LineNumber; // line number in file + PWSTR FileName; // full filename + DWORD64 Address; // first instruction of line +} IMAGEHLP_LINEW64, *PIMAGEHLP_LINEW64; + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define IMAGEHLP_LINE IMAGEHLP_LINE64 +#define PIMAGEHLP_LINE PIMAGEHLP_LINE64 +#else +typedef struct _IMAGEHLP_LINE { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_LINE) + PVOID Key; // internal + DWORD LineNumber; // line number in file + PCHAR FileName; // full filename + DWORD Address; // first instruction of line +} IMAGEHLP_LINE, *PIMAGEHLP_LINE; + +typedef struct _IMAGEHLP_LINEW { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_LINE64) + PVOID Key; // internal + DWORD LineNumber; // line number in file + PCHAR FileName; // full filename + DWORD64 Address; // first instruction of line +} IMAGEHLP_LINEW, *PIMAGEHLP_LINEW; +#endif + +// +// source file structure +// + +typedef struct _SOURCEFILE { + DWORD64 ModBase; // base address of loaded module + PCHAR FileName; // full filename of source +} SOURCEFILE, *PSOURCEFILE; + +typedef struct _SOURCEFILEW { + DWORD64 ModBase; // base address of loaded module + PWSTR FileName; // full filename of source +} SOURCEFILEW, *PSOURCEFILEW; + +// +// data structures used for registered symbol callbacks +// + +#define CBA_DEFERRED_SYMBOL_LOAD_START 0x00000001 +#define CBA_DEFERRED_SYMBOL_LOAD_COMPLETE 0x00000002 +#define CBA_DEFERRED_SYMBOL_LOAD_FAILURE 0x00000003 +#define CBA_SYMBOLS_UNLOADED 0x00000004 +#define CBA_DUPLICATE_SYMBOL 0x00000005 +#define CBA_READ_MEMORY 0x00000006 +#define CBA_DEFERRED_SYMBOL_LOAD_CANCEL 0x00000007 +#define CBA_SET_OPTIONS 0x00000008 +#define CBA_EVENT 0x00000010 +#define CBA_DEFERRED_SYMBOL_LOAD_PARTIAL 0x00000020 +#define CBA_DEBUG_INFO 0x10000000 +#define CBA_SRCSRV_INFO 0x20000000 +#define CBA_SRCSRV_EVENT 0x40000000 + +typedef struct _IMAGEHLP_CBA_READ_MEMORY { + DWORD64 addr; // address to read from + PVOID buf; // buffer to read to + DWORD bytes; // amount of bytes to read + DWORD *bytesread; // pointer to store amount of bytes read +} IMAGEHLP_CBA_READ_MEMORY, *PIMAGEHLP_CBA_READ_MEMORY; + +enum { + sevInfo = 0, + sevProblem, + sevAttn, + sevFatal, + sevMax // unused +}; + +#define EVENT_SRCSPEW_START 100 +#define EVENT_SRCSPEW 100 +#define EVENT_SRCSPEW_END 199 + +typedef struct _IMAGEHLP_CBA_EVENT { + DWORD severity; // values from sevInfo to sevFatal + DWORD code; // numerical code IDs the error + PCHAR desc; // may contain a text description of the error + PVOID object; // value dependant upon the error code +} IMAGEHLP_CBA_EVENT, *PIMAGEHLP_CBA_EVENT; + +typedef struct _IMAGEHLP_CBA_EVENTW { + DWORD severity; // values from sevInfo to sevFatal + DWORD code; // numerical code IDs the error + PCWSTR desc; // may contain a text description of the error + PVOID object; // value dependant upon the error code +} IMAGEHLP_CBA_EVENTW, *PIMAGEHLP_CBA_EVENTW; + +typedef struct _IMAGEHLP_DEFERRED_SYMBOL_LOAD64 { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_DEFERRED_SYMBOL_LOAD64) + DWORD64 BaseOfImage; // base load address of module + DWORD CheckSum; // checksum from the pe header + DWORD TimeDateStamp; // date/time stamp from pe header + CHAR FileName[MAX_PATH]; // symbols file or image name + BOOLEAN Reparse; // load failure reparse + HANDLE hFile; // file handle, if passed + DWORD Flags; // +} IMAGEHLP_DEFERRED_SYMBOL_LOAD64, *PIMAGEHLP_DEFERRED_SYMBOL_LOAD64; + +typedef struct _IMAGEHLP_DEFERRED_SYMBOL_LOADW64 { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_DEFERRED_SYMBOL_LOADW64) + DWORD64 BaseOfImage; // base load address of module + DWORD CheckSum; // checksum from the pe header + DWORD TimeDateStamp; // date/time stamp from pe header + WCHAR FileName[MAX_PATH + 1]; // symbols file or image name + BOOLEAN Reparse; // load failure reparse + HANDLE hFile; // file handle, if passed + DWORD Flags; // +} IMAGEHLP_DEFERRED_SYMBOL_LOADW64, *PIMAGEHLP_DEFERRED_SYMBOL_LOADW64; + +#define DSLFLAG_MISMATCHED_PDB 0x1 +#define DSLFLAG_MISMATCHED_DBG 0x2 + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define IMAGEHLP_DEFERRED_SYMBOL_LOAD IMAGEHLP_DEFERRED_SYMBOL_LOAD64 +#define PIMAGEHLP_DEFERRED_SYMBOL_LOAD PIMAGEHLP_DEFERRED_SYMBOL_LOAD64 +#else +typedef struct _IMAGEHLP_DEFERRED_SYMBOL_LOAD { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_DEFERRED_SYMBOL_LOAD) + DWORD BaseOfImage; // base load address of module + DWORD CheckSum; // checksum from the pe header + DWORD TimeDateStamp; // date/time stamp from pe header + CHAR FileName[MAX_PATH]; // symbols file or image name + BOOLEAN Reparse; // load failure reparse + HANDLE hFile; // file handle, if passed +} IMAGEHLP_DEFERRED_SYMBOL_LOAD, *PIMAGEHLP_DEFERRED_SYMBOL_LOAD; +#endif + +typedef struct _IMAGEHLP_DUPLICATE_SYMBOL64 { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_DUPLICATE_SYMBOL64) + DWORD NumberOfDups; // number of duplicates in the Symbol array + PIMAGEHLP_SYMBOL64 Symbol; // array of duplicate symbols + DWORD SelectedSymbol; // symbol selected (-1 to start) +} IMAGEHLP_DUPLICATE_SYMBOL64, *PIMAGEHLP_DUPLICATE_SYMBOL64; + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define IMAGEHLP_DUPLICATE_SYMBOL IMAGEHLP_DUPLICATE_SYMBOL64 +#define PIMAGEHLP_DUPLICATE_SYMBOL PIMAGEHLP_DUPLICATE_SYMBOL64 +#else +typedef struct _IMAGEHLP_DUPLICATE_SYMBOL { + DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_DUPLICATE_SYMBOL) + DWORD NumberOfDups; // number of duplicates in the Symbol array + PIMAGEHLP_SYMBOL Symbol; // array of duplicate symbols + DWORD SelectedSymbol; // symbol selected (-1 to start) +} IMAGEHLP_DUPLICATE_SYMBOL, *PIMAGEHLP_DUPLICATE_SYMBOL; +#endif + +// If dbghelp ever needs to display graphical UI, it will use this as the parent window. + +BOOL +IMAGEAPI +SymSetParentWindow( + __in HWND hwnd + ); + +PCHAR +IMAGEAPI +SymSetHomeDirectory( + __in_opt HANDLE hProcess, + __in_opt PCSTR dir + ); + +PWSTR +IMAGEAPI +SymSetHomeDirectoryW( + __in_opt HANDLE hProcess, + __in_opt PCWSTR dir + ); + +PCHAR +IMAGEAPI +SymGetHomeDirectory( + __in DWORD type, + __out_ecount(size) PSTR dir, + __in size_t size + ); + +PWSTR +IMAGEAPI +SymGetHomeDirectoryW( + __in DWORD type, + __out_ecount(size) PWSTR dir, + __in size_t size + ); + +typedef enum { + hdBase = 0, // root directory for dbghelp + hdSym, // where symbols are stored + hdSrc, // where source is stored + hdMax // end marker +}; + +typedef struct _OMAP { + ULONG rva; + ULONG rvaTo; +} OMAP, *POMAP; + +BOOL +IMAGEAPI +SymGetOmaps( + __in HANDLE hProcess, + __in DWORD64 BaseOfDll, + __out POMAP *OmapTo, + __out PDWORD64 cOmapTo, + __out POMAP *OmapFrom, + __out PDWORD64 cOmapFrom + ); + +// +// options that are set/returned by SymSetOptions() & SymGetOptions() +// these are used as a mask +// +#define SYMOPT_CASE_INSENSITIVE 0x00000001 +#define SYMOPT_UNDNAME 0x00000002 +#define SYMOPT_DEFERRED_LOADS 0x00000004 +#define SYMOPT_NO_CPP 0x00000008 +#define SYMOPT_LOAD_LINES 0x00000010 +#define SYMOPT_OMAP_FIND_NEAREST 0x00000020 +#define SYMOPT_LOAD_ANYTHING 0x00000040 +#define SYMOPT_IGNORE_CVREC 0x00000080 +#define SYMOPT_NO_UNQUALIFIED_LOADS 0x00000100 +#define SYMOPT_FAIL_CRITICAL_ERRORS 0x00000200 +#define SYMOPT_EXACT_SYMBOLS 0x00000400 +#define SYMOPT_ALLOW_ABSOLUTE_SYMBOLS 0x00000800 +#define SYMOPT_IGNORE_NT_SYMPATH 0x00001000 +#define SYMOPT_INCLUDE_32BIT_MODULES 0x00002000 +#define SYMOPT_PUBLICS_ONLY 0x00004000 +#define SYMOPT_NO_PUBLICS 0x00008000 +#define SYMOPT_AUTO_PUBLICS 0x00010000 +#define SYMOPT_NO_IMAGE_SEARCH 0x00020000 +#define SYMOPT_SECURE 0x00040000 +#define SYMOPT_NO_PROMPTS 0x00080000 +#define SYMOPT_OVERWRITE 0x00100000 +#define SYMOPT_IGNORE_IMAGEDIR 0x00200000 +#define SYMOPT_FLAT_DIRECTORY 0x00400000 +#define SYMOPT_FAVOR_COMPRESSED 0x00800000 +#define SYMOPT_ALLOW_ZERO_ADDRESS 0x01000000 +#define SYMOPT_DISABLE_SYMSRV_AUTODETECT 0x02000000 + +#define SYMOPT_DEBUG 0x80000000 + +DWORD +IMAGEAPI +SymSetOptions( + __in DWORD SymOptions + ); + +DWORD +IMAGEAPI +SymGetOptions( + VOID + ); + +BOOL +IMAGEAPI +SymCleanup( + __in HANDLE hProcess + ); + +BOOL +IMAGEAPI +SymMatchString( + __in PCSTR string, + __in PCSTR expression, + __in BOOL fCase + ); + +BOOL +IMAGEAPI +SymMatchStringA( + __in PCSTR string, + __in PCSTR expression, + __in BOOL fCase + ); + +BOOL +IMAGEAPI +SymMatchStringW( + __in PCWSTR string, + __in PCWSTR expression, + __in BOOL fCase + ); + +typedef BOOL +(CALLBACK *PSYM_ENUMSOURCEFILES_CALLBACK)( + __in PSOURCEFILE pSourceFile, + __in_opt PVOID UserContext + ); + +// for backwards compatibility - don't use this +#define PSYM_ENUMSOURCFILES_CALLBACK PSYM_ENUMSOURCEFILES_CALLBACK + +BOOL +IMAGEAPI +SymEnumSourceFiles( + __in HANDLE hProcess, + __in ULONG64 ModBase, + __in_opt PCSTR Mask, + __in PSYM_ENUMSOURCEFILES_CALLBACK cbSrcFiles, + __in_opt PVOID UserContext + ); + +typedef BOOL +(CALLBACK *PSYM_ENUMSOURCEFILES_CALLBACKW)( + __in PSOURCEFILEW pSourceFile, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymEnumSourceFilesW( + __in HANDLE hProcess, + __in ULONG64 ModBase, + __in_opt PCWSTR Mask, + __in PSYM_ENUMSOURCEFILES_CALLBACKW cbSrcFiles, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymEnumerateModules64( + __in HANDLE hProcess, + __in PSYM_ENUMMODULES_CALLBACK64 EnumModulesCallback, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymEnumerateModulesW64( + __in HANDLE hProcess, + __in PSYM_ENUMMODULES_CALLBACKW64 EnumModulesCallback, + __in_opt PVOID UserContext + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymEnumerateModules SymEnumerateModules64 +#else +BOOL +IMAGEAPI +SymEnumerateModules( + __in HANDLE hProcess, + __in PSYM_ENUMMODULES_CALLBACK EnumModulesCallback, + __in_opt PVOID UserContext + ); +#endif + +BOOL +IMAGEAPI +EnumerateLoadedModulesEx( + __in HANDLE hProcess, + __in PENUMLOADED_MODULES_CALLBACK64 EnumLoadedModulesCallback, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +EnumerateLoadedModulesExW( + __in HANDLE hProcess, + __in PENUMLOADED_MODULES_CALLBACKW64 EnumLoadedModulesCallback, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +EnumerateLoadedModules64( + __in HANDLE hProcess, + __in PENUMLOADED_MODULES_CALLBACK64 EnumLoadedModulesCallback, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +EnumerateLoadedModulesW64( + __in HANDLE hProcess, + __in PENUMLOADED_MODULES_CALLBACKW64 EnumLoadedModulesCallback, + __in_opt PVOID UserContext + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define EnumerateLoadedModules EnumerateLoadedModules64 +#else +BOOL +IMAGEAPI +EnumerateLoadedModules( + __in HANDLE hProcess, + __in PENUMLOADED_MODULES_CALLBACK EnumLoadedModulesCallback, + __in_opt PVOID UserContext + ); +#endif + +PVOID +IMAGEAPI +SymFunctionTableAccess64( + __in HANDLE hProcess, + __in DWORD64 AddrBase + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymFunctionTableAccess SymFunctionTableAccess64 +#else +PVOID +IMAGEAPI +SymFunctionTableAccess( + __in HANDLE hProcess, + __in DWORD AddrBase + ); +#endif + +BOOL +IMAGEAPI +SymGetUnwindInfo( + __in HANDLE hProcess, + __in DWORD64 Address, + __out_bcount_opt(*Size) PVOID Buffer, + __inout PULONG Size + ); + +BOOL +IMAGEAPI +SymGetModuleInfo64( + __in HANDLE hProcess, + __in DWORD64 qwAddr, + __out PIMAGEHLP_MODULE64 ModuleInfo + ); + +BOOL +IMAGEAPI +SymGetModuleInfoW64( + __in HANDLE hProcess, + __in DWORD64 qwAddr, + __out PIMAGEHLP_MODULEW64 ModuleInfo + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymGetModuleInfo SymGetModuleInfo64 +#define SymGetModuleInfoW SymGetModuleInfoW64 +#else +BOOL +IMAGEAPI +SymGetModuleInfo( + __in HANDLE hProcess, + __in DWORD dwAddr, + __out PIMAGEHLP_MODULE ModuleInfo + ); + +BOOL +IMAGEAPI +SymGetModuleInfoW( + __in HANDLE hProcess, + __in DWORD dwAddr, + __out PIMAGEHLP_MODULEW ModuleInfo + ); +#endif + +DWORD64 +IMAGEAPI +SymGetModuleBase64( + __in HANDLE hProcess, + __in DWORD64 qwAddr + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymGetModuleBase SymGetModuleBase64 +#else +DWORD +IMAGEAPI +SymGetModuleBase( + __in HANDLE hProcess, + __in DWORD dwAddr + ); +#endif + +typedef struct _SRCCODEINFO { + DWORD SizeOfStruct; // set to sizeof(SRCCODEINFO) + PVOID Key; // not used + DWORD64 ModBase; // base address of module this applies to + CHAR Obj[MAX_PATH + 1]; // the object file within the module + CHAR FileName[MAX_PATH + 1]; // full filename + DWORD LineNumber; // line number in file + DWORD64 Address; // first instruction of line +} SRCCODEINFO, *PSRCCODEINFO; + +typedef struct _SRCCODEINFOW { + DWORD SizeOfStruct; // set to sizeof(SRCCODEINFO) + PVOID Key; // not used + DWORD64 ModBase; // base address of module this applies to + WCHAR Obj[MAX_PATH + 1]; // the object file within the module + WCHAR FileName[MAX_PATH + 1]; // full filename + DWORD LineNumber; // line number in file + DWORD64 Address; // first instruction of line +} SRCCODEINFOW, *PSRCCODEINFOW; + +typedef BOOL +(CALLBACK *PSYM_ENUMLINES_CALLBACK)( + __in PSRCCODEINFO LineInfo, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymEnumLines( + __in HANDLE hProcess, + __in ULONG64 Base, + __in_opt PCSTR Obj, + __in_opt PCSTR File, + __in PSYM_ENUMLINES_CALLBACK EnumLinesCallback, + __in_opt PVOID UserContext + ); + +typedef BOOL +(CALLBACK *PSYM_ENUMLINES_CALLBACKW)( + __in PSRCCODEINFOW LineInfo, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymEnumLinesW( + __in HANDLE hProcess, + __in ULONG64 Base, + __in_opt PCWSTR Obj, + __in_opt PCWSTR File, + __in PSYM_ENUMLINES_CALLBACKW EnumLinesCallback, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymGetLineFromAddr64( + __in HANDLE hProcess, + __in DWORD64 qwAddr, + __out PDWORD pdwDisplacement, + __out PIMAGEHLP_LINE64 Line64 + ); + +BOOL +IMAGEAPI +SymGetLineFromAddrW64( + __in HANDLE hProcess, + __in DWORD64 dwAddr, + __out PDWORD pdwDisplacement, + __out PIMAGEHLP_LINEW64 Line + ); + +BOOL +IMAGEAPI +SymEnumSourceLines( + __in HANDLE hProcess, + __in ULONG64 Base, + __in_opt PCSTR Obj, + __in_opt PCSTR File, + __in_opt DWORD Line, + __in DWORD Flags, + __in PSYM_ENUMLINES_CALLBACK EnumLinesCallback, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymEnumSourceLinesW( + __in HANDLE hProcess, + __in ULONG64 Base, + __in_opt PCWSTR Obj, + __in_opt PCWSTR File, + __in_opt DWORD Line, + __in DWORD Flags, + __in PSYM_ENUMLINES_CALLBACKW EnumLinesCallback, + __in_opt PVOID UserContext + ); + +// flags for SymEnumSourceLines + +#define ESLFLAG_FULLPATH 0x1 +#define ESLFLAG_NEAREST 0x2 +#define ESLFLAG_PREV 0x4 +#define ESLFLAG_NEXT 0x8 + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymGetLineFromAddr SymGetLineFromAddr64 +#define SymGetLineFromAddrW SymGetLineFromAddrW64 +#else +BOOL +IMAGEAPI +SymGetLineFromAddr( + __in HANDLE hProcess, + __in DWORD dwAddr, + __out PDWORD pdwDisplacement, + __out PIMAGEHLP_LINE Line + ); + +BOOL +IMAGEAPI +SymGetLineFromAddrW( + __in HANDLE hProcess, + __in DWORD dwAddr, + __out PDWORD pdwDisplacement, + __out PIMAGEHLP_LINEW Line + ); +#endif + +BOOL +IMAGEAPI +SymGetLineFromName64( + __in HANDLE hProcess, + __in_opt PCSTR ModuleName, + __in_opt PCSTR FileName, + __in DWORD dwLineNumber, + __out PLONG plDisplacement, + __inout PIMAGEHLP_LINE64 Line + ); + +BOOL +IMAGEAPI +SymGetLineFromNameW64( + __in HANDLE hProcess, + __in_opt PCWSTR ModuleName, + __in_opt PCWSTR FileName, + __in DWORD dwLineNumber, + __out PLONG plDisplacement, + __inout PIMAGEHLP_LINEW64 Line + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymGetLineFromName SymGetLineFromName64 +#else +BOOL +IMAGEAPI +SymGetLineFromName( + __in HANDLE hProcess, + __in_opt PCSTR ModuleName, + __in_opt PCSTR FileName, + __in DWORD dwLineNumber, + __out PLONG plDisplacement, + __inout PIMAGEHLP_LINE Line + ); +#endif + +BOOL +IMAGEAPI +SymGetLineNext64( + __in HANDLE hProcess, + __inout PIMAGEHLP_LINE64 Line + ); + +BOOL +IMAGEAPI +SymGetLineNextW64( + __in HANDLE hProcess, + __inout PIMAGEHLP_LINEW64 Line + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymGetLineNext SymGetLineNext64 +#else +BOOL +IMAGEAPI +SymGetLineNext( + __in HANDLE hProcess, + __inout PIMAGEHLP_LINE Line + ); + +BOOL +IMAGEAPI +SymGetLineNextW( + __in HANDLE hProcess, + __inout PIMAGEHLP_LINEW Line + ); +#endif + +BOOL +IMAGEAPI +SymGetLinePrev64( + __in HANDLE hProcess, + __inout PIMAGEHLP_LINE64 Line + ); + +BOOL +IMAGEAPI +SymGetLinePrevW64( + __in HANDLE hProcess, + __inout PIMAGEHLP_LINEW64 Line + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymGetLinePrev SymGetLinePrev64 +#else +BOOL +IMAGEAPI +SymGetLinePrev( + __in HANDLE hProcess, + __inout PIMAGEHLP_LINE Line + ); + +BOOL +IMAGEAPI +SymGetLinePrevW( + __in HANDLE hProcess, + __inout PIMAGEHLP_LINEW Line + ); +#endif + +ULONG +IMAGEAPI +SymGetFileLineOffsets64( + __in HANDLE hProcess, + __in_opt PCSTR ModuleName, + __in PCSTR FileName, + __out_ecount(BufferLines) PDWORD64 Buffer, + __in ULONG BufferLines + ); + +BOOL +IMAGEAPI +SymMatchFileName( + __in PCSTR FileName, + __in PCSTR Match, + __deref_opt_out PSTR *FileNameStop, + __deref_opt_out PSTR *MatchStop + ); + +BOOL +IMAGEAPI +SymMatchFileNameW( + __in PCWSTR FileName, + __in PCWSTR Match, + __deref_opt_out PWSTR *FileNameStop, + __deref_opt_out PWSTR *MatchStop + ); + +BOOL +IMAGEAPI +SymGetSourceFile( + __in HANDLE hProcess, + __in ULONG64 Base, + __in_opt PCSTR Params, + __in PCSTR FileSpec, + __out_ecount(Size) PSTR FilePath, + __in DWORD Size + ); + +BOOL +IMAGEAPI +SymGetSourceFileW( + __in HANDLE hProcess, + __in ULONG64 Base, + __in_opt PCWSTR Params, + __in PCWSTR FileSpec, + __out_ecount(Size) PWSTR FilePath, + __in DWORD Size + ); + +BOOL +IMAGEAPI +SymGetSourceFileToken( + __in HANDLE hProcess, + __in ULONG64 Base, + __in PCSTR FileSpec, + __deref_out PVOID *Token, + __out DWORD *Size + ); + +BOOL +IMAGEAPI +SymGetSourceFileTokenW( + __in HANDLE hProcess, + __in ULONG64 Base, + __in PCWSTR FileSpec, + __deref_out PVOID *Token, + __out DWORD *Size + ); + +BOOL +IMAGEAPI +SymGetSourceFileFromToken( + __in HANDLE hProcess, + __in PVOID Token, + __in_opt PCSTR Params, + __out_ecount(Size) PSTR FilePath, + __in DWORD Size + ); + +BOOL +IMAGEAPI +SymGetSourceFileFromTokenW( + __in HANDLE hProcess, + __in PVOID Token, + __in_opt PCWSTR Params, + __out_ecount(Size) PWSTR FilePath, + __in DWORD Size + ); + +BOOL +IMAGEAPI +SymGetSourceVarFromToken( + __in HANDLE hProcess, + __in PVOID Token, + __in_opt PCSTR Params, + __in PCSTR VarName, + __out_ecount(Size) PSTR Value, + __in DWORD Size + ); + +BOOL +IMAGEAPI +SymGetSourceVarFromTokenW( + __in HANDLE hProcess, + __in PVOID Token, + __in_opt PCWSTR Params, + __in PCWSTR VarName, + __out_ecount(Size) PWSTR Value, + __in DWORD Size + ); + +typedef BOOL (CALLBACK *PENUMSOURCEFILETOKENSCALLBACK)(__in PVOID token, __in size_t size); + +BOOL +IMAGEAPI +SymEnumSourceFileTokens( + __in HANDLE hProcess, + __in ULONG64 Base, + __in PENUMSOURCEFILETOKENSCALLBACK Callback + ); + +BOOL +IMAGEAPI +SymInitialize( + __in HANDLE hProcess, + __in_opt PCSTR UserSearchPath, + __in BOOL fInvadeProcess + ); + +BOOL +IMAGEAPI +SymInitializeW( + __in HANDLE hProcess, + __in_opt PCWSTR UserSearchPath, + __in BOOL fInvadeProcess + ); + +BOOL +IMAGEAPI +SymGetSearchPath( + __in HANDLE hProcess, + __out_ecount(SearchPathLength) PSTR SearchPath, + __in DWORD SearchPathLength + ); + +BOOL +IMAGEAPI +SymGetSearchPathW( + __in HANDLE hProcess, + __out_ecount(SearchPathLength) PWSTR SearchPath, + __in DWORD SearchPathLength + ); + +BOOL +IMAGEAPI +SymSetSearchPath( + __in HANDLE hProcess, + __in_opt PCSTR SearchPath + ); + +BOOL +IMAGEAPI +SymSetSearchPathW( + __in HANDLE hProcess, + __in_opt PCWSTR SearchPath + ); + +#define SLMFLAG_VIRTUAL 0x1 +#define SLMFLAG_ALT_INDEX 0x2 +#define SLMFLAG_NO_SYMBOLS 0x4 + +DWORD64 +IMAGEAPI +SymLoadModuleEx( + __in HANDLE hProcess, + __in_opt HANDLE hFile, + __in_opt PCSTR ImageName, + __in_opt PCSTR ModuleName, + __in DWORD64 BaseOfDll, + __in DWORD DllSize, + __in_opt PMODLOAD_DATA Data, + __in_opt DWORD Flags + ); + +DWORD64 +IMAGEAPI +SymLoadModuleExW( + __in HANDLE hProcess, + __in_opt HANDLE hFile, + __in_opt PCWSTR ImageName, + __in_opt PCWSTR ModuleName, + __in DWORD64 BaseOfDll, + __in DWORD DllSize, + __in_opt PMODLOAD_DATA Data, + __in_opt DWORD Flags + ); + +BOOL +IMAGEAPI +SymUnloadModule64( + __in HANDLE hProcess, + __in DWORD64 BaseOfDll + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymUnloadModule SymUnloadModule64 +#else +BOOL +IMAGEAPI +SymUnloadModule( + __in HANDLE hProcess, + __in DWORD BaseOfDll + ); +#endif + +BOOL +IMAGEAPI +SymUnDName64( + __in PIMAGEHLP_SYMBOL64 sym, // Symbol to undecorate + __out_ecount(UnDecNameLength) PSTR UnDecName, // Buffer to store undecorated name in + __in DWORD UnDecNameLength // Size of the buffer + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymUnDName SymUnDName64 +#else +BOOL +IMAGEAPI +SymUnDName( + __in PIMAGEHLP_SYMBOL sym, // Symbol to undecorate + __out_ecount(UnDecNameLength) PSTR UnDecName, // Buffer to store undecorated name in + __in DWORD UnDecNameLength // Size of the buffer + ); +#endif + +BOOL +IMAGEAPI +SymRegisterCallback64( + __in HANDLE hProcess, + __in PSYMBOL_REGISTERED_CALLBACK64 CallbackFunction, + __in ULONG64 UserContext + ); + +BOOL +IMAGEAPI +SymRegisterCallbackW64( + __in HANDLE hProcess, + __in PSYMBOL_REGISTERED_CALLBACK64 CallbackFunction, + __in ULONG64 UserContext + ); + +BOOL +IMAGEAPI +SymRegisterFunctionEntryCallback64( + __in HANDLE hProcess, + __in PSYMBOL_FUNCENTRY_CALLBACK64 CallbackFunction, + __in ULONG64 UserContext + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymRegisterCallback SymRegisterCallback64 +#define SymRegisterFunctionEntryCallback SymRegisterFunctionEntryCallback64 +#else +BOOL +IMAGEAPI +SymRegisterCallback( + __in HANDLE hProcess, + __in PSYMBOL_REGISTERED_CALLBACK CallbackFunction, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymRegisterFunctionEntryCallback( + __in HANDLE hProcess, + __in PSYMBOL_FUNCENTRY_CALLBACK CallbackFunction, + __in_opt PVOID UserContext + ); +#endif + + +typedef struct _IMAGEHLP_SYMBOL_SRC { + DWORD sizeofstruct; + DWORD type; + char file[MAX_PATH]; +} IMAGEHLP_SYMBOL_SRC, *PIMAGEHLP_SYMBOL_SRC; + +typedef struct _MODULE_TYPE_INFO { // AKA TYPTYP + USHORT dataLength; + USHORT leaf; + BYTE data[1]; +} MODULE_TYPE_INFO, *PMODULE_TYPE_INFO; + +typedef struct _SYMBOL_INFO { + ULONG SizeOfStruct; + ULONG TypeIndex; // Type Index of symbol + ULONG64 Reserved[2]; + ULONG Index; + ULONG Size; + ULONG64 ModBase; // Base Address of module comtaining this symbol + ULONG Flags; + ULONG64 Value; // Value of symbol, ValuePresent should be 1 + ULONG64 Address; // Address of symbol including base address of module + ULONG Register; // register holding value or pointer to value + ULONG Scope; // scope of the symbol + ULONG Tag; // pdb classification + ULONG NameLen; // Actual length of name + ULONG MaxNameLen; + CHAR Name[1]; // Name of symbol +} SYMBOL_INFO, *PSYMBOL_INFO; + +typedef struct _SYMBOL_INFO_PACKAGE { + SYMBOL_INFO si; + CHAR name[MAX_SYM_NAME + 1]; +} SYMBOL_INFO_PACKAGE, *PSYMBOL_INFO_PACKAGE; + +typedef struct _SYMBOL_INFOW { + ULONG SizeOfStruct; + ULONG TypeIndex; // Type Index of symbol + ULONG64 Reserved[2]; + ULONG Index; + ULONG Size; + ULONG64 ModBase; // Base Address of module comtaining this symbol + ULONG Flags; + ULONG64 Value; // Value of symbol, ValuePresent should be 1 + ULONG64 Address; // Address of symbol including base address of module + ULONG Register; // register holding value or pointer to value + ULONG Scope; // scope of the symbol + ULONG Tag; // pdb classification + ULONG NameLen; // Actual length of name + ULONG MaxNameLen; + WCHAR Name[1]; // Name of symbol +} SYMBOL_INFOW, *PSYMBOL_INFOW; + +typedef struct _SYMBOL_INFO_PACKAGEW { + SYMBOL_INFOW si; + WCHAR name[MAX_SYM_NAME + 1]; +} SYMBOL_INFO_PACKAGEW, *PSYMBOL_INFO_PACKAGEW; + +typedef struct _IMAGEHLP_STACK_FRAME +{ + ULONG64 InstructionOffset; + ULONG64 ReturnOffset; + ULONG64 FrameOffset; + ULONG64 StackOffset; + ULONG64 BackingStoreOffset; + ULONG64 FuncTableEntry; + ULONG64 Params[4]; + ULONG64 Reserved[5]; + BOOL Virtual; + ULONG Reserved2; +} IMAGEHLP_STACK_FRAME, *PIMAGEHLP_STACK_FRAME; + +typedef VOID IMAGEHLP_CONTEXT, *PIMAGEHLP_CONTEXT; + + +BOOL +IMAGEAPI +SymSetContext( + __in HANDLE hProcess, + __in PIMAGEHLP_STACK_FRAME StackFrame, + __in_opt PIMAGEHLP_CONTEXT Context + ); + +BOOL +IMAGEAPI +SymSetScopeFromAddr( + __in HANDLE hProcess, + __in ULONG64 Address + ); + +BOOL +IMAGEAPI +SymSetScopeFromIndex( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in DWORD Index + ); + +typedef BOOL +(CALLBACK *PSYM_ENUMPROCESSES_CALLBACK)( + __in HANDLE hProcess, + __in PVOID UserContext + ); + +BOOL +IMAGEAPI +SymEnumProcesses( + __in PSYM_ENUMPROCESSES_CALLBACK EnumProcessesCallback, + __in PVOID UserContext + ); + +BOOL +IMAGEAPI +SymFromAddr( + __in HANDLE hProcess, + __in DWORD64 Address, + __out_opt PDWORD64 Displacement, + __inout PSYMBOL_INFO Symbol + ); + +BOOL +IMAGEAPI +SymFromAddrW( + __in HANDLE hProcess, + __in DWORD64 Address, + __out_opt PDWORD64 Displacement, + __inout PSYMBOL_INFOW Symbol + ); + +BOOL +IMAGEAPI +SymFromToken( + __in HANDLE hProcess, + __in DWORD64 Base, + __in DWORD Token, + __inout PSYMBOL_INFO Symbol + ); + +BOOL +IMAGEAPI +SymFromTokenW( + __in HANDLE hProcess, + __in DWORD64 Base, + __in DWORD Token, + __inout PSYMBOL_INFOW Symbol + ); + +BOOL +IMAGEAPI +SymNext( + __in HANDLE hProcess, + __inout PSYMBOL_INFO si + ); + +BOOL +IMAGEAPI +SymNextW( + __in HANDLE hProcess, + __inout PSYMBOL_INFOW siw + ); + +BOOL +IMAGEAPI +SymPrev( + __in HANDLE hProcess, + __inout PSYMBOL_INFO si + ); + +BOOL +IMAGEAPI +SymPrevW( + __in HANDLE hProcess, + __inout PSYMBOL_INFOW siw + ); + +// While SymFromName will provide a symbol from a name, +// SymEnumSymbols can provide the same matching information +// for ALL symbols with a matching name, even regular +// expressions. That way you can search across modules +// and differentiate between identically named symbols. + +BOOL +IMAGEAPI +SymFromName( + __in HANDLE hProcess, + __in PCSTR Name, + __inout PSYMBOL_INFO Symbol + ); + +BOOL +IMAGEAPI +SymFromNameW( + __in HANDLE hProcess, + __in PCWSTR Name, + __inout PSYMBOL_INFOW Symbol + ); + +typedef BOOL +(CALLBACK *PSYM_ENUMERATESYMBOLS_CALLBACK)( + __in PSYMBOL_INFO pSymInfo, + __in ULONG SymbolSize, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymEnumSymbols( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in_opt PCSTR Mask, + __in PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback, + __in_opt PVOID UserContext + ); + +typedef BOOL +(CALLBACK *PSYM_ENUMERATESYMBOLS_CALLBACKW)( + __in PSYMBOL_INFOW pSymInfo, + __in ULONG SymbolSize, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymEnumSymbolsW( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in_opt PCWSTR Mask, + __in PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymEnumSymbolsForAddr( + __in HANDLE hProcess, + __in DWORD64 Address, + __in PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymEnumSymbolsForAddrW( + __in HANDLE hProcess, + __in DWORD64 Address, + __in PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback, + __in_opt PVOID UserContext + ); + +#define SYMSEARCH_MASKOBJS 0x01 // used internally to implement other APIs +#define SYMSEARCH_RECURSE 0X02 // recurse scopes +#define SYMSEARCH_GLOBALSONLY 0X04 // search only for global symbols +#define SYMSEARCH_ALLITEMS 0X08 // search for everything in the pdb, not just normal scoped symbols + +BOOL +IMAGEAPI +SymSearch( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in_opt DWORD Index, + __in_opt DWORD SymTag, + __in_opt PCSTR Mask, + __in_opt DWORD64 Address, + __in PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback, + __in_opt PVOID UserContext, + __in DWORD Options + ); + +BOOL +IMAGEAPI +SymSearchW( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in_opt DWORD Index, + __in_opt DWORD SymTag, + __in_opt PCWSTR Mask, + __in_opt DWORD64 Address, + __in PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback, + __in_opt PVOID UserContext, + __in DWORD Options + ); + +BOOL +IMAGEAPI +SymGetScope( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in DWORD Index, + __inout PSYMBOL_INFO Symbol + ); + +BOOL +IMAGEAPI +SymGetScopeW( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in DWORD Index, + __inout PSYMBOL_INFOW Symbol + ); + +BOOL +IMAGEAPI +SymFromIndex( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in DWORD Index, + __inout PSYMBOL_INFO Symbol + ); + +BOOL +IMAGEAPI +SymFromIndexW( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in DWORD Index, + __inout PSYMBOL_INFOW Symbol + ); + +typedef enum _IMAGEHLP_SYMBOL_TYPE_INFO { + TI_GET_SYMTAG, + TI_GET_SYMNAME, + TI_GET_LENGTH, + TI_GET_TYPE, + TI_GET_TYPEID, + TI_GET_BASETYPE, + TI_GET_ARRAYINDEXTYPEID, + TI_FINDCHILDREN, + TI_GET_DATAKIND, + TI_GET_ADDRESSOFFSET, + TI_GET_OFFSET, + TI_GET_VALUE, + TI_GET_COUNT, + TI_GET_CHILDRENCOUNT, + TI_GET_BITPOSITION, + TI_GET_VIRTUALBASECLASS, + TI_GET_VIRTUALTABLESHAPEID, + TI_GET_VIRTUALBASEPOINTEROFFSET, + TI_GET_CLASSPARENTID, + TI_GET_NESTED, + TI_GET_SYMINDEX, + TI_GET_LEXICALPARENT, + TI_GET_ADDRESS, + TI_GET_THISADJUST, + TI_GET_UDTKIND, + TI_IS_EQUIV_TO, + TI_GET_CALLING_CONVENTION, + TI_IS_CLOSE_EQUIV_TO, + TI_GTIEX_REQS_VALID, + TI_GET_VIRTUALBASEOFFSET, + TI_GET_VIRTUALBASEDISPINDEX, + TI_GET_IS_REFERENCE, + TI_GET_INDIRECTVIRTUALBASECLASS, + IMAGEHLP_SYMBOL_TYPE_INFO_MAX, +} IMAGEHLP_SYMBOL_TYPE_INFO; + +typedef struct _TI_FINDCHILDREN_PARAMS { + ULONG Count; + ULONG Start; + ULONG ChildId[1]; +} TI_FINDCHILDREN_PARAMS; + +BOOL +IMAGEAPI +SymGetTypeInfo( + __in HANDLE hProcess, + __in DWORD64 ModBase, + __in ULONG TypeId, + __in IMAGEHLP_SYMBOL_TYPE_INFO GetType, + __out PVOID pInfo + ); + +#define IMAGEHLP_GET_TYPE_INFO_UNCACHED 0x00000001 +#define IMAGEHLP_GET_TYPE_INFO_CHILDREN 0x00000002 + +typedef struct _IMAGEHLP_GET_TYPE_INFO_PARAMS { + IN ULONG SizeOfStruct; + IN ULONG Flags; + IN ULONG NumIds; + IN PULONG TypeIds; + IN ULONG64 TagFilter; + IN ULONG NumReqs; + IN IMAGEHLP_SYMBOL_TYPE_INFO* ReqKinds; + IN PULONG_PTR ReqOffsets; + IN PULONG ReqSizes; + IN ULONG_PTR ReqStride; + IN ULONG_PTR BufferSize; + OUT PVOID Buffer; + OUT ULONG EntriesMatched; + OUT ULONG EntriesFilled; + OUT ULONG64 TagsFound; + OUT ULONG64 AllReqsValid; + IN ULONG NumReqsValid; + OUT PULONG64 ReqsValid OPTIONAL; +} IMAGEHLP_GET_TYPE_INFO_PARAMS, *PIMAGEHLP_GET_TYPE_INFO_PARAMS; + +BOOL +IMAGEAPI +SymGetTypeInfoEx( + __in HANDLE hProcess, + __in DWORD64 ModBase, + __inout PIMAGEHLP_GET_TYPE_INFO_PARAMS Params + ); + +BOOL +IMAGEAPI +SymEnumTypes( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymEnumTypesW( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymEnumTypesByName( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in_opt PCSTR mask, + __in PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymEnumTypesByNameW( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in_opt PCWSTR mask, + __in PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback, + __in_opt PVOID UserContext + ); + +BOOL +IMAGEAPI +SymGetTypeFromName( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in PCSTR Name, + __inout PSYMBOL_INFO Symbol + ); + +BOOL +IMAGEAPI +SymGetTypeFromNameW( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in PCWSTR Name, + __inout PSYMBOL_INFOW Symbol + ); + +BOOL +IMAGEAPI +SymAddSymbol( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in PCSTR Name, + __in DWORD64 Address, + __in DWORD Size, + __in DWORD Flags + ); + +BOOL +IMAGEAPI +SymAddSymbolW( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in PCWSTR Name, + __in DWORD64 Address, + __in DWORD Size, + __in DWORD Flags + ); + +BOOL +IMAGEAPI +SymDeleteSymbol( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in_opt PCSTR Name, + __in DWORD64 Address, + __in DWORD Flags + ); + +BOOL +IMAGEAPI +SymDeleteSymbolW( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in_opt PCWSTR Name, + __in DWORD64 Address, + __in DWORD Flags + ); + +BOOL +IMAGEAPI +SymRefreshModuleList( + __in HANDLE hProcess + ); + +BOOL +IMAGEAPI +SymAddSourceStream( + __in HANDLE hProcess, + __in ULONG64 Base, + __in_opt PCSTR StreamFile, + __in_bcount_opt(Size) PBYTE Buffer, + __in size_t Size + ); + +typedef BOOL (WINAPI *SYMADDSOURCESTREAM)(HANDLE, ULONG64, PCSTR, PBYTE, size_t); + +BOOL +IMAGEAPI +SymAddSourceStreamA( + __in HANDLE hProcess, + __in ULONG64 Base, + __in_opt PCSTR StreamFile, + __in_bcount_opt(Size) PBYTE Buffer, + __in size_t Size + ); + +typedef BOOL (WINAPI *SYMADDSOURCESTREAMA)(HANDLE, ULONG64, PCSTR, PBYTE, size_t); + +BOOL +IMAGEAPI +SymAddSourceStreamW( + __in HANDLE hProcess, + __in ULONG64 Base, + __in_opt PCWSTR FileSpec, + __in_bcount_opt(Size) PBYTE Buffer, + __in size_t Size + ); + +BOOL +IMAGEAPI +SymSrvIsStoreW( + __in_opt HANDLE hProcess, + __in PCWSTR path + ); + +BOOL +IMAGEAPI +SymSrvIsStore( + __in_opt HANDLE hProcess, + __in PCSTR path + ); + +PCSTR +IMAGEAPI +SymSrvDeltaName( + __in HANDLE hProcess, + __in_opt PCSTR SymPath, + __in PCSTR Type, + __in PCSTR File1, + __in PCSTR File2 + ); + +PCWSTR +IMAGEAPI +SymSrvDeltaNameW( + __in HANDLE hProcess, + __in_opt PCWSTR SymPath, + __in PCWSTR Type, + __in PCWSTR File1, + __in PCWSTR File2 + ); + +PCSTR +IMAGEAPI +SymSrvGetSupplement( + __in HANDLE hProcess, + __in_opt PCSTR SymPath, + __in PCSTR Node, + __in PCSTR File + ); + +PCWSTR +IMAGEAPI +SymSrvGetSupplementW( + __in HANDLE hProcess, + __in_opt PCWSTR SymPath, + __in PCWSTR Node, + __in PCWSTR File + ); + +BOOL +IMAGEAPI +SymSrvGetFileIndexes( + __in PCSTR File, + __out GUID *Id, + __out PDWORD Val1, + __out_opt PDWORD Val2, + __in DWORD Flags + ); + +BOOL +IMAGEAPI +SymSrvGetFileIndexesW( + __in PCWSTR File, + __out GUID *Id, + __out PDWORD Val1, + __out_opt PDWORD Val2, + __in DWORD Flags + ); + +BOOL +IMAGEAPI +SymSrvGetFileIndexStringW( + __in HANDLE hProcess, + __in_opt PCWSTR SrvPath, + __in PCWSTR File, + __out_ecount(Size) PWSTR Index, + __in size_t Size, + __in DWORD Flags + ); + +BOOL +IMAGEAPI +SymSrvGetFileIndexString( + __in HANDLE hProcess, + __in_opt PCSTR SrvPath, + __in PCSTR File, + __out_ecount(Size) PSTR Index, + __in size_t Size, + __in DWORD Flags + ); + +typedef struct { + DWORD sizeofstruct; + char file[MAX_PATH +1]; + BOOL stripped; + DWORD timestamp; + DWORD size; + char dbgfile[MAX_PATH +1]; + char pdbfile[MAX_PATH + 1]; + GUID guid; + DWORD sig; + DWORD age; +} SYMSRV_INDEX_INFO, *PSYMSRV_INDEX_INFO; + +typedef struct { + DWORD sizeofstruct; + WCHAR file[MAX_PATH +1]; + BOOL stripped; + DWORD timestamp; + DWORD size; + WCHAR dbgfile[MAX_PATH +1]; + WCHAR pdbfile[MAX_PATH + 1]; + GUID guid; + DWORD sig; + DWORD age; +} SYMSRV_INDEX_INFOW, *PSYMSRV_INDEX_INFOW; + +BOOL +IMAGEAPI +SymSrvGetFileIndexInfo( + __in PCSTR File, + __out PSYMSRV_INDEX_INFO Info, + __in DWORD Flags + ); + +BOOL +IMAGEAPI +SymSrvGetFileIndexInfoW( + __in PCWSTR File, + __out PSYMSRV_INDEX_INFOW Info, + __in DWORD Flags + ); + +PCSTR +IMAGEAPI +SymSrvStoreSupplement( + __in HANDLE hProcess, + __in_opt PCSTR SrvPath, + __in PCSTR Node, + __in PCSTR File, + __in DWORD Flags + ); + +PCWSTR +IMAGEAPI +SymSrvStoreSupplementW( + __in HANDLE hProcess, + __in_opt PCWSTR SymPath, + __in PCWSTR Node, + __in PCWSTR File, + __in DWORD Flags + ); + +PCSTR +IMAGEAPI +SymSrvStoreFile( + __in HANDLE hProcess, + __in_opt PCSTR SrvPath, + __in PCSTR File, + __in DWORD Flags + ); + +PCWSTR +IMAGEAPI +SymSrvStoreFileW( + __in HANDLE hProcess, + __in_opt PCWSTR SrvPath, + __in PCWSTR File, + __in DWORD Flags + ); + +// used by SymGetSymbolFile's "Type" parameter + +typedef enum { + sfImage = 0, + sfDbg, + sfPdb, + sfMpd, + sfMax +}; + +BOOL +IMAGEAPI +SymGetSymbolFile( + __in_opt HANDLE hProcess, + __in_opt PCSTR SymPath, + __in PCSTR ImageFile, + __in DWORD Type, + __out_ecount(cSymbolFile) PSTR SymbolFile, + __in size_t cSymbolFile, + __out_ecount(cDbgFile) PSTR DbgFile, + __in size_t cDbgFile + ); + +BOOL +IMAGEAPI +SymGetSymbolFileW( + __in_opt HANDLE hProcess, + __in_opt PCWSTR SymPath, + __in PCWSTR ImageFile, + __in DWORD Type, + __out_ecount(cSymbolFile) PWSTR SymbolFile, + __in size_t cSymbolFile, + __out_ecount(cDbgFile) PWSTR DbgFile, + __in size_t cDbgFile + ); + +// +// Full user-mode dump creation. +// + +typedef BOOL (WINAPI *PDBGHELP_CREATE_USER_DUMP_CALLBACK)( + __in DWORD DataType, + __in PVOID* Data, + __out LPDWORD DataLength, + __in_opt PVOID UserData + ); + +BOOL +WINAPI +DbgHelpCreateUserDump( + __in_opt LPCSTR FileName, + __in PDBGHELP_CREATE_USER_DUMP_CALLBACK Callback, + __in_opt PVOID UserData + ); + +BOOL +WINAPI +DbgHelpCreateUserDumpW( + __in_opt LPCWSTR FileName, + __in PDBGHELP_CREATE_USER_DUMP_CALLBACK Callback, + __in_opt PVOID UserData + ); + +// ----------------------------------------------------------------- +// The following 4 legacy APIs are fully supported, but newer +// ones are recommended. SymFromName and SymFromAddr provide +// much more detailed info on the returned symbol. + +BOOL +IMAGEAPI +SymGetSymFromAddr64( + __in HANDLE hProcess, + __in DWORD64 qwAddr, + __out_opt PDWORD64 pdwDisplacement, + __inout PIMAGEHLP_SYMBOL64 Symbol + ); + + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymGetSymFromAddr SymGetSymFromAddr64 +#else +BOOL +IMAGEAPI +SymGetSymFromAddr( + __in HANDLE hProcess, + __in DWORD dwAddr, + __out_opt PDWORD pdwDisplacement, + __inout PIMAGEHLP_SYMBOL Symbol + ); +#endif + +// While following two APIs will provide a symbol from a name, +// SymEnumSymbols can provide the same matching information +// for ALL symbols with a matching name, even regular +// expressions. That way you can search across modules +// and differentiate between identically named symbols. + +BOOL +IMAGEAPI +SymGetSymFromName64( + __in HANDLE hProcess, + __in PCSTR Name, + __inout PIMAGEHLP_SYMBOL64 Symbol + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymGetSymFromName SymGetSymFromName64 +#else +BOOL +IMAGEAPI +SymGetSymFromName( + __in HANDLE hProcess, + __in PCSTR Name, + __inout PIMAGEHLP_SYMBOL Symbol + ); +#endif + + +// Symbol server exports + +typedef BOOL (WINAPI *PSYMBOLSERVERPROC)(PCSTR, PCSTR, PVOID, DWORD, DWORD, PSTR); +typedef BOOL (WINAPI *PSYMBOLSERVERPROCA)(PCSTR, PCSTR, PVOID, DWORD, DWORD, PSTR); +typedef BOOL (WINAPI *PSYMBOLSERVERPROCW)(PCWSTR, PCWSTR, PVOID, DWORD, DWORD, PWSTR); +typedef BOOL (WINAPI *PSYMBOLSERVERBYINDEXPROC)(PCSTR, PCSTR, PCSTR, PSTR); +typedef BOOL (WINAPI *PSYMBOLSERVERBYINDEXPROCA)(PCSTR, PCSTR, PCSTR, PSTR); +typedef BOOL (WINAPI *PSYMBOLSERVERBYINDEXPROCW)(PCWSTR, PCWSTR, PCWSTR, PWSTR); +typedef BOOL (WINAPI *PSYMBOLSERVEROPENPROC)(VOID); +typedef BOOL (WINAPI *PSYMBOLSERVERCLOSEPROC)(VOID); +typedef BOOL (WINAPI *PSYMBOLSERVERSETOPTIONSPROC)(UINT_PTR, ULONG64); +typedef BOOL (WINAPI *PSYMBOLSERVERSETOPTIONSWPROC)(UINT_PTR, ULONG64); +typedef BOOL (CALLBACK WINAPI *PSYMBOLSERVERCALLBACKPROC)(UINT_PTR action, ULONG64 data, ULONG64 context); +typedef UINT_PTR (WINAPI *PSYMBOLSERVERGETOPTIONSPROC)(); +typedef BOOL (WINAPI *PSYMBOLSERVERPINGPROC)(PCSTR); +typedef BOOL (WINAPI *PSYMBOLSERVERPINGPROCA)(PCSTR); +typedef BOOL (WINAPI *PSYMBOLSERVERPINGPROCW)(PCWSTR); +typedef BOOL (WINAPI *PSYMBOLSERVERGETVERSION)(LPAPI_VERSION); +typedef BOOL (WINAPI *PSYMBOLSERVERDELTANAME)(PCSTR, PVOID, DWORD, DWORD, PVOID, DWORD, DWORD, PSTR, size_t); +typedef BOOL (WINAPI *PSYMBOLSERVERDELTANAMEW)(PCWSTR, PVOID, DWORD, DWORD, PVOID, DWORD, DWORD, PWSTR, size_t); +typedef BOOL (WINAPI *PSYMBOLSERVERGETSUPPLEMENT)(PCSTR, PCSTR, PCSTR, PSTR, size_t); +typedef BOOL (WINAPI *PSYMBOLSERVERGETSUPPLEMENTW)(PCWSTR, PCWSTR, PCWSTR, PWSTR, size_t); +typedef BOOL (WINAPI *PSYMBOLSERVERSTORESUPPLEMENT)(PCSTR, PCSTR, PCSTR, PSTR, size_t, DWORD); +typedef BOOL (WINAPI *PSYMBOLSERVERSTORESUPPLEMENTW)(PCWSTR, PCWSTR, PCWSTR, PWSTR, size_t, DWORD); +typedef BOOL (WINAPI *PSYMBOLSERVERGETINDEXSTRING)(PVOID, DWORD, DWORD, PSTR, size_t); +typedef BOOL (WINAPI *PSYMBOLSERVERGETINDEXSTRINGW)(PVOID, DWORD, DWORD, PWSTR, size_t); +typedef BOOL (WINAPI *PSYMBOLSERVERSTOREFILE)(PCSTR, PCSTR, PVOID, DWORD, DWORD, PSTR, size_t, DWORD); +typedef BOOL (WINAPI *PSYMBOLSERVERSTOREFILEW)(PCWSTR, PCWSTR, PVOID, DWORD, DWORD, PWSTR, size_t, DWORD); +typedef BOOL (WINAPI *PSYMBOLSERVERISSTORE)(PCSTR); +typedef BOOL (WINAPI *PSYMBOLSERVERISSTOREW)(PCWSTR); +typedef DWORD (WINAPI *PSYMBOLSERVERVERSION)(); +typedef BOOL (CALLBACK WINAPI *PSYMBOLSERVERMESSAGEPROC)(UINT_PTR action, ULONG64 data, ULONG64 context); + +#define SYMSRV_VERSION 2 + +#define SSRVOPT_CALLBACK 0x00000001 +#define SSRVOPT_DWORD 0x00000002 +#define SSRVOPT_DWORDPTR 0x00000004 +#define SSRVOPT_GUIDPTR 0x00000008 +#define SSRVOPT_OLDGUIDPTR 0x00000010 +#define SSRVOPT_UNATTENDED 0x00000020 +#define SSRVOPT_NOCOPY 0x00000040 +#define SSRVOPT_GETPATH 0x00000040 +#define SSRVOPT_PARENTWIN 0x00000080 +#define SSRVOPT_PARAMTYPE 0x00000100 +#define SSRVOPT_SECURE 0x00000200 +#define SSRVOPT_TRACE 0x00000400 +#define SSRVOPT_SETCONTEXT 0x00000800 +#define SSRVOPT_PROXY 0x00001000 +#define SSRVOPT_DOWNSTREAM_STORE 0x00002000 +#define SSRVOPT_OVERWRITE 0x00004000 +#define SSRVOPT_RESETTOU 0x00008000 +#define SSRVOPT_CALLBACKW 0x00010000 +#define SSRVOPT_FLAT_DEFAULT_STORE 0x00020000 +#define SSRVOPT_PROXYW 0x00040000 +#define SSRVOPT_MESSAGE 0x00080000 +#define SSRVOPT_SERVICE 0x00100000 // deprecated +#define SSRVOPT_FAVOR_COMPRESSED 0x00200000 +#define SSRVOPT_STRING 0x00400000 +#define SSRVOPT_WINHTTP 0x00800000 +#define SSRVOPT_WININET 0x01000000 + +#define SSRVOPT_MAX 0x0100000 + +#define SSRVOPT_RESET ((ULONG_PTR)-1) + + +#define NUM_SSRVOPTS 30 + +#define SSRVACTION_TRACE 1 +#define SSRVACTION_QUERYCANCEL 2 +#define SSRVACTION_EVENT 3 +#define SSRVACTION_EVENTW 4 +#define SSRVACTION_SIZE 5 + +#define SYMSTOREOPT_COMPRESS 0x01 +#define SYMSTOREOPT_OVERWRITE 0x02 +#define SYMSTOREOPT_RETURNINDEX 0x04 +#define SYMSTOREOPT_POINTER 0x08 +#define SYMSTOREOPT_ALT_INDEX 0x10 +#define SYMSTOREOPT_UNICODE 0x20 +#define SYMSTOREOPT_PASS_IF_EXISTS 0x40 + +#ifdef DBGHELP_TRANSLATE_TCHAR + #define SymInitialize SymInitializeW + #define SymAddSymbol SymAddSymbolW + #define SymDeleteSymbol SymDeleteSymbolW + #define SearchTreeForFile SearchTreeForFileW + #define UnDecorateSymbolName UnDecorateSymbolNameW + #define SymGetLineFromName64 SymGetLineFromNameW64 + #define SymGetLineFromAddr64 SymGetLineFromAddrW64 + #define SymGetLineNext64 SymGetLineNextW64 + #define SymGetLinePrev64 SymGetLinePrevW64 + #define SymFromName SymFromNameW + #define SymFindExecutableImage SymFindExecutableImageW + #define FindExecutableImageEx FindExecutableImageExW + #define SymSearch SymSearchW + #define SymEnumLines SymEnumLinesW + #define SymEnumSourceLines SymEnumSourceLinesW + #define SymGetTypeFromName SymGetTypeFromNameW + #define SymEnumSymbolsForAddr SymEnumSymbolsForAddrW + #define SymFromAddr SymFromAddrW + #define SymMatchString SymMatchStringW + #define SymEnumSourceFiles SymEnumSourceFilesW + #define SymEnumSymbols SymEnumSymbolsW + #define SymLoadModuleEx SymLoadModuleExW + #define SymSetSearchPath SymSetSearchPathW + #define SymGetSearchPath SymGetSearchPathW + #define EnumDirTree EnumDirTreeW + #define SymFromToken SymFromTokenW + #define SymFromIndex SymFromIndexW + #define SymGetScope SymGetScopeW + #define SymNext SymNextW + #define SymPrev SymPrevW + #define SymEnumTypes SymEnumTypesW + #define SymEnumTypesByName SymEnumTypesByNameW + #define SymRegisterCallback64 SymRegisterCallbackW64 + #define SymFindDebugInfoFile SymFindDebugInfoFileW + #define FindDebugInfoFileEx FindDebugInfoFileExW + #define SymFindFileInPath SymFindFileInPathW + #define SymEnumerateModules64 SymEnumerateModulesW64 + #define SymSetHomeDirectory SymSetHomeDirectoryW + #define SymGetHomeDirectory SymGetHomeDirectoryW + #define SymGetSourceFile SymGetSourceFileW + #define SymGetSourceFileToken SymGetSourceFileTokenW + #define SymGetSourceFileFromToken SymGetSourceFileFromTokenW + #define SymGetSourceVarFromToken SymGetSourceVarFromTokenW + #define SymGetSourceFileToken SymGetSourceFileTokenW + #define SymGetFileLineOffsets64 SymGetFileLineOffsetsW64 + #define SymFindFileInPath SymFindFileInPathW + #define SymMatchFileName SymMatchFileNameW + #define SymGetSourceFileFromToken SymGetSourceFileFromTokenW + #define SymGetSourceVarFromToken SymGetSourceVarFromTokenW + #define SymGetModuleInfo64 SymGetModuleInfoW64 + #define SymSrvIsStore SymSrvIsStoreW + #define SymSrvDeltaName SymSrvDeltaNameW + #define SymSrvGetSupplement SymSrvGetSupplementW + #define SymSrvStoreSupplement SymSrvStoreSupplementW + #define SymSrvGetFileIndexes SymSrvGetFileIndexes + #define SymSrvGetFileIndexString SymSrvGetFileIndexStringW + #define SymSrvStoreFile SymSrvStoreFileW + #define SymGetSymbolFile SymGetSymbolFileW + #define EnumerateLoadedModules64 EnumerateLoadedModulesW64 + #define EnumerateLoadedModulesEx EnumerateLoadedModulesExW + #define SymSrvGetFileIndexInfo SymSrvGetFileIndexInfoW + + #define IMAGEHLP_LINE64 IMAGEHLP_LINEW64 + #define PIMAGEHLP_LINE64 PIMAGEHLP_LINEW64 + #define SYMBOL_INFO SYMBOL_INFOW + #define PSYMBOL_INFO PSYMBOL_INFOW + #define SYMBOL_INFO_PACKAGE SYMBOL_INFO_PACKAGEW + #define PSYMBOL_INFO_PACKAGE PSYMBOL_INFO_PACKAGEW + #define FIND_EXE_FILE_CALLBACK FIND_EXE_FILE_CALLBACKW + #define PFIND_EXE_FILE_CALLBACK PFIND_EXE_FILE_CALLBACKW + #define SYM_ENUMERATESYMBOLS_CALLBACK SYM_ENUMERATESYMBOLS_CALLBACKW + #define PSYM_ENUMERATESYMBOLS_CALLBACK PSYM_ENUMERATESYMBOLS_CALLBACKW + #define SRCCODEINFO SRCCODEINFOW + #define PSRCCODEINFO PSRCCODEINFOW + #define SOURCEFILE SOURCEFILEW + #define PSOURCEFILE PSOURCEFILEW + #define SYM_ENUMSOURECFILES_CALLBACK SYM_ENUMSOURCEFILES_CALLBACKW + #define PSYM_ENUMSOURCEFILES_CALLBACK PSYM_ENUMSOURECFILES_CALLBACKW + #define IMAGEHLP_CBA_EVENT IMAGEHLP_CBA_EVENTW + #define PIMAGEHLP_CBA_EVENT PIMAGEHLP_CBA_EVENTW + #define PENUMDIRTREE_CALLBACK PENUMDIRTREE_CALLBACKW + #define IMAGEHLP_DEFERRED_SYMBOL_LOAD64 IMAGEHLP_DEFERRED_SYMBOL_LOADW64 + #define PIMAGEHLP_DEFERRED_SYMBOL_LOAD64 PIMAGEHLP_DEFERRED_SYMBOL_LOADW64 + #define PFIND_DEBUG_FILE_CALLBACK PFIND_DEBUG_FILE_CALLBACKW + #define PFINDFILEINPATHCALLBACK PFINDFILEINPATHCALLBACKW + #define IMAGEHLP_MODULE64 IMAGEHLP_MODULEW64 + #define PIMAGEHLP_MODULE64 PIMAGEHLP_MODULEW64 + #define SYMSRV_INDEX_INFO SYMSRV_INDEX_INFOW + #define PSYMSRV_INDEX_INFO PSYMSRV_INDEX_INFOW + + #define PSYMBOLSERVERPROC PSYMBOLSERVERPROCW + #define PSYMBOLSERVERPINGPROC PSYMBOLSERVERPINGPROCW +#endif + +// ----------------------------------------------------------------- +// The following APIs exist only for backwards compatibility +// with a pre-release version documented in an MSDN release. + +// You should use SymFindFileInPath if you want to maintain +// future compatibility. + +DBHLP_DEPRECIATED +BOOL +IMAGEAPI +FindFileInPath( + __in HANDLE hprocess, + __in PCSTR SearchPath, + __in PCSTR FileName, + __in PVOID id, + __in DWORD two, + __in DWORD three, + __in DWORD flags, + __out_ecount(MAX_PATH + 1) PSTR FilePath + ); + +// You should use SymFindFileInPath if you want to maintain +// future compatibility. + +DBHLP_DEPRECIATED +BOOL +IMAGEAPI +FindFileInSearchPath( + __in HANDLE hprocess, + __in PCSTR SearchPath, + __in PCSTR FileName, + __in DWORD one, + __in DWORD two, + __in DWORD three, + __out_ecount(MAX_PATH + 1) PSTR FilePath + ); + +DBHLP_DEPRECIATED +BOOL +IMAGEAPI +SymEnumSym( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback, + __in_opt PVOID UserContext + ); + +DBHLP_DEPRECIATED +BOOL +IMAGEAPI +SymEnumerateSymbols64( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in PSYM_ENUMSYMBOLS_CALLBACK64 EnumSymbolsCallback, + __in_opt PVOID UserContext + ); + +DBHLP_DEPRECIATED +BOOL +IMAGEAPI +SymEnumerateSymbolsW64( + __in HANDLE hProcess, + __in ULONG64 BaseOfDll, + __in PSYM_ENUMSYMBOLS_CALLBACK64W EnumSymbolsCallback, + __in_opt PVOID UserContext + ); + + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymEnumerateSymbols SymEnumerateSymbols64 +#define SymEnumerateSymbolsW SymEnumerateSymbolsW64 +#else +DBHLP_DEPRECIATED +BOOL +IMAGEAPI +SymEnumerateSymbols( + __in HANDLE hProcess, + __in ULONG BaseOfDll, + __in PSYM_ENUMSYMBOLS_CALLBACK EnumSymbolsCallback, + __in_opt PVOID UserContext + ); + +DBHLP_DEPRECIATED +BOOL +IMAGEAPI +SymEnumerateSymbolsW( + __in HANDLE hProcess, + __in ULONG BaseOfDll, + __in PSYM_ENUMSYMBOLS_CALLBACKW EnumSymbolsCallback, + __in_opt PVOID UserContext + ); +#endif + +// use SymLoadModuleEx + +DWORD64 +IMAGEAPI +SymLoadModule64( + __in HANDLE hProcess, + __in_opt HANDLE hFile, + __in_opt PCSTR ImageName, + __in_opt PCSTR ModuleName, + __in DWORD64 BaseOfDll, + __in DWORD SizeOfDll + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymLoadModule SymLoadModule64 +#else +DWORD +IMAGEAPI +SymLoadModule( + __in HANDLE hProcess, + __in_opt HANDLE hFile, + __in_opt PCSTR ImageName, + __in_opt PCSTR ModuleName, + __in DWORD BaseOfDll, + __in DWORD SizeOfDll + ); +#endif + +BOOL +IMAGEAPI +SymGetSymNext64( + __in HANDLE hProcess, + __inout PIMAGEHLP_SYMBOL64 Symbol + ); + +BOOL +IMAGEAPI +SymGetSymNextW64( + __in HANDLE hProcess, + __inout PIMAGEHLP_SYMBOLW64 Symbol + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymGetSymNext SymGetSymNext64 +#define SymGetSymNextW SymGetSymNextW64 +#else +BOOL +IMAGEAPI +SymGetSymNext( + __in HANDLE hProcess, + __inout PIMAGEHLP_SYMBOL Symbol + ); + +BOOL +IMAGEAPI +SymGetSymNextW( + __in HANDLE hProcess, + __inout PIMAGEHLP_SYMBOLW Symbol + ); +#endif + +BOOL +IMAGEAPI +SymGetSymPrev64( + __in HANDLE hProcess, + __inout PIMAGEHLP_SYMBOL64 Symbol + ); + +BOOL +IMAGEAPI +SymGetSymPrevW64( + __in HANDLE hProcess, + __inout PIMAGEHLP_SYMBOLW64 Symbol + ); + +#if !defined(_IMAGEHLP_SOURCE_) && defined(_IMAGEHLP64) +#define SymGetSymPrev SymGetSymPrev64 +#define SymGetSymPrevW SymGetSymPrevW64 +#else +BOOL +IMAGEAPI +SymGetSymPrev( + __in HANDLE hProcess, + __inout PIMAGEHLP_SYMBOL Symbol + ); + +BOOL +IMAGEAPI +SymGetSymPrevW( + __in HANDLE hProcess, + __inout PIMAGEHLP_SYMBOLW Symbol + ); +#endif + + +// These values should not be used. +// They have been replaced by SYMFLAG_ values. + +#define SYMF_OMAP_GENERATED 0x00000001 +#define SYMF_OMAP_MODIFIED 0x00000002 +#define SYMF_REGISTER 0x00000008 +#define SYMF_REGREL 0x00000010 +#define SYMF_FRAMEREL 0x00000020 +#define SYMF_PARAMETER 0x00000040 +#define SYMF_LOCAL 0x00000080 +#define SYMF_CONSTANT 0x00000100 +#define SYMF_EXPORT 0x00000200 +#define SYMF_FORWARDER 0x00000400 +#define SYMF_FUNCTION 0x00000800 +#define SYMF_VIRTUAL 0x00001000 +#define SYMF_THUNK 0x00002000 +#define SYMF_TLSREL 0x00004000 + +// These values should also not be used. +// They have been replaced by SYMFLAG_ values. + +#define IMAGEHLP_SYMBOL_INFO_VALUEPRESENT 1 +#define IMAGEHLP_SYMBOL_INFO_REGISTER SYMF_REGISTER // 0x0008 +#define IMAGEHLP_SYMBOL_INFO_REGRELATIVE SYMF_REGREL // 0x0010 +#define IMAGEHLP_SYMBOL_INFO_FRAMERELATIVE SYMF_FRAMEREL // 0x0020 +#define IMAGEHLP_SYMBOL_INFO_PARAMETER SYMF_PARAMETER // 0x0040 +#define IMAGEHLP_SYMBOL_INFO_LOCAL SYMF_LOCAL // 0x0080 +#define IMAGEHLP_SYMBOL_INFO_CONSTANT SYMF_CONSTANT // 0x0100 +#define IMAGEHLP_SYMBOL_FUNCTION SYMF_FUNCTION // 0x0800 +#define IMAGEHLP_SYMBOL_VIRTUAL SYMF_VIRTUAL // 0x1000 +#define IMAGEHLP_SYMBOL_THUNK SYMF_THUNK // 0x2000 +#define IMAGEHLP_SYMBOL_INFO_TLSRELATIVE SYMF_TLSREL // 0x4000 + +#include + + +#include + +#if defined(_MSC_VER) +#if _MSC_VER >= 800 +#if _MSC_VER >= 1200 +#pragma warning(push) +#endif +#pragma warning(disable:4200) /* Zero length array */ +#pragma warning(disable:4201) /* Nameless struct/union */ +#endif +#endif + +#define MINIDUMP_SIGNATURE ('PMDM') +#define MINIDUMP_VERSION (42899) +typedef DWORD RVA; +typedef ULONG64 RVA64; + +typedef struct _MINIDUMP_LOCATION_DESCRIPTOR { + ULONG32 DataSize; + RVA Rva; +} MINIDUMP_LOCATION_DESCRIPTOR; + +typedef struct _MINIDUMP_LOCATION_DESCRIPTOR64 { + ULONG64 DataSize; + RVA64 Rva; +} MINIDUMP_LOCATION_DESCRIPTOR64; + + +typedef struct _MINIDUMP_MEMORY_DESCRIPTOR { + ULONG64 StartOfMemoryRange; + MINIDUMP_LOCATION_DESCRIPTOR Memory; +} MINIDUMP_MEMORY_DESCRIPTOR, *PMINIDUMP_MEMORY_DESCRIPTOR; + +// DESCRIPTOR64 is used for full-memory minidumps where +// all of the raw memory is laid out sequentially at the +// end of the dump. There is no need for individual RVAs +// as the RVA is the base RVA plus the sum of the preceeding +// data blocks. +typedef struct _MINIDUMP_MEMORY_DESCRIPTOR64 { + ULONG64 StartOfMemoryRange; + ULONG64 DataSize; +} MINIDUMP_MEMORY_DESCRIPTOR64, *PMINIDUMP_MEMORY_DESCRIPTOR64; + + +typedef struct _MINIDUMP_HEADER { + ULONG32 Signature; + ULONG32 Version; + ULONG32 NumberOfStreams; + RVA StreamDirectoryRva; + ULONG32 CheckSum; + union { + ULONG32 Reserved; + ULONG32 TimeDateStamp; + }; + ULONG64 Flags; +} MINIDUMP_HEADER, *PMINIDUMP_HEADER; + +// +// The MINIDUMP_HEADER field StreamDirectoryRva points to +// an array of MINIDUMP_DIRECTORY structures. +// + +typedef struct _MINIDUMP_DIRECTORY { + ULONG32 StreamType; + MINIDUMP_LOCATION_DESCRIPTOR Location; +} MINIDUMP_DIRECTORY, *PMINIDUMP_DIRECTORY; + + +typedef struct _MINIDUMP_STRING { + ULONG32 Length; // Length in bytes of the string + WCHAR Buffer [0]; // Variable size buffer +} MINIDUMP_STRING, *PMINIDUMP_STRING; + + + +// +// The MINIDUMP_DIRECTORY field StreamType may be one of the following types. +// Types will be added in the future, so if a program reading the minidump +// header encounters a stream type it does not understand it should ignore +// the data altogether. Any tag above LastReservedStream will not be used by +// the system and is reserved for program-specific information. +// + +typedef enum _MINIDUMP_STREAM_TYPE { + + UnusedStream = 0, + ReservedStream0 = 1, + ReservedStream1 = 2, + ThreadListStream = 3, + ModuleListStream = 4, + MemoryListStream = 5, + ExceptionStream = 6, + SystemInfoStream = 7, + ThreadExListStream = 8, + Memory64ListStream = 9, + CommentStreamA = 10, + CommentStreamW = 11, + HandleDataStream = 12, + FunctionTableStream = 13, + UnloadedModuleListStream = 14, + MiscInfoStream = 15, + MemoryInfoListStream = 16, + ThreadInfoListStream = 17, + HandleOperationListStream = 18, + TokenStream = 19, + + ceStreamNull = 0x8000, + ceStreamSystemInfo = 0x8001, + ceStreamException = 0x8002, + ceStreamModuleList = 0x8003, + ceStreamProcessList = 0x8004, + ceStreamThreadList = 0x8005, + ceStreamThreadContextList = 0x8006, + ceStreamThreadCallStackList = 0x8007, + ceStreamMemoryVirtualList = 0x8008, + ceStreamMemoryPhysicalList = 0x8009, + ceStreamBucketParameters = 0x800A, + ceStreamProcessModuleMap = 0x800B, + ceStreamDiagnosisList = 0x800C, + + LastReservedStream = 0xffff + +} MINIDUMP_STREAM_TYPE; + + +// +// The minidump system information contains processor and +// Operating System specific information. +// + +// +// CPU information is obtained from one of two places. +// +// 1) On x86 computers, CPU_INFORMATION is obtained from the CPUID +// instruction. You must use the X86 portion of the union for X86 +// computers. +// +// 2) On non-x86 architectures, CPU_INFORMATION is obtained by calling +// IsProcessorFeatureSupported(). +// + +typedef union _CPU_INFORMATION { + + // + // X86 platforms use CPUID function to obtain processor information. + // + + struct { + + // + // CPUID Subfunction 0, register EAX (VendorId [0]), + // EBX (VendorId [1]) and ECX (VendorId [2]). + // + + ULONG32 VendorId [ 3 ]; + + // + // CPUID Subfunction 1, register EAX + // + + ULONG32 VersionInformation; + + // + // CPUID Subfunction 1, register EDX + // + + ULONG32 FeatureInformation; + + + // + // CPUID, Subfunction 80000001, register EBX. This will only + // be obtained if the vendor id is "AuthenticAMD". + // + + ULONG32 AMDExtendedCpuFeatures; + + } X86CpuInfo; + + // + // Non-x86 platforms use processor feature flags. + // + + struct { + + ULONG64 ProcessorFeatures [ 2 ]; + + } OtherCpuInfo; + +} CPU_INFORMATION, *PCPU_INFORMATION; + +typedef struct _MINIDUMP_SYSTEM_INFO { + + // + // ProcessorArchitecture, ProcessorLevel and ProcessorRevision are all + // taken from the SYSTEM_INFO structure obtained by GetSystemInfo( ). + // + + USHORT ProcessorArchitecture; + USHORT ProcessorLevel; + USHORT ProcessorRevision; + + union { + USHORT Reserved0; + struct { + UCHAR NumberOfProcessors; + UCHAR ProductType; + }; + }; + + // + // MajorVersion, MinorVersion, BuildNumber, PlatformId and + // CSDVersion are all taken from the OSVERSIONINFO structure + // returned by GetVersionEx( ). + // + + ULONG32 MajorVersion; + ULONG32 MinorVersion; + ULONG32 BuildNumber; + ULONG32 PlatformId; + + // + // RVA to a CSDVersion string in the string table. + // + + RVA CSDVersionRva; + + union { + ULONG32 Reserved1; + struct { + USHORT SuiteMask; + USHORT Reserved2; + }; + }; + + CPU_INFORMATION Cpu; + +} MINIDUMP_SYSTEM_INFO, *PMINIDUMP_SYSTEM_INFO; + + +// +// The minidump thread contains standard thread +// information plus an RVA to the memory for this +// thread and an RVA to the CONTEXT structure for +// this thread. +// + + +// +// ThreadId must be 4 bytes on all architectures. +// + +C_ASSERT (sizeof ( ((PPROCESS_INFORMATION)0)->dwThreadId ) == 4); + +typedef struct _MINIDUMP_THREAD { + ULONG32 ThreadId; + ULONG32 SuspendCount; + ULONG32 PriorityClass; + ULONG32 Priority; + ULONG64 Teb; + MINIDUMP_MEMORY_DESCRIPTOR Stack; + MINIDUMP_LOCATION_DESCRIPTOR ThreadContext; +} MINIDUMP_THREAD, *PMINIDUMP_THREAD; + +// +// The thread list is a container of threads. +// + +typedef struct _MINIDUMP_THREAD_LIST { + ULONG32 NumberOfThreads; + MINIDUMP_THREAD Threads [0]; +} MINIDUMP_THREAD_LIST, *PMINIDUMP_THREAD_LIST; + + +typedef struct _MINIDUMP_THREAD_EX { + ULONG32 ThreadId; + ULONG32 SuspendCount; + ULONG32 PriorityClass; + ULONG32 Priority; + ULONG64 Teb; + MINIDUMP_MEMORY_DESCRIPTOR Stack; + MINIDUMP_LOCATION_DESCRIPTOR ThreadContext; + MINIDUMP_MEMORY_DESCRIPTOR BackingStore; +} MINIDUMP_THREAD_EX, *PMINIDUMP_THREAD_EX; + +// +// The thread list is a container of threads. +// + +typedef struct _MINIDUMP_THREAD_EX_LIST { + ULONG32 NumberOfThreads; + MINIDUMP_THREAD_EX Threads [0]; +} MINIDUMP_THREAD_EX_LIST, *PMINIDUMP_THREAD_EX_LIST; + + +// +// The MINIDUMP_EXCEPTION is the same as EXCEPTION on Win64. +// + +typedef struct _MINIDUMP_EXCEPTION { + ULONG32 ExceptionCode; + ULONG32 ExceptionFlags; + ULONG64 ExceptionRecord; + ULONG64 ExceptionAddress; + ULONG32 NumberParameters; + ULONG32 __unusedAlignment; + ULONG64 ExceptionInformation [ EXCEPTION_MAXIMUM_PARAMETERS ]; +} MINIDUMP_EXCEPTION, *PMINIDUMP_EXCEPTION; + + +// +// The exception information stream contains the id of the thread that caused +// the exception (ThreadId), the exception record for the exception +// (ExceptionRecord) and an RVA to the thread context where the exception +// occured. +// + +typedef struct MINIDUMP_EXCEPTION_STREAM { + ULONG32 ThreadId; + ULONG32 __alignment; + MINIDUMP_EXCEPTION ExceptionRecord; + MINIDUMP_LOCATION_DESCRIPTOR ThreadContext; +} MINIDUMP_EXCEPTION_STREAM, *PMINIDUMP_EXCEPTION_STREAM; + + +// +// The MINIDUMP_MODULE contains information about a +// a specific module. It includes the CheckSum and +// the TimeDateStamp for the module so the module +// can be reloaded during the analysis phase. +// + +typedef struct _MINIDUMP_MODULE { + ULONG64 BaseOfImage; + ULONG32 SizeOfImage; + ULONG32 CheckSum; + ULONG32 TimeDateStamp; + RVA ModuleNameRva; + VS_FIXEDFILEINFO VersionInfo; + MINIDUMP_LOCATION_DESCRIPTOR CvRecord; + MINIDUMP_LOCATION_DESCRIPTOR MiscRecord; + ULONG64 Reserved0; // Reserved for future use. + ULONG64 Reserved1; // Reserved for future use. +} MINIDUMP_MODULE, *PMINIDUMP_MODULE; + + +// +// The minidump module list is a container for modules. +// + +typedef struct _MINIDUMP_MODULE_LIST { + ULONG32 NumberOfModules; + MINIDUMP_MODULE Modules [ 0 ]; +} MINIDUMP_MODULE_LIST, *PMINIDUMP_MODULE_LIST; + + +// +// Memory Ranges +// + +typedef struct _MINIDUMP_MEMORY_LIST { + ULONG32 NumberOfMemoryRanges; + MINIDUMP_MEMORY_DESCRIPTOR MemoryRanges [0]; +} MINIDUMP_MEMORY_LIST, *PMINIDUMP_MEMORY_LIST; + +typedef struct _MINIDUMP_MEMORY64_LIST { + ULONG64 NumberOfMemoryRanges; + RVA64 BaseRva; + MINIDUMP_MEMORY_DESCRIPTOR64 MemoryRanges [0]; +} MINIDUMP_MEMORY64_LIST, *PMINIDUMP_MEMORY64_LIST; + + +// +// Support for user supplied exception information. +// + +typedef struct _MINIDUMP_EXCEPTION_INFORMATION { + DWORD ThreadId; + PEXCEPTION_POINTERS ExceptionPointers; + BOOL ClientPointers; +} MINIDUMP_EXCEPTION_INFORMATION, *PMINIDUMP_EXCEPTION_INFORMATION; + +typedef struct _MINIDUMP_EXCEPTION_INFORMATION64 { + DWORD ThreadId; + ULONG64 ExceptionRecord; + ULONG64 ContextRecord; + BOOL ClientPointers; +} MINIDUMP_EXCEPTION_INFORMATION64, *PMINIDUMP_EXCEPTION_INFORMATION64; + + +// +// Support for capturing system handle state at the time of the dump. +// + +// Per-handle object information varies according to +// the OS, the OS version, the processor type and +// so on. The minidump gives a minidump identifier +// to each possible data format for identification +// purposes but does not control nor describe the actual data. +typedef enum _MINIDUMP_HANDLE_OBJECT_INFORMATION_TYPE { + MiniHandleObjectInformationNone, + MiniThreadInformation1, + MiniMutantInformation1, + MiniMutantInformation2, + MiniProcessInformation1, + MiniProcessInformation2, + MiniHandleObjectInformationTypeMax +} MINIDUMP_HANDLE_OBJECT_INFORMATION_TYPE; + +typedef struct _MINIDUMP_HANDLE_OBJECT_INFORMATION { + RVA NextInfoRva; + ULONG32 InfoType; + ULONG32 SizeOfInfo; + // Raw information follows. +} MINIDUMP_HANDLE_OBJECT_INFORMATION; + +typedef struct _MINIDUMP_HANDLE_DESCRIPTOR { + ULONG64 Handle; + RVA TypeNameRva; + RVA ObjectNameRva; + ULONG32 Attributes; + ULONG32 GrantedAccess; + ULONG32 HandleCount; + ULONG32 PointerCount; +} MINIDUMP_HANDLE_DESCRIPTOR, *PMINIDUMP_HANDLE_DESCRIPTOR; + +typedef struct _MINIDUMP_HANDLE_DESCRIPTOR_2 { + ULONG64 Handle; + RVA TypeNameRva; + RVA ObjectNameRva; + ULONG32 Attributes; + ULONG32 GrantedAccess; + ULONG32 HandleCount; + ULONG32 PointerCount; + RVA ObjectInfoRva; + ULONG32 Reserved0; +} MINIDUMP_HANDLE_DESCRIPTOR_2, *PMINIDUMP_HANDLE_DESCRIPTOR_2; + +// The latest MINIDUMP_HANDLE_DESCRIPTOR definition. +typedef MINIDUMP_HANDLE_DESCRIPTOR_2 MINIDUMP_HANDLE_DESCRIPTOR_N; +typedef MINIDUMP_HANDLE_DESCRIPTOR_N *PMINIDUMP_HANDLE_DESCRIPTOR_N; + +typedef struct _MINIDUMP_HANDLE_DATA_STREAM { + ULONG32 SizeOfHeader; + ULONG32 SizeOfDescriptor; + ULONG32 NumberOfDescriptors; + ULONG32 Reserved; +} MINIDUMP_HANDLE_DATA_STREAM, *PMINIDUMP_HANDLE_DATA_STREAM; + +// Some operating systems can track the last operations +// performed on a handle. For example, Application Verifier +// can enable this for some versions of Windows. The +// handle operation list collects handle operations +// known for the dump target. +// Each entry is an AVRF_HANDLE_OPERATION. +typedef struct _MINIDUMP_HANDLE_OPERATION_LIST { + ULONG32 SizeOfHeader; + ULONG32 SizeOfEntry; + ULONG32 NumberOfEntries; + ULONG32 Reserved; +} MINIDUMP_HANDLE_OPERATION_LIST, *PMINIDUMP_HANDLE_OPERATION_LIST; + + +// +// Support for capturing dynamic function table state at the time of the dump. +// + +typedef struct _MINIDUMP_FUNCTION_TABLE_DESCRIPTOR { + ULONG64 MinimumAddress; + ULONG64 MaximumAddress; + ULONG64 BaseAddress; + ULONG32 EntryCount; + ULONG32 SizeOfAlignPad; +} MINIDUMP_FUNCTION_TABLE_DESCRIPTOR, *PMINIDUMP_FUNCTION_TABLE_DESCRIPTOR; + +typedef struct _MINIDUMP_FUNCTION_TABLE_STREAM { + ULONG32 SizeOfHeader; + ULONG32 SizeOfDescriptor; + ULONG32 SizeOfNativeDescriptor; + ULONG32 SizeOfFunctionEntry; + ULONG32 NumberOfDescriptors; + ULONG32 SizeOfAlignPad; +} MINIDUMP_FUNCTION_TABLE_STREAM, *PMINIDUMP_FUNCTION_TABLE_STREAM; + + +// +// The MINIDUMP_UNLOADED_MODULE contains information about a +// a specific module that was previously loaded but no +// longer is. This can help with diagnosing problems where +// callers attempt to call code that is no longer loaded. +// + +typedef struct _MINIDUMP_UNLOADED_MODULE { + ULONG64 BaseOfImage; + ULONG32 SizeOfImage; + ULONG32 CheckSum; + ULONG32 TimeDateStamp; + RVA ModuleNameRva; +} MINIDUMP_UNLOADED_MODULE, *PMINIDUMP_UNLOADED_MODULE; + + +// +// The minidump unloaded module list is a container for unloaded modules. +// + +typedef struct _MINIDUMP_UNLOADED_MODULE_LIST { + ULONG32 SizeOfHeader; + ULONG32 SizeOfEntry; + ULONG32 NumberOfEntries; +} MINIDUMP_UNLOADED_MODULE_LIST, *PMINIDUMP_UNLOADED_MODULE_LIST; + + +// +// The miscellaneous information stream contains a variety +// of small pieces of information. A member is valid if +// it's within the available size and its corresponding +// bit is set. +// + +#define MINIDUMP_MISC1_PROCESS_ID 0x00000001 +#define MINIDUMP_MISC1_PROCESS_TIMES 0x00000002 +#define MINIDUMP_MISC1_PROCESSOR_POWER_INFO 0x00000004 +#define MINIDUMP_MISC3_PROCESS_INTEGRITY 0x00000010 +#define MINIDUMP_MISC3_PROCESS_EXECUTE_FLAGS 0x00000020 +#define MINIDUMP_MISC3_TIMEZONE 0x00000040 +#define MINIDUMP_MISC3_PROTECTED_PROCESS 0x00000080 + +typedef struct _MINIDUMP_MISC_INFO { + ULONG32 SizeOfInfo; + ULONG32 Flags1; + ULONG32 ProcessId; + ULONG32 ProcessCreateTime; + ULONG32 ProcessUserTime; + ULONG32 ProcessKernelTime; +} MINIDUMP_MISC_INFO, *PMINIDUMP_MISC_INFO; + +typedef struct _MINIDUMP_MISC_INFO_2 { + ULONG32 SizeOfInfo; + ULONG32 Flags1; + ULONG32 ProcessId; + ULONG32 ProcessCreateTime; + ULONG32 ProcessUserTime; + ULONG32 ProcessKernelTime; + ULONG32 ProcessorMaxMhz; + ULONG32 ProcessorCurrentMhz; + ULONG32 ProcessorMhzLimit; + ULONG32 ProcessorMaxIdleState; + ULONG32 ProcessorCurrentIdleState; +} MINIDUMP_MISC_INFO_2, *PMINIDUMP_MISC_INFO_2; + +typedef struct _MINIDUMP_MISC_INFO_3 { + ULONG32 SizeOfInfo; + ULONG32 Flags1; + ULONG32 ProcessId; + ULONG32 ProcessCreateTime; + ULONG32 ProcessUserTime; + ULONG32 ProcessKernelTime; + ULONG32 ProcessorMaxMhz; + ULONG32 ProcessorCurrentMhz; + ULONG32 ProcessorMhzLimit; + ULONG32 ProcessorMaxIdleState; + ULONG32 ProcessorCurrentIdleState; + ULONG32 ProcessIntegrityLevel; + ULONG32 ProcessExecuteFlags; + ULONG32 ProtectedProcess; + ULONG32 TimeZoneId; + TIME_ZONE_INFORMATION TimeZone; +} MINIDUMP_MISC_INFO_3, *PMINIDUMP_MISC_INFO_3; + +// The latest MINIDUMP_MISC_INFO definition. +typedef MINIDUMP_MISC_INFO_3 MINIDUMP_MISC_INFO_N; +typedef MINIDUMP_MISC_INFO_N* PMINIDUMP_MISC_INFO_N; + + +// +// The memory information stream contains memory region +// description information. This stream corresponds to +// what VirtualQuery would return for the process the +// dump was created for. +// + +typedef struct _MINIDUMP_MEMORY_INFO { + ULONG64 BaseAddress; + ULONG64 AllocationBase; + ULONG32 AllocationProtect; + ULONG32 __alignment1; + ULONG64 RegionSize; + ULONG32 State; + ULONG32 Protect; + ULONG32 Type; + ULONG32 __alignment2; +} MINIDUMP_MEMORY_INFO, *PMINIDUMP_MEMORY_INFO; + +typedef struct _MINIDUMP_MEMORY_INFO_LIST { + ULONG SizeOfHeader; + ULONG SizeOfEntry; + ULONG64 NumberOfEntries; +} MINIDUMP_MEMORY_INFO_LIST, *PMINIDUMP_MEMORY_INFO_LIST; + + +// +// The memory information stream contains memory region +// description information. This stream corresponds to +// what VirtualQuery would return for the process the +// dump was created for. +// + +// Thread dump writer status flags. +#define MINIDUMP_THREAD_INFO_ERROR_THREAD 0x00000001 +#define MINIDUMP_THREAD_INFO_WRITING_THREAD 0x00000002 +#define MINIDUMP_THREAD_INFO_EXITED_THREAD 0x00000004 +#define MINIDUMP_THREAD_INFO_INVALID_INFO 0x00000008 +#define MINIDUMP_THREAD_INFO_INVALID_CONTEXT 0x00000010 +#define MINIDUMP_THREAD_INFO_INVALID_TEB 0x00000020 + +typedef struct _MINIDUMP_THREAD_INFO { + ULONG32 ThreadId; + ULONG32 DumpFlags; + ULONG32 DumpError; + ULONG32 ExitStatus; + ULONG64 CreateTime; + ULONG64 ExitTime; + ULONG64 KernelTime; + ULONG64 UserTime; + ULONG64 StartAddress; + ULONG64 Affinity; +} MINIDUMP_THREAD_INFO, *PMINIDUMP_THREAD_INFO; + +typedef struct _MINIDUMP_THREAD_INFO_LIST { + ULONG SizeOfHeader; + ULONG SizeOfEntry; + ULONG NumberOfEntries; +} MINIDUMP_THREAD_INFO_LIST, *PMINIDUMP_THREAD_INFO_LIST; + +// +// Support for token information. +// +typedef struct _MINIDUMP_TOKEN_INFO_HEADER { + ULONG TokenSize; // The size of the token structure. + ULONG TokenId; // The PID in NtOpenProcessToken() call or TID in NtOpenThreadToken() call. + ULONG64 TokenHandle; // The handle value returned. +} MINIDUMP_TOKEN_INFO_HEADER, *PMINIDUMP_TOKEN_INFO_HEADER; + +typedef struct _MINIDUMP_TOKEN_INFO_LIST { + ULONG TokenListSize; + ULONG TokenListEntries; + ULONG ListHeaderSize; + ULONG ElementHeaderSize; +} MINIDUMP_TOKEN_INFO_LIST, *PMINIDUMP_TOKEN_INFO_LIST; + +// +// Support for arbitrary user-defined information. +// + +typedef struct _MINIDUMP_USER_RECORD { + ULONG32 Type; + MINIDUMP_LOCATION_DESCRIPTOR Memory; +} MINIDUMP_USER_RECORD, *PMINIDUMP_USER_RECORD; + + +typedef struct _MINIDUMP_USER_STREAM { + ULONG32 Type; + ULONG BufferSize; + PVOID Buffer; + +} MINIDUMP_USER_STREAM, *PMINIDUMP_USER_STREAM; + + +typedef struct _MINIDUMP_USER_STREAM_INFORMATION { + ULONG UserStreamCount; + PMINIDUMP_USER_STREAM UserStreamArray; +} MINIDUMP_USER_STREAM_INFORMATION, *PMINIDUMP_USER_STREAM_INFORMATION; + +// +// Callback support. +// + +typedef enum _MINIDUMP_CALLBACK_TYPE { + ModuleCallback, + ThreadCallback, + ThreadExCallback, + IncludeThreadCallback, + IncludeModuleCallback, + MemoryCallback, + CancelCallback, + WriteKernelMinidumpCallback, + KernelMinidumpStatusCallback, + RemoveMemoryCallback, + IncludeVmRegionCallback, + IoStartCallback, + IoWriteAllCallback, + IoFinishCallback, + ReadMemoryFailureCallback, + SecondaryFlagsCallback, +} MINIDUMP_CALLBACK_TYPE; + + +typedef struct _MINIDUMP_THREAD_CALLBACK { + ULONG ThreadId; + HANDLE ThreadHandle; + CONTEXT Context; + ULONG SizeOfContext; + ULONG64 StackBase; + ULONG64 StackEnd; +} MINIDUMP_THREAD_CALLBACK, *PMINIDUMP_THREAD_CALLBACK; + + +typedef struct _MINIDUMP_THREAD_EX_CALLBACK { + ULONG ThreadId; + HANDLE ThreadHandle; + CONTEXT Context; + ULONG SizeOfContext; + ULONG64 StackBase; + ULONG64 StackEnd; + ULONG64 BackingStoreBase; + ULONG64 BackingStoreEnd; +} MINIDUMP_THREAD_EX_CALLBACK, *PMINIDUMP_THREAD_EX_CALLBACK; + + +typedef struct _MINIDUMP_INCLUDE_THREAD_CALLBACK { + ULONG ThreadId; +} MINIDUMP_INCLUDE_THREAD_CALLBACK, *PMINIDUMP_INCLUDE_THREAD_CALLBACK; + + +typedef enum _THREAD_WRITE_FLAGS { + ThreadWriteThread = 0x0001, + ThreadWriteStack = 0x0002, + ThreadWriteContext = 0x0004, + ThreadWriteBackingStore = 0x0008, + ThreadWriteInstructionWindow = 0x0010, + ThreadWriteThreadData = 0x0020, + ThreadWriteThreadInfo = 0x0040, +} THREAD_WRITE_FLAGS; + +typedef struct _MINIDUMP_MODULE_CALLBACK { + PWCHAR FullPath; + ULONG64 BaseOfImage; + ULONG SizeOfImage; + ULONG CheckSum; + ULONG TimeDateStamp; + VS_FIXEDFILEINFO VersionInfo; + PVOID CvRecord; + ULONG SizeOfCvRecord; + PVOID MiscRecord; + ULONG SizeOfMiscRecord; +} MINIDUMP_MODULE_CALLBACK, *PMINIDUMP_MODULE_CALLBACK; + + +typedef struct _MINIDUMP_INCLUDE_MODULE_CALLBACK { + ULONG64 BaseOfImage; +} MINIDUMP_INCLUDE_MODULE_CALLBACK, *PMINIDUMP_INCLUDE_MODULE_CALLBACK; + + +typedef enum _MODULE_WRITE_FLAGS { + ModuleWriteModule = 0x0001, + ModuleWriteDataSeg = 0x0002, + ModuleWriteMiscRecord = 0x0004, + ModuleWriteCvRecord = 0x0008, + ModuleReferencedByMemory = 0x0010, + ModuleWriteTlsData = 0x0020, + ModuleWriteCodeSegs = 0x0040, +} MODULE_WRITE_FLAGS; + + +typedef struct _MINIDUMP_IO_CALLBACK { + HANDLE Handle; + ULONG64 Offset; + PVOID Buffer; + ULONG BufferBytes; +} MINIDUMP_IO_CALLBACK, *PMINIDUMP_IO_CALLBACK; + + +typedef struct _MINIDUMP_READ_MEMORY_FAILURE_CALLBACK +{ + ULONG64 Offset; + ULONG Bytes; + HRESULT FailureStatus; +} MINIDUMP_READ_MEMORY_FAILURE_CALLBACK, + *PMINIDUMP_READ_MEMORY_FAILURE_CALLBACK; + + +typedef struct _MINIDUMP_CALLBACK_INPUT { + ULONG ProcessId; + HANDLE ProcessHandle; + ULONG CallbackType; + union { + HRESULT Status; + MINIDUMP_THREAD_CALLBACK Thread; + MINIDUMP_THREAD_EX_CALLBACK ThreadEx; + MINIDUMP_MODULE_CALLBACK Module; + MINIDUMP_INCLUDE_THREAD_CALLBACK IncludeThread; + MINIDUMP_INCLUDE_MODULE_CALLBACK IncludeModule; + MINIDUMP_IO_CALLBACK Io; + MINIDUMP_READ_MEMORY_FAILURE_CALLBACK ReadMemoryFailure; + ULONG SecondaryFlags; + }; +} MINIDUMP_CALLBACK_INPUT, *PMINIDUMP_CALLBACK_INPUT; + +typedef struct _MINIDUMP_CALLBACK_OUTPUT { + union { + ULONG ModuleWriteFlags; + ULONG ThreadWriteFlags; + ULONG SecondaryFlags; + struct { + ULONG64 MemoryBase; + ULONG MemorySize; + }; + struct { + BOOL CheckCancel; + BOOL Cancel; + }; + HANDLE Handle; + struct { + MINIDUMP_MEMORY_INFO VmRegion; + BOOL Continue; + }; + HRESULT Status; + }; +} MINIDUMP_CALLBACK_OUTPUT, *PMINIDUMP_CALLBACK_OUTPUT; + + +// +// A normal minidump contains just the information +// necessary to capture stack traces for all of the +// existing threads in a process. +// +// A minidump with data segments includes all of the data +// sections from loaded modules in order to capture +// global variable contents. This can make the dump much +// larger if many modules have global data. +// +// A minidump with full memory includes all of the accessible +// memory in the process and can be very large. A minidump +// with full memory always has the raw memory data at the end +// of the dump so that the initial structures in the dump can +// be mapped directly without having to include the raw +// memory information. +// +// Stack and backing store memory can be filtered to remove +// data unnecessary for stack walking. This can improve +// compression of stacks and also deletes data that may +// be private and should not be stored in a dump. +// Memory can also be scanned to see what modules are +// referenced by stack and backing store memory to allow +// omission of other modules to reduce dump size. +// In either of these modes the ModuleReferencedByMemory flag +// is set for all modules referenced before the base +// module callbacks occur. +// +// On some operating systems a list of modules that were +// recently unloaded is kept in addition to the currently +// loaded module list. This information can be saved in +// the dump if desired. +// +// Stack and backing store memory can be scanned for referenced +// pages in order to pick up data referenced by locals or other +// stack memory. This can increase the size of a dump significantly. +// +// Module paths may contain undesired information such as user names +// or other important directory names so they can be stripped. This +// option reduces the ability to locate the proper image later +// and should only be used in certain situations. +// +// Complete operating system per-process and per-thread information can +// be gathered and stored in the dump. +// +// The virtual address space can be scanned for various types +// of memory to be included in the dump. +// +// Code which is concerned with potentially private information +// getting into the minidump can set a flag that automatically +// modifies all existing and future flags to avoid placing +// unnecessary data in the dump. Basic data, such as stack +// information, will still be included but optional data, such +// as indirect memory, will not. +// +// When doing a full memory dump it's possible to store all +// of the enumerated memory region descriptive information +// in a memory information stream. +// +// Additional thread information beyond the basic thread +// structure can be collected if desired. +// +// A minidump with code segments includes all of the code +// and code-related sections from loaded modules in order +// to capture executable content. +// +// MiniDumpWithoutAuxiliaryState turns off any secondary, +// auxiliary-supported memory gathering. +// +// MiniDumpWithFullAuxiliaryState asks any present auxiliary +// data providers to include all of their state in the dump. +// The exact set of what is provided depends on the auxiliary. +// This can be quite large. +// + +typedef enum _MINIDUMP_TYPE { + MiniDumpNormal = 0x00000000, + MiniDumpWithDataSegs = 0x00000001, + MiniDumpWithFullMemory = 0x00000002, + MiniDumpWithHandleData = 0x00000004, + MiniDumpFilterMemory = 0x00000008, + MiniDumpScanMemory = 0x00000010, + MiniDumpWithUnloadedModules = 0x00000020, + MiniDumpWithIndirectlyReferencedMemory = 0x00000040, + MiniDumpFilterModulePaths = 0x00000080, + MiniDumpWithProcessThreadData = 0x00000100, + MiniDumpWithPrivateReadWriteMemory = 0x00000200, + MiniDumpWithoutOptionalData = 0x00000400, + MiniDumpWithFullMemoryInfo = 0x00000800, + MiniDumpWithThreadInfo = 0x00001000, + MiniDumpWithCodeSegs = 0x00002000, + MiniDumpWithoutAuxiliaryState = 0x00004000, + MiniDumpWithFullAuxiliaryState = 0x00008000, + MiniDumpWithPrivateWriteCopyMemory = 0x00010000, + MiniDumpIgnoreInaccessibleMemory = 0x00020000, + MiniDumpWithTokenInformation = 0x00040000, + MiniDumpValidTypeFlags = 0x0007ffff, +} MINIDUMP_TYPE; + +// +// In addition to the primary flags provided to +// MiniDumpWriteDump there are additional, less +// frequently used options queried via the secondary +// flags callback. +// +// MiniSecondaryWithoutPowerInfo suppresses the minidump +// query that retrieves processor power information for +// MINIDUMP_MISC_INFO. +// + +typedef enum _MINIDUMP_SECONDARY_FLAGS { + MiniSecondaryWithoutPowerInfo = 0x00000001, + + MiniSecondaryValidFlags = 0x00000001, +} MINIDUMP_SECONDARY_FLAGS; + + +// +// The minidump callback should modify the FieldsToWrite parameter to reflect +// what portions of the specified thread or module should be written to the +// file. +// + +typedef +BOOL +(WINAPI * MINIDUMP_CALLBACK_ROUTINE) ( + __inout PVOID CallbackParam, + __in PMINIDUMP_CALLBACK_INPUT CallbackInput, + __inout PMINIDUMP_CALLBACK_OUTPUT CallbackOutput + ); + +typedef struct _MINIDUMP_CALLBACK_INFORMATION { + MINIDUMP_CALLBACK_ROUTINE CallbackRoutine; + PVOID CallbackParam; +} MINIDUMP_CALLBACK_INFORMATION, *PMINIDUMP_CALLBACK_INFORMATION; + + + +//++ +// +// PVOID +// RVA_TO_ADDR( +// PVOID Mapping, +// ULONG Rva +// ) +// +// Routine Description: +// +// Map an RVA that is contained within a mapped file to it's associated +// flat address. +// +// Arguments: +// +// Mapping - Base address of mapped file containing the RVA. +// +// Rva - An Rva to fixup. +// +// Return Values: +// +// A pointer to the desired data. +// +//-- + +#define RVA_TO_ADDR(Mapping,Rva) ((PVOID)(((ULONG_PTR) (Mapping)) + (Rva))) + +BOOL +WINAPI +MiniDumpWriteDump( + __in HANDLE hProcess, + __in DWORD ProcessId, + __in HANDLE hFile, + __in MINIDUMP_TYPE DumpType, + __in_opt PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, + __in_opt PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, + __in_opt PMINIDUMP_CALLBACK_INFORMATION CallbackParam + ); + +BOOL +WINAPI +MiniDumpReadDumpStream( + __in PVOID BaseOfDump, + __in ULONG StreamNumber, + __deref_out_opt PMINIDUMP_DIRECTORY * Dir, + __deref_out_opt PVOID * StreamPointer, + __out_opt ULONG * StreamSize + ); + +#if defined(_MSC_VER) +#if _MSC_VER >= 800 +#if _MSC_VER >= 1200 +#pragma warning(pop) +#else +#pragma warning(default:4200) /* Zero length array */ +#pragma warning(default:4201) /* Nameless struct/union */ +#endif +#endif +#endif + +#include + +#ifdef __cplusplus +} +#endif + + +#endif // _DBGHELP_ + diff --git a/lib/dbghelp/lib/Win32/DbgHelp.Lib b/lib/dbghelp/lib/Win32/DbgHelp.Lib new file mode 100644 index 00000000..8ae9cf97 Binary files /dev/null and b/lib/dbghelp/lib/Win32/DbgHelp.Lib differ diff --git a/lib/dbghelp/lib/x64/DbgHelp.Lib b/lib/dbghelp/lib/x64/DbgHelp.Lib new file mode 100644 index 00000000..07608792 Binary files /dev/null and b/lib/dbghelp/lib/x64/DbgHelp.Lib differ diff --git a/lib/gtest/CHANGES b/lib/gtest/CHANGES new file mode 100644 index 00000000..05521324 --- /dev/null +++ b/lib/gtest/CHANGES @@ -0,0 +1,157 @@ +Changes for 1.7.0: + +* New feature: death tests are supported on OpenBSD and in iOS + simulator now. +* New feature: Google Test now implements a protocol to allow + a test runner to detect that a test program has exited + prematurely and report it as a failure (before it would be + falsely reported as a success if the exit code is 0). +* New feature: Test::RecordProperty() can now be used outside of the + lifespan of a test method, in which case it will be attributed to + the current test case or the test program in the XML report. +* New feature (potentially breaking): --gtest_list_tests now prints + the type parameters and value parameters for each test. +* Improvement: char pointers and char arrays are now escaped properly + in failure messages. +* Improvement: failure summary in XML reports now includes file and + line information. +* Improvement: the XML element now has a timestamp attribute. +* Improvement: When --gtest_filter is specified, XML report now doesn't + contain information about tests that are filtered out. +* Fixed the bug where long --gtest_filter flag values are truncated in + death tests. +* Potentially breaking change: RUN_ALL_TESTS() is now implemented as a + function instead of a macro in order to work better with Clang. +* Compatibility fixes with C++ 11 and various platforms. +* Bug/warning fixes. + +Changes for 1.6.0: + +* New feature: ADD_FAILURE_AT() for reporting a test failure at the + given source location -- useful for writing testing utilities. +* New feature: the universal value printer is moved from Google Mock + to Google Test. +* New feature: type parameters and value parameters are reported in + the XML report now. +* A gtest_disable_pthreads CMake option. +* Colored output works in GNU Screen sessions now. +* Parameters of value-parameterized tests are now printed in the + textual output. +* Failures from ad hoc test assertions run before RUN_ALL_TESTS() are + now correctly reported. +* Arguments of ASSERT_XY and EXPECT_XY no longer need to support << to + ostream. +* More complete handling of exceptions. +* GTEST_ASSERT_XY can be used instead of ASSERT_XY in case the latter + name is already used by another library. +* --gtest_catch_exceptions is now true by default, allowing a test + program to continue after an exception is thrown. +* Value-parameterized test fixtures can now derive from Test and + WithParamInterface separately, easing conversion of legacy tests. +* Death test messages are clearly marked to make them more + distinguishable from other messages. +* Compatibility fixes for Android, Google Native Client, MinGW, HP UX, + PowerPC, Lucid autotools, libCStd, Sun C++, Borland C++ Builder (Code Gear), + IBM XL C++ (Visual Age C++), and C++0x. +* Bug fixes and implementation clean-ups. +* Potentially incompatible changes: disables the harmful 'make install' + command in autotools. + +Changes for 1.5.0: + + * New feature: assertions can be safely called in multiple threads + where the pthreads library is available. + * New feature: predicates used inside EXPECT_TRUE() and friends + can now generate custom failure messages. + * New feature: Google Test can now be compiled as a DLL. + * New feature: fused source files are included. + * New feature: prints help when encountering unrecognized Google Test flags. + * Experimental feature: CMake build script (requires CMake 2.6.4+). + * Experimental feature: the Pump script for meta programming. + * double values streamed to an assertion are printed with enough precision + to differentiate any two different values. + * Google Test now works on Solaris and AIX. + * Build and test script improvements. + * Bug fixes and implementation clean-ups. + + Potentially breaking changes: + + * Stopped supporting VC++ 7.1 with exceptions disabled. + * Dropped support for 'make install'. + +Changes for 1.4.0: + + * New feature: the event listener API + * New feature: test shuffling + * New feature: the XML report format is closer to junitreport and can + be parsed by Hudson now. + * New feature: when a test runs under Visual Studio, its failures are + integrated in the IDE. + * New feature: /MD(d) versions of VC++ projects. + * New feature: elapsed time for the tests is printed by default. + * New feature: comes with a TR1 tuple implementation such that Boost + is no longer needed for Combine(). + * New feature: EXPECT_DEATH_IF_SUPPORTED macro and friends. + * New feature: the Xcode project can now produce static gtest + libraries in addition to a framework. + * Compatibility fixes for Solaris, Cygwin, minGW, Windows Mobile, + Symbian, gcc, and C++Builder. + * Bug fixes and implementation clean-ups. + +Changes for 1.3.0: + + * New feature: death tests on Windows, Cygwin, and Mac. + * New feature: ability to use Google Test assertions in other testing + frameworks. + * New feature: ability to run disabled test via + --gtest_also_run_disabled_tests. + * New feature: the --help flag for printing the usage. + * New feature: access to Google Test flag values in user code. + * New feature: a script that packs Google Test into one .h and one + .cc file for easy deployment. + * New feature: support for distributing test functions to multiple + machines (requires support from the test runner). + * Bug fixes and implementation clean-ups. + +Changes for 1.2.1: + + * Compatibility fixes for Linux IA-64 and IBM z/OS. + * Added support for using Boost and other TR1 implementations. + * Changes to the build scripts to support upcoming release of Google C++ + Mocking Framework. + * Added Makefile to the distribution package. + * Improved build instructions in README. + +Changes for 1.2.0: + + * New feature: value-parameterized tests. + * New feature: the ASSERT/EXPECT_(NON)FATAL_FAILURE(_ON_ALL_THREADS) + macros. + * Changed the XML report format to match JUnit/Ant's. + * Added tests to the Xcode project. + * Added scons/SConscript for building with SCons. + * Added src/gtest-all.cc for building Google Test from a single file. + * Fixed compatibility with Solaris and z/OS. + * Enabled running Python tests on systems with python 2.3 installed, + e.g. Mac OS X 10.4. + * Bug fixes. + +Changes for 1.1.0: + + * New feature: type-parameterized tests. + * New feature: exception assertions. + * New feature: printing elapsed time of tests. + * Improved the robustness of death tests. + * Added an Xcode project and samples. + * Adjusted the output format on Windows to be understandable by Visual Studio. + * Minor bug fixes. + +Changes for 1.0.1: + + * Added project files for Visual Studio 7.1. + * Fixed issues with compiling on Mac OS X. + * Fixed issues with compiling on Cygwin. + +Changes for 1.0.0: + + * Initial Open Source release of Google Test diff --git a/lib/gtest/CMakeLists.txt b/lib/gtest/CMakeLists.txt new file mode 100644 index 00000000..57470c84 --- /dev/null +++ b/lib/gtest/CMakeLists.txt @@ -0,0 +1,252 @@ +######################################################################## +# CMake build script for Google Test. +# +# To run the tests for Google Test itself on Linux, use 'make test' or +# ctest. You can select which tests to run using 'ctest -R regex'. +# For more options, run 'ctest --help'. + +# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to +# make it prominent in the GUI. +option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF) + +# When other libraries are using a shared version of runtime libraries, +# Google Test also has to use one. +option( + gtest_force_shared_crt + "Use shared (DLL) run-time lib even when Google Test is built as static lib." + OFF) + +option(gtest_build_tests "Build all of gtest's own tests." OFF) + +option(gtest_build_samples "Build gtest's sample programs." OFF) + +option(gtest_disable_pthreads "Disable uses of pthreads in gtest." OFF) + +# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build(). +include(cmake/hermetic_build.cmake OPTIONAL) + +if (COMMAND pre_project_set_up_hermetic_build) + pre_project_set_up_hermetic_build() +endif() + +######################################################################## +# +# Project-wide settings + +# Name of the project. +# +# CMake files in this project can refer to the root source directory +# as ${gtest_SOURCE_DIR} and to the root binary directory as +# ${gtest_BINARY_DIR}. +# Language "C" is required for find_package(Threads). +project(gtest CXX C) +cmake_minimum_required(VERSION 2.6.2) + +if (COMMAND set_up_hermetic_build) + set_up_hermetic_build() +endif() + +# Define helper functions and macros used by Google Test. +include(cmake/internal_utils.cmake) + +config_compiler_and_linker() # Defined in internal_utils.cmake. + +# Where Google Test's .h files can be found. +include_directories( + ${gtest_SOURCE_DIR}/include + ${gtest_SOURCE_DIR}) + +# Where Google Test's libraries can be found. +link_directories(${gtest_BINARY_DIR}/src) + +######################################################################## +# +# Defines the gtest & gtest_main libraries. User tests should link +# with one of them. + +# Google Test libraries. We build them using more strict warnings than what +# are used for other targets, to ensure that gtest can be compiled by a user +# aggressive about warnings. +cxx_library(gtest "${cxx_strict}" src/gtest-all.cc) +cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc) +target_link_libraries(gtest_main gtest) + +######################################################################## +# +# Samples on how to link user tests with gtest or gtest_main. +# +# They are not built by default. To build them, set the +# gtest_build_samples option to ON. You can do it by running ccmake +# or specifying the -Dgtest_build_samples=ON flag when running cmake. + +if (gtest_build_samples) + cxx_executable(sample1_unittest samples gtest_main samples/sample1.cc) + cxx_executable(sample2_unittest samples gtest_main samples/sample2.cc) + cxx_executable(sample3_unittest samples gtest_main) + cxx_executable(sample4_unittest samples gtest_main samples/sample4.cc) + cxx_executable(sample5_unittest samples gtest_main samples/sample1.cc) + cxx_executable(sample6_unittest samples gtest_main) + cxx_executable(sample7_unittest samples gtest_main) + cxx_executable(sample8_unittest samples gtest_main) + cxx_executable(sample9_unittest samples gtest) + cxx_executable(sample10_unittest samples gtest) +endif() + +######################################################################## +# +# Google Test's own tests. +# +# You can skip this section if you aren't interested in testing +# Google Test itself. +# +# The tests are not built by default. To build them, set the +# gtest_build_tests option to ON. You can do it by running ccmake +# or specifying the -Dgtest_build_tests=ON flag when running cmake. + +if (gtest_build_tests) + # This must be set in the root directory for the tests to be run by + # 'make test' or ctest. + enable_testing() + + ############################################################ + # C++ tests built with standard compiler flags. + + cxx_test(gtest-death-test_test gtest_main) + cxx_test(gtest_environment_test gtest) + cxx_test(gtest-filepath_test gtest_main) + cxx_test(gtest-linked_ptr_test gtest_main) + cxx_test(gtest-listener_test gtest_main) + cxx_test(gtest_main_unittest gtest_main) + cxx_test(gtest-message_test gtest_main) + cxx_test(gtest_no_test_unittest gtest) + cxx_test(gtest-options_test gtest_main) + cxx_test(gtest-param-test_test gtest + test/gtest-param-test2_test.cc) + cxx_test(gtest-port_test gtest_main) + cxx_test(gtest_pred_impl_unittest gtest_main) + cxx_test(gtest_premature_exit_test gtest + test/gtest_premature_exit_test.cc) + cxx_test(gtest-printers_test gtest_main) + cxx_test(gtest_prod_test gtest_main + test/production.cc) + cxx_test(gtest_repeat_test gtest) + cxx_test(gtest_sole_header_test gtest_main) + cxx_test(gtest_stress_test gtest) + cxx_test(gtest-test-part_test gtest_main) + cxx_test(gtest_throw_on_failure_ex_test gtest) + cxx_test(gtest-typed-test_test gtest_main + test/gtest-typed-test2_test.cc) + cxx_test(gtest_unittest gtest_main) + cxx_test(gtest-unittest-api_test gtest) + + ############################################################ + # C++ tests built with non-standard compiler flags. + + # MSVC 7.1 does not support STL with exceptions disabled. + if (NOT MSVC OR MSVC_VERSION GREATER 1310) + cxx_library(gtest_no_exception "${cxx_no_exception}" + src/gtest-all.cc) + cxx_library(gtest_main_no_exception "${cxx_no_exception}" + src/gtest-all.cc src/gtest_main.cc) + endif() + cxx_library(gtest_main_no_rtti "${cxx_no_rtti}" + src/gtest-all.cc src/gtest_main.cc) + + cxx_test_with_flags(gtest-death-test_ex_nocatch_test + "${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=0" + gtest test/gtest-death-test_ex_test.cc) + cxx_test_with_flags(gtest-death-test_ex_catch_test + "${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=1" + gtest test/gtest-death-test_ex_test.cc) + + cxx_test_with_flags(gtest_no_rtti_unittest "${cxx_no_rtti}" + gtest_main_no_rtti test/gtest_unittest.cc) + + cxx_shared_library(gtest_dll "${cxx_default}" + src/gtest-all.cc src/gtest_main.cc) + + cxx_executable_with_flags(gtest_dll_test_ "${cxx_default}" + gtest_dll test/gtest_all_test.cc) + set_target_properties(gtest_dll_test_ + PROPERTIES + COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1") + + if (NOT MSVC OR NOT MSVC_VERSION EQUAL 1600) + # The C++ Standard specifies tuple_element. + # Yet MSVC 10's declares tuple_element. + # That declaration conflicts with our own standard-conforming + # tuple implementation. Therefore using our own tuple with + # MSVC 10 doesn't compile. + cxx_library(gtest_main_use_own_tuple "${cxx_use_own_tuple}" + src/gtest-all.cc src/gtest_main.cc) + + cxx_test_with_flags(gtest-tuple_test "${cxx_use_own_tuple}" + gtest_main_use_own_tuple test/gtest-tuple_test.cc) + + cxx_test_with_flags(gtest_use_own_tuple_test "${cxx_use_own_tuple}" + gtest_main_use_own_tuple + test/gtest-param-test_test.cc test/gtest-param-test2_test.cc) + endif() + + ############################################################ + # Python tests. + + cxx_executable(gtest_break_on_failure_unittest_ test gtest) + py_test(gtest_break_on_failure_unittest) + + # MSVC 7.1 does not support STL with exceptions disabled. + if (NOT MSVC OR MSVC_VERSION GREATER 1310) + cxx_executable_with_flags( + gtest_catch_exceptions_no_ex_test_ + "${cxx_no_exception}" + gtest_main_no_exception + test/gtest_catch_exceptions_test_.cc) + endif() + + cxx_executable_with_flags( + gtest_catch_exceptions_ex_test_ + "${cxx_exception}" + gtest_main + test/gtest_catch_exceptions_test_.cc) + py_test(gtest_catch_exceptions_test) + + cxx_executable(gtest_color_test_ test gtest) + py_test(gtest_color_test) + + cxx_executable(gtest_env_var_test_ test gtest) + py_test(gtest_env_var_test) + + cxx_executable(gtest_filter_unittest_ test gtest) + py_test(gtest_filter_unittest) + + cxx_executable(gtest_help_test_ test gtest_main) + py_test(gtest_help_test) + + cxx_executable(gtest_list_tests_unittest_ test gtest) + py_test(gtest_list_tests_unittest) + + cxx_executable(gtest_output_test_ test gtest) + py_test(gtest_output_test) + + cxx_executable(gtest_shuffle_test_ test gtest) + py_test(gtest_shuffle_test) + + # MSVC 7.1 does not support STL with exceptions disabled. + if (NOT MSVC OR MSVC_VERSION GREATER 1310) + cxx_executable(gtest_throw_on_failure_test_ test gtest_no_exception) + set_target_properties(gtest_throw_on_failure_test_ + PROPERTIES + COMPILE_FLAGS "${cxx_no_exception}") + py_test(gtest_throw_on_failure_test) + endif() + + cxx_executable(gtest_uninitialized_test_ test gtest) + py_test(gtest_uninitialized_test) + + cxx_executable(gtest_xml_outfile1_test_ test gtest_main) + cxx_executable(gtest_xml_outfile2_test_ test gtest_main) + py_test(gtest_xml_outfiles_test) + + cxx_executable(gtest_xml_output_unittest_ test gtest) + py_test(gtest_xml_output_unittest) +endif() diff --git a/lib/gtest/CONTRIBUTORS b/lib/gtest/CONTRIBUTORS new file mode 100644 index 00000000..feae2fc0 --- /dev/null +++ b/lib/gtest/CONTRIBUTORS @@ -0,0 +1,37 @@ +# This file contains a list of people who've made non-trivial +# contribution to the Google C++ Testing Framework project. People +# who commit code to the project are encouraged to add their names +# here. Please keep the list sorted by first names. + +Ajay Joshi +Balázs Dán +Bharat Mediratta +Chandler Carruth +Chris Prince +Chris Taylor +Dan Egnor +Eric Roman +Hady Zalek +Jeffrey Yasskin +Jói Sigurðsson +Keir Mierle +Keith Ray +Kenton Varda +Manuel Klimek +Markus Heule +Mika Raento +Miklós Fazekas +Pasi Valminen +Patrick Hanna +Patrick Riley +Peter Kaminski +Preston Jackson +Rainer Klaffenboeck +Russ Cox +Russ Rufer +Sean Mcafee +Sigurður Ásgeirsson +Tracy Bialik +Vadim Berman +Vlad Losev +Zhanyong Wan diff --git a/lib/gtest/LICENSE b/lib/gtest/LICENSE new file mode 100644 index 00000000..1941a11f --- /dev/null +++ b/lib/gtest/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/lib/gtest/Makefile.am b/lib/gtest/Makefile.am new file mode 100644 index 00000000..9c96b425 --- /dev/null +++ b/lib/gtest/Makefile.am @@ -0,0 +1,306 @@ +# Automake file + +ACLOCAL_AMFLAGS = -I m4 + +# Nonstandard package files for distribution +EXTRA_DIST = \ + CHANGES \ + CONTRIBUTORS \ + LICENSE \ + include/gtest/gtest-param-test.h.pump \ + include/gtest/internal/gtest-param-util-generated.h.pump \ + include/gtest/internal/gtest-tuple.h.pump \ + include/gtest/internal/gtest-type-util.h.pump \ + make/Makefile \ + scripts/fuse_gtest_files.py \ + scripts/gen_gtest_pred_impl.py \ + scripts/pump.py \ + scripts/test/Makefile + +# gtest source files that we don't compile directly. They are +# #included by gtest-all.cc. +GTEST_SRC = \ + src/gtest-death-test.cc \ + src/gtest-filepath.cc \ + src/gtest-internal-inl.h \ + src/gtest-port.cc \ + src/gtest-printers.cc \ + src/gtest-test-part.cc \ + src/gtest-typed-test.cc \ + src/gtest.cc + +EXTRA_DIST += $(GTEST_SRC) + +# Sample files that we don't compile. +EXTRA_DIST += \ + samples/prime_tables.h \ + samples/sample2_unittest.cc \ + samples/sample3_unittest.cc \ + samples/sample4_unittest.cc \ + samples/sample5_unittest.cc \ + samples/sample6_unittest.cc \ + samples/sample7_unittest.cc \ + samples/sample8_unittest.cc \ + samples/sample9_unittest.cc + +# C++ test files that we don't compile directly. +EXTRA_DIST += \ + test/gtest-death-test_ex_test.cc \ + test/gtest-death-test_test.cc \ + test/gtest-filepath_test.cc \ + test/gtest-linked_ptr_test.cc \ + test/gtest-listener_test.cc \ + test/gtest-message_test.cc \ + test/gtest-options_test.cc \ + test/gtest-param-test2_test.cc \ + test/gtest-param-test2_test.cc \ + test/gtest-param-test_test.cc \ + test/gtest-param-test_test.cc \ + test/gtest-param-test_test.h \ + test/gtest-port_test.cc \ + test/gtest_premature_exit_test.cc \ + test/gtest-printers_test.cc \ + test/gtest-test-part_test.cc \ + test/gtest-tuple_test.cc \ + test/gtest-typed-test2_test.cc \ + test/gtest-typed-test_test.cc \ + test/gtest-typed-test_test.h \ + test/gtest-unittest-api_test.cc \ + test/gtest_break_on_failure_unittest_.cc \ + test/gtest_catch_exceptions_test_.cc \ + test/gtest_color_test_.cc \ + test/gtest_env_var_test_.cc \ + test/gtest_environment_test.cc \ + test/gtest_filter_unittest_.cc \ + test/gtest_help_test_.cc \ + test/gtest_list_tests_unittest_.cc \ + test/gtest_main_unittest.cc \ + test/gtest_no_test_unittest.cc \ + test/gtest_output_test_.cc \ + test/gtest_pred_impl_unittest.cc \ + test/gtest_prod_test.cc \ + test/gtest_repeat_test.cc \ + test/gtest_shuffle_test_.cc \ + test/gtest_sole_header_test.cc \ + test/gtest_stress_test.cc \ + test/gtest_throw_on_failure_ex_test.cc \ + test/gtest_throw_on_failure_test_.cc \ + test/gtest_uninitialized_test_.cc \ + test/gtest_unittest.cc \ + test/gtest_unittest.cc \ + test/gtest_xml_outfile1_test_.cc \ + test/gtest_xml_outfile2_test_.cc \ + test/gtest_xml_output_unittest_.cc \ + test/production.cc \ + test/production.h + +# Python tests that we don't run. +EXTRA_DIST += \ + test/gtest_break_on_failure_unittest.py \ + test/gtest_catch_exceptions_test.py \ + test/gtest_color_test.py \ + test/gtest_env_var_test.py \ + test/gtest_filter_unittest.py \ + test/gtest_help_test.py \ + test/gtest_list_tests_unittest.py \ + test/gtest_output_test.py \ + test/gtest_output_test_golden_lin.txt \ + test/gtest_shuffle_test.py \ + test/gtest_test_utils.py \ + test/gtest_throw_on_failure_test.py \ + test/gtest_uninitialized_test.py \ + test/gtest_xml_outfiles_test.py \ + test/gtest_xml_output_unittest.py \ + test/gtest_xml_test_utils.py + +# CMake script +EXTRA_DIST += \ + CMakeLists.txt \ + cmake/internal_utils.cmake + +# MSVC project files +EXTRA_DIST += \ + msvc/gtest-md.sln \ + msvc/gtest-md.vcproj \ + msvc/gtest.sln \ + msvc/gtest.vcproj \ + msvc/gtest_main-md.vcproj \ + msvc/gtest_main.vcproj \ + msvc/gtest_prod_test-md.vcproj \ + msvc/gtest_prod_test.vcproj \ + msvc/gtest_unittest-md.vcproj \ + msvc/gtest_unittest.vcproj + +# xcode project files +EXTRA_DIST += \ + xcode/Config/DebugProject.xcconfig \ + xcode/Config/FrameworkTarget.xcconfig \ + xcode/Config/General.xcconfig \ + xcode/Config/ReleaseProject.xcconfig \ + xcode/Config/StaticLibraryTarget.xcconfig \ + xcode/Config/TestTarget.xcconfig \ + xcode/Resources/Info.plist \ + xcode/Scripts/runtests.sh \ + xcode/Scripts/versiongenerate.py \ + xcode/gtest.xcodeproj/project.pbxproj + +# xcode sample files +EXTRA_DIST += \ + xcode/Samples/FrameworkSample/Info.plist \ + xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj \ + xcode/Samples/FrameworkSample/runtests.sh \ + xcode/Samples/FrameworkSample/widget.cc \ + xcode/Samples/FrameworkSample/widget.h \ + xcode/Samples/FrameworkSample/widget_test.cc + +# C++Builder project files +EXTRA_DIST += \ + codegear/gtest.cbproj \ + codegear/gtest.groupproj \ + codegear/gtest_all.cc \ + codegear/gtest_link.cc \ + codegear/gtest_main.cbproj \ + codegear/gtest_unittest.cbproj + +# Distribute and install M4 macro +m4datadir = $(datadir)/aclocal +m4data_DATA = m4/gtest.m4 +EXTRA_DIST += $(m4data_DATA) + +# We define the global AM_CPPFLAGS as everything we compile includes from these +# directories. +AM_CPPFLAGS = -I$(srcdir) -I$(srcdir)/include + +# Modifies compiler and linker flags for pthreads compatibility. +if HAVE_PTHREADS + AM_CXXFLAGS = @PTHREAD_CFLAGS@ -DGTEST_HAS_PTHREAD=1 + AM_LIBS = @PTHREAD_LIBS@ +else + AM_CXXFLAGS = -DGTEST_HAS_PTHREAD=0 +endif + +# Build rules for libraries. +lib_LTLIBRARIES = lib/libgtest.la lib/libgtest_main.la + +lib_libgtest_la_SOURCES = src/gtest-all.cc + +pkginclude_HEADERS = \ + include/gtest/gtest-death-test.h \ + include/gtest/gtest-message.h \ + include/gtest/gtest-param-test.h \ + include/gtest/gtest-printers.h \ + include/gtest/gtest-spi.h \ + include/gtest/gtest-test-part.h \ + include/gtest/gtest-typed-test.h \ + include/gtest/gtest.h \ + include/gtest/gtest_pred_impl.h \ + include/gtest/gtest_prod.h + +pkginclude_internaldir = $(pkgincludedir)/internal +pkginclude_internal_HEADERS = \ + include/gtest/internal/gtest-death-test-internal.h \ + include/gtest/internal/gtest-filepath.h \ + include/gtest/internal/gtest-internal.h \ + include/gtest/internal/gtest-linked_ptr.h \ + include/gtest/internal/gtest-param-util-generated.h \ + include/gtest/internal/gtest-param-util.h \ + include/gtest/internal/gtest-port.h \ + include/gtest/internal/gtest-string.h \ + include/gtest/internal/gtest-tuple.h \ + include/gtest/internal/gtest-type-util.h + +lib_libgtest_main_la_SOURCES = src/gtest_main.cc +lib_libgtest_main_la_LIBADD = lib/libgtest.la + +# Bulid rules for samples and tests. Automake's naming for some of +# these variables isn't terribly obvious, so this is a brief +# reference: +# +# TESTS -- Programs run automatically by "make check" +# check_PROGRAMS -- Programs built by "make check" but not necessarily run + +noinst_LTLIBRARIES = samples/libsamples.la + +samples_libsamples_la_SOURCES = \ + samples/sample1.cc \ + samples/sample1.h \ + samples/sample2.cc \ + samples/sample2.h \ + samples/sample3-inl.h \ + samples/sample4.cc \ + samples/sample4.h + +TESTS= +TESTS_ENVIRONMENT = GTEST_SOURCE_DIR="$(srcdir)/test" \ + GTEST_BUILD_DIR="$(top_builddir)/test" +check_PROGRAMS= + +# A simple sample on using gtest. +TESTS += samples/sample1_unittest +check_PROGRAMS += samples/sample1_unittest +samples_sample1_unittest_SOURCES = samples/sample1_unittest.cc +samples_sample1_unittest_LDADD = lib/libgtest_main.la \ + lib/libgtest.la \ + samples/libsamples.la + +# Another sample. It also verifies that libgtest works. +TESTS += samples/sample10_unittest +check_PROGRAMS += samples/sample10_unittest +samples_sample10_unittest_SOURCES = samples/sample10_unittest.cc +samples_sample10_unittest_LDADD = lib/libgtest.la + +# This tests most constructs of gtest and verifies that libgtest_main +# and libgtest work. +TESTS += test/gtest_all_test +check_PROGRAMS += test/gtest_all_test +test_gtest_all_test_SOURCES = test/gtest_all_test.cc +test_gtest_all_test_LDADD = lib/libgtest_main.la \ + lib/libgtest.la + +# Tests that fused gtest files compile and work. +FUSED_GTEST_SRC = \ + fused-src/gtest/gtest-all.cc \ + fused-src/gtest/gtest.h \ + fused-src/gtest/gtest_main.cc + +if HAVE_PYTHON +TESTS += test/fused_gtest_test +check_PROGRAMS += test/fused_gtest_test +test_fused_gtest_test_SOURCES = $(FUSED_GTEST_SRC) \ + samples/sample1.cc samples/sample1_unittest.cc +test_fused_gtest_test_CPPFLAGS = -I"$(srcdir)/fused-src" + +# Build rules for putting fused Google Test files into the distribution +# package. The user can also create those files by manually running +# scripts/fuse_gtest_files.py. +$(test_fused_gtest_test_SOURCES): fused-gtest + +fused-gtest: $(pkginclude_HEADERS) $(pkginclude_internal_HEADERS) \ + $(GTEST_SRC) src/gtest-all.cc src/gtest_main.cc \ + scripts/fuse_gtest_files.py + mkdir -p "$(srcdir)/fused-src" + chmod -R u+w "$(srcdir)/fused-src" + rm -f "$(srcdir)/fused-src/gtest/gtest-all.cc" + rm -f "$(srcdir)/fused-src/gtest/gtest.h" + "$(srcdir)/scripts/fuse_gtest_files.py" "$(srcdir)/fused-src" + cp -f "$(srcdir)/src/gtest_main.cc" "$(srcdir)/fused-src/gtest/" + +maintainer-clean-local: + rm -rf "$(srcdir)/fused-src" +endif + +# Death tests may produce core dumps in the build directory. In case +# this happens, clean them to keep distcleancheck happy. +CLEANFILES = core + +# Disables 'make install' as installing a compiled version of Google +# Test can lead to undefined behavior due to violation of the +# One-Definition Rule. + +install-exec-local: + echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Test into your build system." + false + +install-data-local: + echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Test into your build system." + false diff --git a/lib/gtest/Makefile.in b/lib/gtest/Makefile.in new file mode 100644 index 00000000..874de747 --- /dev/null +++ b/lib/gtest/Makefile.in @@ -0,0 +1,1360 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Automake file + + + +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +TESTS = samples/sample1_unittest$(EXEEXT) \ + samples/sample10_unittest$(EXEEXT) \ + test/gtest_all_test$(EXEEXT) $(am__EXEEXT_1) +check_PROGRAMS = samples/sample1_unittest$(EXEEXT) \ + samples/sample10_unittest$(EXEEXT) \ + test/gtest_all_test$(EXEEXT) $(am__EXEEXT_1) +@HAVE_PYTHON_TRUE@am__append_1 = test/fused_gtest_test +@HAVE_PYTHON_TRUE@am__append_2 = test/fused_gtest_test +subdir = . +DIST_COMMON = README $(am__configure_deps) $(pkginclude_HEADERS) \ + $(pkginclude_internal_HEADERS) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in $(top_srcdir)/build-aux/config.h.in \ + $(top_srcdir)/configure $(top_srcdir)/scripts/gtest-config.in \ + build-aux/config.guess build-aux/config.sub build-aux/depcomp \ + build-aux/install-sh build-aux/ltmain.sh build-aux/missing +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ + $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ + $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ + $(top_srcdir)/m4/acx_pthread.m4 $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ + configure.lineno config.status.lineno +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/build-aux/config.h +CONFIG_CLEAN_FILES = scripts/gtest-config +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(m4datadir)" \ + "$(DESTDIR)$(pkgincludedir)" \ + "$(DESTDIR)$(pkginclude_internaldir)" +LTLIBRARIES = $(lib_LTLIBRARIES) $(noinst_LTLIBRARIES) +lib_libgtest_la_LIBADD = +am__dirstamp = $(am__leading_dot)dirstamp +am_lib_libgtest_la_OBJECTS = src/gtest-all.lo +lib_libgtest_la_OBJECTS = $(am_lib_libgtest_la_OBJECTS) +lib_libgtest_main_la_DEPENDENCIES = lib/libgtest.la +am_lib_libgtest_main_la_OBJECTS = src/gtest_main.lo +lib_libgtest_main_la_OBJECTS = $(am_lib_libgtest_main_la_OBJECTS) +samples_libsamples_la_LIBADD = +am_samples_libsamples_la_OBJECTS = samples/sample1.lo \ + samples/sample2.lo samples/sample4.lo +samples_libsamples_la_OBJECTS = $(am_samples_libsamples_la_OBJECTS) +@HAVE_PYTHON_TRUE@am__EXEEXT_1 = test/fused_gtest_test$(EXEEXT) +am_samples_sample10_unittest_OBJECTS = \ + samples/sample10_unittest.$(OBJEXT) +samples_sample10_unittest_OBJECTS = \ + $(am_samples_sample10_unittest_OBJECTS) +samples_sample10_unittest_DEPENDENCIES = lib/libgtest.la +am_samples_sample1_unittest_OBJECTS = \ + samples/sample1_unittest.$(OBJEXT) +samples_sample1_unittest_OBJECTS = \ + $(am_samples_sample1_unittest_OBJECTS) +samples_sample1_unittest_DEPENDENCIES = lib/libgtest_main.la \ + lib/libgtest.la samples/libsamples.la +am__test_fused_gtest_test_SOURCES_DIST = fused-src/gtest/gtest-all.cc \ + fused-src/gtest/gtest.h fused-src/gtest/gtest_main.cc \ + samples/sample1.cc samples/sample1_unittest.cc +am__objects_1 = \ + fused-src/gtest/test_fused_gtest_test-gtest-all.$(OBJEXT) \ + fused-src/gtest/test_fused_gtest_test-gtest_main.$(OBJEXT) +@HAVE_PYTHON_TRUE@am_test_fused_gtest_test_OBJECTS = $(am__objects_1) \ +@HAVE_PYTHON_TRUE@ samples/test_fused_gtest_test-sample1.$(OBJEXT) \ +@HAVE_PYTHON_TRUE@ samples/test_fused_gtest_test-sample1_unittest.$(OBJEXT) +test_fused_gtest_test_OBJECTS = $(am_test_fused_gtest_test_OBJECTS) +test_fused_gtest_test_LDADD = $(LDADD) +am_test_gtest_all_test_OBJECTS = test/gtest_all_test.$(OBJEXT) +test_gtest_all_test_OBJECTS = $(am_test_gtest_all_test_OBJECTS) +test_gtest_all_test_DEPENDENCIES = lib/libgtest_main.la \ + lib/libgtest.la +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)/build-aux +depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp +am__depfiles_maybe = depfiles +am__mv = mv -f +CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +LTCXXCOMPILE = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +CXXLD = $(CXX) +CXXLINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=link $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) \ + $(LDFLAGS) -o $@ +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ + $(LDFLAGS) -o $@ +SOURCES = $(lib_libgtest_la_SOURCES) $(lib_libgtest_main_la_SOURCES) \ + $(samples_libsamples_la_SOURCES) \ + $(samples_sample10_unittest_SOURCES) \ + $(samples_sample1_unittest_SOURCES) \ + $(test_fused_gtest_test_SOURCES) \ + $(test_gtest_all_test_SOURCES) +DIST_SOURCES = $(lib_libgtest_la_SOURCES) \ + $(lib_libgtest_main_la_SOURCES) \ + $(samples_libsamples_la_SOURCES) \ + $(samples_sample10_unittest_SOURCES) \ + $(samples_sample1_unittest_SOURCES) \ + $(am__test_fused_gtest_test_SOURCES_DIST) \ + $(test_gtest_all_test_SOURCES) +DATA = $(m4data_DATA) +HEADERS = $(pkginclude_HEADERS) $(pkginclude_internal_HEADERS) +ETAGS = etags +CTAGS = ctags +am__tty_colors = \ +red=; grn=; lgn=; blu=; std= +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +distdir = $(PACKAGE)-$(VERSION) +top_distdir = $(distdir) +am__remove_distdir = \ + if test -d "$(distdir)"; then \ + find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ + && rm -rf "$(distdir)" \ + || { sleep 5 && rm -rf "$(distdir)"; }; \ + else :; fi +DIST_ARCHIVES = $(distdir).tar.gz $(distdir).tar.bz2 $(distdir).zip +GZIP_ENV = --best +distuninstallcheck_listfiles = find . -type f -print +am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ + | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' +distcleancheck_listfiles = find . -type f -print +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PTHREAD_CC = @PTHREAD_CC@ +PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ +PTHREAD_LIBS = @PTHREAD_LIBS@ +PYTHON = @PYTHON@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +VERSION = @VERSION@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +acx_pthread_config = @acx_pthread_config@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +ACLOCAL_AMFLAGS = -I m4 + +# Nonstandard package files for distribution + +# Sample files that we don't compile. + +# C++ test files that we don't compile directly. + +# Python tests that we don't run. + +# CMake script + +# MSVC project files + +# xcode project files + +# xcode sample files + +# C++Builder project files +EXTRA_DIST = CHANGES CONTRIBUTORS LICENSE \ + include/gtest/gtest-param-test.h.pump \ + include/gtest/internal/gtest-param-util-generated.h.pump \ + include/gtest/internal/gtest-tuple.h.pump \ + include/gtest/internal/gtest-type-util.h.pump make/Makefile \ + scripts/fuse_gtest_files.py scripts/gen_gtest_pred_impl.py \ + scripts/pump.py scripts/test/Makefile $(GTEST_SRC) \ + samples/prime_tables.h samples/sample2_unittest.cc \ + samples/sample3_unittest.cc samples/sample4_unittest.cc \ + samples/sample5_unittest.cc samples/sample6_unittest.cc \ + samples/sample7_unittest.cc samples/sample8_unittest.cc \ + samples/sample9_unittest.cc test/gtest-death-test_ex_test.cc \ + test/gtest-death-test_test.cc test/gtest-filepath_test.cc \ + test/gtest-linked_ptr_test.cc test/gtest-listener_test.cc \ + test/gtest-message_test.cc test/gtest-options_test.cc \ + test/gtest-param-test2_test.cc test/gtest-param-test2_test.cc \ + test/gtest-param-test_test.cc test/gtest-param-test_test.cc \ + test/gtest-param-test_test.h test/gtest-port_test.cc \ + test/gtest_premature_exit_test.cc test/gtest-printers_test.cc \ + test/gtest-test-part_test.cc test/gtest-tuple_test.cc \ + test/gtest-typed-test2_test.cc test/gtest-typed-test_test.cc \ + test/gtest-typed-test_test.h test/gtest-unittest-api_test.cc \ + test/gtest_break_on_failure_unittest_.cc \ + test/gtest_catch_exceptions_test_.cc test/gtest_color_test_.cc \ + test/gtest_env_var_test_.cc test/gtest_environment_test.cc \ + test/gtest_filter_unittest_.cc test/gtest_help_test_.cc \ + test/gtest_list_tests_unittest_.cc test/gtest_main_unittest.cc \ + test/gtest_no_test_unittest.cc test/gtest_output_test_.cc \ + test/gtest_pred_impl_unittest.cc test/gtest_prod_test.cc \ + test/gtest_repeat_test.cc test/gtest_shuffle_test_.cc \ + test/gtest_sole_header_test.cc test/gtest_stress_test.cc \ + test/gtest_throw_on_failure_ex_test.cc \ + test/gtest_throw_on_failure_test_.cc \ + test/gtest_uninitialized_test_.cc test/gtest_unittest.cc \ + test/gtest_unittest.cc test/gtest_xml_outfile1_test_.cc \ + test/gtest_xml_outfile2_test_.cc \ + test/gtest_xml_output_unittest_.cc test/production.cc \ + test/production.h test/gtest_break_on_failure_unittest.py \ + test/gtest_catch_exceptions_test.py test/gtest_color_test.py \ + test/gtest_env_var_test.py test/gtest_filter_unittest.py \ + test/gtest_help_test.py test/gtest_list_tests_unittest.py \ + test/gtest_output_test.py \ + test/gtest_output_test_golden_lin.txt \ + test/gtest_shuffle_test.py test/gtest_test_utils.py \ + test/gtest_throw_on_failure_test.py \ + test/gtest_uninitialized_test.py \ + test/gtest_xml_outfiles_test.py \ + test/gtest_xml_output_unittest.py test/gtest_xml_test_utils.py \ + CMakeLists.txt cmake/internal_utils.cmake msvc/gtest-md.sln \ + msvc/gtest-md.vcproj msvc/gtest.sln msvc/gtest.vcproj \ + msvc/gtest_main-md.vcproj msvc/gtest_main.vcproj \ + msvc/gtest_prod_test-md.vcproj msvc/gtest_prod_test.vcproj \ + msvc/gtest_unittest-md.vcproj msvc/gtest_unittest.vcproj \ + xcode/Config/DebugProject.xcconfig \ + xcode/Config/FrameworkTarget.xcconfig \ + xcode/Config/General.xcconfig \ + xcode/Config/ReleaseProject.xcconfig \ + xcode/Config/StaticLibraryTarget.xcconfig \ + xcode/Config/TestTarget.xcconfig xcode/Resources/Info.plist \ + xcode/Scripts/runtests.sh xcode/Scripts/versiongenerate.py \ + xcode/gtest.xcodeproj/project.pbxproj \ + xcode/Samples/FrameworkSample/Info.plist \ + xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj \ + xcode/Samples/FrameworkSample/runtests.sh \ + xcode/Samples/FrameworkSample/widget.cc \ + xcode/Samples/FrameworkSample/widget.h \ + xcode/Samples/FrameworkSample/widget_test.cc \ + codegear/gtest.cbproj codegear/gtest.groupproj \ + codegear/gtest_all.cc codegear/gtest_link.cc \ + codegear/gtest_main.cbproj codegear/gtest_unittest.cbproj \ + $(m4data_DATA) + +# gtest source files that we don't compile directly. They are +# #included by gtest-all.cc. +GTEST_SRC = \ + src/gtest-death-test.cc \ + src/gtest-filepath.cc \ + src/gtest-internal-inl.h \ + src/gtest-port.cc \ + src/gtest-printers.cc \ + src/gtest-test-part.cc \ + src/gtest-typed-test.cc \ + src/gtest.cc + + +# Distribute and install M4 macro +m4datadir = $(datadir)/aclocal +m4data_DATA = m4/gtest.m4 + +# We define the global AM_CPPFLAGS as everything we compile includes from these +# directories. +AM_CPPFLAGS = -I$(srcdir) -I$(srcdir)/include +@HAVE_PTHREADS_FALSE@AM_CXXFLAGS = -DGTEST_HAS_PTHREAD=0 + +# Modifies compiler and linker flags for pthreads compatibility. +@HAVE_PTHREADS_TRUE@AM_CXXFLAGS = @PTHREAD_CFLAGS@ -DGTEST_HAS_PTHREAD=1 +@HAVE_PTHREADS_TRUE@AM_LIBS = @PTHREAD_LIBS@ + +# Build rules for libraries. +lib_LTLIBRARIES = lib/libgtest.la lib/libgtest_main.la +lib_libgtest_la_SOURCES = src/gtest-all.cc +pkginclude_HEADERS = \ + include/gtest/gtest-death-test.h \ + include/gtest/gtest-message.h \ + include/gtest/gtest-param-test.h \ + include/gtest/gtest-printers.h \ + include/gtest/gtest-spi.h \ + include/gtest/gtest-test-part.h \ + include/gtest/gtest-typed-test.h \ + include/gtest/gtest.h \ + include/gtest/gtest_pred_impl.h \ + include/gtest/gtest_prod.h + +pkginclude_internaldir = $(pkgincludedir)/internal +pkginclude_internal_HEADERS = \ + include/gtest/internal/gtest-death-test-internal.h \ + include/gtest/internal/gtest-filepath.h \ + include/gtest/internal/gtest-internal.h \ + include/gtest/internal/gtest-linked_ptr.h \ + include/gtest/internal/gtest-param-util-generated.h \ + include/gtest/internal/gtest-param-util.h \ + include/gtest/internal/gtest-port.h \ + include/gtest/internal/gtest-string.h \ + include/gtest/internal/gtest-tuple.h \ + include/gtest/internal/gtest-type-util.h + +lib_libgtest_main_la_SOURCES = src/gtest_main.cc +lib_libgtest_main_la_LIBADD = lib/libgtest.la + +# Bulid rules for samples and tests. Automake's naming for some of +# these variables isn't terribly obvious, so this is a brief +# reference: +# +# TESTS -- Programs run automatically by "make check" +# check_PROGRAMS -- Programs built by "make check" but not necessarily run +noinst_LTLIBRARIES = samples/libsamples.la +samples_libsamples_la_SOURCES = \ + samples/sample1.cc \ + samples/sample1.h \ + samples/sample2.cc \ + samples/sample2.h \ + samples/sample3-inl.h \ + samples/sample4.cc \ + samples/sample4.h + +TESTS_ENVIRONMENT = GTEST_SOURCE_DIR="$(srcdir)/test" \ + GTEST_BUILD_DIR="$(top_builddir)/test" + +samples_sample1_unittest_SOURCES = samples/sample1_unittest.cc +samples_sample1_unittest_LDADD = lib/libgtest_main.la \ + lib/libgtest.la \ + samples/libsamples.la + +samples_sample10_unittest_SOURCES = samples/sample10_unittest.cc +samples_sample10_unittest_LDADD = lib/libgtest.la +test_gtest_all_test_SOURCES = test/gtest_all_test.cc +test_gtest_all_test_LDADD = lib/libgtest_main.la \ + lib/libgtest.la + + +# Tests that fused gtest files compile and work. +FUSED_GTEST_SRC = \ + fused-src/gtest/gtest-all.cc \ + fused-src/gtest/gtest.h \ + fused-src/gtest/gtest_main.cc + +@HAVE_PYTHON_TRUE@test_fused_gtest_test_SOURCES = $(FUSED_GTEST_SRC) \ +@HAVE_PYTHON_TRUE@ samples/sample1.cc samples/sample1_unittest.cc + +@HAVE_PYTHON_TRUE@test_fused_gtest_test_CPPFLAGS = -I"$(srcdir)/fused-src" + +# Death tests may produce core dumps in the build directory. In case +# this happens, clean them to keep distcleancheck happy. +CLEANFILES = core +all: all-am + +.SUFFIXES: +.SUFFIXES: .cc .lo .o .obj +am--refresh: Makefile + @: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \ + $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + echo ' $(SHELL) ./config.status'; \ + $(SHELL) ./config.status;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + $(SHELL) ./config.status --recheck + +$(top_srcdir)/configure: $(am__configure_deps) + $(am__cd) $(srcdir) && $(AUTOCONF) +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) +$(am__aclocal_m4_deps): + +build-aux/config.h: build-aux/stamp-h1 + @if test ! -f $@; then rm -f build-aux/stamp-h1; else :; fi + @if test ! -f $@; then $(MAKE) $(AM_MAKEFLAGS) build-aux/stamp-h1; else :; fi + +build-aux/stamp-h1: $(top_srcdir)/build-aux/config.h.in $(top_builddir)/config.status + @rm -f build-aux/stamp-h1 + cd $(top_builddir) && $(SHELL) ./config.status build-aux/config.h +$(top_srcdir)/build-aux/config.h.in: $(am__configure_deps) + ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) + rm -f build-aux/stamp-h1 + touch $@ + +distclean-hdr: + -rm -f build-aux/config.h build-aux/stamp-h1 +scripts/gtest-config: $(top_builddir)/config.status $(top_srcdir)/scripts/gtest-config.in + cd $(top_builddir) && $(SHELL) ./config.status $@ +install-libLTLIBRARIES: $(lib_LTLIBRARIES) + @$(NORMAL_INSTALL) + test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)" + @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ + list2=; for p in $$list; do \ + if test -f $$p; then \ + list2="$$list2 $$p"; \ + else :; fi; \ + done; \ + test -z "$$list2" || { \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ + } + +uninstall-libLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ + for p in $$list; do \ + $(am__strip_dir) \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ + done + +clean-libLTLIBRARIES: + -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) + @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done + +clean-noinstLTLIBRARIES: + -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) + @list='$(noinst_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done +src/$(am__dirstamp): + @$(MKDIR_P) src + @: > src/$(am__dirstamp) +src/$(DEPDIR)/$(am__dirstamp): + @$(MKDIR_P) src/$(DEPDIR) + @: > src/$(DEPDIR)/$(am__dirstamp) +src/gtest-all.lo: src/$(am__dirstamp) src/$(DEPDIR)/$(am__dirstamp) +lib/$(am__dirstamp): + @$(MKDIR_P) lib + @: > lib/$(am__dirstamp) +lib/libgtest.la: $(lib_libgtest_la_OBJECTS) $(lib_libgtest_la_DEPENDENCIES) $(EXTRA_lib_libgtest_la_DEPENDENCIES) lib/$(am__dirstamp) + $(CXXLINK) -rpath $(libdir) $(lib_libgtest_la_OBJECTS) $(lib_libgtest_la_LIBADD) $(LIBS) +src/gtest_main.lo: src/$(am__dirstamp) src/$(DEPDIR)/$(am__dirstamp) +lib/libgtest_main.la: $(lib_libgtest_main_la_OBJECTS) $(lib_libgtest_main_la_DEPENDENCIES) $(EXTRA_lib_libgtest_main_la_DEPENDENCIES) lib/$(am__dirstamp) + $(CXXLINK) -rpath $(libdir) $(lib_libgtest_main_la_OBJECTS) $(lib_libgtest_main_la_LIBADD) $(LIBS) +samples/$(am__dirstamp): + @$(MKDIR_P) samples + @: > samples/$(am__dirstamp) +samples/$(DEPDIR)/$(am__dirstamp): + @$(MKDIR_P) samples/$(DEPDIR) + @: > samples/$(DEPDIR)/$(am__dirstamp) +samples/sample1.lo: samples/$(am__dirstamp) \ + samples/$(DEPDIR)/$(am__dirstamp) +samples/sample2.lo: samples/$(am__dirstamp) \ + samples/$(DEPDIR)/$(am__dirstamp) +samples/sample4.lo: samples/$(am__dirstamp) \ + samples/$(DEPDIR)/$(am__dirstamp) +samples/libsamples.la: $(samples_libsamples_la_OBJECTS) $(samples_libsamples_la_DEPENDENCIES) $(EXTRA_samples_libsamples_la_DEPENDENCIES) samples/$(am__dirstamp) + $(CXXLINK) $(samples_libsamples_la_OBJECTS) $(samples_libsamples_la_LIBADD) $(LIBS) + +clean-checkPROGRAMS: + @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ + echo " rm -f" $$list; \ + rm -f $$list || exit $$?; \ + test -n "$(EXEEXT)" || exit 0; \ + list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ + echo " rm -f" $$list; \ + rm -f $$list +samples/sample10_unittest.$(OBJEXT): samples/$(am__dirstamp) \ + samples/$(DEPDIR)/$(am__dirstamp) +samples/sample10_unittest$(EXEEXT): $(samples_sample10_unittest_OBJECTS) $(samples_sample10_unittest_DEPENDENCIES) $(EXTRA_samples_sample10_unittest_DEPENDENCIES) samples/$(am__dirstamp) + @rm -f samples/sample10_unittest$(EXEEXT) + $(CXXLINK) $(samples_sample10_unittest_OBJECTS) $(samples_sample10_unittest_LDADD) $(LIBS) +samples/sample1_unittest.$(OBJEXT): samples/$(am__dirstamp) \ + samples/$(DEPDIR)/$(am__dirstamp) +samples/sample1_unittest$(EXEEXT): $(samples_sample1_unittest_OBJECTS) $(samples_sample1_unittest_DEPENDENCIES) $(EXTRA_samples_sample1_unittest_DEPENDENCIES) samples/$(am__dirstamp) + @rm -f samples/sample1_unittest$(EXEEXT) + $(CXXLINK) $(samples_sample1_unittest_OBJECTS) $(samples_sample1_unittest_LDADD) $(LIBS) +fused-src/gtest/$(am__dirstamp): + @$(MKDIR_P) fused-src/gtest + @: > fused-src/gtest/$(am__dirstamp) +fused-src/gtest/$(DEPDIR)/$(am__dirstamp): + @$(MKDIR_P) fused-src/gtest/$(DEPDIR) + @: > fused-src/gtest/$(DEPDIR)/$(am__dirstamp) +fused-src/gtest/test_fused_gtest_test-gtest-all.$(OBJEXT): \ + fused-src/gtest/$(am__dirstamp) \ + fused-src/gtest/$(DEPDIR)/$(am__dirstamp) +fused-src/gtest/test_fused_gtest_test-gtest_main.$(OBJEXT): \ + fused-src/gtest/$(am__dirstamp) \ + fused-src/gtest/$(DEPDIR)/$(am__dirstamp) +samples/test_fused_gtest_test-sample1.$(OBJEXT): \ + samples/$(am__dirstamp) samples/$(DEPDIR)/$(am__dirstamp) +samples/test_fused_gtest_test-sample1_unittest.$(OBJEXT): \ + samples/$(am__dirstamp) samples/$(DEPDIR)/$(am__dirstamp) +test/$(am__dirstamp): + @$(MKDIR_P) test + @: > test/$(am__dirstamp) +test/fused_gtest_test$(EXEEXT): $(test_fused_gtest_test_OBJECTS) $(test_fused_gtest_test_DEPENDENCIES) $(EXTRA_test_fused_gtest_test_DEPENDENCIES) test/$(am__dirstamp) + @rm -f test/fused_gtest_test$(EXEEXT) + $(CXXLINK) $(test_fused_gtest_test_OBJECTS) $(test_fused_gtest_test_LDADD) $(LIBS) +test/$(DEPDIR)/$(am__dirstamp): + @$(MKDIR_P) test/$(DEPDIR) + @: > test/$(DEPDIR)/$(am__dirstamp) +test/gtest_all_test.$(OBJEXT): test/$(am__dirstamp) \ + test/$(DEPDIR)/$(am__dirstamp) +test/gtest_all_test$(EXEEXT): $(test_gtest_all_test_OBJECTS) $(test_gtest_all_test_DEPENDENCIES) $(EXTRA_test_gtest_all_test_DEPENDENCIES) test/$(am__dirstamp) + @rm -f test/gtest_all_test$(EXEEXT) + $(CXXLINK) $(test_gtest_all_test_OBJECTS) $(test_gtest_all_test_LDADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + -rm -f fused-src/gtest/test_fused_gtest_test-gtest-all.$(OBJEXT) + -rm -f fused-src/gtest/test_fused_gtest_test-gtest_main.$(OBJEXT) + -rm -f samples/sample1.$(OBJEXT) + -rm -f samples/sample1.lo + -rm -f samples/sample10_unittest.$(OBJEXT) + -rm -f samples/sample1_unittest.$(OBJEXT) + -rm -f samples/sample2.$(OBJEXT) + -rm -f samples/sample2.lo + -rm -f samples/sample4.$(OBJEXT) + -rm -f samples/sample4.lo + -rm -f samples/test_fused_gtest_test-sample1.$(OBJEXT) + -rm -f samples/test_fused_gtest_test-sample1_unittest.$(OBJEXT) + -rm -f src/gtest-all.$(OBJEXT) + -rm -f src/gtest-all.lo + -rm -f src/gtest_main.$(OBJEXT) + -rm -f src/gtest_main.lo + -rm -f test/gtest_all_test.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@fused-src/gtest/$(DEPDIR)/test_fused_gtest_test-gtest-all.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@fused-src/gtest/$(DEPDIR)/test_fused_gtest_test-gtest_main.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@samples/$(DEPDIR)/sample1.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@samples/$(DEPDIR)/sample10_unittest.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@samples/$(DEPDIR)/sample1_unittest.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@samples/$(DEPDIR)/sample2.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@samples/$(DEPDIR)/sample4.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@samples/$(DEPDIR)/test_fused_gtest_test-sample1.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@samples/$(DEPDIR)/test_fused_gtest_test-sample1_unittest.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@src/$(DEPDIR)/gtest-all.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@src/$(DEPDIR)/gtest_main.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@test/$(DEPDIR)/gtest_all_test.Po@am__quote@ + +.cc.o: +@am__fastdepCXX_TRUE@ depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ +@am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ +@am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< + +.cc.obj: +@am__fastdepCXX_TRUE@ depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ +@am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ +@am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` + +.cc.lo: +@am__fastdepCXX_TRUE@ depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ +@am__fastdepCXX_TRUE@ $(LTCXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ +@am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< + +fused-src/gtest/test_fused_gtest_test-gtest-all.o: fused-src/gtest/gtest-all.cc +@am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT fused-src/gtest/test_fused_gtest_test-gtest-all.o -MD -MP -MF fused-src/gtest/$(DEPDIR)/test_fused_gtest_test-gtest-all.Tpo -c -o fused-src/gtest/test_fused_gtest_test-gtest-all.o `test -f 'fused-src/gtest/gtest-all.cc' || echo '$(srcdir)/'`fused-src/gtest/gtest-all.cc +@am__fastdepCXX_TRUE@ $(am__mv) fused-src/gtest/$(DEPDIR)/test_fused_gtest_test-gtest-all.Tpo fused-src/gtest/$(DEPDIR)/test_fused_gtest_test-gtest-all.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='fused-src/gtest/gtest-all.cc' object='fused-src/gtest/test_fused_gtest_test-gtest-all.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o fused-src/gtest/test_fused_gtest_test-gtest-all.o `test -f 'fused-src/gtest/gtest-all.cc' || echo '$(srcdir)/'`fused-src/gtest/gtest-all.cc + +fused-src/gtest/test_fused_gtest_test-gtest-all.obj: fused-src/gtest/gtest-all.cc +@am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT fused-src/gtest/test_fused_gtest_test-gtest-all.obj -MD -MP -MF fused-src/gtest/$(DEPDIR)/test_fused_gtest_test-gtest-all.Tpo -c -o fused-src/gtest/test_fused_gtest_test-gtest-all.obj `if test -f 'fused-src/gtest/gtest-all.cc'; then $(CYGPATH_W) 'fused-src/gtest/gtest-all.cc'; else $(CYGPATH_W) '$(srcdir)/fused-src/gtest/gtest-all.cc'; fi` +@am__fastdepCXX_TRUE@ $(am__mv) fused-src/gtest/$(DEPDIR)/test_fused_gtest_test-gtest-all.Tpo fused-src/gtest/$(DEPDIR)/test_fused_gtest_test-gtest-all.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='fused-src/gtest/gtest-all.cc' object='fused-src/gtest/test_fused_gtest_test-gtest-all.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o fused-src/gtest/test_fused_gtest_test-gtest-all.obj `if test -f 'fused-src/gtest/gtest-all.cc'; then $(CYGPATH_W) 'fused-src/gtest/gtest-all.cc'; else $(CYGPATH_W) '$(srcdir)/fused-src/gtest/gtest-all.cc'; fi` + +fused-src/gtest/test_fused_gtest_test-gtest_main.o: fused-src/gtest/gtest_main.cc +@am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT fused-src/gtest/test_fused_gtest_test-gtest_main.o -MD -MP -MF fused-src/gtest/$(DEPDIR)/test_fused_gtest_test-gtest_main.Tpo -c -o fused-src/gtest/test_fused_gtest_test-gtest_main.o `test -f 'fused-src/gtest/gtest_main.cc' || echo '$(srcdir)/'`fused-src/gtest/gtest_main.cc +@am__fastdepCXX_TRUE@ $(am__mv) fused-src/gtest/$(DEPDIR)/test_fused_gtest_test-gtest_main.Tpo fused-src/gtest/$(DEPDIR)/test_fused_gtest_test-gtest_main.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='fused-src/gtest/gtest_main.cc' object='fused-src/gtest/test_fused_gtest_test-gtest_main.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o fused-src/gtest/test_fused_gtest_test-gtest_main.o `test -f 'fused-src/gtest/gtest_main.cc' || echo '$(srcdir)/'`fused-src/gtest/gtest_main.cc + +fused-src/gtest/test_fused_gtest_test-gtest_main.obj: fused-src/gtest/gtest_main.cc +@am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT fused-src/gtest/test_fused_gtest_test-gtest_main.obj -MD -MP -MF fused-src/gtest/$(DEPDIR)/test_fused_gtest_test-gtest_main.Tpo -c -o fused-src/gtest/test_fused_gtest_test-gtest_main.obj `if test -f 'fused-src/gtest/gtest_main.cc'; then $(CYGPATH_W) 'fused-src/gtest/gtest_main.cc'; else $(CYGPATH_W) '$(srcdir)/fused-src/gtest/gtest_main.cc'; fi` +@am__fastdepCXX_TRUE@ $(am__mv) fused-src/gtest/$(DEPDIR)/test_fused_gtest_test-gtest_main.Tpo fused-src/gtest/$(DEPDIR)/test_fused_gtest_test-gtest_main.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='fused-src/gtest/gtest_main.cc' object='fused-src/gtest/test_fused_gtest_test-gtest_main.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o fused-src/gtest/test_fused_gtest_test-gtest_main.obj `if test -f 'fused-src/gtest/gtest_main.cc'; then $(CYGPATH_W) 'fused-src/gtest/gtest_main.cc'; else $(CYGPATH_W) '$(srcdir)/fused-src/gtest/gtest_main.cc'; fi` + +samples/test_fused_gtest_test-sample1.o: samples/sample1.cc +@am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT samples/test_fused_gtest_test-sample1.o -MD -MP -MF samples/$(DEPDIR)/test_fused_gtest_test-sample1.Tpo -c -o samples/test_fused_gtest_test-sample1.o `test -f 'samples/sample1.cc' || echo '$(srcdir)/'`samples/sample1.cc +@am__fastdepCXX_TRUE@ $(am__mv) samples/$(DEPDIR)/test_fused_gtest_test-sample1.Tpo samples/$(DEPDIR)/test_fused_gtest_test-sample1.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='samples/sample1.cc' object='samples/test_fused_gtest_test-sample1.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o samples/test_fused_gtest_test-sample1.o `test -f 'samples/sample1.cc' || echo '$(srcdir)/'`samples/sample1.cc + +samples/test_fused_gtest_test-sample1.obj: samples/sample1.cc +@am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT samples/test_fused_gtest_test-sample1.obj -MD -MP -MF samples/$(DEPDIR)/test_fused_gtest_test-sample1.Tpo -c -o samples/test_fused_gtest_test-sample1.obj `if test -f 'samples/sample1.cc'; then $(CYGPATH_W) 'samples/sample1.cc'; else $(CYGPATH_W) '$(srcdir)/samples/sample1.cc'; fi` +@am__fastdepCXX_TRUE@ $(am__mv) samples/$(DEPDIR)/test_fused_gtest_test-sample1.Tpo samples/$(DEPDIR)/test_fused_gtest_test-sample1.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='samples/sample1.cc' object='samples/test_fused_gtest_test-sample1.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o samples/test_fused_gtest_test-sample1.obj `if test -f 'samples/sample1.cc'; then $(CYGPATH_W) 'samples/sample1.cc'; else $(CYGPATH_W) '$(srcdir)/samples/sample1.cc'; fi` + +samples/test_fused_gtest_test-sample1_unittest.o: samples/sample1_unittest.cc +@am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT samples/test_fused_gtest_test-sample1_unittest.o -MD -MP -MF samples/$(DEPDIR)/test_fused_gtest_test-sample1_unittest.Tpo -c -o samples/test_fused_gtest_test-sample1_unittest.o `test -f 'samples/sample1_unittest.cc' || echo '$(srcdir)/'`samples/sample1_unittest.cc +@am__fastdepCXX_TRUE@ $(am__mv) samples/$(DEPDIR)/test_fused_gtest_test-sample1_unittest.Tpo samples/$(DEPDIR)/test_fused_gtest_test-sample1_unittest.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='samples/sample1_unittest.cc' object='samples/test_fused_gtest_test-sample1_unittest.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o samples/test_fused_gtest_test-sample1_unittest.o `test -f 'samples/sample1_unittest.cc' || echo '$(srcdir)/'`samples/sample1_unittest.cc + +samples/test_fused_gtest_test-sample1_unittest.obj: samples/sample1_unittest.cc +@am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT samples/test_fused_gtest_test-sample1_unittest.obj -MD -MP -MF samples/$(DEPDIR)/test_fused_gtest_test-sample1_unittest.Tpo -c -o samples/test_fused_gtest_test-sample1_unittest.obj `if test -f 'samples/sample1_unittest.cc'; then $(CYGPATH_W) 'samples/sample1_unittest.cc'; else $(CYGPATH_W) '$(srcdir)/samples/sample1_unittest.cc'; fi` +@am__fastdepCXX_TRUE@ $(am__mv) samples/$(DEPDIR)/test_fused_gtest_test-sample1_unittest.Tpo samples/$(DEPDIR)/test_fused_gtest_test-sample1_unittest.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='samples/sample1_unittest.cc' object='samples/test_fused_gtest_test-sample1_unittest.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_fused_gtest_test_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o samples/test_fused_gtest_test-sample1_unittest.obj `if test -f 'samples/sample1_unittest.cc'; then $(CYGPATH_W) 'samples/sample1_unittest.cc'; else $(CYGPATH_W) '$(srcdir)/samples/sample1_unittest.cc'; fi` + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + -rm -rf lib/.libs lib/_libs + -rm -rf samples/.libs samples/_libs + -rm -rf src/.libs src/_libs + -rm -rf test/.libs test/_libs + +distclean-libtool: + -rm -f libtool config.lt +install-m4dataDATA: $(m4data_DATA) + @$(NORMAL_INSTALL) + test -z "$(m4datadir)" || $(MKDIR_P) "$(DESTDIR)$(m4datadir)" + @list='$(m4data_DATA)'; test -n "$(m4datadir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(m4datadir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(m4datadir)" || exit $$?; \ + done + +uninstall-m4dataDATA: + @$(NORMAL_UNINSTALL) + @list='$(m4data_DATA)'; test -n "$(m4datadir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(m4datadir)'; $(am__uninstall_files_from_dir) +install-pkgincludeHEADERS: $(pkginclude_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(pkgincludedir)" || $(MKDIR_P) "$(DESTDIR)$(pkgincludedir)" + @list='$(pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(pkgincludedir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(pkgincludedir)" || exit $$?; \ + done + +uninstall-pkgincludeHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(pkgincludedir)'; $(am__uninstall_files_from_dir) +install-pkginclude_internalHEADERS: $(pkginclude_internal_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(pkginclude_internaldir)" || $(MKDIR_P) "$(DESTDIR)$(pkginclude_internaldir)" + @list='$(pkginclude_internal_HEADERS)'; test -n "$(pkginclude_internaldir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(pkginclude_internaldir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(pkginclude_internaldir)" || exit $$?; \ + done + +uninstall-pkginclude_internalHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(pkginclude_internal_HEADERS)'; test -n "$(pkginclude_internaldir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(pkginclude_internaldir)'; $(am__uninstall_files_from_dir) + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +check-TESTS: $(TESTS) + @failed=0; all=0; xfail=0; xpass=0; skip=0; \ + srcdir=$(srcdir); export srcdir; \ + list=' $(TESTS) '; \ + $(am__tty_colors); \ + if test -n "$$list"; then \ + for tst in $$list; do \ + if test -f ./$$tst; then dir=./; \ + elif test -f $$tst; then dir=; \ + else dir="$(srcdir)/"; fi; \ + if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \ + all=`expr $$all + 1`; \ + case " $(XFAIL_TESTS) " in \ + *[\ \ ]$$tst[\ \ ]*) \ + xpass=`expr $$xpass + 1`; \ + failed=`expr $$failed + 1`; \ + col=$$red; res=XPASS; \ + ;; \ + *) \ + col=$$grn; res=PASS; \ + ;; \ + esac; \ + elif test $$? -ne 77; then \ + all=`expr $$all + 1`; \ + case " $(XFAIL_TESTS) " in \ + *[\ \ ]$$tst[\ \ ]*) \ + xfail=`expr $$xfail + 1`; \ + col=$$lgn; res=XFAIL; \ + ;; \ + *) \ + failed=`expr $$failed + 1`; \ + col=$$red; res=FAIL; \ + ;; \ + esac; \ + else \ + skip=`expr $$skip + 1`; \ + col=$$blu; res=SKIP; \ + fi; \ + echo "$${col}$$res$${std}: $$tst"; \ + done; \ + if test "$$all" -eq 1; then \ + tests="test"; \ + All=""; \ + else \ + tests="tests"; \ + All="All "; \ + fi; \ + if test "$$failed" -eq 0; then \ + if test "$$xfail" -eq 0; then \ + banner="$$All$$all $$tests passed"; \ + else \ + if test "$$xfail" -eq 1; then failures=failure; else failures=failures; fi; \ + banner="$$All$$all $$tests behaved as expected ($$xfail expected $$failures)"; \ + fi; \ + else \ + if test "$$xpass" -eq 0; then \ + banner="$$failed of $$all $$tests failed"; \ + else \ + if test "$$xpass" -eq 1; then passes=pass; else passes=passes; fi; \ + banner="$$failed of $$all $$tests did not behave as expected ($$xpass unexpected $$passes)"; \ + fi; \ + fi; \ + dashes="$$banner"; \ + skipped=""; \ + if test "$$skip" -ne 0; then \ + if test "$$skip" -eq 1; then \ + skipped="($$skip test was not run)"; \ + else \ + skipped="($$skip tests were not run)"; \ + fi; \ + test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \ + dashes="$$skipped"; \ + fi; \ + report=""; \ + if test "$$failed" -ne 0 && test -n "$(PACKAGE_BUGREPORT)"; then \ + report="Please report to $(PACKAGE_BUGREPORT)"; \ + test `echo "$$report" | wc -c` -le `echo "$$banner" | wc -c` || \ + dashes="$$report"; \ + fi; \ + dashes=`echo "$$dashes" | sed s/./=/g`; \ + if test "$$failed" -eq 0; then \ + col="$$grn"; \ + else \ + col="$$red"; \ + fi; \ + echo "$${col}$$dashes$${std}"; \ + echo "$${col}$$banner$${std}"; \ + test -z "$$skipped" || echo "$${col}$$skipped$${std}"; \ + test -z "$$report" || echo "$${col}$$report$${std}"; \ + echo "$${col}$$dashes$${std}"; \ + test "$$failed" -eq 0; \ + else :; fi + +distdir: $(DISTFILES) + $(am__remove_distdir) + test -d "$(distdir)" || mkdir "$(distdir)" + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + -test -n "$(am__skip_mode_fix)" \ + || find "$(distdir)" -type d ! -perm -755 \ + -exec chmod u+rwx,go+rx {} \; -o \ + ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ + ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ + ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ + || chmod -R a+r "$(distdir)" +dist-gzip: distdir + tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz + $(am__remove_distdir) +dist-bzip2: distdir + tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 + $(am__remove_distdir) + +dist-lzip: distdir + tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz + $(am__remove_distdir) + +dist-lzma: distdir + tardir=$(distdir) && $(am__tar) | lzma -9 -c >$(distdir).tar.lzma + $(am__remove_distdir) + +dist-xz: distdir + tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz + $(am__remove_distdir) + +dist-tarZ: distdir + tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z + $(am__remove_distdir) + +dist-shar: distdir + shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz + $(am__remove_distdir) +dist-zip: distdir + -rm -f $(distdir).zip + zip -rq $(distdir).zip $(distdir) + $(am__remove_distdir) + +dist dist-all: distdir + tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz + tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 + -rm -f $(distdir).zip + zip -rq $(distdir).zip $(distdir) + $(am__remove_distdir) + +# This target untars the dist file and tries a VPATH configuration. Then +# it guarantees that the distribution is self-contained by making another +# tarfile. +distcheck: dist + case '$(DIST_ARCHIVES)' in \ + *.tar.gz*) \ + GZIP=$(GZIP_ENV) gzip -dc $(distdir).tar.gz | $(am__untar) ;;\ + *.tar.bz2*) \ + bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ + *.tar.lzma*) \ + lzma -dc $(distdir).tar.lzma | $(am__untar) ;;\ + *.tar.lz*) \ + lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ + *.tar.xz*) \ + xz -dc $(distdir).tar.xz | $(am__untar) ;;\ + *.tar.Z*) \ + uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ + *.shar.gz*) \ + GZIP=$(GZIP_ENV) gzip -dc $(distdir).shar.gz | unshar ;;\ + *.zip*) \ + unzip $(distdir).zip ;;\ + esac + chmod -R a-w $(distdir); chmod a+w $(distdir) + mkdir $(distdir)/_build + mkdir $(distdir)/_inst + chmod a-w $(distdir) + test -d $(distdir)/_build || exit 0; \ + dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ + && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ + && am__cwd=`pwd` \ + && $(am__cd) $(distdir)/_build \ + && ../configure --srcdir=.. --prefix="$$dc_install_base" \ + $(AM_DISTCHECK_CONFIGURE_FLAGS) \ + $(DISTCHECK_CONFIGURE_FLAGS) \ + && $(MAKE) $(AM_MAKEFLAGS) \ + && $(MAKE) $(AM_MAKEFLAGS) dvi \ + && $(MAKE) $(AM_MAKEFLAGS) check \ + && $(MAKE) $(AM_MAKEFLAGS) install \ + && $(MAKE) $(AM_MAKEFLAGS) installcheck \ + && $(MAKE) $(AM_MAKEFLAGS) uninstall \ + && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ + distuninstallcheck \ + && chmod -R a-w "$$dc_install_base" \ + && ({ \ + (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ + distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ + } || { rm -rf "$$dc_destdir"; exit 1; }) \ + && rm -rf "$$dc_destdir" \ + && $(MAKE) $(AM_MAKEFLAGS) dist \ + && rm -rf $(DIST_ARCHIVES) \ + && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \ + && cd "$$am__cwd" \ + || exit 1 + $(am__remove_distdir) + @(echo "$(distdir) archives ready for distribution: "; \ + list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ + sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' +distuninstallcheck: + @test -n '$(distuninstallcheck_dir)' || { \ + echo 'ERROR: trying to run $@ with an empty' \ + '$$(distuninstallcheck_dir)' >&2; \ + exit 1; \ + }; \ + $(am__cd) '$(distuninstallcheck_dir)' || { \ + echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \ + exit 1; \ + }; \ + test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \ + || { echo "ERROR: files left after uninstall:" ; \ + if test -n "$(DESTDIR)"; then \ + echo " (check DESTDIR support)"; \ + fi ; \ + $(distuninstallcheck_listfiles) ; \ + exit 1; } >&2 +distcleancheck: distclean + @if test '$(srcdir)' = . ; then \ + echo "ERROR: distcleancheck can only run from a VPATH build" ; \ + exit 1 ; \ + fi + @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ + || { echo "ERROR: files left in build directory after distclean:" ; \ + $(distcleancheck_listfiles) ; \ + exit 1; } >&2 +check-am: all-am + $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) + $(MAKE) $(AM_MAKEFLAGS) check-TESTS +check: check-am +all-am: Makefile $(LTLIBRARIES) $(DATA) $(HEADERS) +installdirs: + for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(m4datadir)" "$(DESTDIR)$(pkgincludedir)" "$(DESTDIR)$(pkginclude_internaldir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + -rm -f fused-src/gtest/$(DEPDIR)/$(am__dirstamp) + -rm -f fused-src/gtest/$(am__dirstamp) + -rm -f lib/$(am__dirstamp) + -rm -f samples/$(DEPDIR)/$(am__dirstamp) + -rm -f samples/$(am__dirstamp) + -rm -f src/$(DEPDIR)/$(am__dirstamp) + -rm -f src/$(am__dirstamp) + -rm -f test/$(DEPDIR)/$(am__dirstamp) + -rm -f test/$(am__dirstamp) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +@HAVE_PYTHON_FALSE@maintainer-clean-local: +clean: clean-am + +clean-am: clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \ + clean-libtool clean-noinstLTLIBRARIES mostlyclean-am + +distclean: distclean-am + -rm -f $(am__CONFIG_DISTCLEAN_FILES) + -rm -rf fused-src/gtest/$(DEPDIR) samples/$(DEPDIR) src/$(DEPDIR) test/$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-hdr distclean-libtool distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-data-local install-m4dataDATA \ + install-pkgincludeHEADERS install-pkginclude_internalHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: install-exec-local install-libLTLIBRARIES + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f $(am__CONFIG_DISTCLEAN_FILES) + -rm -rf $(top_srcdir)/autom4te.cache + -rm -rf fused-src/gtest/$(DEPDIR) samples/$(DEPDIR) src/$(DEPDIR) test/$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic \ + maintainer-clean-local + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-libLTLIBRARIES uninstall-m4dataDATA \ + uninstall-pkgincludeHEADERS \ + uninstall-pkginclude_internalHEADERS + +.MAKE: check-am install-am install-strip + +.PHONY: CTAGS GTAGS all all-am am--refresh check check-TESTS check-am \ + clean clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \ + clean-libtool clean-noinstLTLIBRARIES ctags dist dist-all \ + dist-bzip2 dist-gzip dist-lzip dist-lzma dist-shar dist-tarZ \ + dist-xz dist-zip distcheck distclean distclean-compile \ + distclean-generic distclean-hdr distclean-libtool \ + distclean-tags distcleancheck distdir distuninstallcheck dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-data-local install-dvi \ + install-dvi-am install-exec install-exec-am install-exec-local \ + install-html install-html-am install-info install-info-am \ + install-libLTLIBRARIES install-m4dataDATA install-man \ + install-pdf install-pdf-am install-pkgincludeHEADERS \ + install-pkginclude_internalHEADERS install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic \ + maintainer-clean-local mostlyclean mostlyclean-compile \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + tags uninstall uninstall-am uninstall-libLTLIBRARIES \ + uninstall-m4dataDATA uninstall-pkgincludeHEADERS \ + uninstall-pkginclude_internalHEADERS + + +# Build rules for putting fused Google Test files into the distribution +# package. The user can also create those files by manually running +# scripts/fuse_gtest_files.py. +@HAVE_PYTHON_TRUE@$(test_fused_gtest_test_SOURCES): fused-gtest + +@HAVE_PYTHON_TRUE@fused-gtest: $(pkginclude_HEADERS) $(pkginclude_internal_HEADERS) \ +@HAVE_PYTHON_TRUE@ $(GTEST_SRC) src/gtest-all.cc src/gtest_main.cc \ +@HAVE_PYTHON_TRUE@ scripts/fuse_gtest_files.py +@HAVE_PYTHON_TRUE@ mkdir -p "$(srcdir)/fused-src" +@HAVE_PYTHON_TRUE@ chmod -R u+w "$(srcdir)/fused-src" +@HAVE_PYTHON_TRUE@ rm -f "$(srcdir)/fused-src/gtest/gtest-all.cc" +@HAVE_PYTHON_TRUE@ rm -f "$(srcdir)/fused-src/gtest/gtest.h" +@HAVE_PYTHON_TRUE@ "$(srcdir)/scripts/fuse_gtest_files.py" "$(srcdir)/fused-src" +@HAVE_PYTHON_TRUE@ cp -f "$(srcdir)/src/gtest_main.cc" "$(srcdir)/fused-src/gtest/" + +@HAVE_PYTHON_TRUE@maintainer-clean-local: +@HAVE_PYTHON_TRUE@ rm -rf "$(srcdir)/fused-src" + +# Disables 'make install' as installing a compiled version of Google +# Test can lead to undefined behavior due to violation of the +# One-Definition Rule. + +install-exec-local: + echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Test into your build system." + false + +install-data-local: + echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Test into your build system." + false + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/lib/gtest/README b/lib/gtest/README new file mode 100644 index 00000000..26f35a84 --- /dev/null +++ b/lib/gtest/README @@ -0,0 +1,435 @@ +Google C++ Testing Framework +============================ + +http://code.google.com/p/googletest/ + +Overview +-------- + +Google's framework for writing C++ tests on a variety of platforms +(Linux, Mac OS X, Windows, Windows CE, Symbian, etc). Based on the +xUnit architecture. Supports automatic test discovery, a rich set of +assertions, user-defined assertions, death tests, fatal and non-fatal +failures, various options for running the tests, and XML test report +generation. + +Please see the project page above for more information as well as the +mailing list for questions, discussions, and development. There is +also an IRC channel on OFTC (irc.oftc.net) #gtest available. Please +join us! + +Requirements for End Users +-------------------------- + +Google Test is designed to have fairly minimal requirements to build +and use with your projects, but there are some. Currently, we support +Linux, Windows, Mac OS X, and Cygwin. We will also make our best +effort to support other platforms (e.g. Solaris, AIX, and z/OS). +However, since core members of the Google Test project have no access +to these platforms, Google Test may have outstanding issues there. If +you notice any problems on your platform, please notify +googletestframework@googlegroups.com. Patches for fixing them are +even more welcome! + +### Linux Requirements ### + +These are the base requirements to build and use Google Test from a source +package (as described below): + * GNU-compatible Make or gmake + * POSIX-standard shell + * POSIX(-2) Regular Expressions (regex.h) + * A C++98-standard-compliant compiler + +### Windows Requirements ### + + * Microsoft Visual C++ 7.1 or newer + +### Cygwin Requirements ### + + * Cygwin 1.5.25-14 or newer + +### Mac OS X Requirements ### + + * Mac OS X 10.4 Tiger or newer + * Developer Tools Installed + +Also, you'll need CMake 2.6.4 or higher if you want to build the +samples using the provided CMake script, regardless of the platform. + +Requirements for Contributors +----------------------------- + +We welcome patches. If you plan to contribute a patch, you need to +build Google Test and its own tests from an SVN checkout (described +below), which has further requirements: + + * Python version 2.3 or newer (for running some of the tests and + re-generating certain source files from templates) + * CMake 2.6.4 or newer + +Getting the Source +------------------ + +There are two primary ways of getting Google Test's source code: you +can download a stable source release in your preferred archive format, +or directly check out the source from our Subversion (SVN) repositary. +The SVN checkout requires a few extra steps and some extra software +packages on your system, but lets you track the latest development and +make patches much more easily, so we highly encourage it. + +### Source Package ### + +Google Test is released in versioned source packages which can be +downloaded from the download page [1]. Several different archive +formats are provided, but the only difference is the tools used to +manipulate them, and the size of the resulting file. Download +whichever you are most comfortable with. + + [1] http://code.google.com/p/googletest/downloads/list + +Once the package is downloaded, expand it using whichever tools you +prefer for that type. This will result in a new directory with the +name "gtest-X.Y.Z" which contains all of the source code. Here are +some examples on Linux: + + tar -xvzf gtest-X.Y.Z.tar.gz + tar -xvjf gtest-X.Y.Z.tar.bz2 + unzip gtest-X.Y.Z.zip + +### SVN Checkout ### + +To check out the main branch (also known as the "trunk") of Google +Test, run the following Subversion command: + + svn checkout http://googletest.googlecode.com/svn/trunk/ gtest-svn + +Setting up the Build +-------------------- + +To build Google Test and your tests that use it, you need to tell your +build system where to find its headers and source files. The exact +way to do it depends on which build system you use, and is usually +straightforward. + +### Generic Build Instructions ### + +Suppose you put Google Test in directory ${GTEST_DIR}. To build it, +create a library build target (or a project as called by Visual Studio +and Xcode) to compile + + ${GTEST_DIR}/src/gtest-all.cc + +with ${GTEST_DIR}/include in the system header search path and ${GTEST_DIR} +in the normal header search path. Assuming a Linux-like system and gcc, +something like the following will do: + + g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \ + -pthread -c ${GTEST_DIR}/src/gtest-all.cc + ar -rv libgtest.a gtest-all.o + +(We need -pthread as Google Test uses threads.) + +Next, you should compile your test source file with +${GTEST_DIR}/include in the system header search path, and link it +with gtest and any other necessary libraries: + + g++ -isystem ${GTEST_DIR}/include -pthread path/to/your_test.cc libgtest.a \ + -o your_test + +As an example, the make/ directory contains a Makefile that you can +use to build Google Test on systems where GNU make is available +(e.g. Linux, Mac OS X, and Cygwin). It doesn't try to build Google +Test's own tests. Instead, it just builds the Google Test library and +a sample test. You can use it as a starting point for your own build +script. + +If the default settings are correct for your environment, the +following commands should succeed: + + cd ${GTEST_DIR}/make + make + ./sample1_unittest + +If you see errors, try to tweak the contents of make/Makefile to make +them go away. There are instructions in make/Makefile on how to do +it. + +### Using CMake ### + +Google Test comes with a CMake build script (CMakeLists.txt) that can +be used on a wide range of platforms ("C" stands for cross-platofrm.). +If you don't have CMake installed already, you can download it for +free from http://www.cmake.org/. + +CMake works by generating native makefiles or build projects that can +be used in the compiler environment of your choice. The typical +workflow starts with: + + mkdir mybuild # Create a directory to hold the build output. + cd mybuild + cmake ${GTEST_DIR} # Generate native build scripts. + +If you want to build Google Test's samples, you should replace the +last command with + + cmake -Dgtest_build_samples=ON ${GTEST_DIR} + +If you are on a *nix system, you should now see a Makefile in the +current directory. Just type 'make' to build gtest. + +If you use Windows and have Vistual Studio installed, a gtest.sln file +and several .vcproj files will be created. You can then build them +using Visual Studio. + +On Mac OS X with Xcode installed, a .xcodeproj file will be generated. + +### Legacy Build Scripts ### + +Before settling on CMake, we have been providing hand-maintained build +projects/scripts for Visual Studio, Xcode, and Autotools. While we +continue to provide them for convenience, they are not actively +maintained any more. We highly recommend that you follow the +instructions in the previous two sections to integrate Google Test +with your existing build system. + +If you still need to use the legacy build scripts, here's how: + +The msvc\ folder contains two solutions with Visual C++ projects. +Open the gtest.sln or gtest-md.sln file using Visual Studio, and you +are ready to build Google Test the same way you build any Visual +Studio project. Files that have names ending with -md use DLL +versions of Microsoft runtime libraries (the /MD or the /MDd compiler +option). Files without that suffix use static versions of the runtime +libraries (the /MT or the /MTd option). Please note that one must use +the same option to compile both gtest and the test code. If you use +Visual Studio 2005 or above, we recommend the -md version as /MD is +the default for new projects in these versions of Visual Studio. + +On Mac OS X, open the gtest.xcodeproj in the xcode/ folder using +Xcode. Build the "gtest" target. The universal binary framework will +end up in your selected build directory (selected in the Xcode +"Preferences..." -> "Building" pane and defaults to xcode/build). +Alternatively, at the command line, enter: + + xcodebuild + +This will build the "Release" configuration of gtest.framework in your +default build location. See the "xcodebuild" man page for more +information about building different configurations and building in +different locations. + +If you wish to use the Google Test Xcode project with Xcode 4.x and +above, you need to either: + * update the SDK configuration options in xcode/Config/General.xconfig. + Comment options SDKROOT, MACOS_DEPLOYMENT_TARGET, and GCC_VERSION. If + you choose this route you lose the ability to target earlier versions + of MacOS X. + * Install an SDK for an earlier version. This doesn't appear to be + supported by Apple, but has been reported to work + (http://stackoverflow.com/questions/5378518). + +Tweaking Google Test +-------------------- + +Google Test can be used in diverse environments. The default +configuration may not work (or may not work well) out of the box in +some environments. However, you can easily tweak Google Test by +defining control macros on the compiler command line. Generally, +these macros are named like GTEST_XYZ and you define them to either 1 +or 0 to enable or disable a certain feature. + +We list the most frequently used macros below. For a complete list, +see file include/gtest/internal/gtest-port.h. + +### Choosing a TR1 Tuple Library ### + +Some Google Test features require the C++ Technical Report 1 (TR1) +tuple library, which is not yet available with all compilers. The +good news is that Google Test implements a subset of TR1 tuple that's +enough for its own need, and will automatically use this when the +compiler doesn't provide TR1 tuple. + +Usually you don't need to care about which tuple library Google Test +uses. However, if your project already uses TR1 tuple, you need to +tell Google Test to use the same TR1 tuple library the rest of your +project uses, or the two tuple implementations will clash. To do +that, add + + -DGTEST_USE_OWN_TR1_TUPLE=0 + +to the compiler flags while compiling Google Test and your tests. If +you want to force Google Test to use its own tuple library, just add + + -DGTEST_USE_OWN_TR1_TUPLE=1 + +to the compiler flags instead. + +If you don't want Google Test to use tuple at all, add + + -DGTEST_HAS_TR1_TUPLE=0 + +and all features using tuple will be disabled. + +### Multi-threaded Tests ### + +Google Test is thread-safe where the pthread library is available. +After #include "gtest/gtest.h", you can check the GTEST_IS_THREADSAFE +macro to see whether this is the case (yes if the macro is #defined to +1, no if it's undefined.). + +If Google Test doesn't correctly detect whether pthread is available +in your environment, you can force it with + + -DGTEST_HAS_PTHREAD=1 + +or + + -DGTEST_HAS_PTHREAD=0 + +When Google Test uses pthread, you may need to add flags to your +compiler and/or linker to select the pthread library, or you'll get +link errors. If you use the CMake script or the deprecated Autotools +script, this is taken care of for you. If you use your own build +script, you'll need to read your compiler and linker's manual to +figure out what flags to add. + +### As a Shared Library (DLL) ### + +Google Test is compact, so most users can build and link it as a +static library for the simplicity. You can choose to use Google Test +as a shared library (known as a DLL on Windows) if you prefer. + +To compile *gtest* as a shared library, add + + -DGTEST_CREATE_SHARED_LIBRARY=1 + +to the compiler flags. You'll also need to tell the linker to produce +a shared library instead - consult your linker's manual for how to do +it. + +To compile your *tests* that use the gtest shared library, add + + -DGTEST_LINKED_AS_SHARED_LIBRARY=1 + +to the compiler flags. + +Note: while the above steps aren't technically necessary today when +using some compilers (e.g. GCC), they may become necessary in the +future, if we decide to improve the speed of loading the library (see +http://gcc.gnu.org/wiki/Visibility for details). Therefore you are +recommended to always add the above flags when using Google Test as a +shared library. Otherwise a future release of Google Test may break +your build script. + +### Avoiding Macro Name Clashes ### + +In C++, macros don't obey namespaces. Therefore two libraries that +both define a macro of the same name will clash if you #include both +definitions. In case a Google Test macro clashes with another +library, you can force Google Test to rename its macro to avoid the +conflict. + +Specifically, if both Google Test and some other code define macro +FOO, you can add + + -DGTEST_DONT_DEFINE_FOO=1 + +to the compiler flags to tell Google Test to change the macro's name +from FOO to GTEST_FOO. Currently FOO can be FAIL, SUCCEED, or TEST. +For example, with -DGTEST_DONT_DEFINE_TEST=1, you'll need to write + + GTEST_TEST(SomeTest, DoesThis) { ... } + +instead of + + TEST(SomeTest, DoesThis) { ... } + +in order to define a test. + +Upgrating from an Earlier Version +--------------------------------- + +We strive to keep Google Test releases backward compatible. +Sometimes, though, we have to make some breaking changes for the +users' long-term benefits. This section describes what you'll need to +do if you are upgrading from an earlier version of Google Test. + +### Upgrading from 1.3.0 or Earlier ### + +You may need to explicitly enable or disable Google Test's own TR1 +tuple library. See the instructions in section "Choosing a TR1 Tuple +Library". + +### Upgrading from 1.4.0 or Earlier ### + +The Autotools build script (configure + make) is no longer officially +supportted. You are encouraged to migrate to your own build system or +use CMake. If you still need to use Autotools, you can find +instructions in the README file from Google Test 1.4.0. + +On platforms where the pthread library is available, Google Test uses +it in order to be thread-safe. See the "Multi-threaded Tests" section +for what this means to your build script. + +If you use Microsoft Visual C++ 7.1 with exceptions disabled, Google +Test will no longer compile. This should affect very few people, as a +large portion of STL (including ) doesn't compile in this mode +anyway. We decided to stop supporting it in order to greatly simplify +Google Test's implementation. + +Developing Google Test +---------------------- + +This section discusses how to make your own changes to Google Test. + +### Testing Google Test Itself ### + +To make sure your changes work as intended and don't break existing +functionality, you'll want to compile and run Google Test's own tests. +For that you can use CMake: + + mkdir mybuild + cd mybuild + cmake -Dgtest_build_tests=ON ${GTEST_DIR} + +Make sure you have Python installed, as some of Google Test's tests +are written in Python. If the cmake command complains about not being +able to find Python ("Could NOT find PythonInterp (missing: +PYTHON_EXECUTABLE)"), try telling it explicitly where your Python +executable can be found: + + cmake -DPYTHON_EXECUTABLE=path/to/python -Dgtest_build_tests=ON ${GTEST_DIR} + +Next, you can build Google Test and all of its own tests. On *nix, +this is usually done by 'make'. To run the tests, do + + make test + +All tests should pass. + +### Regenerating Source Files ### + +Some of Google Test's source files are generated from templates (not +in the C++ sense) using a script. A template file is named FOO.pump, +where FOO is the name of the file it will generate. For example, the +file include/gtest/internal/gtest-type-util.h.pump is used to generate +gtest-type-util.h in the same directory. + +Normally you don't need to worry about regenerating the source files, +unless you need to modify them. In that case, you should modify the +corresponding .pump files instead and run the pump.py Python script to +regenerate them. You can find pump.py in the scripts/ directory. +Read the Pump manual [2] for how to use it. + + [2] http://code.google.com/p/googletest/wiki/PumpManual + +### Contributing a Patch ### + +We welcome patches. Please read the Google Test developer's guide [3] +for how you can contribute. In particular, make sure you have signed +the Contributor License Agreement, or we won't be able to accept the +patch. + + [3] http://code.google.com/p/googletest/wiki/GoogleTestDevGuide + +Happy testing! diff --git a/lib/gtest/configure b/lib/gtest/configure new file mode 100644 index 00000000..582a9a05 --- /dev/null +++ b/lib/gtest/configure @@ -0,0 +1,18222 @@ +#! /bin/sh +# Guess values for system-dependent variables and create Makefiles. +# Generated by GNU Autoconf 2.68 for Google C++ Testing Framework 1.7.0. +# +# Report bugs to . +# +# +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, +# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software +# Foundation, Inc. +# +# +# This configure script is free software; the Free Software Foundation +# gives unlimited permission to copy, distribute and modify it. +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +if test "x$CONFIG_SHELL" = x; then + as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else + case \`(set -o) 2>/dev/null\` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi +" + as_required="as_fn_return () { (exit \$1); } +as_fn_success () { as_fn_return 0; } +as_fn_failure () { as_fn_return 1; } +as_fn_ret_success () { return 0; } +as_fn_ret_failure () { return 1; } + +exitcode=0 +as_fn_success || { exitcode=1; echo as_fn_success failed.; } +as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } +as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } +as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } +if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : + +else + exitcode=1; echo positional parameters were not saved. +fi +test x\$exitcode = x0 || exit 1" + as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO + as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO + eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && + test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 + + test -n \"\${ZSH_VERSION+set}\${BASH_VERSION+set}\" || ( + ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' + ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO + ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO + PATH=/empty FPATH=/empty; export PATH FPATH + test \"X\`printf %s \$ECHO\`\" = \"X\$ECHO\" \\ + || test \"X\`print -r -- \$ECHO\`\" = \"X\$ECHO\" ) || exit 1 +test \$(( 1 + 1 )) = 2 || exit 1" + if (eval "$as_required") 2>/dev/null; then : + as_have_required=yes +else + as_have_required=no +fi + if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : + +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_found=false +for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + as_found=: + case $as_dir in #( + /*) + for as_base in sh bash ksh sh5; do + # Try only shells that exist, to save several forks. + as_shell=$as_dir/$as_base + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : + CONFIG_SHELL=$as_shell as_have_required=yes + if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : + break 2 +fi +fi + done;; + esac + as_found=false +done +$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : + CONFIG_SHELL=$SHELL as_have_required=yes +fi; } +IFS=$as_save_IFS + + + if test "x$CONFIG_SHELL" != x; then : + # We cannot yet assume a decent shell, so we have to provide a + # neutralization value for shells without unset; and this also + # works around shells that cannot unset nonexistent variables. + # Preserve -v and -x to the replacement shell. + BASH_ENV=/dev/null + ENV=/dev/null + (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV + export CONFIG_SHELL + case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; + esac + exec "$CONFIG_SHELL" $as_opts "$as_myself" ${1+"$@"} +fi + + if test x$as_have_required = xno; then : + $as_echo "$0: This script requires a shell more modern than all" + $as_echo "$0: the shells that I found on your system." + if test x${ZSH_VERSION+set} = xset ; then + $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" + $as_echo "$0: be upgraded to zsh 4.3.4 or later." + else + $as_echo "$0: Please tell bug-autoconf@gnu.org and +$0: googletestframework@googlegroups.com about your system, +$0: including any error possibly output before this +$0: message. Then install a modern shell, or manually run +$0: the script under such a shell if you do have one." + fi + exit 1 +fi +fi +fi +SHELL=${CONFIG_SHELL-/bin/sh} +export SHELL +# Unset more variables known to interfere with behavior of common tools. +CLICOLOR_FORCE= GREP_OPTIONS= +unset CLICOLOR_FORCE GREP_OPTIONS + +## --------------------- ## +## M4sh Shell Functions. ## +## --------------------- ## +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + + + as_lineno_1=$LINENO as_lineno_1a=$LINENO + as_lineno_2=$LINENO as_lineno_2a=$LINENO + eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && + test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { + # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } + + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -p' + fi +else + as_ln_s='cp -p' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +if test -x / >/dev/null 2>&1; then + as_test_x='test -x' +else + if ls -dL / >/dev/null 2>&1; then + as_ls_L_option=L + else + as_ls_L_option= + fi + as_test_x=' + eval sh -c '\'' + if test -d "$1"; then + test -d "$1/."; + else + case $1 in #( + -*)set "./$1";; + esac; + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( + ???[sx]*):;;*)false;;esac;fi + '\'' sh + ' +fi +as_executable_p=$as_test_x + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + +SHELL=${CONFIG_SHELL-/bin/sh} + + +test -n "$DJDIR" || exec 7<&0 &1 + +# Name of the host. +# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, +# so uname gets run too. +ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` + +# +# Initializations. +# +ac_default_prefix=/usr/local +ac_clean_files= +ac_config_libobj_dir=. +LIBOBJS= +cross_compiling=no +subdirs= +MFLAGS= +MAKEFLAGS= + +# Identity of this package. +PACKAGE_NAME='Google C++ Testing Framework' +PACKAGE_TARNAME='gtest' +PACKAGE_VERSION='1.7.0' +PACKAGE_STRING='Google C++ Testing Framework 1.7.0' +PACKAGE_BUGREPORT='googletestframework@googlegroups.com' +PACKAGE_URL='' + +ac_unique_file="./LICENSE" +# Factoring default headers for most tests. +ac_includes_default="\ +#include +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_STAT_H +# include +#endif +#ifdef STDC_HEADERS +# include +# include +#else +# ifdef HAVE_STDLIB_H +# include +# endif +#endif +#ifdef HAVE_STRING_H +# if !defined STDC_HEADERS && defined HAVE_MEMORY_H +# include +# endif +# include +#endif +#ifdef HAVE_STRINGS_H +# include +#endif +#ifdef HAVE_INTTYPES_H +# include +#endif +#ifdef HAVE_STDINT_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif" + +ac_subst_vars='am__EXEEXT_FALSE +am__EXEEXT_TRUE +LTLIBOBJS +LIBOBJS +HAVE_PTHREADS_FALSE +HAVE_PTHREADS_TRUE +PTHREAD_CFLAGS +PTHREAD_LIBS +PTHREAD_CC +acx_pthread_config +HAVE_PYTHON_FALSE +HAVE_PYTHON_TRUE +PYTHON +CXXCPP +CPP +OTOOL64 +OTOOL +LIPO +NMEDIT +DSYMUTIL +MANIFEST_TOOL +RANLIB +ac_ct_AR +AR +DLLTOOL +OBJDUMP +LN_S +NM +ac_ct_DUMPBIN +DUMPBIN +LD +FGREP +EGREP +GREP +SED +host_os +host_vendor +host_cpu +host +build_os +build_vendor +build_cpu +build +LIBTOOL +am__fastdepCXX_FALSE +am__fastdepCXX_TRUE +CXXDEPMODE +ac_ct_CXX +CXXFLAGS +CXX +am__fastdepCC_FALSE +am__fastdepCC_TRUE +CCDEPMODE +am__nodep +AMDEPBACKSLASH +AMDEP_FALSE +AMDEP_TRUE +am__quote +am__include +DEPDIR +OBJEXT +EXEEXT +ac_ct_CC +CPPFLAGS +LDFLAGS +CFLAGS +CC +am__untar +am__tar +AMTAR +am__leading_dot +SET_MAKE +AWK +mkdir_p +MKDIR_P +INSTALL_STRIP_PROGRAM +STRIP +install_sh +MAKEINFO +AUTOHEADER +AUTOMAKE +AUTOCONF +ACLOCAL +VERSION +PACKAGE +CYGPATH_W +am__isrc +INSTALL_DATA +INSTALL_SCRIPT +INSTALL_PROGRAM +target_alias +host_alias +build_alias +LIBS +ECHO_T +ECHO_N +ECHO_C +DEFS +mandir +localedir +libdir +psdir +pdfdir +dvidir +htmldir +infodir +docdir +oldincludedir +includedir +localstatedir +sharedstatedir +sysconfdir +datadir +datarootdir +libexecdir +sbindir +bindir +program_transform_name +prefix +exec_prefix +PACKAGE_URL +PACKAGE_BUGREPORT +PACKAGE_STRING +PACKAGE_VERSION +PACKAGE_TARNAME +PACKAGE_NAME +PATH_SEPARATOR +SHELL' +ac_subst_files='' +ac_user_opts=' +enable_option_checking +enable_dependency_tracking +enable_shared +enable_static +with_pic +enable_fast_install +with_gnu_ld +with_sysroot +enable_libtool_lock +with_pthreads +' + ac_precious_vars='build_alias +host_alias +target_alias +CC +CFLAGS +LDFLAGS +LIBS +CPPFLAGS +CXX +CXXFLAGS +CCC +CPP +CXXCPP' + + +# Initialize some variables set by options. +ac_init_help= +ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= +# The variables have the same names as the options, with +# dashes changed to underlines. +cache_file=/dev/null +exec_prefix=NONE +no_create= +no_recursion= +prefix=NONE +program_prefix=NONE +program_suffix=NONE +program_transform_name=s,x,x, +silent= +site= +srcdir= +verbose= +x_includes=NONE +x_libraries=NONE + +# Installation directory options. +# These are left unexpanded so users can "make install exec_prefix=/foo" +# and all the variables that are supposed to be based on exec_prefix +# by default will actually change. +# Use braces instead of parens because sh, perl, etc. also accept them. +# (The list follows the same order as the GNU Coding Standards.) +bindir='${exec_prefix}/bin' +sbindir='${exec_prefix}/sbin' +libexecdir='${exec_prefix}/libexec' +datarootdir='${prefix}/share' +datadir='${datarootdir}' +sysconfdir='${prefix}/etc' +sharedstatedir='${prefix}/com' +localstatedir='${prefix}/var' +includedir='${prefix}/include' +oldincludedir='/usr/include' +docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' +infodir='${datarootdir}/info' +htmldir='${docdir}' +dvidir='${docdir}' +pdfdir='${docdir}' +psdir='${docdir}' +libdir='${exec_prefix}/lib' +localedir='${datarootdir}/locale' +mandir='${datarootdir}/man' + +ac_prev= +ac_dashdash= +for ac_option +do + # If the previous option needs an argument, assign it. + if test -n "$ac_prev"; then + eval $ac_prev=\$ac_option + ac_prev= + continue + fi + + case $ac_option in + *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; + *=) ac_optarg= ;; + *) ac_optarg=yes ;; + esac + + # Accept the important Cygnus configure options, so we can diagnose typos. + + case $ac_dashdash$ac_option in + --) + ac_dashdash=yes ;; + + -bindir | --bindir | --bindi | --bind | --bin | --bi) + ac_prev=bindir ;; + -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) + bindir=$ac_optarg ;; + + -build | --build | --buil | --bui | --bu) + ac_prev=build_alias ;; + -build=* | --build=* | --buil=* | --bui=* | --bu=*) + build_alias=$ac_optarg ;; + + -cache-file | --cache-file | --cache-fil | --cache-fi \ + | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) + ac_prev=cache_file ;; + -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ + | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) + cache_file=$ac_optarg ;; + + --config-cache | -C) + cache_file=config.cache ;; + + -datadir | --datadir | --datadi | --datad) + ac_prev=datadir ;; + -datadir=* | --datadir=* | --datadi=* | --datad=*) + datadir=$ac_optarg ;; + + -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ + | --dataroo | --dataro | --datar) + ac_prev=datarootdir ;; + -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ + | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) + datarootdir=$ac_optarg ;; + + -disable-* | --disable-*) + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; + + -docdir | --docdir | --docdi | --doc | --do) + ac_prev=docdir ;; + -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) + docdir=$ac_optarg ;; + + -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) + ac_prev=dvidir ;; + -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) + dvidir=$ac_optarg ;; + + -enable-* | --enable-*) + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; + + -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ + | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ + | --exec | --exe | --ex) + ac_prev=exec_prefix ;; + -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ + | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ + | --exec=* | --exe=* | --ex=*) + exec_prefix=$ac_optarg ;; + + -gas | --gas | --ga | --g) + # Obsolete; use --with-gas. + with_gas=yes ;; + + -help | --help | --hel | --he | -h) + ac_init_help=long ;; + -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) + ac_init_help=recursive ;; + -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) + ac_init_help=short ;; + + -host | --host | --hos | --ho) + ac_prev=host_alias ;; + -host=* | --host=* | --hos=* | --ho=*) + host_alias=$ac_optarg ;; + + -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) + ac_prev=htmldir ;; + -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ + | --ht=*) + htmldir=$ac_optarg ;; + + -includedir | --includedir | --includedi | --included | --include \ + | --includ | --inclu | --incl | --inc) + ac_prev=includedir ;; + -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ + | --includ=* | --inclu=* | --incl=* | --inc=*) + includedir=$ac_optarg ;; + + -infodir | --infodir | --infodi | --infod | --info | --inf) + ac_prev=infodir ;; + -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) + infodir=$ac_optarg ;; + + -libdir | --libdir | --libdi | --libd) + ac_prev=libdir ;; + -libdir=* | --libdir=* | --libdi=* | --libd=*) + libdir=$ac_optarg ;; + + -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ + | --libexe | --libex | --libe) + ac_prev=libexecdir ;; + -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ + | --libexe=* | --libex=* | --libe=*) + libexecdir=$ac_optarg ;; + + -localedir | --localedir | --localedi | --localed | --locale) + ac_prev=localedir ;; + -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) + localedir=$ac_optarg ;; + + -localstatedir | --localstatedir | --localstatedi | --localstated \ + | --localstate | --localstat | --localsta | --localst | --locals) + ac_prev=localstatedir ;; + -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ + | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) + localstatedir=$ac_optarg ;; + + -mandir | --mandir | --mandi | --mand | --man | --ma | --m) + ac_prev=mandir ;; + -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) + mandir=$ac_optarg ;; + + -nfp | --nfp | --nf) + # Obsolete; use --without-fp. + with_fp=no ;; + + -no-create | --no-create | --no-creat | --no-crea | --no-cre \ + | --no-cr | --no-c | -n) + no_create=yes ;; + + -no-recursion | --no-recursion | --no-recursio | --no-recursi \ + | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) + no_recursion=yes ;; + + -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ + | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ + | --oldin | --oldi | --old | --ol | --o) + ac_prev=oldincludedir ;; + -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ + | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ + | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) + oldincludedir=$ac_optarg ;; + + -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) + ac_prev=prefix ;; + -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) + prefix=$ac_optarg ;; + + -program-prefix | --program-prefix | --program-prefi | --program-pref \ + | --program-pre | --program-pr | --program-p) + ac_prev=program_prefix ;; + -program-prefix=* | --program-prefix=* | --program-prefi=* \ + | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) + program_prefix=$ac_optarg ;; + + -program-suffix | --program-suffix | --program-suffi | --program-suff \ + | --program-suf | --program-su | --program-s) + ac_prev=program_suffix ;; + -program-suffix=* | --program-suffix=* | --program-suffi=* \ + | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) + program_suffix=$ac_optarg ;; + + -program-transform-name | --program-transform-name \ + | --program-transform-nam | --program-transform-na \ + | --program-transform-n | --program-transform- \ + | --program-transform | --program-transfor \ + | --program-transfo | --program-transf \ + | --program-trans | --program-tran \ + | --progr-tra | --program-tr | --program-t) + ac_prev=program_transform_name ;; + -program-transform-name=* | --program-transform-name=* \ + | --program-transform-nam=* | --program-transform-na=* \ + | --program-transform-n=* | --program-transform-=* \ + | --program-transform=* | --program-transfor=* \ + | --program-transfo=* | --program-transf=* \ + | --program-trans=* | --program-tran=* \ + | --progr-tra=* | --program-tr=* | --program-t=*) + program_transform_name=$ac_optarg ;; + + -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) + ac_prev=pdfdir ;; + -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) + pdfdir=$ac_optarg ;; + + -psdir | --psdir | --psdi | --psd | --ps) + ac_prev=psdir ;; + -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) + psdir=$ac_optarg ;; + + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + silent=yes ;; + + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) + ac_prev=sbindir ;; + -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ + | --sbi=* | --sb=*) + sbindir=$ac_optarg ;; + + -sharedstatedir | --sharedstatedir | --sharedstatedi \ + | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ + | --sharedst | --shareds | --shared | --share | --shar \ + | --sha | --sh) + ac_prev=sharedstatedir ;; + -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ + | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ + | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ + | --sha=* | --sh=*) + sharedstatedir=$ac_optarg ;; + + -site | --site | --sit) + ac_prev=site ;; + -site=* | --site=* | --sit=*) + site=$ac_optarg ;; + + -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) + ac_prev=srcdir ;; + -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) + srcdir=$ac_optarg ;; + + -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ + | --syscon | --sysco | --sysc | --sys | --sy) + ac_prev=sysconfdir ;; + -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ + | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) + sysconfdir=$ac_optarg ;; + + -target | --target | --targe | --targ | --tar | --ta | --t) + ac_prev=target_alias ;; + -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) + target_alias=$ac_optarg ;; + + -v | -verbose | --verbose | --verbos | --verbo | --verb) + verbose=yes ;; + + -version | --version | --versio | --versi | --vers | -V) + ac_init_version=: ;; + + -with-* | --with-*) + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; + + -without-* | --without-*) + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; + + --x) + # Obsolete; use --with-x. + with_x=yes ;; + + -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ + | --x-incl | --x-inc | --x-in | --x-i) + ac_prev=x_includes ;; + -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ + | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) + x_includes=$ac_optarg ;; + + -x-libraries | --x-libraries | --x-librarie | --x-librari \ + | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) + ac_prev=x_libraries ;; + -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ + | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) + x_libraries=$ac_optarg ;; + + -*) as_fn_error $? "unrecognized option: \`$ac_option' +Try \`$0 --help' for more information" + ;; + + *=*) + ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` + # Reject names that are not valid shell variable names. + case $ac_envvar in #( + '' | [0-9]* | *[!_$as_cr_alnum]* ) + as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; + esac + eval $ac_envvar=\$ac_optarg + export $ac_envvar ;; + + *) + # FIXME: should be removed in autoconf 3.0. + $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && + $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" + ;; + + esac +done + +if test -n "$ac_prev"; then + ac_option=--`echo $ac_prev | sed 's/_/-/g'` + as_fn_error $? "missing argument to $ac_option" +fi + +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; + *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac +fi + +# Check all directory arguments for consistency. +for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ + datadir sysconfdir sharedstatedir localstatedir includedir \ + oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ + libdir localedir mandir +do + eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. + case $ac_val in + [\\/$]* | ?:[\\/]* ) continue;; + NONE | '' ) case $ac_var in *prefix ) continue;; esac;; + esac + as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" +done + +# There might be people who depend on the old broken behavior: `$host' +# used to hold the argument of --host etc. +# FIXME: To remove some day. +build=$build_alias +host=$host_alias +target=$target_alias + +# FIXME: To remove some day. +if test "x$host_alias" != x; then + if test "x$build_alias" = x; then + cross_compiling=maybe + $as_echo "$as_me: WARNING: if you wanted to set the --build type, don't use --host. + If a cross compiler is detected then cross compile mode will be used" >&2 + elif test "x$build_alias" != "x$host_alias"; then + cross_compiling=yes + fi +fi + +ac_tool_prefix= +test -n "$host_alias" && ac_tool_prefix=$host_alias- + +test "$silent" = yes && exec 6>/dev/null + + +ac_pwd=`pwd` && test -n "$ac_pwd" && +ac_ls_di=`ls -di .` && +ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || + as_fn_error $? "working directory cannot be determined" +test "X$ac_ls_di" = "X$ac_pwd_ls_di" || + as_fn_error $? "pwd does not report name of working directory" + + +# Find the source files, if location was not specified. +if test -z "$srcdir"; then + ac_srcdir_defaulted=yes + # Try the directory containing this script, then the parent directory. + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_myself" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + srcdir=$ac_confdir + if test ! -r "$srcdir/$ac_unique_file"; then + srcdir=.. + fi +else + ac_srcdir_defaulted=no +fi +if test ! -r "$srcdir/$ac_unique_file"; then + test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." + as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" +fi +ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" +ac_abs_confdir=`( + cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" + pwd)` +# When building in place, set srcdir=. +if test "$ac_abs_confdir" = "$ac_pwd"; then + srcdir=. +fi +# Remove unnecessary trailing slashes from srcdir. +# Double slashes in file names in object file debugging info +# mess up M-x gdb in Emacs. +case $srcdir in +*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; +esac +for ac_var in $ac_precious_vars; do + eval ac_env_${ac_var}_set=\${${ac_var}+set} + eval ac_env_${ac_var}_value=\$${ac_var} + eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} + eval ac_cv_env_${ac_var}_value=\$${ac_var} +done + +# +# Report the --help message. +# +if test "$ac_init_help" = "long"; then + # Omit some internal or obsolete options to make the list less imposing. + # This message is too long to be a string in the A/UX 3.1 sh. + cat <<_ACEOF +\`configure' configures Google C++ Testing Framework 1.7.0 to adapt to many kinds of systems. + +Usage: $0 [OPTION]... [VAR=VALUE]... + +To assign environment variables (e.g., CC, CFLAGS...), specify them as +VAR=VALUE. See below for descriptions of some of the useful variables. + +Defaults for the options are specified in brackets. + +Configuration: + -h, --help display this help and exit + --help=short display options specific to this package + --help=recursive display the short help of all the included packages + -V, --version display version information and exit + -q, --quiet, --silent do not print \`checking ...' messages + --cache-file=FILE cache test results in FILE [disabled] + -C, --config-cache alias for \`--cache-file=config.cache' + -n, --no-create do not create output files + --srcdir=DIR find the sources in DIR [configure dir or \`..'] + +Installation directories: + --prefix=PREFIX install architecture-independent files in PREFIX + [$ac_default_prefix] + --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX + [PREFIX] + +By default, \`make install' will install all the files in +\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify +an installation prefix other than \`$ac_default_prefix' using \`--prefix', +for instance \`--prefix=\$HOME'. + +For better control, use the options below. + +Fine tuning of the installation directories: + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/gtest] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] +_ACEOF + + cat <<\_ACEOF + +Program names: + --program-prefix=PREFIX prepend PREFIX to installed program names + --program-suffix=SUFFIX append SUFFIX to installed program names + --program-transform-name=PROGRAM run sed PROGRAM on installed program names + +System types: + --build=BUILD configure for building on BUILD [guessed] + --host=HOST cross-compile to build programs to run on HOST [BUILD] +_ACEOF +fi + +if test -n "$ac_init_help"; then + case $ac_init_help in + short | recursive ) echo "Configuration of Google C++ Testing Framework 1.7.0:";; + esac + cat <<\_ACEOF + +Optional Features: + --disable-option-checking ignore unrecognized --enable/--with options + --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) + --enable-FEATURE[=ARG] include FEATURE [ARG=yes] + --disable-dependency-tracking speeds up one-time build + --enable-dependency-tracking do not reject slow dependency extractors + --enable-shared[=PKGS] build shared libraries [default=yes] + --enable-static[=PKGS] build static libraries [default=yes] + --enable-fast-install[=PKGS] + optimize for fast installation [default=yes] + --disable-libtool-lock avoid locking (might break parallel builds) + +Optional Packages: + --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] + --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) + --with-pic[=PKGS] try to use only PIC/non-PIC objects [default=use + both] + --with-gnu-ld assume the C compiler uses GNU ld [default=no] + --with-sysroot=DIR Search for dependent libraries within DIR + (or the compiler's sysroot if not specified). + --with-pthreads use pthreads (default is yes) + +Some influential environment variables: + CC C compiler command + CFLAGS C compiler flags + LDFLAGS linker flags, e.g. -L if you have libraries in a + nonstandard directory + LIBS libraries to pass to the linker, e.g. -l + CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if + you have headers in a nonstandard directory + CXX C++ compiler command + CXXFLAGS C++ compiler flags + CPP C preprocessor + CXXCPP C++ preprocessor + +Use these variables to override the choices made by `configure' or to help +it to find libraries and programs with nonstandard names/locations. + +Report bugs to . +_ACEOF +ac_status=$? +fi + +if test "$ac_init_help" = "recursive"; then + # If there are subdirs, report their specific --help. + for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + cd "$ac_dir" || { ac_status=$?; continue; } + # Check for guested configure. + if test -f "$ac_srcdir/configure.gnu"; then + echo && + $SHELL "$ac_srcdir/configure.gnu" --help=recursive + elif test -f "$ac_srcdir/configure"; then + echo && + $SHELL "$ac_srcdir/configure" --help=recursive + else + $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + fi || ac_status=$? + cd "$ac_pwd" || { ac_status=$?; break; } + done +fi + +test -n "$ac_init_help" && exit $ac_status +if $ac_init_version; then + cat <<\_ACEOF +Google C++ Testing Framework configure 1.7.0 +generated by GNU Autoconf 2.68 + +Copyright (C) 2010 Free Software Foundation, Inc. +This configure script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it. +_ACEOF + exit +fi + +## ------------------------ ## +## Autoconf initialization. ## +## ------------------------ ## + +# ac_fn_c_try_compile LINENO +# -------------------------- +# Try to compile conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext + if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_compile + +# ac_fn_cxx_try_compile LINENO +# ---------------------------- +# Try to compile conftest.$ac_ext, and return whether this succeeded. +ac_fn_cxx_try_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext + if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_cxx_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_cxx_try_compile + +# ac_fn_c_try_link LINENO +# ----------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_link () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest$ac_exeext + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information + # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would + # interfere with the next link command; also delete a directory that is + # left behind by Apple's compiler. We do this before executing the actions. + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_link + +# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists and can be compiled using the include files in +# INCLUDES, setting the cache variable VAR accordingly. +ac_fn_c_check_header_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_header_compile + +# ac_fn_c_try_cpp LINENO +# ---------------------- +# Try to preprocess conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_cpp () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } > conftest.i && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_cpp + +# ac_fn_c_try_run LINENO +# ---------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes +# that executables *can* be run. +ac_fn_c_try_run () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then : + ac_retval=0 +else + $as_echo "$as_me: program exited with status $ac_status" >&5 + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=$ac_status +fi + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_run + +# ac_fn_c_check_func LINENO FUNC VAR +# ---------------------------------- +# Tests whether FUNC exists, setting the cache variable VAR accordingly +ac_fn_c_check_func () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Define $2 to an innocuous variant, in case declares $2. + For example, HP-UX 11i declares gettimeofday. */ +#define $2 innocuous_$2 + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $2 (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef $2 + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $2 (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$2 || defined __stub___$2 +choke me +#endif + +int +main () +{ +return $2 (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_func + +# ac_fn_cxx_try_cpp LINENO +# ------------------------ +# Try to preprocess conftest.$ac_ext, and return whether this succeeded. +ac_fn_cxx_try_cpp () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } > conftest.i && { + test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" || + test ! -s conftest.err + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_cxx_try_cpp + +# ac_fn_cxx_try_link LINENO +# ------------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. +ac_fn_cxx_try_link () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest$ac_exeext + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_cxx_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information + # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would + # interfere with the next link command; also delete a directory that is + # left behind by Apple's compiler. We do this before executing the actions. + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_cxx_try_link +cat >config.log <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. + +It was created by Google C++ Testing Framework $as_me 1.7.0, which was +generated by GNU Autoconf 2.68. Invocation command line was + + $ $0 $@ + +_ACEOF +exec 5>>config.log +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## + +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` + +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` + +_ASUNAME + +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + $as_echo "PATH: $as_dir" + done +IFS=$as_save_IFS + +} >&5 + +cat >&5 <<_ACEOF + + +## ----------- ## +## Core tests. ## +## ----------- ## + +_ACEOF + + +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *\'*) + ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; + 2) + as_fn_append ac_configure_args1 " '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; + esac + fi + as_fn_append ac_configure_args " '$ac_arg'" + ;; + esac + done +done +{ ac_configure_args0=; unset ac_configure_args0;} +{ ac_configure_args1=; unset ac_configure_args1;} + +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. +trap 'exit_status=$? + # Save into config.log some information that might help in debugging. + { + echo + + $as_echo "## ---------------- ## +## Cache variables. ## +## ---------------- ##" + echo + # The following way of writing the cache mishandles newlines in values, +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + (set) 2>&1 | + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + sed -n \ + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( + *) + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) + echo + + $as_echo "## ----------------- ## +## Output variables. ## +## ----------------- ##" + echo + for ac_var in $ac_subst_vars + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + + if test -n "$ac_subst_files"; then + $as_echo "## ------------------- ## +## File substitutions. ## +## ------------------- ##" + echo + for ac_var in $ac_subst_files + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + fi + + if test -s confdefs.h; then + $as_echo "## ----------- ## +## confdefs.h. ## +## ----------- ##" + echo + cat confdefs.h + echo + fi + test "$ac_signal" != 0 && + $as_echo "$as_me: caught signal $ac_signal" + $as_echo "$as_me: exit $exit_status" + } >&5 + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status +' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal +done +ac_signal=0 + +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -f -r conftest* confdefs.h + +$as_echo "/* confdefs.h */" > confdefs.h + +# Predefined preprocessor variables. + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_NAME "$PACKAGE_NAME" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_TARNAME "$PACKAGE_TARNAME" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_VERSION "$PACKAGE_VERSION" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_STRING "$PACKAGE_STRING" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_URL "$PACKAGE_URL" +_ACEOF + + +# Let the site file select an alternate cache file if it wants to. +# Prefer an explicitly selected file to automatically selected ones. +ac_site_file1=NONE +ac_site_file2=NONE +if test -n "$CONFIG_SITE"; then + # We do not want a PATH search for config.site. + case $CONFIG_SITE in #(( + -*) ac_site_file1=./$CONFIG_SITE;; + */*) ac_site_file1=$CONFIG_SITE;; + *) ac_site_file1=./$CONFIG_SITE;; + esac +elif test "x$prefix" != xNONE; then + ac_site_file1=$prefix/share/config.site + ac_site_file2=$prefix/etc/config.site +else + ac_site_file1=$ac_default_prefix/share/config.site + ac_site_file2=$ac_default_prefix/etc/config.site +fi +for ac_site_file in "$ac_site_file1" "$ac_site_file2" +do + test "x$ac_site_file" = xNONE && continue + if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 +$as_echo "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" \ + || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "failed to load site script $ac_site_file +See \`config.log' for more details" "$LINENO" 5; } + fi +done + +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special files + # actually), so we avoid doing that. DJGPP emulates it as a regular file. + if test /dev/null != "$cache_file" && test -f "$cache_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 +$as_echo "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; + esac + fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 +$as_echo "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi + +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 +$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 +$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 +$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) as_fn_append ac_configure_args " '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 +$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} + as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 +fi +## -------------------- ## +## Main body of script. ## +## -------------------- ## + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + +# Provide various options to initialize the Autoconf and configure processes. + + + +ac_aux_dir= +for ac_dir in build-aux "$srcdir"/build-aux; do + if test -f "$ac_dir/install-sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install-sh -c" + break + elif test -f "$ac_dir/install.sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install.sh -c" + break + elif test -f "$ac_dir/shtool"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/shtool install -c" + break + fi +done +if test -z "$ac_aux_dir"; then + as_fn_error $? "cannot find install-sh, install.sh, or shtool in build-aux \"$srcdir\"/build-aux" "$LINENO" 5 +fi + +# These three variables are undocumented and unsupported, +# and are intended to be withdrawn in a future Autoconf release. +# They can cause serious problems if a builder's source tree is in a directory +# whose full name contains unusual characters. +ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. +ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. +ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. + + +ac_config_headers="$ac_config_headers build-aux/config.h" + +ac_config_files="$ac_config_files Makefile" + +ac_config_files="$ac_config_files scripts/gtest-config" + + +# Initialize Automake with various options. We require at least v1.9, prevent +# pedantic complaints about package files, and enable various distribution +# targets. +am__api_version='1.11' + +# Find a good install program. We prefer a C program (faster), +# so one script is as good as another. But avoid the broken or +# incompatible versions: +# SysV /etc/install, /usr/sbin/install +# SunOS /usr/etc/install +# IRIX /sbin/install +# AIX /bin/install +# AmigaOS /C/install, which installs bootblocks on floppy discs +# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag +# AFS /usr/afsws/bin/install, which mishandles nonexistent args +# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" +# OS/2's system install, which has a completely different semantic +# ./install, which can be erroneously created by make from ./install.sh. +# Reject install programs that cannot install multiple files. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 +$as_echo_n "checking for a BSD-compatible install... " >&6; } +if test -z "$INSTALL"; then +if ${ac_cv_path_install+:} false; then : + $as_echo_n "(cached) " >&6 +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + # Account for people who put trailing slashes in PATH elements. +case $as_dir/ in #(( + ./ | .// | /[cC]/* | \ + /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ + ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ + /usr/ucb/* ) ;; + *) + # OSF1 and SCO ODT 3.0 have their own names for install. + # Don't use installbsd from OSF since it installs stuff as root + # by default. + for ac_prog in ginstall scoinst install; do + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; }; then + if test $ac_prog = install && + grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # AIX install. It has an incompatible calling convention. + : + elif test $ac_prog = install && + grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # program-specific install script used by HP pwplus--don't use. + : + else + rm -rf conftest.one conftest.two conftest.dir + echo one > conftest.one + echo two > conftest.two + mkdir conftest.dir + if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && + test -s conftest.one && test -s conftest.two && + test -s conftest.dir/conftest.one && + test -s conftest.dir/conftest.two + then + ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" + break 3 + fi + fi + fi + done + done + ;; +esac + + done +IFS=$as_save_IFS + +rm -rf conftest.one conftest.two conftest.dir + +fi + if test "${ac_cv_path_install+set}" = set; then + INSTALL=$ac_cv_path_install + else + # As a last resort, use the slow shell script. Don't cache a + # value for INSTALL within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + INSTALL=$ac_install_sh + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 +$as_echo "$INSTALL" >&6; } + +# Use test -z because SunOS4 sh mishandles braces in ${var-val}. +# It thinks the first close brace ends the variable substitution. +test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' + +test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' + +test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build environment is sane" >&5 +$as_echo_n "checking whether build environment is sane... " >&6; } +# Just in case +sleep 1 +echo timestamp > conftest.file +# Reject unsafe characters in $srcdir or the absolute working directory +# name. Accept space and tab only in the latter. +am_lf=' +' +case `pwd` in + *[\\\"\#\$\&\'\`$am_lf]*) + as_fn_error $? "unsafe absolute working directory name" "$LINENO" 5;; +esac +case $srcdir in + *[\\\"\#\$\&\'\`$am_lf\ \ ]*) + as_fn_error $? "unsafe srcdir value: \`$srcdir'" "$LINENO" 5;; +esac + +# Do `set' in a subshell so we don't clobber the current shell's +# arguments. Must try -L first in case configure is actually a +# symlink; some systems play weird games with the mod time of symlinks +# (eg FreeBSD returns the mod time of the symlink's containing +# directory). +if ( + set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` + if test "$*" = "X"; then + # -L didn't work. + set X `ls -t "$srcdir/configure" conftest.file` + fi + rm -f conftest.file + if test "$*" != "X $srcdir/configure conftest.file" \ + && test "$*" != "X conftest.file $srcdir/configure"; then + + # If neither matched, then we have a broken ls. This can happen + # if, for instance, CONFIG_SHELL is bash and it inherits a + # broken ls alias from the environment. This has actually + # happened. Such a system could not be considered "sane". + as_fn_error $? "ls -t appears to fail. Make sure there is not a broken +alias in your environment" "$LINENO" 5 + fi + + test "$2" = conftest.file + ) +then + # Ok. + : +else + as_fn_error $? "newly created file is older than distributed files! +Check your system clock" "$LINENO" 5 +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +test "$program_prefix" != NONE && + program_transform_name="s&^&$program_prefix&;$program_transform_name" +# Use a double $ so make ignores it. +test "$program_suffix" != NONE && + program_transform_name="s&\$&$program_suffix&;$program_transform_name" +# Double any \ or $. +# By default was `s,x,x', remove it if useless. +ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' +program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"` + +# expand $ac_aux_dir to an absolute path +am_aux_dir=`cd $ac_aux_dir && pwd` + +if test x"${MISSING+set}" != xset; then + case $am_aux_dir in + *\ * | *\ *) + MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; + *) + MISSING="\${SHELL} $am_aux_dir/missing" ;; + esac +fi +# Use eval to expand $SHELL +if eval "$MISSING --run true"; then + am_missing_run="$MISSING --run " +else + am_missing_run= + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`missing' script is too old or missing" >&5 +$as_echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;} +fi + +if test x"${install_sh}" != xset; then + case $am_aux_dir in + *\ * | *\ *) + install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; + *) + install_sh="\${SHELL} $am_aux_dir/install-sh" + esac +fi + +# Installed binaries are usually stripped using `strip' when the user +# run `make install-strip'. However `strip' might not be the right +# tool to use in cross-compilation environments, therefore Automake +# will honor the `STRIP' environment variable to overrule this program. +if test "$cross_compiling" != no; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. +set dummy ${ac_tool_prefix}strip; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_STRIP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$STRIP"; then + ac_cv_prog_STRIP="$STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_STRIP="${ac_tool_prefix}strip" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +STRIP=$ac_cv_prog_STRIP +if test -n "$STRIP"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 +$as_echo "$STRIP" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_STRIP"; then + ac_ct_STRIP=$STRIP + # Extract the first word of "strip", so it can be a program name with args. +set dummy strip; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_STRIP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_STRIP"; then + ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_STRIP="strip" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP +if test -n "$ac_ct_STRIP"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 +$as_echo "$ac_ct_STRIP" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_STRIP" = x; then + STRIP=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + STRIP=$ac_ct_STRIP + fi +else + STRIP="$ac_cv_prog_STRIP" +fi + +fi +INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a thread-safe mkdir -p" >&5 +$as_echo_n "checking for a thread-safe mkdir -p... " >&6; } +if test -z "$MKDIR_P"; then + if ${ac_cv_path_mkdir+:} false; then : + $as_echo_n "(cached) " >&6 +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in mkdir gmkdir; do + for ac_exec_ext in '' $ac_executable_extensions; do + { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; } || continue + case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #( + 'mkdir (GNU coreutils) '* | \ + 'mkdir (coreutils) '* | \ + 'mkdir (fileutils) '4.1*) + ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext + break 3;; + esac + done + done + done +IFS=$as_save_IFS + +fi + + test -d ./--version && rmdir ./--version + if test "${ac_cv_path_mkdir+set}" = set; then + MKDIR_P="$ac_cv_path_mkdir -p" + else + # As a last resort, use the slow shell script. Don't cache a + # value for MKDIR_P within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + MKDIR_P="$ac_install_sh -d" + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5 +$as_echo "$MKDIR_P" >&6; } + +mkdir_p="$MKDIR_P" +case $mkdir_p in + [\\/$]* | ?:[\\/]*) ;; + */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; +esac + +for ac_prog in gawk mawk nawk awk +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_AWK+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$AWK"; then + ac_cv_prog_AWK="$AWK" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_AWK="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +AWK=$ac_cv_prog_AWK +if test -n "$AWK"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 +$as_echo "$AWK" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$AWK" && break +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 +$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } +set x ${MAKE-make} +ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` +if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat >conftest.make <<\_ACEOF +SHELL = /bin/sh +all: + @echo '@@@%%%=$(MAKE)=@@@%%%' +_ACEOF +# GNU make sometimes prints "make[1]: Entering ...", which would confuse us. +case `${MAKE-make} -f conftest.make 2>/dev/null` in + *@@@%%%=?*=@@@%%%*) + eval ac_cv_prog_make_${ac_make}_set=yes;; + *) + eval ac_cv_prog_make_${ac_make}_set=no;; +esac +rm -f conftest.make +fi +if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + SET_MAKE= +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + SET_MAKE="MAKE=${MAKE-make}" +fi + +rm -rf .tst 2>/dev/null +mkdir .tst 2>/dev/null +if test -d .tst; then + am__leading_dot=. +else + am__leading_dot=_ +fi +rmdir .tst 2>/dev/null + +if test "`cd $srcdir && pwd`" != "`pwd`"; then + # Use -I$(srcdir) only when $(srcdir) != ., so that make's output + # is not polluted with repeated "-I." + am__isrc=' -I$(srcdir)' + # test to see if srcdir already configured + if test -f $srcdir/config.status; then + as_fn_error $? "source directory already configured; run \"make distclean\" there first" "$LINENO" 5 + fi +fi + +# test whether we have cygpath +if test -z "$CYGPATH_W"; then + if (cygpath --version) >/dev/null 2>/dev/null; then + CYGPATH_W='cygpath -w' + else + CYGPATH_W=echo + fi +fi + + +# Define the identity of the package. + PACKAGE='gtest' + VERSION='1.7.0' + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE "$PACKAGE" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define VERSION "$VERSION" +_ACEOF + +# Some tools Automake needs. + +ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"} + + +AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"} + + +AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"} + + +AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} + + +MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} + +# We need awk for the "check" target. The system "awk" is bad on +# some platforms. +# Always define AMTAR for backward compatibility. Yes, it's still used +# in the wild :-( We should find a proper way to deprecate it ... +AMTAR='$${TAR-tar}' + +am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -' + + + + + + +# Check for programs used in building Google Test. +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="${ac_tool_prefix}gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CC="gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" +fi + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="${ac_tool_prefix}cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + fi +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" + fi +fi +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl.exe + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$CC" && break + done +fi +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl.exe +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CC="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_CC" && break +done + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +fi + +fi + + +test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "no acceptable C compiler found in \$PATH +See \`config.log' for more details" "$LINENO" 5; } + +# Provide some information about the compiler. +$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +for ac_option in --version -v -V -qversion; do + { { ac_try="$ac_compiler $ac_option >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compiler $ac_option >&5") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + sed '10a\ +... rest of stderr output deleted ... + 10q' conftest.err >conftest.er1 + cat conftest.er1 >&5 + fi + rm -f conftest.er1 conftest.err + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +done + +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 +$as_echo_n "checking whether the C compiler works... " >&6; } +ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { { ac_try="$ac_link_default" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link_default") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. + break;; + * ) + break;; + esac +done +test "$ac_cv_exeext" = no && ac_cv_exeext= + +else + ac_file='' +fi +if test -z "$ac_file"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +$as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error 77 "C compiler cannot create executables +See \`config.log' for more details" "$LINENO" 5; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 +$as_echo_n "checking for C compiler default output file name... " >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 +$as_echo "$ac_file" >&6; } +ac_exeext=$ac_cv_exeext + +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 +$as_echo_n "checking for suffix of executables... " >&6; } +if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + break;; + * ) break;; + esac +done +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest conftest$ac_cv_exeext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 +$as_echo "$ac_cv_exeext" >&6; } + +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +FILE *f = fopen ("conftest.out", "w"); + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +ac_clean_files="$ac_clean_files conftest.out" +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 +$as_echo_n "checking whether we are cross compiling... " >&6; } +if test "$cross_compiling" != yes; then + { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if { ac_try='./conftest$ac_cv_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details" "$LINENO" 5; } + fi + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 +$as_echo "$cross_compiling" >&6; } + +rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 +$as_echo_n "checking for suffix of object files... " >&6; } +if ${ac_cv_objext+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.o conftest.obj +if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of object files: cannot compile +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest.$ac_cv_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 +$as_echo "$ac_cv_objext" >&6; } +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 +$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } +if ${ac_cv_c_compiler_gnu+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_compiler_gnu=yes +else + ac_compiler_gnu=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 +$as_echo "$ac_cv_c_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GCC=yes +else + GCC= +fi +ac_test_CFLAGS=${CFLAGS+set} +ac_save_CFLAGS=$CFLAGS +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 +$as_echo_n "checking whether $CC accepts -g... " >&6; } +if ${ac_cv_prog_cc_g+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +else + CFLAGS="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 +$as_echo "$ac_cv_prog_cc_g" >&6; } +if test "$ac_test_CFLAGS" = set; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 +$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } +if ${ac_cv_prog_cc_c89+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_prog_cc_c89=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include +/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ +struct buf { int x; }; +FILE * (*rcsopen) (struct buf *, struct stat *, int); +static char *e (p, i) + char **p; + int i; +{ + return p[i]; +} +static char *f (char * (*g) (char **, int), char **p, ...) +{ + char *s; + va_list v; + va_start (v,p); + s = g (p, va_arg (v,int)); + va_end (v); + return s; +} + +/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has + function prototypes and stuff, but not '\xHH' hex character constants. + These don't provoke an error unfortunately, instead are silently treated + as 'x'. The following induces an error, until -std is added to get + proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an + array size at least. It's necessary to write '\x00'==0 to get something + that's true only with -std. */ +int osf4_cc_array ['\x00' == 0 ? 1 : -1]; + +/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters + inside strings and character constants. */ +#define FOO(x) 'x' +int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; + +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; +int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); +int argc; +char **argv; +int +main () +{ +return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; + ; + return 0; +} +_ACEOF +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ + -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_c89=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext + test "x$ac_cv_prog_cc_c89" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC + +fi +# AC_CACHE_VAL +case "x$ac_cv_prog_cc_c89" in + x) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; + xno) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; + *) + CC="$CC $ac_cv_prog_cc_c89" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 +$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; +esac +if test "x$ac_cv_prog_cc_c89" != xno; then : + +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +DEPDIR="${am__leading_dot}deps" + +ac_config_commands="$ac_config_commands depfiles" + + +am_make=${MAKE-make} +cat > confinc << 'END' +am__doit: + @echo this is the am__doit target +.PHONY: am__doit +END +# If we don't find an include directive, just comment out the code. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for style of include used by $am_make" >&5 +$as_echo_n "checking for style of include used by $am_make... " >&6; } +am__include="#" +am__quote= +_am_result=none +# First try GNU make style include. +echo "include confinc" > confmf +# Ignore all kinds of additional output from `make'. +case `$am_make -s -f confmf 2> /dev/null` in #( +*the\ am__doit\ target*) + am__include=include + am__quote= + _am_result=GNU + ;; +esac +# Now try BSD make style include. +if test "$am__include" = "#"; then + echo '.include "confinc"' > confmf + case `$am_make -s -f confmf 2> /dev/null` in #( + *the\ am__doit\ target*) + am__include=.include + am__quote="\"" + _am_result=BSD + ;; + esac +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $_am_result" >&5 +$as_echo "$_am_result" >&6; } +rm -f confinc confmf + +# Check whether --enable-dependency-tracking was given. +if test "${enable_dependency_tracking+set}" = set; then : + enableval=$enable_dependency_tracking; +fi + +if test "x$enable_dependency_tracking" != xno; then + am_depcomp="$ac_aux_dir/depcomp" + AMDEPBACKSLASH='\' + am__nodep='_no' +fi + if test "x$enable_dependency_tracking" != xno; then + AMDEP_TRUE= + AMDEP_FALSE='#' +else + AMDEP_TRUE='#' + AMDEP_FALSE= +fi + + + +depcc="$CC" am_compiler_list= + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 +$as_echo_n "checking dependency style of $depcc... " >&6; } +if ${am_cv_CC_dependencies_compiler_type+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then + # We make a subdir and do the tests there. Otherwise we can end up + # making bogus files that we don't know about and never remove. For + # instance it was reported that on HP-UX the gcc test will end up + # making a dummy file named `D' -- because `-MD' means `put the output + # in D'. + rm -rf conftest.dir + mkdir conftest.dir + # Copy depcomp to subdir because otherwise we won't find it if we're + # using a relative directory. + cp "$am_depcomp" conftest.dir + cd conftest.dir + # We will build objects and dependencies in a subdirectory because + # it helps to detect inapplicable dependency modes. For instance + # both Tru64's cc and ICC support -MD to output dependencies as a + # side effect of compilation, but ICC will put the dependencies in + # the current directory while Tru64 will put them in the object + # directory. + mkdir sub + + am_cv_CC_dependencies_compiler_type=none + if test "$am_compiler_list" = ""; then + am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` + fi + am__universal=false + case " $depcc " in #( + *\ -arch\ *\ -arch\ *) am__universal=true ;; + esac + + for depmode in $am_compiler_list; do + # Setup a source with many dependencies, because some compilers + # like to wrap large dependency lists on column 80 (with \), and + # we should not choose a depcomp mode which is confused by this. + # + # We need to recreate these files for each test, as the compiler may + # overwrite some of them when testing with obscure command lines. + # This happens at least with the AIX C compiler. + : > sub/conftest.c + for i in 1 2 3 4 5 6; do + echo '#include "conftst'$i'.h"' >> sub/conftest.c + # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with + # Solaris 8's {/usr,}/bin/sh. + touch sub/conftst$i.h + done + echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + + # We check with `-c' and `-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle `-M -o', and we need to detect this. Also, some Intel + # versions had trouble with output in subdirs + am__obj=sub/conftest.${OBJEXT-o} + am__minus_obj="-o $am__obj" + case $depmode in + gcc) + # This depmode causes a compiler race in universal mode. + test "$am__universal" = false || continue + ;; + nosideeffect) + # after this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested + if test "x$enable_dependency_tracking" = xyes; then + continue + else + break + fi + ;; + msvc7 | msvc7msys | msvisualcpp | msvcmsys) + # This compiler won't grok `-c -o', but also, the minuso test has + # not run yet. These depmodes are late enough in the game, and + # so weak that their functioning should not be impacted. + am__obj=conftest.${OBJEXT-o} + am__minus_obj= + ;; + none) break ;; + esac + if depmode=$depmode \ + source=sub/conftest.c object=$am__obj \ + depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ + $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ + >/dev/null 2>conftest.err && + grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && + grep $am__obj sub/conftest.Po > /dev/null 2>&1 && + ${MAKE-make} -s -f confmf > /dev/null 2>&1; then + # icc doesn't choke on unknown options, it will just issue warnings + # or remarks (even with -Werror). So we grep stderr for any message + # that says an option was ignored or not supported. + # When given -MP, icc 7.0 and 7.1 complain thusly: + # icc: Command line warning: ignoring option '-M'; no argument required + # The diagnosis changed in icc 8.0: + # icc: Command line remark: option '-MP' not supported + if (grep 'ignoring option' conftest.err || + grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else + am_cv_CC_dependencies_compiler_type=$depmode + break + fi + fi + done + + cd .. + rm -rf conftest.dir +else + am_cv_CC_dependencies_compiler_type=none +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_compiler_type" >&5 +$as_echo "$am_cv_CC_dependencies_compiler_type" >&6; } +CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type + + if + test "x$enable_dependency_tracking" != xno \ + && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then + am__fastdepCC_TRUE= + am__fastdepCC_FALSE='#' +else + am__fastdepCC_TRUE='#' + am__fastdepCC_FALSE= +fi + + +ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu +if test -z "$CXX"; then + if test -n "$CCC"; then + CXX=$CCC + else + if test -n "$ac_tool_prefix"; then + for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CXX+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CXX"; then + ac_cv_prog_CXX="$CXX" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CXX="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CXX=$ac_cv_prog_CXX +if test -n "$CXX"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 +$as_echo "$CXX" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$CXX" && break + done +fi +if test -z "$CXX"; then + ac_ct_CXX=$CXX + for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_CXX+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CXX"; then + ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CXX="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CXX=$ac_cv_prog_ac_ct_CXX +if test -n "$ac_ct_CXX"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CXX" >&5 +$as_echo "$ac_ct_CXX" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_CXX" && break +done + + if test "x$ac_ct_CXX" = x; then + CXX="g++" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CXX=$ac_ct_CXX + fi +fi + + fi +fi +# Provide some information about the compiler. +$as_echo "$as_me:${as_lineno-$LINENO}: checking for C++ compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +for ac_option in --version -v -V -qversion; do + { { ac_try="$ac_compiler $ac_option >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compiler $ac_option >&5") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + sed '10a\ +... rest of stderr output deleted ... + 10q' conftest.err >conftest.er1 + cat conftest.er1 >&5 + fi + rm -f conftest.er1 conftest.err + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C++ compiler" >&5 +$as_echo_n "checking whether we are using the GNU C++ compiler... " >&6; } +if ${ac_cv_cxx_compiler_gnu+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_cxx_try_compile "$LINENO"; then : + ac_compiler_gnu=yes +else + ac_compiler_gnu=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_cxx_compiler_gnu=$ac_compiler_gnu + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_compiler_gnu" >&5 +$as_echo "$ac_cv_cxx_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GXX=yes +else + GXX= +fi +ac_test_CXXFLAGS=${CXXFLAGS+set} +ac_save_CXXFLAGS=$CXXFLAGS +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts -g" >&5 +$as_echo_n "checking whether $CXX accepts -g... " >&6; } +if ${ac_cv_prog_cxx_g+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_save_cxx_werror_flag=$ac_cxx_werror_flag + ac_cxx_werror_flag=yes + ac_cv_prog_cxx_g=no + CXXFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_cxx_try_compile "$LINENO"; then : + ac_cv_prog_cxx_g=yes +else + CXXFLAGS="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_cxx_try_compile "$LINENO"; then : + +else + ac_cxx_werror_flag=$ac_save_cxx_werror_flag + CXXFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_cxx_try_compile "$LINENO"; then : + ac_cv_prog_cxx_g=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_cxx_werror_flag=$ac_save_cxx_werror_flag +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_g" >&5 +$as_echo "$ac_cv_prog_cxx_g" >&6; } +if test "$ac_test_CXXFLAGS" = set; then + CXXFLAGS=$ac_save_CXXFLAGS +elif test $ac_cv_prog_cxx_g = yes; then + if test "$GXX" = yes; then + CXXFLAGS="-g -O2" + else + CXXFLAGS="-g" + fi +else + if test "$GXX" = yes; then + CXXFLAGS="-O2" + else + CXXFLAGS= + fi +fi +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +depcc="$CXX" am_compiler_list= + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 +$as_echo_n "checking dependency style of $depcc... " >&6; } +if ${am_cv_CXX_dependencies_compiler_type+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then + # We make a subdir and do the tests there. Otherwise we can end up + # making bogus files that we don't know about and never remove. For + # instance it was reported that on HP-UX the gcc test will end up + # making a dummy file named `D' -- because `-MD' means `put the output + # in D'. + rm -rf conftest.dir + mkdir conftest.dir + # Copy depcomp to subdir because otherwise we won't find it if we're + # using a relative directory. + cp "$am_depcomp" conftest.dir + cd conftest.dir + # We will build objects and dependencies in a subdirectory because + # it helps to detect inapplicable dependency modes. For instance + # both Tru64's cc and ICC support -MD to output dependencies as a + # side effect of compilation, but ICC will put the dependencies in + # the current directory while Tru64 will put them in the object + # directory. + mkdir sub + + am_cv_CXX_dependencies_compiler_type=none + if test "$am_compiler_list" = ""; then + am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` + fi + am__universal=false + case " $depcc " in #( + *\ -arch\ *\ -arch\ *) am__universal=true ;; + esac + + for depmode in $am_compiler_list; do + # Setup a source with many dependencies, because some compilers + # like to wrap large dependency lists on column 80 (with \), and + # we should not choose a depcomp mode which is confused by this. + # + # We need to recreate these files for each test, as the compiler may + # overwrite some of them when testing with obscure command lines. + # This happens at least with the AIX C compiler. + : > sub/conftest.c + for i in 1 2 3 4 5 6; do + echo '#include "conftst'$i'.h"' >> sub/conftest.c + # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with + # Solaris 8's {/usr,}/bin/sh. + touch sub/conftst$i.h + done + echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + + # We check with `-c' and `-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle `-M -o', and we need to detect this. Also, some Intel + # versions had trouble with output in subdirs + am__obj=sub/conftest.${OBJEXT-o} + am__minus_obj="-o $am__obj" + case $depmode in + gcc) + # This depmode causes a compiler race in universal mode. + test "$am__universal" = false || continue + ;; + nosideeffect) + # after this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested + if test "x$enable_dependency_tracking" = xyes; then + continue + else + break + fi + ;; + msvc7 | msvc7msys | msvisualcpp | msvcmsys) + # This compiler won't grok `-c -o', but also, the minuso test has + # not run yet. These depmodes are late enough in the game, and + # so weak that their functioning should not be impacted. + am__obj=conftest.${OBJEXT-o} + am__minus_obj= + ;; + none) break ;; + esac + if depmode=$depmode \ + source=sub/conftest.c object=$am__obj \ + depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ + $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ + >/dev/null 2>conftest.err && + grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && + grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && + grep $am__obj sub/conftest.Po > /dev/null 2>&1 && + ${MAKE-make} -s -f confmf > /dev/null 2>&1; then + # icc doesn't choke on unknown options, it will just issue warnings + # or remarks (even with -Werror). So we grep stderr for any message + # that says an option was ignored or not supported. + # When given -MP, icc 7.0 and 7.1 complain thusly: + # icc: Command line warning: ignoring option '-M'; no argument required + # The diagnosis changed in icc 8.0: + # icc: Command line remark: option '-MP' not supported + if (grep 'ignoring option' conftest.err || + grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else + am_cv_CXX_dependencies_compiler_type=$depmode + break + fi + fi + done + + cd .. + rm -rf conftest.dir +else + am_cv_CXX_dependencies_compiler_type=none +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CXX_dependencies_compiler_type" >&5 +$as_echo "$am_cv_CXX_dependencies_compiler_type" >&6; } +CXXDEPMODE=depmode=$am_cv_CXX_dependencies_compiler_type + + if + test "x$enable_dependency_tracking" != xno \ + && test "$am_cv_CXX_dependencies_compiler_type" = gcc3; then + am__fastdepCXX_TRUE= + am__fastdepCXX_FALSE='#' +else + am__fastdepCXX_TRUE='#' + am__fastdepCXX_FALSE= +fi + + +ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + +case `pwd` in + *\ * | *\ *) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5 +$as_echo "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;; +esac + + + +macro_version='2.4.2' +macro_revision='1.3337' + + + + + + + + + + + + + +ltmain="$ac_aux_dir/ltmain.sh" + +# Make sure we can run config.sub. +$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || + as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 +$as_echo_n "checking build system type... " >&6; } +if ${ac_cv_build+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_build_alias=$build_alias +test "x$ac_build_alias" = x && + ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` +test "x$ac_build_alias" = x && + as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 +ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || + as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 +$as_echo "$ac_cv_build" >&6; } +case $ac_cv_build in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; +esac +build=$ac_cv_build +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_build +shift +build_cpu=$1 +build_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +build_os=$* +IFS=$ac_save_IFS +case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 +$as_echo_n "checking host system type... " >&6; } +if ${ac_cv_host+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "x$host_alias" = x; then + ac_cv_host=$ac_cv_build +else + ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || + as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 +$as_echo "$ac_cv_host" >&6; } +case $ac_cv_host in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; +esac +host=$ac_cv_host +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_host +shift +host_cpu=$1 +host_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +host_os=$* +IFS=$ac_save_IFS +case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac + + +# Backslashify metacharacters that are still active within +# double-quoted strings. +sed_quote_subst='s/\(["`$\\]\)/\\\1/g' + +# Same as above, but do not quote variable references. +double_quote_subst='s/\(["`\\]\)/\\\1/g' + +# Sed substitution to delay expansion of an escaped shell variable in a +# double_quote_subst'ed string. +delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' + +# Sed substitution to delay expansion of an escaped single quote. +delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' + +# Sed substitution to avoid accidental globbing in evaled expressions +no_glob_subst='s/\*/\\\*/g' + +ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO +ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5 +$as_echo_n "checking how to print strings... " >&6; } +# Test print first, because it will be a builtin if present. +if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ + test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then + ECHO='print -r --' +elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then + ECHO='printf %s\n' +else + # Use this function as a fallback that always works. + func_fallback_echo () + { + eval 'cat <<_LTECHO_EOF +$1 +_LTECHO_EOF' + } + ECHO='func_fallback_echo' +fi + +# func_echo_all arg... +# Invoke $ECHO with all args, space-separated. +func_echo_all () +{ + $ECHO "" +} + +case "$ECHO" in + printf*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: printf" >&5 +$as_echo "printf" >&6; } ;; + print*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: print -r" >&5 +$as_echo "print -r" >&6; } ;; + *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: cat" >&5 +$as_echo "cat" >&6; } ;; +esac + + + + + + + + + + + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 +$as_echo_n "checking for a sed that does not truncate output... " >&6; } +if ${ac_cv_path_SED+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ + for ac_i in 1 2 3 4 5 6 7; do + ac_script="$ac_script$as_nl$ac_script" + done + echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed + { ac_script=; unset ac_script;} + if test -z "$SED"; then + ac_path_SED_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in sed gsed; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_SED="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_SED" && $as_test_x "$ac_path_SED"; } || continue +# Check for GNU ac_path_SED and select it if it is found. + # Check for GNU $ac_path_SED +case `"$ac_path_SED" --version 2>&1` in +*GNU*) + ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo '' >> "conftest.nl" + "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_SED_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_SED="$ac_path_SED" + ac_path_SED_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_SED_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_SED"; then + as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5 + fi +else + ac_cv_path_SED=$SED +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 +$as_echo "$ac_cv_path_SED" >&6; } + SED="$ac_cv_path_SED" + rm -f conftest.sed + +test -z "$SED" && SED=sed +Xsed="$SED -e 1s/^X//" + + + + + + + + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 +$as_echo_n "checking for grep that handles long lines and -e... " >&6; } +if ${ac_cv_path_GREP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -z "$GREP"; then + ac_path_GREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in grep ggrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue +# Check for GNU ac_path_GREP and select it if it is found. + # Check for GNU $ac_path_GREP +case `"$ac_path_GREP" --version 2>&1` in +*GNU*) + ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'GREP' >> "conftest.nl" + "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_GREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_GREP="$ac_path_GREP" + ac_path_GREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_GREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_GREP"; then + as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_GREP=$GREP +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 +$as_echo "$ac_cv_path_GREP" >&6; } + GREP="$ac_cv_path_GREP" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 +$as_echo_n "checking for egrep... " >&6; } +if ${ac_cv_path_EGREP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + if test -z "$EGREP"; then + ac_path_EGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue +# Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_EGREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_EGREP"; then + as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_EGREP=$EGREP +fi + + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 +$as_echo "$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5 +$as_echo_n "checking for fgrep... " >&6; } +if ${ac_cv_path_FGREP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1 + then ac_cv_path_FGREP="$GREP -F" + else + if test -z "$FGREP"; then + ac_path_FGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in fgrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_FGREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_FGREP" && $as_test_x "$ac_path_FGREP"; } || continue +# Check for GNU ac_path_FGREP and select it if it is found. + # Check for GNU $ac_path_FGREP +case `"$ac_path_FGREP" --version 2>&1` in +*GNU*) + ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'FGREP' >> "conftest.nl" + "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_FGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_FGREP="$ac_path_FGREP" + ac_path_FGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_FGREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_FGREP"; then + as_fn_error $? "no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_FGREP=$FGREP +fi + + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5 +$as_echo "$ac_cv_path_FGREP" >&6; } + FGREP="$ac_cv_path_FGREP" + + +test -z "$GREP" && GREP=grep + + + + + + + + + + + + + + + + + + + +# Check whether --with-gnu-ld was given. +if test "${with_gnu_ld+set}" = set; then : + withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes +else + with_gnu_ld=no +fi + +ac_prog=ld +if test "$GCC" = yes; then + # Check if gcc -print-prog-name=ld gives a path. + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 +$as_echo_n "checking for ld used by $CC... " >&6; } + case $host in + *-*-mingw*) + # gcc leaves a trailing carriage return which upsets mingw + ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; + *) + ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; + esac + case $ac_prog in + # Accept absolute paths. + [\\/]* | ?:[\\/]*) + re_direlt='/[^/][^/]*/\.\./' + # Canonicalize the pathname of ld + ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` + while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do + ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` + done + test -z "$LD" && LD="$ac_prog" + ;; + "") + # If it fails, then pretend we aren't using GCC. + ac_prog=ld + ;; + *) + # If it is relative, then search for the first ld in PATH. + with_gnu_ld=unknown + ;; + esac +elif test "$with_gnu_ld" = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 +$as_echo_n "checking for GNU ld... " >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 +$as_echo_n "checking for non-GNU ld... " >&6; } +fi +if ${lt_cv_path_LD+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -z "$LD"; then + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then + lt_cv_path_LD="$ac_dir/$ac_prog" + # Check to see if the program is GNU ld. I'd rather use --version, + # but apparently some variants of GNU ld only accept -v. + # Break only if it was the GNU/non-GNU ld that we prefer. + case `"$lt_cv_path_LD" -v 2>&1 &5 +$as_echo "$LD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 +$as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; } +if ${lt_cv_prog_gnu_ld+:} false; then : + $as_echo_n "(cached) " >&6 +else + # I'd rather use --version here, but apparently some GNU lds only accept -v. +case `$LD -v 2>&1 &5 +$as_echo "$lt_cv_prog_gnu_ld" >&6; } +with_gnu_ld=$lt_cv_prog_gnu_ld + + + + + + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5 +$as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; } +if ${lt_cv_path_NM+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$NM"; then + # Let the user override the test. + lt_cv_path_NM="$NM" +else + lt_nm_to_check="${ac_tool_prefix}nm" + if test -n "$ac_tool_prefix" && test "$build" = "$host"; then + lt_nm_to_check="$lt_nm_to_check nm" + fi + for lt_tmp_nm in $lt_nm_to_check; do + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + tmp_nm="$ac_dir/$lt_tmp_nm" + if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then + # Check to see if the nm accepts a BSD-compat flag. + # Adding the `sed 1q' prevents false positives on HP-UX, which says: + # nm: unknown option "B" ignored + # Tru64's nm complains that /dev/null is an invalid object file + case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in + */dev/null* | *'Invalid file or object type'*) + lt_cv_path_NM="$tmp_nm -B" + break + ;; + *) + case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in + */dev/null*) + lt_cv_path_NM="$tmp_nm -p" + break + ;; + *) + lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but + continue # so that we can try to find one that supports BSD flags + ;; + esac + ;; + esac + fi + done + IFS="$lt_save_ifs" + done + : ${lt_cv_path_NM=no} +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5 +$as_echo "$lt_cv_path_NM" >&6; } +if test "$lt_cv_path_NM" != "no"; then + NM="$lt_cv_path_NM" +else + # Didn't find any BSD compatible name lister, look for dumpbin. + if test -n "$DUMPBIN"; then : + # Let the user override the test. + else + if test -n "$ac_tool_prefix"; then + for ac_prog in dumpbin "link -dump" + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_DUMPBIN+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$DUMPBIN"; then + ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +DUMPBIN=$ac_cv_prog_DUMPBIN +if test -n "$DUMPBIN"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5 +$as_echo "$DUMPBIN" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$DUMPBIN" && break + done +fi +if test -z "$DUMPBIN"; then + ac_ct_DUMPBIN=$DUMPBIN + for ac_prog in dumpbin "link -dump" +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_DUMPBIN+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_DUMPBIN"; then + ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_DUMPBIN="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN +if test -n "$ac_ct_DUMPBIN"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5 +$as_echo "$ac_ct_DUMPBIN" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_DUMPBIN" && break +done + + if test "x$ac_ct_DUMPBIN" = x; then + DUMPBIN=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + DUMPBIN=$ac_ct_DUMPBIN + fi +fi + + case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in + *COFF*) + DUMPBIN="$DUMPBIN -symbols" + ;; + *) + DUMPBIN=: + ;; + esac + fi + + if test "$DUMPBIN" != ":"; then + NM="$DUMPBIN" + fi +fi +test -z "$NM" && NM=nm + + + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5 +$as_echo_n "checking the name lister ($NM) interface... " >&6; } +if ${lt_cv_nm_interface+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_nm_interface="BSD nm" + echo "int some_variable = 0;" > conftest.$ac_ext + (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5) + (eval "$ac_compile" 2>conftest.err) + cat conftest.err >&5 + (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&5) + (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) + cat conftest.err >&5 + (eval echo "\"\$as_me:$LINENO: output\"" >&5) + cat conftest.out >&5 + if $GREP 'External.*some_variable' conftest.out > /dev/null; then + lt_cv_nm_interface="MS dumpbin" + fi + rm -f conftest* +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5 +$as_echo "$lt_cv_nm_interface" >&6; } + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 +$as_echo_n "checking whether ln -s works... " >&6; } +LN_S=$as_ln_s +if test "$LN_S" = "ln -s"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 +$as_echo "no, using $LN_S" >&6; } +fi + +# find the maximum length of command line arguments +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5 +$as_echo_n "checking the maximum length of command line arguments... " >&6; } +if ${lt_cv_sys_max_cmd_len+:} false; then : + $as_echo_n "(cached) " >&6 +else + i=0 + teststring="ABCD" + + case $build_os in + msdosdjgpp*) + # On DJGPP, this test can blow up pretty badly due to problems in libc + # (any single argument exceeding 2000 bytes causes a buffer overrun + # during glob expansion). Even if it were fixed, the result of this + # check would be larger than it should be. + lt_cv_sys_max_cmd_len=12288; # 12K is about right + ;; + + gnu*) + # Under GNU Hurd, this test is not required because there is + # no limit to the length of command line arguments. + # Libtool will interpret -1 as no limit whatsoever + lt_cv_sys_max_cmd_len=-1; + ;; + + cygwin* | mingw* | cegcc*) + # On Win9x/ME, this test blows up -- it succeeds, but takes + # about 5 minutes as the teststring grows exponentially. + # Worse, since 9x/ME are not pre-emptively multitasking, + # you end up with a "frozen" computer, even though with patience + # the test eventually succeeds (with a max line length of 256k). + # Instead, let's just punt: use the minimum linelength reported by + # all of the supported platforms: 8192 (on NT/2K/XP). + lt_cv_sys_max_cmd_len=8192; + ;; + + mint*) + # On MiNT this can take a long time and run out of memory. + lt_cv_sys_max_cmd_len=8192; + ;; + + amigaos*) + # On AmigaOS with pdksh, this test takes hours, literally. + # So we just punt and use a minimum line length of 8192. + lt_cv_sys_max_cmd_len=8192; + ;; + + netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) + # This has been around since 386BSD, at least. Likely further. + if test -x /sbin/sysctl; then + lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` + elif test -x /usr/sbin/sysctl; then + lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` + else + lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs + fi + # And add a safety zone + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` + ;; + + interix*) + # We know the value 262144 and hardcode it with a safety zone (like BSD) + lt_cv_sys_max_cmd_len=196608 + ;; + + os2*) + # The test takes a long time on OS/2. + lt_cv_sys_max_cmd_len=8192 + ;; + + osf*) + # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure + # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not + # nice to cause kernel panics so lets avoid the loop below. + # First set a reasonable default. + lt_cv_sys_max_cmd_len=16384 + # + if test -x /sbin/sysconfig; then + case `/sbin/sysconfig -q proc exec_disable_arg_limit` in + *1*) lt_cv_sys_max_cmd_len=-1 ;; + esac + fi + ;; + sco3.2v5*) + lt_cv_sys_max_cmd_len=102400 + ;; + sysv5* | sco5v6* | sysv4.2uw2*) + kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` + if test -n "$kargmax"; then + lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[ ]//'` + else + lt_cv_sys_max_cmd_len=32768 + fi + ;; + *) + lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` + if test -n "$lt_cv_sys_max_cmd_len"; then + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` + else + # Make teststring a little bigger before we do anything with it. + # a 1K string should be a reasonable start. + for i in 1 2 3 4 5 6 7 8 ; do + teststring=$teststring$teststring + done + SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} + # If test is not a shell built-in, we'll probably end up computing a + # maximum length that is only half of the actual maximum length, but + # we can't tell. + while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \ + = "X$teststring$teststring"; } >/dev/null 2>&1 && + test $i != 17 # 1/2 MB should be enough + do + i=`expr $i + 1` + teststring=$teststring$teststring + done + # Only check the string length outside the loop. + lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` + teststring= + # Add a significant safety factor because C++ compilers can tack on + # massive amounts of additional arguments before passing them to the + # linker. It appears as though 1/2 is a usable value. + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` + fi + ;; + esac + +fi + +if test -n $lt_cv_sys_max_cmd_len ; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5 +$as_echo "$lt_cv_sys_max_cmd_len" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5 +$as_echo "none" >&6; } +fi +max_cmd_len=$lt_cv_sys_max_cmd_len + + + + + + +: ${CP="cp -f"} +: ${MV="mv -f"} +: ${RM="rm -f"} + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands some XSI constructs" >&5 +$as_echo_n "checking whether the shell understands some XSI constructs... " >&6; } +# Try some XSI features +xsi_shell=no +( _lt_dummy="a/b/c" + test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \ + = c,a/b,b/c, \ + && eval 'test $(( 1 + 1 )) -eq 2 \ + && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \ + && xsi_shell=yes +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $xsi_shell" >&5 +$as_echo "$xsi_shell" >&6; } + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands \"+=\"" >&5 +$as_echo_n "checking whether the shell understands \"+=\"... " >&6; } +lt_shell_append=no +( foo=bar; set foo baz; eval "$1+=\$2" && test "$foo" = barbaz ) \ + >/dev/null 2>&1 \ + && lt_shell_append=yes +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_shell_append" >&5 +$as_echo "$lt_shell_append" >&6; } + + +if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then + lt_unset=unset +else + lt_unset=false +fi + + + + + +# test EBCDIC or ASCII +case `echo X|tr X '\101'` in + A) # ASCII based system + # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr + lt_SP2NL='tr \040 \012' + lt_NL2SP='tr \015\012 \040\040' + ;; + *) # EBCDIC based system + lt_SP2NL='tr \100 \n' + lt_NL2SP='tr \r\n \100\100' + ;; +esac + + + + + + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to $host format" >&5 +$as_echo_n "checking how to convert $build file names to $host format... " >&6; } +if ${lt_cv_to_host_file_cmd+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $host in + *-*-mingw* ) + case $build in + *-*-mingw* ) # actually msys + lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 + ;; + *-*-cygwin* ) + lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 + ;; + * ) # otherwise, assume *nix + lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 + ;; + esac + ;; + *-*-cygwin* ) + case $build in + *-*-mingw* ) # actually msys + lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin + ;; + *-*-cygwin* ) + lt_cv_to_host_file_cmd=func_convert_file_noop + ;; + * ) # otherwise, assume *nix + lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin + ;; + esac + ;; + * ) # unhandled hosts (and "normal" native builds) + lt_cv_to_host_file_cmd=func_convert_file_noop + ;; +esac + +fi + +to_host_file_cmd=$lt_cv_to_host_file_cmd +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_host_file_cmd" >&5 +$as_echo "$lt_cv_to_host_file_cmd" >&6; } + + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to toolchain format" >&5 +$as_echo_n "checking how to convert $build file names to toolchain format... " >&6; } +if ${lt_cv_to_tool_file_cmd+:} false; then : + $as_echo_n "(cached) " >&6 +else + #assume ordinary cross tools, or native build. +lt_cv_to_tool_file_cmd=func_convert_file_noop +case $host in + *-*-mingw* ) + case $build in + *-*-mingw* ) # actually msys + lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 + ;; + esac + ;; +esac + +fi + +to_tool_file_cmd=$lt_cv_to_tool_file_cmd +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_tool_file_cmd" >&5 +$as_echo "$lt_cv_to_tool_file_cmd" >&6; } + + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5 +$as_echo_n "checking for $LD option to reload object files... " >&6; } +if ${lt_cv_ld_reload_flag+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_ld_reload_flag='-r' +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5 +$as_echo "$lt_cv_ld_reload_flag" >&6; } +reload_flag=$lt_cv_ld_reload_flag +case $reload_flag in +"" | " "*) ;; +*) reload_flag=" $reload_flag" ;; +esac +reload_cmds='$LD$reload_flag -o $output$reload_objs' +case $host_os in + cygwin* | mingw* | pw32* | cegcc*) + if test "$GCC" != yes; then + reload_cmds=false + fi + ;; + darwin*) + if test "$GCC" = yes; then + reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs' + else + reload_cmds='$LD$reload_flag -o $output$reload_objs' + fi + ;; +esac + + + + + + + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args. +set dummy ${ac_tool_prefix}objdump; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_OBJDUMP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$OBJDUMP"; then + ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +OBJDUMP=$ac_cv_prog_OBJDUMP +if test -n "$OBJDUMP"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5 +$as_echo "$OBJDUMP" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_OBJDUMP"; then + ac_ct_OBJDUMP=$OBJDUMP + # Extract the first word of "objdump", so it can be a program name with args. +set dummy objdump; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_OBJDUMP"; then + ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_OBJDUMP="objdump" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP +if test -n "$ac_ct_OBJDUMP"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5 +$as_echo "$ac_ct_OBJDUMP" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_OBJDUMP" = x; then + OBJDUMP="false" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + OBJDUMP=$ac_ct_OBJDUMP + fi +else + OBJDUMP="$ac_cv_prog_OBJDUMP" +fi + +test -z "$OBJDUMP" && OBJDUMP=objdump + + + + + + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5 +$as_echo_n "checking how to recognize dependent libraries... " >&6; } +if ${lt_cv_deplibs_check_method+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_file_magic_cmd='$MAGIC_CMD' +lt_cv_file_magic_test_file= +lt_cv_deplibs_check_method='unknown' +# Need to set the preceding variable on all platforms that support +# interlibrary dependencies. +# 'none' -- dependencies not supported. +# `unknown' -- same as none, but documents that we really don't know. +# 'pass_all' -- all dependencies passed with no checks. +# 'test_compile' -- check by making test program. +# 'file_magic [[regex]]' -- check by looking for files in library path +# which responds to the $file_magic_cmd with a given extended regex. +# If you have `file' or equivalent on your system and you're not sure +# whether `pass_all' will *always* work, you probably want this one. + +case $host_os in +aix[4-9]*) + lt_cv_deplibs_check_method=pass_all + ;; + +beos*) + lt_cv_deplibs_check_method=pass_all + ;; + +bsdi[45]*) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)' + lt_cv_file_magic_cmd='/usr/bin/file -L' + lt_cv_file_magic_test_file=/shlib/libc.so + ;; + +cygwin*) + # func_win32_libid is a shell function defined in ltmain.sh + lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' + lt_cv_file_magic_cmd='func_win32_libid' + ;; + +mingw* | pw32*) + # Base MSYS/MinGW do not provide the 'file' command needed by + # func_win32_libid shell function, so use a weaker test based on 'objdump', + # unless we find 'file', for example because we are cross-compiling. + # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin. + if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then + lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' + lt_cv_file_magic_cmd='func_win32_libid' + else + # Keep this pattern in sync with the one in func_win32_libid. + lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' + lt_cv_file_magic_cmd='$OBJDUMP -f' + fi + ;; + +cegcc*) + # use the weaker test based on 'objdump'. See mingw*. + lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' + lt_cv_file_magic_cmd='$OBJDUMP -f' + ;; + +darwin* | rhapsody*) + lt_cv_deplibs_check_method=pass_all + ;; + +freebsd* | dragonfly*) + if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then + case $host_cpu in + i*86 ) + # Not sure whether the presence of OpenBSD here was a mistake. + # Let's accept both of them until this is cleared up. + lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library' + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` + ;; + esac + else + lt_cv_deplibs_check_method=pass_all + fi + ;; + +gnu*) + lt_cv_deplibs_check_method=pass_all + ;; + +haiku*) + lt_cv_deplibs_check_method=pass_all + ;; + +hpux10.20* | hpux11*) + lt_cv_file_magic_cmd=/usr/bin/file + case $host_cpu in + ia64*) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64' + lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so + ;; + hppa*64*) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]' + lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl + ;; + *) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9]\.[0-9]) shared library' + lt_cv_file_magic_test_file=/usr/lib/libc.sl + ;; + esac + ;; + +interix[3-9]*) + # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$' + ;; + +irix5* | irix6* | nonstopux*) + case $LD in + *-32|*"-32 ") libmagic=32-bit;; + *-n32|*"-n32 ") libmagic=N32;; + *-64|*"-64 ") libmagic=64-bit;; + *) libmagic=never-match;; + esac + lt_cv_deplibs_check_method=pass_all + ;; + +# This must be glibc/ELF. +linux* | k*bsd*-gnu | kopensolaris*-gnu) + lt_cv_deplibs_check_method=pass_all + ;; + +netbsd* | netbsdelf*-gnu) + if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$' + fi + ;; + +newos6*) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)' + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=/usr/lib/libnls.so + ;; + +*nto* | *qnx*) + lt_cv_deplibs_check_method=pass_all + ;; + +openbsd*) + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' + fi + ;; + +osf3* | osf4* | osf5*) + lt_cv_deplibs_check_method=pass_all + ;; + +rdos*) + lt_cv_deplibs_check_method=pass_all + ;; + +solaris*) + lt_cv_deplibs_check_method=pass_all + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + lt_cv_deplibs_check_method=pass_all + ;; + +sysv4 | sysv4.3*) + case $host_vendor in + motorola) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]' + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` + ;; + ncr) + lt_cv_deplibs_check_method=pass_all + ;; + sequent) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )' + ;; + sni) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib" + lt_cv_file_magic_test_file=/lib/libc.so + ;; + siemens) + lt_cv_deplibs_check_method=pass_all + ;; + pc) + lt_cv_deplibs_check_method=pass_all + ;; + esac + ;; + +tpf*) + lt_cv_deplibs_check_method=pass_all + ;; +esac + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5 +$as_echo "$lt_cv_deplibs_check_method" >&6; } + +file_magic_glob= +want_nocaseglob=no +if test "$build" = "$host"; then + case $host_os in + mingw* | pw32*) + if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then + want_nocaseglob=yes + else + file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[\1]\/[\1]\/g;/g"` + fi + ;; + esac +fi + +file_magic_cmd=$lt_cv_file_magic_cmd +deplibs_check_method=$lt_cv_deplibs_check_method +test -z "$deplibs_check_method" && deplibs_check_method=unknown + + + + + + + + + + + + + + + + + + + + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args. +set dummy ${ac_tool_prefix}dlltool; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_DLLTOOL+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$DLLTOOL"; then + ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +DLLTOOL=$ac_cv_prog_DLLTOOL +if test -n "$DLLTOOL"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5 +$as_echo "$DLLTOOL" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_DLLTOOL"; then + ac_ct_DLLTOOL=$DLLTOOL + # Extract the first word of "dlltool", so it can be a program name with args. +set dummy dlltool; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_DLLTOOL+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_DLLTOOL"; then + ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_DLLTOOL="dlltool" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL +if test -n "$ac_ct_DLLTOOL"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5 +$as_echo "$ac_ct_DLLTOOL" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_DLLTOOL" = x; then + DLLTOOL="false" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + DLLTOOL=$ac_ct_DLLTOOL + fi +else + DLLTOOL="$ac_cv_prog_DLLTOOL" +fi + +test -z "$DLLTOOL" && DLLTOOL=dlltool + + + + + + + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to associate runtime and link libraries" >&5 +$as_echo_n "checking how to associate runtime and link libraries... " >&6; } +if ${lt_cv_sharedlib_from_linklib_cmd+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_sharedlib_from_linklib_cmd='unknown' + +case $host_os in +cygwin* | mingw* | pw32* | cegcc*) + # two different shell functions defined in ltmain.sh + # decide which to use based on capabilities of $DLLTOOL + case `$DLLTOOL --help 2>&1` in + *--identify-strict*) + lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib + ;; + *) + lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback + ;; + esac + ;; +*) + # fallback: assume linklib IS sharedlib + lt_cv_sharedlib_from_linklib_cmd="$ECHO" + ;; +esac + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_linklib_cmd" >&5 +$as_echo "$lt_cv_sharedlib_from_linklib_cmd" >&6; } +sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd +test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO + + + + + + + + +if test -n "$ac_tool_prefix"; then + for ac_prog in ar + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_AR+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$AR"; then + ac_cv_prog_AR="$AR" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_AR="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +AR=$ac_cv_prog_AR +if test -n "$AR"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 +$as_echo "$AR" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$AR" && break + done +fi +if test -z "$AR"; then + ac_ct_AR=$AR + for ac_prog in ar +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_AR+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_AR"; then + ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_AR="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_AR=$ac_cv_prog_ac_ct_AR +if test -n "$ac_ct_AR"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5 +$as_echo "$ac_ct_AR" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_AR" && break +done + + if test "x$ac_ct_AR" = x; then + AR="false" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + AR=$ac_ct_AR + fi +fi + +: ${AR=ar} +: ${AR_FLAGS=cru} + + + + + + + + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for archiver @FILE support" >&5 +$as_echo_n "checking for archiver @FILE support... " >&6; } +if ${lt_cv_ar_at_file+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_ar_at_file=no + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_cxx_try_compile "$LINENO"; then : + echo conftest.$ac_objext > conftest.lst + lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 + (eval $lt_ar_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if test "$ac_status" -eq 0; then + # Ensure the archiver fails upon bogus file names. + rm -f conftest.$ac_objext libconftest.a + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 + (eval $lt_ar_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if test "$ac_status" -ne 0; then + lt_cv_ar_at_file=@ + fi + fi + rm -f conftest.* libconftest.a + +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5 +$as_echo "$lt_cv_ar_at_file" >&6; } + +if test "x$lt_cv_ar_at_file" = xno; then + archiver_list_spec= +else + archiver_list_spec=$lt_cv_ar_at_file +fi + + + + + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. +set dummy ${ac_tool_prefix}strip; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_STRIP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$STRIP"; then + ac_cv_prog_STRIP="$STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_STRIP="${ac_tool_prefix}strip" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +STRIP=$ac_cv_prog_STRIP +if test -n "$STRIP"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 +$as_echo "$STRIP" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_STRIP"; then + ac_ct_STRIP=$STRIP + # Extract the first word of "strip", so it can be a program name with args. +set dummy strip; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_STRIP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_STRIP"; then + ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_STRIP="strip" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP +if test -n "$ac_ct_STRIP"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 +$as_echo "$ac_ct_STRIP" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_STRIP" = x; then + STRIP=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + STRIP=$ac_ct_STRIP + fi +else + STRIP="$ac_cv_prog_STRIP" +fi + +test -z "$STRIP" && STRIP=: + + + + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. +set dummy ${ac_tool_prefix}ranlib; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_RANLIB+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$RANLIB"; then + ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +RANLIB=$ac_cv_prog_RANLIB +if test -n "$RANLIB"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 +$as_echo "$RANLIB" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_RANLIB"; then + ac_ct_RANLIB=$RANLIB + # Extract the first word of "ranlib", so it can be a program name with args. +set dummy ranlib; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_RANLIB+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_RANLIB"; then + ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_RANLIB="ranlib" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB +if test -n "$ac_ct_RANLIB"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 +$as_echo "$ac_ct_RANLIB" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_RANLIB" = x; then + RANLIB=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + RANLIB=$ac_ct_RANLIB + fi +else + RANLIB="$ac_cv_prog_RANLIB" +fi + +test -z "$RANLIB" && RANLIB=: + + + + + + +# Determine commands to create old-style static archives. +old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' +old_postinstall_cmds='chmod 644 $oldlib' +old_postuninstall_cmds= + +if test -n "$RANLIB"; then + case $host_os in + openbsd*) + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" + ;; + *) + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" + ;; + esac + old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" +fi + +case $host_os in + darwin*) + lock_old_archive_extraction=yes ;; + *) + lock_old_archive_extraction=no ;; +esac + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# Check for command to grab the raw symbol name followed by C symbol from nm. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5 +$as_echo_n "checking command to parse $NM output from $compiler object... " >&6; } +if ${lt_cv_sys_global_symbol_pipe+:} false; then : + $as_echo_n "(cached) " >&6 +else + +# These are sane defaults that work on at least a few old systems. +# [They come from Ultrix. What could be older than Ultrix?!! ;)] + +# Character class describing NM global symbol codes. +symcode='[BCDEGRST]' + +# Regexp to match symbols that can be accessed directly from C. +sympat='\([_A-Za-z][_A-Za-z0-9]*\)' + +# Define system-specific variables. +case $host_os in +aix*) + symcode='[BCDT]' + ;; +cygwin* | mingw* | pw32* | cegcc*) + symcode='[ABCDGISTW]' + ;; +hpux*) + if test "$host_cpu" = ia64; then + symcode='[ABCDEGRST]' + fi + ;; +irix* | nonstopux*) + symcode='[BCDEGRST]' + ;; +osf*) + symcode='[BCDEGQRST]' + ;; +solaris*) + symcode='[BDRT]' + ;; +sco3.2v5*) + symcode='[DT]' + ;; +sysv4.2uw2*) + symcode='[DT]' + ;; +sysv5* | sco5v6* | unixware* | OpenUNIX*) + symcode='[ABDT]' + ;; +sysv4) + symcode='[DFNSTU]' + ;; +esac + +# If we're using GNU nm, then use its standard symbol codes. +case `$NM -V 2>&1` in +*GNU* | *'with BFD'*) + symcode='[ABCDGIRSTW]' ;; +esac + +# Transform an extracted symbol line into a proper C declaration. +# Some systems (esp. on ia64) link data and code symbols differently, +# so use this general approach. +lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" + +# Transform an extracted symbol line into symbol name and symbol address +lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\)[ ]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (void *) \&\2},/p'" +lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([^ ]*\)[ ]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \(lib[^ ]*\)$/ {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"lib\2\", (void *) \&\2},/p'" + +# Handle CRLF in mingw tool chain +opt_cr= +case $build_os in +mingw*) + opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp + ;; +esac + +# Try without a prefix underscore, then with it. +for ac_symprfx in "" "_"; do + + # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. + symxfrm="\\1 $ac_symprfx\\2 \\2" + + # Write the raw and C identifiers. + if test "$lt_cv_nm_interface" = "MS dumpbin"; then + # Fake it for dumpbin and say T for any non-static function + # and D for any global variable. + # Also find C++ and __fastcall symbols from MSVC++, + # which start with @ or ?. + lt_cv_sys_global_symbol_pipe="$AWK '"\ +" {last_section=section; section=\$ 3};"\ +" /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ +" /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ +" \$ 0!~/External *\|/{next};"\ +" / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ +" {if(hide[section]) next};"\ +" {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\ +" {split(\$ 0, a, /\||\r/); split(a[2], s)};"\ +" s[1]~/^[@?]/{print s[1], s[1]; next};"\ +" s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\ +" ' prfx=^$ac_symprfx" + else + lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" + fi + lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'" + + # Check to see that the pipe works correctly. + pipe_works=no + + rm -f conftest* + cat > conftest.$ac_ext <<_LT_EOF +#ifdef __cplusplus +extern "C" { +#endif +char nm_test_var; +void nm_test_func(void); +void nm_test_func(void){} +#ifdef __cplusplus +} +#endif +int main(){nm_test_var='a';nm_test_func();return(0);} +_LT_EOF + + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + # Now try to grab the symbols. + nlist=conftest.nm + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist\""; } >&5 + (eval $NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && test -s "$nlist"; then + # Try sorting and uniquifying the output. + if sort "$nlist" | uniq > "$nlist"T; then + mv -f "$nlist"T "$nlist" + else + rm -f "$nlist"T + fi + + # Make sure that we snagged all the symbols we need. + if $GREP ' nm_test_var$' "$nlist" >/dev/null; then + if $GREP ' nm_test_func$' "$nlist" >/dev/null; then + cat <<_LT_EOF > conftest.$ac_ext +/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ +#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) +/* DATA imports from DLLs on WIN32 con't be const, because runtime + relocations are performed -- see ld's documentation on pseudo-relocs. */ +# define LT_DLSYM_CONST +#elif defined(__osf__) +/* This system does not cope well with relocations in const data. */ +# define LT_DLSYM_CONST +#else +# define LT_DLSYM_CONST const +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +_LT_EOF + # Now generate the symbol file. + eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' + + cat <<_LT_EOF >> conftest.$ac_ext + +/* The mapping between symbol names and symbols. */ +LT_DLSYM_CONST struct { + const char *name; + void *address; +} +lt__PROGRAM__LTX_preloaded_symbols[] = +{ + { "@PROGRAM@", (void *) 0 }, +_LT_EOF + $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext + cat <<\_LT_EOF >> conftest.$ac_ext + {0, (void *) 0} +}; + +/* This works around a problem in FreeBSD linker */ +#ifdef FREEBSD_WORKAROUND +static const void *lt_preloaded_setup() { + return lt__PROGRAM__LTX_preloaded_symbols; +} +#endif + +#ifdef __cplusplus +} +#endif +_LT_EOF + # Now try linking the two files. + mv conftest.$ac_objext conftstm.$ac_objext + lt_globsym_save_LIBS=$LIBS + lt_globsym_save_CFLAGS=$CFLAGS + LIBS="conftstm.$ac_objext" + CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag" + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 + (eval $ac_link) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && test -s conftest${ac_exeext}; then + pipe_works=yes + fi + LIBS=$lt_globsym_save_LIBS + CFLAGS=$lt_globsym_save_CFLAGS + else + echo "cannot find nm_test_func in $nlist" >&5 + fi + else + echo "cannot find nm_test_var in $nlist" >&5 + fi + else + echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5 + fi + else + echo "$progname: failed program was:" >&5 + cat conftest.$ac_ext >&5 + fi + rm -rf conftest* conftst* + + # Do not use the global_symbol_pipe unless it works. + if test "$pipe_works" = yes; then + break + else + lt_cv_sys_global_symbol_pipe= + fi +done + +fi + +if test -z "$lt_cv_sys_global_symbol_pipe"; then + lt_cv_sys_global_symbol_to_cdecl= +fi +if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: failed" >&5 +$as_echo "failed" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 +$as_echo "ok" >&6; } +fi + +# Response file support. +if test "$lt_cv_nm_interface" = "MS dumpbin"; then + nm_file_list_spec='@' +elif $NM --help 2>/dev/null | grep '[@]FILE' >/dev/null; then + nm_file_list_spec='@' +fi + + + + + + + + + + + + + + + + + + + + + + + + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sysroot" >&5 +$as_echo_n "checking for sysroot... " >&6; } + +# Check whether --with-sysroot was given. +if test "${with_sysroot+set}" = set; then : + withval=$with_sysroot; +else + with_sysroot=no +fi + + +lt_sysroot= +case ${with_sysroot} in #( + yes) + if test "$GCC" = yes; then + lt_sysroot=`$CC --print-sysroot 2>/dev/null` + fi + ;; #( + /*) + lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"` + ;; #( + no|'') + ;; #( + *) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${with_sysroot}" >&5 +$as_echo "${with_sysroot}" >&6; } + as_fn_error $? "The sysroot must be an absolute path." "$LINENO" 5 + ;; +esac + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${lt_sysroot:-no}" >&5 +$as_echo "${lt_sysroot:-no}" >&6; } + + + + + + +# Check whether --enable-libtool-lock was given. +if test "${enable_libtool_lock+set}" = set; then : + enableval=$enable_libtool_lock; +fi + +test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes + +# Some flags need to be propagated to the compiler or linker for good +# libtool support. +case $host in +ia64-*-hpux*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + case `/usr/bin/file conftest.$ac_objext` in + *ELF-32*) + HPUX_IA64_MODE="32" + ;; + *ELF-64*) + HPUX_IA64_MODE="64" + ;; + esac + fi + rm -rf conftest* + ;; +*-*-irix6*) + # Find out which ABI we are using. + echo '#line '$LINENO' "configure"' > conftest.$ac_ext + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + if test "$lt_cv_prog_gnu_ld" = yes; then + case `/usr/bin/file conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -melf32bsmip" + ;; + *N32*) + LD="${LD-ld} -melf32bmipn32" + ;; + *64-bit*) + LD="${LD-ld} -melf64bmip" + ;; + esac + else + case `/usr/bin/file conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -32" + ;; + *N32*) + LD="${LD-ld} -n32" + ;; + *64-bit*) + LD="${LD-ld} -64" + ;; + esac + fi + fi + rm -rf conftest* + ;; + +x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \ +s390*-*linux*|s390*-*tpf*|sparc*-*linux*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + case `/usr/bin/file conftest.o` in + *32-bit*) + case $host in + x86_64-*kfreebsd*-gnu) + LD="${LD-ld} -m elf_i386_fbsd" + ;; + x86_64-*linux*) + LD="${LD-ld} -m elf_i386" + ;; + ppc64-*linux*|powerpc64-*linux*) + LD="${LD-ld} -m elf32ppclinux" + ;; + s390x-*linux*) + LD="${LD-ld} -m elf_s390" + ;; + sparc64-*linux*) + LD="${LD-ld} -m elf32_sparc" + ;; + esac + ;; + *64-bit*) + case $host in + x86_64-*kfreebsd*-gnu) + LD="${LD-ld} -m elf_x86_64_fbsd" + ;; + x86_64-*linux*) + LD="${LD-ld} -m elf_x86_64" + ;; + ppc*-*linux*|powerpc*-*linux*) + LD="${LD-ld} -m elf64ppc" + ;; + s390*-*linux*|s390*-*tpf*) + LD="${LD-ld} -m elf64_s390" + ;; + sparc*-*linux*) + LD="${LD-ld} -m elf64_sparc" + ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; + +*-*-sco3.2v5*) + # On SCO OpenServer 5, we need -belf to get full-featured binaries. + SAVE_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS -belf" + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler needs -belf" >&5 +$as_echo_n "checking whether the C compiler needs -belf... " >&6; } +if ${lt_cv_cc_needs_belf+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + lt_cv_cc_needs_belf=yes +else + lt_cv_cc_needs_belf=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5 +$as_echo "$lt_cv_cc_needs_belf" >&6; } + if test x"$lt_cv_cc_needs_belf" != x"yes"; then + # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf + CFLAGS="$SAVE_CFLAGS" + fi + ;; +*-*solaris*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + case `/usr/bin/file conftest.o` in + *64-bit*) + case $lt_cv_prog_gnu_ld in + yes*) + case $host in + i?86-*-solaris*) + LD="${LD-ld} -m elf_x86_64" + ;; + sparc*-*-solaris*) + LD="${LD-ld} -m elf64_sparc" + ;; + esac + # GNU ld 2.21 introduced _sol2 emulations. Use them if available. + if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then + LD="${LD-ld}_sol2" + fi + ;; + *) + if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then + LD="${LD-ld} -64" + fi + ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; +esac + +need_locks="$enable_libtool_lock" + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}mt", so it can be a program name with args. +set dummy ${ac_tool_prefix}mt; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_MANIFEST_TOOL+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$MANIFEST_TOOL"; then + ac_cv_prog_MANIFEST_TOOL="$MANIFEST_TOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_MANIFEST_TOOL="${ac_tool_prefix}mt" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +MANIFEST_TOOL=$ac_cv_prog_MANIFEST_TOOL +if test -n "$MANIFEST_TOOL"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MANIFEST_TOOL" >&5 +$as_echo "$MANIFEST_TOOL" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_MANIFEST_TOOL"; then + ac_ct_MANIFEST_TOOL=$MANIFEST_TOOL + # Extract the first word of "mt", so it can be a program name with args. +set dummy mt; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_MANIFEST_TOOL+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_MANIFEST_TOOL"; then + ac_cv_prog_ac_ct_MANIFEST_TOOL="$ac_ct_MANIFEST_TOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_MANIFEST_TOOL="mt" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_MANIFEST_TOOL=$ac_cv_prog_ac_ct_MANIFEST_TOOL +if test -n "$ac_ct_MANIFEST_TOOL"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_MANIFEST_TOOL" >&5 +$as_echo "$ac_ct_MANIFEST_TOOL" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_MANIFEST_TOOL" = x; then + MANIFEST_TOOL=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + MANIFEST_TOOL=$ac_ct_MANIFEST_TOOL + fi +else + MANIFEST_TOOL="$ac_cv_prog_MANIFEST_TOOL" +fi + +test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if $MANIFEST_TOOL is a manifest tool" >&5 +$as_echo_n "checking if $MANIFEST_TOOL is a manifest tool... " >&6; } +if ${lt_cv_path_mainfest_tool+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_path_mainfest_tool=no + echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&5 + $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out + cat conftest.err >&5 + if $GREP 'Manifest Tool' conftest.out > /dev/null; then + lt_cv_path_mainfest_tool=yes + fi + rm -f conftest* +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_mainfest_tool" >&5 +$as_echo "$lt_cv_path_mainfest_tool" >&6; } +if test "x$lt_cv_path_mainfest_tool" != xyes; then + MANIFEST_TOOL=: +fi + + + + + + + case $host_os in + rhapsody* | darwin*) + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a program name with args. +set dummy ${ac_tool_prefix}dsymutil; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_DSYMUTIL+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$DSYMUTIL"; then + ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_DSYMUTIL="${ac_tool_prefix}dsymutil" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +DSYMUTIL=$ac_cv_prog_DSYMUTIL +if test -n "$DSYMUTIL"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DSYMUTIL" >&5 +$as_echo "$DSYMUTIL" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_DSYMUTIL"; then + ac_ct_DSYMUTIL=$DSYMUTIL + # Extract the first word of "dsymutil", so it can be a program name with args. +set dummy dsymutil; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_DSYMUTIL+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_DSYMUTIL"; then + ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_DSYMUTIL="dsymutil" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_DSYMUTIL=$ac_cv_prog_ac_ct_DSYMUTIL +if test -n "$ac_ct_DSYMUTIL"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DSYMUTIL" >&5 +$as_echo "$ac_ct_DSYMUTIL" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_DSYMUTIL" = x; then + DSYMUTIL=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + DSYMUTIL=$ac_ct_DSYMUTIL + fi +else + DSYMUTIL="$ac_cv_prog_DSYMUTIL" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a program name with args. +set dummy ${ac_tool_prefix}nmedit; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_NMEDIT+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$NMEDIT"; then + ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_NMEDIT="${ac_tool_prefix}nmedit" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +NMEDIT=$ac_cv_prog_NMEDIT +if test -n "$NMEDIT"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NMEDIT" >&5 +$as_echo "$NMEDIT" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_NMEDIT"; then + ac_ct_NMEDIT=$NMEDIT + # Extract the first word of "nmedit", so it can be a program name with args. +set dummy nmedit; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_NMEDIT+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_NMEDIT"; then + ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_NMEDIT="nmedit" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_NMEDIT=$ac_cv_prog_ac_ct_NMEDIT +if test -n "$ac_ct_NMEDIT"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_NMEDIT" >&5 +$as_echo "$ac_ct_NMEDIT" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_NMEDIT" = x; then + NMEDIT=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + NMEDIT=$ac_ct_NMEDIT + fi +else + NMEDIT="$ac_cv_prog_NMEDIT" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}lipo", so it can be a program name with args. +set dummy ${ac_tool_prefix}lipo; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_LIPO+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$LIPO"; then + ac_cv_prog_LIPO="$LIPO" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_LIPO="${ac_tool_prefix}lipo" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +LIPO=$ac_cv_prog_LIPO +if test -n "$LIPO"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIPO" >&5 +$as_echo "$LIPO" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_LIPO"; then + ac_ct_LIPO=$LIPO + # Extract the first word of "lipo", so it can be a program name with args. +set dummy lipo; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_LIPO+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_LIPO"; then + ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_LIPO="lipo" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_LIPO=$ac_cv_prog_ac_ct_LIPO +if test -n "$ac_ct_LIPO"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_LIPO" >&5 +$as_echo "$ac_ct_LIPO" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_LIPO" = x; then + LIPO=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + LIPO=$ac_ct_LIPO + fi +else + LIPO="$ac_cv_prog_LIPO" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}otool", so it can be a program name with args. +set dummy ${ac_tool_prefix}otool; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_OTOOL+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$OTOOL"; then + ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_OTOOL="${ac_tool_prefix}otool" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +OTOOL=$ac_cv_prog_OTOOL +if test -n "$OTOOL"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL" >&5 +$as_echo "$OTOOL" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_OTOOL"; then + ac_ct_OTOOL=$OTOOL + # Extract the first word of "otool", so it can be a program name with args. +set dummy otool; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_OTOOL+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_OTOOL"; then + ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_OTOOL="otool" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_OTOOL=$ac_cv_prog_ac_ct_OTOOL +if test -n "$ac_ct_OTOOL"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL" >&5 +$as_echo "$ac_ct_OTOOL" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_OTOOL" = x; then + OTOOL=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + OTOOL=$ac_ct_OTOOL + fi +else + OTOOL="$ac_cv_prog_OTOOL" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}otool64", so it can be a program name with args. +set dummy ${ac_tool_prefix}otool64; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_OTOOL64+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$OTOOL64"; then + ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_OTOOL64="${ac_tool_prefix}otool64" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +OTOOL64=$ac_cv_prog_OTOOL64 +if test -n "$OTOOL64"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL64" >&5 +$as_echo "$OTOOL64" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_OTOOL64"; then + ac_ct_OTOOL64=$OTOOL64 + # Extract the first word of "otool64", so it can be a program name with args. +set dummy otool64; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_OTOOL64+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_OTOOL64"; then + ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_OTOOL64="otool64" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_OTOOL64=$ac_cv_prog_ac_ct_OTOOL64 +if test -n "$ac_ct_OTOOL64"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL64" >&5 +$as_echo "$ac_ct_OTOOL64" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_OTOOL64" = x; then + OTOOL64=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + OTOOL64=$ac_ct_OTOOL64 + fi +else + OTOOL64="$ac_cv_prog_OTOOL64" +fi + + + + + + + + + + + + + + + + + + + + + + + + + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -single_module linker flag" >&5 +$as_echo_n "checking for -single_module linker flag... " >&6; } +if ${lt_cv_apple_cc_single_mod+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_apple_cc_single_mod=no + if test -z "${LT_MULTI_MODULE}"; then + # By default we will add the -single_module flag. You can override + # by either setting the environment variable LT_MULTI_MODULE + # non-empty at configure time, or by adding -multi_module to the + # link flags. + rm -rf libconftest.dylib* + echo "int foo(void){return 1;}" > conftest.c + echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ +-dynamiclib -Wl,-single_module conftest.c" >&5 + $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ + -dynamiclib -Wl,-single_module conftest.c 2>conftest.err + _lt_result=$? + # If there is a non-empty error log, and "single_module" + # appears in it, assume the flag caused a linker warning + if test -s conftest.err && $GREP single_module conftest.err; then + cat conftest.err >&5 + # Otherwise, if the output was created with a 0 exit code from + # the compiler, it worked. + elif test -f libconftest.dylib && test $_lt_result -eq 0; then + lt_cv_apple_cc_single_mod=yes + else + cat conftest.err >&5 + fi + rm -rf libconftest.dylib* + rm -f conftest.* + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mod" >&5 +$as_echo "$lt_cv_apple_cc_single_mod" >&6; } + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -exported_symbols_list linker flag" >&5 +$as_echo_n "checking for -exported_symbols_list linker flag... " >&6; } +if ${lt_cv_ld_exported_symbols_list+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_ld_exported_symbols_list=no + save_LDFLAGS=$LDFLAGS + echo "_main" > conftest.sym + LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + lt_cv_ld_exported_symbols_list=yes +else + lt_cv_ld_exported_symbols_list=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + LDFLAGS="$save_LDFLAGS" + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbols_list" >&5 +$as_echo "$lt_cv_ld_exported_symbols_list" >&6; } + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -force_load linker flag" >&5 +$as_echo_n "checking for -force_load linker flag... " >&6; } +if ${lt_cv_ld_force_load+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_ld_force_load=no + cat > conftest.c << _LT_EOF +int forced_loaded() { return 2;} +_LT_EOF + echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&5 + $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&5 + echo "$AR cru libconftest.a conftest.o" >&5 + $AR cru libconftest.a conftest.o 2>&5 + echo "$RANLIB libconftest.a" >&5 + $RANLIB libconftest.a 2>&5 + cat > conftest.c << _LT_EOF +int main() { return 0;} +_LT_EOF + echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&5 + $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err + _lt_result=$? + if test -s conftest.err && $GREP force_load conftest.err; then + cat conftest.err >&5 + elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then + lt_cv_ld_force_load=yes + else + cat conftest.err >&5 + fi + rm -f conftest.err libconftest.a conftest conftest.c + rm -rf conftest.dSYM + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_force_load" >&5 +$as_echo "$lt_cv_ld_force_load" >&6; } + case $host_os in + rhapsody* | darwin1.[012]) + _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;; + darwin1.*) + _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; + darwin*) # darwin 5.x on + # if running on 10.5 or later, the deployment target defaults + # to the OS version, if on x86, and 10.4, the deployment + # target defaults to 10.4. Don't you love it? + case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in + 10.0,*86*-darwin8*|10.0,*-darwin[91]*) + _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; + 10.[012]*) + _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; + 10.*) + _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; + esac + ;; + esac + if test "$lt_cv_apple_cc_single_mod" = "yes"; then + _lt_dar_single_mod='$single_module' + fi + if test "$lt_cv_ld_exported_symbols_list" = "yes"; then + _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym' + else + _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}' + fi + if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then + _lt_dsymutil='~$DSYMUTIL $lib || :' + else + _lt_dsymutil= + fi + ;; + esac + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 +$as_echo_n "checking how to run the C preprocessor... " >&6; } +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= +fi +if test -z "$CPP"; then + if ${ac_cv_prog_CPP+:} false; then : + $as_echo_n "(cached) " >&6 +else + # Double quotes because CPP needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + break +fi + + done + ac_cv_prog_CPP=$CPP + +fi + CPP=$ac_cv_prog_CPP +else + ac_cv_prog_CPP=$CPP +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 +$as_echo "$CPP" >&6; } +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details" "$LINENO" 5; } +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if ${ac_cv_header_stdc+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdc=yes +else + ac_cv_header_stdc=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then : + : +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + +else + ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +$as_echo "#define STDC_HEADERS 1" >>confdefs.h + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default +" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + +for ac_header in dlfcn.h +do : + ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default +" +if test "x$ac_cv_header_dlfcn_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_DLFCN_H 1 +_ACEOF + +fi + +done + + + +func_stripname_cnf () +{ + case ${2} in + .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;; + *) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;; + esac +} # func_stripname_cnf + + + + + +# Set options + + + + enable_dlopen=no + + + enable_win32_dll=no + + + # Check whether --enable-shared was given. +if test "${enable_shared+set}" = set; then : + enableval=$enable_shared; p=${PACKAGE-default} + case $enableval in + yes) enable_shared=yes ;; + no) enable_shared=no ;; + *) + enable_shared=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_shared=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac +else + enable_shared=yes +fi + + + + + + + + + + # Check whether --enable-static was given. +if test "${enable_static+set}" = set; then : + enableval=$enable_static; p=${PACKAGE-default} + case $enableval in + yes) enable_static=yes ;; + no) enable_static=no ;; + *) + enable_static=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_static=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac +else + enable_static=yes +fi + + + + + + + + + + +# Check whether --with-pic was given. +if test "${with_pic+set}" = set; then : + withval=$with_pic; lt_p=${PACKAGE-default} + case $withval in + yes|no) pic_mode=$withval ;; + *) + pic_mode=default + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for lt_pkg in $withval; do + IFS="$lt_save_ifs" + if test "X$lt_pkg" = "X$lt_p"; then + pic_mode=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac +else + pic_mode=default +fi + + +test -z "$pic_mode" && pic_mode=default + + + + + + + + # Check whether --enable-fast-install was given. +if test "${enable_fast_install+set}" = set; then : + enableval=$enable_fast_install; p=${PACKAGE-default} + case $enableval in + yes) enable_fast_install=yes ;; + no) enable_fast_install=no ;; + *) + enable_fast_install=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_fast_install=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac +else + enable_fast_install=yes +fi + + + + + + + + + + + +# This can be used to rebuild libtool when needed +LIBTOOL_DEPS="$ltmain" + +# Always use our own libtool. +LIBTOOL='$(SHELL) $(top_builddir)/libtool' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +test -z "$LN_S" && LN_S="ln -s" + + + + + + + + + + + + + + +if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for objdir" >&5 +$as_echo_n "checking for objdir... " >&6; } +if ${lt_cv_objdir+:} false; then : + $as_echo_n "(cached) " >&6 +else + rm -f .libs 2>/dev/null +mkdir .libs 2>/dev/null +if test -d .libs; then + lt_cv_objdir=.libs +else + # MS-DOS does not allow filenames that begin with a dot. + lt_cv_objdir=_libs +fi +rmdir .libs 2>/dev/null +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_objdir" >&5 +$as_echo "$lt_cv_objdir" >&6; } +objdir=$lt_cv_objdir + + + + + +cat >>confdefs.h <<_ACEOF +#define LT_OBJDIR "$lt_cv_objdir/" +_ACEOF + + + + +case $host_os in +aix3*) + # AIX sometimes has problems with the GCC collect2 program. For some + # reason, if we set the COLLECT_NAMES environment variable, the problems + # vanish in a puff of smoke. + if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES + fi + ;; +esac + +# Global variables: +ofile=libtool +can_build_shared=yes + +# All known linkers require a `.a' archive for static linking (except MSVC, +# which needs '.lib'). +libext=a + +with_gnu_ld="$lt_cv_prog_gnu_ld" + +old_CC="$CC" +old_CFLAGS="$CFLAGS" + +# Set sane defaults for various variables +test -z "$CC" && CC=cc +test -z "$LTCC" && LTCC=$CC +test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS +test -z "$LD" && LD=ld +test -z "$ac_objext" && ac_objext=o + +for cc_temp in $compiler""; do + case $cc_temp in + compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; + distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; + \-*) ;; + *) break;; + esac +done +cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` + + +# Only perform the check for file, if the check method requires it +test -z "$MAGIC_CMD" && MAGIC_CMD=file +case $deplibs_check_method in +file_magic*) + if test "$file_magic_cmd" = '$MAGIC_CMD'; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${ac_tool_prefix}file" >&5 +$as_echo_n "checking for ${ac_tool_prefix}file... " >&6; } +if ${lt_cv_path_MAGIC_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $MAGIC_CMD in +[\\/*] | ?:[\\/]*) + lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. + ;; +*) + lt_save_MAGIC_CMD="$MAGIC_CMD" + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" + for ac_dir in $ac_dummy; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f $ac_dir/${ac_tool_prefix}file; then + lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file" + if test -n "$file_magic_test_file"; then + case $deplibs_check_method in + "file_magic "*) + file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` + MAGIC_CMD="$lt_cv_path_MAGIC_CMD" + if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | + $EGREP "$file_magic_regex" > /dev/null; then + : + else + cat <<_LT_EOF 1>&2 + +*** Warning: the command libtool uses to detect shared libraries, +*** $file_magic_cmd, produces output that libtool cannot recognize. +*** The result is that libtool may fail to recognize shared libraries +*** as such. This will affect the creation of libtool libraries that +*** depend on shared libraries, but programs linked with such libtool +*** libraries will work regardless of this problem. Nevertheless, you +*** may want to report the problem to your system manager and/or to +*** bug-libtool@gnu.org + +_LT_EOF + fi ;; + esac + fi + break + fi + done + IFS="$lt_save_ifs" + MAGIC_CMD="$lt_save_MAGIC_CMD" + ;; +esac +fi + +MAGIC_CMD="$lt_cv_path_MAGIC_CMD" +if test -n "$MAGIC_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 +$as_echo "$MAGIC_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + + + +if test -z "$lt_cv_path_MAGIC_CMD"; then + if test -n "$ac_tool_prefix"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for file" >&5 +$as_echo_n "checking for file... " >&6; } +if ${lt_cv_path_MAGIC_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $MAGIC_CMD in +[\\/*] | ?:[\\/]*) + lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. + ;; +*) + lt_save_MAGIC_CMD="$MAGIC_CMD" + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" + for ac_dir in $ac_dummy; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f $ac_dir/file; then + lt_cv_path_MAGIC_CMD="$ac_dir/file" + if test -n "$file_magic_test_file"; then + case $deplibs_check_method in + "file_magic "*) + file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` + MAGIC_CMD="$lt_cv_path_MAGIC_CMD" + if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | + $EGREP "$file_magic_regex" > /dev/null; then + : + else + cat <<_LT_EOF 1>&2 + +*** Warning: the command libtool uses to detect shared libraries, +*** $file_magic_cmd, produces output that libtool cannot recognize. +*** The result is that libtool may fail to recognize shared libraries +*** as such. This will affect the creation of libtool libraries that +*** depend on shared libraries, but programs linked with such libtool +*** libraries will work regardless of this problem. Nevertheless, you +*** may want to report the problem to your system manager and/or to +*** bug-libtool@gnu.org + +_LT_EOF + fi ;; + esac + fi + break + fi + done + IFS="$lt_save_ifs" + MAGIC_CMD="$lt_save_MAGIC_CMD" + ;; +esac +fi + +MAGIC_CMD="$lt_cv_path_MAGIC_CMD" +if test -n "$MAGIC_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 +$as_echo "$MAGIC_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + else + MAGIC_CMD=: + fi +fi + + fi + ;; +esac + +# Use C for the default configuration in the libtool script + +lt_save_CC="$CC" +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +# Source file extension for C test sources. +ac_ext=c + +# Object file extension for compiled C test sources. +objext=o +objext=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="int some_variable = 0;" + +# Code to be used in simple link tests +lt_simple_link_test_code='int main(){return(0);}' + + + + + + + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC + +# Save the default compiler, since it gets overwritten when the other +# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. +compiler_DEFAULT=$CC + +# save warnings/boilerplate of simple test code +ac_outfile=conftest.$ac_objext +echo "$lt_simple_compile_test_code" >conftest.$ac_ext +eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_compiler_boilerplate=`cat conftest.err` +$RM conftest* + +ac_outfile=conftest.$ac_objext +echo "$lt_simple_link_test_code" >conftest.$ac_ext +eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_linker_boilerplate=`cat conftest.err` +$RM -r conftest* + + +## CAVEAT EMPTOR: +## There is no encapsulation within the following macros, do not change +## the running order or otherwise move them around unless you know exactly +## what you are doing... +if test -n "$compiler"; then + +lt_prog_compiler_no_builtin_flag= + +if test "$GCC" = yes; then + case $cc_basename in + nvcc*) + lt_prog_compiler_no_builtin_flag=' -Xcompiler -fno-builtin' ;; + *) + lt_prog_compiler_no_builtin_flag=' -fno-builtin' ;; + esac + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 +$as_echo_n "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; } +if ${lt_cv_prog_compiler_rtti_exceptions+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_rtti_exceptions=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="-fno-rtti -fno-exceptions" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_rtti_exceptions=yes + fi + fi + $RM conftest* + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 +$as_echo "$lt_cv_prog_compiler_rtti_exceptions" >&6; } + +if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then + lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions" +else + : +fi + +fi + + + + + + + lt_prog_compiler_wl= +lt_prog_compiler_pic= +lt_prog_compiler_static= + + + if test "$GCC" = yes; then + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_static='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static='-Bstatic' + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + lt_prog_compiler_pic='-fPIC' + ;; + m68k) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4' + ;; + esac + ;; + + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + + mingw* | cygwin* | pw32* | os2* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + lt_prog_compiler_pic='-DDLL_EXPORT' + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic='-fno-common' + ;; + + haiku*) + # PIC is the default for Haiku. + # The "-static" flag exists, but is broken. + lt_prog_compiler_static= + ;; + + hpux*) + # PIC is the default for 64-bit PA HP-UX, but not for 32-bit + # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag + # sets the default TLS model and affects inlining. + case $host_cpu in + hppa*64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic='-fPIC' + ;; + esac + ;; + + interix[3-9]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + + msdosdjgpp*) + # Just because we use GCC doesn't mean we suddenly get shared libraries + # on systems that don't support them. + lt_prog_compiler_can_build_shared=no + enable_shared=no + ;; + + *nto* | *qnx*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + lt_prog_compiler_pic='-fPIC -shared' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic=-Kconform_pic + fi + ;; + + *) + lt_prog_compiler_pic='-fPIC' + ;; + esac + + case $cc_basename in + nvcc*) # Cuda Compiler Driver 2.2 + lt_prog_compiler_wl='-Xlinker ' + if test -n "$lt_prog_compiler_pic"; then + lt_prog_compiler_pic="-Xcompiler $lt_prog_compiler_pic" + fi + ;; + esac + else + # PORTME Check for flag to pass linker flags through the system compiler. + case $host_os in + aix*) + lt_prog_compiler_wl='-Wl,' + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static='-Bstatic' + else + lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp' + fi + ;; + + mingw* | cygwin* | pw32* | os2* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic='-DDLL_EXPORT' + ;; + + hpux9* | hpux10* | hpux11*) + lt_prog_compiler_wl='-Wl,' + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic='+Z' + ;; + esac + # Is there a better lt_prog_compiler_static that works with the bundled CC? + lt_prog_compiler_static='${wl}-a ${wl}archive' + ;; + + irix5* | irix6* | nonstopux*) + lt_prog_compiler_wl='-Wl,' + # PIC (with -KPIC) is the default. + lt_prog_compiler_static='-non_shared' + ;; + + linux* | k*bsd*-gnu | kopensolaris*-gnu) + case $cc_basename in + # old Intel for x86_64 which still supported -KPIC. + ecc*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-static' + ;; + # icc used to be incompatible with GCC. + # ICC 10 doesn't accept -KPIC any more. + icc* | ifort*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; + # Lahey Fortran 8.1. + lf95*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='--shared' + lt_prog_compiler_static='--static' + ;; + nagfor*) + # NAG Fortran compiler + lt_prog_compiler_wl='-Wl,-Wl,,' + lt_prog_compiler_pic='-PIC' + lt_prog_compiler_static='-Bstatic' + ;; + pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) + # Portland Group compilers (*not* the Pentium gcc compiler, + # which looks to be a dead project) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fpic' + lt_prog_compiler_static='-Bstatic' + ;; + ccc*) + lt_prog_compiler_wl='-Wl,' + # All Alpha code is PIC. + lt_prog_compiler_static='-non_shared' + ;; + xl* | bgxl* | bgf* | mpixl*) + # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-qpic' + lt_prog_compiler_static='-qstaticlink' + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [1-7].* | *Sun*Fortran*\ 8.[0-3]*) + # Sun Fortran 8.3 passes all unrecognized flags to the linker + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + lt_prog_compiler_wl='' + ;; + *Sun\ F* | *Sun*Fortran*) + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + lt_prog_compiler_wl='-Qoption ld ' + ;; + *Sun\ C*) + # Sun C 5.9 + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + lt_prog_compiler_wl='-Wl,' + ;; + *Intel*\ [CF]*Compiler*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; + *Portland\ Group*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fpic' + lt_prog_compiler_static='-Bstatic' + ;; + esac + ;; + esac + ;; + + newsos6) + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + *nto* | *qnx*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + lt_prog_compiler_pic='-fPIC -shared' + ;; + + osf3* | osf4* | osf5*) + lt_prog_compiler_wl='-Wl,' + # All OSF/1 code is PIC. + lt_prog_compiler_static='-non_shared' + ;; + + rdos*) + lt_prog_compiler_static='-non_shared' + ;; + + solaris*) + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + case $cc_basename in + f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) + lt_prog_compiler_wl='-Qoption ld ';; + *) + lt_prog_compiler_wl='-Wl,';; + esac + ;; + + sunos4*) + lt_prog_compiler_wl='-Qoption ld ' + lt_prog_compiler_pic='-PIC' + lt_prog_compiler_static='-Bstatic' + ;; + + sysv4 | sysv4.2uw2* | sysv4.3*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + sysv4*MP*) + if test -d /usr/nec ;then + lt_prog_compiler_pic='-Kconform_pic' + lt_prog_compiler_static='-Bstatic' + fi + ;; + + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + unicos*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_can_build_shared=no + ;; + + uts4*) + lt_prog_compiler_pic='-pic' + lt_prog_compiler_static='-Bstatic' + ;; + + *) + lt_prog_compiler_can_build_shared=no + ;; + esac + fi + +case $host_os in + # For platforms which do not support PIC, -DPIC is meaningless: + *djgpp*) + lt_prog_compiler_pic= + ;; + *) + lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC" + ;; +esac + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 +$as_echo_n "checking for $compiler option to produce PIC... " >&6; } +if ${lt_cv_prog_compiler_pic+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_pic=$lt_prog_compiler_pic +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic" >&5 +$as_echo "$lt_cv_prog_compiler_pic" >&6; } +lt_prog_compiler_pic=$lt_cv_prog_compiler_pic + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$lt_prog_compiler_pic"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5 +$as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; } +if ${lt_cv_prog_compiler_pic_works+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_pic_works=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$lt_prog_compiler_pic -DPIC" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_pic_works=yes + fi + fi + $RM conftest* + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5 +$as_echo "$lt_cv_prog_compiler_pic_works" >&6; } + +if test x"$lt_cv_prog_compiler_pic_works" = xyes; then + case $lt_prog_compiler_pic in + "" | " "*) ;; + *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;; + esac +else + lt_prog_compiler_pic= + lt_prog_compiler_can_build_shared=no +fi + +fi + + + + + + + + + + + +# +# Check to make sure the static flag actually works. +# +wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\" +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 +$as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } +if ${lt_cv_prog_compiler_static_works+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_static_works=no + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS $lt_tmp_static_flag" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&5 + $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_static_works=yes + fi + else + lt_cv_prog_compiler_static_works=yes + fi + fi + $RM -r conftest* + LDFLAGS="$save_LDFLAGS" + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5 +$as_echo "$lt_cv_prog_compiler_static_works" >&6; } + +if test x"$lt_cv_prog_compiler_static_works" = xyes; then + : +else + lt_prog_compiler_static= +fi + + + + + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 +$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } +if ${lt_cv_prog_compiler_c_o+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_c_o=no + $RM -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + lt_cv_prog_compiler_c_o=yes + fi + fi + chmod u+w . 2>&5 + $RM conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files + $RM out/* && rmdir out + cd .. + $RM -r conftest + $RM conftest* + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 +$as_echo "$lt_cv_prog_compiler_c_o" >&6; } + + + + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 +$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } +if ${lt_cv_prog_compiler_c_o+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_c_o=no + $RM -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + lt_cv_prog_compiler_c_o=yes + fi + fi + chmod u+w . 2>&5 + $RM conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files + $RM out/* && rmdir out + cd .. + $RM -r conftest + $RM conftest* + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 +$as_echo "$lt_cv_prog_compiler_c_o" >&6; } + + + + +hard_links="nottested" +if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then + # do not overwrite the value of need_locks provided by the user + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5 +$as_echo_n "checking if we can lock with hard links... " >&6; } + hard_links=yes + $RM conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5 +$as_echo "$hard_links" >&6; } + if test "$hard_links" = no; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 +$as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} + need_locks=warn + fi +else + need_locks=no +fi + + + + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +$as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } + + runpath_var= + allow_undefined_flag= + always_export_symbols=no + archive_cmds= + archive_expsym_cmds= + compiler_needs_object=no + enable_shared_with_static_runtimes=no + export_dynamic_flag_spec= + export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + hardcode_automatic=no + hardcode_direct=no + hardcode_direct_absolute=no + hardcode_libdir_flag_spec= + hardcode_libdir_separator= + hardcode_minus_L=no + hardcode_shlibpath_var=unsupported + inherit_rpath=no + link_all_deplibs=unknown + module_cmds= + module_expsym_cmds= + old_archive_from_new_cmds= + old_archive_from_expsyms_cmds= + thread_safe_flag_spec= + whole_archive_flag_spec= + # include_expsyms should be a list of space-separated symbols to be *always* + # included in the symbol list + include_expsyms= + # exclude_expsyms can be an extended regexp of symbols to exclude + # it will be wrapped by ` (' and `)$', so one must not match beginning or + # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', + # as well as any symbol that contains `d'. + exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' + # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out + # platforms (ab)use it in PIC code, but their linkers get confused if + # the symbol is explicitly referenced. Since portable code cannot + # rely on this symbol name, it's probably fine to never include it in + # preloaded symbol tables. + # Exclude shared library initialization/finalization symbols. + extract_expsyms_cmds= + + case $host_os in + cygwin* | mingw* | pw32* | cegcc*) + # FIXME: the MSVC++ port hasn't been tested in a loooong time + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + if test "$GCC" != yes; then + with_gnu_ld=no + fi + ;; + interix*) + # we just hope/assume this is gcc and not c89 (= MSVC++) + with_gnu_ld=yes + ;; + openbsd*) + with_gnu_ld=no + ;; + linux* | k*bsd*-gnu | gnu*) + link_all_deplibs=no + ;; + esac + + ld_shlibs=yes + + # On some targets, GNU ld is compatible enough with the native linker + # that we're better off using the native interface for both. + lt_use_gnu_ld_interface=no + if test "$with_gnu_ld" = yes; then + case $host_os in + aix*) + # The AIX port of GNU ld has always aspired to compatibility + # with the native linker. However, as the warning in the GNU ld + # block says, versions before 2.19.5* couldn't really create working + # shared libraries, regardless of the interface used. + case `$LD -v 2>&1` in + *\ \(GNU\ Binutils\)\ 2.19.5*) ;; + *\ \(GNU\ Binutils\)\ 2.[2-9]*) ;; + *\ \(GNU\ Binutils\)\ [3-9]*) ;; + *) + lt_use_gnu_ld_interface=yes + ;; + esac + ;; + *) + lt_use_gnu_ld_interface=yes + ;; + esac + fi + + if test "$lt_use_gnu_ld_interface" = yes; then + # If archive_cmds runs LD, not CC, wlarc should be empty + wlarc='${wl}' + + # Set some defaults for GNU ld with shared library support. These + # are reset later if shared libraries are not supported. Putting them + # here allows them to be overridden if necessary. + runpath_var=LD_RUN_PATH + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + export_dynamic_flag_spec='${wl}--export-dynamic' + # ancient GNU ld didn't support --whole-archive et. al. + if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then + whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + whole_archive_flag_spec= + fi + supports_anon_versioning=no + case `$LD -v 2>&1` in + *GNU\ gold*) supports_anon_versioning=yes ;; + *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 + *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... + *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... + *\ 2.11.*) ;; # other 2.11 versions + *) supports_anon_versioning=yes ;; + esac + + # See if GNU ld supports shared libraries. + case $host_os in + aix[3-9]*) + # On AIX/PPC, the GNU linker is very broken + if test "$host_cpu" != ia64; then + ld_shlibs=no + cat <<_LT_EOF 1>&2 + +*** Warning: the GNU linker, at least up to release 2.19, is reported +*** to be unable to reliably create shared libraries on AIX. +*** Therefore, libtool is disabling shared libraries support. If you +*** really care for shared libraries, you may want to install binutils +*** 2.20 or above, or modify your PATH so that a non-GNU linker is found. +*** You will then need to restart the configuration process. + +_LT_EOF + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='' + ;; + m68k) + archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + ;; + esac + ;; + + beos*) + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + allow_undefined_flag=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + ld_shlibs=no + fi + ;; + + cygwin* | mingw* | pw32* | cegcc*) + # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless, + # as there is no search path for DLLs. + hardcode_libdir_flag_spec='-L$libdir' + export_dynamic_flag_spec='${wl}--export-all-symbols' + allow_undefined_flag=unsupported + always_export_symbols=no + enable_shared_with_static_runtimes=yes + export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols' + exclude_expsyms='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname' + + if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + else + ld_shlibs=no + fi + ;; + + haiku*) + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + link_all_deplibs=yes + ;; + + interix[3-9]*) + hardcode_direct=no + hardcode_shlibpath_var=no + hardcode_libdir_flag_spec='${wl}-rpath,$libdir' + export_dynamic_flag_spec='${wl}-E' + # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. + # Instead, shared libraries are loaded at an image base (0x10000000 by + # default) and relocated if they conflict, which is a slow very memory + # consuming and fragmenting process. To avoid this, we pick a random, + # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link + # time. Moving up from 0x10000000 also allows more sbrk(2) space. + archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + archive_expsym_cmds='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + ;; + + gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) + tmp_diet=no + if test "$host_os" = linux-dietlibc; then + case $cc_basename in + diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) + esac + fi + if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ + && test "$tmp_diet" = no + then + tmp_addflag=' $pic_flag' + tmp_sharedflag='-shared' + case $cc_basename,$host_cpu in + pgcc*) # Portland Group C compiler + whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_addflag=' $pic_flag' + ;; + pgf77* | pgf90* | pgf95* | pgfortran*) + # Portland Group f77 and f90 compilers + whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_addflag=' $pic_flag -Mnomain' ;; + ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 + tmp_addflag=' -i_dynamic' ;; + efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 + tmp_addflag=' -i_dynamic -nofor_main' ;; + ifc* | ifort*) # Intel Fortran compiler + tmp_addflag=' -nofor_main' ;; + lf95*) # Lahey Fortran 8.1 + whole_archive_flag_spec= + tmp_sharedflag='--shared' ;; + xl[cC]* | bgxl[cC]* | mpixl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf below) + tmp_sharedflag='-qmkshrobj' + tmp_addflag= ;; + nvcc*) # Cuda Compiler Driver 2.2 + whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' + compiler_needs_object=yes + ;; + esac + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) # Sun C 5.9 + whole_archive_flag_spec='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' + compiler_needs_object=yes + tmp_sharedflag='-G' ;; + *Sun\ F*) # Sun Fortran 8.3 + tmp_sharedflag='-G' ;; + esac + archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + + if test "x$supports_anon_versioning" = xyes; then + archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' + fi + + case $cc_basename in + xlf* | bgf* | bgxlf* | mpixlf*) + # IBM XL Fortran 10.1 on PPC cannot create shared libs itself + whole_archive_flag_spec='--whole-archive$convenience --no-whole-archive' + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' + if test "x$supports_anon_versioning" = xyes; then + archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + echo "local: *; };" >> $output_objdir/$libname.ver~ + $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' + fi + ;; + esac + else + ld_shlibs=no + fi + ;; + + netbsd* | netbsdelf*-gnu) + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' + wlarc= + else + archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + fi + ;; + + solaris*) + if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then + ld_shlibs=no + cat <<_LT_EOF 1>&2 + +*** Warning: The releases 2.8.* of the GNU linker cannot reliably +*** create shared libraries on Solaris systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.9.1 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +_LT_EOF + elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs=no + fi + ;; + + sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) + case `$LD -v 2>&1` in + *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) + ld_shlibs=no + cat <<_LT_EOF 1>&2 + +*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not +*** reliably create shared libraries on SCO systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.16.91.0.3 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +_LT_EOF + ;; + *) + # For security reasons, it is highly recommended that you always + # use absolute paths for naming shared libraries, and exclude the + # DT_RUNPATH tag from executables and libraries. But doing so + # requires that you compile everything twice, which is a pain. + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs=no + fi + ;; + esac + ;; + + sunos4*) + archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' + wlarc= + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + *) + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs=no + fi + ;; + esac + + if test "$ld_shlibs" = no; then + runpath_var= + hardcode_libdir_flag_spec= + export_dynamic_flag_spec= + whole_archive_flag_spec= + fi + else + # PORTME fill in a description of your system's linker (not GNU ld) + case $host_os in + aix3*) + allow_undefined_flag=unsupported + always_export_symbols=yes + archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' + # Note: this linker hardcodes the directories in LIBPATH if there + # are no directories specified by -L. + hardcode_minus_L=yes + if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then + # Neither direct hardcoding nor static linking is supported with a + # broken collect2. + hardcode_direct=unsupported + fi + ;; + + aix[4-9]*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + # Also, AIX nm treats weak defined symbols like other global + # defined symbols, whereas GNU nm marks them as "W". + if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then + export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' + else + export_symbols_cmds='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' + fi + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) + for ld_flag in $LDFLAGS; do + if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then + aix_use_runtimelinking=yes + break + fi + done + ;; + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + archive_cmds='' + hardcode_direct=yes + hardcode_direct_absolute=yes + hardcode_libdir_separator=':' + link_all_deplibs=yes + file_list_spec='${wl}-f,' + + if test "$GCC" = yes; then + case $host_os in aix4.[012]|aix4.[012].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && + strings "$collect2name" | $GREP resolve_lib_name >/dev/null + then + # We have reworked collect2 + : + else + # We have old collect2 + hardcode_direct=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + hardcode_minus_L=yes + hardcode_libdir_flag_spec='-L$libdir' + hardcode_libdir_separator= + fi + ;; + esac + shared_flag='-shared' + if test "$aix_use_runtimelinking" = yes; then + shared_flag="$shared_flag "'${wl}-G' + fi + link_all_deplibs=no + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + export_dynamic_flag_spec='${wl}-bexpall' + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + always_export_symbols=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + allow_undefined_flag='-berok' + # Determine the default libpath from the value encoded in an + # empty executable. + if test "${lt_cv_aix_libpath+set}" = set; then + aix_libpath=$lt_cv_aix_libpath +else + if ${lt_cv_aix_libpath_+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + + lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\([^ ]*\) *$/\1/ + p + } + }' + lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` + # Check for a 64-bit object if we didn't find anything. + if test -z "$lt_cv_aix_libpath_"; then + lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` + fi +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + if test -z "$lt_cv_aix_libpath_"; then + lt_cv_aix_libpath_="/usr/lib:/lib" + fi + +fi + + aix_libpath=$lt_cv_aix_libpath_ +fi + + hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" + archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib' + allow_undefined_flag="-z nodefs" + archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an + # empty executable. + if test "${lt_cv_aix_libpath+set}" = set; then + aix_libpath=$lt_cv_aix_libpath +else + if ${lt_cv_aix_libpath_+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + + lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\([^ ]*\) *$/\1/ + p + } + }' + lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` + # Check for a 64-bit object if we didn't find anything. + if test -z "$lt_cv_aix_libpath_"; then + lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` + fi +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + if test -z "$lt_cv_aix_libpath_"; then + lt_cv_aix_libpath_="/usr/lib:/lib" + fi + +fi + + aix_libpath=$lt_cv_aix_libpath_ +fi + + hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + no_undefined_flag=' ${wl}-bernotok' + allow_undefined_flag=' ${wl}-berok' + if test "$with_gnu_ld" = yes; then + # We only use this code for GNU lds that support --whole-archive. + whole_archive_flag_spec='${wl}--whole-archive$convenience ${wl}--no-whole-archive' + else + # Exported symbols can be pulled into shared objects from archives + whole_archive_flag_spec='$convenience' + fi + archive_cmds_need_lc=yes + # This is similar to how AIX traditionally builds its shared libraries. + archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='' + ;; + m68k) + archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + ;; + esac + ;; + + bsdi[45]*) + export_dynamic_flag_spec=-rdynamic + ;; + + cygwin* | mingw* | pw32* | cegcc*) + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + case $cc_basename in + cl*) + # Native MSVC + hardcode_libdir_flag_spec=' ' + allow_undefined_flag=unsupported + always_export_symbols=yes + file_list_spec='@' + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=".dll" + # FIXME: Setting linknames here is a bad hack. + archive_cmds='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' + archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; + else + sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; + fi~ + $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ + linknames=' + # The linker will not automatically build a static lib if we build a DLL. + # _LT_TAGVAR(old_archive_from_new_cmds, )='true' + enable_shared_with_static_runtimes=yes + exclude_expsyms='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' + export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1,DATA/'\'' | $SED -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' + # Don't use ranlib + old_postinstall_cmds='chmod 644 $oldlib' + postlink_cmds='lt_outputfile="@OUTPUT@"~ + lt_tool_outputfile="@TOOL_OUTPUT@"~ + case $lt_outputfile in + *.exe|*.EXE) ;; + *) + lt_outputfile="$lt_outputfile.exe" + lt_tool_outputfile="$lt_tool_outputfile.exe" + ;; + esac~ + if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then + $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; + $RM "$lt_outputfile.manifest"; + fi' + ;; + *) + # Assume MSVC wrapper + hardcode_libdir_flag_spec=' ' + allow_undefined_flag=unsupported + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=".dll" + # FIXME: Setting linknames here is a bad hack. + archive_cmds='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' + # The linker will automatically build a .lib file if we build a DLL. + old_archive_from_new_cmds='true' + # FIXME: Should let the user specify the lib program. + old_archive_cmds='lib -OUT:$oldlib$oldobjs$old_deplibs' + enable_shared_with_static_runtimes=yes + ;; + esac + ;; + + darwin* | rhapsody*) + + + archive_cmds_need_lc=no + hardcode_direct=no + hardcode_automatic=yes + hardcode_shlibpath_var=unsupported + if test "$lt_cv_ld_force_load" = "yes"; then + whole_archive_flag_spec='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' + + else + whole_archive_flag_spec='' + fi + link_all_deplibs=yes + allow_undefined_flag="$_lt_dar_allow_undefined" + case $cc_basename in + ifort*) _lt_dar_can_shared=yes ;; + *) _lt_dar_can_shared=$GCC ;; + esac + if test "$_lt_dar_can_shared" = "yes"; then + output_verbose_link_cmd=func_echo_all + archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" + module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" + archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" + module_expsym_cmds="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" + + else + ld_shlibs=no + fi + + ;; + + dgux*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_shlibpath_var=no + ;; + + # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor + # support. Future versions do this automatically, but an explicit c++rt0.o + # does not break anything, and helps significantly (at the cost of a little + # extra space). + freebsd2.2*) + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + # Unfortunately, older versions of FreeBSD 2 do not have this feature. + freebsd2.*) + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes + hardcode_minus_L=yes + hardcode_shlibpath_var=no + ;; + + # FreeBSD 3 and greater uses gcc -shared to do shared libraries. + freebsd* | dragonfly*) + archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + hpux9*) + if test "$GCC" = yes; then + archive_cmds='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + fi + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_separator=: + hardcode_direct=yes + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + export_dynamic_flag_spec='${wl}-E' + ;; + + hpux10*) + if test "$GCC" = yes && test "$with_gnu_ld" = no; then + archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' + fi + if test "$with_gnu_ld" = no; then + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_separator=: + hardcode_direct=yes + hardcode_direct_absolute=yes + export_dynamic_flag_spec='${wl}-E' + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + fi + ;; + + hpux11*) + if test "$GCC" = yes && test "$with_gnu_ld" = no; then + case $host_cpu in + hppa*64*) + archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + else + case $host_cpu in + hppa*64*) + archive_cmds='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + + # Older versions of the 11.00 compiler do not understand -b yet + # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $CC understands -b" >&5 +$as_echo_n "checking if $CC understands -b... " >&6; } +if ${lt_cv_prog_compiler__b+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler__b=no + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS -b" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&5 + $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler__b=yes + fi + else + lt_cv_prog_compiler__b=yes + fi + fi + $RM -r conftest* + LDFLAGS="$save_LDFLAGS" + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler__b" >&5 +$as_echo "$lt_cv_prog_compiler__b" >&6; } + +if test x"$lt_cv_prog_compiler__b" = xyes; then + archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' +else + archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' +fi + + ;; + esac + fi + if test "$with_gnu_ld" = no; then + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_separator=: + + case $host_cpu in + hppa*64*|ia64*) + hardcode_direct=no + hardcode_shlibpath_var=no + ;; + *) + hardcode_direct=yes + hardcode_direct_absolute=yes + export_dynamic_flag_spec='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + ;; + esac + fi + ;; + + irix5* | irix6* | nonstopux*) + if test "$GCC" = yes; then + archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + # Try to use the -exported_symbol ld option, if it does not + # work, assume that -exports_file does not work either and + # implicitly export all symbols. + # This should be the same for all languages, so no per-tag cache variable. + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $host_os linker accepts -exported_symbol" >&5 +$as_echo_n "checking whether the $host_os linker accepts -exported_symbol... " >&6; } +if ${lt_cv_irix_exported_symbol+:} false; then : + $as_echo_n "(cached) " >&6 +else + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int foo (void) { return 0; } +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + lt_cv_irix_exported_symbol=yes +else + lt_cv_irix_exported_symbol=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + LDFLAGS="$save_LDFLAGS" +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_irix_exported_symbol" >&5 +$as_echo "$lt_cv_irix_exported_symbol" >&6; } + if test "$lt_cv_irix_exported_symbol" = yes; then + archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib' + fi + else + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib' + fi + archive_cmds_need_lc='no' + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + inherit_rpath=yes + link_all_deplibs=yes + ;; + + netbsd* | netbsdelf*-gnu) + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out + else + archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF + fi + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + newsos6) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + hardcode_shlibpath_var=no + ;; + + *nto* | *qnx*) + ;; + + openbsd*) + if test -f /usr/libexec/ld.so; then + hardcode_direct=yes + hardcode_shlibpath_var=no + hardcode_direct_absolute=yes + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' + hardcode_libdir_flag_spec='${wl}-rpath,$libdir' + export_dynamic_flag_spec='${wl}-E' + else + case $host_os in + openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec='-R$libdir' + ;; + *) + archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec='${wl}-rpath,$libdir' + ;; + esac + fi + else + ld_shlibs=no + fi + ;; + + os2*) + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + allow_undefined_flag=unsupported + archive_cmds='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' + old_archive_from_new_cmds='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' + ;; + + osf3*) + if test "$GCC" = yes; then + allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + allow_undefined_flag=' -expect_unresolved \*' + archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' + fi + archive_cmds_need_lc='no' + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + ;; + + osf4* | osf5*) # as osf3* with the addition of -msym flag + if test "$GCC" = yes; then + allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + else + allow_undefined_flag=' -expect_unresolved \*' + archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' + archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ + $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp' + + # Both c and cxx compiler support -rpath directly + hardcode_libdir_flag_spec='-rpath $libdir' + fi + archive_cmds_need_lc='no' + hardcode_libdir_separator=: + ;; + + solaris*) + no_undefined_flag=' -z defs' + if test "$GCC" = yes; then + wlarc='${wl}' + archive_cmds='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' + else + case `$CC -V 2>&1` in + *"Compilers 5.0"*) + wlarc='' + archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' + ;; + *) + wlarc='${wl}' + archive_cmds='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' + ;; + esac + fi + hardcode_libdir_flag_spec='-R$libdir' + hardcode_shlibpath_var=no + case $host_os in + solaris2.[0-5] | solaris2.[0-5].*) ;; + *) + # The compiler driver will combine and reorder linker options, + # but understands `-z linker_flag'. GCC discards it without `$wl', + # but is careful enough not to reorder. + # Supported since Solaris 2.6 (maybe 2.5.1?) + if test "$GCC" = yes; then + whole_archive_flag_spec='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' + else + whole_archive_flag_spec='-z allextract$convenience -z defaultextract' + fi + ;; + esac + link_all_deplibs=yes + ;; + + sunos4*) + if test "x$host_vendor" = xsequent; then + # Use $CC to link under sequent, because it throws in some extra .o + # files that make .init and .fini sections work. + archive_cmds='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' + fi + hardcode_libdir_flag_spec='-L$libdir' + hardcode_direct=yes + hardcode_minus_L=yes + hardcode_shlibpath_var=no + ;; + + sysv4) + case $host_vendor in + sni) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes # is this really true??? + ;; + siemens) + ## LD is ld it makes a PLAMLIB + ## CC just makes a GrossModule. + archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags' + reload_cmds='$CC -r -o $output$reload_objs' + hardcode_direct=no + ;; + motorola) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=no #Motorola manual says yes, but my tests say they lie + ;; + esac + runpath_var='LD_RUN_PATH' + hardcode_shlibpath_var=no + ;; + + sysv4.3*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var=no + export_dynamic_flag_spec='-Bexport' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var=no + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + ld_shlibs=yes + fi + ;; + + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) + no_undefined_flag='${wl}-z,text' + archive_cmds_need_lc=no + hardcode_shlibpath_var=no + runpath_var='LD_RUN_PATH' + + if test "$GCC" = yes; then + archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + sysv5* | sco3.2v5* | sco5v6*) + # Note: We can NOT use -z defs as we might desire, because we do not + # link with -lc, and that would cause any symbols used from libc to + # always be unresolved, which means just about no library would + # ever link correctly. If we're not using GNU ld we use -z text + # though, which does catch some bad symbols but isn't as heavy-handed + # as -z defs. + no_undefined_flag='${wl}-z,text' + allow_undefined_flag='${wl}-z,nodefs' + archive_cmds_need_lc=no + hardcode_shlibpath_var=no + hardcode_libdir_flag_spec='${wl}-R,$libdir' + hardcode_libdir_separator=':' + link_all_deplibs=yes + export_dynamic_flag_spec='${wl}-Bexport' + runpath_var='LD_RUN_PATH' + + if test "$GCC" = yes; then + archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + uts4*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_shlibpath_var=no + ;; + + *) + ld_shlibs=no + ;; + esac + + if test x$host_vendor = xsni; then + case $host in + sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + export_dynamic_flag_spec='${wl}-Blargedynsym' + ;; + esac + fi + fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs" >&5 +$as_echo "$ld_shlibs" >&6; } +test "$ld_shlibs" = no && can_build_shared=no + +with_gnu_ld=$with_gnu_ld + + + + + + + + + + + + + + + +# +# Do we need to explicitly link libc? +# +case "x$archive_cmds_need_lc" in +x|xyes) + # Assume -lc should be added + archive_cmds_need_lc=yes + + if test "$enable_shared" = yes && test "$GCC" = yes; then + case $archive_cmds in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5 +$as_echo_n "checking whether -lc should be explicitly linked in... " >&6; } +if ${lt_cv_archive_cmds_need_lc+:} false; then : + $as_echo_n "(cached) " >&6 +else + $RM conftest* + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$lt_prog_compiler_wl + pic_flag=$lt_prog_compiler_pic + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$allow_undefined_flag + allow_undefined_flag= + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5 + (eval $archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + then + lt_cv_archive_cmds_need_lc=no + else + lt_cv_archive_cmds_need_lc=yes + fi + allow_undefined_flag=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $RM conftest* + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc" >&5 +$as_echo "$lt_cv_archive_cmds_need_lc" >&6; } + archive_cmds_need_lc=$lt_cv_archive_cmds_need_lc + ;; + esac + fi + ;; +esac + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5 +$as_echo_n "checking dynamic linker characteristics... " >&6; } + +if test "$GCC" = yes; then + case $host_os in + darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; + *) lt_awk_arg="/^libraries:/" ;; + esac + case $host_os in + mingw* | cegcc*) lt_sed_strip_eq="s,=\([A-Za-z]:\),\1,g" ;; + *) lt_sed_strip_eq="s,=/,/,g" ;; + esac + lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` + case $lt_search_path_spec in + *\;*) + # if the path contains ";" then we assume it to be the separator + # otherwise default to the standard path separator (i.e. ":") - it is + # assumed that no part of a normal pathname contains ";" but that should + # okay in the real world where ";" in dirpaths is itself problematic. + lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` + ;; + *) + lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` + ;; + esac + # Ok, now we have the path, separated by spaces, we can step through it + # and add multilib dir if necessary. + lt_tmp_lt_search_path_spec= + lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` + for lt_sys_path in $lt_search_path_spec; do + if test -d "$lt_sys_path/$lt_multi_os_dir"; then + lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" + else + test -d "$lt_sys_path" && \ + lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" + fi + done + lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' +BEGIN {RS=" "; FS="/|\n";} { + lt_foo=""; + lt_count=0; + for (lt_i = NF; lt_i > 0; lt_i--) { + if ($lt_i != "" && $lt_i != ".") { + if ($lt_i == "..") { + lt_count++; + } else { + if (lt_count == 0) { + lt_foo="/" $lt_i lt_foo; + } else { + lt_count--; + } + } + } + } + if (lt_foo != "") { lt_freq[lt_foo]++; } + if (lt_freq[lt_foo] == 1) { print lt_foo; } +}'` + # AWK program above erroneously prepends '/' to C:/dos/paths + # for these hosts. + case $host_os in + mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ + $SED 's,/\([A-Za-z]:\),\1,g'` ;; + esac + sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` +else + sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" +fi +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=".so" +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +case $host_os in +aix3*) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='${libname}${release}${shared_ext}$major' + ;; + +aix[4-9]*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test "$host_cpu" = ia64; then + # AIX 5 supports IA64 + library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line `#! .'. This would cause the generated library to + # depend on `.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[01] | aix4.[01].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # AIX (on Power*) has no versioning support, so currently we can not hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + if test "$aix_use_runtimelinking" = yes; then + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + else + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='${libname}${release}.a $libname.a' + soname_spec='${libname}${release}${shared_ext}$major' + fi + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + case $host_cpu in + powerpc) + # Since July 2007 AmigaOS4 officially supports .so libraries. + # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + ;; + m68k) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + esac + ;; + +beos*) + library_names_spec='${libname}${shared_ext}' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi[45]*) + version_type=linux # correct to gnu/linux during the next big refactor + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32* | cegcc*) + version_type=windows + shrext_cmds=".dll" + need_version=no + need_lib_prefix=no + + case $GCC,$cc_basename in + yes,*) + # gcc + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname~ + if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then + eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; + fi' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $RM \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + + sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api" + ;; + mingw* | cegcc*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + ;; + esac + dynamic_linker='Win32 ld.exe' + ;; + + *,cl*) + # Native MSVC + libname_spec='$name' + soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + library_names_spec='${libname}.dll.lib' + + case $build_os in + mingw*) + sys_lib_search_path_spec= + lt_save_ifs=$IFS + IFS=';' + for lt_path in $LIB + do + IFS=$lt_save_ifs + # Let DOS variable expansion print the short 8.3 style file name. + lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` + sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" + done + IFS=$lt_save_ifs + # Convert to MSYS style. + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'` + ;; + cygwin*) + # Convert to unix form, then to dos form, then back to unix form + # but this time dos style (no spaces!) so that the unix form looks + # like /cygdrive/c/PROGRA~1:/cygdr... + sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` + sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` + sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + ;; + *) + sys_lib_search_path_spec="$LIB" + if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then + # It is most probably a Windows format PATH. + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + # FIXME: find the short name or the path components, as spaces are + # common. (e.g. "Program Files" -> "PROGRA~1") + ;; + esac + + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $RM \$dlpath' + shlibpath_overrides_runpath=yes + dynamic_linker='Win32 link.exe' + ;; + + *) + # Assume MSVC wrapper + library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' + dynamic_linker='Win32 ld.exe' + ;; + esac + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' + soname_spec='${libname}${release}${major}$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' + + sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib" + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd* | dragonfly*) + # DragonFly does not have aout. When/if they implement a new + # versioning mechanism, adjust this. + if test -x /usr/bin/objformat; then + objformat=`/usr/bin/objformat` + else + case $host_os in + freebsd[23].*) objformat=aout ;; + *) objformat=elf ;; + esac + fi + version_type=freebsd-$objformat + case $version_type in + freebsd-elf*) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' + need_version=yes + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2.*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.[01]* | freebsdelf3.[01]*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ + freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + *) # from 4.6 on, and DragonFly + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + esac + ;; + +gnu*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +haiku*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + dynamic_linker="$host_os runtime_loader" + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LIBRARY_PATH + shlibpath_overrides_runpath=yes + sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case $host_cpu in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + if test "X$HPUX_IA64_MODE" = X32; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + fi + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555, ... + postinstall_cmds='chmod 555 $lib' + # or fails outright, so override atomically: + install_override_mode=555 + ;; + +interix[3-9]*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test "$lt_cv_prog_gnu_ld" = yes; then + version_type=linux # correct to gnu/linux during the next big refactor + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +# This must be glibc/ELF. +linux* | k*bsd*-gnu | kopensolaris*-gnu) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + + # Some binutils ld are patched to set DT_RUNPATH + if ${lt_cv_shlibpath_overrides_runpath+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_shlibpath_overrides_runpath=no + save_LDFLAGS=$LDFLAGS + save_libdir=$libdir + eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \ + LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\"" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then : + lt_cv_shlibpath_overrides_runpath=yes +fi +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + LDFLAGS=$save_LDFLAGS + libdir=$save_libdir + +fi + + shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath + + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + + # Append ld.so.conf contents to the search path + if test -f /etc/ld.so.conf; then + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsdelf*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='NetBSD ld.elf_so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +*nto* | *qnx*) + version_type=qnx + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='ldqnx.so' + ;; + +openbsd*) + version_type=sunos + sys_lib_dlsearch_path_spec="/usr/lib" + need_lib_prefix=no + # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. + case $host_os in + openbsd3.3 | openbsd3.3.*) need_version=yes ;; + *) need_version=no ;; + esac + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + case $host_os in + openbsd2.[89] | openbsd2.[89].*) + shlibpath_overrides_runpath=no + ;; + *) + shlibpath_overrides_runpath=yes + ;; + esac + else + shlibpath_overrides_runpath=yes + fi + ;; + +os2*) + libname_spec='$name' + shrext_cmds=".dll" + need_lib_prefix=no + library_names_spec='$libname${shared_ext} $libname.a' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=LIBPATH + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" + ;; + +rdos*) + dynamic_linker=no + ;; + +solaris*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test "$with_gnu_ld" = yes; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.3*) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec ;then + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' + soname_spec='$libname${shared_ext}.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + version_type=freebsd-elf + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + if test "$with_gnu_ld" = yes; then + sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' + else + sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' + case $host_os in + sco3.2v5*) + sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" + ;; + esac + fi + sys_lib_dlsearch_path_spec='/usr/lib' + ;; + +tpf*) + # TPF is a cross-target only. Preferred cross-host = GNU/Linux. + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +uts4*) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 +$as_echo "$dynamic_linker" >&6; } +test "$dynamic_linker" = no && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test "$GCC" = yes; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then + sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" +fi +if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then + sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" +fi + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5 +$as_echo_n "checking how to hardcode library paths into programs... " >&6; } +hardcode_action= +if test -n "$hardcode_libdir_flag_spec" || + test -n "$runpath_var" || + test "X$hardcode_automatic" = "Xyes" ; then + + # We can hardcode non-existent directories. + if test "$hardcode_direct" != no && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test "$_LT_TAGVAR(hardcode_shlibpath_var, )" != no && + test "$hardcode_minus_L" != no; then + # Linking always hardcodes the temporary library directory. + hardcode_action=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + hardcode_action=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + hardcode_action=unsupported +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5 +$as_echo "$hardcode_action" >&6; } + +if test "$hardcode_action" = relink || + test "$inherit_rpath" = yes; then + # Fast installation is not supported + enable_fast_install=no +elif test "$shlibpath_overrides_runpath" = yes || + test "$enable_shared" = no; then + # Fast installation is not necessary + enable_fast_install=needless +fi + + + + + + + if test "x$enable_dlopen" != xyes; then + enable_dlopen=unknown + enable_dlopen_self=unknown + enable_dlopen_self_static=unknown +else + lt_cv_dlopen=no + lt_cv_dlopen_libs= + + case $host_os in + beos*) + lt_cv_dlopen="load_add_on" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ;; + + mingw* | pw32* | cegcc*) + lt_cv_dlopen="LoadLibrary" + lt_cv_dlopen_libs= + ;; + + cygwin*) + lt_cv_dlopen="dlopen" + lt_cv_dlopen_libs= + ;; + + darwin*) + # if libdl is installed we need to link against it + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 +$as_echo_n "checking for dlopen in -ldl... " >&6; } +if ${ac_cv_lib_dl_dlopen+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int +main () +{ +return dlopen (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_dl_dlopen=yes +else + ac_cv_lib_dl_dlopen=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 +$as_echo "$ac_cv_lib_dl_dlopen" >&6; } +if test "x$ac_cv_lib_dl_dlopen" = xyes; then : + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" +else + + lt_cv_dlopen="dyld" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + +fi + + ;; + + *) + ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load" +if test "x$ac_cv_func_shl_load" = xyes; then : + lt_cv_dlopen="shl_load" +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 +$as_echo_n "checking for shl_load in -ldld... " >&6; } +if ${ac_cv_lib_dld_shl_load+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char shl_load (); +int +main () +{ +return shl_load (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_dld_shl_load=yes +else + ac_cv_lib_dld_shl_load=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5 +$as_echo "$ac_cv_lib_dld_shl_load" >&6; } +if test "x$ac_cv_lib_dld_shl_load" = xyes; then : + lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld" +else + ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" +if test "x$ac_cv_func_dlopen" = xyes; then : + lt_cv_dlopen="dlopen" +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 +$as_echo_n "checking for dlopen in -ldl... " >&6; } +if ${ac_cv_lib_dl_dlopen+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int +main () +{ +return dlopen (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_dl_dlopen=yes +else + ac_cv_lib_dl_dlopen=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 +$as_echo "$ac_cv_lib_dl_dlopen" >&6; } +if test "x$ac_cv_lib_dl_dlopen" = xyes; then : + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5 +$as_echo_n "checking for dlopen in -lsvld... " >&6; } +if ${ac_cv_lib_svld_dlopen+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lsvld $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int +main () +{ +return dlopen (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_svld_dlopen=yes +else + ac_cv_lib_svld_dlopen=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5 +$as_echo "$ac_cv_lib_svld_dlopen" >&6; } +if test "x$ac_cv_lib_svld_dlopen" = xyes; then : + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld" +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5 +$as_echo_n "checking for dld_link in -ldld... " >&6; } +if ${ac_cv_lib_dld_dld_link+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dld_link (); +int +main () +{ +return dld_link (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_dld_dld_link=yes +else + ac_cv_lib_dld_dld_link=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5 +$as_echo "$ac_cv_lib_dld_dld_link" >&6; } +if test "x$ac_cv_lib_dld_dld_link" = xyes; then : + lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld" +fi + + +fi + + +fi + + +fi + + +fi + + +fi + + ;; + esac + + if test "x$lt_cv_dlopen" != xno; then + enable_dlopen=yes + else + enable_dlopen=no + fi + + case $lt_cv_dlopen in + dlopen) + save_CPPFLAGS="$CPPFLAGS" + test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" + + save_LDFLAGS="$LDFLAGS" + wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" + + save_LIBS="$LIBS" + LIBS="$lt_cv_dlopen_libs $LIBS" + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5 +$as_echo_n "checking whether a program can dlopen itself... " >&6; } +if ${lt_cv_dlopen_self+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + lt_cv_dlopen_self=cross +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext <<_LT_EOF +#line $LINENO "configure" +#include "confdefs.h" + +#if HAVE_DLFCN_H +#include +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +/* When -fvisbility=hidden is used, assume the code has been annotated + correspondingly for the symbols needed. */ +#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) +int fnord () __attribute__((visibility("default"))); +#endif + +int fnord () { return 42; } +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else + { + if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + else puts (dlerror ()); + } + /* dlclose (self); */ + } + else + puts (dlerror ()); + + return status; +} +_LT_EOF + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 + (eval $ac_link) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) >&5 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; + x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; + x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;; + esac + else : + # compilation failed + lt_cv_dlopen_self=no + fi +fi +rm -fr conftest* + + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5 +$as_echo "$lt_cv_dlopen_self" >&6; } + + if test "x$lt_cv_dlopen_self" = xyes; then + wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5 +$as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; } +if ${lt_cv_dlopen_self_static+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + lt_cv_dlopen_self_static=cross +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext <<_LT_EOF +#line $LINENO "configure" +#include "confdefs.h" + +#if HAVE_DLFCN_H +#include +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +/* When -fvisbility=hidden is used, assume the code has been annotated + correspondingly for the symbols needed. */ +#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) +int fnord () __attribute__((visibility("default"))); +#endif + +int fnord () { return 42; } +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else + { + if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + else puts (dlerror ()); + } + /* dlclose (self); */ + } + else + puts (dlerror ()); + + return status; +} +_LT_EOF + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 + (eval $ac_link) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) >&5 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; + x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; + x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;; + esac + else : + # compilation failed + lt_cv_dlopen_self_static=no + fi +fi +rm -fr conftest* + + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5 +$as_echo "$lt_cv_dlopen_self_static" >&6; } + fi + + CPPFLAGS="$save_CPPFLAGS" + LDFLAGS="$save_LDFLAGS" + LIBS="$save_LIBS" + ;; + esac + + case $lt_cv_dlopen_self in + yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; + *) enable_dlopen_self=unknown ;; + esac + + case $lt_cv_dlopen_self_static in + yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; + *) enable_dlopen_self_static=unknown ;; + esac +fi + + + + + + + + + + + + + + + + + +striplib= +old_striplib= +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stripping libraries is possible" >&5 +$as_echo_n "checking whether stripping libraries is possible... " >&6; } +if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then + test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" + test -z "$striplib" && striplib="$STRIP --strip-unneeded" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else +# FIXME - insert some real tests, host_os isn't really good enough + case $host_os in + darwin*) + if test -n "$STRIP" ; then + striplib="$STRIP -x" + old_striplib="$STRIP -S" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + fi + ;; + *) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ;; + esac +fi + + + + + + + + + + + + + # Report which library types will actually be built + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5 +$as_echo_n "checking if libtool supports shared libraries... " >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5 +$as_echo "$can_build_shared" >&6; } + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5 +$as_echo_n "checking whether to build shared libraries... " >&6; } + test "$can_build_shared" = "no" && enable_shared=no + + # On AIX, shared libraries and static libraries use the same namespace, and + # are all built from PIC. + case $host_os in + aix3*) + test "$enable_shared" = yes && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; + + aix[4-9]*) + if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then + test "$enable_shared" = yes && enable_static=no + fi + ;; + esac + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5 +$as_echo "$enable_shared" >&6; } + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5 +$as_echo_n "checking whether to build static libraries... " >&6; } + # Make sure either enable_shared or enable_static is yes. + test "$enable_shared" = yes || enable_static=yes + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5 +$as_echo "$enable_static" >&6; } + + + + +fi +ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + +CC="$lt_save_CC" + + if test -n "$CXX" && ( test "X$CXX" != "Xno" && + ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) || + (test "X$CXX" != "Xg++"))) ; then + ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C++ preprocessor" >&5 +$as_echo_n "checking how to run the C++ preprocessor... " >&6; } +if test -z "$CXXCPP"; then + if ${ac_cv_prog_CXXCPP+:} false; then : + $as_echo_n "(cached) " >&6 +else + # Double quotes because CXXCPP needs to be expanded + for CXXCPP in "$CXX -E" "/lib/cpp" + do + ac_preproc_ok=false +for ac_cxx_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_cxx_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_cxx_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + break +fi + + done + ac_cv_prog_CXXCPP=$CXXCPP + +fi + CXXCPP=$ac_cv_prog_CXXCPP +else + ac_cv_prog_CXXCPP=$CXXCPP +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXXCPP" >&5 +$as_echo "$CXXCPP" >&6; } +ac_preproc_ok=false +for ac_cxx_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_cxx_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_cxx_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "C++ preprocessor \"$CXXCPP\" fails sanity check +See \`config.log' for more details" "$LINENO" 5; } +fi + +ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + +else + _lt_caught_CXX_error=yes +fi + +ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + +archive_cmds_need_lc_CXX=no +allow_undefined_flag_CXX= +always_export_symbols_CXX=no +archive_expsym_cmds_CXX= +compiler_needs_object_CXX=no +export_dynamic_flag_spec_CXX= +hardcode_direct_CXX=no +hardcode_direct_absolute_CXX=no +hardcode_libdir_flag_spec_CXX= +hardcode_libdir_separator_CXX= +hardcode_minus_L_CXX=no +hardcode_shlibpath_var_CXX=unsupported +hardcode_automatic_CXX=no +inherit_rpath_CXX=no +module_cmds_CXX= +module_expsym_cmds_CXX= +link_all_deplibs_CXX=unknown +old_archive_cmds_CXX=$old_archive_cmds +reload_flag_CXX=$reload_flag +reload_cmds_CXX=$reload_cmds +no_undefined_flag_CXX= +whole_archive_flag_spec_CXX= +enable_shared_with_static_runtimes_CXX=no + +# Source file extension for C++ test sources. +ac_ext=cpp + +# Object file extension for compiled C++ test sources. +objext=o +objext_CXX=$objext + +# No sense in running all these tests if we already determined that +# the CXX compiler isn't working. Some variables (like enable_shared) +# are currently assumed to apply to all compilers on this platform, +# and will be corrupted by setting them based on a non-working compiler. +if test "$_lt_caught_CXX_error" != yes; then + # Code to be used in simple compile tests + lt_simple_compile_test_code="int some_variable = 0;" + + # Code to be used in simple link tests + lt_simple_link_test_code='int main(int, char *[]) { return(0); }' + + # ltmain only uses $CC for tagged configurations so make sure $CC is set. + + + + + + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + + # save warnings/boilerplate of simple test code + ac_outfile=conftest.$ac_objext +echo "$lt_simple_compile_test_code" >conftest.$ac_ext +eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_compiler_boilerplate=`cat conftest.err` +$RM conftest* + + ac_outfile=conftest.$ac_objext +echo "$lt_simple_link_test_code" >conftest.$ac_ext +eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_linker_boilerplate=`cat conftest.err` +$RM -r conftest* + + + # Allow CC to be a program name with arguments. + lt_save_CC=$CC + lt_save_CFLAGS=$CFLAGS + lt_save_LD=$LD + lt_save_GCC=$GCC + GCC=$GXX + lt_save_with_gnu_ld=$with_gnu_ld + lt_save_path_LD=$lt_cv_path_LD + if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then + lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx + else + $as_unset lt_cv_prog_gnu_ld + fi + if test -n "${lt_cv_path_LDCXX+set}"; then + lt_cv_path_LD=$lt_cv_path_LDCXX + else + $as_unset lt_cv_path_LD + fi + test -z "${LDCXX+set}" || LD=$LDCXX + CC=${CXX-"c++"} + CFLAGS=$CXXFLAGS + compiler=$CC + compiler_CXX=$CC + for cc_temp in $compiler""; do + case $cc_temp in + compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; + distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; + \-*) ;; + *) break;; + esac +done +cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` + + + if test -n "$compiler"; then + # We don't want -fno-exception when compiling C++ code, so set the + # no_builtin_flag separately + if test "$GXX" = yes; then + lt_prog_compiler_no_builtin_flag_CXX=' -fno-builtin' + else + lt_prog_compiler_no_builtin_flag_CXX= + fi + + if test "$GXX" = yes; then + # Set up default GNU C++ configuration + + + +# Check whether --with-gnu-ld was given. +if test "${with_gnu_ld+set}" = set; then : + withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes +else + with_gnu_ld=no +fi + +ac_prog=ld +if test "$GCC" = yes; then + # Check if gcc -print-prog-name=ld gives a path. + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 +$as_echo_n "checking for ld used by $CC... " >&6; } + case $host in + *-*-mingw*) + # gcc leaves a trailing carriage return which upsets mingw + ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; + *) + ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; + esac + case $ac_prog in + # Accept absolute paths. + [\\/]* | ?:[\\/]*) + re_direlt='/[^/][^/]*/\.\./' + # Canonicalize the pathname of ld + ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` + while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do + ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` + done + test -z "$LD" && LD="$ac_prog" + ;; + "") + # If it fails, then pretend we aren't using GCC. + ac_prog=ld + ;; + *) + # If it is relative, then search for the first ld in PATH. + with_gnu_ld=unknown + ;; + esac +elif test "$with_gnu_ld" = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 +$as_echo_n "checking for GNU ld... " >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 +$as_echo_n "checking for non-GNU ld... " >&6; } +fi +if ${lt_cv_path_LD+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -z "$LD"; then + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then + lt_cv_path_LD="$ac_dir/$ac_prog" + # Check to see if the program is GNU ld. I'd rather use --version, + # but apparently some variants of GNU ld only accept -v. + # Break only if it was the GNU/non-GNU ld that we prefer. + case `"$lt_cv_path_LD" -v 2>&1 &5 +$as_echo "$LD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 +$as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; } +if ${lt_cv_prog_gnu_ld+:} false; then : + $as_echo_n "(cached) " >&6 +else + # I'd rather use --version here, but apparently some GNU lds only accept -v. +case `$LD -v 2>&1 &5 +$as_echo "$lt_cv_prog_gnu_ld" >&6; } +with_gnu_ld=$lt_cv_prog_gnu_ld + + + + + + + + # Check if GNU C++ uses GNU ld as the underlying linker, since the + # archiving commands below assume that GNU ld is being used. + if test "$with_gnu_ld" = yes; then + archive_cmds_CXX='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_CXX='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + + hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' + export_dynamic_flag_spec_CXX='${wl}--export-dynamic' + + # If archive_cmds runs LD, not CC, wlarc should be empty + # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to + # investigate it a little bit more. (MM) + wlarc='${wl}' + + # ancient GNU ld didn't support --whole-archive et. al. + if eval "`$CC -print-prog-name=ld` --help 2>&1" | + $GREP 'no-whole-archive' > /dev/null; then + whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + whole_archive_flag_spec_CXX= + fi + else + with_gnu_ld=no + wlarc= + + # A generic and very simple default shared library creation + # command for GNU C++ for the case where it uses the native + # linker, instead of GNU ld. If possible, this setting should + # overridden to take advantage of the native linker features on + # the platform it is being used on. + archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' + fi + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' + + else + GXX=no + with_gnu_ld=no + wlarc= + fi + + # PORTME: fill in a description of your system's C++ link characteristics + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +$as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } + ld_shlibs_CXX=yes + case $host_os in + aix3*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + aix[4-9]*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) + for ld_flag in $LDFLAGS; do + case $ld_flag in + *-brtl*) + aix_use_runtimelinking=yes + break + ;; + esac + done + ;; + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + archive_cmds_CXX='' + hardcode_direct_CXX=yes + hardcode_direct_absolute_CXX=yes + hardcode_libdir_separator_CXX=':' + link_all_deplibs_CXX=yes + file_list_spec_CXX='${wl}-f,' + + if test "$GXX" = yes; then + case $host_os in aix4.[012]|aix4.[012].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && + strings "$collect2name" | $GREP resolve_lib_name >/dev/null + then + # We have reworked collect2 + : + else + # We have old collect2 + hardcode_direct_CXX=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + hardcode_minus_L_CXX=yes + hardcode_libdir_flag_spec_CXX='-L$libdir' + hardcode_libdir_separator_CXX= + fi + esac + shared_flag='-shared' + if test "$aix_use_runtimelinking" = yes; then + shared_flag="$shared_flag "'${wl}-G' + fi + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + export_dynamic_flag_spec_CXX='${wl}-bexpall' + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to + # export. + always_export_symbols_CXX=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + allow_undefined_flag_CXX='-berok' + # Determine the default libpath from the value encoded in an empty + # executable. + if test "${lt_cv_aix_libpath+set}" = set; then + aix_libpath=$lt_cv_aix_libpath +else + if ${lt_cv_aix_libpath__CXX+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_cxx_try_link "$LINENO"; then : + + lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\([^ ]*\) *$/\1/ + p + } + }' + lt_cv_aix_libpath__CXX=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` + # Check for a 64-bit object if we didn't find anything. + if test -z "$lt_cv_aix_libpath__CXX"; then + lt_cv_aix_libpath__CXX=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` + fi +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + if test -z "$lt_cv_aix_libpath__CXX"; then + lt_cv_aix_libpath__CXX="/usr/lib:/lib" + fi + +fi + + aix_libpath=$lt_cv_aix_libpath__CXX +fi + + hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath" + + archive_expsym_cmds_CXX='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + hardcode_libdir_flag_spec_CXX='${wl}-R $libdir:/usr/lib:/lib' + allow_undefined_flag_CXX="-z nodefs" + archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an + # empty executable. + if test "${lt_cv_aix_libpath+set}" = set; then + aix_libpath=$lt_cv_aix_libpath +else + if ${lt_cv_aix_libpath__CXX+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_cxx_try_link "$LINENO"; then : + + lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\([^ ]*\) *$/\1/ + p + } + }' + lt_cv_aix_libpath__CXX=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` + # Check for a 64-bit object if we didn't find anything. + if test -z "$lt_cv_aix_libpath__CXX"; then + lt_cv_aix_libpath__CXX=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` + fi +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + if test -z "$lt_cv_aix_libpath__CXX"; then + lt_cv_aix_libpath__CXX="/usr/lib:/lib" + fi + +fi + + aix_libpath=$lt_cv_aix_libpath__CXX +fi + + hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + no_undefined_flag_CXX=' ${wl}-bernotok' + allow_undefined_flag_CXX=' ${wl}-berok' + if test "$with_gnu_ld" = yes; then + # We only use this code for GNU lds that support --whole-archive. + whole_archive_flag_spec_CXX='${wl}--whole-archive$convenience ${wl}--no-whole-archive' + else + # Exported symbols can be pulled into shared objects from archives + whole_archive_flag_spec_CXX='$convenience' + fi + archive_cmds_need_lc_CXX=yes + # This is similar to how AIX traditionally builds its shared + # libraries. + archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + beos*) + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + allow_undefined_flag_CXX=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + archive_cmds_CXX='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + ld_shlibs_CXX=no + fi + ;; + + chorus*) + case $cc_basename in + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + + cygwin* | mingw* | pw32* | cegcc*) + case $GXX,$cc_basename in + ,cl* | no,cl*) + # Native MSVC + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + hardcode_libdir_flag_spec_CXX=' ' + allow_undefined_flag_CXX=unsupported + always_export_symbols_CXX=yes + file_list_spec_CXX='@' + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=".dll" + # FIXME: Setting linknames here is a bad hack. + archive_cmds_CXX='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' + archive_expsym_cmds_CXX='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; + else + $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; + fi~ + $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ + linknames=' + # The linker will not automatically build a static lib if we build a DLL. + # _LT_TAGVAR(old_archive_from_new_cmds, CXX)='true' + enable_shared_with_static_runtimes_CXX=yes + # Don't use ranlib + old_postinstall_cmds_CXX='chmod 644 $oldlib' + postlink_cmds_CXX='lt_outputfile="@OUTPUT@"~ + lt_tool_outputfile="@TOOL_OUTPUT@"~ + case $lt_outputfile in + *.exe|*.EXE) ;; + *) + lt_outputfile="$lt_outputfile.exe" + lt_tool_outputfile="$lt_tool_outputfile.exe" + ;; + esac~ + func_to_tool_file "$lt_outputfile"~ + if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then + $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; + $RM "$lt_outputfile.manifest"; + fi' + ;; + *) + # g++ + # _LT_TAGVAR(hardcode_libdir_flag_spec, CXX) is actually meaningless, + # as there is no search path for DLLs. + hardcode_libdir_flag_spec_CXX='-L$libdir' + export_dynamic_flag_spec_CXX='${wl}--export-all-symbols' + allow_undefined_flag_CXX=unsupported + always_export_symbols_CXX=no + enable_shared_with_static_runtimes_CXX=yes + + if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then + archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + archive_expsym_cmds_CXX='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + else + ld_shlibs_CXX=no + fi + ;; + esac + ;; + darwin* | rhapsody*) + + + archive_cmds_need_lc_CXX=no + hardcode_direct_CXX=no + hardcode_automatic_CXX=yes + hardcode_shlibpath_var_CXX=unsupported + if test "$lt_cv_ld_force_load" = "yes"; then + whole_archive_flag_spec_CXX='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' + + else + whole_archive_flag_spec_CXX='' + fi + link_all_deplibs_CXX=yes + allow_undefined_flag_CXX="$_lt_dar_allow_undefined" + case $cc_basename in + ifort*) _lt_dar_can_shared=yes ;; + *) _lt_dar_can_shared=$GCC ;; + esac + if test "$_lt_dar_can_shared" = "yes"; then + output_verbose_link_cmd=func_echo_all + archive_cmds_CXX="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" + module_cmds_CXX="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" + archive_expsym_cmds_CXX="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" + module_expsym_cmds_CXX="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" + if test "$lt_cv_apple_cc_single_mod" != "yes"; then + archive_cmds_CXX="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}" + archive_expsym_cmds_CXX="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}" + fi + + else + ld_shlibs_CXX=no + fi + + ;; + + dgux*) + case $cc_basename in + ec++*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + ghcx*) + # Green Hills C++ Compiler + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + + freebsd2.*) + # C++ shared libraries reported to be fairly broken before + # switch to ELF + ld_shlibs_CXX=no + ;; + + freebsd-elf*) + archive_cmds_need_lc_CXX=no + ;; + + freebsd* | dragonfly*) + # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF + # conventions + ld_shlibs_CXX=yes + ;; + + gnu*) + ;; + + haiku*) + archive_cmds_CXX='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + link_all_deplibs_CXX=yes + ;; + + hpux9*) + hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_CXX=: + export_dynamic_flag_spec_CXX='${wl}-E' + hardcode_direct_CXX=yes + hardcode_minus_L_CXX=yes # Not in the search PATH, + # but as the default + # location of the library. + + case $cc_basename in + CC*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + aCC*) + archive_cmds_CXX='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' + ;; + *) + if test "$GXX" = yes; then + archive_cmds_CXX='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + fi + ;; + esac + ;; + + hpux10*|hpux11*) + if test $with_gnu_ld = no; then + hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir' + hardcode_libdir_separator_CXX=: + + case $host_cpu in + hppa*64*|ia64*) + ;; + *) + export_dynamic_flag_spec_CXX='${wl}-E' + ;; + esac + fi + case $host_cpu in + hppa*64*|ia64*) + hardcode_direct_CXX=no + hardcode_shlibpath_var_CXX=no + ;; + *) + hardcode_direct_CXX=yes + hardcode_direct_absolute_CXX=yes + hardcode_minus_L_CXX=yes # Not in the search PATH, + # but as the default + # location of the library. + ;; + esac + + case $cc_basename in + CC*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + aCC*) + case $host_cpu in + hppa*64*) + archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + ia64*) + archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + *) + archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + esac + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' + ;; + *) + if test "$GXX" = yes; then + if test $with_gnu_ld = no; then + case $host_cpu in + hppa*64*) + archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + ia64*) + archive_cmds_CXX='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + *) + archive_cmds_CXX='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + esac + fi + else + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + fi + ;; + esac + ;; + + interix[3-9]*) + hardcode_direct_CXX=no + hardcode_shlibpath_var_CXX=no + hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' + export_dynamic_flag_spec_CXX='${wl}-E' + # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. + # Instead, shared libraries are loaded at an image base (0x10000000 by + # default) and relocated if they conflict, which is a slow very memory + # consuming and fragmenting process. To avoid this, we pick a random, + # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link + # time. Moving up from 0x10000000 also allows more sbrk(2) space. + archive_cmds_CXX='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + archive_expsym_cmds_CXX='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + ;; + irix5* | irix6*) + case $cc_basename in + CC*) + # SGI C++ + archive_cmds_CXX='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' + + # Archives containing C++ object files must be created using + # "CC -ar", where "CC" is the IRIX C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + old_archive_cmds_CXX='$CC -ar -WR,-u -o $oldlib $oldobjs' + ;; + *) + if test "$GXX" = yes; then + if test "$with_gnu_ld" = no; then + archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib' + fi + fi + link_all_deplibs_CXX=yes + ;; + esac + hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_CXX=: + inherit_rpath_CXX=yes + ;; + + linux* | k*bsd*-gnu | kopensolaris*-gnu) + case $cc_basename in + KCC*) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + archive_expsym_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib' + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' + + hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' + export_dynamic_flag_spec_CXX='${wl}--export-dynamic' + + # Archives containing C++ object files must be created using + # "CC -Bstatic", where "CC" is the KAI C++ compiler. + old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs' + ;; + icpc* | ecpc* ) + # Intel C++ + with_gnu_ld=yes + # version 8.0 and above of icpc choke on multiply defined symbols + # if we add $predep_objects and $postdep_objects, however 7.1 and + # earlier do not add the objects themselves. + case `$CC -V 2>&1` in + *"Version 7."*) + archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + ;; + *) # Version 8.0 or newer + tmp_idyn= + case $host_cpu in + ia64*) tmp_idyn=' -i_dynamic';; + esac + archive_cmds_CXX='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_CXX='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + ;; + esac + archive_cmds_need_lc_CXX=no + hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' + export_dynamic_flag_spec_CXX='${wl}--export-dynamic' + whole_archive_flag_spec_CXX='${wl}--whole-archive$convenience ${wl}--no-whole-archive' + ;; + pgCC* | pgcpp*) + # Portland Group C++ compiler + case `$CC -V` in + *pgCC\ [1-5].* | *pgcpp\ [1-5].*) + prelink_cmds_CXX='tpldir=Template.dir~ + rm -rf $tpldir~ + $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~ + compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"' + old_archive_cmds_CXX='tpldir=Template.dir~ + rm -rf $tpldir~ + $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~ + $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~ + $RANLIB $oldlib' + archive_cmds_CXX='tpldir=Template.dir~ + rm -rf $tpldir~ + $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ + $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' + archive_expsym_cmds_CXX='tpldir=Template.dir~ + rm -rf $tpldir~ + $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ + $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' + ;; + *) # Version 6 and above use weak symbols + archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' + archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' + ;; + esac + + hardcode_libdir_flag_spec_CXX='${wl}--rpath ${wl}$libdir' + export_dynamic_flag_spec_CXX='${wl}--export-dynamic' + whole_archive_flag_spec_CXX='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' + ;; + cxx*) + # Compaq C++ + archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols' + + runpath_var=LD_RUN_PATH + hardcode_libdir_flag_spec_CXX='-rpath $libdir' + hardcode_libdir_separator_CXX=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed' + ;; + xl* | mpixl* | bgxl*) + # IBM XL 8.0 on PPC, with GNU ld + hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' + export_dynamic_flag_spec_CXX='${wl}--export-dynamic' + archive_cmds_CXX='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + if test "x$supports_anon_versioning" = xyes; then + archive_expsym_cmds_CXX='echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' + fi + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C++ 5.9 + no_undefined_flag_CXX=' -zdefs' + archive_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + archive_expsym_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols' + hardcode_libdir_flag_spec_CXX='-R$libdir' + whole_archive_flag_spec_CXX='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' + compiler_needs_object_CXX=yes + + # Not sure whether something based on + # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 + # would be better. + output_verbose_link_cmd='func_echo_all' + + # Archives containing C++ object files must be created using + # "CC -xar", where "CC" is the Sun C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs' + ;; + esac + ;; + esac + ;; + + lynxos*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + + m88k*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + + mvs*) + case $cc_basename in + cxx*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + archive_cmds_CXX='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' + wlarc= + hardcode_libdir_flag_spec_CXX='-R$libdir' + hardcode_direct_CXX=yes + hardcode_shlibpath_var_CXX=no + fi + # Workaround some broken pre-1.5 toolchains + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' + ;; + + *nto* | *qnx*) + ld_shlibs_CXX=yes + ;; + + openbsd2*) + # C++ shared libraries are fairly broken + ld_shlibs_CXX=no + ;; + + openbsd*) + if test -f /usr/libexec/ld.so; then + hardcode_direct_CXX=yes + hardcode_shlibpath_var_CXX=no + hardcode_direct_absolute_CXX=yes + archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' + hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib' + export_dynamic_flag_spec_CXX='${wl}-E' + whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + fi + output_verbose_link_cmd=func_echo_all + else + ld_shlibs_CXX=no + fi + ;; + + osf3* | osf4* | osf5*) + case $cc_basename in + KCC*) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + + hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' + hardcode_libdir_separator_CXX=: + + # Archives containing C++ object files must be created using + # the KAI C++ compiler. + case $host in + osf3*) old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs' ;; + *) old_archive_cmds_CXX='$CC -o $oldlib $oldobjs' ;; + esac + ;; + RCC*) + # Rational C++ 2.4.1 + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + cxx*) + case $host in + osf3*) + allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' + ;; + *) + allow_undefined_flag_CXX=' -expect_unresolved \*' + archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' + archive_expsym_cmds_CXX='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ + echo "-hidden">> $lib.exp~ + $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~ + $RM $lib.exp' + hardcode_libdir_flag_spec_CXX='-rpath $libdir' + ;; + esac + + hardcode_libdir_separator_CXX=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' + ;; + *) + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*' + case $host in + osf3*) + archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + ;; + *) + archive_cmds_CXX='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + ;; + esac + + hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator_CXX=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' + + else + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + fi + ;; + esac + ;; + + psos*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + + sunos4*) + case $cc_basename in + CC*) + # Sun C++ 4.x + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + lcc*) + # Lucid + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + + solaris*) + case $cc_basename in + CC* | sunCC*) + # Sun C++ 4.2, 5.x and Centerline C++ + archive_cmds_need_lc_CXX=yes + no_undefined_flag_CXX=' -zdefs' + archive_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' + + hardcode_libdir_flag_spec_CXX='-R$libdir' + hardcode_shlibpath_var_CXX=no + case $host_os in + solaris2.[0-5] | solaris2.[0-5].*) ;; + *) + # The compiler driver will combine and reorder linker options, + # but understands `-z linker_flag'. + # Supported since Solaris 2.6 (maybe 2.5.1?) + whole_archive_flag_spec_CXX='-z allextract$convenience -z defaultextract' + ;; + esac + link_all_deplibs_CXX=yes + + output_verbose_link_cmd='func_echo_all' + + # Archives containing C++ object files must be created using + # "CC -xar", where "CC" is the Sun C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs' + ;; + gcx*) + # Green Hills C++ Compiler + archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + + # The C++ compiler must be used to create the archive. + old_archive_cmds_CXX='$CC $LDFLAGS -archive -o $oldlib $oldobjs' + ;; + *) + # GNU C++ compiler with Solaris linker + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + no_undefined_flag_CXX=' ${wl}-z ${wl}defs' + if $CC --version | $GREP -v '^2\.7' > /dev/null; then + archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' + else + # g++ 2.7 appears to require `-G' NOT `-shared' on this + # platform. + archive_cmds_CXX='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' + fi + + hardcode_libdir_flag_spec_CXX='${wl}-R $wl$libdir' + case $host_os in + solaris2.[0-5] | solaris2.[0-5].*) ;; + *) + whole_archive_flag_spec_CXX='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' + ;; + esac + fi + ;; + esac + ;; + + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) + no_undefined_flag_CXX='${wl}-z,text' + archive_cmds_need_lc_CXX=no + hardcode_shlibpath_var_CXX=no + runpath_var='LD_RUN_PATH' + + case $cc_basename in + CC*) + archive_cmds_CXX='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds_CXX='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + ;; + + sysv5* | sco3.2v5* | sco5v6*) + # Note: We can NOT use -z defs as we might desire, because we do not + # link with -lc, and that would cause any symbols used from libc to + # always be unresolved, which means just about no library would + # ever link correctly. If we're not using GNU ld we use -z text + # though, which does catch some bad symbols but isn't as heavy-handed + # as -z defs. + no_undefined_flag_CXX='${wl}-z,text' + allow_undefined_flag_CXX='${wl}-z,nodefs' + archive_cmds_need_lc_CXX=no + hardcode_shlibpath_var_CXX=no + hardcode_libdir_flag_spec_CXX='${wl}-R,$libdir' + hardcode_libdir_separator_CXX=':' + link_all_deplibs_CXX=yes + export_dynamic_flag_spec_CXX='${wl}-Bexport' + runpath_var='LD_RUN_PATH' + + case $cc_basename in + CC*) + archive_cmds_CXX='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + old_archive_cmds_CXX='$CC -Tprelink_objects $oldobjs~ + '"$old_archive_cmds_CXX" + reload_cmds_CXX='$CC -Tprelink_objects $reload_objs~ + '"$reload_cmds_CXX" + ;; + *) + archive_cmds_CXX='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + ;; + + tandem*) + case $cc_basename in + NCC*) + # NonStop-UX NCC 3.20 + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + ;; + + vxworks*) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + + *) + # FIXME: insert proper C++ library support + ld_shlibs_CXX=no + ;; + esac + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs_CXX" >&5 +$as_echo "$ld_shlibs_CXX" >&6; } + test "$ld_shlibs_CXX" = no && can_build_shared=no + + GCC_CXX="$GXX" + LD_CXX="$LD" + + ## CAVEAT EMPTOR: + ## There is no encapsulation within the following macros, do not change + ## the running order or otherwise move them around unless you know exactly + ## what you are doing... + # Dependencies to place before and after the object being linked: +predep_objects_CXX= +postdep_objects_CXX= +predeps_CXX= +postdeps_CXX= +compiler_lib_search_path_CXX= + +cat > conftest.$ac_ext <<_LT_EOF +class Foo +{ +public: + Foo (void) { a = 0; } +private: + int a; +}; +_LT_EOF + + +_lt_libdeps_save_CFLAGS=$CFLAGS +case "$CC $CFLAGS " in #( +*\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;; +*\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;; +*\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;; +esac + +if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + # Parse the compiler output and extract the necessary + # objects, libraries and library flags. + + # Sentinel used to keep track of whether or not we are before + # the conftest object file. + pre_test_object_deps_done=no + + for p in `eval "$output_verbose_link_cmd"`; do + case ${prev}${p} in + + -L* | -R* | -l*) + # Some compilers place space between "-{L,R}" and the path. + # Remove the space. + if test $p = "-L" || + test $p = "-R"; then + prev=$p + continue + fi + + # Expand the sysroot to ease extracting the directories later. + if test -z "$prev"; then + case $p in + -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;; + -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;; + -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;; + esac + fi + case $p in + =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;; + esac + if test "$pre_test_object_deps_done" = no; then + case ${prev} in + -L | -R) + # Internal compiler library paths should come after those + # provided the user. The postdeps already come after the + # user supplied libs so there is no need to process them. + if test -z "$compiler_lib_search_path_CXX"; then + compiler_lib_search_path_CXX="${prev}${p}" + else + compiler_lib_search_path_CXX="${compiler_lib_search_path_CXX} ${prev}${p}" + fi + ;; + # The "-l" case would never come before the object being + # linked, so don't bother handling this case. + esac + else + if test -z "$postdeps_CXX"; then + postdeps_CXX="${prev}${p}" + else + postdeps_CXX="${postdeps_CXX} ${prev}${p}" + fi + fi + prev= + ;; + + *.lto.$objext) ;; # Ignore GCC LTO objects + *.$objext) + # This assumes that the test object file only shows up + # once in the compiler output. + if test "$p" = "conftest.$objext"; then + pre_test_object_deps_done=yes + continue + fi + + if test "$pre_test_object_deps_done" = no; then + if test -z "$predep_objects_CXX"; then + predep_objects_CXX="$p" + else + predep_objects_CXX="$predep_objects_CXX $p" + fi + else + if test -z "$postdep_objects_CXX"; then + postdep_objects_CXX="$p" + else + postdep_objects_CXX="$postdep_objects_CXX $p" + fi + fi + ;; + + *) ;; # Ignore the rest. + + esac + done + + # Clean up. + rm -f a.out a.exe +else + echo "libtool.m4: error: problem compiling CXX test program" +fi + +$RM -f confest.$objext +CFLAGS=$_lt_libdeps_save_CFLAGS + +# PORTME: override above test on systems where it is broken +case $host_os in +interix[3-9]*) + # Interix 3.5 installs completely hosed .la files for C++, so rather than + # hack all around it, let's just trust "g++" to DTRT. + predep_objects_CXX= + postdep_objects_CXX= + postdeps_CXX= + ;; + +linux*) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C++ 5.9 + + # The more standards-conforming stlport4 library is + # incompatible with the Cstd library. Avoid specifying + # it if it's in CXXFLAGS. Ignore libCrun as + # -library=stlport4 depends on it. + case " $CXX $CXXFLAGS " in + *" -library=stlport4 "*) + solaris_use_stlport4=yes + ;; + esac + + if test "$solaris_use_stlport4" != yes; then + postdeps_CXX='-library=Cstd -library=Crun' + fi + ;; + esac + ;; + +solaris*) + case $cc_basename in + CC* | sunCC*) + # The more standards-conforming stlport4 library is + # incompatible with the Cstd library. Avoid specifying + # it if it's in CXXFLAGS. Ignore libCrun as + # -library=stlport4 depends on it. + case " $CXX $CXXFLAGS " in + *" -library=stlport4 "*) + solaris_use_stlport4=yes + ;; + esac + + # Adding this requires a known-good setup of shared libraries for + # Sun compiler versions before 5.6, else PIC objects from an old + # archive will be linked into the output, leading to subtle bugs. + if test "$solaris_use_stlport4" != yes; then + postdeps_CXX='-library=Cstd -library=Crun' + fi + ;; + esac + ;; +esac + + +case " $postdeps_CXX " in +*" -lc "*) archive_cmds_need_lc_CXX=no ;; +esac + compiler_lib_search_dirs_CXX= +if test -n "${compiler_lib_search_path_CXX}"; then + compiler_lib_search_dirs_CXX=`echo " ${compiler_lib_search_path_CXX}" | ${SED} -e 's! -L! !g' -e 's!^ !!'` +fi + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + lt_prog_compiler_wl_CXX= +lt_prog_compiler_pic_CXX= +lt_prog_compiler_static_CXX= + + + # C++ specific cases for pic, static, wl, etc. + if test "$GXX" = yes; then + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_CXX='-Bstatic' + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + lt_prog_compiler_pic_CXX='-fPIC' + ;; + m68k) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + lt_prog_compiler_pic_CXX='-m68020 -resident32 -malways-restore-a4' + ;; + esac + ;; + + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + mingw* | cygwin* | os2* | pw32* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + lt_prog_compiler_pic_CXX='-DDLL_EXPORT' + ;; + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic_CXX='-fno-common' + ;; + *djgpp*) + # DJGPP does not support shared libraries at all + lt_prog_compiler_pic_CXX= + ;; + haiku*) + # PIC is the default for Haiku. + # The "-static" flag exists, but is broken. + lt_prog_compiler_static_CXX= + ;; + interix[3-9]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic_CXX=-Kconform_pic + fi + ;; + hpux*) + # PIC is the default for 64-bit PA HP-UX, but not for 32-bit + # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag + # sets the default TLS model and affects inlining. + case $host_cpu in + hppa*64*) + ;; + *) + lt_prog_compiler_pic_CXX='-fPIC' + ;; + esac + ;; + *qnx* | *nto*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + lt_prog_compiler_pic_CXX='-fPIC -shared' + ;; + *) + lt_prog_compiler_pic_CXX='-fPIC' + ;; + esac + else + case $host_os in + aix[4-9]*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_CXX='-Bstatic' + else + lt_prog_compiler_static_CXX='-bnso -bI:/lib/syscalls.exp' + fi + ;; + chorus*) + case $cc_basename in + cxch68*) + # Green Hills C++ Compiler + # _LT_TAGVAR(lt_prog_compiler_static, CXX)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" + ;; + esac + ;; + mingw* | cygwin* | os2* | pw32* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic_CXX='-DDLL_EXPORT' + ;; + dgux*) + case $cc_basename in + ec++*) + lt_prog_compiler_pic_CXX='-KPIC' + ;; + ghcx*) + # Green Hills C++ Compiler + lt_prog_compiler_pic_CXX='-pic' + ;; + *) + ;; + esac + ;; + freebsd* | dragonfly*) + # FreeBSD uses GNU C++ + ;; + hpux9* | hpux10* | hpux11*) + case $cc_basename in + CC*) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX='${wl}-a ${wl}archive' + if test "$host_cpu" != ia64; then + lt_prog_compiler_pic_CXX='+Z' + fi + ;; + aCC*) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX='${wl}-a ${wl}archive' + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic_CXX='+Z' + ;; + esac + ;; + *) + ;; + esac + ;; + interix*) + # This is c89, which is MS Visual C++ (no shared libs) + # Anyone wants to do a port? + ;; + irix5* | irix6* | nonstopux*) + case $cc_basename in + CC*) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX='-non_shared' + # CC pic flag -KPIC is the default. + ;; + *) + ;; + esac + ;; + linux* | k*bsd*-gnu | kopensolaris*-gnu) + case $cc_basename in + KCC*) + # KAI C++ Compiler + lt_prog_compiler_wl_CXX='--backend -Wl,' + lt_prog_compiler_pic_CXX='-fPIC' + ;; + ecpc* ) + # old Intel C++ for x86_64 which still supported -KPIC. + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_pic_CXX='-KPIC' + lt_prog_compiler_static_CXX='-static' + ;; + icpc* ) + # Intel C++, used to be incompatible with GCC. + # ICC 10 doesn't accept -KPIC any more. + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_pic_CXX='-fPIC' + lt_prog_compiler_static_CXX='-static' + ;; + pgCC* | pgcpp*) + # Portland Group C++ compiler + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_pic_CXX='-fpic' + lt_prog_compiler_static_CXX='-Bstatic' + ;; + cxx*) + # Compaq C++ + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + lt_prog_compiler_pic_CXX= + lt_prog_compiler_static_CXX='-non_shared' + ;; + xlc* | xlC* | bgxl[cC]* | mpixl[cC]*) + # IBM XL 8.0, 9.0 on PPC and BlueGene + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_pic_CXX='-qpic' + lt_prog_compiler_static_CXX='-qstaticlink' + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C++ 5.9 + lt_prog_compiler_pic_CXX='-KPIC' + lt_prog_compiler_static_CXX='-Bstatic' + lt_prog_compiler_wl_CXX='-Qoption ld ' + ;; + esac + ;; + esac + ;; + lynxos*) + ;; + m88k*) + ;; + mvs*) + case $cc_basename in + cxx*) + lt_prog_compiler_pic_CXX='-W c,exportall' + ;; + *) + ;; + esac + ;; + netbsd* | netbsdelf*-gnu) + ;; + *qnx* | *nto*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + lt_prog_compiler_pic_CXX='-fPIC -shared' + ;; + osf3* | osf4* | osf5*) + case $cc_basename in + KCC*) + lt_prog_compiler_wl_CXX='--backend -Wl,' + ;; + RCC*) + # Rational C++ 2.4.1 + lt_prog_compiler_pic_CXX='-pic' + ;; + cxx*) + # Digital/Compaq C++ + lt_prog_compiler_wl_CXX='-Wl,' + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + lt_prog_compiler_pic_CXX= + lt_prog_compiler_static_CXX='-non_shared' + ;; + *) + ;; + esac + ;; + psos*) + ;; + solaris*) + case $cc_basename in + CC* | sunCC*) + # Sun C++ 4.2, 5.x and Centerline C++ + lt_prog_compiler_pic_CXX='-KPIC' + lt_prog_compiler_static_CXX='-Bstatic' + lt_prog_compiler_wl_CXX='-Qoption ld ' + ;; + gcx*) + # Green Hills C++ Compiler + lt_prog_compiler_pic_CXX='-PIC' + ;; + *) + ;; + esac + ;; + sunos4*) + case $cc_basename in + CC*) + # Sun C++ 4.x + lt_prog_compiler_pic_CXX='-pic' + lt_prog_compiler_static_CXX='-Bstatic' + ;; + lcc*) + # Lucid + lt_prog_compiler_pic_CXX='-pic' + ;; + *) + ;; + esac + ;; + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + case $cc_basename in + CC*) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_pic_CXX='-KPIC' + lt_prog_compiler_static_CXX='-Bstatic' + ;; + esac + ;; + tandem*) + case $cc_basename in + NCC*) + # NonStop-UX NCC 3.20 + lt_prog_compiler_pic_CXX='-KPIC' + ;; + *) + ;; + esac + ;; + vxworks*) + ;; + *) + lt_prog_compiler_can_build_shared_CXX=no + ;; + esac + fi + +case $host_os in + # For platforms which do not support PIC, -DPIC is meaningless: + *djgpp*) + lt_prog_compiler_pic_CXX= + ;; + *) + lt_prog_compiler_pic_CXX="$lt_prog_compiler_pic_CXX -DPIC" + ;; +esac + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 +$as_echo_n "checking for $compiler option to produce PIC... " >&6; } +if ${lt_cv_prog_compiler_pic_CXX+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_pic_CXX=$lt_prog_compiler_pic_CXX +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_CXX" >&5 +$as_echo "$lt_cv_prog_compiler_pic_CXX" >&6; } +lt_prog_compiler_pic_CXX=$lt_cv_prog_compiler_pic_CXX + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$lt_prog_compiler_pic_CXX"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works" >&5 +$as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works... " >&6; } +if ${lt_cv_prog_compiler_pic_works_CXX+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_pic_works_CXX=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$lt_prog_compiler_pic_CXX -DPIC" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_pic_works_CXX=yes + fi + fi + $RM conftest* + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works_CXX" >&5 +$as_echo "$lt_cv_prog_compiler_pic_works_CXX" >&6; } + +if test x"$lt_cv_prog_compiler_pic_works_CXX" = xyes; then + case $lt_prog_compiler_pic_CXX in + "" | " "*) ;; + *) lt_prog_compiler_pic_CXX=" $lt_prog_compiler_pic_CXX" ;; + esac +else + lt_prog_compiler_pic_CXX= + lt_prog_compiler_can_build_shared_CXX=no +fi + +fi + + + + + +# +# Check to make sure the static flag actually works. +# +wl=$lt_prog_compiler_wl_CXX eval lt_tmp_static_flag=\"$lt_prog_compiler_static_CXX\" +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 +$as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } +if ${lt_cv_prog_compiler_static_works_CXX+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_static_works_CXX=no + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS $lt_tmp_static_flag" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&5 + $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_static_works_CXX=yes + fi + else + lt_cv_prog_compiler_static_works_CXX=yes + fi + fi + $RM -r conftest* + LDFLAGS="$save_LDFLAGS" + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works_CXX" >&5 +$as_echo "$lt_cv_prog_compiler_static_works_CXX" >&6; } + +if test x"$lt_cv_prog_compiler_static_works_CXX" = xyes; then + : +else + lt_prog_compiler_static_CXX= +fi + + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 +$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } +if ${lt_cv_prog_compiler_c_o_CXX+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_c_o_CXX=no + $RM -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + lt_cv_prog_compiler_c_o_CXX=yes + fi + fi + chmod u+w . 2>&5 + $RM conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files + $RM out/* && rmdir out + cd .. + $RM -r conftest + $RM conftest* + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o_CXX" >&5 +$as_echo "$lt_cv_prog_compiler_c_o_CXX" >&6; } + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 +$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } +if ${lt_cv_prog_compiler_c_o_CXX+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_c_o_CXX=no + $RM -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + lt_cv_prog_compiler_c_o_CXX=yes + fi + fi + chmod u+w . 2>&5 + $RM conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files + $RM out/* && rmdir out + cd .. + $RM -r conftest + $RM conftest* + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o_CXX" >&5 +$as_echo "$lt_cv_prog_compiler_c_o_CXX" >&6; } + + + + +hard_links="nottested" +if test "$lt_cv_prog_compiler_c_o_CXX" = no && test "$need_locks" != no; then + # do not overwrite the value of need_locks provided by the user + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5 +$as_echo_n "checking if we can lock with hard links... " >&6; } + hard_links=yes + $RM conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5 +$as_echo "$hard_links" >&6; } + if test "$hard_links" = no; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 +$as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} + need_locks=warn + fi +else + need_locks=no +fi + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +$as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } + + export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + exclude_expsyms_CXX='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' + case $host_os in + aix[4-9]*) + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + # Also, AIX nm treats weak defined symbols like other global defined + # symbols, whereas GNU nm marks them as "W". + if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then + export_symbols_cmds_CXX='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' + else + export_symbols_cmds_CXX='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' + fi + ;; + pw32*) + export_symbols_cmds_CXX="$ltdll_cmds" + ;; + cygwin* | mingw* | cegcc*) + case $cc_basename in + cl*) + exclude_expsyms_CXX='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' + ;; + *) + export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols' + exclude_expsyms_CXX='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname' + ;; + esac + ;; + linux* | k*bsd*-gnu | gnu*) + link_all_deplibs_CXX=no + ;; + *) + export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + ;; + esac + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs_CXX" >&5 +$as_echo "$ld_shlibs_CXX" >&6; } +test "$ld_shlibs_CXX" = no && can_build_shared=no + +with_gnu_ld_CXX=$with_gnu_ld + + + + + + +# +# Do we need to explicitly link libc? +# +case "x$archive_cmds_need_lc_CXX" in +x|xyes) + # Assume -lc should be added + archive_cmds_need_lc_CXX=yes + + if test "$enable_shared" = yes && test "$GCC" = yes; then + case $archive_cmds_CXX in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5 +$as_echo_n "checking whether -lc should be explicitly linked in... " >&6; } +if ${lt_cv_archive_cmds_need_lc_CXX+:} false; then : + $as_echo_n "(cached) " >&6 +else + $RM conftest* + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$lt_prog_compiler_wl_CXX + pic_flag=$lt_prog_compiler_pic_CXX + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$allow_undefined_flag_CXX + allow_undefined_flag_CXX= + if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds_CXX 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5 + (eval $archive_cmds_CXX 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + then + lt_cv_archive_cmds_need_lc_CXX=no + else + lt_cv_archive_cmds_need_lc_CXX=yes + fi + allow_undefined_flag_CXX=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $RM conftest* + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc_CXX" >&5 +$as_echo "$lt_cv_archive_cmds_need_lc_CXX" >&6; } + archive_cmds_need_lc_CXX=$lt_cv_archive_cmds_need_lc_CXX + ;; + esac + fi + ;; +esac + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5 +$as_echo_n "checking dynamic linker characteristics... " >&6; } + +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=".so" +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +case $host_os in +aix3*) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='${libname}${release}${shared_ext}$major' + ;; + +aix[4-9]*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test "$host_cpu" = ia64; then + # AIX 5 supports IA64 + library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line `#! .'. This would cause the generated library to + # depend on `.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[01] | aix4.[01].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # AIX (on Power*) has no versioning support, so currently we can not hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + if test "$aix_use_runtimelinking" = yes; then + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + else + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='${libname}${release}.a $libname.a' + soname_spec='${libname}${release}${shared_ext}$major' + fi + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + case $host_cpu in + powerpc) + # Since July 2007 AmigaOS4 officially supports .so libraries. + # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + ;; + m68k) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + esac + ;; + +beos*) + library_names_spec='${libname}${shared_ext}' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi[45]*) + version_type=linux # correct to gnu/linux during the next big refactor + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32* | cegcc*) + version_type=windows + shrext_cmds=".dll" + need_version=no + need_lib_prefix=no + + case $GCC,$cc_basename in + yes,*) + # gcc + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname~ + if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then + eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; + fi' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $RM \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + + ;; + mingw* | cegcc*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + ;; + esac + dynamic_linker='Win32 ld.exe' + ;; + + *,cl*) + # Native MSVC + libname_spec='$name' + soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + library_names_spec='${libname}.dll.lib' + + case $build_os in + mingw*) + sys_lib_search_path_spec= + lt_save_ifs=$IFS + IFS=';' + for lt_path in $LIB + do + IFS=$lt_save_ifs + # Let DOS variable expansion print the short 8.3 style file name. + lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` + sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" + done + IFS=$lt_save_ifs + # Convert to MSYS style. + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'` + ;; + cygwin*) + # Convert to unix form, then to dos form, then back to unix form + # but this time dos style (no spaces!) so that the unix form looks + # like /cygdrive/c/PROGRA~1:/cygdr... + sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` + sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` + sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + ;; + *) + sys_lib_search_path_spec="$LIB" + if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then + # It is most probably a Windows format PATH. + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + # FIXME: find the short name or the path components, as spaces are + # common. (e.g. "Program Files" -> "PROGRA~1") + ;; + esac + + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $RM \$dlpath' + shlibpath_overrides_runpath=yes + dynamic_linker='Win32 link.exe' + ;; + + *) + # Assume MSVC wrapper + library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' + dynamic_linker='Win32 ld.exe' + ;; + esac + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' + soname_spec='${libname}${release}${major}$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' + + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd* | dragonfly*) + # DragonFly does not have aout. When/if they implement a new + # versioning mechanism, adjust this. + if test -x /usr/bin/objformat; then + objformat=`/usr/bin/objformat` + else + case $host_os in + freebsd[23].*) objformat=aout ;; + *) objformat=elf ;; + esac + fi + version_type=freebsd-$objformat + case $version_type in + freebsd-elf*) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' + need_version=yes + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2.*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.[01]* | freebsdelf3.[01]*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ + freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + *) # from 4.6 on, and DragonFly + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + esac + ;; + +gnu*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +haiku*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + dynamic_linker="$host_os runtime_loader" + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LIBRARY_PATH + shlibpath_overrides_runpath=yes + sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case $host_cpu in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + if test "X$HPUX_IA64_MODE" = X32; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + fi + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555, ... + postinstall_cmds='chmod 555 $lib' + # or fails outright, so override atomically: + install_override_mode=555 + ;; + +interix[3-9]*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test "$lt_cv_prog_gnu_ld" = yes; then + version_type=linux # correct to gnu/linux during the next big refactor + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +# This must be glibc/ELF. +linux* | k*bsd*-gnu | kopensolaris*-gnu) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + + # Some binutils ld are patched to set DT_RUNPATH + if ${lt_cv_shlibpath_overrides_runpath+:} false; then : + $as_echo_n "(cached) " >&6 +else + lt_cv_shlibpath_overrides_runpath=no + save_LDFLAGS=$LDFLAGS + save_libdir=$libdir + eval "libdir=/foo; wl=\"$lt_prog_compiler_wl_CXX\"; \ + LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec_CXX\"" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_cxx_try_link "$LINENO"; then : + if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then : + lt_cv_shlibpath_overrides_runpath=yes +fi +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + LDFLAGS=$save_LDFLAGS + libdir=$save_libdir + +fi + + shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath + + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + + # Append ld.so.conf contents to the search path + if test -f /etc/ld.so.conf; then + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsdelf*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='NetBSD ld.elf_so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +*nto* | *qnx*) + version_type=qnx + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='ldqnx.so' + ;; + +openbsd*) + version_type=sunos + sys_lib_dlsearch_path_spec="/usr/lib" + need_lib_prefix=no + # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. + case $host_os in + openbsd3.3 | openbsd3.3.*) need_version=yes ;; + *) need_version=no ;; + esac + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + case $host_os in + openbsd2.[89] | openbsd2.[89].*) + shlibpath_overrides_runpath=no + ;; + *) + shlibpath_overrides_runpath=yes + ;; + esac + else + shlibpath_overrides_runpath=yes + fi + ;; + +os2*) + libname_spec='$name' + shrext_cmds=".dll" + need_lib_prefix=no + library_names_spec='$libname${shared_ext} $libname.a' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=LIBPATH + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" + ;; + +rdos*) + dynamic_linker=no + ;; + +solaris*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test "$with_gnu_ld" = yes; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.3*) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec ;then + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' + soname_spec='$libname${shared_ext}.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + version_type=freebsd-elf + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + if test "$with_gnu_ld" = yes; then + sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' + else + sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' + case $host_os in + sco3.2v5*) + sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" + ;; + esac + fi + sys_lib_dlsearch_path_spec='/usr/lib' + ;; + +tpf*) + # TPF is a cross-target only. Preferred cross-host = GNU/Linux. + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +uts4*) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 +$as_echo "$dynamic_linker" >&6; } +test "$dynamic_linker" = no && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test "$GCC" = yes; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then + sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" +fi +if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then + sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" +fi + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5 +$as_echo_n "checking how to hardcode library paths into programs... " >&6; } +hardcode_action_CXX= +if test -n "$hardcode_libdir_flag_spec_CXX" || + test -n "$runpath_var_CXX" || + test "X$hardcode_automatic_CXX" = "Xyes" ; then + + # We can hardcode non-existent directories. + if test "$hardcode_direct_CXX" != no && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test "$_LT_TAGVAR(hardcode_shlibpath_var, CXX)" != no && + test "$hardcode_minus_L_CXX" != no; then + # Linking always hardcodes the temporary library directory. + hardcode_action_CXX=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + hardcode_action_CXX=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + hardcode_action_CXX=unsupported +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action_CXX" >&5 +$as_echo "$hardcode_action_CXX" >&6; } + +if test "$hardcode_action_CXX" = relink || + test "$inherit_rpath_CXX" = yes; then + # Fast installation is not supported + enable_fast_install=no +elif test "$shlibpath_overrides_runpath" = yes || + test "$enable_shared" = no; then + # Fast installation is not necessary + enable_fast_install=needless +fi + + + + + + + + fi # test -n "$compiler" + + CC=$lt_save_CC + CFLAGS=$lt_save_CFLAGS + LDCXX=$LD + LD=$lt_save_LD + GCC=$lt_save_GCC + with_gnu_ld=$lt_save_with_gnu_ld + lt_cv_path_LDCXX=$lt_cv_path_LD + lt_cv_path_LD=$lt_save_path_LD + lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld + lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld +fi # test "$_lt_caught_CXX_error" != yes + +ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + + + + + + + + + + + + + + + + ac_config_commands="$ac_config_commands libtool" + + + + +# Only expand once: + + + +# TODO(chandlerc@google.com): Currently we aren't running the Python tests +# against the interpreter detected by AM_PATH_PYTHON, and so we condition +# HAVE_PYTHON by requiring "python" to be in the PATH, and that interpreter's +# version to be >= 2.3. This will allow the scripts to use a "/usr/bin/env" +# hashbang. +PYTHON= # We *do not* allow the user to specify a python interpreter +# Extract the first word of "python", so it can be a program name with args. +set dummy python; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_PYTHON+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $PYTHON in + [\\/]* | ?:[\\/]*) + ac_cv_path_PYTHON="$PYTHON" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_PYTHON="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + test -z "$ac_cv_path_PYTHON" && ac_cv_path_PYTHON=":" + ;; +esac +fi +PYTHON=$ac_cv_path_PYTHON +if test -n "$PYTHON"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON" >&5 +$as_echo "$PYTHON" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +if test "$PYTHON" != ":"; then : + prog="import sys +# split strings by '.' and convert to numeric. Append some zeros +# because we need at least 4 digits for the hex conversion. +# map returns an iterator in Python 3.0 and a list in 2.x +minver = list(map(int, '2.3'.split('.'))) + [0, 0, 0] +minverhex = 0 +# xrange is not present in Python 3.0 and range returns an iterator +for i in list(range(0, 4)): minverhex = (minverhex << 8) + minver[i] +sys.exit(sys.hexversion < minverhex)" + if { echo "$as_me:$LINENO: $PYTHON -c "$prog"" >&5 + ($PYTHON -c "$prog") >&5 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then : + : +else + PYTHON=":" +fi +fi + if test "$PYTHON" != ":"; then + HAVE_PYTHON_TRUE= + HAVE_PYTHON_FALSE='#' +else + HAVE_PYTHON_TRUE='#' + HAVE_PYTHON_FALSE= +fi + + +# Configure pthreads. + +# Check whether --with-pthreads was given. +if test "${with_pthreads+set}" = set; then : + withval=$with_pthreads; with_pthreads=$withval +else + with_pthreads=check +fi + + +have_pthreads=no +if test "x$with_pthreads" != "xno"; then : + + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +acx_pthread_ok=no + +# We used to check for pthread.h first, but this fails if pthread.h +# requires special compiler flags (e.g. on True64 or Sequent). +# It gets checked for in the link test anyway. + +# First of all, check if the user has set any of the PTHREAD_LIBS, +# etcetera environment variables, and if threads linking works using +# them: +if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then + save_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + save_LIBS="$LIBS" + LIBS="$PTHREAD_LIBS $LIBS" + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS" >&5 +$as_echo_n "checking for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char pthread_join (); +int +main () +{ +return pthread_join (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + acx_pthread_ok=yes +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $acx_pthread_ok" >&5 +$as_echo "$acx_pthread_ok" >&6; } + if test x"$acx_pthread_ok" = xno; then + PTHREAD_LIBS="" + PTHREAD_CFLAGS="" + fi + LIBS="$save_LIBS" + CFLAGS="$save_CFLAGS" +fi + +# We must check for the threads library under a number of different +# names; the ordering is very important because some systems +# (e.g. DEC) have both -lpthread and -lpthreads, where one of the +# libraries is broken (non-POSIX). + +# Create a list of thread flags to try. Items starting with a "-" are +# C compiler flags, and other items are library names, except for "none" +# which indicates that we try without any flags at all, and "pthread-config" +# which is a program returning the flags for the Pth emulation library. + +acx_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config" + +# The ordering *is* (sometimes) important. Some notes on the +# individual items follow: + +# pthreads: AIX (must check this before -lpthread) +# none: in case threads are in libc; should be tried before -Kthread and +# other compiler flags to prevent continual compiler warnings +# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h) +# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able) +# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread) +# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads) +# -pthreads: Solaris/gcc +# -mthreads: Mingw32/gcc, Lynx/gcc +# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it +# doesn't hurt to check since this sometimes defines pthreads too; +# also defines -D_REENTRANT) +# ... -mt is also the pthreads flag for HP/aCC +# pthread: Linux, etcetera +# --thread-safe: KAI C++ +# pthread-config: use pthread-config program (for GNU Pth library) + +case "${host_cpu}-${host_os}" in + *solaris*) + + # On Solaris (at least, for some versions), libc contains stubbed + # (non-functional) versions of the pthreads routines, so link-based + # tests will erroneously succeed. (We need to link with -pthreads/-mt/ + # -lpthread.) (The stubs are missing pthread_cleanup_push, or rather + # a function called by this macro, so we could check for that, but + # who knows whether they'll stub that too in a future libc.) So, + # we'll just look for -pthreads and -lpthread first: + + acx_pthread_flags="-pthreads pthread -mt -pthread $acx_pthread_flags" + ;; +esac + +if test x"$acx_pthread_ok" = xno; then +for flag in $acx_pthread_flags; do + + case $flag in + none) + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether pthreads work without any flags" >&5 +$as_echo_n "checking whether pthreads work without any flags... " >&6; } + ;; + + -*) + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether pthreads work with $flag" >&5 +$as_echo_n "checking whether pthreads work with $flag... " >&6; } + PTHREAD_CFLAGS="$flag" + ;; + + pthread-config) + # Extract the first word of "pthread-config", so it can be a program name with args. +set dummy pthread-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_acx_pthread_config+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$acx_pthread_config"; then + ac_cv_prog_acx_pthread_config="$acx_pthread_config" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_acx_pthread_config="yes" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + test -z "$ac_cv_prog_acx_pthread_config" && ac_cv_prog_acx_pthread_config="no" +fi +fi +acx_pthread_config=$ac_cv_prog_acx_pthread_config +if test -n "$acx_pthread_config"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $acx_pthread_config" >&5 +$as_echo "$acx_pthread_config" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + if test x"$acx_pthread_config" = xno; then continue; fi + PTHREAD_CFLAGS="`pthread-config --cflags`" + PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`" + ;; + + *) + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for the pthreads library -l$flag" >&5 +$as_echo_n "checking for the pthreads library -l$flag... " >&6; } + PTHREAD_LIBS="-l$flag" + ;; + esac + + save_LIBS="$LIBS" + save_CFLAGS="$CFLAGS" + LIBS="$PTHREAD_LIBS $LIBS" + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + + # Check for various functions. We must include pthread.h, + # since some functions may be macros. (On the Sequent, we + # need a special flag -Kthread to make this header compile.) + # We check for pthread_join because it is in -lpthread on IRIX + # while pthread_create is in libc. We check for pthread_attr_init + # due to DEC craziness with -lpthreads. We check for + # pthread_cleanup_push because it is one of the few pthread + # functions on Solaris that doesn't have a non-functional libc stub. + # We try pthread_create on general principles. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +pthread_t th; pthread_join(th, 0); + pthread_attr_init(0); pthread_cleanup_push(0, 0); + pthread_create(0,0,0,0); pthread_cleanup_pop(0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + acx_pthread_ok=yes +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + + LIBS="$save_LIBS" + CFLAGS="$save_CFLAGS" + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $acx_pthread_ok" >&5 +$as_echo "$acx_pthread_ok" >&6; } + if test "x$acx_pthread_ok" = xyes; then + break; + fi + + PTHREAD_LIBS="" + PTHREAD_CFLAGS="" +done +fi + +# Various other checks: +if test "x$acx_pthread_ok" = xyes; then + save_LIBS="$LIBS" + LIBS="$PTHREAD_LIBS $LIBS" + save_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + + # Detect AIX lossage: JOINABLE attribute is called UNDETACHED. + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for joinable pthread attribute" >&5 +$as_echo_n "checking for joinable pthread attribute... " >&6; } + attr_name=unknown + for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +int attr=$attr; return attr; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + attr_name=$attr; break +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + done + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $attr_name" >&5 +$as_echo "$attr_name" >&6; } + if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then + +cat >>confdefs.h <<_ACEOF +#define PTHREAD_CREATE_JOINABLE $attr_name +_ACEOF + + fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if more special flags are required for pthreads" >&5 +$as_echo_n "checking if more special flags are required for pthreads... " >&6; } + flag=no + case "${host_cpu}-${host_os}" in + *-aix* | *-freebsd* | *-darwin*) flag="-D_THREAD_SAFE";; + *solaris* | *-osf* | *-hpux*) flag="-D_REENTRANT";; + esac + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${flag}" >&5 +$as_echo "${flag}" >&6; } + if test "x$flag" != xno; then + PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS" + fi + + LIBS="$save_LIBS" + CFLAGS="$save_CFLAGS" + # More AIX lossage: must compile with xlc_r or cc_r + if test x"$GCC" != xyes; then + for ac_prog in xlc_r cc_r +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_PTHREAD_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$PTHREAD_CC"; then + ac_cv_prog_PTHREAD_CC="$PTHREAD_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_PTHREAD_CC="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +PTHREAD_CC=$ac_cv_prog_PTHREAD_CC +if test -n "$PTHREAD_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PTHREAD_CC" >&5 +$as_echo "$PTHREAD_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$PTHREAD_CC" && break +done +test -n "$PTHREAD_CC" || PTHREAD_CC="${CC}" + + else + PTHREAD_CC=$CC + fi + + # The next part tries to detect GCC inconsistency with -shared on some + # architectures and systems. The problem is that in certain + # configurations, when -shared is specified, GCC "forgets" to + # internally use various flags which are still necessary. + + # + # Prepare the flags + # + save_CFLAGS="$CFLAGS" + save_LIBS="$LIBS" + save_CC="$CC" + + # Try with the flags determined by the earlier checks. + # + # -Wl,-z,defs forces link-time symbol resolution, so that the + # linking checks with -shared actually have any value + # + # FIXME: -fPIC is required for -shared on many architectures, + # so we specify it here, but the right way would probably be to + # properly detect whether it is actually required. + CFLAGS="-shared -fPIC -Wl,-z,defs $CFLAGS $PTHREAD_CFLAGS" + LIBS="$PTHREAD_LIBS $LIBS" + CC="$PTHREAD_CC" + + # In order not to create several levels of indentation, we test + # the value of "$done" until we find the cure or run out of ideas. + done="no" + + # First, make sure the CFLAGS we added are actually accepted by our + # compiler. If not (and OS X's ld, for instance, does not accept -z), + # then we can't do this test. + if test x"$done" = xno; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to check for GCC pthread/shared inconsistencies" >&5 +$as_echo_n "checking whether to check for GCC pthread/shared inconsistencies... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + +else + done=yes +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + + if test "x$done" = xyes ; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + fi + fi + + if test x"$done" = xno; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -pthread is sufficient with -shared" >&5 +$as_echo_n "checking whether -pthread is sufficient with -shared... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +pthread_t th; pthread_join(th, 0); + pthread_attr_init(0); pthread_cleanup_push(0, 0); + pthread_create(0,0,0,0); pthread_cleanup_pop(0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + done=yes +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + + if test "x$done" = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + fi + fi + + # + # Linux gcc on some architectures such as mips/mipsel forgets + # about -lpthread + # + if test x"$done" = xno; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lpthread fixes that" >&5 +$as_echo_n "checking whether -lpthread fixes that... " >&6; } + LIBS="-lpthread $PTHREAD_LIBS $save_LIBS" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +pthread_t th; pthread_join(th, 0); + pthread_attr_init(0); pthread_cleanup_push(0, 0); + pthread_create(0,0,0,0); pthread_cleanup_pop(0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + done=yes +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + + if test "x$done" = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + PTHREAD_LIBS="-lpthread $PTHREAD_LIBS" + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + fi + fi + # + # FreeBSD 4.10 gcc forgets to use -lc_r instead of -lc + # + if test x"$done" = xno; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc_r fixes that" >&5 +$as_echo_n "checking whether -lc_r fixes that... " >&6; } + LIBS="-lc_r $PTHREAD_LIBS $save_LIBS" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +pthread_t th; pthread_join(th, 0); + pthread_attr_init(0); pthread_cleanup_push(0, 0); + pthread_create(0,0,0,0); pthread_cleanup_pop(0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + done=yes +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + + if test "x$done" = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + PTHREAD_LIBS="-lc_r $PTHREAD_LIBS" + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + fi + fi + if test x"$done" = xno; then + # OK, we have run out of ideas + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Impossible to determine how to use pthreads with shared libraries" >&5 +$as_echo "$as_me: WARNING: Impossible to determine how to use pthreads with shared libraries" >&2;} + + # so it's not safe to assume that we may use pthreads + acx_pthread_ok=no + fi + + CFLAGS="$save_CFLAGS" + LIBS="$save_LIBS" + CC="$save_CC" +else + PTHREAD_CC="$CC" +fi + + + + + +# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND: +if test x"$acx_pthread_ok" = xyes; then + +$as_echo "#define HAVE_PTHREAD 1" >>confdefs.h + + : +else + acx_pthread_ok=no + if test "x$with_pthreads" != "xcheck"; then : + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "--with-pthreads was specified, but unable to be used +See \`config.log' for more details" "$LINENO" 5; } +fi +fi +ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu + + + have_pthreads="$acx_pthread_ok" +fi + if test "x$have_pthreads" = "xyes"; then + HAVE_PTHREADS_TRUE= + HAVE_PTHREADS_FALSE='#' +else + HAVE_PTHREADS_TRUE='#' + HAVE_PTHREADS_FALSE= +fi + + + + +# TODO(chandlerc@google.com) Check for the necessary system headers. + +# TODO(chandlerc@google.com) Check the types, structures, and other compiler +# and architecture characteristics. + +# Output the generated files. No further autoconf macros may be used. +cat >confcache <<\_ACEOF +# This file is a shell script that caches the results of configure +# tests run on this system so they can be shared between configure +# scripts and configure runs, see configure's option --config-cache. +# It is not useful on other systems. If it contains results you don't +# want to keep, you may remove or edit it. +# +# config.status only pays attention to the cache file if you give it +# the --recheck option to rerun configure. +# +# `ac_cv_env_foo' variables (set or unset) will be overridden when +# loading this file, other *unset* `ac_cv_foo' will be assigned the +# following values. + +_ACEOF + +# The following way of writing the cache mishandles newlines in values, +# but we know of no workaround that is simple, portable, and efficient. +# So, we kill variables containing newlines. +# Ultrix sh set writes to stderr and can't be redirected directly, +# and sets the high bit in the cache file unless we assign to the vars. +( + for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + + (set) 2>&1 | + case $as_nl`(ac_space=' '; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + # `set' does not quote correctly, so add quotes: double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \. + sed -n \ + "s/'/'\\\\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" + ;; #( + *) + # `set' quotes correctly as required by POSIX, so do not add quotes. + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) | + sed ' + /^ac_cv_env_/b end + t clear + :clear + s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ + t end + s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ + :end' >>confcache +if diff "$cache_file" confcache >/dev/null 2>&1; then :; else + if test -w "$cache_file"; then + if test "x$cache_file" != "x/dev/null"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 +$as_echo "$as_me: updating cache $cache_file" >&6;} + if test ! -f "$cache_file" || test -h "$cache_file"; then + cat confcache >"$cache_file" + else + case $cache_file in #( + */* | ?:*) + mv -f confcache "$cache_file"$$ && + mv -f "$cache_file"$$ "$cache_file" ;; #( + *) + mv -f confcache "$cache_file" ;; + esac + fi + fi + else + { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 +$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} + fi +fi +rm -f confcache + +test "x$prefix" = xNONE && prefix=$ac_default_prefix +# Let make expand exec_prefix. +test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' + +DEFS=-DHAVE_CONFIG_H + +ac_libobjs= +ac_ltlibobjs= +U= +for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue + # 1. Remove the extension, and $U if already installed. + ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' + ac_i=`$as_echo "$ac_i" | sed "$ac_script"` + # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR + # will be set to the directory where LIBOBJS objects are built. + as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" + as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' +done +LIBOBJS=$ac_libobjs + +LTLIBOBJS=$ac_ltlibobjs + + + if test -n "$EXEEXT"; then + am__EXEEXT_TRUE= + am__EXEEXT_FALSE='#' +else + am__EXEEXT_TRUE='#' + am__EXEEXT_FALSE= +fi + +if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then + as_fn_error $? "conditional \"AMDEP\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then + as_fn_error $? "conditional \"am__fastdepCC\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${am__fastdepCXX_TRUE}" && test -z "${am__fastdepCXX_FALSE}"; then + as_fn_error $? "conditional \"am__fastdepCXX\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${HAVE_PYTHON_TRUE}" && test -z "${HAVE_PYTHON_FALSE}"; then + as_fn_error $? "conditional \"HAVE_PYTHON\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi +if test -z "${HAVE_PTHREADS_TRUE}" && test -z "${HAVE_PTHREADS_FALSE}"; then + as_fn_error $? "conditional \"HAVE_PTHREADS\" was never defined. +Usually this means the macro was only invoked conditionally." "$LINENO" 5 +fi + +: "${CONFIG_STATUS=./config.status}" +ac_write_fail=0 +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files $CONFIG_STATUS" +{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} +as_write_fail=0 +cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 +#! $SHELL +# Generated by $as_me. +# Run this file to recreate the current configuration. +# Compiler output produced by configure, useful for debugging +# configure, is in config.log if it exists. + +debug=false +ac_cs_recheck=false +ac_cs_silent=false + +SHELL=\${CONFIG_SHELL-$SHELL} +export SHELL +_ASEOF +cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -p' + fi +else + as_ln_s='cp -p' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +if test -x / >/dev/null 2>&1; then + as_test_x='test -x' +else + if ls -dL / >/dev/null 2>&1; then + as_ls_L_option=L + else + as_ls_L_option= + fi + as_test_x=' + eval sh -c '\'' + if test -d "$1"; then + test -d "$1/."; + else + case $1 in #( + -*)set "./$1";; + esac; + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( + ???[sx]*):;;*)false;;esac;fi + '\'' sh + ' +fi +as_executable_p=$as_test_x + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +exec 6>&1 +## ----------------------------------- ## +## Main body of $CONFIG_STATUS script. ## +## ----------------------------------- ## +_ASEOF +test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# Save the log message, to keep $0 and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. +ac_log=" +This file was extended by Google C++ Testing Framework $as_me 1.7.0, which was +generated by GNU Autoconf 2.68. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + +_ACEOF + +case $ac_config_files in *" +"*) set x $ac_config_files; shift; ac_config_files=$*;; +esac + +case $ac_config_headers in *" +"*) set x $ac_config_headers; shift; ac_config_headers=$*;; +esac + + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# Files that config.status was made for. +config_files="$ac_config_files" +config_headers="$ac_config_headers" +config_commands="$ac_config_commands" + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +ac_cs_usage="\ +\`$as_me' instantiates files and other configuration actions +from templates according to the current configuration. Unless the files +and actions are specified as TAGs, all are instantiated by default. + +Usage: $0 [OPTION]... [TAG]... + + -h, --help print this help, then exit + -V, --version print version number and configuration settings, then exit + --config print configuration, then exit + -q, --quiet, --silent + do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE + +Configuration files: +$config_files + +Configuration headers: +$config_headers + +Configuration commands: +$config_commands + +Report bugs to ." + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" +ac_cs_version="\\ +Google C++ Testing Framework config.status 1.7.0 +configured by $0, generated by GNU Autoconf 2.68, + with options \\"\$ac_cs_config\\" + +Copyright (C) 2010 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." + +ac_pwd='$ac_pwd' +srcdir='$srcdir' +INSTALL='$INSTALL' +MKDIR_P='$MKDIR_P' +AWK='$AWK' +test -n "\$AWK" || AWK=awk +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=?*) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` + ac_shift=: + ;; + --*=) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg= + ac_shift=: + ;; + *) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + esac + + case $ac_option in + # Handling of the options. + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + $as_echo "$ac_cs_version"; exit ;; + --config | --confi | --conf | --con | --co | --c ) + $as_echo "$ac_cs_config"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + '') as_fn_error $? "missing file argument" ;; + esac + as_fn_append CONFIG_FILES " '$ac_optarg'" + ac_need_defaults=false;; + --header | --heade | --head | --hea ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append CONFIG_HEADERS " '$ac_optarg'" + ac_need_defaults=false;; + --he | --h) + # Conflict between --help and --header + as_fn_error $? "ambiguous option: \`$1' +Try \`$0 --help' for more information.";; + --help | --hel | -h ) + $as_echo "$ac_cs_usage"; exit ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) as_fn_error $? "unrecognized option: \`$1' +Try \`$0 --help' for more information." ;; + + *) as_fn_append ac_config_targets " $1" + ac_need_defaults=false ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +if \$ac_cs_recheck; then + set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' + export CONFIG_SHELL + exec "\$@" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + $as_echo "$ac_log" +} >&5 + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# +# INIT-COMMANDS +# +AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir" + + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +sed_quote_subst='$sed_quote_subst' +double_quote_subst='$double_quote_subst' +delay_variable_subst='$delay_variable_subst' +macro_version='`$ECHO "$macro_version" | $SED "$delay_single_quote_subst"`' +macro_revision='`$ECHO "$macro_revision" | $SED "$delay_single_quote_subst"`' +enable_shared='`$ECHO "$enable_shared" | $SED "$delay_single_quote_subst"`' +enable_static='`$ECHO "$enable_static" | $SED "$delay_single_quote_subst"`' +pic_mode='`$ECHO "$pic_mode" | $SED "$delay_single_quote_subst"`' +enable_fast_install='`$ECHO "$enable_fast_install" | $SED "$delay_single_quote_subst"`' +SHELL='`$ECHO "$SHELL" | $SED "$delay_single_quote_subst"`' +ECHO='`$ECHO "$ECHO" | $SED "$delay_single_quote_subst"`' +PATH_SEPARATOR='`$ECHO "$PATH_SEPARATOR" | $SED "$delay_single_quote_subst"`' +host_alias='`$ECHO "$host_alias" | $SED "$delay_single_quote_subst"`' +host='`$ECHO "$host" | $SED "$delay_single_quote_subst"`' +host_os='`$ECHO "$host_os" | $SED "$delay_single_quote_subst"`' +build_alias='`$ECHO "$build_alias" | $SED "$delay_single_quote_subst"`' +build='`$ECHO "$build" | $SED "$delay_single_quote_subst"`' +build_os='`$ECHO "$build_os" | $SED "$delay_single_quote_subst"`' +SED='`$ECHO "$SED" | $SED "$delay_single_quote_subst"`' +Xsed='`$ECHO "$Xsed" | $SED "$delay_single_quote_subst"`' +GREP='`$ECHO "$GREP" | $SED "$delay_single_quote_subst"`' +EGREP='`$ECHO "$EGREP" | $SED "$delay_single_quote_subst"`' +FGREP='`$ECHO "$FGREP" | $SED "$delay_single_quote_subst"`' +LD='`$ECHO "$LD" | $SED "$delay_single_quote_subst"`' +NM='`$ECHO "$NM" | $SED "$delay_single_quote_subst"`' +LN_S='`$ECHO "$LN_S" | $SED "$delay_single_quote_subst"`' +max_cmd_len='`$ECHO "$max_cmd_len" | $SED "$delay_single_quote_subst"`' +ac_objext='`$ECHO "$ac_objext" | $SED "$delay_single_quote_subst"`' +exeext='`$ECHO "$exeext" | $SED "$delay_single_quote_subst"`' +lt_unset='`$ECHO "$lt_unset" | $SED "$delay_single_quote_subst"`' +lt_SP2NL='`$ECHO "$lt_SP2NL" | $SED "$delay_single_quote_subst"`' +lt_NL2SP='`$ECHO "$lt_NL2SP" | $SED "$delay_single_quote_subst"`' +lt_cv_to_host_file_cmd='`$ECHO "$lt_cv_to_host_file_cmd" | $SED "$delay_single_quote_subst"`' +lt_cv_to_tool_file_cmd='`$ECHO "$lt_cv_to_tool_file_cmd" | $SED "$delay_single_quote_subst"`' +reload_flag='`$ECHO "$reload_flag" | $SED "$delay_single_quote_subst"`' +reload_cmds='`$ECHO "$reload_cmds" | $SED "$delay_single_quote_subst"`' +OBJDUMP='`$ECHO "$OBJDUMP" | $SED "$delay_single_quote_subst"`' +deplibs_check_method='`$ECHO "$deplibs_check_method" | $SED "$delay_single_quote_subst"`' +file_magic_cmd='`$ECHO "$file_magic_cmd" | $SED "$delay_single_quote_subst"`' +file_magic_glob='`$ECHO "$file_magic_glob" | $SED "$delay_single_quote_subst"`' +want_nocaseglob='`$ECHO "$want_nocaseglob" | $SED "$delay_single_quote_subst"`' +DLLTOOL='`$ECHO "$DLLTOOL" | $SED "$delay_single_quote_subst"`' +sharedlib_from_linklib_cmd='`$ECHO "$sharedlib_from_linklib_cmd" | $SED "$delay_single_quote_subst"`' +AR='`$ECHO "$AR" | $SED "$delay_single_quote_subst"`' +AR_FLAGS='`$ECHO "$AR_FLAGS" | $SED "$delay_single_quote_subst"`' +archiver_list_spec='`$ECHO "$archiver_list_spec" | $SED "$delay_single_quote_subst"`' +STRIP='`$ECHO "$STRIP" | $SED "$delay_single_quote_subst"`' +RANLIB='`$ECHO "$RANLIB" | $SED "$delay_single_quote_subst"`' +old_postinstall_cmds='`$ECHO "$old_postinstall_cmds" | $SED "$delay_single_quote_subst"`' +old_postuninstall_cmds='`$ECHO "$old_postuninstall_cmds" | $SED "$delay_single_quote_subst"`' +old_archive_cmds='`$ECHO "$old_archive_cmds" | $SED "$delay_single_quote_subst"`' +lock_old_archive_extraction='`$ECHO "$lock_old_archive_extraction" | $SED "$delay_single_quote_subst"`' +CC='`$ECHO "$CC" | $SED "$delay_single_quote_subst"`' +CFLAGS='`$ECHO "$CFLAGS" | $SED "$delay_single_quote_subst"`' +compiler='`$ECHO "$compiler" | $SED "$delay_single_quote_subst"`' +GCC='`$ECHO "$GCC" | $SED "$delay_single_quote_subst"`' +lt_cv_sys_global_symbol_pipe='`$ECHO "$lt_cv_sys_global_symbol_pipe" | $SED "$delay_single_quote_subst"`' +lt_cv_sys_global_symbol_to_cdecl='`$ECHO "$lt_cv_sys_global_symbol_to_cdecl" | $SED "$delay_single_quote_subst"`' +lt_cv_sys_global_symbol_to_c_name_address='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address" | $SED "$delay_single_quote_subst"`' +lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address_lib_prefix" | $SED "$delay_single_quote_subst"`' +nm_file_list_spec='`$ECHO "$nm_file_list_spec" | $SED "$delay_single_quote_subst"`' +lt_sysroot='`$ECHO "$lt_sysroot" | $SED "$delay_single_quote_subst"`' +objdir='`$ECHO "$objdir" | $SED "$delay_single_quote_subst"`' +MAGIC_CMD='`$ECHO "$MAGIC_CMD" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_no_builtin_flag='`$ECHO "$lt_prog_compiler_no_builtin_flag" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_pic='`$ECHO "$lt_prog_compiler_pic" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_wl='`$ECHO "$lt_prog_compiler_wl" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_static='`$ECHO "$lt_prog_compiler_static" | $SED "$delay_single_quote_subst"`' +lt_cv_prog_compiler_c_o='`$ECHO "$lt_cv_prog_compiler_c_o" | $SED "$delay_single_quote_subst"`' +need_locks='`$ECHO "$need_locks" | $SED "$delay_single_quote_subst"`' +MANIFEST_TOOL='`$ECHO "$MANIFEST_TOOL" | $SED "$delay_single_quote_subst"`' +DSYMUTIL='`$ECHO "$DSYMUTIL" | $SED "$delay_single_quote_subst"`' +NMEDIT='`$ECHO "$NMEDIT" | $SED "$delay_single_quote_subst"`' +LIPO='`$ECHO "$LIPO" | $SED "$delay_single_quote_subst"`' +OTOOL='`$ECHO "$OTOOL" | $SED "$delay_single_quote_subst"`' +OTOOL64='`$ECHO "$OTOOL64" | $SED "$delay_single_quote_subst"`' +libext='`$ECHO "$libext" | $SED "$delay_single_quote_subst"`' +shrext_cmds='`$ECHO "$shrext_cmds" | $SED "$delay_single_quote_subst"`' +extract_expsyms_cmds='`$ECHO "$extract_expsyms_cmds" | $SED "$delay_single_quote_subst"`' +archive_cmds_need_lc='`$ECHO "$archive_cmds_need_lc" | $SED "$delay_single_quote_subst"`' +enable_shared_with_static_runtimes='`$ECHO "$enable_shared_with_static_runtimes" | $SED "$delay_single_quote_subst"`' +export_dynamic_flag_spec='`$ECHO "$export_dynamic_flag_spec" | $SED "$delay_single_quote_subst"`' +whole_archive_flag_spec='`$ECHO "$whole_archive_flag_spec" | $SED "$delay_single_quote_subst"`' +compiler_needs_object='`$ECHO "$compiler_needs_object" | $SED "$delay_single_quote_subst"`' +old_archive_from_new_cmds='`$ECHO "$old_archive_from_new_cmds" | $SED "$delay_single_quote_subst"`' +old_archive_from_expsyms_cmds='`$ECHO "$old_archive_from_expsyms_cmds" | $SED "$delay_single_quote_subst"`' +archive_cmds='`$ECHO "$archive_cmds" | $SED "$delay_single_quote_subst"`' +archive_expsym_cmds='`$ECHO "$archive_expsym_cmds" | $SED "$delay_single_quote_subst"`' +module_cmds='`$ECHO "$module_cmds" | $SED "$delay_single_quote_subst"`' +module_expsym_cmds='`$ECHO "$module_expsym_cmds" | $SED "$delay_single_quote_subst"`' +with_gnu_ld='`$ECHO "$with_gnu_ld" | $SED "$delay_single_quote_subst"`' +allow_undefined_flag='`$ECHO "$allow_undefined_flag" | $SED "$delay_single_quote_subst"`' +no_undefined_flag='`$ECHO "$no_undefined_flag" | $SED "$delay_single_quote_subst"`' +hardcode_libdir_flag_spec='`$ECHO "$hardcode_libdir_flag_spec" | $SED "$delay_single_quote_subst"`' +hardcode_libdir_separator='`$ECHO "$hardcode_libdir_separator" | $SED "$delay_single_quote_subst"`' +hardcode_direct='`$ECHO "$hardcode_direct" | $SED "$delay_single_quote_subst"`' +hardcode_direct_absolute='`$ECHO "$hardcode_direct_absolute" | $SED "$delay_single_quote_subst"`' +hardcode_minus_L='`$ECHO "$hardcode_minus_L" | $SED "$delay_single_quote_subst"`' +hardcode_shlibpath_var='`$ECHO "$hardcode_shlibpath_var" | $SED "$delay_single_quote_subst"`' +hardcode_automatic='`$ECHO "$hardcode_automatic" | $SED "$delay_single_quote_subst"`' +inherit_rpath='`$ECHO "$inherit_rpath" | $SED "$delay_single_quote_subst"`' +link_all_deplibs='`$ECHO "$link_all_deplibs" | $SED "$delay_single_quote_subst"`' +always_export_symbols='`$ECHO "$always_export_symbols" | $SED "$delay_single_quote_subst"`' +export_symbols_cmds='`$ECHO "$export_symbols_cmds" | $SED "$delay_single_quote_subst"`' +exclude_expsyms='`$ECHO "$exclude_expsyms" | $SED "$delay_single_quote_subst"`' +include_expsyms='`$ECHO "$include_expsyms" | $SED "$delay_single_quote_subst"`' +prelink_cmds='`$ECHO "$prelink_cmds" | $SED "$delay_single_quote_subst"`' +postlink_cmds='`$ECHO "$postlink_cmds" | $SED "$delay_single_quote_subst"`' +file_list_spec='`$ECHO "$file_list_spec" | $SED "$delay_single_quote_subst"`' +variables_saved_for_relink='`$ECHO "$variables_saved_for_relink" | $SED "$delay_single_quote_subst"`' +need_lib_prefix='`$ECHO "$need_lib_prefix" | $SED "$delay_single_quote_subst"`' +need_version='`$ECHO "$need_version" | $SED "$delay_single_quote_subst"`' +version_type='`$ECHO "$version_type" | $SED "$delay_single_quote_subst"`' +runpath_var='`$ECHO "$runpath_var" | $SED "$delay_single_quote_subst"`' +shlibpath_var='`$ECHO "$shlibpath_var" | $SED "$delay_single_quote_subst"`' +shlibpath_overrides_runpath='`$ECHO "$shlibpath_overrides_runpath" | $SED "$delay_single_quote_subst"`' +libname_spec='`$ECHO "$libname_spec" | $SED "$delay_single_quote_subst"`' +library_names_spec='`$ECHO "$library_names_spec" | $SED "$delay_single_quote_subst"`' +soname_spec='`$ECHO "$soname_spec" | $SED "$delay_single_quote_subst"`' +install_override_mode='`$ECHO "$install_override_mode" | $SED "$delay_single_quote_subst"`' +postinstall_cmds='`$ECHO "$postinstall_cmds" | $SED "$delay_single_quote_subst"`' +postuninstall_cmds='`$ECHO "$postuninstall_cmds" | $SED "$delay_single_quote_subst"`' +finish_cmds='`$ECHO "$finish_cmds" | $SED "$delay_single_quote_subst"`' +finish_eval='`$ECHO "$finish_eval" | $SED "$delay_single_quote_subst"`' +hardcode_into_libs='`$ECHO "$hardcode_into_libs" | $SED "$delay_single_quote_subst"`' +sys_lib_search_path_spec='`$ECHO "$sys_lib_search_path_spec" | $SED "$delay_single_quote_subst"`' +sys_lib_dlsearch_path_spec='`$ECHO "$sys_lib_dlsearch_path_spec" | $SED "$delay_single_quote_subst"`' +hardcode_action='`$ECHO "$hardcode_action" | $SED "$delay_single_quote_subst"`' +enable_dlopen='`$ECHO "$enable_dlopen" | $SED "$delay_single_quote_subst"`' +enable_dlopen_self='`$ECHO "$enable_dlopen_self" | $SED "$delay_single_quote_subst"`' +enable_dlopen_self_static='`$ECHO "$enable_dlopen_self_static" | $SED "$delay_single_quote_subst"`' +old_striplib='`$ECHO "$old_striplib" | $SED "$delay_single_quote_subst"`' +striplib='`$ECHO "$striplib" | $SED "$delay_single_quote_subst"`' +compiler_lib_search_dirs='`$ECHO "$compiler_lib_search_dirs" | $SED "$delay_single_quote_subst"`' +predep_objects='`$ECHO "$predep_objects" | $SED "$delay_single_quote_subst"`' +postdep_objects='`$ECHO "$postdep_objects" | $SED "$delay_single_quote_subst"`' +predeps='`$ECHO "$predeps" | $SED "$delay_single_quote_subst"`' +postdeps='`$ECHO "$postdeps" | $SED "$delay_single_quote_subst"`' +compiler_lib_search_path='`$ECHO "$compiler_lib_search_path" | $SED "$delay_single_quote_subst"`' +LD_CXX='`$ECHO "$LD_CXX" | $SED "$delay_single_quote_subst"`' +reload_flag_CXX='`$ECHO "$reload_flag_CXX" | $SED "$delay_single_quote_subst"`' +reload_cmds_CXX='`$ECHO "$reload_cmds_CXX" | $SED "$delay_single_quote_subst"`' +old_archive_cmds_CXX='`$ECHO "$old_archive_cmds_CXX" | $SED "$delay_single_quote_subst"`' +compiler_CXX='`$ECHO "$compiler_CXX" | $SED "$delay_single_quote_subst"`' +GCC_CXX='`$ECHO "$GCC_CXX" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_no_builtin_flag_CXX='`$ECHO "$lt_prog_compiler_no_builtin_flag_CXX" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_pic_CXX='`$ECHO "$lt_prog_compiler_pic_CXX" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_wl_CXX='`$ECHO "$lt_prog_compiler_wl_CXX" | $SED "$delay_single_quote_subst"`' +lt_prog_compiler_static_CXX='`$ECHO "$lt_prog_compiler_static_CXX" | $SED "$delay_single_quote_subst"`' +lt_cv_prog_compiler_c_o_CXX='`$ECHO "$lt_cv_prog_compiler_c_o_CXX" | $SED "$delay_single_quote_subst"`' +archive_cmds_need_lc_CXX='`$ECHO "$archive_cmds_need_lc_CXX" | $SED "$delay_single_quote_subst"`' +enable_shared_with_static_runtimes_CXX='`$ECHO "$enable_shared_with_static_runtimes_CXX" | $SED "$delay_single_quote_subst"`' +export_dynamic_flag_spec_CXX='`$ECHO "$export_dynamic_flag_spec_CXX" | $SED "$delay_single_quote_subst"`' +whole_archive_flag_spec_CXX='`$ECHO "$whole_archive_flag_spec_CXX" | $SED "$delay_single_quote_subst"`' +compiler_needs_object_CXX='`$ECHO "$compiler_needs_object_CXX" | $SED "$delay_single_quote_subst"`' +old_archive_from_new_cmds_CXX='`$ECHO "$old_archive_from_new_cmds_CXX" | $SED "$delay_single_quote_subst"`' +old_archive_from_expsyms_cmds_CXX='`$ECHO "$old_archive_from_expsyms_cmds_CXX" | $SED "$delay_single_quote_subst"`' +archive_cmds_CXX='`$ECHO "$archive_cmds_CXX" | $SED "$delay_single_quote_subst"`' +archive_expsym_cmds_CXX='`$ECHO "$archive_expsym_cmds_CXX" | $SED "$delay_single_quote_subst"`' +module_cmds_CXX='`$ECHO "$module_cmds_CXX" | $SED "$delay_single_quote_subst"`' +module_expsym_cmds_CXX='`$ECHO "$module_expsym_cmds_CXX" | $SED "$delay_single_quote_subst"`' +with_gnu_ld_CXX='`$ECHO "$with_gnu_ld_CXX" | $SED "$delay_single_quote_subst"`' +allow_undefined_flag_CXX='`$ECHO "$allow_undefined_flag_CXX" | $SED "$delay_single_quote_subst"`' +no_undefined_flag_CXX='`$ECHO "$no_undefined_flag_CXX" | $SED "$delay_single_quote_subst"`' +hardcode_libdir_flag_spec_CXX='`$ECHO "$hardcode_libdir_flag_spec_CXX" | $SED "$delay_single_quote_subst"`' +hardcode_libdir_separator_CXX='`$ECHO "$hardcode_libdir_separator_CXX" | $SED "$delay_single_quote_subst"`' +hardcode_direct_CXX='`$ECHO "$hardcode_direct_CXX" | $SED "$delay_single_quote_subst"`' +hardcode_direct_absolute_CXX='`$ECHO "$hardcode_direct_absolute_CXX" | $SED "$delay_single_quote_subst"`' +hardcode_minus_L_CXX='`$ECHO "$hardcode_minus_L_CXX" | $SED "$delay_single_quote_subst"`' +hardcode_shlibpath_var_CXX='`$ECHO "$hardcode_shlibpath_var_CXX" | $SED "$delay_single_quote_subst"`' +hardcode_automatic_CXX='`$ECHO "$hardcode_automatic_CXX" | $SED "$delay_single_quote_subst"`' +inherit_rpath_CXX='`$ECHO "$inherit_rpath_CXX" | $SED "$delay_single_quote_subst"`' +link_all_deplibs_CXX='`$ECHO "$link_all_deplibs_CXX" | $SED "$delay_single_quote_subst"`' +always_export_symbols_CXX='`$ECHO "$always_export_symbols_CXX" | $SED "$delay_single_quote_subst"`' +export_symbols_cmds_CXX='`$ECHO "$export_symbols_cmds_CXX" | $SED "$delay_single_quote_subst"`' +exclude_expsyms_CXX='`$ECHO "$exclude_expsyms_CXX" | $SED "$delay_single_quote_subst"`' +include_expsyms_CXX='`$ECHO "$include_expsyms_CXX" | $SED "$delay_single_quote_subst"`' +prelink_cmds_CXX='`$ECHO "$prelink_cmds_CXX" | $SED "$delay_single_quote_subst"`' +postlink_cmds_CXX='`$ECHO "$postlink_cmds_CXX" | $SED "$delay_single_quote_subst"`' +file_list_spec_CXX='`$ECHO "$file_list_spec_CXX" | $SED "$delay_single_quote_subst"`' +hardcode_action_CXX='`$ECHO "$hardcode_action_CXX" | $SED "$delay_single_quote_subst"`' +compiler_lib_search_dirs_CXX='`$ECHO "$compiler_lib_search_dirs_CXX" | $SED "$delay_single_quote_subst"`' +predep_objects_CXX='`$ECHO "$predep_objects_CXX" | $SED "$delay_single_quote_subst"`' +postdep_objects_CXX='`$ECHO "$postdep_objects_CXX" | $SED "$delay_single_quote_subst"`' +predeps_CXX='`$ECHO "$predeps_CXX" | $SED "$delay_single_quote_subst"`' +postdeps_CXX='`$ECHO "$postdeps_CXX" | $SED "$delay_single_quote_subst"`' +compiler_lib_search_path_CXX='`$ECHO "$compiler_lib_search_path_CXX" | $SED "$delay_single_quote_subst"`' + +LTCC='$LTCC' +LTCFLAGS='$LTCFLAGS' +compiler='$compiler_DEFAULT' + +# A function that is used when there is no print builtin or printf. +func_fallback_echo () +{ + eval 'cat <<_LTECHO_EOF +\$1 +_LTECHO_EOF' +} + +# Quote evaled strings. +for var in SHELL \ +ECHO \ +PATH_SEPARATOR \ +SED \ +GREP \ +EGREP \ +FGREP \ +LD \ +NM \ +LN_S \ +lt_SP2NL \ +lt_NL2SP \ +reload_flag \ +OBJDUMP \ +deplibs_check_method \ +file_magic_cmd \ +file_magic_glob \ +want_nocaseglob \ +DLLTOOL \ +sharedlib_from_linklib_cmd \ +AR \ +AR_FLAGS \ +archiver_list_spec \ +STRIP \ +RANLIB \ +CC \ +CFLAGS \ +compiler \ +lt_cv_sys_global_symbol_pipe \ +lt_cv_sys_global_symbol_to_cdecl \ +lt_cv_sys_global_symbol_to_c_name_address \ +lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \ +nm_file_list_spec \ +lt_prog_compiler_no_builtin_flag \ +lt_prog_compiler_pic \ +lt_prog_compiler_wl \ +lt_prog_compiler_static \ +lt_cv_prog_compiler_c_o \ +need_locks \ +MANIFEST_TOOL \ +DSYMUTIL \ +NMEDIT \ +LIPO \ +OTOOL \ +OTOOL64 \ +shrext_cmds \ +export_dynamic_flag_spec \ +whole_archive_flag_spec \ +compiler_needs_object \ +with_gnu_ld \ +allow_undefined_flag \ +no_undefined_flag \ +hardcode_libdir_flag_spec \ +hardcode_libdir_separator \ +exclude_expsyms \ +include_expsyms \ +file_list_spec \ +variables_saved_for_relink \ +libname_spec \ +library_names_spec \ +soname_spec \ +install_override_mode \ +finish_eval \ +old_striplib \ +striplib \ +compiler_lib_search_dirs \ +predep_objects \ +postdep_objects \ +predeps \ +postdeps \ +compiler_lib_search_path \ +LD_CXX \ +reload_flag_CXX \ +compiler_CXX \ +lt_prog_compiler_no_builtin_flag_CXX \ +lt_prog_compiler_pic_CXX \ +lt_prog_compiler_wl_CXX \ +lt_prog_compiler_static_CXX \ +lt_cv_prog_compiler_c_o_CXX \ +export_dynamic_flag_spec_CXX \ +whole_archive_flag_spec_CXX \ +compiler_needs_object_CXX \ +with_gnu_ld_CXX \ +allow_undefined_flag_CXX \ +no_undefined_flag_CXX \ +hardcode_libdir_flag_spec_CXX \ +hardcode_libdir_separator_CXX \ +exclude_expsyms_CXX \ +include_expsyms_CXX \ +file_list_spec_CXX \ +compiler_lib_search_dirs_CXX \ +predep_objects_CXX \ +postdep_objects_CXX \ +predeps_CXX \ +postdeps_CXX \ +compiler_lib_search_path_CXX; do + case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in + *[\\\\\\\`\\"\\\$]*) + eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" + ;; + *) + eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" + ;; + esac +done + +# Double-quote double-evaled strings. +for var in reload_cmds \ +old_postinstall_cmds \ +old_postuninstall_cmds \ +old_archive_cmds \ +extract_expsyms_cmds \ +old_archive_from_new_cmds \ +old_archive_from_expsyms_cmds \ +archive_cmds \ +archive_expsym_cmds \ +module_cmds \ +module_expsym_cmds \ +export_symbols_cmds \ +prelink_cmds \ +postlink_cmds \ +postinstall_cmds \ +postuninstall_cmds \ +finish_cmds \ +sys_lib_search_path_spec \ +sys_lib_dlsearch_path_spec \ +reload_cmds_CXX \ +old_archive_cmds_CXX \ +old_archive_from_new_cmds_CXX \ +old_archive_from_expsyms_cmds_CXX \ +archive_cmds_CXX \ +archive_expsym_cmds_CXX \ +module_cmds_CXX \ +module_expsym_cmds_CXX \ +export_symbols_cmds_CXX \ +prelink_cmds_CXX \ +postlink_cmds_CXX; do + case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in + *[\\\\\\\`\\"\\\$]*) + eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" + ;; + *) + eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" + ;; + esac +done + +ac_aux_dir='$ac_aux_dir' +xsi_shell='$xsi_shell' +lt_shell_append='$lt_shell_append' + +# See if we are running on zsh, and set the options which allow our +# commands through without removal of \ escapes INIT. +if test -n "\${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST +fi + + + PACKAGE='$PACKAGE' + VERSION='$VERSION' + TIMESTAMP='$TIMESTAMP' + RM='$RM' + ofile='$ofile' + + + + + + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + +# Handling of arguments. +for ac_config_target in $ac_config_targets +do + case $ac_config_target in + "build-aux/config.h") CONFIG_HEADERS="$CONFIG_HEADERS build-aux/config.h" ;; + "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; + "scripts/gtest-config") CONFIG_FILES="$CONFIG_FILES scripts/gtest-config" ;; + "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;; + "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;; + + *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; + esac +done + + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files + test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers + test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason against having it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. +$debug || +{ + tmp= ac_tmp= + trap 'exit_status=$? + : "${ac_tmp:=$tmp}" + { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status +' 0 + trap 'as_fn_exit 1' 1 2 13 15 +} +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && + test -d "$tmp" +} || +{ + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") +} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 +ac_tmp=$tmp + +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. +if test -n "$CONFIG_FILES"; then + + +ac_cr=`echo X | tr X '\015'` +# On cygwin, bash can eat \r inside `` if the user requested igncr. +# But we know of no other shell where ac_cr would be empty at this +# point, so we can use a bashism as a fallback. +if test "x$ac_cr" = x; then + eval ac_cr=\$\'\\r\' +fi +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$ac_tmp/subs1.awk" && +_ACEOF + + +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 +ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` +ac_delim='%!_!# ' +for ac_last_try in false false false false false :; do + . ./conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + + ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` + if test $ac_delim_n = $ac_delim_num; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done +rm -f conf$$subs.sh + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && +_ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\)..*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\)..*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' >$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + + print line +} + +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ + || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 +_ACEOF + +# VPATH may cause trouble with some makes, so we remove sole $(srcdir), +# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and +# trailing colons and then remove the whole line if VPATH becomes empty +# (actually we leave an empty line to preserve line numbers). +if test "x$srcdir" = x.; then + ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ +h +s/// +s/^/:/ +s/[ ]*$/:/ +s/:\$(srcdir):/:/g +s/:\${srcdir}:/:/g +s/:@srcdir@:/:/g +s/^:*// +s/:*$// +x +s/\(=[ ]*\).*/\1/ +G +s/\n// +s/^[^=]*=[ ]*$// +}' +fi + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +fi # test -n "$CONFIG_FILES" + +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$ac_tmp/defines.awk" <<\_ACAWK || +BEGIN { +_ACEOF + +# Transform confdefs.h into an awk script `defines.awk', embedded as +# here-document in config.status, that substitutes the proper values into +# config.h.in to produce config.h. + +# Create a delimiter string that does not exist in confdefs.h, to ease +# handling of long lines. +ac_delim='%!_!# ' +for ac_last_try in false false :; do + ac_tt=`sed -n "/$ac_delim/p" confdefs.h` + if test -z "$ac_tt"; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +# For the awk script, D is an array of macro values keyed by name, +# likewise P contains macro parameters if any. Preserve backslash +# newline sequences. + +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +sed -n ' +s/.\{148\}/&'"$ac_delim"'/g +t rset +:rset +s/^[ ]*#[ ]*define[ ][ ]*/ / +t def +d +:def +s/\\$// +t bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3"/p +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p +d +:bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3\\\\\\n"\\/p +t cont +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p +t cont +d +:cont +n +s/.\{148\}/&'"$ac_delim"'/g +t clear +:clear +s/\\$// +t bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/"/p +d +:bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p +b cont +' >$CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { + line = \$ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + prefix = substr(line, 1, index(line, defundef) - 1) + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", prefix defundef, macro, "*/" + next + } + } +} +{ print } +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 +fi # test -n "$CONFIG_HEADERS" + + +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS" +shift +for ac_tag +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$ac_tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; + esac + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + as_fn_append ac_file_inputs " '$ac_f'" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} + fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac + + case $ac_tag in + *:-:* | *:-) cat >"$ac_tmp/stdin" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; + esac + ;; + esac + + ac_dir=`$as_dirname -- "$ac_file" || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + as_dir="$ac_dir"; as_fn_mkdir_p + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + + case $ac_mode in + :F) + # + # CONFIG_FILE + # + + case $INSTALL in + [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; + *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; + esac + ac_MKDIR_P=$MKDIR_P + case $MKDIR_P in + [\\/$]* | ?:[\\/]* ) ;; + */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;; + esac +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# If the template does not know about datarootdir, expand it. +# FIXME: This hack should be removed a few years after 2.60. +ac_datarootdir_hack=; ac_datarootdir_seen= +ac_sed_dataroot=' +/datarootdir/ { + p + q +} +/@datadir@/p +/@docdir@/p +/@infodir@/p +/@localedir@/p +/@mandir@/p' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in +*datarootdir*) ac_datarootdir_seen=yes;; +*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + ac_datarootdir_hack=' + s&@datadir@&$datadir&g + s&@docdir@&$docdir&g + s&@infodir@&$infodir&g + s&@localedir@&$localedir&g + s&@mandir@&$mandir&g + s&\\\${datarootdir}&$datarootdir&g' ;; +esac +_ACEOF + +# Neutralize VPATH when `$srcdir' = `.'. +# Shell code in configure.ac might set extrasub. +# FIXME: do we really want to maintain this feature? +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub +$extrasub +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +:t +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +s|@configure_input@|$ac_sed_conf_input|;t t +s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t +s&@srcdir@&$ac_srcdir&;t t +s&@abs_srcdir@&$ac_abs_srcdir&;t t +s&@top_srcdir@&$ac_top_srcdir&;t t +s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t +s&@builddir@&$ac_builddir&;t t +s&@abs_builddir@&$ac_abs_builddir&;t t +s&@abs_top_builddir@&$ac_abs_top_builddir&;t t +s&@INSTALL@&$ac_INSTALL&;t t +s&@MKDIR_P@&$ac_MKDIR_P&;t t +$ac_datarootdir_hack +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ + >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + +test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && + { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ + "$ac_tmp/out"`; test -z "$ac_out"; } && + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&5 +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&2;} + + rm -f "$ac_tmp/stdin" + case $ac_file in + -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; + *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; + esac \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + ;; + :H) + # + # CONFIG_HEADER + # + if test x"$ac_file" != x-; then + { + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" + } >"$ac_tmp/config.h" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then + { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 +$as_echo "$as_me: $ac_file is unchanged" >&6;} + else + rm -f "$ac_file" + mv "$ac_tmp/config.h" "$ac_file" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + fi + else + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ + || as_fn_error $? "could not create -" "$LINENO" 5 + fi +# Compute "$ac_file"'s index in $config_headers. +_am_arg="$ac_file" +_am_stamp_count=1 +for _am_header in $config_headers :; do + case $_am_header in + $_am_arg | $_am_arg:* ) + break ;; + * ) + _am_stamp_count=`expr $_am_stamp_count + 1` ;; + esac +done +echo "timestamp for $_am_arg" >`$as_dirname -- "$_am_arg" || +$as_expr X"$_am_arg" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$_am_arg" : 'X\(//\)[^/]' \| \ + X"$_am_arg" : 'X\(//\)$' \| \ + X"$_am_arg" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$_am_arg" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'`/stamp-h$_am_stamp_count + ;; + + :C) { $as_echo "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5 +$as_echo "$as_me: executing $ac_file commands" >&6;} + ;; + esac + + + case $ac_file$ac_mode in + "scripts/gtest-config":F) chmod +x scripts/gtest-config ;; + "depfiles":C) test x"$AMDEP_TRUE" != x"" || { + # Autoconf 2.62 quotes --file arguments for eval, but not when files + # are listed without --file. Let's play safe and only enable the eval + # if we detect the quoting. + case $CONFIG_FILES in + *\'*) eval set x "$CONFIG_FILES" ;; + *) set x $CONFIG_FILES ;; + esac + shift + for mf + do + # Strip MF so we end up with the name of the file. + mf=`echo "$mf" | sed -e 's/:.*$//'` + # Check whether this is an Automake generated Makefile or not. + # We used to match only the files named `Makefile.in', but + # some people rename them; so instead we look at the file content. + # Grep'ing the first line is not enough: some people post-process + # each Makefile.in and add a new line on top of each file to say so. + # Grep'ing the whole file is not good either: AIX grep has a line + # limit of 2048, but all sed's we know have understand at least 4000. + if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then + dirpart=`$as_dirname -- "$mf" || +$as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$mf" : 'X\(//\)[^/]' \| \ + X"$mf" : 'X\(//\)$' \| \ + X"$mf" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$mf" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + else + continue + fi + # Extract the definition of DEPDIR, am__include, and am__quote + # from the Makefile without running `make'. + DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` + test -z "$DEPDIR" && continue + am__include=`sed -n 's/^am__include = //p' < "$mf"` + test -z "am__include" && continue + am__quote=`sed -n 's/^am__quote = //p' < "$mf"` + # When using ansi2knr, U may be empty or an underscore; expand it + U=`sed -n 's/^U = //p' < "$mf"` + # Find all dependency output files, they are included files with + # $(DEPDIR) in their names. We invoke sed twice because it is the + # simplest approach to changing $(DEPDIR) to its actual value in the + # expansion. + for file in `sed -n " + s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ + sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do + # Make sure the directory exists. + test -f "$dirpart/$file" && continue + fdir=`$as_dirname -- "$file" || +$as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$file" : 'X\(//\)[^/]' \| \ + X"$file" : 'X\(//\)$' \| \ + X"$file" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + as_dir=$dirpart/$fdir; as_fn_mkdir_p + # echo "creating $dirpart/$file" + echo '# dummy' > "$dirpart/$file" + done + done +} + ;; + "libtool":C) + + # See if we are running on zsh, and set the options which allow our + # commands through without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + + cfgfile="${ofile}T" + trap "$RM \"$cfgfile\"; exit 1" 1 2 15 + $RM "$cfgfile" + + cat <<_LT_EOF >> "$cfgfile" +#! $SHELL + +# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. +# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: +# NOTE: Changes made to this file will be lost: look at ltmain.sh. +# +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, +# 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# Written by Gordon Matzigkeit, 1996 +# +# This file is part of GNU Libtool. +# +# GNU Libtool is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 2 of +# the License, or (at your option) any later version. +# +# As a special exception to the GNU General Public License, +# if you distribute this file as part of a program or library that +# is built using GNU Libtool, you may include this file under the +# same distribution terms that you use for the rest of that program. +# +# GNU Libtool is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GNU Libtool; see the file COPYING. If not, a copy +# can be downloaded from http://www.gnu.org/licenses/gpl.html, or +# obtained by writing to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + +# The names of the tagged configurations supported by this script. +available_tags="CXX " + +# ### BEGIN LIBTOOL CONFIG + +# Which release of libtool.m4 was used? +macro_version=$macro_version +macro_revision=$macro_revision + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# What type of objects to build. +pic_mode=$pic_mode + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# An echo program that protects backslashes. +ECHO=$lt_ECHO + +# The PATH separator for the build system. +PATH_SEPARATOR=$lt_PATH_SEPARATOR + +# The host system. +host_alias=$host_alias +host=$host +host_os=$host_os + +# The build system. +build_alias=$build_alias +build=$build +build_os=$build_os + +# A sed program that does not truncate output. +SED=$lt_SED + +# Sed that helps us avoid accidentally triggering echo(1) options like -n. +Xsed="\$SED -e 1s/^X//" + +# A grep program that handles long lines. +GREP=$lt_GREP + +# An ERE matcher. +EGREP=$lt_EGREP + +# A literal string matcher. +FGREP=$lt_FGREP + +# A BSD- or MS-compatible name lister. +NM=$lt_NM + +# Whether we need soft or hard links. +LN_S=$lt_LN_S + +# What is the maximum length of a command? +max_cmd_len=$max_cmd_len + +# Object file suffix (normally "o"). +objext=$ac_objext + +# Executable file suffix (normally ""). +exeext=$exeext + +# whether the shell understands "unset". +lt_unset=$lt_unset + +# turn spaces into newlines. +SP2NL=$lt_lt_SP2NL + +# turn newlines into spaces. +NL2SP=$lt_lt_NL2SP + +# convert \$build file names to \$host format. +to_host_file_cmd=$lt_cv_to_host_file_cmd + +# convert \$build files to toolchain format. +to_tool_file_cmd=$lt_cv_to_tool_file_cmd + +# An object symbol dumper. +OBJDUMP=$lt_OBJDUMP + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method = "file_magic". +file_magic_cmd=$lt_file_magic_cmd + +# How to find potential files when deplibs_check_method = "file_magic". +file_magic_glob=$lt_file_magic_glob + +# Find potential files using nocaseglob when deplibs_check_method = "file_magic". +want_nocaseglob=$lt_want_nocaseglob + +# DLL creation program. +DLLTOOL=$lt_DLLTOOL + +# Command to associate shared and link libraries. +sharedlib_from_linklib_cmd=$lt_sharedlib_from_linklib_cmd + +# The archiver. +AR=$lt_AR + +# Flags to create an archive. +AR_FLAGS=$lt_AR_FLAGS + +# How to feed a file listing to the archiver. +archiver_list_spec=$lt_archiver_list_spec + +# A symbol stripping program. +STRIP=$lt_STRIP + +# Commands used to install an old-style archive. +RANLIB=$lt_RANLIB +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# Whether to use a lock for old archive extraction. +lock_old_archive_extraction=$lock_old_archive_extraction + +# A C compiler. +LTCC=$lt_CC + +# LTCC compiler flags. +LTCFLAGS=$lt_CFLAGS + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration. +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair. +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# Transform the output of nm in a C name address pair when lib prefix is needed. +global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix + +# Specify filename containing input files for \$NM. +nm_file_list_spec=$lt_nm_file_list_spec + +# The root where to search for dependent libraries,and in which our libraries should be installed. +lt_sysroot=$lt_sysroot + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# Used to examine libraries when file_magic_cmd begins with "file". +MAGIC_CMD=$MAGIC_CMD + +# Must we lock files when doing compilation? +need_locks=$lt_need_locks + +# Manifest tool. +MANIFEST_TOOL=$lt_MANIFEST_TOOL + +# Tool to manipulate archived DWARF debug symbol files on Mac OS X. +DSYMUTIL=$lt_DSYMUTIL + +# Tool to change global to local symbols on Mac OS X. +NMEDIT=$lt_NMEDIT + +# Tool to manipulate fat objects and archives on Mac OS X. +LIPO=$lt_LIPO + +# ldd/readelf like tool for Mach-O binaries on Mac OS X. +OTOOL=$lt_OTOOL + +# ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. +OTOOL64=$lt_OTOOL64 + +# Old archive suffix (normally "a"). +libext=$libext + +# Shared library suffix (normally ".so"). +shrext_cmds=$lt_shrext_cmds + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at link time. +variables_saved_for_relink=$lt_variables_saved_for_relink + +# Do we need the "lib" prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Library versioning type. +version_type=$version_type + +# Shared library runtime path variable. +runpath_var=$runpath_var + +# Shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Permission mode override for installation of shared libraries. +install_override_mode=$lt_install_override_mode + +# Command to use after installation of a shared archive. +postinstall_cmds=$lt_postinstall_cmds + +# Command to use after uninstallation of a shared archive. +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# As "finish_cmds", except a single script fragment to be evaled but +# not shown. +finish_eval=$lt_finish_eval + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Compile-time system search path for libraries. +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries. +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + + +# The linker used to build libraries. +LD=$lt_LD + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# Commands used to build an old-style archive. +old_archive_cmds=$lt_old_archive_cmds + +# A language specific compiler. +CC=$lt_compiler + +# Is the compiler the GNU compiler? +with_gcc=$GCC + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc + +# Whether or not to disallow shared libs when runtime libs are static. +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec + +# Whether the compiler copes with passing no objects directly. +compiler_needs_object=$lt_compiler_needs_object + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds + +# Commands used to build a shared archive. +archive_cmds=$lt_archive_cmds +archive_expsym_cmds=$lt_archive_expsym_cmds + +# Commands used to build a loadable module if different from building +# a shared archive. +module_cmds=$lt_module_cmds +module_expsym_cmds=$lt_module_expsym_cmds + +# Whether we are building with GNU ld or not. +with_gnu_ld=$lt_with_gnu_ld + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag + +# Flag that enforces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec + +# Whether we need a single "-rpath" flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator + +# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes +# DIR into the resulting binary. +hardcode_direct=$hardcode_direct + +# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes +# DIR into the resulting binary and the resulting library dependency is +# "absolute",i.e impossible to change by setting \${shlibpath_var} if the +# library is relocated. +hardcode_direct_absolute=$hardcode_direct_absolute + +# Set to "yes" if using the -LDIR flag during linking hardcodes DIR +# into the resulting binary. +hardcode_minus_L=$hardcode_minus_L + +# Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR +# into the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var + +# Set to "yes" if building a shared library automatically hardcodes DIR +# into the library and all subsequent libraries and executables linked +# against it. +hardcode_automatic=$hardcode_automatic + +# Set to yes if linker adds runtime paths of dependent libraries +# to runtime path list. +inherit_rpath=$inherit_rpath + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs + +# Set to "yes" if exported symbols are required. +always_export_symbols=$always_export_symbols + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms + +# Commands necessary for linking programs (against libraries) with templates. +prelink_cmds=$lt_prelink_cmds + +# Commands necessary for finishing linking programs. +postlink_cmds=$lt_postlink_cmds + +# Specify filename containing input files. +file_list_spec=$lt_file_list_spec + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action + +# The directories searched by this compiler when creating a shared library. +compiler_lib_search_dirs=$lt_compiler_lib_search_dirs + +# Dependencies to place before and after the objects being linked to +# create a shared library. +predep_objects=$lt_predep_objects +postdep_objects=$lt_postdep_objects +predeps=$lt_predeps +postdeps=$lt_postdeps + +# The library search path used internally by the compiler when linking +# a shared library. +compiler_lib_search_path=$lt_compiler_lib_search_path + +# ### END LIBTOOL CONFIG + +_LT_EOF + + case $host_os in + aix3*) + cat <<\_LT_EOF >> "$cfgfile" +# AIX sometimes has problems with the GCC collect2 program. For some +# reason, if we set the COLLECT_NAMES environment variable, the problems +# vanish in a puff of smoke. +if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES +fi +_LT_EOF + ;; + esac + + +ltmain="$ac_aux_dir/ltmain.sh" + + + # We use sed instead of cat because bash on DJGPP gets confused if + # if finds mixed CR/LF and LF-only lines. Since sed operates in + # text mode, it properly converts lines to CR/LF. This bash problem + # is reportedly fixed, but why not run on old versions too? + sed '$q' "$ltmain" >> "$cfgfile" \ + || (rm -f "$cfgfile"; exit 1) + + if test x"$xsi_shell" = xyes; then + sed -e '/^func_dirname ()$/,/^} # func_dirname /c\ +func_dirname ()\ +{\ +\ case ${1} in\ +\ */*) func_dirname_result="${1%/*}${2}" ;;\ +\ * ) func_dirname_result="${3}" ;;\ +\ esac\ +} # Extended-shell func_dirname implementation' "$cfgfile" > $cfgfile.tmp \ + && mv -f "$cfgfile.tmp" "$cfgfile" \ + || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") +test 0 -eq $? || _lt_function_replace_fail=: + + + sed -e '/^func_basename ()$/,/^} # func_basename /c\ +func_basename ()\ +{\ +\ func_basename_result="${1##*/}"\ +} # Extended-shell func_basename implementation' "$cfgfile" > $cfgfile.tmp \ + && mv -f "$cfgfile.tmp" "$cfgfile" \ + || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") +test 0 -eq $? || _lt_function_replace_fail=: + + + sed -e '/^func_dirname_and_basename ()$/,/^} # func_dirname_and_basename /c\ +func_dirname_and_basename ()\ +{\ +\ case ${1} in\ +\ */*) func_dirname_result="${1%/*}${2}" ;;\ +\ * ) func_dirname_result="${3}" ;;\ +\ esac\ +\ func_basename_result="${1##*/}"\ +} # Extended-shell func_dirname_and_basename implementation' "$cfgfile" > $cfgfile.tmp \ + && mv -f "$cfgfile.tmp" "$cfgfile" \ + || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") +test 0 -eq $? || _lt_function_replace_fail=: + + + sed -e '/^func_stripname ()$/,/^} # func_stripname /c\ +func_stripname ()\ +{\ +\ # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\ +\ # positional parameters, so assign one to ordinary parameter first.\ +\ func_stripname_result=${3}\ +\ func_stripname_result=${func_stripname_result#"${1}"}\ +\ func_stripname_result=${func_stripname_result%"${2}"}\ +} # Extended-shell func_stripname implementation' "$cfgfile" > $cfgfile.tmp \ + && mv -f "$cfgfile.tmp" "$cfgfile" \ + || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") +test 0 -eq $? || _lt_function_replace_fail=: + + + sed -e '/^func_split_long_opt ()$/,/^} # func_split_long_opt /c\ +func_split_long_opt ()\ +{\ +\ func_split_long_opt_name=${1%%=*}\ +\ func_split_long_opt_arg=${1#*=}\ +} # Extended-shell func_split_long_opt implementation' "$cfgfile" > $cfgfile.tmp \ + && mv -f "$cfgfile.tmp" "$cfgfile" \ + || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") +test 0 -eq $? || _lt_function_replace_fail=: + + + sed -e '/^func_split_short_opt ()$/,/^} # func_split_short_opt /c\ +func_split_short_opt ()\ +{\ +\ func_split_short_opt_arg=${1#??}\ +\ func_split_short_opt_name=${1%"$func_split_short_opt_arg"}\ +} # Extended-shell func_split_short_opt implementation' "$cfgfile" > $cfgfile.tmp \ + && mv -f "$cfgfile.tmp" "$cfgfile" \ + || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") +test 0 -eq $? || _lt_function_replace_fail=: + + + sed -e '/^func_lo2o ()$/,/^} # func_lo2o /c\ +func_lo2o ()\ +{\ +\ case ${1} in\ +\ *.lo) func_lo2o_result=${1%.lo}.${objext} ;;\ +\ *) func_lo2o_result=${1} ;;\ +\ esac\ +} # Extended-shell func_lo2o implementation' "$cfgfile" > $cfgfile.tmp \ + && mv -f "$cfgfile.tmp" "$cfgfile" \ + || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") +test 0 -eq $? || _lt_function_replace_fail=: + + + sed -e '/^func_xform ()$/,/^} # func_xform /c\ +func_xform ()\ +{\ + func_xform_result=${1%.*}.lo\ +} # Extended-shell func_xform implementation' "$cfgfile" > $cfgfile.tmp \ + && mv -f "$cfgfile.tmp" "$cfgfile" \ + || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") +test 0 -eq $? || _lt_function_replace_fail=: + + + sed -e '/^func_arith ()$/,/^} # func_arith /c\ +func_arith ()\ +{\ + func_arith_result=$(( $* ))\ +} # Extended-shell func_arith implementation' "$cfgfile" > $cfgfile.tmp \ + && mv -f "$cfgfile.tmp" "$cfgfile" \ + || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") +test 0 -eq $? || _lt_function_replace_fail=: + + + sed -e '/^func_len ()$/,/^} # func_len /c\ +func_len ()\ +{\ + func_len_result=${#1}\ +} # Extended-shell func_len implementation' "$cfgfile" > $cfgfile.tmp \ + && mv -f "$cfgfile.tmp" "$cfgfile" \ + || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") +test 0 -eq $? || _lt_function_replace_fail=: + +fi + +if test x"$lt_shell_append" = xyes; then + sed -e '/^func_append ()$/,/^} # func_append /c\ +func_append ()\ +{\ + eval "${1}+=\\${2}"\ +} # Extended-shell func_append implementation' "$cfgfile" > $cfgfile.tmp \ + && mv -f "$cfgfile.tmp" "$cfgfile" \ + || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") +test 0 -eq $? || _lt_function_replace_fail=: + + + sed -e '/^func_append_quoted ()$/,/^} # func_append_quoted /c\ +func_append_quoted ()\ +{\ +\ func_quote_for_eval "${2}"\ +\ eval "${1}+=\\\\ \\$func_quote_for_eval_result"\ +} # Extended-shell func_append_quoted implementation' "$cfgfile" > $cfgfile.tmp \ + && mv -f "$cfgfile.tmp" "$cfgfile" \ + || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") +test 0 -eq $? || _lt_function_replace_fail=: + + + # Save a `func_append' function call where possible by direct use of '+=' + sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \ + && mv -f "$cfgfile.tmp" "$cfgfile" \ + || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") + test 0 -eq $? || _lt_function_replace_fail=: +else + # Save a `func_append' function call even when '+=' is not available + sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \ + && mv -f "$cfgfile.tmp" "$cfgfile" \ + || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") + test 0 -eq $? || _lt_function_replace_fail=: +fi + +if test x"$_lt_function_replace_fail" = x":"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Unable to substitute extended shell functions in $ofile" >&5 +$as_echo "$as_me: WARNING: Unable to substitute extended shell functions in $ofile" >&2;} +fi + + + mv -f "$cfgfile" "$ofile" || + (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") + chmod +x "$ofile" + + + cat <<_LT_EOF >> "$ofile" + +# ### BEGIN LIBTOOL TAG CONFIG: CXX + +# The linker used to build libraries. +LD=$lt_LD_CXX + +# How to create reloadable object files. +reload_flag=$lt_reload_flag_CXX +reload_cmds=$lt_reload_cmds_CXX + +# Commands used to build an old-style archive. +old_archive_cmds=$lt_old_archive_cmds_CXX + +# A language specific compiler. +CC=$lt_compiler_CXX + +# Is the compiler the GNU compiler? +with_gcc=$GCC_CXX + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_CXX + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic_CXX + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl_CXX + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static_CXX + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o_CXX + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc_CXX + +# Whether or not to disallow shared libs when runtime libs are static. +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_CXX + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_CXX + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec_CXX + +# Whether the compiler copes with passing no objects directly. +compiler_needs_object=$lt_compiler_needs_object_CXX + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_CXX + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_CXX + +# Commands used to build a shared archive. +archive_cmds=$lt_archive_cmds_CXX +archive_expsym_cmds=$lt_archive_expsym_cmds_CXX + +# Commands used to build a loadable module if different from building +# a shared archive. +module_cmds=$lt_module_cmds_CXX +module_expsym_cmds=$lt_module_expsym_cmds_CXX + +# Whether we are building with GNU ld or not. +with_gnu_ld=$lt_with_gnu_ld_CXX + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag_CXX + +# Flag that enforces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag_CXX + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_CXX + +# Whether we need a single "-rpath" flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator_CXX + +# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes +# DIR into the resulting binary. +hardcode_direct=$hardcode_direct_CXX + +# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes +# DIR into the resulting binary and the resulting library dependency is +# "absolute",i.e impossible to change by setting \${shlibpath_var} if the +# library is relocated. +hardcode_direct_absolute=$hardcode_direct_absolute_CXX + +# Set to "yes" if using the -LDIR flag during linking hardcodes DIR +# into the resulting binary. +hardcode_minus_L=$hardcode_minus_L_CXX + +# Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR +# into the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var_CXX + +# Set to "yes" if building a shared library automatically hardcodes DIR +# into the library and all subsequent libraries and executables linked +# against it. +hardcode_automatic=$hardcode_automatic_CXX + +# Set to yes if linker adds runtime paths of dependent libraries +# to runtime path list. +inherit_rpath=$inherit_rpath_CXX + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs_CXX + +# Set to "yes" if exported symbols are required. +always_export_symbols=$always_export_symbols_CXX + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds_CXX + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms_CXX + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms_CXX + +# Commands necessary for linking programs (against libraries) with templates. +prelink_cmds=$lt_prelink_cmds_CXX + +# Commands necessary for finishing linking programs. +postlink_cmds=$lt_postlink_cmds_CXX + +# Specify filename containing input files. +file_list_spec=$lt_file_list_spec_CXX + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action_CXX + +# The directories searched by this compiler when creating a shared library. +compiler_lib_search_dirs=$lt_compiler_lib_search_dirs_CXX + +# Dependencies to place before and after the objects being linked to +# create a shared library. +predep_objects=$lt_predep_objects_CXX +postdep_objects=$lt_postdep_objects_CXX +predeps=$lt_predeps_CXX +postdeps=$lt_postdeps_CXX + +# The library search path used internally by the compiler when linking +# a shared library. +compiler_lib_search_path=$lt_compiler_lib_search_path_CXX + +# ### END LIBTOOL TAG CONFIG: CXX +_LT_EOF + + ;; + + esac +done # for ac_tag + + +as_fn_exit 0 +_ACEOF +ac_clean_files=$ac_clean_files_save + +test $ac_write_fail = 0 || + as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 + + +# configure is writing to config.log, and then calls config.status. +# config.status does its own redirection, appending to config.log. +# Unfortunately, on DOS this fails, as config.log is still kept open +# by configure, so config.status won't be able to write to it; its +# output is simply discarded. So we exec the FD to /dev/null, +# effectively closing config.log, so it can be properly (re)opened and +# appended to by config.status. When coming back to configure, we +# need to make the FD available again. +if test "$no_create" != yes; then + ac_cs_success=: + ac_config_status_args= + test "$silent" = yes && + ac_config_status_args="$ac_config_status_args --quiet" + exec 5>/dev/null + $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false + exec 5>>config.log + # Use ||, not &&, to avoid exiting from the if with $? = 1, which + # would make configure fail if this is the last instruction. + $ac_cs_success || as_fn_exit 1 +fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 +$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} +fi + diff --git a/lib/gtest/configure.ac b/lib/gtest/configure.ac new file mode 100644 index 00000000..cc592e15 --- /dev/null +++ b/lib/gtest/configure.ac @@ -0,0 +1,68 @@ +m4_include(m4/acx_pthread.m4) + +# At this point, the Xcode project assumes the version string will be three +# integers separated by periods and surrounded by square brackets (e.g. +# "[1.0.1]"). It also asumes that there won't be any closing parenthesis +# between "AC_INIT(" and the closing ")" including comments and strings. +AC_INIT([Google C++ Testing Framework], + [1.7.0], + [googletestframework@googlegroups.com], + [gtest]) + +# Provide various options to initialize the Autoconf and configure processes. +AC_PREREQ([2.59]) +AC_CONFIG_SRCDIR([./LICENSE]) +AC_CONFIG_MACRO_DIR([m4]) +AC_CONFIG_AUX_DIR([build-aux]) +AC_CONFIG_HEADERS([build-aux/config.h]) +AC_CONFIG_FILES([Makefile]) +AC_CONFIG_FILES([scripts/gtest-config], [chmod +x scripts/gtest-config]) + +# Initialize Automake with various options. We require at least v1.9, prevent +# pedantic complaints about package files, and enable various distribution +# targets. +AM_INIT_AUTOMAKE([1.9 dist-bzip2 dist-zip foreign subdir-objects]) + +# Check for programs used in building Google Test. +AC_PROG_CC +AC_PROG_CXX +AC_LANG([C++]) +AC_PROG_LIBTOOL + +# TODO(chandlerc@google.com): Currently we aren't running the Python tests +# against the interpreter detected by AM_PATH_PYTHON, and so we condition +# HAVE_PYTHON by requiring "python" to be in the PATH, and that interpreter's +# version to be >= 2.3. This will allow the scripts to use a "/usr/bin/env" +# hashbang. +PYTHON= # We *do not* allow the user to specify a python interpreter +AC_PATH_PROG([PYTHON],[python],[:]) +AS_IF([test "$PYTHON" != ":"], + [AM_PYTHON_CHECK_VERSION([$PYTHON],[2.3],[:],[PYTHON=":"])]) +AM_CONDITIONAL([HAVE_PYTHON],[test "$PYTHON" != ":"]) + +# Configure pthreads. +AC_ARG_WITH([pthreads], + [AS_HELP_STRING([--with-pthreads], + [use pthreads (default is yes)])], + [with_pthreads=$withval], + [with_pthreads=check]) + +have_pthreads=no +AS_IF([test "x$with_pthreads" != "xno"], + [ACX_PTHREAD( + [], + [AS_IF([test "x$with_pthreads" != "xcheck"], + [AC_MSG_FAILURE( + [--with-pthreads was specified, but unable to be used])])]) + have_pthreads="$acx_pthread_ok"]) +AM_CONDITIONAL([HAVE_PTHREADS],[test "x$have_pthreads" = "xyes"]) +AC_SUBST(PTHREAD_CFLAGS) +AC_SUBST(PTHREAD_LIBS) + +# TODO(chandlerc@google.com) Check for the necessary system headers. + +# TODO(chandlerc@google.com) Check the types, structures, and other compiler +# and architecture characteristics. + +# Output the generated files. No further autoconf macros may be used. +AC_OUTPUT diff --git a/lib/gtest/include/gtest/gtest-death-test.h b/lib/gtest/include/gtest/gtest-death-test.h new file mode 100644 index 00000000..957a69c6 --- /dev/null +++ b/lib/gtest/include/gtest/gtest-death-test.h @@ -0,0 +1,294 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file defines the public API for death tests. It is +// #included by gtest.h so a user doesn't need to include this +// directly. + +#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ +#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ + +#include "gtest/internal/gtest-death-test-internal.h" + +namespace testing { + +// This flag controls the style of death tests. Valid values are "threadsafe", +// meaning that the death test child process will re-execute the test binary +// from the start, running only a single death test, or "fast", +// meaning that the child process will execute the test logic immediately +// after forking. +GTEST_DECLARE_string_(death_test_style); + +#if GTEST_HAS_DEATH_TEST + +namespace internal { + +// Returns a Boolean value indicating whether the caller is currently +// executing in the context of the death test child process. Tools such as +// Valgrind heap checkers may need this to modify their behavior in death +// tests. IMPORTANT: This is an internal utility. Using it may break the +// implementation of death tests. User code MUST NOT use it. +GTEST_API_ bool InDeathTestChild(); + +} // namespace internal + +// The following macros are useful for writing death tests. + +// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is +// executed: +// +// 1. It generates a warning if there is more than one active +// thread. This is because it's safe to fork() or clone() only +// when there is a single thread. +// +// 2. The parent process clone()s a sub-process and runs the death +// test in it; the sub-process exits with code 0 at the end of the +// death test, if it hasn't exited already. +// +// 3. The parent process waits for the sub-process to terminate. +// +// 4. The parent process checks the exit code and error message of +// the sub-process. +// +// Examples: +// +// ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number"); +// for (int i = 0; i < 5; i++) { +// EXPECT_DEATH(server.ProcessRequest(i), +// "Invalid request .* in ProcessRequest()") +// << "Failed to die on request " << i; +// } +// +// ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting"); +// +// bool KilledBySIGHUP(int exit_code) { +// return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP; +// } +// +// ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!"); +// +// On the regular expressions used in death tests: +// +// On POSIX-compliant systems (*nix), we use the library, +// which uses the POSIX extended regex syntax. +// +// On other platforms (e.g. Windows), we only support a simple regex +// syntax implemented as part of Google Test. This limited +// implementation should be enough most of the time when writing +// death tests; though it lacks many features you can find in PCRE +// or POSIX extended regex syntax. For example, we don't support +// union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and +// repetition count ("x{5,7}"), among others. +// +// Below is the syntax that we do support. We chose it to be a +// subset of both PCRE and POSIX extended regex, so it's easy to +// learn wherever you come from. In the following: 'A' denotes a +// literal character, period (.), or a single \\ escape sequence; +// 'x' and 'y' denote regular expressions; 'm' and 'n' are for +// natural numbers. +// +// c matches any literal character c +// \\d matches any decimal digit +// \\D matches any character that's not a decimal digit +// \\f matches \f +// \\n matches \n +// \\r matches \r +// \\s matches any ASCII whitespace, including \n +// \\S matches any character that's not a whitespace +// \\t matches \t +// \\v matches \v +// \\w matches any letter, _, or decimal digit +// \\W matches any character that \\w doesn't match +// \\c matches any literal character c, which must be a punctuation +// . matches any single character except \n +// A? matches 0 or 1 occurrences of A +// A* matches 0 or many occurrences of A +// A+ matches 1 or many occurrences of A +// ^ matches the beginning of a string (not that of each line) +// $ matches the end of a string (not that of each line) +// xy matches x followed by y +// +// If you accidentally use PCRE or POSIX extended regex features +// not implemented by us, you will get a run-time failure. In that +// case, please try to rewrite your regular expression within the +// above syntax. +// +// This implementation is *not* meant to be as highly tuned or robust +// as a compiled regex library, but should perform well enough for a +// death test, which already incurs significant overhead by launching +// a child process. +// +// Known caveats: +// +// A "threadsafe" style death test obtains the path to the test +// program from argv[0] and re-executes it in the sub-process. For +// simplicity, the current implementation doesn't search the PATH +// when launching the sub-process. This means that the user must +// invoke the test program via a path that contains at least one +// path separator (e.g. path/to/foo_test and +// /absolute/path/to/bar_test are fine, but foo_test is not). This +// is rarely a problem as people usually don't put the test binary +// directory in PATH. +// +// TODO(wan@google.com): make thread-safe death tests search the PATH. + +// Asserts that a given statement causes the program to exit, with an +// integer exit status that satisfies predicate, and emitting error output +// that matches regex. +# define ASSERT_EXIT(statement, predicate, regex) \ + GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_) + +// Like ASSERT_EXIT, but continues on to successive tests in the +// test case, if any: +# define EXPECT_EXIT(statement, predicate, regex) \ + GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_) + +// Asserts that a given statement causes the program to exit, either by +// explicitly exiting with a nonzero exit code or being killed by a +// signal, and emitting error output that matches regex. +# define ASSERT_DEATH(statement, regex) \ + ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) + +// Like ASSERT_DEATH, but continues on to successive tests in the +// test case, if any: +# define EXPECT_DEATH(statement, regex) \ + EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) + +// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: + +// Tests that an exit code describes a normal exit with a given exit code. +class GTEST_API_ ExitedWithCode { + public: + explicit ExitedWithCode(int exit_code); + bool operator()(int exit_status) const; + private: + // No implementation - assignment is unsupported. + void operator=(const ExitedWithCode& other); + + const int exit_code_; +}; + +# if !GTEST_OS_WINDOWS +// Tests that an exit code describes an exit due to termination by a +// given signal. +class GTEST_API_ KilledBySignal { + public: + explicit KilledBySignal(int signum); + bool operator()(int exit_status) const; + private: + const int signum_; +}; +# endif // !GTEST_OS_WINDOWS + +// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode. +// The death testing framework causes this to have interesting semantics, +// since the sideeffects of the call are only visible in opt mode, and not +// in debug mode. +// +// In practice, this can be used to test functions that utilize the +// LOG(DFATAL) macro using the following style: +// +// int DieInDebugOr12(int* sideeffect) { +// if (sideeffect) { +// *sideeffect = 12; +// } +// LOG(DFATAL) << "death"; +// return 12; +// } +// +// TEST(TestCase, TestDieOr12WorksInDgbAndOpt) { +// int sideeffect = 0; +// // Only asserts in dbg. +// EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death"); +// +// #ifdef NDEBUG +// // opt-mode has sideeffect visible. +// EXPECT_EQ(12, sideeffect); +// #else +// // dbg-mode no visible sideeffect. +// EXPECT_EQ(0, sideeffect); +// #endif +// } +// +// This will assert that DieInDebugReturn12InOpt() crashes in debug +// mode, usually due to a DCHECK or LOG(DFATAL), but returns the +// appropriate fallback value (12 in this case) in opt mode. If you +// need to test that a function has appropriate side-effects in opt +// mode, include assertions against the side-effects. A general +// pattern for this is: +// +// EXPECT_DEBUG_DEATH({ +// // Side-effects here will have an effect after this statement in +// // opt mode, but none in debug mode. +// EXPECT_EQ(12, DieInDebugOr12(&sideeffect)); +// }, "death"); +// +# ifdef NDEBUG + +# define EXPECT_DEBUG_DEATH(statement, regex) \ + GTEST_EXECUTE_STATEMENT_(statement, regex) + +# define ASSERT_DEBUG_DEATH(statement, regex) \ + GTEST_EXECUTE_STATEMENT_(statement, regex) + +# else + +# define EXPECT_DEBUG_DEATH(statement, regex) \ + EXPECT_DEATH(statement, regex) + +# define ASSERT_DEBUG_DEATH(statement, regex) \ + ASSERT_DEATH(statement, regex) + +# endif // NDEBUG for EXPECT_DEBUG_DEATH +#endif // GTEST_HAS_DEATH_TEST + +// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and +// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if +// death tests are supported; otherwise they just issue a warning. This is +// useful when you are combining death test assertions with normal test +// assertions in one test. +#if GTEST_HAS_DEATH_TEST +# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ + EXPECT_DEATH(statement, regex) +# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ + ASSERT_DEATH(statement, regex) +#else +# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ + GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, ) +# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ + GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return) +#endif + +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ diff --git a/lib/gtest/include/gtest/gtest-message.h b/lib/gtest/include/gtest/gtest-message.h new file mode 100644 index 00000000..fe879bca --- /dev/null +++ b/lib/gtest/include/gtest/gtest-message.h @@ -0,0 +1,250 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file defines the Message class. +// +// IMPORTANT NOTE: Due to limitation of the C++ language, we have to +// leave some internal implementation details in this header file. +// They are clearly marked by comments like this: +// +// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +// +// Such code is NOT meant to be used by a user directly, and is subject +// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user +// program! + +#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ +#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ + +#include + +#include "gtest/internal/gtest-port.h" + +// Ensures that there is at least one operator<< in the global namespace. +// See Message& operator<<(...) below for why. +void operator<<(const testing::internal::Secret&, int); + +namespace testing { + +// The Message class works like an ostream repeater. +// +// Typical usage: +// +// 1. You stream a bunch of values to a Message object. +// It will remember the text in a stringstream. +// 2. Then you stream the Message object to an ostream. +// This causes the text in the Message to be streamed +// to the ostream. +// +// For example; +// +// testing::Message foo; +// foo << 1 << " != " << 2; +// std::cout << foo; +// +// will print "1 != 2". +// +// Message is not intended to be inherited from. In particular, its +// destructor is not virtual. +// +// Note that stringstream behaves differently in gcc and in MSVC. You +// can stream a NULL char pointer to it in the former, but not in the +// latter (it causes an access violation if you do). The Message +// class hides this difference by treating a NULL char pointer as +// "(null)". +class GTEST_API_ Message { + private: + // The type of basic IO manipulators (endl, ends, and flush) for + // narrow streams. + typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&); + + public: + // Constructs an empty Message. + Message(); + + // Copy constructor. + Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT + *ss_ << msg.GetString(); + } + + // Constructs a Message from a C-string. + explicit Message(const char* str) : ss_(new ::std::stringstream) { + *ss_ << str; + } + +#if GTEST_OS_SYMBIAN + // Streams a value (either a pointer or not) to this object. + template + inline Message& operator <<(const T& value) { + StreamHelper(typename internal::is_pointer::type(), value); + return *this; + } +#else + // Streams a non-pointer value to this object. + template + inline Message& operator <<(const T& val) { + // Some libraries overload << for STL containers. These + // overloads are defined in the global namespace instead of ::std. + // + // C++'s symbol lookup rule (i.e. Koenig lookup) says that these + // overloads are visible in either the std namespace or the global + // namespace, but not other namespaces, including the testing + // namespace which Google Test's Message class is in. + // + // To allow STL containers (and other types that has a << operator + // defined in the global namespace) to be used in Google Test + // assertions, testing::Message must access the custom << operator + // from the global namespace. With this using declaration, + // overloads of << defined in the global namespace and those + // visible via Koenig lookup are both exposed in this function. + using ::operator <<; + *ss_ << val; + return *this; + } + + // Streams a pointer value to this object. + // + // This function is an overload of the previous one. When you + // stream a pointer to a Message, this definition will be used as it + // is more specialized. (The C++ Standard, section + // [temp.func.order].) If you stream a non-pointer, then the + // previous definition will be used. + // + // The reason for this overload is that streaming a NULL pointer to + // ostream is undefined behavior. Depending on the compiler, you + // may get "0", "(nil)", "(null)", or an access violation. To + // ensure consistent result across compilers, we always treat NULL + // as "(null)". + template + inline Message& operator <<(T* const& pointer) { // NOLINT + if (pointer == NULL) { + *ss_ << "(null)"; + } else { + *ss_ << pointer; + } + return *this; + } +#endif // GTEST_OS_SYMBIAN + + // Since the basic IO manipulators are overloaded for both narrow + // and wide streams, we have to provide this specialized definition + // of operator <<, even though its body is the same as the + // templatized version above. Without this definition, streaming + // endl or other basic IO manipulators to Message will confuse the + // compiler. + Message& operator <<(BasicNarrowIoManip val) { + *ss_ << val; + return *this; + } + + // Instead of 1/0, we want to see true/false for bool values. + Message& operator <<(bool b) { + return *this << (b ? "true" : "false"); + } + + // These two overloads allow streaming a wide C string to a Message + // using the UTF-8 encoding. + Message& operator <<(const wchar_t* wide_c_str); + Message& operator <<(wchar_t* wide_c_str); + +#if GTEST_HAS_STD_WSTRING + // Converts the given wide string to a narrow string using the UTF-8 + // encoding, and streams the result to this Message object. + Message& operator <<(const ::std::wstring& wstr); +#endif // GTEST_HAS_STD_WSTRING + +#if GTEST_HAS_GLOBAL_WSTRING + // Converts the given wide string to a narrow string using the UTF-8 + // encoding, and streams the result to this Message object. + Message& operator <<(const ::wstring& wstr); +#endif // GTEST_HAS_GLOBAL_WSTRING + + // Gets the text streamed to this object so far as an std::string. + // Each '\0' character in the buffer is replaced with "\\0". + // + // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + std::string GetString() const; + + private: + +#if GTEST_OS_SYMBIAN + // These are needed as the Nokia Symbian Compiler cannot decide between + // const T& and const T* in a function template. The Nokia compiler _can_ + // decide between class template specializations for T and T*, so a + // tr1::type_traits-like is_pointer works, and we can overload on that. + template + inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) { + if (pointer == NULL) { + *ss_ << "(null)"; + } else { + *ss_ << pointer; + } + } + template + inline void StreamHelper(internal::false_type /*is_pointer*/, + const T& value) { + // See the comments in Message& operator <<(const T&) above for why + // we need this using statement. + using ::operator <<; + *ss_ << value; + } +#endif // GTEST_OS_SYMBIAN + + // We'll hold the text streamed to this object here. + const internal::scoped_ptr< ::std::stringstream> ss_; + + // We declare (but don't implement) this to prevent the compiler + // from implementing the assignment operator. + void operator=(const Message&); +}; + +// Streams a Message to an ostream. +inline std::ostream& operator <<(std::ostream& os, const Message& sb) { + return os << sb.GetString(); +} + +namespace internal { + +// Converts a streamable value to an std::string. A NULL pointer is +// converted to "(null)". When the input value is a ::string, +// ::std::string, ::wstring, or ::std::wstring object, each NUL +// character in it is replaced with "\\0". +template +std::string StreamableToString(const T& streamable) { + return (Message() << streamable).GetString(); +} + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ diff --git a/lib/gtest/include/gtest/gtest-param-test.h b/lib/gtest/include/gtest/gtest-param-test.h new file mode 100644 index 00000000..d6702c8f --- /dev/null +++ b/lib/gtest/include/gtest/gtest-param-test.h @@ -0,0 +1,1421 @@ +// This file was GENERATED by command: +// pump.py gtest-param-test.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: vladl@google.com (Vlad Losev) +// +// Macros and functions for implementing parameterized tests +// in Google C++ Testing Framework (Google Test) +// +// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ +#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ + + +// Value-parameterized tests allow you to test your code with different +// parameters without writing multiple copies of the same test. +// +// Here is how you use value-parameterized tests: + +#if 0 + +// To write value-parameterized tests, first you should define a fixture +// class. It is usually derived from testing::TestWithParam (see below for +// another inheritance scheme that's sometimes useful in more complicated +// class hierarchies), where the type of your parameter values. +// TestWithParam is itself derived from testing::Test. T can be any +// copyable type. If it's a raw pointer, you are responsible for managing the +// lifespan of the pointed values. + +class FooTest : public ::testing::TestWithParam { + // You can implement all the usual class fixture members here. +}; + +// Then, use the TEST_P macro to define as many parameterized tests +// for this fixture as you want. The _P suffix is for "parameterized" +// or "pattern", whichever you prefer to think. + +TEST_P(FooTest, DoesBlah) { + // Inside a test, access the test parameter with the GetParam() method + // of the TestWithParam class: + EXPECT_TRUE(foo.Blah(GetParam())); + ... +} + +TEST_P(FooTest, HasBlahBlah) { + ... +} + +// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test +// case with any set of parameters you want. Google Test defines a number +// of functions for generating test parameters. They return what we call +// (surprise!) parameter generators. Here is a summary of them, which +// are all in the testing namespace: +// +// +// Range(begin, end [, step]) - Yields values {begin, begin+step, +// begin+step+step, ...}. The values do not +// include end. step defaults to 1. +// Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}. +// ValuesIn(container) - Yields values from a C-style array, an STL +// ValuesIn(begin,end) container, or an iterator range [begin, end). +// Bool() - Yields sequence {false, true}. +// Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product +// for the math savvy) of the values generated +// by the N generators. +// +// For more details, see comments at the definitions of these functions below +// in this file. +// +// The following statement will instantiate tests from the FooTest test case +// each with parameter values "meeny", "miny", and "moe". + +INSTANTIATE_TEST_CASE_P(InstantiationName, + FooTest, + Values("meeny", "miny", "moe")); + +// To distinguish different instances of the pattern, (yes, you +// can instantiate it more then once) the first argument to the +// INSTANTIATE_TEST_CASE_P macro is a prefix that will be added to the +// actual test case name. Remember to pick unique prefixes for different +// instantiations. The tests from the instantiation above will have +// these names: +// +// * InstantiationName/FooTest.DoesBlah/0 for "meeny" +// * InstantiationName/FooTest.DoesBlah/1 for "miny" +// * InstantiationName/FooTest.DoesBlah/2 for "moe" +// * InstantiationName/FooTest.HasBlahBlah/0 for "meeny" +// * InstantiationName/FooTest.HasBlahBlah/1 for "miny" +// * InstantiationName/FooTest.HasBlahBlah/2 for "moe" +// +// You can use these names in --gtest_filter. +// +// This statement will instantiate all tests from FooTest again, each +// with parameter values "cat" and "dog": + +const char* pets[] = {"cat", "dog"}; +INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); + +// The tests from the instantiation above will have these names: +// +// * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat" +// * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog" +// * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat" +// * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog" +// +// Please note that INSTANTIATE_TEST_CASE_P will instantiate all tests +// in the given test case, whether their definitions come before or +// AFTER the INSTANTIATE_TEST_CASE_P statement. +// +// Please also note that generator expressions (including parameters to the +// generators) are evaluated in InitGoogleTest(), after main() has started. +// This allows the user on one hand, to adjust generator parameters in order +// to dynamically determine a set of tests to run and on the other hand, +// give the user a chance to inspect the generated tests with Google Test +// reflection API before RUN_ALL_TESTS() is executed. +// +// You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc +// for more examples. +// +// In the future, we plan to publish the API for defining new parameter +// generators. But for now this interface remains part of the internal +// implementation and is subject to change. +// +// +// A parameterized test fixture must be derived from testing::Test and from +// testing::WithParamInterface, where T is the type of the parameter +// values. Inheriting from TestWithParam satisfies that requirement because +// TestWithParam inherits from both Test and WithParamInterface. In more +// complicated hierarchies, however, it is occasionally useful to inherit +// separately from Test and WithParamInterface. For example: + +class BaseTest : public ::testing::Test { + // You can inherit all the usual members for a non-parameterized test + // fixture here. +}; + +class DerivedTest : public BaseTest, public ::testing::WithParamInterface { + // The usual test fixture members go here too. +}; + +TEST_F(BaseTest, HasFoo) { + // This is an ordinary non-parameterized test. +} + +TEST_P(DerivedTest, DoesBlah) { + // GetParam works just the same here as if you inherit from TestWithParam. + EXPECT_TRUE(foo.Blah(GetParam())); +} + +#endif // 0 + +#include "gtest/internal/gtest-port.h" + +#if !GTEST_OS_SYMBIAN +# include +#endif + +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-param-util-generated.h" + +#if GTEST_HAS_PARAM_TEST + +namespace testing { + +// Functions producing parameter generators. +// +// Google Test uses these generators to produce parameters for value- +// parameterized tests. When a parameterized test case is instantiated +// with a particular generator, Google Test creates and runs tests +// for each element in the sequence produced by the generator. +// +// In the following sample, tests from test case FooTest are instantiated +// each three times with parameter values 3, 5, and 8: +// +// class FooTest : public TestWithParam { ... }; +// +// TEST_P(FooTest, TestThis) { +// } +// TEST_P(FooTest, TestThat) { +// } +// INSTANTIATE_TEST_CASE_P(TestSequence, FooTest, Values(3, 5, 8)); +// + +// Range() returns generators providing sequences of values in a range. +// +// Synopsis: +// Range(start, end) +// - returns a generator producing a sequence of values {start, start+1, +// start+2, ..., }. +// Range(start, end, step) +// - returns a generator producing a sequence of values {start, start+step, +// start+step+step, ..., }. +// Notes: +// * The generated sequences never include end. For example, Range(1, 5) +// returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2) +// returns a generator producing {1, 3, 5, 7}. +// * start and end must have the same type. That type may be any integral or +// floating-point type or a user defined type satisfying these conditions: +// * It must be assignable (have operator=() defined). +// * It must have operator+() (operator+(int-compatible type) for +// two-operand version). +// * It must have operator<() defined. +// Elements in the resulting sequences will also have that type. +// * Condition start < end must be satisfied in order for resulting sequences +// to contain any elements. +// +template +internal::ParamGenerator Range(T start, T end, IncrementT step) { + return internal::ParamGenerator( + new internal::RangeGenerator(start, end, step)); +} + +template +internal::ParamGenerator Range(T start, T end) { + return Range(start, end, 1); +} + +// ValuesIn() function allows generation of tests with parameters coming from +// a container. +// +// Synopsis: +// ValuesIn(const T (&array)[N]) +// - returns a generator producing sequences with elements from +// a C-style array. +// ValuesIn(const Container& container) +// - returns a generator producing sequences with elements from +// an STL-style container. +// ValuesIn(Iterator begin, Iterator end) +// - returns a generator producing sequences with elements from +// a range [begin, end) defined by a pair of STL-style iterators. These +// iterators can also be plain C pointers. +// +// Please note that ValuesIn copies the values from the containers +// passed in and keeps them to generate tests in RUN_ALL_TESTS(). +// +// Examples: +// +// This instantiates tests from test case StringTest +// each with C-string values of "foo", "bar", and "baz": +// +// const char* strings[] = {"foo", "bar", "baz"}; +// INSTANTIATE_TEST_CASE_P(StringSequence, SrtingTest, ValuesIn(strings)); +// +// This instantiates tests from test case StlStringTest +// each with STL strings with values "a" and "b": +// +// ::std::vector< ::std::string> GetParameterStrings() { +// ::std::vector< ::std::string> v; +// v.push_back("a"); +// v.push_back("b"); +// return v; +// } +// +// INSTANTIATE_TEST_CASE_P(CharSequence, +// StlStringTest, +// ValuesIn(GetParameterStrings())); +// +// +// This will also instantiate tests from CharTest +// each with parameter values 'a' and 'b': +// +// ::std::list GetParameterChars() { +// ::std::list list; +// list.push_back('a'); +// list.push_back('b'); +// return list; +// } +// ::std::list l = GetParameterChars(); +// INSTANTIATE_TEST_CASE_P(CharSequence2, +// CharTest, +// ValuesIn(l.begin(), l.end())); +// +template +internal::ParamGenerator< + typename ::testing::internal::IteratorTraits::value_type> +ValuesIn(ForwardIterator begin, ForwardIterator end) { + typedef typename ::testing::internal::IteratorTraits + ::value_type ParamType; + return internal::ParamGenerator( + new internal::ValuesInIteratorRangeGenerator(begin, end)); +} + +template +internal::ParamGenerator ValuesIn(const T (&array)[N]) { + return ValuesIn(array, array + N); +} + +template +internal::ParamGenerator ValuesIn( + const Container& container) { + return ValuesIn(container.begin(), container.end()); +} + +// Values() allows generating tests from explicitly specified list of +// parameters. +// +// Synopsis: +// Values(T v1, T v2, ..., T vN) +// - returns a generator producing sequences with elements v1, v2, ..., vN. +// +// For example, this instantiates tests from test case BarTest each +// with values "one", "two", and "three": +// +// INSTANTIATE_TEST_CASE_P(NumSequence, BarTest, Values("one", "two", "three")); +// +// This instantiates tests from test case BazTest each with values 1, 2, 3.5. +// The exact type of values will depend on the type of parameter in BazTest. +// +// INSTANTIATE_TEST_CASE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); +// +// Currently, Values() supports from 1 to 50 parameters. +// +template +internal::ValueArray1 Values(T1 v1) { + return internal::ValueArray1(v1); +} + +template +internal::ValueArray2 Values(T1 v1, T2 v2) { + return internal::ValueArray2(v1, v2); +} + +template +internal::ValueArray3 Values(T1 v1, T2 v2, T3 v3) { + return internal::ValueArray3(v1, v2, v3); +} + +template +internal::ValueArray4 Values(T1 v1, T2 v2, T3 v3, T4 v4) { + return internal::ValueArray4(v1, v2, v3, v4); +} + +template +internal::ValueArray5 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5) { + return internal::ValueArray5(v1, v2, v3, v4, v5); +} + +template +internal::ValueArray6 Values(T1 v1, T2 v2, T3 v3, + T4 v4, T5 v5, T6 v6) { + return internal::ValueArray6(v1, v2, v3, v4, v5, v6); +} + +template +internal::ValueArray7 Values(T1 v1, T2 v2, T3 v3, + T4 v4, T5 v5, T6 v6, T7 v7) { + return internal::ValueArray7(v1, v2, v3, v4, v5, + v6, v7); +} + +template +internal::ValueArray8 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) { + return internal::ValueArray8(v1, v2, v3, v4, + v5, v6, v7, v8); +} + +template +internal::ValueArray9 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) { + return internal::ValueArray9(v1, v2, v3, + v4, v5, v6, v7, v8, v9); +} + +template +internal::ValueArray10 Values(T1 v1, + T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) { + return internal::ValueArray10(v1, + v2, v3, v4, v5, v6, v7, v8, v9, v10); +} + +template +internal::ValueArray11 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11) { + return internal::ValueArray11(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11); +} + +template +internal::ValueArray12 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12) { + return internal::ValueArray12(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12); +} + +template +internal::ValueArray13 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13) { + return internal::ValueArray13(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13); +} + +template +internal::ValueArray14 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) { + return internal::ValueArray14(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, + v14); +} + +template +internal::ValueArray15 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, + T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) { + return internal::ValueArray15(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, + v13, v14, v15); +} + +template +internal::ValueArray16 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16) { + return internal::ValueArray16(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, + v12, v13, v14, v15, v16); +} + +template +internal::ValueArray17 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17) { + return internal::ValueArray17(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, + v11, v12, v13, v14, v15, v16, v17); +} + +template +internal::ValueArray18 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, + T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18) { + return internal::ValueArray18(v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18); +} + +template +internal::ValueArray19 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, + T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19) { + return internal::ValueArray19(v1, v2, v3, v4, v5, v6, v7, v8, + v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19); +} + +template +internal::ValueArray20 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20) { + return internal::ValueArray20(v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20); +} + +template +internal::ValueArray21 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21) { + return internal::ValueArray21(v1, v2, v3, v4, v5, v6, + v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21); +} + +template +internal::ValueArray22 Values(T1 v1, T2 v2, T3 v3, + T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22) { + return internal::ValueArray22(v1, v2, v3, v4, + v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22); +} + +template +internal::ValueArray23 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23) { + return internal::ValueArray23(v1, v2, v3, + v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22, v23); +} + +template +internal::ValueArray24 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23, T24 v24) { + return internal::ValueArray24(v1, v2, + v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, + v19, v20, v21, v22, v23, v24); +} + +template +internal::ValueArray25 Values(T1 v1, + T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, + T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, + T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25) { + return internal::ValueArray25(v1, + v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, + v18, v19, v20, v21, v22, v23, v24, v25); +} + +template +internal::ValueArray26 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26) { + return internal::ValueArray26(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, + v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26); +} + +template +internal::ValueArray27 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27) { + return internal::ValueArray27(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, + v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27); +} + +template +internal::ValueArray28 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28) { + return internal::ValueArray28(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, + v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, + v28); +} + +template +internal::ValueArray29 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29) { + return internal::ValueArray29(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, + v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, + v27, v28, v29); +} + +template +internal::ValueArray30 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, + T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, + T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) { + return internal::ValueArray30(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, + v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, + v26, v27, v28, v29, v30); +} + +template +internal::ValueArray31 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) { + return internal::ValueArray31(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, + v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31); +} + +template +internal::ValueArray32 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32) { + return internal::ValueArray32(v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, + v24, v25, v26, v27, v28, v29, v30, v31, v32); +} + +template +internal::ValueArray33 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, + T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32, T33 v33) { + return internal::ValueArray33(v1, v2, v3, v4, v5, v6, v7, v8, + v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, + v24, v25, v26, v27, v28, v29, v30, v31, v32, v33); +} + +template +internal::ValueArray34 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, + T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, + T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, + T31 v31, T32 v32, T33 v33, T34 v34) { + return internal::ValueArray34(v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, + v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34); +} + +template +internal::ValueArray35 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, + T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, + T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35) { + return internal::ValueArray35(v1, v2, v3, v4, v5, v6, + v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, + v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35); +} + +template +internal::ValueArray36 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, + T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, + T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36) { + return internal::ValueArray36(v1, v2, v3, v4, + v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, + v34, v35, v36); +} + +template +internal::ValueArray37 Values(T1 v1, T2 v2, T3 v3, + T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, + T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, + T37 v37) { + return internal::ValueArray37(v1, v2, v3, + v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, + v34, v35, v36, v37); +} + +template +internal::ValueArray38 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, + T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, + T37 v37, T38 v38) { + return internal::ValueArray38(v1, v2, + v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, + v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, + v33, v34, v35, v36, v37, v38); +} + +template +internal::ValueArray39 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, + T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, + T37 v37, T38 v38, T39 v39) { + return internal::ValueArray39(v1, + v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, + v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, + v32, v33, v34, v35, v36, v37, v38, v39); +} + +template +internal::ValueArray40 Values(T1 v1, + T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, + T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, + T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, + T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) { + return internal::ValueArray40(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, + v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, + v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40); +} + +template +internal::ValueArray41 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41) { + return internal::ValueArray41(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, + v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, + v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41); +} + +template +internal::ValueArray42 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42) { + return internal::ValueArray42(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, + v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, + v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, + v42); +} + +template +internal::ValueArray43 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43) { + return internal::ValueArray43(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, + v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, + v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, + v41, v42, v43); +} + +template +internal::ValueArray44 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44) { + return internal::ValueArray44(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, + v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, + v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, + v40, v41, v42, v43, v44); +} + +template +internal::ValueArray45 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, + T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, + T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, + T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, + T41 v41, T42 v42, T43 v43, T44 v44, T45 v45) { + return internal::ValueArray45(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, + v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, + v39, v40, v41, v42, v43, v44, v45); +} + +template +internal::ValueArray46 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, + T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) { + return internal::ValueArray46(v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, + v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, + v38, v39, v40, v41, v42, v43, v44, v45, v46); +} + +template +internal::ValueArray47 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, + T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) { + return internal::ValueArray47(v1, v2, v3, v4, v5, v6, v7, v8, + v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, + v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, + v38, v39, v40, v41, v42, v43, v44, v45, v46, v47); +} + +template +internal::ValueArray48 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, + T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, + T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, + T48 v48) { + return internal::ValueArray48(v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, + v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, + v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48); +} + +template +internal::ValueArray49 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, + T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, + T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, + T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, + T47 v47, T48 v48, T49 v49) { + return internal::ValueArray49(v1, v2, v3, v4, v5, v6, + v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, + v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, + v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49); +} + +template +internal::ValueArray50 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, + T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, + T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, + T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, + T46 v46, T47 v47, T48 v48, T49 v49, T50 v50) { + return internal::ValueArray50(v1, v2, v3, v4, + v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, + v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, + v48, v49, v50); +} + +// Bool() allows generating tests with parameters in a set of (false, true). +// +// Synopsis: +// Bool() +// - returns a generator producing sequences with elements {false, true}. +// +// It is useful when testing code that depends on Boolean flags. Combinations +// of multiple flags can be tested when several Bool()'s are combined using +// Combine() function. +// +// In the following example all tests in the test case FlagDependentTest +// will be instantiated twice with parameters false and true. +// +// class FlagDependentTest : public testing::TestWithParam { +// virtual void SetUp() { +// external_flag = GetParam(); +// } +// } +// INSTANTIATE_TEST_CASE_P(BoolSequence, FlagDependentTest, Bool()); +// +inline internal::ParamGenerator Bool() { + return Values(false, true); +} + +# if GTEST_HAS_COMBINE +// Combine() allows the user to combine two or more sequences to produce +// values of a Cartesian product of those sequences' elements. +// +// Synopsis: +// Combine(gen1, gen2, ..., genN) +// - returns a generator producing sequences with elements coming from +// the Cartesian product of elements from the sequences generated by +// gen1, gen2, ..., genN. The sequence elements will have a type of +// tuple where T1, T2, ..., TN are the types +// of elements from sequences produces by gen1, gen2, ..., genN. +// +// Combine can have up to 10 arguments. This number is currently limited +// by the maximum number of elements in the tuple implementation used by Google +// Test. +// +// Example: +// +// This will instantiate tests in test case AnimalTest each one with +// the parameter values tuple("cat", BLACK), tuple("cat", WHITE), +// tuple("dog", BLACK), and tuple("dog", WHITE): +// +// enum Color { BLACK, GRAY, WHITE }; +// class AnimalTest +// : public testing::TestWithParam > {...}; +// +// TEST_P(AnimalTest, AnimalLooksNice) {...} +// +// INSTANTIATE_TEST_CASE_P(AnimalVariations, AnimalTest, +// Combine(Values("cat", "dog"), +// Values(BLACK, WHITE))); +// +// This will instantiate tests in FlagDependentTest with all variations of two +// Boolean flags: +// +// class FlagDependentTest +// : public testing::TestWithParam > { +// virtual void SetUp() { +// // Assigns external_flag_1 and external_flag_2 values from the tuple. +// tie(external_flag_1, external_flag_2) = GetParam(); +// } +// }; +// +// TEST_P(FlagDependentTest, TestFeature1) { +// // Test your code using external_flag_1 and external_flag_2 here. +// } +// INSTANTIATE_TEST_CASE_P(TwoBoolSequence, FlagDependentTest, +// Combine(Bool(), Bool())); +// +template +internal::CartesianProductHolder2 Combine( + const Generator1& g1, const Generator2& g2) { + return internal::CartesianProductHolder2( + g1, g2); +} + +template +internal::CartesianProductHolder3 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3) { + return internal::CartesianProductHolder3( + g1, g2, g3); +} + +template +internal::CartesianProductHolder4 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4) { + return internal::CartesianProductHolder4( + g1, g2, g3, g4); +} + +template +internal::CartesianProductHolder5 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5) { + return internal::CartesianProductHolder5( + g1, g2, g3, g4, g5); +} + +template +internal::CartesianProductHolder6 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6) { + return internal::CartesianProductHolder6( + g1, g2, g3, g4, g5, g6); +} + +template +internal::CartesianProductHolder7 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6, + const Generator7& g7) { + return internal::CartesianProductHolder7( + g1, g2, g3, g4, g5, g6, g7); +} + +template +internal::CartesianProductHolder8 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6, + const Generator7& g7, const Generator8& g8) { + return internal::CartesianProductHolder8( + g1, g2, g3, g4, g5, g6, g7, g8); +} + +template +internal::CartesianProductHolder9 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6, + const Generator7& g7, const Generator8& g8, const Generator9& g9) { + return internal::CartesianProductHolder9( + g1, g2, g3, g4, g5, g6, g7, g8, g9); +} + +template +internal::CartesianProductHolder10 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6, + const Generator7& g7, const Generator8& g8, const Generator9& g9, + const Generator10& g10) { + return internal::CartesianProductHolder10( + g1, g2, g3, g4, g5, g6, g7, g8, g9, g10); +} +# endif // GTEST_HAS_COMBINE + + + +# define TEST_P(test_case_name, test_name) \ + class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ + : public test_case_name { \ + public: \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ + virtual void TestBody(); \ + private: \ + static int AddToRegistry() { \ + ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ + GetTestCasePatternHolder(\ + #test_case_name, __FILE__, __LINE__)->AddTestPattern(\ + #test_case_name, \ + #test_name, \ + new ::testing::internal::TestMetaFactory< \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>()); \ + return 0; \ + } \ + static int gtest_registering_dummy_; \ + GTEST_DISALLOW_COPY_AND_ASSIGN_(\ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ + }; \ + int GTEST_TEST_CLASS_NAME_(test_case_name, \ + test_name)::gtest_registering_dummy_ = \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ + void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() + +# define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator) \ + ::testing::internal::ParamGenerator \ + gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \ + int gtest_##prefix##test_case_name##_dummy_ = \ + ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ + GetTestCasePatternHolder(\ + #test_case_name, __FILE__, __LINE__)->AddTestCaseInstantiation(\ + #prefix, \ + >est_##prefix##test_case_name##_EvalGenerator_, \ + __FILE__, __LINE__) + +} // namespace testing + +#endif // GTEST_HAS_PARAM_TEST + +#endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ diff --git a/lib/gtest/include/gtest/gtest-param-test.h.pump b/lib/gtest/include/gtest/gtest-param-test.h.pump new file mode 100644 index 00000000..2dc9303b --- /dev/null +++ b/lib/gtest/include/gtest/gtest-param-test.h.pump @@ -0,0 +1,487 @@ +$$ -*- mode: c++; -*- +$var n = 50 $$ Maximum length of Values arguments we want to support. +$var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: vladl@google.com (Vlad Losev) +// +// Macros and functions for implementing parameterized tests +// in Google C++ Testing Framework (Google Test) +// +// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ +#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ + + +// Value-parameterized tests allow you to test your code with different +// parameters without writing multiple copies of the same test. +// +// Here is how you use value-parameterized tests: + +#if 0 + +// To write value-parameterized tests, first you should define a fixture +// class. It is usually derived from testing::TestWithParam (see below for +// another inheritance scheme that's sometimes useful in more complicated +// class hierarchies), where the type of your parameter values. +// TestWithParam is itself derived from testing::Test. T can be any +// copyable type. If it's a raw pointer, you are responsible for managing the +// lifespan of the pointed values. + +class FooTest : public ::testing::TestWithParam { + // You can implement all the usual class fixture members here. +}; + +// Then, use the TEST_P macro to define as many parameterized tests +// for this fixture as you want. The _P suffix is for "parameterized" +// or "pattern", whichever you prefer to think. + +TEST_P(FooTest, DoesBlah) { + // Inside a test, access the test parameter with the GetParam() method + // of the TestWithParam class: + EXPECT_TRUE(foo.Blah(GetParam())); + ... +} + +TEST_P(FooTest, HasBlahBlah) { + ... +} + +// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test +// case with any set of parameters you want. Google Test defines a number +// of functions for generating test parameters. They return what we call +// (surprise!) parameter generators. Here is a summary of them, which +// are all in the testing namespace: +// +// +// Range(begin, end [, step]) - Yields values {begin, begin+step, +// begin+step+step, ...}. The values do not +// include end. step defaults to 1. +// Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}. +// ValuesIn(container) - Yields values from a C-style array, an STL +// ValuesIn(begin,end) container, or an iterator range [begin, end). +// Bool() - Yields sequence {false, true}. +// Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product +// for the math savvy) of the values generated +// by the N generators. +// +// For more details, see comments at the definitions of these functions below +// in this file. +// +// The following statement will instantiate tests from the FooTest test case +// each with parameter values "meeny", "miny", and "moe". + +INSTANTIATE_TEST_CASE_P(InstantiationName, + FooTest, + Values("meeny", "miny", "moe")); + +// To distinguish different instances of the pattern, (yes, you +// can instantiate it more then once) the first argument to the +// INSTANTIATE_TEST_CASE_P macro is a prefix that will be added to the +// actual test case name. Remember to pick unique prefixes for different +// instantiations. The tests from the instantiation above will have +// these names: +// +// * InstantiationName/FooTest.DoesBlah/0 for "meeny" +// * InstantiationName/FooTest.DoesBlah/1 for "miny" +// * InstantiationName/FooTest.DoesBlah/2 for "moe" +// * InstantiationName/FooTest.HasBlahBlah/0 for "meeny" +// * InstantiationName/FooTest.HasBlahBlah/1 for "miny" +// * InstantiationName/FooTest.HasBlahBlah/2 for "moe" +// +// You can use these names in --gtest_filter. +// +// This statement will instantiate all tests from FooTest again, each +// with parameter values "cat" and "dog": + +const char* pets[] = {"cat", "dog"}; +INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); + +// The tests from the instantiation above will have these names: +// +// * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat" +// * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog" +// * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat" +// * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog" +// +// Please note that INSTANTIATE_TEST_CASE_P will instantiate all tests +// in the given test case, whether their definitions come before or +// AFTER the INSTANTIATE_TEST_CASE_P statement. +// +// Please also note that generator expressions (including parameters to the +// generators) are evaluated in InitGoogleTest(), after main() has started. +// This allows the user on one hand, to adjust generator parameters in order +// to dynamically determine a set of tests to run and on the other hand, +// give the user a chance to inspect the generated tests with Google Test +// reflection API before RUN_ALL_TESTS() is executed. +// +// You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc +// for more examples. +// +// In the future, we plan to publish the API for defining new parameter +// generators. But for now this interface remains part of the internal +// implementation and is subject to change. +// +// +// A parameterized test fixture must be derived from testing::Test and from +// testing::WithParamInterface, where T is the type of the parameter +// values. Inheriting from TestWithParam satisfies that requirement because +// TestWithParam inherits from both Test and WithParamInterface. In more +// complicated hierarchies, however, it is occasionally useful to inherit +// separately from Test and WithParamInterface. For example: + +class BaseTest : public ::testing::Test { + // You can inherit all the usual members for a non-parameterized test + // fixture here. +}; + +class DerivedTest : public BaseTest, public ::testing::WithParamInterface { + // The usual test fixture members go here too. +}; + +TEST_F(BaseTest, HasFoo) { + // This is an ordinary non-parameterized test. +} + +TEST_P(DerivedTest, DoesBlah) { + // GetParam works just the same here as if you inherit from TestWithParam. + EXPECT_TRUE(foo.Blah(GetParam())); +} + +#endif // 0 + +#include "gtest/internal/gtest-port.h" + +#if !GTEST_OS_SYMBIAN +# include +#endif + +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-param-util-generated.h" + +#if GTEST_HAS_PARAM_TEST + +namespace testing { + +// Functions producing parameter generators. +// +// Google Test uses these generators to produce parameters for value- +// parameterized tests. When a parameterized test case is instantiated +// with a particular generator, Google Test creates and runs tests +// for each element in the sequence produced by the generator. +// +// In the following sample, tests from test case FooTest are instantiated +// each three times with parameter values 3, 5, and 8: +// +// class FooTest : public TestWithParam { ... }; +// +// TEST_P(FooTest, TestThis) { +// } +// TEST_P(FooTest, TestThat) { +// } +// INSTANTIATE_TEST_CASE_P(TestSequence, FooTest, Values(3, 5, 8)); +// + +// Range() returns generators providing sequences of values in a range. +// +// Synopsis: +// Range(start, end) +// - returns a generator producing a sequence of values {start, start+1, +// start+2, ..., }. +// Range(start, end, step) +// - returns a generator producing a sequence of values {start, start+step, +// start+step+step, ..., }. +// Notes: +// * The generated sequences never include end. For example, Range(1, 5) +// returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2) +// returns a generator producing {1, 3, 5, 7}. +// * start and end must have the same type. That type may be any integral or +// floating-point type or a user defined type satisfying these conditions: +// * It must be assignable (have operator=() defined). +// * It must have operator+() (operator+(int-compatible type) for +// two-operand version). +// * It must have operator<() defined. +// Elements in the resulting sequences will also have that type. +// * Condition start < end must be satisfied in order for resulting sequences +// to contain any elements. +// +template +internal::ParamGenerator Range(T start, T end, IncrementT step) { + return internal::ParamGenerator( + new internal::RangeGenerator(start, end, step)); +} + +template +internal::ParamGenerator Range(T start, T end) { + return Range(start, end, 1); +} + +// ValuesIn() function allows generation of tests with parameters coming from +// a container. +// +// Synopsis: +// ValuesIn(const T (&array)[N]) +// - returns a generator producing sequences with elements from +// a C-style array. +// ValuesIn(const Container& container) +// - returns a generator producing sequences with elements from +// an STL-style container. +// ValuesIn(Iterator begin, Iterator end) +// - returns a generator producing sequences with elements from +// a range [begin, end) defined by a pair of STL-style iterators. These +// iterators can also be plain C pointers. +// +// Please note that ValuesIn copies the values from the containers +// passed in and keeps them to generate tests in RUN_ALL_TESTS(). +// +// Examples: +// +// This instantiates tests from test case StringTest +// each with C-string values of "foo", "bar", and "baz": +// +// const char* strings[] = {"foo", "bar", "baz"}; +// INSTANTIATE_TEST_CASE_P(StringSequence, SrtingTest, ValuesIn(strings)); +// +// This instantiates tests from test case StlStringTest +// each with STL strings with values "a" and "b": +// +// ::std::vector< ::std::string> GetParameterStrings() { +// ::std::vector< ::std::string> v; +// v.push_back("a"); +// v.push_back("b"); +// return v; +// } +// +// INSTANTIATE_TEST_CASE_P(CharSequence, +// StlStringTest, +// ValuesIn(GetParameterStrings())); +// +// +// This will also instantiate tests from CharTest +// each with parameter values 'a' and 'b': +// +// ::std::list GetParameterChars() { +// ::std::list list; +// list.push_back('a'); +// list.push_back('b'); +// return list; +// } +// ::std::list l = GetParameterChars(); +// INSTANTIATE_TEST_CASE_P(CharSequence2, +// CharTest, +// ValuesIn(l.begin(), l.end())); +// +template +internal::ParamGenerator< + typename ::testing::internal::IteratorTraits::value_type> +ValuesIn(ForwardIterator begin, ForwardIterator end) { + typedef typename ::testing::internal::IteratorTraits + ::value_type ParamType; + return internal::ParamGenerator( + new internal::ValuesInIteratorRangeGenerator(begin, end)); +} + +template +internal::ParamGenerator ValuesIn(const T (&array)[N]) { + return ValuesIn(array, array + N); +} + +template +internal::ParamGenerator ValuesIn( + const Container& container) { + return ValuesIn(container.begin(), container.end()); +} + +// Values() allows generating tests from explicitly specified list of +// parameters. +// +// Synopsis: +// Values(T v1, T v2, ..., T vN) +// - returns a generator producing sequences with elements v1, v2, ..., vN. +// +// For example, this instantiates tests from test case BarTest each +// with values "one", "two", and "three": +// +// INSTANTIATE_TEST_CASE_P(NumSequence, BarTest, Values("one", "two", "three")); +// +// This instantiates tests from test case BazTest each with values 1, 2, 3.5. +// The exact type of values will depend on the type of parameter in BazTest. +// +// INSTANTIATE_TEST_CASE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); +// +// Currently, Values() supports from 1 to $n parameters. +// +$range i 1..n +$for i [[ +$range j 1..i + +template <$for j, [[typename T$j]]> +internal::ValueArray$i<$for j, [[T$j]]> Values($for j, [[T$j v$j]]) { + return internal::ValueArray$i<$for j, [[T$j]]>($for j, [[v$j]]); +} + +]] + +// Bool() allows generating tests with parameters in a set of (false, true). +// +// Synopsis: +// Bool() +// - returns a generator producing sequences with elements {false, true}. +// +// It is useful when testing code that depends on Boolean flags. Combinations +// of multiple flags can be tested when several Bool()'s are combined using +// Combine() function. +// +// In the following example all tests in the test case FlagDependentTest +// will be instantiated twice with parameters false and true. +// +// class FlagDependentTest : public testing::TestWithParam { +// virtual void SetUp() { +// external_flag = GetParam(); +// } +// } +// INSTANTIATE_TEST_CASE_P(BoolSequence, FlagDependentTest, Bool()); +// +inline internal::ParamGenerator Bool() { + return Values(false, true); +} + +# if GTEST_HAS_COMBINE +// Combine() allows the user to combine two or more sequences to produce +// values of a Cartesian product of those sequences' elements. +// +// Synopsis: +// Combine(gen1, gen2, ..., genN) +// - returns a generator producing sequences with elements coming from +// the Cartesian product of elements from the sequences generated by +// gen1, gen2, ..., genN. The sequence elements will have a type of +// tuple where T1, T2, ..., TN are the types +// of elements from sequences produces by gen1, gen2, ..., genN. +// +// Combine can have up to $maxtuple arguments. This number is currently limited +// by the maximum number of elements in the tuple implementation used by Google +// Test. +// +// Example: +// +// This will instantiate tests in test case AnimalTest each one with +// the parameter values tuple("cat", BLACK), tuple("cat", WHITE), +// tuple("dog", BLACK), and tuple("dog", WHITE): +// +// enum Color { BLACK, GRAY, WHITE }; +// class AnimalTest +// : public testing::TestWithParam > {...}; +// +// TEST_P(AnimalTest, AnimalLooksNice) {...} +// +// INSTANTIATE_TEST_CASE_P(AnimalVariations, AnimalTest, +// Combine(Values("cat", "dog"), +// Values(BLACK, WHITE))); +// +// This will instantiate tests in FlagDependentTest with all variations of two +// Boolean flags: +// +// class FlagDependentTest +// : public testing::TestWithParam > { +// virtual void SetUp() { +// // Assigns external_flag_1 and external_flag_2 values from the tuple. +// tie(external_flag_1, external_flag_2) = GetParam(); +// } +// }; +// +// TEST_P(FlagDependentTest, TestFeature1) { +// // Test your code using external_flag_1 and external_flag_2 here. +// } +// INSTANTIATE_TEST_CASE_P(TwoBoolSequence, FlagDependentTest, +// Combine(Bool(), Bool())); +// +$range i 2..maxtuple +$for i [[ +$range j 1..i + +template <$for j, [[typename Generator$j]]> +internal::CartesianProductHolder$i<$for j, [[Generator$j]]> Combine( + $for j, [[const Generator$j& g$j]]) { + return internal::CartesianProductHolder$i<$for j, [[Generator$j]]>( + $for j, [[g$j]]); +} + +]] +# endif // GTEST_HAS_COMBINE + + + +# define TEST_P(test_case_name, test_name) \ + class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ + : public test_case_name { \ + public: \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ + virtual void TestBody(); \ + private: \ + static int AddToRegistry() { \ + ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ + GetTestCasePatternHolder(\ + #test_case_name, __FILE__, __LINE__)->AddTestPattern(\ + #test_case_name, \ + #test_name, \ + new ::testing::internal::TestMetaFactory< \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>()); \ + return 0; \ + } \ + static int gtest_registering_dummy_; \ + GTEST_DISALLOW_COPY_AND_ASSIGN_(\ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ + }; \ + int GTEST_TEST_CLASS_NAME_(test_case_name, \ + test_name)::gtest_registering_dummy_ = \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ + void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() + +# define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator) \ + ::testing::internal::ParamGenerator \ + gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \ + int gtest_##prefix##test_case_name##_dummy_ = \ + ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ + GetTestCasePatternHolder(\ + #test_case_name, __FILE__, __LINE__)->AddTestCaseInstantiation(\ + #prefix, \ + >est_##prefix##test_case_name##_EvalGenerator_, \ + __FILE__, __LINE__) + +} // namespace testing + +#endif // GTEST_HAS_PARAM_TEST + +#endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ diff --git a/lib/gtest/include/gtest/gtest-printers.h b/lib/gtest/include/gtest/gtest-printers.h new file mode 100644 index 00000000..0639d9f5 --- /dev/null +++ b/lib/gtest/include/gtest/gtest-printers.h @@ -0,0 +1,855 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Test - The Google C++ Testing Framework +// +// This file implements a universal value printer that can print a +// value of any type T: +// +// void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr); +// +// A user can teach this function how to print a class type T by +// defining either operator<<() or PrintTo() in the namespace that +// defines T. More specifically, the FIRST defined function in the +// following list will be used (assuming T is defined in namespace +// foo): +// +// 1. foo::PrintTo(const T&, ostream*) +// 2. operator<<(ostream&, const T&) defined in either foo or the +// global namespace. +// +// If none of the above is defined, it will print the debug string of +// the value if it is a protocol buffer, or print the raw bytes in the +// value otherwise. +// +// To aid debugging: when T is a reference type, the address of the +// value is also printed; when T is a (const) char pointer, both the +// pointer value and the NUL-terminated string it points to are +// printed. +// +// We also provide some convenient wrappers: +// +// // Prints a value to a string. For a (const or not) char +// // pointer, the NUL-terminated string (but not the pointer) is +// // printed. +// std::string ::testing::PrintToString(const T& value); +// +// // Prints a value tersely: for a reference type, the referenced +// // value (but not the address) is printed; for a (const or not) char +// // pointer, the NUL-terminated string (but not the pointer) is +// // printed. +// void ::testing::internal::UniversalTersePrint(const T& value, ostream*); +// +// // Prints value using the type inferred by the compiler. The difference +// // from UniversalTersePrint() is that this function prints both the +// // pointer and the NUL-terminated string for a (const or not) char pointer. +// void ::testing::internal::UniversalPrint(const T& value, ostream*); +// +// // Prints the fields of a tuple tersely to a string vector, one +// // element for each field. Tuple support must be enabled in +// // gtest-port.h. +// std::vector UniversalTersePrintTupleFieldsToStrings( +// const Tuple& value); +// +// Known limitation: +// +// The print primitives print the elements of an STL-style container +// using the compiler-inferred type of *iter where iter is a +// const_iterator of the container. When const_iterator is an input +// iterator but not a forward iterator, this inferred type may not +// match value_type, and the print output may be incorrect. In +// practice, this is rarely a problem as for most containers +// const_iterator is a forward iterator. We'll fix this if there's an +// actual need for it. Note that this fix cannot rely on value_type +// being defined as many user-defined container types don't have +// value_type. + +#ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ +#define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ + +#include // NOLINT +#include +#include +#include +#include +#include "gtest/internal/gtest-port.h" +#include "gtest/internal/gtest-internal.h" + +namespace testing { + +// Definitions in the 'internal' and 'internal2' name spaces are +// subject to change without notice. DO NOT USE THEM IN USER CODE! +namespace internal2 { + +// Prints the given number of bytes in the given object to the given +// ostream. +GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, + size_t count, + ::std::ostream* os); + +// For selecting which printer to use when a given type has neither << +// nor PrintTo(). +enum TypeKind { + kProtobuf, // a protobuf type + kConvertibleToInteger, // a type implicitly convertible to BiggestInt + // (e.g. a named or unnamed enum type) + kOtherType // anything else +}; + +// TypeWithoutFormatter::PrintValue(value, os) is called +// by the universal printer to print a value of type T when neither +// operator<< nor PrintTo() is defined for T, where kTypeKind is the +// "kind" of T as defined by enum TypeKind. +template +class TypeWithoutFormatter { + public: + // This default version is called when kTypeKind is kOtherType. + static void PrintValue(const T& value, ::std::ostream* os) { + PrintBytesInObjectTo(reinterpret_cast(&value), + sizeof(value), os); + } +}; + +// We print a protobuf using its ShortDebugString() when the string +// doesn't exceed this many characters; otherwise we print it using +// DebugString() for better readability. +const size_t kProtobufOneLinerMaxLength = 50; + +template +class TypeWithoutFormatter { + public: + static void PrintValue(const T& value, ::std::ostream* os) { + const ::testing::internal::string short_str = value.ShortDebugString(); + const ::testing::internal::string pretty_str = + short_str.length() <= kProtobufOneLinerMaxLength ? + short_str : ("\n" + value.DebugString()); + *os << ("<" + pretty_str + ">"); + } +}; + +template +class TypeWithoutFormatter { + public: + // Since T has no << operator or PrintTo() but can be implicitly + // converted to BiggestInt, we print it as a BiggestInt. + // + // Most likely T is an enum type (either named or unnamed), in which + // case printing it as an integer is the desired behavior. In case + // T is not an enum, printing it as an integer is the best we can do + // given that it has no user-defined printer. + static void PrintValue(const T& value, ::std::ostream* os) { + const internal::BiggestInt kBigInt = value; + *os << kBigInt; + } +}; + +// Prints the given value to the given ostream. If the value is a +// protocol message, its debug string is printed; if it's an enum or +// of a type implicitly convertible to BiggestInt, it's printed as an +// integer; otherwise the bytes in the value are printed. This is +// what UniversalPrinter::Print() does when it knows nothing about +// type T and T has neither << operator nor PrintTo(). +// +// A user can override this behavior for a class type Foo by defining +// a << operator in the namespace where Foo is defined. +// +// We put this operator in namespace 'internal2' instead of 'internal' +// to simplify the implementation, as much code in 'internal' needs to +// use << in STL, which would conflict with our own << were it defined +// in 'internal'. +// +// Note that this operator<< takes a generic std::basic_ostream type instead of the more restricted std::ostream. If +// we define it to take an std::ostream instead, we'll get an +// "ambiguous overloads" compiler error when trying to print a type +// Foo that supports streaming to std::basic_ostream, as the compiler cannot tell whether +// operator<<(std::ostream&, const T&) or +// operator<<(std::basic_stream, const Foo&) is more +// specific. +template +::std::basic_ostream& operator<<( + ::std::basic_ostream& os, const T& x) { + TypeWithoutFormatter::value ? kProtobuf : + internal::ImplicitlyConvertible::value ? + kConvertibleToInteger : kOtherType)>::PrintValue(x, &os); + return os; +} + +} // namespace internal2 +} // namespace testing + +// This namespace MUST NOT BE NESTED IN ::testing, or the name look-up +// magic needed for implementing UniversalPrinter won't work. +namespace testing_internal { + +// Used to print a value that is not an STL-style container when the +// user doesn't define PrintTo() for it. +template +void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) { + // With the following statement, during unqualified name lookup, + // testing::internal2::operator<< appears as if it was declared in + // the nearest enclosing namespace that contains both + // ::testing_internal and ::testing::internal2, i.e. the global + // namespace. For more details, refer to the C++ Standard section + // 7.3.4-1 [namespace.udir]. This allows us to fall back onto + // testing::internal2::operator<< in case T doesn't come with a << + // operator. + // + // We cannot write 'using ::testing::internal2::operator<<;', which + // gcc 3.3 fails to compile due to a compiler bug. + using namespace ::testing::internal2; // NOLINT + + // Assuming T is defined in namespace foo, in the next statement, + // the compiler will consider all of: + // + // 1. foo::operator<< (thanks to Koenig look-up), + // 2. ::operator<< (as the current namespace is enclosed in ::), + // 3. testing::internal2::operator<< (thanks to the using statement above). + // + // The operator<< whose type matches T best will be picked. + // + // We deliberately allow #2 to be a candidate, as sometimes it's + // impossible to define #1 (e.g. when foo is ::std, defining + // anything in it is undefined behavior unless you are a compiler + // vendor.). + *os << value; +} + +} // namespace testing_internal + +namespace testing { +namespace internal { + +// UniversalPrinter::Print(value, ostream_ptr) prints the given +// value to the given ostream. The caller must ensure that +// 'ostream_ptr' is not NULL, or the behavior is undefined. +// +// We define UniversalPrinter as a class template (as opposed to a +// function template), as we need to partially specialize it for +// reference types, which cannot be done with function templates. +template +class UniversalPrinter; + +template +void UniversalPrint(const T& value, ::std::ostream* os); + +// Used to print an STL-style container when the user doesn't define +// a PrintTo() for it. +template +void DefaultPrintTo(IsContainer /* dummy */, + false_type /* is not a pointer */, + const C& container, ::std::ostream* os) { + const size_t kMaxCount = 32; // The maximum number of elements to print. + *os << '{'; + size_t count = 0; + for (typename C::const_iterator it = container.begin(); + it != container.end(); ++it, ++count) { + if (count > 0) { + *os << ','; + if (count == kMaxCount) { // Enough has been printed. + *os << " ..."; + break; + } + } + *os << ' '; + // We cannot call PrintTo(*it, os) here as PrintTo() doesn't + // handle *it being a native array. + internal::UniversalPrint(*it, os); + } + + if (count > 0) { + *os << ' '; + } + *os << '}'; +} + +// Used to print a pointer that is neither a char pointer nor a member +// pointer, when the user doesn't define PrintTo() for it. (A member +// variable pointer or member function pointer doesn't really point to +// a location in the address space. Their representation is +// implementation-defined. Therefore they will be printed as raw +// bytes.) +template +void DefaultPrintTo(IsNotContainer /* dummy */, + true_type /* is a pointer */, + T* p, ::std::ostream* os) { + if (p == NULL) { + *os << "NULL"; + } else { + // C++ doesn't allow casting from a function pointer to any object + // pointer. + // + // IsTrue() silences warnings: "Condition is always true", + // "unreachable code". + if (IsTrue(ImplicitlyConvertible::value)) { + // T is not a function type. We just call << to print p, + // relying on ADL to pick up user-defined << for their pointer + // types, if any. + *os << p; + } else { + // T is a function type, so '*os << p' doesn't do what we want + // (it just prints p as bool). We want to print p as a const + // void*. However, we cannot cast it to const void* directly, + // even using reinterpret_cast, as earlier versions of gcc + // (e.g. 3.4.5) cannot compile the cast when p is a function + // pointer. Casting to UInt64 first solves the problem. + *os << reinterpret_cast( + reinterpret_cast(p)); + } + } +} + +// Used to print a non-container, non-pointer value when the user +// doesn't define PrintTo() for it. +template +void DefaultPrintTo(IsNotContainer /* dummy */, + false_type /* is not a pointer */, + const T& value, ::std::ostream* os) { + ::testing_internal::DefaultPrintNonContainerTo(value, os); +} + +// Prints the given value using the << operator if it has one; +// otherwise prints the bytes in it. This is what +// UniversalPrinter::Print() does when PrintTo() is not specialized +// or overloaded for type T. +// +// A user can override this behavior for a class type Foo by defining +// an overload of PrintTo() in the namespace where Foo is defined. We +// give the user this option as sometimes defining a << operator for +// Foo is not desirable (e.g. the coding style may prevent doing it, +// or there is already a << operator but it doesn't do what the user +// wants). +template +void PrintTo(const T& value, ::std::ostream* os) { + // DefaultPrintTo() is overloaded. The type of its first two + // arguments determine which version will be picked. If T is an + // STL-style container, the version for container will be called; if + // T is a pointer, the pointer version will be called; otherwise the + // generic version will be called. + // + // Note that we check for container types here, prior to we check + // for protocol message types in our operator<<. The rationale is: + // + // For protocol messages, we want to give people a chance to + // override Google Mock's format by defining a PrintTo() or + // operator<<. For STL containers, other formats can be + // incompatible with Google Mock's format for the container + // elements; therefore we check for container types here to ensure + // that our format is used. + // + // The second argument of DefaultPrintTo() is needed to bypass a bug + // in Symbian's C++ compiler that prevents it from picking the right + // overload between: + // + // PrintTo(const T& x, ...); + // PrintTo(T* x, ...); + DefaultPrintTo(IsContainerTest(0), is_pointer(), value, os); +} + +// The following list of PrintTo() overloads tells +// UniversalPrinter::Print() how to print standard types (built-in +// types, strings, plain arrays, and pointers). + +// Overloads for various char types. +GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os); +GTEST_API_ void PrintTo(signed char c, ::std::ostream* os); +inline void PrintTo(char c, ::std::ostream* os) { + // When printing a plain char, we always treat it as unsigned. This + // way, the output won't be affected by whether the compiler thinks + // char is signed or not. + PrintTo(static_cast(c), os); +} + +// Overloads for other simple built-in types. +inline void PrintTo(bool x, ::std::ostream* os) { + *os << (x ? "true" : "false"); +} + +// Overload for wchar_t type. +// Prints a wchar_t as a symbol if it is printable or as its internal +// code otherwise and also as its decimal code (except for L'\0'). +// The L'\0' char is printed as "L'\\0'". The decimal code is printed +// as signed integer when wchar_t is implemented by the compiler +// as a signed type and is printed as an unsigned integer when wchar_t +// is implemented as an unsigned type. +GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os); + +// Overloads for C strings. +GTEST_API_ void PrintTo(const char* s, ::std::ostream* os); +inline void PrintTo(char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} + +// signed/unsigned char is often used for representing binary data, so +// we print pointers to it as void* to be safe. +inline void PrintTo(const signed char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} +inline void PrintTo(signed char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} +inline void PrintTo(const unsigned char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} +inline void PrintTo(unsigned char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} + +// MSVC can be configured to define wchar_t as a typedef of unsigned +// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native +// type. When wchar_t is a typedef, defining an overload for const +// wchar_t* would cause unsigned short* be printed as a wide string, +// possibly causing invalid memory accesses. +#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) +// Overloads for wide C strings +GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os); +inline void PrintTo(wchar_t* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} +#endif + +// Overload for C arrays. Multi-dimensional arrays are printed +// properly. + +// Prints the given number of elements in an array, without printing +// the curly braces. +template +void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) { + UniversalPrint(a[0], os); + for (size_t i = 1; i != count; i++) { + *os << ", "; + UniversalPrint(a[i], os); + } +} + +// Overloads for ::string and ::std::string. +#if GTEST_HAS_GLOBAL_STRING +GTEST_API_ void PrintStringTo(const ::string&s, ::std::ostream* os); +inline void PrintTo(const ::string& s, ::std::ostream* os) { + PrintStringTo(s, os); +} +#endif // GTEST_HAS_GLOBAL_STRING + +GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os); +inline void PrintTo(const ::std::string& s, ::std::ostream* os) { + PrintStringTo(s, os); +} + +// Overloads for ::wstring and ::std::wstring. +#if GTEST_HAS_GLOBAL_WSTRING +GTEST_API_ void PrintWideStringTo(const ::wstring&s, ::std::ostream* os); +inline void PrintTo(const ::wstring& s, ::std::ostream* os) { + PrintWideStringTo(s, os); +} +#endif // GTEST_HAS_GLOBAL_WSTRING + +#if GTEST_HAS_STD_WSTRING +GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os); +inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { + PrintWideStringTo(s, os); +} +#endif // GTEST_HAS_STD_WSTRING + +#if GTEST_HAS_TR1_TUPLE +// Overload for ::std::tr1::tuple. Needed for printing function arguments, +// which are packed as tuples. + +// Helper function for printing a tuple. T must be instantiated with +// a tuple type. +template +void PrintTupleTo(const T& t, ::std::ostream* os); + +// Overloaded PrintTo() for tuples of various arities. We support +// tuples of up-to 10 fields. The following implementation works +// regardless of whether tr1::tuple is implemented using the +// non-standard variadic template feature or not. + +inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo( + const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} +#endif // GTEST_HAS_TR1_TUPLE + +// Overload for std::pair. +template +void PrintTo(const ::std::pair& value, ::std::ostream* os) { + *os << '('; + // We cannot use UniversalPrint(value.first, os) here, as T1 may be + // a reference type. The same for printing value.second. + UniversalPrinter::Print(value.first, os); + *os << ", "; + UniversalPrinter::Print(value.second, os); + *os << ')'; +} + +// Implements printing a non-reference type T by letting the compiler +// pick the right overload of PrintTo() for T. +template +class UniversalPrinter { + public: + // MSVC warns about adding const to a function type, so we want to + // disable the warning. +#ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4180) // Temporarily disables warning 4180. +#endif // _MSC_VER + + // Note: we deliberately don't call this PrintTo(), as that name + // conflicts with ::testing::internal::PrintTo in the body of the + // function. + static void Print(const T& value, ::std::ostream* os) { + // By default, ::testing::internal::PrintTo() is used for printing + // the value. + // + // Thanks to Koenig look-up, if T is a class and has its own + // PrintTo() function defined in its namespace, that function will + // be visible here. Since it is more specific than the generic ones + // in ::testing::internal, it will be picked by the compiler in the + // following statement - exactly what we want. + PrintTo(value, os); + } + +#ifdef _MSC_VER +# pragma warning(pop) // Restores the warning state. +#endif // _MSC_VER +}; + +// UniversalPrintArray(begin, len, os) prints an array of 'len' +// elements, starting at address 'begin'. +template +void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { + if (len == 0) { + *os << "{}"; + } else { + *os << "{ "; + const size_t kThreshold = 18; + const size_t kChunkSize = 8; + // If the array has more than kThreshold elements, we'll have to + // omit some details by printing only the first and the last + // kChunkSize elements. + // TODO(wan@google.com): let the user control the threshold using a flag. + if (len <= kThreshold) { + PrintRawArrayTo(begin, len, os); + } else { + PrintRawArrayTo(begin, kChunkSize, os); + *os << ", ..., "; + PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os); + } + *os << " }"; + } +} +// This overload prints a (const) char array compactly. +GTEST_API_ void UniversalPrintArray( + const char* begin, size_t len, ::std::ostream* os); + +// This overload prints a (const) wchar_t array compactly. +GTEST_API_ void UniversalPrintArray( + const wchar_t* begin, size_t len, ::std::ostream* os); + +// Implements printing an array type T[N]. +template +class UniversalPrinter { + public: + // Prints the given array, omitting some elements when there are too + // many. + static void Print(const T (&a)[N], ::std::ostream* os) { + UniversalPrintArray(a, N, os); + } +}; + +// Implements printing a reference type T&. +template +class UniversalPrinter { + public: + // MSVC warns about adding const to a function type, so we want to + // disable the warning. +#ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4180) // Temporarily disables warning 4180. +#endif // _MSC_VER + + static void Print(const T& value, ::std::ostream* os) { + // Prints the address of the value. We use reinterpret_cast here + // as static_cast doesn't compile when T is a function type. + *os << "@" << reinterpret_cast(&value) << " "; + + // Then prints the value itself. + UniversalPrint(value, os); + } + +#ifdef _MSC_VER +# pragma warning(pop) // Restores the warning state. +#endif // _MSC_VER +}; + +// Prints a value tersely: for a reference type, the referenced value +// (but not the address) is printed; for a (const) char pointer, the +// NUL-terminated string (but not the pointer) is printed. + +template +class UniversalTersePrinter { + public: + static void Print(const T& value, ::std::ostream* os) { + UniversalPrint(value, os); + } +}; +template +class UniversalTersePrinter { + public: + static void Print(const T& value, ::std::ostream* os) { + UniversalPrint(value, os); + } +}; +template +class UniversalTersePrinter { + public: + static void Print(const T (&value)[N], ::std::ostream* os) { + UniversalPrinter::Print(value, os); + } +}; +template <> +class UniversalTersePrinter { + public: + static void Print(const char* str, ::std::ostream* os) { + if (str == NULL) { + *os << "NULL"; + } else { + UniversalPrint(string(str), os); + } + } +}; +template <> +class UniversalTersePrinter { + public: + static void Print(char* str, ::std::ostream* os) { + UniversalTersePrinter::Print(str, os); + } +}; + +#if GTEST_HAS_STD_WSTRING +template <> +class UniversalTersePrinter { + public: + static void Print(const wchar_t* str, ::std::ostream* os) { + if (str == NULL) { + *os << "NULL"; + } else { + UniversalPrint(::std::wstring(str), os); + } + } +}; +#endif + +template <> +class UniversalTersePrinter { + public: + static void Print(wchar_t* str, ::std::ostream* os) { + UniversalTersePrinter::Print(str, os); + } +}; + +template +void UniversalTersePrint(const T& value, ::std::ostream* os) { + UniversalTersePrinter::Print(value, os); +} + +// Prints a value using the type inferred by the compiler. The +// difference between this and UniversalTersePrint() is that for a +// (const) char pointer, this prints both the pointer and the +// NUL-terminated string. +template +void UniversalPrint(const T& value, ::std::ostream* os) { + // A workarond for the bug in VC++ 7.1 that prevents us from instantiating + // UniversalPrinter with T directly. + typedef T T1; + UniversalPrinter::Print(value, os); +} + +#if GTEST_HAS_TR1_TUPLE +typedef ::std::vector Strings; + +// This helper template allows PrintTo() for tuples and +// UniversalTersePrintTupleFieldsToStrings() to be defined by +// induction on the number of tuple fields. The idea is that +// TuplePrefixPrinter::PrintPrefixTo(t, os) prints the first N +// fields in tuple t, and can be defined in terms of +// TuplePrefixPrinter. + +// The inductive case. +template +struct TuplePrefixPrinter { + // Prints the first N fields of a tuple. + template + static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { + TuplePrefixPrinter::PrintPrefixTo(t, os); + *os << ", "; + UniversalPrinter::type> + ::Print(::std::tr1::get(t), os); + } + + // Tersely prints the first N fields of a tuple to a string vector, + // one element for each field. + template + static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { + TuplePrefixPrinter::TersePrintPrefixToStrings(t, strings); + ::std::stringstream ss; + UniversalTersePrint(::std::tr1::get(t), &ss); + strings->push_back(ss.str()); + } +}; + +// Base cases. +template <> +struct TuplePrefixPrinter<0> { + template + static void PrintPrefixTo(const Tuple&, ::std::ostream*) {} + + template + static void TersePrintPrefixToStrings(const Tuple&, Strings*) {} +}; +// We have to specialize the entire TuplePrefixPrinter<> class +// template here, even though the definition of +// TersePrintPrefixToStrings() is the same as the generic version, as +// Embarcadero (formerly CodeGear, formerly Borland) C++ doesn't +// support specializing a method template of a class template. +template <> +struct TuplePrefixPrinter<1> { + template + static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { + UniversalPrinter::type>:: + Print(::std::tr1::get<0>(t), os); + } + + template + static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { + ::std::stringstream ss; + UniversalTersePrint(::std::tr1::get<0>(t), &ss); + strings->push_back(ss.str()); + } +}; + +// Helper function for printing a tuple. T must be instantiated with +// a tuple type. +template +void PrintTupleTo(const T& t, ::std::ostream* os) { + *os << "("; + TuplePrefixPrinter< ::std::tr1::tuple_size::value>:: + PrintPrefixTo(t, os); + *os << ")"; +} + +// Prints the fields of a tuple tersely to a string vector, one +// element for each field. See the comment before +// UniversalTersePrint() for how we define "tersely". +template +Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) { + Strings result; + TuplePrefixPrinter< ::std::tr1::tuple_size::value>:: + TersePrintPrefixToStrings(value, &result); + return result; +} +#endif // GTEST_HAS_TR1_TUPLE + +} // namespace internal + +template +::std::string PrintToString(const T& value) { + ::std::stringstream ss; + internal::UniversalTersePrinter::Print(value, &ss); + return ss.str(); +} + +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ diff --git a/lib/gtest/include/gtest/gtest-spi.h b/lib/gtest/include/gtest/gtest-spi.h new file mode 100644 index 00000000..f63fa9a1 --- /dev/null +++ b/lib/gtest/include/gtest/gtest-spi.h @@ -0,0 +1,232 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// Utilities for testing Google Test itself and code that uses Google Test +// (e.g. frameworks built on top of Google Test). + +#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ +#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ + +#include "gtest/gtest.h" + +namespace testing { + +// This helper class can be used to mock out Google Test failure reporting +// so that we can test Google Test or code that builds on Google Test. +// +// An object of this class appends a TestPartResult object to the +// TestPartResultArray object given in the constructor whenever a Google Test +// failure is reported. It can either intercept only failures that are +// generated in the same thread that created this object or it can intercept +// all generated failures. The scope of this mock object can be controlled with +// the second argument to the two arguments constructor. +class GTEST_API_ ScopedFakeTestPartResultReporter + : public TestPartResultReporterInterface { + public: + // The two possible mocking modes of this object. + enum InterceptMode { + INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures. + INTERCEPT_ALL_THREADS // Intercepts all failures. + }; + + // The c'tor sets this object as the test part result reporter used + // by Google Test. The 'result' parameter specifies where to report the + // results. This reporter will only catch failures generated in the current + // thread. DEPRECATED + explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result); + + // Same as above, but you can choose the interception scope of this object. + ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, + TestPartResultArray* result); + + // The d'tor restores the previous test part result reporter. + virtual ~ScopedFakeTestPartResultReporter(); + + // Appends the TestPartResult object to the TestPartResultArray + // received in the constructor. + // + // This method is from the TestPartResultReporterInterface + // interface. + virtual void ReportTestPartResult(const TestPartResult& result); + private: + void Init(); + + const InterceptMode intercept_mode_; + TestPartResultReporterInterface* old_reporter_; + TestPartResultArray* const result_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter); +}; + +namespace internal { + +// A helper class for implementing EXPECT_FATAL_FAILURE() and +// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given +// TestPartResultArray contains exactly one failure that has the given +// type and contains the given substring. If that's not the case, a +// non-fatal failure will be generated. +class GTEST_API_ SingleFailureChecker { + public: + // The constructor remembers the arguments. + SingleFailureChecker(const TestPartResultArray* results, + TestPartResult::Type type, + const string& substr); + ~SingleFailureChecker(); + private: + const TestPartResultArray* const results_; + const TestPartResult::Type type_; + const string substr_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); +}; + +} // namespace internal + +} // namespace testing + +// A set of macros for testing Google Test assertions or code that's expected +// to generate Google Test fatal failures. It verifies that the given +// statement will cause exactly one fatal Google Test failure with 'substr' +// being part of the failure message. +// +// There are two different versions of this macro. EXPECT_FATAL_FAILURE only +// affects and considers failures generated in the current thread and +// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. +// +// The verification of the assertion is done correctly even when the statement +// throws an exception or aborts the current function. +// +// Known restrictions: +// - 'statement' cannot reference local non-static variables or +// non-static members of the current object. +// - 'statement' cannot return a value. +// - You cannot stream a failure message to this macro. +// +// Note that even though the implementations of the following two +// macros are much alike, we cannot refactor them to use a common +// helper macro, due to some peculiarity in how the preprocessor +// works. The AcceptsMacroThatExpandsToUnprotectedComma test in +// gtest_unittest.cc will fail to compile if we do that. +#define EXPECT_FATAL_FAILURE(statement, substr) \ + do { \ + class GTestExpectFatalFailureHelper {\ + public:\ + static void Execute() { statement; }\ + };\ + ::testing::TestPartResultArray gtest_failures;\ + ::testing::internal::SingleFailureChecker gtest_checker(\ + >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ + {\ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ + ::testing::ScopedFakeTestPartResultReporter:: \ + INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ + GTestExpectFatalFailureHelper::Execute();\ + }\ + } while (::testing::internal::AlwaysFalse()) + +#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ + do { \ + class GTestExpectFatalFailureHelper {\ + public:\ + static void Execute() { statement; }\ + };\ + ::testing::TestPartResultArray gtest_failures;\ + ::testing::internal::SingleFailureChecker gtest_checker(\ + >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ + {\ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ + ::testing::ScopedFakeTestPartResultReporter:: \ + INTERCEPT_ALL_THREADS, >est_failures);\ + GTestExpectFatalFailureHelper::Execute();\ + }\ + } while (::testing::internal::AlwaysFalse()) + +// A macro for testing Google Test assertions or code that's expected to +// generate Google Test non-fatal failures. It asserts that the given +// statement will cause exactly one non-fatal Google Test failure with 'substr' +// being part of the failure message. +// +// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only +// affects and considers failures generated in the current thread and +// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. +// +// 'statement' is allowed to reference local variables and members of +// the current object. +// +// The verification of the assertion is done correctly even when the statement +// throws an exception or aborts the current function. +// +// Known restrictions: +// - You cannot stream a failure message to this macro. +// +// Note that even though the implementations of the following two +// macros are much alike, we cannot refactor them to use a common +// helper macro, due to some peculiarity in how the preprocessor +// works. If we do that, the code won't compile when the user gives +// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that +// expands to code containing an unprotected comma. The +// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc +// catches that. +// +// For the same reason, we have to write +// if (::testing::internal::AlwaysTrue()) { statement; } +// instead of +// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) +// to avoid an MSVC warning on unreachable code. +#define EXPECT_NONFATAL_FAILURE(statement, substr) \ + do {\ + ::testing::TestPartResultArray gtest_failures;\ + ::testing::internal::SingleFailureChecker gtest_checker(\ + >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ + (substr));\ + {\ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ + ::testing::ScopedFakeTestPartResultReporter:: \ + INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ + if (::testing::internal::AlwaysTrue()) { statement; }\ + }\ + } while (::testing::internal::AlwaysFalse()) + +#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ + do {\ + ::testing::TestPartResultArray gtest_failures;\ + ::testing::internal::SingleFailureChecker gtest_checker(\ + >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ + (substr));\ + {\ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ + ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ + >est_failures);\ + if (::testing::internal::AlwaysTrue()) { statement; }\ + }\ + } while (::testing::internal::AlwaysFalse()) + +#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_ diff --git a/lib/gtest/include/gtest/gtest-test-part.h b/lib/gtest/include/gtest/gtest-test-part.h new file mode 100644 index 00000000..77eb8448 --- /dev/null +++ b/lib/gtest/include/gtest/gtest-test-part.h @@ -0,0 +1,179 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: mheule@google.com (Markus Heule) +// + +#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ +#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ + +#include +#include +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-string.h" + +namespace testing { + +// A copyable object representing the result of a test part (i.e. an +// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()). +// +// Don't inherit from TestPartResult as its destructor is not virtual. +class GTEST_API_ TestPartResult { + public: + // The possible outcomes of a test part (i.e. an assertion or an + // explicit SUCCEED(), FAIL(), or ADD_FAILURE()). + enum Type { + kSuccess, // Succeeded. + kNonFatalFailure, // Failed but the test can continue. + kFatalFailure // Failed and the test should be terminated. + }; + + // C'tor. TestPartResult does NOT have a default constructor. + // Always use this constructor (with parameters) to create a + // TestPartResult object. + TestPartResult(Type a_type, + const char* a_file_name, + int a_line_number, + const char* a_message) + : type_(a_type), + file_name_(a_file_name == NULL ? "" : a_file_name), + line_number_(a_line_number), + summary_(ExtractSummary(a_message)), + message_(a_message) { + } + + // Gets the outcome of the test part. + Type type() const { return type_; } + + // Gets the name of the source file where the test part took place, or + // NULL if it's unknown. + const char* file_name() const { + return file_name_.empty() ? NULL : file_name_.c_str(); + } + + // Gets the line in the source file where the test part took place, + // or -1 if it's unknown. + int line_number() const { return line_number_; } + + // Gets the summary of the failure message. + const char* summary() const { return summary_.c_str(); } + + // Gets the message associated with the test part. + const char* message() const { return message_.c_str(); } + + // Returns true iff the test part passed. + bool passed() const { return type_ == kSuccess; } + + // Returns true iff the test part failed. + bool failed() const { return type_ != kSuccess; } + + // Returns true iff the test part non-fatally failed. + bool nonfatally_failed() const { return type_ == kNonFatalFailure; } + + // Returns true iff the test part fatally failed. + bool fatally_failed() const { return type_ == kFatalFailure; } + + private: + Type type_; + + // Gets the summary of the failure message by omitting the stack + // trace in it. + static std::string ExtractSummary(const char* message); + + // The name of the source file where the test part took place, or + // "" if the source file is unknown. + std::string file_name_; + // The line in the source file where the test part took place, or -1 + // if the line number is unknown. + int line_number_; + std::string summary_; // The test failure summary. + std::string message_; // The test failure message. +}; + +// Prints a TestPartResult object. +std::ostream& operator<<(std::ostream& os, const TestPartResult& result); + +// An array of TestPartResult objects. +// +// Don't inherit from TestPartResultArray as its destructor is not +// virtual. +class GTEST_API_ TestPartResultArray { + public: + TestPartResultArray() {} + + // Appends the given TestPartResult to the array. + void Append(const TestPartResult& result); + + // Returns the TestPartResult at the given index (0-based). + const TestPartResult& GetTestPartResult(int index) const; + + // Returns the number of TestPartResult objects in the array. + int size() const; + + private: + std::vector array_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray); +}; + +// This interface knows how to report a test part result. +class TestPartResultReporterInterface { + public: + virtual ~TestPartResultReporterInterface() {} + + virtual void ReportTestPartResult(const TestPartResult& result) = 0; +}; + +namespace internal { + +// This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a +// statement generates new fatal failures. To do so it registers itself as the +// current test part result reporter. Besides checking if fatal failures were +// reported, it only delegates the reporting to the former result reporter. +// The original result reporter is restored in the destructor. +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +class GTEST_API_ HasNewFatalFailureHelper + : public TestPartResultReporterInterface { + public: + HasNewFatalFailureHelper(); + virtual ~HasNewFatalFailureHelper(); + virtual void ReportTestPartResult(const TestPartResult& result); + bool has_new_fatal_failure() const { return has_new_fatal_failure_; } + private: + bool has_new_fatal_failure_; + TestPartResultReporterInterface* original_reporter_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper); +}; + +} // namespace internal + +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ diff --git a/lib/gtest/include/gtest/gtest-typed-test.h b/lib/gtest/include/gtest/gtest-typed-test.h new file mode 100644 index 00000000..fe1e83b2 --- /dev/null +++ b/lib/gtest/include/gtest/gtest-typed-test.h @@ -0,0 +1,259 @@ +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ +#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ + +// This header implements typed tests and type-parameterized tests. + +// Typed (aka type-driven) tests repeat the same test for types in a +// list. You must know which types you want to test with when writing +// typed tests. Here's how you do it: + +#if 0 + +// First, define a fixture class template. It should be parameterized +// by a type. Remember to derive it from testing::Test. +template +class FooTest : public testing::Test { + public: + ... + typedef std::list List; + static T shared_; + T value_; +}; + +// Next, associate a list of types with the test case, which will be +// repeated for each type in the list. The typedef is necessary for +// the macro to parse correctly. +typedef testing::Types MyTypes; +TYPED_TEST_CASE(FooTest, MyTypes); + +// If the type list contains only one type, you can write that type +// directly without Types<...>: +// TYPED_TEST_CASE(FooTest, int); + +// Then, use TYPED_TEST() instead of TEST_F() to define as many typed +// tests for this test case as you want. +TYPED_TEST(FooTest, DoesBlah) { + // Inside a test, refer to TypeParam to get the type parameter. + // Since we are inside a derived class template, C++ requires use to + // visit the members of FooTest via 'this'. + TypeParam n = this->value_; + + // To visit static members of the fixture, add the TestFixture:: + // prefix. + n += TestFixture::shared_; + + // To refer to typedefs in the fixture, add the "typename + // TestFixture::" prefix. + typename TestFixture::List values; + values.push_back(n); + ... +} + +TYPED_TEST(FooTest, HasPropertyA) { ... } + +#endif // 0 + +// Type-parameterized tests are abstract test patterns parameterized +// by a type. Compared with typed tests, type-parameterized tests +// allow you to define the test pattern without knowing what the type +// parameters are. The defined pattern can be instantiated with +// different types any number of times, in any number of translation +// units. +// +// If you are designing an interface or concept, you can define a +// suite of type-parameterized tests to verify properties that any +// valid implementation of the interface/concept should have. Then, +// each implementation can easily instantiate the test suite to verify +// that it conforms to the requirements, without having to write +// similar tests repeatedly. Here's an example: + +#if 0 + +// First, define a fixture class template. It should be parameterized +// by a type. Remember to derive it from testing::Test. +template +class FooTest : public testing::Test { + ... +}; + +// Next, declare that you will define a type-parameterized test case +// (the _P suffix is for "parameterized" or "pattern", whichever you +// prefer): +TYPED_TEST_CASE_P(FooTest); + +// Then, use TYPED_TEST_P() to define as many type-parameterized tests +// for this type-parameterized test case as you want. +TYPED_TEST_P(FooTest, DoesBlah) { + // Inside a test, refer to TypeParam to get the type parameter. + TypeParam n = 0; + ... +} + +TYPED_TEST_P(FooTest, HasPropertyA) { ... } + +// Now the tricky part: you need to register all test patterns before +// you can instantiate them. The first argument of the macro is the +// test case name; the rest are the names of the tests in this test +// case. +REGISTER_TYPED_TEST_CASE_P(FooTest, + DoesBlah, HasPropertyA); + +// Finally, you are free to instantiate the pattern with the types you +// want. If you put the above code in a header file, you can #include +// it in multiple C++ source files and instantiate it multiple times. +// +// To distinguish different instances of the pattern, the first +// argument to the INSTANTIATE_* macro is a prefix that will be added +// to the actual test case name. Remember to pick unique prefixes for +// different instances. +typedef testing::Types MyTypes; +INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); + +// If the type list contains only one type, you can write that type +// directly without Types<...>: +// INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); + +#endif // 0 + +#include "gtest/internal/gtest-port.h" +#include "gtest/internal/gtest-type-util.h" + +// Implements typed tests. + +#if GTEST_HAS_TYPED_TEST + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Expands to the name of the typedef for the type parameters of the +// given test case. +# define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_ + +// The 'Types' template argument below must have spaces around it +// since some compilers may choke on '>>' when passing a template +// instance (e.g. Types) +# define TYPED_TEST_CASE(CaseName, Types) \ + typedef ::testing::internal::TypeList< Types >::type \ + GTEST_TYPE_PARAMS_(CaseName) + +# define TYPED_TEST(CaseName, TestName) \ + template \ + class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ + : public CaseName { \ + private: \ + typedef CaseName TestFixture; \ + typedef gtest_TypeParam_ TypeParam; \ + virtual void TestBody(); \ + }; \ + bool gtest_##CaseName##_##TestName##_registered_ GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::internal::TypeParameterizedTest< \ + CaseName, \ + ::testing::internal::TemplateSel< \ + GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \ + GTEST_TYPE_PARAMS_(CaseName)>::Register(\ + "", #CaseName, #TestName, 0); \ + template \ + void GTEST_TEST_CLASS_NAME_(CaseName, TestName)::TestBody() + +#endif // GTEST_HAS_TYPED_TEST + +// Implements type-parameterized tests. + +#if GTEST_HAS_TYPED_TEST_P + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Expands to the namespace name that the type-parameterized tests for +// the given type-parameterized test case are defined in. The exact +// name of the namespace is subject to change without notice. +# define GTEST_CASE_NAMESPACE_(TestCaseName) \ + gtest_case_##TestCaseName##_ + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Expands to the name of the variable used to remember the names of +// the defined tests in the given test case. +# define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \ + gtest_typed_test_case_p_state_##TestCaseName##_ + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY. +// +// Expands to the name of the variable used to remember the names of +// the registered tests in the given test case. +# define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \ + gtest_registered_test_names_##TestCaseName##_ + +// The variables defined in the type-parameterized test macros are +// static as typically these macros are used in a .h file that can be +// #included in multiple translation units linked together. +# define TYPED_TEST_CASE_P(CaseName) \ + static ::testing::internal::TypedTestCasePState \ + GTEST_TYPED_TEST_CASE_P_STATE_(CaseName) + +# define TYPED_TEST_P(CaseName, TestName) \ + namespace GTEST_CASE_NAMESPACE_(CaseName) { \ + template \ + class TestName : public CaseName { \ + private: \ + typedef CaseName TestFixture; \ + typedef gtest_TypeParam_ TypeParam; \ + virtual void TestBody(); \ + }; \ + static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ + GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\ + __FILE__, __LINE__, #CaseName, #TestName); \ + } \ + template \ + void GTEST_CASE_NAMESPACE_(CaseName)::TestName::TestBody() + +# define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \ + namespace GTEST_CASE_NAMESPACE_(CaseName) { \ + typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ + } \ + static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \ + GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\ + __FILE__, __LINE__, #__VA_ARGS__) + +// The 'Types' template argument below must have spaces around it +// since some compilers may choke on '>>' when passing a template +// instance (e.g. Types) +# define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \ + bool gtest_##Prefix##_##CaseName GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::internal::TypeParameterizedTestCase::type>::Register(\ + #Prefix, #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName)) + +#endif // GTEST_HAS_TYPED_TEST_P + +#endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ diff --git a/lib/gtest/include/gtest/gtest.h b/lib/gtest/include/gtest/gtest.h new file mode 100644 index 00000000..6fa0a392 --- /dev/null +++ b/lib/gtest/include/gtest/gtest.h @@ -0,0 +1,2291 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file defines the public API for Google Test. It should be +// included by any test program that uses Google Test. +// +// IMPORTANT NOTE: Due to limitation of the C++ language, we have to +// leave some internal implementation details in this header file. +// They are clearly marked by comments like this: +// +// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +// +// Such code is NOT meant to be used by a user directly, and is subject +// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user +// program! +// +// Acknowledgment: Google Test borrowed the idea of automatic test +// registration from Barthelemy Dagenais' (barthelemy@prologique.com) +// easyUnit framework. + +#ifndef GTEST_INCLUDE_GTEST_GTEST_H_ +#define GTEST_INCLUDE_GTEST_GTEST_H_ + +#include +#include +#include + +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-string.h" +#include "gtest/gtest-death-test.h" +#include "gtest/gtest-message.h" +#include "gtest/gtest-param-test.h" +#include "gtest/gtest-printers.h" +#include "gtest/gtest_prod.h" +#include "gtest/gtest-test-part.h" +#include "gtest/gtest-typed-test.h" + +// Depending on the platform, different string classes are available. +// On Linux, in addition to ::std::string, Google also makes use of +// class ::string, which has the same interface as ::std::string, but +// has a different implementation. +// +// The user can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that +// ::string is available AND is a distinct type to ::std::string, or +// define it to 0 to indicate otherwise. +// +// If the user's ::std::string and ::string are the same class due to +// aliasing, he should define GTEST_HAS_GLOBAL_STRING to 0. +// +// If the user doesn't define GTEST_HAS_GLOBAL_STRING, it is defined +// heuristically. + +namespace testing { + +// Declares the flags. + +// This flag temporary enables the disabled tests. +GTEST_DECLARE_bool_(also_run_disabled_tests); + +// This flag brings the debugger on an assertion failure. +GTEST_DECLARE_bool_(break_on_failure); + +// This flag controls whether Google Test catches all test-thrown exceptions +// and logs them as failures. +GTEST_DECLARE_bool_(catch_exceptions); + +// This flag enables using colors in terminal output. Available values are +// "yes" to enable colors, "no" (disable colors), or "auto" (the default) +// to let Google Test decide. +GTEST_DECLARE_string_(color); + +// This flag sets up the filter to select by name using a glob pattern +// the tests to run. If the filter is not given all tests are executed. +GTEST_DECLARE_string_(filter); + +// This flag causes the Google Test to list tests. None of the tests listed +// are actually run if the flag is provided. +GTEST_DECLARE_bool_(list_tests); + +// This flag controls whether Google Test emits a detailed XML report to a file +// in addition to its normal textual output. +GTEST_DECLARE_string_(output); + +// This flags control whether Google Test prints the elapsed time for each +// test. +GTEST_DECLARE_bool_(print_time); + +// This flag specifies the random number seed. +GTEST_DECLARE_int32_(random_seed); + +// This flag sets how many times the tests are repeated. The default value +// is 1. If the value is -1 the tests are repeating forever. +GTEST_DECLARE_int32_(repeat); + +// This flag controls whether Google Test includes Google Test internal +// stack frames in failure stack traces. +GTEST_DECLARE_bool_(show_internal_stack_frames); + +// When this flag is specified, tests' order is randomized on every iteration. +GTEST_DECLARE_bool_(shuffle); + +// This flag specifies the maximum number of stack frames to be +// printed in a failure message. +GTEST_DECLARE_int32_(stack_trace_depth); + +// When this flag is specified, a failed assertion will throw an +// exception if exceptions are enabled, or exit the program with a +// non-zero code otherwise. +GTEST_DECLARE_bool_(throw_on_failure); + +// When this flag is set with a "host:port" string, on supported +// platforms test results are streamed to the specified port on +// the specified host machine. +GTEST_DECLARE_string_(stream_result_to); + +// The upper limit for valid stack trace depths. +const int kMaxStackTraceDepth = 100; + +namespace internal { + +class AssertHelper; +class DefaultGlobalTestPartResultReporter; +class ExecDeathTest; +class NoExecDeathTest; +class FinalSuccessChecker; +class GTestFlagSaver; +class StreamingListenerTest; +class TestResultAccessor; +class TestEventListenersAccessor; +class TestEventRepeater; +class UnitTestRecordPropertyTestHelper; +class WindowsDeathTest; +class UnitTestImpl* GetUnitTestImpl(); +void ReportFailureInUnknownLocation(TestPartResult::Type result_type, + const std::string& message); + +} // namespace internal + +// The friend relationship of some of these classes is cyclic. +// If we don't forward declare them the compiler might confuse the classes +// in friendship clauses with same named classes on the scope. +class Test; +class TestCase; +class TestInfo; +class UnitTest; + +// A class for indicating whether an assertion was successful. When +// the assertion wasn't successful, the AssertionResult object +// remembers a non-empty message that describes how it failed. +// +// To create an instance of this class, use one of the factory functions +// (AssertionSuccess() and AssertionFailure()). +// +// This class is useful for two purposes: +// 1. Defining predicate functions to be used with Boolean test assertions +// EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts +// 2. Defining predicate-format functions to be +// used with predicate assertions (ASSERT_PRED_FORMAT*, etc). +// +// For example, if you define IsEven predicate: +// +// testing::AssertionResult IsEven(int n) { +// if ((n % 2) == 0) +// return testing::AssertionSuccess(); +// else +// return testing::AssertionFailure() << n << " is odd"; +// } +// +// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5))) +// will print the message +// +// Value of: IsEven(Fib(5)) +// Actual: false (5 is odd) +// Expected: true +// +// instead of a more opaque +// +// Value of: IsEven(Fib(5)) +// Actual: false +// Expected: true +// +// in case IsEven is a simple Boolean predicate. +// +// If you expect your predicate to be reused and want to support informative +// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up +// about half as often as positive ones in our tests), supply messages for +// both success and failure cases: +// +// testing::AssertionResult IsEven(int n) { +// if ((n % 2) == 0) +// return testing::AssertionSuccess() << n << " is even"; +// else +// return testing::AssertionFailure() << n << " is odd"; +// } +// +// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print +// +// Value of: IsEven(Fib(6)) +// Actual: true (8 is even) +// Expected: false +// +// NB: Predicates that support negative Boolean assertions have reduced +// performance in positive ones so be careful not to use them in tests +// that have lots (tens of thousands) of positive Boolean assertions. +// +// To use this class with EXPECT_PRED_FORMAT assertions such as: +// +// // Verifies that Foo() returns an even number. +// EXPECT_PRED_FORMAT1(IsEven, Foo()); +// +// you need to define: +// +// testing::AssertionResult IsEven(const char* expr, int n) { +// if ((n % 2) == 0) +// return testing::AssertionSuccess(); +// else +// return testing::AssertionFailure() +// << "Expected: " << expr << " is even\n Actual: it's " << n; +// } +// +// If Foo() returns 5, you will see the following message: +// +// Expected: Foo() is even +// Actual: it's 5 +// +class GTEST_API_ AssertionResult { + public: + // Copy constructor. + // Used in EXPECT_TRUE/FALSE(assertion_result). + AssertionResult(const AssertionResult& other); + // Used in the EXPECT_TRUE/FALSE(bool_expression). + explicit AssertionResult(bool success) : success_(success) {} + + // Returns true iff the assertion succeeded. + operator bool() const { return success_; } // NOLINT + + // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. + AssertionResult operator!() const; + + // Returns the text streamed into this AssertionResult. Test assertions + // use it when they fail (i.e., the predicate's outcome doesn't match the + // assertion's expectation). When nothing has been streamed into the + // object, returns an empty string. + const char* message() const { + return message_.get() != NULL ? message_->c_str() : ""; + } + // TODO(vladl@google.com): Remove this after making sure no clients use it. + // Deprecated; please use message() instead. + const char* failure_message() const { return message(); } + + // Streams a custom failure message into this object. + template AssertionResult& operator<<(const T& value) { + AppendMessage(Message() << value); + return *this; + } + + // Allows streaming basic output manipulators such as endl or flush into + // this object. + AssertionResult& operator<<( + ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) { + AppendMessage(Message() << basic_manipulator); + return *this; + } + + private: + // Appends the contents of message to message_. + void AppendMessage(const Message& a_message) { + if (message_.get() == NULL) + message_.reset(new ::std::string); + message_->append(a_message.GetString().c_str()); + } + + // Stores result of the assertion predicate. + bool success_; + // Stores the message describing the condition in case the expectation + // construct is not satisfied with the predicate's outcome. + // Referenced via a pointer to avoid taking too much stack frame space + // with test assertions. + internal::scoped_ptr< ::std::string> message_; + + GTEST_DISALLOW_ASSIGN_(AssertionResult); +}; + +// Makes a successful assertion result. +GTEST_API_ AssertionResult AssertionSuccess(); + +// Makes a failed assertion result. +GTEST_API_ AssertionResult AssertionFailure(); + +// Makes a failed assertion result with the given failure message. +// Deprecated; use AssertionFailure() << msg. +GTEST_API_ AssertionResult AssertionFailure(const Message& msg); + +// The abstract class that all tests inherit from. +// +// In Google Test, a unit test program contains one or many TestCases, and +// each TestCase contains one or many Tests. +// +// When you define a test using the TEST macro, you don't need to +// explicitly derive from Test - the TEST macro automatically does +// this for you. +// +// The only time you derive from Test is when defining a test fixture +// to be used a TEST_F. For example: +// +// class FooTest : public testing::Test { +// protected: +// virtual void SetUp() { ... } +// virtual void TearDown() { ... } +// ... +// }; +// +// TEST_F(FooTest, Bar) { ... } +// TEST_F(FooTest, Baz) { ... } +// +// Test is not copyable. +class GTEST_API_ Test { + public: + friend class TestInfo; + + // Defines types for pointers to functions that set up and tear down + // a test case. + typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc; + typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc; + + // The d'tor is virtual as we intend to inherit from Test. + virtual ~Test(); + + // Sets up the stuff shared by all tests in this test case. + // + // Google Test will call Foo::SetUpTestCase() before running the first + // test in test case Foo. Hence a sub-class can define its own + // SetUpTestCase() method to shadow the one defined in the super + // class. + static void SetUpTestCase() {} + + // Tears down the stuff shared by all tests in this test case. + // + // Google Test will call Foo::TearDownTestCase() after running the last + // test in test case Foo. Hence a sub-class can define its own + // TearDownTestCase() method to shadow the one defined in the super + // class. + static void TearDownTestCase() {} + + // Returns true iff the current test has a fatal failure. + static bool HasFatalFailure(); + + // Returns true iff the current test has a non-fatal failure. + static bool HasNonfatalFailure(); + + // Returns true iff the current test has a (either fatal or + // non-fatal) failure. + static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } + + // Logs a property for the current test, test case, or for the entire + // invocation of the test program when used outside of the context of a + // test case. Only the last value for a given key is remembered. These + // are public static so they can be called from utility functions that are + // not members of the test fixture. Calls to RecordProperty made during + // lifespan of the test (from the moment its constructor starts to the + // moment its destructor finishes) will be output in XML as attributes of + // the element. Properties recorded from fixture's + // SetUpTestCase or TearDownTestCase are logged as attributes of the + // corresponding element. Calls to RecordProperty made in the + // global context (before or after invocation of RUN_ALL_TESTS and from + // SetUp/TearDown method of Environment objects registered with Google + // Test) will be output as attributes of the element. + static void RecordProperty(const std::string& key, const std::string& value); + static void RecordProperty(const std::string& key, int value); + + protected: + // Creates a Test object. + Test(); + + // Sets up the test fixture. + virtual void SetUp(); + + // Tears down the test fixture. + virtual void TearDown(); + + private: + // Returns true iff the current test has the same fixture class as + // the first test in the current test case. + static bool HasSameFixtureClass(); + + // Runs the test after the test fixture has been set up. + // + // A sub-class must implement this to define the test logic. + // + // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM. + // Instead, use the TEST or TEST_F macro. + virtual void TestBody() = 0; + + // Sets up, executes, and tears down the test. + void Run(); + + // Deletes self. We deliberately pick an unusual name for this + // internal method to avoid clashing with names used in user TESTs. + void DeleteSelf_() { delete this; } + + // Uses a GTestFlagSaver to save and restore all Google Test flags. + const internal::GTestFlagSaver* const gtest_flag_saver_; + + // Often a user mis-spells SetUp() as Setup() and spends a long time + // wondering why it is never called by Google Test. The declaration of + // the following method is solely for catching such an error at + // compile time: + // + // - The return type is deliberately chosen to be not void, so it + // will be a conflict if a user declares void Setup() in his test + // fixture. + // + // - This method is private, so it will be another compiler error + // if a user calls it from his test fixture. + // + // DO NOT OVERRIDE THIS FUNCTION. + // + // If you see an error about overriding the following function or + // about it being private, you have mis-spelled SetUp() as Setup(). + struct Setup_should_be_spelled_SetUp {}; + virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } + + // We disallow copying Tests. + GTEST_DISALLOW_COPY_AND_ASSIGN_(Test); +}; + +typedef internal::TimeInMillis TimeInMillis; + +// A copyable object representing a user specified test property which can be +// output as a key/value string pair. +// +// Don't inherit from TestProperty as its destructor is not virtual. +class TestProperty { + public: + // C'tor. TestProperty does NOT have a default constructor. + // Always use this constructor (with parameters) to create a + // TestProperty object. + TestProperty(const std::string& a_key, const std::string& a_value) : + key_(a_key), value_(a_value) { + } + + // Gets the user supplied key. + const char* key() const { + return key_.c_str(); + } + + // Gets the user supplied value. + const char* value() const { + return value_.c_str(); + } + + // Sets a new value, overriding the one supplied in the constructor. + void SetValue(const std::string& new_value) { + value_ = new_value; + } + + private: + // The key supplied by the user. + std::string key_; + // The value supplied by the user. + std::string value_; +}; + +// The result of a single Test. This includes a list of +// TestPartResults, a list of TestProperties, a count of how many +// death tests there are in the Test, and how much time it took to run +// the Test. +// +// TestResult is not copyable. +class GTEST_API_ TestResult { + public: + // Creates an empty TestResult. + TestResult(); + + // D'tor. Do not inherit from TestResult. + ~TestResult(); + + // Gets the number of all test parts. This is the sum of the number + // of successful test parts and the number of failed test parts. + int total_part_count() const; + + // Returns the number of the test properties. + int test_property_count() const; + + // Returns true iff the test passed (i.e. no test part failed). + bool Passed() const { return !Failed(); } + + // Returns true iff the test failed. + bool Failed() const; + + // Returns true iff the test fatally failed. + bool HasFatalFailure() const; + + // Returns true iff the test has a non-fatal failure. + bool HasNonfatalFailure() const; + + // Returns the elapsed time, in milliseconds. + TimeInMillis elapsed_time() const { return elapsed_time_; } + + // Returns the i-th test part result among all the results. i can range + // from 0 to test_property_count() - 1. If i is not in that range, aborts + // the program. + const TestPartResult& GetTestPartResult(int i) const; + + // Returns the i-th test property. i can range from 0 to + // test_property_count() - 1. If i is not in that range, aborts the + // program. + const TestProperty& GetTestProperty(int i) const; + + private: + friend class TestInfo; + friend class TestCase; + friend class UnitTest; + friend class internal::DefaultGlobalTestPartResultReporter; + friend class internal::ExecDeathTest; + friend class internal::TestResultAccessor; + friend class internal::UnitTestImpl; + friend class internal::WindowsDeathTest; + + // Gets the vector of TestPartResults. + const std::vector& test_part_results() const { + return test_part_results_; + } + + // Gets the vector of TestProperties. + const std::vector& test_properties() const { + return test_properties_; + } + + // Sets the elapsed time. + void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; } + + // Adds a test property to the list. The property is validated and may add + // a non-fatal failure if invalid (e.g., if it conflicts with reserved + // key names). If a property is already recorded for the same key, the + // value will be updated, rather than storing multiple values for the same + // key. xml_element specifies the element for which the property is being + // recorded and is used for validation. + void RecordProperty(const std::string& xml_element, + const TestProperty& test_property); + + // Adds a failure if the key is a reserved attribute of Google Test + // testcase tags. Returns true if the property is valid. + // TODO(russr): Validate attribute names are legal and human readable. + static bool ValidateTestProperty(const std::string& xml_element, + const TestProperty& test_property); + + // Adds a test part result to the list. + void AddTestPartResult(const TestPartResult& test_part_result); + + // Returns the death test count. + int death_test_count() const { return death_test_count_; } + + // Increments the death test count, returning the new count. + int increment_death_test_count() { return ++death_test_count_; } + + // Clears the test part results. + void ClearTestPartResults(); + + // Clears the object. + void Clear(); + + // Protects mutable state of the property vector and of owned + // properties, whose values may be updated. + internal::Mutex test_properites_mutex_; + + // The vector of TestPartResults + std::vector test_part_results_; + // The vector of TestProperties + std::vector test_properties_; + // Running count of death tests. + int death_test_count_; + // The elapsed time, in milliseconds. + TimeInMillis elapsed_time_; + + // We disallow copying TestResult. + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult); +}; // class TestResult + +// A TestInfo object stores the following information about a test: +// +// Test case name +// Test name +// Whether the test should be run +// A function pointer that creates the test object when invoked +// Test result +// +// The constructor of TestInfo registers itself with the UnitTest +// singleton such that the RUN_ALL_TESTS() macro knows which tests to +// run. +class GTEST_API_ TestInfo { + public: + // Destructs a TestInfo object. This function is not virtual, so + // don't inherit from TestInfo. + ~TestInfo(); + + // Returns the test case name. + const char* test_case_name() const { return test_case_name_.c_str(); } + + // Returns the test name. + const char* name() const { return name_.c_str(); } + + // Returns the name of the parameter type, or NULL if this is not a typed + // or a type-parameterized test. + const char* type_param() const { + if (type_param_.get() != NULL) + return type_param_->c_str(); + return NULL; + } + + // Returns the text representation of the value parameter, or NULL if this + // is not a value-parameterized test. + const char* value_param() const { + if (value_param_.get() != NULL) + return value_param_->c_str(); + return NULL; + } + + // Returns true if this test should run, that is if the test is not + // disabled (or it is disabled but the also_run_disabled_tests flag has + // been specified) and its full name matches the user-specified filter. + // + // Google Test allows the user to filter the tests by their full names. + // The full name of a test Bar in test case Foo is defined as + // "Foo.Bar". Only the tests that match the filter will run. + // + // A filter is a colon-separated list of glob (not regex) patterns, + // optionally followed by a '-' and a colon-separated list of + // negative patterns (tests to exclude). A test is run if it + // matches one of the positive patterns and does not match any of + // the negative patterns. + // + // For example, *A*:Foo.* is a filter that matches any string that + // contains the character 'A' or starts with "Foo.". + bool should_run() const { return should_run_; } + + // Returns true iff this test will appear in the XML report. + bool is_reportable() const { + // For now, the XML report includes all tests matching the filter. + // In the future, we may trim tests that are excluded because of + // sharding. + return matches_filter_; + } + + // Returns the result of the test. + const TestResult* result() const { return &result_; } + + private: +#if GTEST_HAS_DEATH_TEST + friend class internal::DefaultDeathTestFactory; +#endif // GTEST_HAS_DEATH_TEST + friend class Test; + friend class TestCase; + friend class internal::UnitTestImpl; + friend class internal::StreamingListenerTest; + friend TestInfo* internal::MakeAndRegisterTestInfo( + const char* test_case_name, + const char* name, + const char* type_param, + const char* value_param, + internal::TypeId fixture_class_id, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc, + internal::TestFactoryBase* factory); + + // Constructs a TestInfo object. The newly constructed instance assumes + // ownership of the factory object. + TestInfo(const std::string& test_case_name, + const std::string& name, + const char* a_type_param, // NULL if not a type-parameterized test + const char* a_value_param, // NULL if not a value-parameterized test + internal::TypeId fixture_class_id, + internal::TestFactoryBase* factory); + + // Increments the number of death tests encountered in this test so + // far. + int increment_death_test_count() { + return result_.increment_death_test_count(); + } + + // Creates the test object, runs it, records its result, and then + // deletes it. + void Run(); + + static void ClearTestResult(TestInfo* test_info) { + test_info->result_.Clear(); + } + + // These fields are immutable properties of the test. + const std::string test_case_name_; // Test case name + const std::string name_; // Test name + // Name of the parameter type, or NULL if this is not a typed or a + // type-parameterized test. + const internal::scoped_ptr type_param_; + // Text representation of the value parameter, or NULL if this is not a + // value-parameterized test. + const internal::scoped_ptr value_param_; + const internal::TypeId fixture_class_id_; // ID of the test fixture class + bool should_run_; // True iff this test should run + bool is_disabled_; // True iff this test is disabled + bool matches_filter_; // True if this test matches the + // user-specified filter. + internal::TestFactoryBase* const factory_; // The factory that creates + // the test object + + // This field is mutable and needs to be reset before running the + // test for the second time. + TestResult result_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); +}; + +// A test case, which consists of a vector of TestInfos. +// +// TestCase is not copyable. +class GTEST_API_ TestCase { + public: + // Creates a TestCase with the given name. + // + // TestCase does NOT have a default constructor. Always use this + // constructor to create a TestCase object. + // + // Arguments: + // + // name: name of the test case + // a_type_param: the name of the test's type parameter, or NULL if + // this is not a type-parameterized test. + // set_up_tc: pointer to the function that sets up the test case + // tear_down_tc: pointer to the function that tears down the test case + TestCase(const char* name, const char* a_type_param, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc); + + // Destructor of TestCase. + virtual ~TestCase(); + + // Gets the name of the TestCase. + const char* name() const { return name_.c_str(); } + + // Returns the name of the parameter type, or NULL if this is not a + // type-parameterized test case. + const char* type_param() const { + if (type_param_.get() != NULL) + return type_param_->c_str(); + return NULL; + } + + // Returns true if any test in this test case should run. + bool should_run() const { return should_run_; } + + // Gets the number of successful tests in this test case. + int successful_test_count() const; + + // Gets the number of failed tests in this test case. + int failed_test_count() const; + + // Gets the number of disabled tests that will be reported in the XML report. + int reportable_disabled_test_count() const; + + // Gets the number of disabled tests in this test case. + int disabled_test_count() const; + + // Gets the number of tests to be printed in the XML report. + int reportable_test_count() const; + + // Get the number of tests in this test case that should run. + int test_to_run_count() const; + + // Gets the number of all tests in this test case. + int total_test_count() const; + + // Returns true iff the test case passed. + bool Passed() const { return !Failed(); } + + // Returns true iff the test case failed. + bool Failed() const { return failed_test_count() > 0; } + + // Returns the elapsed time, in milliseconds. + TimeInMillis elapsed_time() const { return elapsed_time_; } + + // Returns the i-th test among all the tests. i can range from 0 to + // total_test_count() - 1. If i is not in that range, returns NULL. + const TestInfo* GetTestInfo(int i) const; + + // Returns the TestResult that holds test properties recorded during + // execution of SetUpTestCase and TearDownTestCase. + const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; } + + private: + friend class Test; + friend class internal::UnitTestImpl; + + // Gets the (mutable) vector of TestInfos in this TestCase. + std::vector& test_info_list() { return test_info_list_; } + + // Gets the (immutable) vector of TestInfos in this TestCase. + const std::vector& test_info_list() const { + return test_info_list_; + } + + // Returns the i-th test among all the tests. i can range from 0 to + // total_test_count() - 1. If i is not in that range, returns NULL. + TestInfo* GetMutableTestInfo(int i); + + // Sets the should_run member. + void set_should_run(bool should) { should_run_ = should; } + + // Adds a TestInfo to this test case. Will delete the TestInfo upon + // destruction of the TestCase object. + void AddTestInfo(TestInfo * test_info); + + // Clears the results of all tests in this test case. + void ClearResult(); + + // Clears the results of all tests in the given test case. + static void ClearTestCaseResult(TestCase* test_case) { + test_case->ClearResult(); + } + + // Runs every test in this TestCase. + void Run(); + + // Runs SetUpTestCase() for this TestCase. This wrapper is needed + // for catching exceptions thrown from SetUpTestCase(). + void RunSetUpTestCase() { (*set_up_tc_)(); } + + // Runs TearDownTestCase() for this TestCase. This wrapper is + // needed for catching exceptions thrown from TearDownTestCase(). + void RunTearDownTestCase() { (*tear_down_tc_)(); } + + // Returns true iff test passed. + static bool TestPassed(const TestInfo* test_info) { + return test_info->should_run() && test_info->result()->Passed(); + } + + // Returns true iff test failed. + static bool TestFailed(const TestInfo* test_info) { + return test_info->should_run() && test_info->result()->Failed(); + } + + // Returns true iff the test is disabled and will be reported in the XML + // report. + static bool TestReportableDisabled(const TestInfo* test_info) { + return test_info->is_reportable() && test_info->is_disabled_; + } + + // Returns true iff test is disabled. + static bool TestDisabled(const TestInfo* test_info) { + return test_info->is_disabled_; + } + + // Returns true iff this test will appear in the XML report. + static bool TestReportable(const TestInfo* test_info) { + return test_info->is_reportable(); + } + + // Returns true if the given test should run. + static bool ShouldRunTest(const TestInfo* test_info) { + return test_info->should_run(); + } + + // Shuffles the tests in this test case. + void ShuffleTests(internal::Random* random); + + // Restores the test order to before the first shuffle. + void UnshuffleTests(); + + // Name of the test case. + std::string name_; + // Name of the parameter type, or NULL if this is not a typed or a + // type-parameterized test. + const internal::scoped_ptr type_param_; + // The vector of TestInfos in their original order. It owns the + // elements in the vector. + std::vector test_info_list_; + // Provides a level of indirection for the test list to allow easy + // shuffling and restoring the test order. The i-th element in this + // vector is the index of the i-th test in the shuffled test list. + std::vector test_indices_; + // Pointer to the function that sets up the test case. + Test::SetUpTestCaseFunc set_up_tc_; + // Pointer to the function that tears down the test case. + Test::TearDownTestCaseFunc tear_down_tc_; + // True iff any test in this test case should run. + bool should_run_; + // Elapsed time, in milliseconds. + TimeInMillis elapsed_time_; + // Holds test properties recorded during execution of SetUpTestCase and + // TearDownTestCase. + TestResult ad_hoc_test_result_; + + // We disallow copying TestCases. + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); +}; + +// An Environment object is capable of setting up and tearing down an +// environment. The user should subclass this to define his own +// environment(s). +// +// An Environment object does the set-up and tear-down in virtual +// methods SetUp() and TearDown() instead of the constructor and the +// destructor, as: +// +// 1. You cannot safely throw from a destructor. This is a problem +// as in some cases Google Test is used where exceptions are enabled, and +// we may want to implement ASSERT_* using exceptions where they are +// available. +// 2. You cannot use ASSERT_* directly in a constructor or +// destructor. +class Environment { + public: + // The d'tor is virtual as we need to subclass Environment. + virtual ~Environment() {} + + // Override this to define how to set up the environment. + virtual void SetUp() {} + + // Override this to define how to tear down the environment. + virtual void TearDown() {} + private: + // If you see an error about overriding the following function or + // about it being private, you have mis-spelled SetUp() as Setup(). + struct Setup_should_be_spelled_SetUp {}; + virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } +}; + +// The interface for tracing execution of tests. The methods are organized in +// the order the corresponding events are fired. +class TestEventListener { + public: + virtual ~TestEventListener() {} + + // Fired before any test activity starts. + virtual void OnTestProgramStart(const UnitTest& unit_test) = 0; + + // Fired before each iteration of tests starts. There may be more than + // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration + // index, starting from 0. + virtual void OnTestIterationStart(const UnitTest& unit_test, + int iteration) = 0; + + // Fired before environment set-up for each iteration of tests starts. + virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0; + + // Fired after environment set-up for each iteration of tests ends. + virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0; + + // Fired before the test case starts. + virtual void OnTestCaseStart(const TestCase& test_case) = 0; + + // Fired before the test starts. + virtual void OnTestStart(const TestInfo& test_info) = 0; + + // Fired after a failed assertion or a SUCCEED() invocation. + virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0; + + // Fired after the test ends. + virtual void OnTestEnd(const TestInfo& test_info) = 0; + + // Fired after the test case ends. + virtual void OnTestCaseEnd(const TestCase& test_case) = 0; + + // Fired before environment tear-down for each iteration of tests starts. + virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0; + + // Fired after environment tear-down for each iteration of tests ends. + virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0; + + // Fired after each iteration of tests finishes. + virtual void OnTestIterationEnd(const UnitTest& unit_test, + int iteration) = 0; + + // Fired after all test activities have ended. + virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; +}; + +// The convenience class for users who need to override just one or two +// methods and are not concerned that a possible change to a signature of +// the methods they override will not be caught during the build. For +// comments about each method please see the definition of TestEventListener +// above. +class EmptyTestEventListener : public TestEventListener { + public: + virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, + int /*iteration*/) {} + virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {} + virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestCaseStart(const TestCase& /*test_case*/) {} + virtual void OnTestStart(const TestInfo& /*test_info*/) {} + virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {} + virtual void OnTestEnd(const TestInfo& /*test_info*/) {} + virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {} + virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {} + virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, + int /*iteration*/) {} + virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} +}; + +// TestEventListeners lets users add listeners to track events in Google Test. +class GTEST_API_ TestEventListeners { + public: + TestEventListeners(); + ~TestEventListeners(); + + // Appends an event listener to the end of the list. Google Test assumes + // the ownership of the listener (i.e. it will delete the listener when + // the test program finishes). + void Append(TestEventListener* listener); + + // Removes the given event listener from the list and returns it. It then + // becomes the caller's responsibility to delete the listener. Returns + // NULL if the listener is not found in the list. + TestEventListener* Release(TestEventListener* listener); + + // Returns the standard listener responsible for the default console + // output. Can be removed from the listeners list to shut down default + // console output. Note that removing this object from the listener list + // with Release transfers its ownership to the caller and makes this + // function return NULL the next time. + TestEventListener* default_result_printer() const { + return default_result_printer_; + } + + // Returns the standard listener responsible for the default XML output + // controlled by the --gtest_output=xml flag. Can be removed from the + // listeners list by users who want to shut down the default XML output + // controlled by this flag and substitute it with custom one. Note that + // removing this object from the listener list with Release transfers its + // ownership to the caller and makes this function return NULL the next + // time. + TestEventListener* default_xml_generator() const { + return default_xml_generator_; + } + + private: + friend class TestCase; + friend class TestInfo; + friend class internal::DefaultGlobalTestPartResultReporter; + friend class internal::NoExecDeathTest; + friend class internal::TestEventListenersAccessor; + friend class internal::UnitTestImpl; + + // Returns repeater that broadcasts the TestEventListener events to all + // subscribers. + TestEventListener* repeater(); + + // Sets the default_result_printer attribute to the provided listener. + // The listener is also added to the listener list and previous + // default_result_printer is removed from it and deleted. The listener can + // also be NULL in which case it will not be added to the list. Does + // nothing if the previous and the current listener objects are the same. + void SetDefaultResultPrinter(TestEventListener* listener); + + // Sets the default_xml_generator attribute to the provided listener. The + // listener is also added to the listener list and previous + // default_xml_generator is removed from it and deleted. The listener can + // also be NULL in which case it will not be added to the list. Does + // nothing if the previous and the current listener objects are the same. + void SetDefaultXmlGenerator(TestEventListener* listener); + + // Controls whether events will be forwarded by the repeater to the + // listeners in the list. + bool EventForwardingEnabled() const; + void SuppressEventForwarding(); + + // The actual list of listeners. + internal::TestEventRepeater* repeater_; + // Listener responsible for the standard result output. + TestEventListener* default_result_printer_; + // Listener responsible for the creation of the XML output file. + TestEventListener* default_xml_generator_; + + // We disallow copying TestEventListeners. + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners); +}; + +// A UnitTest consists of a vector of TestCases. +// +// This is a singleton class. The only instance of UnitTest is +// created when UnitTest::GetInstance() is first called. This +// instance is never deleted. +// +// UnitTest is not copyable. +// +// This class is thread-safe as long as the methods are called +// according to their specification. +class GTEST_API_ UnitTest { + public: + // Gets the singleton UnitTest object. The first time this method + // is called, a UnitTest object is constructed and returned. + // Consecutive calls will return the same object. + static UnitTest* GetInstance(); + + // Runs all tests in this UnitTest object and prints the result. + // Returns 0 if successful, or 1 otherwise. + // + // This method can only be called from the main thread. + // + // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + int Run() GTEST_MUST_USE_RESULT_; + + // Returns the working directory when the first TEST() or TEST_F() + // was executed. The UnitTest object owns the string. + const char* original_working_dir() const; + + // Returns the TestCase object for the test that's currently running, + // or NULL if no test is running. + const TestCase* current_test_case() const + GTEST_LOCK_EXCLUDED_(mutex_); + + // Returns the TestInfo object for the test that's currently running, + // or NULL if no test is running. + const TestInfo* current_test_info() const + GTEST_LOCK_EXCLUDED_(mutex_); + + // Returns the random seed used at the start of the current test run. + int random_seed() const; + +#if GTEST_HAS_PARAM_TEST + // Returns the ParameterizedTestCaseRegistry object used to keep track of + // value-parameterized tests and instantiate and register them. + // + // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + internal::ParameterizedTestCaseRegistry& parameterized_test_registry() + GTEST_LOCK_EXCLUDED_(mutex_); +#endif // GTEST_HAS_PARAM_TEST + + // Gets the number of successful test cases. + int successful_test_case_count() const; + + // Gets the number of failed test cases. + int failed_test_case_count() const; + + // Gets the number of all test cases. + int total_test_case_count() const; + + // Gets the number of all test cases that contain at least one test + // that should run. + int test_case_to_run_count() const; + + // Gets the number of successful tests. + int successful_test_count() const; + + // Gets the number of failed tests. + int failed_test_count() const; + + // Gets the number of disabled tests that will be reported in the XML report. + int reportable_disabled_test_count() const; + + // Gets the number of disabled tests. + int disabled_test_count() const; + + // Gets the number of tests to be printed in the XML report. + int reportable_test_count() const; + + // Gets the number of all tests. + int total_test_count() const; + + // Gets the number of tests that should run. + int test_to_run_count() const; + + // Gets the time of the test program start, in ms from the start of the + // UNIX epoch. + TimeInMillis start_timestamp() const; + + // Gets the elapsed time, in milliseconds. + TimeInMillis elapsed_time() const; + + // Returns true iff the unit test passed (i.e. all test cases passed). + bool Passed() const; + + // Returns true iff the unit test failed (i.e. some test case failed + // or something outside of all tests failed). + bool Failed() const; + + // Gets the i-th test case among all the test cases. i can range from 0 to + // total_test_case_count() - 1. If i is not in that range, returns NULL. + const TestCase* GetTestCase(int i) const; + + // Returns the TestResult containing information on test failures and + // properties logged outside of individual test cases. + const TestResult& ad_hoc_test_result() const; + + // Returns the list of event listeners that can be used to track events + // inside Google Test. + TestEventListeners& listeners(); + + private: + // Registers and returns a global test environment. When a test + // program is run, all global test environments will be set-up in + // the order they were registered. After all tests in the program + // have finished, all global test environments will be torn-down in + // the *reverse* order they were registered. + // + // The UnitTest object takes ownership of the given environment. + // + // This method can only be called from the main thread. + Environment* AddEnvironment(Environment* env); + + // Adds a TestPartResult to the current TestResult object. All + // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) + // eventually call this to report their results. The user code + // should use the assertion macros instead of calling this directly. + void AddTestPartResult(TestPartResult::Type result_type, + const char* file_name, + int line_number, + const std::string& message, + const std::string& os_stack_trace) + GTEST_LOCK_EXCLUDED_(mutex_); + + // Adds a TestProperty to the current TestResult object when invoked from + // inside a test, to current TestCase's ad_hoc_test_result_ when invoked + // from SetUpTestCase or TearDownTestCase, or to the global property set + // when invoked elsewhere. If the result already contains a property with + // the same key, the value will be updated. + void RecordProperty(const std::string& key, const std::string& value); + + // Gets the i-th test case among all the test cases. i can range from 0 to + // total_test_case_count() - 1. If i is not in that range, returns NULL. + TestCase* GetMutableTestCase(int i); + + // Accessors for the implementation object. + internal::UnitTestImpl* impl() { return impl_; } + const internal::UnitTestImpl* impl() const { return impl_; } + + // These classes and funcions are friends as they need to access private + // members of UnitTest. + friend class Test; + friend class internal::AssertHelper; + friend class internal::ScopedTrace; + friend class internal::StreamingListenerTest; + friend class internal::UnitTestRecordPropertyTestHelper; + friend Environment* AddGlobalTestEnvironment(Environment* env); + friend internal::UnitTestImpl* internal::GetUnitTestImpl(); + friend void internal::ReportFailureInUnknownLocation( + TestPartResult::Type result_type, + const std::string& message); + + // Creates an empty UnitTest. + UnitTest(); + + // D'tor + virtual ~UnitTest(); + + // Pushes a trace defined by SCOPED_TRACE() on to the per-thread + // Google Test trace stack. + void PushGTestTrace(const internal::TraceInfo& trace) + GTEST_LOCK_EXCLUDED_(mutex_); + + // Pops a trace from the per-thread Google Test trace stack. + void PopGTestTrace() + GTEST_LOCK_EXCLUDED_(mutex_); + + // Protects mutable state in *impl_. This is mutable as some const + // methods need to lock it too. + mutable internal::Mutex mutex_; + + // Opaque implementation object. This field is never changed once + // the object is constructed. We don't mark it as const here, as + // doing so will cause a warning in the constructor of UnitTest. + // Mutable state in *impl_ is protected by mutex_. + internal::UnitTestImpl* impl_; + + // We disallow copying UnitTest. + GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest); +}; + +// A convenient wrapper for adding an environment for the test +// program. +// +// You should call this before RUN_ALL_TESTS() is called, probably in +// main(). If you use gtest_main, you need to call this before main() +// starts for it to take effect. For example, you can define a global +// variable like this: +// +// testing::Environment* const foo_env = +// testing::AddGlobalTestEnvironment(new FooEnvironment); +// +// However, we strongly recommend you to write your own main() and +// call AddGlobalTestEnvironment() there, as relying on initialization +// of global variables makes the code harder to read and may cause +// problems when you register multiple environments from different +// translation units and the environments have dependencies among them +// (remember that the compiler doesn't guarantee the order in which +// global variables from different translation units are initialized). +inline Environment* AddGlobalTestEnvironment(Environment* env) { + return UnitTest::GetInstance()->AddEnvironment(env); +} + +// Initializes Google Test. This must be called before calling +// RUN_ALL_TESTS(). In particular, it parses a command line for the +// flags that Google Test recognizes. Whenever a Google Test flag is +// seen, it is removed from argv, and *argc is decremented. +// +// No value is returned. Instead, the Google Test flag variables are +// updated. +// +// Calling the function for the second time has no user-visible effect. +GTEST_API_ void InitGoogleTest(int* argc, char** argv); + +// This overloaded version can be used in Windows programs compiled in +// UNICODE mode. +GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv); + +namespace internal { + +// FormatForComparison::Format(value) formats a +// value of type ToPrint that is an operand of a comparison assertion +// (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in +// the comparison, and is used to help determine the best way to +// format the value. In particular, when the value is a C string +// (char pointer) and the other operand is an STL string object, we +// want to format the C string as a string, since we know it is +// compared by value with the string object. If the value is a char +// pointer but the other operand is not an STL string object, we don't +// know whether the pointer is supposed to point to a NUL-terminated +// string, and thus want to print it as a pointer to be safe. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + +// The default case. +template +class FormatForComparison { + public: + static ::std::string Format(const ToPrint& value) { + return ::testing::PrintToString(value); + } +}; + +// Array. +template +class FormatForComparison { + public: + static ::std::string Format(const ToPrint* value) { + return FormatForComparison::Format(value); + } +}; + +// By default, print C string as pointers to be safe, as we don't know +// whether they actually point to a NUL-terminated string. + +#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \ + template \ + class FormatForComparison { \ + public: \ + static ::std::string Format(CharType* value) { \ + return ::testing::PrintToString(static_cast(value)); \ + } \ + } + +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char); +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char); +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t); +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t); + +#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_ + +// If a C string is compared with an STL string object, we know it's meant +// to point to a NUL-terminated string, and thus can print it as a string. + +#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \ + template <> \ + class FormatForComparison { \ + public: \ + static ::std::string Format(CharType* value) { \ + return ::testing::PrintToString(value); \ + } \ + } + +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string); + +#if GTEST_HAS_GLOBAL_STRING +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::string); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::string); +#endif + +#if GTEST_HAS_GLOBAL_WSTRING +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::wstring); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::wstring); +#endif + +#if GTEST_HAS_STD_WSTRING +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring); +#endif + +#undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_ + +// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc) +// operand to be used in a failure message. The type (but not value) +// of the other operand may affect the format. This allows us to +// print a char* as a raw pointer when it is compared against another +// char* or void*, and print it as a C string when it is compared +// against an std::string object, for example. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +template +std::string FormatForComparisonFailureMessage( + const T1& value, const T2& /* other_operand */) { + return FormatForComparison::Format(value); +} + +// The helper function for {ASSERT|EXPECT}_EQ. +template +AssertionResult CmpHelperEQ(const char* expected_expression, + const char* actual_expression, + const T1& expected, + const T2& actual) { +#ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4389) // Temporarily disables warning on + // signed/unsigned mismatch. +#endif + + if (expected == actual) { + return AssertionSuccess(); + } + +#ifdef _MSC_VER +# pragma warning(pop) // Restores the warning state. +#endif + + return EqFailure(expected_expression, + actual_expression, + FormatForComparisonFailureMessage(expected, actual), + FormatForComparisonFailureMessage(actual, expected), + false); +} + +// With this overloaded version, we allow anonymous enums to be used +// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums +// can be implicitly cast to BiggestInt. +GTEST_API_ AssertionResult CmpHelperEQ(const char* expected_expression, + const char* actual_expression, + BiggestInt expected, + BiggestInt actual); + +// The helper class for {ASSERT|EXPECT}_EQ. The template argument +// lhs_is_null_literal is true iff the first argument to ASSERT_EQ() +// is a null pointer literal. The following default implementation is +// for lhs_is_null_literal being false. +template +class EqHelper { + public: + // This templatized version is for the general case. + template + static AssertionResult Compare(const char* expected_expression, + const char* actual_expression, + const T1& expected, + const T2& actual) { + return CmpHelperEQ(expected_expression, actual_expression, expected, + actual); + } + + // With this overloaded version, we allow anonymous enums to be used + // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous + // enums can be implicitly cast to BiggestInt. + // + // Even though its body looks the same as the above version, we + // cannot merge the two, as it will make anonymous enums unhappy. + static AssertionResult Compare(const char* expected_expression, + const char* actual_expression, + BiggestInt expected, + BiggestInt actual) { + return CmpHelperEQ(expected_expression, actual_expression, expected, + actual); + } +}; + +// This specialization is used when the first argument to ASSERT_EQ() +// is a null pointer literal, like NULL, false, or 0. +template <> +class EqHelper { + public: + // We define two overloaded versions of Compare(). The first + // version will be picked when the second argument to ASSERT_EQ() is + // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or + // EXPECT_EQ(false, a_bool). + template + static AssertionResult Compare( + const char* expected_expression, + const char* actual_expression, + const T1& expected, + const T2& actual, + // The following line prevents this overload from being considered if T2 + // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr) + // expands to Compare("", "", NULL, my_ptr), which requires a conversion + // to match the Secret* in the other overload, which would otherwise make + // this template match better. + typename EnableIf::value>::type* = 0) { + return CmpHelperEQ(expected_expression, actual_expression, expected, + actual); + } + + // This version will be picked when the second argument to ASSERT_EQ() is a + // pointer, e.g. ASSERT_EQ(NULL, a_pointer). + template + static AssertionResult Compare( + const char* expected_expression, + const char* actual_expression, + // We used to have a second template parameter instead of Secret*. That + // template parameter would deduce to 'long', making this a better match + // than the first overload even without the first overload's EnableIf. + // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to + // non-pointer argument" (even a deduced integral argument), so the old + // implementation caused warnings in user code. + Secret* /* expected (NULL) */, + T* actual) { + // We already know that 'expected' is a null pointer. + return CmpHelperEQ(expected_expression, actual_expression, + static_cast(NULL), actual); + } +}; + +// A macro for implementing the helper functions needed to implement +// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste +// of similar code. +// +// For each templatized helper function, we also define an overloaded +// version for BiggestInt in order to reduce code bloat and allow +// anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled +// with gcc 4. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ +template \ +AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ + const T1& val1, const T2& val2) {\ + if (val1 op val2) {\ + return AssertionSuccess();\ + } else {\ + return AssertionFailure() \ + << "Expected: (" << expr1 << ") " #op " (" << expr2\ + << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ + << " vs " << FormatForComparisonFailureMessage(val2, val1);\ + }\ +}\ +GTEST_API_ AssertionResult CmpHelper##op_name(\ + const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) + +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + +// Implements the helper function for {ASSERT|EXPECT}_NE +GTEST_IMPL_CMP_HELPER_(NE, !=); +// Implements the helper function for {ASSERT|EXPECT}_LE +GTEST_IMPL_CMP_HELPER_(LE, <=); +// Implements the helper function for {ASSERT|EXPECT}_LT +GTEST_IMPL_CMP_HELPER_(LT, <); +// Implements the helper function for {ASSERT|EXPECT}_GE +GTEST_IMPL_CMP_HELPER_(GE, >=); +// Implements the helper function for {ASSERT|EXPECT}_GT +GTEST_IMPL_CMP_HELPER_(GT, >); + +#undef GTEST_IMPL_CMP_HELPER_ + +// The helper function for {ASSERT|EXPECT}_STREQ. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, + const char* actual_expression, + const char* expected, + const char* actual); + +// The helper function for {ASSERT|EXPECT}_STRCASEEQ. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, + const char* actual_expression, + const char* expected, + const char* actual); + +// The helper function for {ASSERT|EXPECT}_STRNE. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2); + +// The helper function for {ASSERT|EXPECT}_STRCASENE. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2); + + +// Helper function for *_STREQ on wide strings. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, + const char* actual_expression, + const wchar_t* expected, + const wchar_t* actual); + +// Helper function for *_STRNE on wide strings. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, + const char* s2_expression, + const wchar_t* s1, + const wchar_t* s2); + +} // namespace internal + +// IsSubstring() and IsNotSubstring() are intended to be used as the +// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by +// themselves. They check whether needle is a substring of haystack +// (NULL is considered a substring of itself only), and return an +// appropriate error message when they fail. +// +// The {needle,haystack}_expr arguments are the stringified +// expressions that generated the two real arguments. +GTEST_API_ AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const char* needle, const char* haystack); +GTEST_API_ AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const wchar_t* needle, const wchar_t* haystack); +GTEST_API_ AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const char* needle, const char* haystack); +GTEST_API_ AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const wchar_t* needle, const wchar_t* haystack); +GTEST_API_ AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, const ::std::string& haystack); +GTEST_API_ AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, const ::std::string& haystack); + +#if GTEST_HAS_STD_WSTRING +GTEST_API_ AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, const ::std::wstring& haystack); +GTEST_API_ AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, const ::std::wstring& haystack); +#endif // GTEST_HAS_STD_WSTRING + +namespace internal { + +// Helper template function for comparing floating-points. +// +// Template parameter: +// +// RawType: the raw floating-point type (either float or double) +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +template +AssertionResult CmpHelperFloatingPointEQ(const char* expected_expression, + const char* actual_expression, + RawType expected, + RawType actual) { + const FloatingPoint lhs(expected), rhs(actual); + + if (lhs.AlmostEquals(rhs)) { + return AssertionSuccess(); + } + + ::std::stringstream expected_ss; + expected_ss << std::setprecision(std::numeric_limits::digits10 + 2) + << expected; + + ::std::stringstream actual_ss; + actual_ss << std::setprecision(std::numeric_limits::digits10 + 2) + << actual; + + return EqFailure(expected_expression, + actual_expression, + StringStreamToString(&expected_ss), + StringStreamToString(&actual_ss), + false); +} + +// Helper function for implementing ASSERT_NEAR. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, + const char* expr2, + const char* abs_error_expr, + double val1, + double val2, + double abs_error); + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// A class that enables one to stream messages to assertion macros +class GTEST_API_ AssertHelper { + public: + // Constructor. + AssertHelper(TestPartResult::Type type, + const char* file, + int line, + const char* message); + ~AssertHelper(); + + // Message assignment is a semantic trick to enable assertion + // streaming; see the GTEST_MESSAGE_ macro below. + void operator=(const Message& message) const; + + private: + // We put our data in a struct so that the size of the AssertHelper class can + // be as small as possible. This is important because gcc is incapable of + // re-using stack space even for temporary variables, so every EXPECT_EQ + // reserves stack space for another AssertHelper. + struct AssertHelperData { + AssertHelperData(TestPartResult::Type t, + const char* srcfile, + int line_num, + const char* msg) + : type(t), file(srcfile), line(line_num), message(msg) { } + + TestPartResult::Type const type; + const char* const file; + int const line; + std::string const message; + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); + }; + + AssertHelperData* const data_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper); +}; + +} // namespace internal + +#if GTEST_HAS_PARAM_TEST +// The pure interface class that all value-parameterized tests inherit from. +// A value-parameterized class must inherit from both ::testing::Test and +// ::testing::WithParamInterface. In most cases that just means inheriting +// from ::testing::TestWithParam, but more complicated test hierarchies +// may need to inherit from Test and WithParamInterface at different levels. +// +// This interface has support for accessing the test parameter value via +// the GetParam() method. +// +// Use it with one of the parameter generator defining functions, like Range(), +// Values(), ValuesIn(), Bool(), and Combine(). +// +// class FooTest : public ::testing::TestWithParam { +// protected: +// FooTest() { +// // Can use GetParam() here. +// } +// virtual ~FooTest() { +// // Can use GetParam() here. +// } +// virtual void SetUp() { +// // Can use GetParam() here. +// } +// virtual void TearDown { +// // Can use GetParam() here. +// } +// }; +// TEST_P(FooTest, DoesBar) { +// // Can use GetParam() method here. +// Foo foo; +// ASSERT_TRUE(foo.DoesBar(GetParam())); +// } +// INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10)); + +template +class WithParamInterface { + public: + typedef T ParamType; + virtual ~WithParamInterface() {} + + // The current parameter value. Is also available in the test fixture's + // constructor. This member function is non-static, even though it only + // references static data, to reduce the opportunity for incorrect uses + // like writing 'WithParamInterface::GetParam()' for a test that + // uses a fixture whose parameter type is int. + const ParamType& GetParam() const { + GTEST_CHECK_(parameter_ != NULL) + << "GetParam() can only be called inside a value-parameterized test " + << "-- did you intend to write TEST_P instead of TEST_F?"; + return *parameter_; + } + + private: + // Sets parameter value. The caller is responsible for making sure the value + // remains alive and unchanged throughout the current test. + static void SetParam(const ParamType* parameter) { + parameter_ = parameter; + } + + // Static value used for accessing parameter during a test lifetime. + static const ParamType* parameter_; + + // TestClass must be a subclass of WithParamInterface and Test. + template friend class internal::ParameterizedTestFactory; +}; + +template +const T* WithParamInterface::parameter_ = NULL; + +// Most value-parameterized classes can ignore the existence of +// WithParamInterface, and can just inherit from ::testing::TestWithParam. + +template +class TestWithParam : public Test, public WithParamInterface { +}; + +#endif // GTEST_HAS_PARAM_TEST + +// Macros for indicating success/failure in test code. + +// ADD_FAILURE unconditionally adds a failure to the current test. +// SUCCEED generates a success - it doesn't automatically make the +// current test successful, as a test is only successful when it has +// no failure. +// +// EXPECT_* verifies that a certain condition is satisfied. If not, +// it behaves like ADD_FAILURE. In particular: +// +// EXPECT_TRUE verifies that a Boolean condition is true. +// EXPECT_FALSE verifies that a Boolean condition is false. +// +// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except +// that they will also abort the current function on failure. People +// usually want the fail-fast behavior of FAIL and ASSERT_*, but those +// writing data-driven tests often find themselves using ADD_FAILURE +// and EXPECT_* more. + +// Generates a nonfatal failure with a generic message. +#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") + +// Generates a nonfatal failure at the given source file location with +// a generic message. +#define ADD_FAILURE_AT(file, line) \ + GTEST_MESSAGE_AT_(file, line, "Failed", \ + ::testing::TestPartResult::kNonFatalFailure) + +// Generates a fatal failure with a generic message. +#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") + +// Define this macro to 1 to omit the definition of FAIL(), which is a +// generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_FAIL +# define FAIL() GTEST_FAIL() +#endif + +// Generates a success with a generic message. +#define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded") + +// Define this macro to 1 to omit the definition of SUCCEED(), which +// is a generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_SUCCEED +# define SUCCEED() GTEST_SUCCEED() +#endif + +// Macros for testing exceptions. +// +// * {ASSERT|EXPECT}_THROW(statement, expected_exception): +// Tests that the statement throws the expected exception. +// * {ASSERT|EXPECT}_NO_THROW(statement): +// Tests that the statement doesn't throw any exception. +// * {ASSERT|EXPECT}_ANY_THROW(statement): +// Tests that the statement throws an exception. + +#define EXPECT_THROW(statement, expected_exception) \ + GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_) +#define EXPECT_NO_THROW(statement) \ + GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_) +#define EXPECT_ANY_THROW(statement) \ + GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_) +#define ASSERT_THROW(statement, expected_exception) \ + GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_) +#define ASSERT_NO_THROW(statement) \ + GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_) +#define ASSERT_ANY_THROW(statement) \ + GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_) + +// Boolean assertions. Condition can be either a Boolean expression or an +// AssertionResult. For more information on how to use AssertionResult with +// these macros see comments on that class. +#define EXPECT_TRUE(condition) \ + GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ + GTEST_NONFATAL_FAILURE_) +#define EXPECT_FALSE(condition) \ + GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ + GTEST_NONFATAL_FAILURE_) +#define ASSERT_TRUE(condition) \ + GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ + GTEST_FATAL_FAILURE_) +#define ASSERT_FALSE(condition) \ + GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ + GTEST_FATAL_FAILURE_) + +// Includes the auto-generated header that implements a family of +// generic predicate assertion macros. +#include "gtest/gtest_pred_impl.h" + +// Macros for testing equalities and inequalities. +// +// * {ASSERT|EXPECT}_EQ(expected, actual): Tests that expected == actual +// * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2 +// * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2 +// * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2 +// * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2 +// * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2 +// +// When they are not, Google Test prints both the tested expressions and +// their actual values. The values must be compatible built-in types, +// or you will get a compiler error. By "compatible" we mean that the +// values can be compared by the respective operator. +// +// Note: +// +// 1. It is possible to make a user-defined type work with +// {ASSERT|EXPECT}_??(), but that requires overloading the +// comparison operators and is thus discouraged by the Google C++ +// Usage Guide. Therefore, you are advised to use the +// {ASSERT|EXPECT}_TRUE() macro to assert that two objects are +// equal. +// +// 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on +// pointers (in particular, C strings). Therefore, if you use it +// with two C strings, you are testing how their locations in memory +// are related, not how their content is related. To compare two C +// strings by content, use {ASSERT|EXPECT}_STR*(). +// +// 3. {ASSERT|EXPECT}_EQ(expected, actual) is preferred to +// {ASSERT|EXPECT}_TRUE(expected == actual), as the former tells you +// what the actual value is when it fails, and similarly for the +// other comparisons. +// +// 4. Do not depend on the order in which {ASSERT|EXPECT}_??() +// evaluate their arguments, which is undefined. +// +// 5. These macros evaluate their arguments exactly once. +// +// Examples: +// +// EXPECT_NE(5, Foo()); +// EXPECT_EQ(NULL, a_pointer); +// ASSERT_LT(i, array_size); +// ASSERT_GT(records.size(), 0) << "There is no record left."; + +#define EXPECT_EQ(expected, actual) \ + EXPECT_PRED_FORMAT2(::testing::internal:: \ + EqHelper::Compare, \ + expected, actual) +#define EXPECT_NE(expected, actual) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, expected, actual) +#define EXPECT_LE(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) +#define EXPECT_LT(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) +#define EXPECT_GE(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) +#define EXPECT_GT(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) + +#define GTEST_ASSERT_EQ(expected, actual) \ + ASSERT_PRED_FORMAT2(::testing::internal:: \ + EqHelper::Compare, \ + expected, actual) +#define GTEST_ASSERT_NE(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) +#define GTEST_ASSERT_LE(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) +#define GTEST_ASSERT_LT(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) +#define GTEST_ASSERT_GE(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) +#define GTEST_ASSERT_GT(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) + +// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of +// ASSERT_XY(), which clashes with some users' own code. + +#if !GTEST_DONT_DEFINE_ASSERT_EQ +# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_NE +# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_LE +# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_LT +# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_GE +# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_GT +# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) +#endif + +// C-string Comparisons. All tests treat NULL and any non-NULL string +// as different. Two NULLs are equal. +// +// * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2 +// * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2 +// * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case +// * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case +// +// For wide or narrow string objects, you can use the +// {ASSERT|EXPECT}_??() macros. +// +// Don't depend on the order in which the arguments are evaluated, +// which is undefined. +// +// These macros evaluate their arguments exactly once. + +#define EXPECT_STREQ(expected, actual) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) +#define EXPECT_STRNE(s1, s2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) +#define EXPECT_STRCASEEQ(expected, actual) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) +#define EXPECT_STRCASENE(s1, s2)\ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) + +#define ASSERT_STREQ(expected, actual) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) +#define ASSERT_STRNE(s1, s2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) +#define ASSERT_STRCASEEQ(expected, actual) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) +#define ASSERT_STRCASENE(s1, s2)\ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) + +// Macros for comparing floating-point numbers. +// +// * {ASSERT|EXPECT}_FLOAT_EQ(expected, actual): +// Tests that two float values are almost equal. +// * {ASSERT|EXPECT}_DOUBLE_EQ(expected, actual): +// Tests that two double values are almost equal. +// * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error): +// Tests that v1 and v2 are within the given distance to each other. +// +// Google Test uses ULP-based comparison to automatically pick a default +// error bound that is appropriate for the operands. See the +// FloatingPoint template class in gtest-internal.h if you are +// interested in the implementation details. + +#define EXPECT_FLOAT_EQ(expected, actual)\ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ + expected, actual) + +#define EXPECT_DOUBLE_EQ(expected, actual)\ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ + expected, actual) + +#define ASSERT_FLOAT_EQ(expected, actual)\ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ + expected, actual) + +#define ASSERT_DOUBLE_EQ(expected, actual)\ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ + expected, actual) + +#define EXPECT_NEAR(val1, val2, abs_error)\ + EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ + val1, val2, abs_error) + +#define ASSERT_NEAR(val1, val2, abs_error)\ + ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ + val1, val2, abs_error) + +// These predicate format functions work on floating-point values, and +// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g. +// +// EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0); + +// Asserts that val1 is less than, or almost equal to, val2. Fails +// otherwise. In particular, it fails if either val1 or val2 is NaN. +GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, + float val1, float val2); +GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, + double val1, double val2); + + +#if GTEST_OS_WINDOWS + +// Macros that test for HRESULT failure and success, these are only useful +// on Windows, and rely on Windows SDK macros and APIs to compile. +// +// * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr) +// +// When expr unexpectedly fails or succeeds, Google Test prints the +// expected result and the actual result with both a human-readable +// string representation of the error, if available, as well as the +// hex result code. +# define EXPECT_HRESULT_SUCCEEDED(expr) \ + EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) + +# define ASSERT_HRESULT_SUCCEEDED(expr) \ + ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) + +# define EXPECT_HRESULT_FAILED(expr) \ + EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) + +# define ASSERT_HRESULT_FAILED(expr) \ + ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) + +#endif // GTEST_OS_WINDOWS + +// Macros that execute statement and check that it doesn't generate new fatal +// failures in the current thread. +// +// * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement); +// +// Examples: +// +// EXPECT_NO_FATAL_FAILURE(Process()); +// ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed"; +// +#define ASSERT_NO_FATAL_FAILURE(statement) \ + GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) +#define EXPECT_NO_FATAL_FAILURE(statement) \ + GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) + +// Causes a trace (including the source file path, the current line +// number, and the given message) to be included in every test failure +// message generated by code in the current scope. The effect is +// undone when the control leaves the current scope. +// +// The message argument can be anything streamable to std::ostream. +// +// In the implementation, we include the current line number as part +// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s +// to appear in the same block - as long as they are on different +// lines. +#define SCOPED_TRACE(message) \ + ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ + __FILE__, __LINE__, ::testing::Message() << (message)) + +// Compile-time assertion for type equality. +// StaticAssertTypeEq() compiles iff type1 and type2 are +// the same type. The value it returns is not interesting. +// +// Instead of making StaticAssertTypeEq a class template, we make it a +// function template that invokes a helper class template. This +// prevents a user from misusing StaticAssertTypeEq by +// defining objects of that type. +// +// CAVEAT: +// +// When used inside a method of a class template, +// StaticAssertTypeEq() is effective ONLY IF the method is +// instantiated. For example, given: +// +// template class Foo { +// public: +// void Bar() { testing::StaticAssertTypeEq(); } +// }; +// +// the code: +// +// void Test1() { Foo foo; } +// +// will NOT generate a compiler error, as Foo::Bar() is never +// actually instantiated. Instead, you need: +// +// void Test2() { Foo foo; foo.Bar(); } +// +// to cause a compiler error. +template +bool StaticAssertTypeEq() { + (void)internal::StaticAssertTypeEqHelper(); + return true; +} + +// Defines a test. +// +// The first parameter is the name of the test case, and the second +// parameter is the name of the test within the test case. +// +// The convention is to end the test case name with "Test". For +// example, a test case for the Foo class can be named FooTest. +// +// The user should put his test code between braces after using this +// macro. Example: +// +// TEST(FooTest, InitializesCorrectly) { +// Foo foo; +// EXPECT_TRUE(foo.StatusIsOK()); +// } + +// Note that we call GetTestTypeId() instead of GetTypeId< +// ::testing::Test>() here to get the type ID of testing::Test. This +// is to work around a suspected linker bug when using Google Test as +// a framework on Mac OS X. The bug causes GetTypeId< +// ::testing::Test>() to return different values depending on whether +// the call is from the Google Test framework itself or from user test +// code. GetTestTypeId() is guaranteed to always return the same +// value, as it always calls GetTypeId<>() from the Google Test +// framework. +#define GTEST_TEST(test_case_name, test_name)\ + GTEST_TEST_(test_case_name, test_name, \ + ::testing::Test, ::testing::internal::GetTestTypeId()) + +// Define this macro to 1 to omit the definition of TEST(), which +// is a generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_TEST +# define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) +#endif + +// Defines a test that uses a test fixture. +// +// The first parameter is the name of the test fixture class, which +// also doubles as the test case name. The second parameter is the +// name of the test within the test case. +// +// A test fixture class must be declared earlier. The user should put +// his test code between braces after using this macro. Example: +// +// class FooTest : public testing::Test { +// protected: +// virtual void SetUp() { b_.AddElement(3); } +// +// Foo a_; +// Foo b_; +// }; +// +// TEST_F(FooTest, InitializesCorrectly) { +// EXPECT_TRUE(a_.StatusIsOK()); +// } +// +// TEST_F(FooTest, ReturnsElementCountCorrectly) { +// EXPECT_EQ(0, a_.size()); +// EXPECT_EQ(1, b_.size()); +// } + +#define TEST_F(test_fixture, test_name)\ + GTEST_TEST_(test_fixture, test_name, test_fixture, \ + ::testing::internal::GetTypeId()) + +} // namespace testing + +// Use this function in main() to run all tests. It returns 0 if all +// tests are successful, or 1 otherwise. +// +// RUN_ALL_TESTS() should be invoked after the command line has been +// parsed by InitGoogleTest(). +// +// This function was formerly a macro; thus, it is in the global +// namespace and has an all-caps name. +int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_; + +inline int RUN_ALL_TESTS() { + return ::testing::UnitTest::GetInstance()->Run(); +} + +#endif // GTEST_INCLUDE_GTEST_GTEST_H_ diff --git a/lib/gtest/include/gtest/gtest_pred_impl.h b/lib/gtest/include/gtest/gtest_pred_impl.h new file mode 100644 index 00000000..30ae712f --- /dev/null +++ b/lib/gtest/include/gtest/gtest_pred_impl.h @@ -0,0 +1,358 @@ +// Copyright 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// This file is AUTOMATICALLY GENERATED on 10/31/2011 by command +// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! +// +// Implements a family of generic predicate assertion macros. + +#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ +#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ + +// Makes sure this header is not included before gtest.h. +#ifndef GTEST_INCLUDE_GTEST_GTEST_H_ +# error Do not include gtest_pred_impl.h directly. Include gtest.h instead. +#endif // GTEST_INCLUDE_GTEST_GTEST_H_ + +// This header implements a family of generic predicate assertion +// macros: +// +// ASSERT_PRED_FORMAT1(pred_format, v1) +// ASSERT_PRED_FORMAT2(pred_format, v1, v2) +// ... +// +// where pred_format is a function or functor that takes n (in the +// case of ASSERT_PRED_FORMATn) values and their source expression +// text, and returns a testing::AssertionResult. See the definition +// of ASSERT_EQ in gtest.h for an example. +// +// If you don't care about formatting, you can use the more +// restrictive version: +// +// ASSERT_PRED1(pred, v1) +// ASSERT_PRED2(pred, v1, v2) +// ... +// +// where pred is an n-ary function or functor that returns bool, +// and the values v1, v2, ..., must support the << operator for +// streaming to std::ostream. +// +// We also define the EXPECT_* variations. +// +// For now we only support predicates whose arity is at most 5. +// Please email googletestframework@googlegroups.com if you need +// support for higher arities. + +// GTEST_ASSERT_ is the basic statement to which all of the assertions +// in this file reduce. Don't use this in your code. + +#define GTEST_ASSERT_(expression, on_failure) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (const ::testing::AssertionResult gtest_ar = (expression)) \ + ; \ + else \ + on_failure(gtest_ar.failure_message()) + + +// Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use +// this in your code. +template +AssertionResult AssertPred1Helper(const char* pred_text, + const char* e1, + Pred pred, + const T1& v1) { + if (pred(v1)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. +// Don't use this in your code. +#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, v1), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use +// this in your code. +#define GTEST_PRED1_(pred, v1, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \ + #v1, \ + pred, \ + v1), on_failure) + +// Unary predicate assertion macros. +#define EXPECT_PRED_FORMAT1(pred_format, v1) \ + GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED1(pred, v1) \ + GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT1(pred_format, v1) \ + GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED1(pred, v1) \ + GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) + + + +// Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use +// this in your code. +template +AssertionResult AssertPred2Helper(const char* pred_text, + const char* e1, + const char* e2, + Pred pred, + const T1& v1, + const T2& v2) { + if (pred(v1, v2)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. +// Don't use this in your code. +#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use +// this in your code. +#define GTEST_PRED2_(pred, v1, v2, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \ + #v1, \ + #v2, \ + pred, \ + v1, \ + v2), on_failure) + +// Binary predicate assertion macros. +#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \ + GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED2(pred, v1, v2) \ + GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \ + GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED2(pred, v1, v2) \ + GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) + + + +// Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use +// this in your code. +template +AssertionResult AssertPred3Helper(const char* pred_text, + const char* e1, + const char* e2, + const char* e3, + Pred pred, + const T1& v1, + const T2& v2, + const T3& v3) { + if (pred(v1, v2, v3)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ", " + << e3 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2 + << "\n" << e3 << " evaluates to " << v3; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. +// Don't use this in your code. +#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use +// this in your code. +#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \ + #v1, \ + #v2, \ + #v3, \ + pred, \ + v1, \ + v2, \ + v3), on_failure) + +// Ternary predicate assertion macros. +#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \ + GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED3(pred, v1, v2, v3) \ + GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \ + GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED3(pred, v1, v2, v3) \ + GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) + + + +// Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use +// this in your code. +template +AssertionResult AssertPred4Helper(const char* pred_text, + const char* e1, + const char* e2, + const char* e3, + const char* e4, + Pred pred, + const T1& v1, + const T2& v2, + const T3& v3, + const T4& v4) { + if (pred(v1, v2, v3, v4)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ", " + << e3 << ", " + << e4 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2 + << "\n" << e3 << " evaluates to " << v3 + << "\n" << e4 << " evaluates to " << v4; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. +// Don't use this in your code. +#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use +// this in your code. +#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \ + #v1, \ + #v2, \ + #v3, \ + #v4, \ + pred, \ + v1, \ + v2, \ + v3, \ + v4), on_failure) + +// 4-ary predicate assertion macros. +#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ + GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED4(pred, v1, v2, v3, v4) \ + GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ + GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED4(pred, v1, v2, v3, v4) \ + GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) + + + +// Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use +// this in your code. +template +AssertionResult AssertPred5Helper(const char* pred_text, + const char* e1, + const char* e2, + const char* e3, + const char* e4, + const char* e5, + Pred pred, + const T1& v1, + const T2& v2, + const T3& v3, + const T4& v4, + const T5& v5) { + if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ", " + << e3 << ", " + << e4 << ", " + << e5 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2 + << "\n" << e3 << " evaluates to " << v3 + << "\n" << e4 << " evaluates to " << v4 + << "\n" << e5 << " evaluates to " << v5; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. +// Don't use this in your code. +#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use +// this in your code. +#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \ + #v1, \ + #v2, \ + #v3, \ + #v4, \ + #v5, \ + pred, \ + v1, \ + v2, \ + v3, \ + v4, \ + v5), on_failure) + +// 5-ary predicate assertion macros. +#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ + GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \ + GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ + GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \ + GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) + + + +#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ diff --git a/lib/gtest/include/gtest/gtest_prod.h b/lib/gtest/include/gtest/gtest_prod.h new file mode 100644 index 00000000..da80ddc6 --- /dev/null +++ b/lib/gtest/include/gtest/gtest_prod.h @@ -0,0 +1,58 @@ +// Copyright 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// Google C++ Testing Framework definitions useful in production code. + +#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ +#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ + +// When you need to test the private or protected members of a class, +// use the FRIEND_TEST macro to declare your tests as friends of the +// class. For example: +// +// class MyClass { +// private: +// void MyMethod(); +// FRIEND_TEST(MyClassTest, MyMethod); +// }; +// +// class MyClassTest : public testing::Test { +// // ... +// }; +// +// TEST_F(MyClassTest, MyMethod) { +// // Can call MyClass::MyMethod() here. +// } + +#define FRIEND_TEST(test_case_name, test_name)\ +friend class test_case_name##_##test_name##_Test + +#endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_ diff --git a/lib/gtest/include/gtest/internal/gtest-death-test-internal.h b/lib/gtest/include/gtest/internal/gtest-death-test-internal.h new file mode 100644 index 00000000..2b3a78f5 --- /dev/null +++ b/lib/gtest/include/gtest/internal/gtest-death-test-internal.h @@ -0,0 +1,319 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file defines internal utilities needed for implementing +// death tests. They are subject to change without notice. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ + +#include "gtest/internal/gtest-internal.h" + +#include + +namespace testing { +namespace internal { + +GTEST_DECLARE_string_(internal_run_death_test); + +// Names of the flags (needed for parsing Google Test flags). +const char kDeathTestStyleFlag[] = "death_test_style"; +const char kDeathTestUseFork[] = "death_test_use_fork"; +const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; + +#if GTEST_HAS_DEATH_TEST + +// DeathTest is a class that hides much of the complexity of the +// GTEST_DEATH_TEST_ macro. It is abstract; its static Create method +// returns a concrete class that depends on the prevailing death test +// style, as defined by the --gtest_death_test_style and/or +// --gtest_internal_run_death_test flags. + +// In describing the results of death tests, these terms are used with +// the corresponding definitions: +// +// exit status: The integer exit information in the format specified +// by wait(2) +// exit code: The integer code passed to exit(3), _exit(2), or +// returned from main() +class GTEST_API_ DeathTest { + public: + // Create returns false if there was an error determining the + // appropriate action to take for the current death test; for example, + // if the gtest_death_test_style flag is set to an invalid value. + // The LastMessage method will return a more detailed message in that + // case. Otherwise, the DeathTest pointer pointed to by the "test" + // argument is set. If the death test should be skipped, the pointer + // is set to NULL; otherwise, it is set to the address of a new concrete + // DeathTest object that controls the execution of the current test. + static bool Create(const char* statement, const RE* regex, + const char* file, int line, DeathTest** test); + DeathTest(); + virtual ~DeathTest() { } + + // A helper class that aborts a death test when it's deleted. + class ReturnSentinel { + public: + explicit ReturnSentinel(DeathTest* test) : test_(test) { } + ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } + private: + DeathTest* const test_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel); + } GTEST_ATTRIBUTE_UNUSED_; + + // An enumeration of possible roles that may be taken when a death + // test is encountered. EXECUTE means that the death test logic should + // be executed immediately. OVERSEE means that the program should prepare + // the appropriate environment for a child process to execute the death + // test, then wait for it to complete. + enum TestRole { OVERSEE_TEST, EXECUTE_TEST }; + + // An enumeration of the three reasons that a test might be aborted. + enum AbortReason { + TEST_ENCOUNTERED_RETURN_STATEMENT, + TEST_THREW_EXCEPTION, + TEST_DID_NOT_DIE + }; + + // Assumes one of the above roles. + virtual TestRole AssumeRole() = 0; + + // Waits for the death test to finish and returns its status. + virtual int Wait() = 0; + + // Returns true if the death test passed; that is, the test process + // exited during the test, its exit status matches a user-supplied + // predicate, and its stderr output matches a user-supplied regular + // expression. + // The user-supplied predicate may be a macro expression rather + // than a function pointer or functor, or else Wait and Passed could + // be combined. + virtual bool Passed(bool exit_status_ok) = 0; + + // Signals that the death test did not die as expected. + virtual void Abort(AbortReason reason) = 0; + + // Returns a human-readable outcome message regarding the outcome of + // the last death test. + static const char* LastMessage(); + + static void set_last_death_test_message(const std::string& message); + + private: + // A string containing a description of the outcome of the last death test. + static std::string last_death_test_message_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); +}; + +// Factory interface for death tests. May be mocked out for testing. +class DeathTestFactory { + public: + virtual ~DeathTestFactory() { } + virtual bool Create(const char* statement, const RE* regex, + const char* file, int line, DeathTest** test) = 0; +}; + +// A concrete DeathTestFactory implementation for normal use. +class DefaultDeathTestFactory : public DeathTestFactory { + public: + virtual bool Create(const char* statement, const RE* regex, + const char* file, int line, DeathTest** test); +}; + +// Returns true if exit_status describes a process that was terminated +// by a signal, or exited normally with a nonzero exit code. +GTEST_API_ bool ExitedUnsuccessfully(int exit_status); + +// Traps C++ exceptions escaping statement and reports them as test +// failures. Note that trapping SEH exceptions is not implemented here. +# if GTEST_HAS_EXCEPTIONS +# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } catch (const ::std::exception& gtest_exception) { \ + fprintf(\ + stderr, \ + "\n%s: Caught std::exception-derived exception escaping the " \ + "death test statement. Exception message: %s\n", \ + ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \ + gtest_exception.what()); \ + fflush(stderr); \ + death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ + } catch (...) { \ + death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ + } + +# else +# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) + +# endif + +// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, +// ASSERT_EXIT*, and EXPECT_EXIT*. +# define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + const ::testing::internal::RE& gtest_regex = (regex); \ + ::testing::internal::DeathTest* gtest_dt; \ + if (!::testing::internal::DeathTest::Create(#statement, >est_regex, \ + __FILE__, __LINE__, >est_dt)) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ + } \ + if (gtest_dt != NULL) { \ + ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \ + gtest_dt_ptr(gtest_dt); \ + switch (gtest_dt->AssumeRole()) { \ + case ::testing::internal::DeathTest::OVERSEE_TEST: \ + if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ + } \ + break; \ + case ::testing::internal::DeathTest::EXECUTE_TEST: { \ + ::testing::internal::DeathTest::ReturnSentinel \ + gtest_sentinel(gtest_dt); \ + GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ + gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ + break; \ + } \ + default: \ + break; \ + } \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \ + fail(::testing::internal::DeathTest::LastMessage()) +// The symbol "fail" here expands to something into which a message +// can be streamed. + +// This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in +// NDEBUG mode. In this case we need the statements to be executed, the regex is +// ignored, and the macro must accept a streamed message even though the message +// is never printed. +# define GTEST_EXECUTE_STATEMENT_(statement, regex) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } else \ + ::testing::Message() + +// A class representing the parsed contents of the +// --gtest_internal_run_death_test flag, as it existed when +// RUN_ALL_TESTS was called. +class InternalRunDeathTestFlag { + public: + InternalRunDeathTestFlag(const std::string& a_file, + int a_line, + int an_index, + int a_write_fd) + : file_(a_file), line_(a_line), index_(an_index), + write_fd_(a_write_fd) {} + + ~InternalRunDeathTestFlag() { + if (write_fd_ >= 0) + posix::Close(write_fd_); + } + + const std::string& file() const { return file_; } + int line() const { return line_; } + int index() const { return index_; } + int write_fd() const { return write_fd_; } + + private: + std::string file_; + int line_; + int index_; + int write_fd_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag); +}; + +// Returns a newly created InternalRunDeathTestFlag object with fields +// initialized from the GTEST_FLAG(internal_run_death_test) flag if +// the flag is specified; otherwise returns NULL. +InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag(); + +#else // GTEST_HAS_DEATH_TEST + +// This macro is used for implementing macros such as +// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where +// death tests are not supported. Those macros must compile on such systems +// iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on +// systems that support death tests. This allows one to write such a macro +// on a system that does not support death tests and be sure that it will +// compile on a death-test supporting system. +// +// Parameters: +// statement - A statement that a macro such as EXPECT_DEATH would test +// for program termination. This macro has to make sure this +// statement is compiled but not executed, to ensure that +// EXPECT_DEATH_IF_SUPPORTED compiles with a certain +// parameter iff EXPECT_DEATH compiles with it. +// regex - A regex that a macro such as EXPECT_DEATH would use to test +// the output of statement. This parameter has to be +// compiled but not evaluated by this macro, to ensure that +// this macro only accepts expressions that a macro such as +// EXPECT_DEATH would accept. +// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED +// and a return statement for ASSERT_DEATH_IF_SUPPORTED. +// This ensures that ASSERT_DEATH_IF_SUPPORTED will not +// compile inside functions where ASSERT_DEATH doesn't +// compile. +// +// The branch that has an always false condition is used to ensure that +// statement and regex are compiled (and thus syntactically correct) but +// never executed. The unreachable code macro protects the terminator +// statement from generating an 'unreachable code' warning in case +// statement unconditionally returns or throws. The Message constructor at +// the end allows the syntax of streaming additional messages into the +// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. +# define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + GTEST_LOG_(WARNING) \ + << "Death tests are not supported on this platform.\n" \ + << "Statement '" #statement "' cannot be verified."; \ + } else if (::testing::internal::AlwaysFalse()) { \ + ::testing::internal::RE::PartialMatch(".*", (regex)); \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + terminator; \ + } else \ + ::testing::Message() + +#endif // GTEST_HAS_DEATH_TEST + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ diff --git a/lib/gtest/include/gtest/internal/gtest-filepath.h b/lib/gtest/include/gtest/internal/gtest-filepath.h new file mode 100644 index 00000000..7a13b4b0 --- /dev/null +++ b/lib/gtest/include/gtest/internal/gtest-filepath.h @@ -0,0 +1,206 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: keith.ray@gmail.com (Keith Ray) +// +// Google Test filepath utilities +// +// This header file declares classes and functions used internally by +// Google Test. They are subject to change without notice. +// +// This file is #included in . +// Do not include this header file separately! + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ + +#include "gtest/internal/gtest-string.h" + +namespace testing { +namespace internal { + +// FilePath - a class for file and directory pathname manipulation which +// handles platform-specific conventions (like the pathname separator). +// Used for helper functions for naming files in a directory for xml output. +// Except for Set methods, all methods are const or static, which provides an +// "immutable value object" -- useful for peace of mind. +// A FilePath with a value ending in a path separator ("like/this/") represents +// a directory, otherwise it is assumed to represent a file. In either case, +// it may or may not represent an actual file or directory in the file system. +// Names are NOT checked for syntax correctness -- no checking for illegal +// characters, malformed paths, etc. + +class GTEST_API_ FilePath { + public: + FilePath() : pathname_("") { } + FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } + + explicit FilePath(const std::string& pathname) : pathname_(pathname) { + Normalize(); + } + + FilePath& operator=(const FilePath& rhs) { + Set(rhs); + return *this; + } + + void Set(const FilePath& rhs) { + pathname_ = rhs.pathname_; + } + + const std::string& string() const { return pathname_; } + const char* c_str() const { return pathname_.c_str(); } + + // Returns the current working directory, or "" if unsuccessful. + static FilePath GetCurrentDir(); + + // Given directory = "dir", base_name = "test", number = 0, + // extension = "xml", returns "dir/test.xml". If number is greater + // than zero (e.g., 12), returns "dir/test_12.xml". + // On Windows platform, uses \ as the separator rather than /. + static FilePath MakeFileName(const FilePath& directory, + const FilePath& base_name, + int number, + const char* extension); + + // Given directory = "dir", relative_path = "test.xml", + // returns "dir/test.xml". + // On Windows, uses \ as the separator rather than /. + static FilePath ConcatPaths(const FilePath& directory, + const FilePath& relative_path); + + // Returns a pathname for a file that does not currently exist. The pathname + // will be directory/base_name.extension or + // directory/base_name_.extension if directory/base_name.extension + // already exists. The number will be incremented until a pathname is found + // that does not already exist. + // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. + // There could be a race condition if two or more processes are calling this + // function at the same time -- they could both pick the same filename. + static FilePath GenerateUniqueFileName(const FilePath& directory, + const FilePath& base_name, + const char* extension); + + // Returns true iff the path is "". + bool IsEmpty() const { return pathname_.empty(); } + + // If input name has a trailing separator character, removes it and returns + // the name, otherwise return the name string unmodified. + // On Windows platform, uses \ as the separator, other platforms use /. + FilePath RemoveTrailingPathSeparator() const; + + // Returns a copy of the FilePath with the directory part removed. + // Example: FilePath("path/to/file").RemoveDirectoryName() returns + // FilePath("file"). If there is no directory part ("just_a_file"), it returns + // the FilePath unmodified. If there is no file part ("just_a_dir/") it + // returns an empty FilePath (""). + // On Windows platform, '\' is the path separator, otherwise it is '/'. + FilePath RemoveDirectoryName() const; + + // RemoveFileName returns the directory path with the filename removed. + // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". + // If the FilePath is "a_file" or "/a_file", RemoveFileName returns + // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does + // not have a file, like "just/a/dir/", it returns the FilePath unmodified. + // On Windows platform, '\' is the path separator, otherwise it is '/'. + FilePath RemoveFileName() const; + + // Returns a copy of the FilePath with the case-insensitive extension removed. + // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns + // FilePath("dir/file"). If a case-insensitive extension is not + // found, returns a copy of the original FilePath. + FilePath RemoveExtension(const char* extension) const; + + // Creates directories so that path exists. Returns true if successful or if + // the directories already exist; returns false if unable to create + // directories for any reason. Will also return false if the FilePath does + // not represent a directory (that is, it doesn't end with a path separator). + bool CreateDirectoriesRecursively() const; + + // Create the directory so that path exists. Returns true if successful or + // if the directory already exists; returns false if unable to create the + // directory for any reason, including if the parent directory does not + // exist. Not named "CreateDirectory" because that's a macro on Windows. + bool CreateFolder() const; + + // Returns true if FilePath describes something in the file-system, + // either a file, directory, or whatever, and that something exists. + bool FileOrDirectoryExists() const; + + // Returns true if pathname describes a directory in the file-system + // that exists. + bool DirectoryExists() const; + + // Returns true if FilePath ends with a path separator, which indicates that + // it is intended to represent a directory. Returns false otherwise. + // This does NOT check that a directory (or file) actually exists. + bool IsDirectory() const; + + // Returns true if pathname describes a root directory. (Windows has one + // root directory per disk drive.) + bool IsRootDirectory() const; + + // Returns true if pathname describes an absolute path. + bool IsAbsolutePath() const; + + private: + // Replaces multiple consecutive separators with a single separator. + // For example, "bar///foo" becomes "bar/foo". Does not eliminate other + // redundancies that might be in a pathname involving "." or "..". + // + // A pathname with multiple consecutive separators may occur either through + // user error or as a result of some scripts or APIs that generate a pathname + // with a trailing separator. On other platforms the same API or script + // may NOT generate a pathname with a trailing "/". Then elsewhere that + // pathname may have another "/" and pathname components added to it, + // without checking for the separator already being there. + // The script language and operating system may allow paths like "foo//bar" + // but some of the functions in FilePath will not handle that correctly. In + // particular, RemoveTrailingPathSeparator() only removes one separator, and + // it is called in CreateDirectoriesRecursively() assuming that it will change + // a pathname from directory syntax (trailing separator) to filename syntax. + // + // On Windows this method also replaces the alternate path separator '/' with + // the primary path separator '\\', so that for example "bar\\/\\foo" becomes + // "bar\\foo". + + void Normalize(); + + // Returns a pointer to the last occurence of a valid path separator in + // the FilePath. On Windows, for example, both '/' and '\' are valid path + // separators. Returns NULL if no path separator was found. + const char* FindLastPathSeparator() const; + + std::string pathname_; +}; // class FilePath + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ diff --git a/lib/gtest/include/gtest/internal/gtest-internal.h b/lib/gtest/include/gtest/internal/gtest-internal.h new file mode 100644 index 00000000..0dcc3a31 --- /dev/null +++ b/lib/gtest/include/gtest/internal/gtest-internal.h @@ -0,0 +1,1158 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file declares functions and macros used internally by +// Google Test. They are subject to change without notice. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ + +#include "gtest/internal/gtest-port.h" + +#if GTEST_OS_LINUX +# include +# include +# include +# include +#endif // GTEST_OS_LINUX + +#if GTEST_HAS_EXCEPTIONS +# include +#endif + +#include +#include +#include +#include +#include +#include + +#include "gtest/gtest-message.h" +#include "gtest/internal/gtest-string.h" +#include "gtest/internal/gtest-filepath.h" +#include "gtest/internal/gtest-type-util.h" + +// Due to C++ preprocessor weirdness, we need double indirection to +// concatenate two tokens when one of them is __LINE__. Writing +// +// foo ## __LINE__ +// +// will result in the token foo__LINE__, instead of foo followed by +// the current line number. For more details, see +// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 +#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) +#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar + +class ProtocolMessage; +namespace proto2 { class Message; } + +namespace testing { + +// Forward declarations. + +class AssertionResult; // Result of an assertion. +class Message; // Represents a failure message. +class Test; // Represents a test. +class TestInfo; // Information about a test. +class TestPartResult; // Result of a test part. +class UnitTest; // A collection of test cases. + +template +::std::string PrintToString(const T& value); + +namespace internal { + +struct TraceInfo; // Information about a trace point. +class ScopedTrace; // Implements scoped trace. +class TestInfoImpl; // Opaque implementation of TestInfo +class UnitTestImpl; // Opaque implementation of UnitTest + +// How many times InitGoogleTest() has been called. +GTEST_API_ extern int g_init_gtest_count; + +// The text used in failure messages to indicate the start of the +// stack trace. +GTEST_API_ extern const char kStackTraceMarker[]; + +// Two overloaded helpers for checking at compile time whether an +// expression is a null pointer literal (i.e. NULL or any 0-valued +// compile-time integral constant). Their return values have +// different sizes, so we can use sizeof() to test which version is +// picked by the compiler. These helpers have no implementations, as +// we only need their signatures. +// +// Given IsNullLiteralHelper(x), the compiler will pick the first +// version if x can be implicitly converted to Secret*, and pick the +// second version otherwise. Since Secret is a secret and incomplete +// type, the only expression a user can write that has type Secret* is +// a null pointer literal. Therefore, we know that x is a null +// pointer literal if and only if the first version is picked by the +// compiler. +char IsNullLiteralHelper(Secret* p); +char (&IsNullLiteralHelper(...))[2]; // NOLINT + +// A compile-time bool constant that is true if and only if x is a +// null pointer literal (i.e. NULL or any 0-valued compile-time +// integral constant). +#ifdef GTEST_ELLIPSIS_NEEDS_POD_ +// We lose support for NULL detection where the compiler doesn't like +// passing non-POD classes through ellipsis (...). +# define GTEST_IS_NULL_LITERAL_(x) false +#else +# define GTEST_IS_NULL_LITERAL_(x) \ + (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1) +#endif // GTEST_ELLIPSIS_NEEDS_POD_ + +// Appends the user-supplied message to the Google-Test-generated message. +GTEST_API_ std::string AppendUserMessage( + const std::string& gtest_msg, const Message& user_msg); + +#if GTEST_HAS_EXCEPTIONS + +// This exception is thrown by (and only by) a failed Google Test +// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions +// are enabled). We derive it from std::runtime_error, which is for +// errors presumably detectable only at run time. Since +// std::runtime_error inherits from std::exception, many testing +// frameworks know how to extract and print the message inside it. +class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error { + public: + explicit GoogleTestFailureException(const TestPartResult& failure); +}; + +#endif // GTEST_HAS_EXCEPTIONS + +// A helper class for creating scoped traces in user programs. +class GTEST_API_ ScopedTrace { + public: + // The c'tor pushes the given source file location and message onto + // a trace stack maintained by Google Test. + ScopedTrace(const char* file, int line, const Message& message); + + // The d'tor pops the info pushed by the c'tor. + // + // Note that the d'tor is not virtual in order to be efficient. + // Don't inherit from ScopedTrace! + ~ScopedTrace(); + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace); +} GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its + // c'tor and d'tor. Therefore it doesn't + // need to be used otherwise. + +// Constructs and returns the message for an equality assertion +// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. +// +// The first four parameters are the expressions used in the assertion +// and their values, as strings. For example, for ASSERT_EQ(foo, bar) +// where foo is 5 and bar is 6, we have: +// +// expected_expression: "foo" +// actual_expression: "bar" +// expected_value: "5" +// actual_value: "6" +// +// The ignoring_case parameter is true iff the assertion is a +// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will +// be inserted into the message. +GTEST_API_ AssertionResult EqFailure(const char* expected_expression, + const char* actual_expression, + const std::string& expected_value, + const std::string& actual_value, + bool ignoring_case); + +// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. +GTEST_API_ std::string GetBoolAssertionFailureMessage( + const AssertionResult& assertion_result, + const char* expression_text, + const char* actual_predicate_value, + const char* expected_predicate_value); + +// This template class represents an IEEE floating-point number +// (either single-precision or double-precision, depending on the +// template parameters). +// +// The purpose of this class is to do more sophisticated number +// comparison. (Due to round-off error, etc, it's very unlikely that +// two floating-points will be equal exactly. Hence a naive +// comparison by the == operation often doesn't work.) +// +// Format of IEEE floating-point: +// +// The most-significant bit being the leftmost, an IEEE +// floating-point looks like +// +// sign_bit exponent_bits fraction_bits +// +// Here, sign_bit is a single bit that designates the sign of the +// number. +// +// For float, there are 8 exponent bits and 23 fraction bits. +// +// For double, there are 11 exponent bits and 52 fraction bits. +// +// More details can be found at +// http://en.wikipedia.org/wiki/IEEE_floating-point_standard. +// +// Template parameter: +// +// RawType: the raw floating-point type (either float or double) +template +class FloatingPoint { + public: + // Defines the unsigned integer type that has the same size as the + // floating point number. + typedef typename TypeWithSize::UInt Bits; + + // Constants. + + // # of bits in a number. + static const size_t kBitCount = 8*sizeof(RawType); + + // # of fraction bits in a number. + static const size_t kFractionBitCount = + std::numeric_limits::digits - 1; + + // # of exponent bits in a number. + static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; + + // The mask for the sign bit. + static const Bits kSignBitMask = static_cast(1) << (kBitCount - 1); + + // The mask for the fraction bits. + static const Bits kFractionBitMask = + ~static_cast(0) >> (kExponentBitCount + 1); + + // The mask for the exponent bits. + static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); + + // How many ULP's (Units in the Last Place) we want to tolerate when + // comparing two numbers. The larger the value, the more error we + // allow. A 0 value means that two numbers must be exactly the same + // to be considered equal. + // + // The maximum error of a single floating-point operation is 0.5 + // units in the last place. On Intel CPU's, all floating-point + // calculations are done with 80-bit precision, while double has 64 + // bits. Therefore, 4 should be enough for ordinary use. + // + // See the following article for more details on ULP: + // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ + static const size_t kMaxUlps = 4; + + // Constructs a FloatingPoint from a raw floating-point number. + // + // On an Intel CPU, passing a non-normalized NAN (Not a Number) + // around may change its bits, although the new value is guaranteed + // to be also a NAN. Therefore, don't expect this constructor to + // preserve the bits in x when x is a NAN. + explicit FloatingPoint(const RawType& x) { u_.value_ = x; } + + // Static methods + + // Reinterprets a bit pattern as a floating-point number. + // + // This function is needed to test the AlmostEquals() method. + static RawType ReinterpretBits(const Bits bits) { + FloatingPoint fp(0); + fp.u_.bits_ = bits; + return fp.u_.value_; + } + + // Returns the floating-point number that represent positive infinity. + static RawType Infinity() { + return ReinterpretBits(kExponentBitMask); + } + + // Returns the maximum representable finite floating-point number. + static RawType Max(); + + // Non-static methods + + // Returns the bits that represents this number. + const Bits &bits() const { return u_.bits_; } + + // Returns the exponent bits of this number. + Bits exponent_bits() const { return kExponentBitMask & u_.bits_; } + + // Returns the fraction bits of this number. + Bits fraction_bits() const { return kFractionBitMask & u_.bits_; } + + // Returns the sign bit of this number. + Bits sign_bit() const { return kSignBitMask & u_.bits_; } + + // Returns true iff this is NAN (not a number). + bool is_nan() const { + // It's a NAN if the exponent bits are all ones and the fraction + // bits are not entirely zeros. + return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0); + } + + // Returns true iff this number is at most kMaxUlps ULP's away from + // rhs. In particular, this function: + // + // - returns false if either number is (or both are) NAN. + // - treats really large numbers as almost equal to infinity. + // - thinks +0.0 and -0.0 are 0 DLP's apart. + bool AlmostEquals(const FloatingPoint& rhs) const { + // The IEEE standard says that any comparison operation involving + // a NAN must return false. + if (is_nan() || rhs.is_nan()) return false; + + return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) + <= kMaxUlps; + } + + private: + // The data type used to store the actual floating-point number. + union FloatingPointUnion { + RawType value_; // The raw floating-point number. + Bits bits_; // The bits that represent the number. + }; + + // Converts an integer from the sign-and-magnitude representation to + // the biased representation. More precisely, let N be 2 to the + // power of (kBitCount - 1), an integer x is represented by the + // unsigned number x + N. + // + // For instance, + // + // -N + 1 (the most negative number representable using + // sign-and-magnitude) is represented by 1; + // 0 is represented by N; and + // N - 1 (the biggest number representable using + // sign-and-magnitude) is represented by 2N - 1. + // + // Read http://en.wikipedia.org/wiki/Signed_number_representations + // for more details on signed number representations. + static Bits SignAndMagnitudeToBiased(const Bits &sam) { + if (kSignBitMask & sam) { + // sam represents a negative number. + return ~sam + 1; + } else { + // sam represents a positive number. + return kSignBitMask | sam; + } + } + + // Given two numbers in the sign-and-magnitude representation, + // returns the distance between them as an unsigned number. + static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, + const Bits &sam2) { + const Bits biased1 = SignAndMagnitudeToBiased(sam1); + const Bits biased2 = SignAndMagnitudeToBiased(sam2); + return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); + } + + FloatingPointUnion u_; +}; + +// We cannot use std::numeric_limits::max() as it clashes with the max() +// macro defined by . +template <> +inline float FloatingPoint::Max() { return FLT_MAX; } +template <> +inline double FloatingPoint::Max() { return DBL_MAX; } + +// Typedefs the instances of the FloatingPoint template class that we +// care to use. +typedef FloatingPoint Float; +typedef FloatingPoint Double; + +// In order to catch the mistake of putting tests that use different +// test fixture classes in the same test case, we need to assign +// unique IDs to fixture classes and compare them. The TypeId type is +// used to hold such IDs. The user should treat TypeId as an opaque +// type: the only operation allowed on TypeId values is to compare +// them for equality using the == operator. +typedef const void* TypeId; + +template +class TypeIdHelper { + public: + // dummy_ must not have a const type. Otherwise an overly eager + // compiler (e.g. MSVC 7.1 & 8.0) may try to merge + // TypeIdHelper::dummy_ for different Ts as an "optimization". + static bool dummy_; +}; + +template +bool TypeIdHelper::dummy_ = false; + +// GetTypeId() returns the ID of type T. Different values will be +// returned for different types. Calling the function twice with the +// same type argument is guaranteed to return the same ID. +template +TypeId GetTypeId() { + // The compiler is required to allocate a different + // TypeIdHelper::dummy_ variable for each T used to instantiate + // the template. Therefore, the address of dummy_ is guaranteed to + // be unique. + return &(TypeIdHelper::dummy_); +} + +// Returns the type ID of ::testing::Test. Always call this instead +// of GetTypeId< ::testing::Test>() to get the type ID of +// ::testing::Test, as the latter may give the wrong result due to a +// suspected linker bug when compiling Google Test as a Mac OS X +// framework. +GTEST_API_ TypeId GetTestTypeId(); + +// Defines the abstract factory interface that creates instances +// of a Test object. +class TestFactoryBase { + public: + virtual ~TestFactoryBase() {} + + // Creates a test instance to run. The instance is both created and destroyed + // within TestInfoImpl::Run() + virtual Test* CreateTest() = 0; + + protected: + TestFactoryBase() {} + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase); +}; + +// This class provides implementation of TeastFactoryBase interface. +// It is used in TEST and TEST_F macros. +template +class TestFactoryImpl : public TestFactoryBase { + public: + virtual Test* CreateTest() { return new TestClass; } +}; + +#if GTEST_OS_WINDOWS + +// Predicate-formatters for implementing the HRESULT checking macros +// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED} +// We pass a long instead of HRESULT to avoid causing an +// include dependency for the HRESULT type. +GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr, + long hr); // NOLINT +GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr, + long hr); // NOLINT + +#endif // GTEST_OS_WINDOWS + +// Types of SetUpTestCase() and TearDownTestCase() functions. +typedef void (*SetUpTestCaseFunc)(); +typedef void (*TearDownTestCaseFunc)(); + +// Creates a new TestInfo object and registers it with Google Test; +// returns the created object. +// +// Arguments: +// +// test_case_name: name of the test case +// name: name of the test +// type_param the name of the test's type parameter, or NULL if +// this is not a typed or a type-parameterized test. +// value_param text representation of the test's value parameter, +// or NULL if this is not a type-parameterized test. +// fixture_class_id: ID of the test fixture class +// set_up_tc: pointer to the function that sets up the test case +// tear_down_tc: pointer to the function that tears down the test case +// factory: pointer to the factory that creates a test object. +// The newly created TestInfo instance will assume +// ownership of the factory object. +GTEST_API_ TestInfo* MakeAndRegisterTestInfo( + const char* test_case_name, + const char* name, + const char* type_param, + const char* value_param, + TypeId fixture_class_id, + SetUpTestCaseFunc set_up_tc, + TearDownTestCaseFunc tear_down_tc, + TestFactoryBase* factory); + +// If *pstr starts with the given prefix, modifies *pstr to be right +// past the prefix and returns true; otherwise leaves *pstr unchanged +// and returns false. None of pstr, *pstr, and prefix can be NULL. +GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr); + +#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +// State of the definition of a type-parameterized test case. +class GTEST_API_ TypedTestCasePState { + public: + TypedTestCasePState() : registered_(false) {} + + // Adds the given test name to defined_test_names_ and return true + // if the test case hasn't been registered; otherwise aborts the + // program. + bool AddTestName(const char* file, int line, const char* case_name, + const char* test_name) { + if (registered_) { + fprintf(stderr, "%s Test %s must be defined before " + "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n", + FormatFileLocation(file, line).c_str(), test_name, case_name); + fflush(stderr); + posix::Abort(); + } + defined_test_names_.insert(test_name); + return true; + } + + // Verifies that registered_tests match the test names in + // defined_test_names_; returns registered_tests if successful, or + // aborts the program otherwise. + const char* VerifyRegisteredTestNames( + const char* file, int line, const char* registered_tests); + + private: + bool registered_; + ::std::set defined_test_names_; +}; + +// Skips to the first non-space char after the first comma in 'str'; +// returns NULL if no comma is found in 'str'. +inline const char* SkipComma(const char* str) { + const char* comma = strchr(str, ','); + if (comma == NULL) { + return NULL; + } + while (IsSpace(*(++comma))) {} + return comma; +} + +// Returns the prefix of 'str' before the first comma in it; returns +// the entire string if it contains no comma. +inline std::string GetPrefixUntilComma(const char* str) { + const char* comma = strchr(str, ','); + return comma == NULL ? str : std::string(str, comma); +} + +// TypeParameterizedTest::Register() +// registers a list of type-parameterized tests with Google Test. The +// return value is insignificant - we just need to return something +// such that we can call this function in a namespace scope. +// +// Implementation note: The GTEST_TEMPLATE_ macro declares a template +// template parameter. It's defined in gtest-type-util.h. +template +class TypeParameterizedTest { + public: + // 'index' is the index of the test in the type list 'Types' + // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase, + // Types). Valid values for 'index' are [0, N - 1] where N is the + // length of Types. + static bool Register(const char* prefix, const char* case_name, + const char* test_names, int index) { + typedef typename Types::Head Type; + typedef Fixture FixtureClass; + typedef typename GTEST_BIND_(TestSel, Type) TestClass; + + // First, registers the first type-parameterized test in the type + // list. + MakeAndRegisterTestInfo( + (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name + "/" + + StreamableToString(index)).c_str(), + GetPrefixUntilComma(test_names).c_str(), + GetTypeName().c_str(), + NULL, // No value parameter. + GetTypeId(), + TestClass::SetUpTestCase, + TestClass::TearDownTestCase, + new TestFactoryImpl); + + // Next, recurses (at compile time) with the tail of the type list. + return TypeParameterizedTest + ::Register(prefix, case_name, test_names, index + 1); + } +}; + +// The base case for the compile time recursion. +template +class TypeParameterizedTest { + public: + static bool Register(const char* /*prefix*/, const char* /*case_name*/, + const char* /*test_names*/, int /*index*/) { + return true; + } +}; + +// TypeParameterizedTestCase::Register() +// registers *all combinations* of 'Tests' and 'Types' with Google +// Test. The return value is insignificant - we just need to return +// something such that we can call this function in a namespace scope. +template +class TypeParameterizedTestCase { + public: + static bool Register(const char* prefix, const char* case_name, + const char* test_names) { + typedef typename Tests::Head Head; + + // First, register the first test in 'Test' for each type in 'Types'. + TypeParameterizedTest::Register( + prefix, case_name, test_names, 0); + + // Next, recurses (at compile time) with the tail of the test list. + return TypeParameterizedTestCase + ::Register(prefix, case_name, SkipComma(test_names)); + } +}; + +// The base case for the compile time recursion. +template +class TypeParameterizedTestCase { + public: + static bool Register(const char* /*prefix*/, const char* /*case_name*/, + const char* /*test_names*/) { + return true; + } +}; + +#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +// Returns the current OS stack trace as an std::string. +// +// The maximum number of stack frames to be included is specified by +// the gtest_stack_trace_depth flag. The skip_count parameter +// specifies the number of top frames to be skipped, which doesn't +// count against the number of frames to be included. +// +// For example, if Foo() calls Bar(), which in turn calls +// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in +// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. +GTEST_API_ std::string GetCurrentOsStackTraceExceptTop( + UnitTest* unit_test, int skip_count); + +// Helpers for suppressing warnings on unreachable code or constant +// condition. + +// Always returns true. +GTEST_API_ bool AlwaysTrue(); + +// Always returns false. +inline bool AlwaysFalse() { return !AlwaysTrue(); } + +// Helper for suppressing false warning from Clang on a const char* +// variable declared in a conditional expression always being NULL in +// the else branch. +struct GTEST_API_ ConstCharPtr { + ConstCharPtr(const char* str) : value(str) {} + operator bool() const { return true; } + const char* value; +}; + +// A simple Linear Congruential Generator for generating random +// numbers with a uniform distribution. Unlike rand() and srand(), it +// doesn't use global state (and therefore can't interfere with user +// code). Unlike rand_r(), it's portable. An LCG isn't very random, +// but it's good enough for our purposes. +class GTEST_API_ Random { + public: + static const UInt32 kMaxRange = 1u << 31; + + explicit Random(UInt32 seed) : state_(seed) {} + + void Reseed(UInt32 seed) { state_ = seed; } + + // Generates a random number from [0, range). Crashes if 'range' is + // 0 or greater than kMaxRange. + UInt32 Generate(UInt32 range); + + private: + UInt32 state_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); +}; + +// Defining a variable of type CompileAssertTypesEqual will cause a +// compiler error iff T1 and T2 are different types. +template +struct CompileAssertTypesEqual; + +template +struct CompileAssertTypesEqual { +}; + +// Removes the reference from a type if it is a reference type, +// otherwise leaves it unchanged. This is the same as +// tr1::remove_reference, which is not widely available yet. +template +struct RemoveReference { typedef T type; }; // NOLINT +template +struct RemoveReference { typedef T type; }; // NOLINT + +// A handy wrapper around RemoveReference that works when the argument +// T depends on template parameters. +#define GTEST_REMOVE_REFERENCE_(T) \ + typename ::testing::internal::RemoveReference::type + +// Removes const from a type if it is a const type, otherwise leaves +// it unchanged. This is the same as tr1::remove_const, which is not +// widely available yet. +template +struct RemoveConst { typedef T type; }; // NOLINT +template +struct RemoveConst { typedef T type; }; // NOLINT + +// MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above +// definition to fail to remove the const in 'const int[3]' and 'const +// char[3][4]'. The following specialization works around the bug. +template +struct RemoveConst { + typedef typename RemoveConst::type type[N]; +}; + +#if defined(_MSC_VER) && _MSC_VER < 1400 +// This is the only specialization that allows VC++ 7.1 to remove const in +// 'const int[3] and 'const int[3][4]'. However, it causes trouble with GCC +// and thus needs to be conditionally compiled. +template +struct RemoveConst { + typedef typename RemoveConst::type type[N]; +}; +#endif + +// A handy wrapper around RemoveConst that works when the argument +// T depends on template parameters. +#define GTEST_REMOVE_CONST_(T) \ + typename ::testing::internal::RemoveConst::type + +// Turns const U&, U&, const U, and U all into U. +#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \ + GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T)) + +// Adds reference to a type if it is not a reference type, +// otherwise leaves it unchanged. This is the same as +// tr1::add_reference, which is not widely available yet. +template +struct AddReference { typedef T& type; }; // NOLINT +template +struct AddReference { typedef T& type; }; // NOLINT + +// A handy wrapper around AddReference that works when the argument T +// depends on template parameters. +#define GTEST_ADD_REFERENCE_(T) \ + typename ::testing::internal::AddReference::type + +// Adds a reference to const on top of T as necessary. For example, +// it transforms +// +// char ==> const char& +// const char ==> const char& +// char& ==> const char& +// const char& ==> const char& +// +// The argument T must depend on some template parameters. +#define GTEST_REFERENCE_TO_CONST_(T) \ + GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T)) + +// ImplicitlyConvertible::value is a compile-time bool +// constant that's true iff type From can be implicitly converted to +// type To. +template +class ImplicitlyConvertible { + private: + // We need the following helper functions only for their types. + // They have no implementations. + + // MakeFrom() is an expression whose type is From. We cannot simply + // use From(), as the type From may not have a public default + // constructor. + static From MakeFrom(); + + // These two functions are overloaded. Given an expression + // Helper(x), the compiler will pick the first version if x can be + // implicitly converted to type To; otherwise it will pick the + // second version. + // + // The first version returns a value of size 1, and the second + // version returns a value of size 2. Therefore, by checking the + // size of Helper(x), which can be done at compile time, we can tell + // which version of Helper() is used, and hence whether x can be + // implicitly converted to type To. + static char Helper(To); + static char (&Helper(...))[2]; // NOLINT + + // We have to put the 'public' section after the 'private' section, + // or MSVC refuses to compile the code. + public: + // MSVC warns about implicitly converting from double to int for + // possible loss of data, so we need to temporarily disable the + // warning. +#ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4244) // Temporarily disables warning 4244. + + static const bool value = + sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; +# pragma warning(pop) // Restores the warning state. +#elif defined(__BORLANDC__) + // C++Builder cannot use member overload resolution during template + // instantiation. The simplest workaround is to use its C++0x type traits + // functions (C++Builder 2009 and above only). + static const bool value = __is_convertible(From, To); +#else + static const bool value = + sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; +#endif // _MSV_VER +}; +template +const bool ImplicitlyConvertible::value; + +// IsAProtocolMessage::value is a compile-time bool constant that's +// true iff T is type ProtocolMessage, proto2::Message, or a subclass +// of those. +template +struct IsAProtocolMessage + : public bool_constant< + ImplicitlyConvertible::value || + ImplicitlyConvertible::value> { +}; + +// When the compiler sees expression IsContainerTest(0), if C is an +// STL-style container class, the first overload of IsContainerTest +// will be viable (since both C::iterator* and C::const_iterator* are +// valid types and NULL can be implicitly converted to them). It will +// be picked over the second overload as 'int' is a perfect match for +// the type of argument 0. If C::iterator or C::const_iterator is not +// a valid type, the first overload is not viable, and the second +// overload will be picked. Therefore, we can determine whether C is +// a container class by checking the type of IsContainerTest(0). +// The value of the expression is insignificant. +// +// Note that we look for both C::iterator and C::const_iterator. The +// reason is that C++ injects the name of a class as a member of the +// class itself (e.g. you can refer to class iterator as either +// 'iterator' or 'iterator::iterator'). If we look for C::iterator +// only, for example, we would mistakenly think that a class named +// iterator is an STL container. +// +// Also note that the simpler approach of overloading +// IsContainerTest(typename C::const_iterator*) and +// IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++. +typedef int IsContainer; +template +IsContainer IsContainerTest(int /* dummy */, + typename C::iterator* /* it */ = NULL, + typename C::const_iterator* /* const_it */ = NULL) { + return 0; +} + +typedef char IsNotContainer; +template +IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; } + +// EnableIf::type is void when 'Cond' is true, and +// undefined when 'Cond' is false. To use SFINAE to make a function +// overload only apply when a particular expression is true, add +// "typename EnableIf::type* = 0" as the last parameter. +template struct EnableIf; +template<> struct EnableIf { typedef void type; }; // NOLINT + +// Utilities for native arrays. + +// ArrayEq() compares two k-dimensional native arrays using the +// elements' operator==, where k can be any integer >= 0. When k is +// 0, ArrayEq() degenerates into comparing a single pair of values. + +template +bool ArrayEq(const T* lhs, size_t size, const U* rhs); + +// This generic version is used when k is 0. +template +inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; } + +// This overload is used when k >= 1. +template +inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { + return internal::ArrayEq(lhs, N, rhs); +} + +// This helper reduces code bloat. If we instead put its logic inside +// the previous ArrayEq() function, arrays with different sizes would +// lead to different copies of the template code. +template +bool ArrayEq(const T* lhs, size_t size, const U* rhs) { + for (size_t i = 0; i != size; i++) { + if (!internal::ArrayEq(lhs[i], rhs[i])) + return false; + } + return true; +} + +// Finds the first element in the iterator range [begin, end) that +// equals elem. Element may be a native array type itself. +template +Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { + for (Iter it = begin; it != end; ++it) { + if (internal::ArrayEq(*it, elem)) + return it; + } + return end; +} + +// CopyArray() copies a k-dimensional native array using the elements' +// operator=, where k can be any integer >= 0. When k is 0, +// CopyArray() degenerates into copying a single value. + +template +void CopyArray(const T* from, size_t size, U* to); + +// This generic version is used when k is 0. +template +inline void CopyArray(const T& from, U* to) { *to = from; } + +// This overload is used when k >= 1. +template +inline void CopyArray(const T(&from)[N], U(*to)[N]) { + internal::CopyArray(from, N, *to); +} + +// This helper reduces code bloat. If we instead put its logic inside +// the previous CopyArray() function, arrays with different sizes +// would lead to different copies of the template code. +template +void CopyArray(const T* from, size_t size, U* to) { + for (size_t i = 0; i != size; i++) { + internal::CopyArray(from[i], to + i); + } +} + +// The relation between an NativeArray object (see below) and the +// native array it represents. +enum RelationToSource { + kReference, // The NativeArray references the native array. + kCopy // The NativeArray makes a copy of the native array and + // owns the copy. +}; + +// Adapts a native array to a read-only STL-style container. Instead +// of the complete STL container concept, this adaptor only implements +// members useful for Google Mock's container matchers. New members +// should be added as needed. To simplify the implementation, we only +// support Element being a raw type (i.e. having no top-level const or +// reference modifier). It's the client's responsibility to satisfy +// this requirement. Element can be an array type itself (hence +// multi-dimensional arrays are supported). +template +class NativeArray { + public: + // STL-style container typedefs. + typedef Element value_type; + typedef Element* iterator; + typedef const Element* const_iterator; + + // Constructs from a native array. + NativeArray(const Element* array, size_t count, RelationToSource relation) { + Init(array, count, relation); + } + + // Copy constructor. + NativeArray(const NativeArray& rhs) { + Init(rhs.array_, rhs.size_, rhs.relation_to_source_); + } + + ~NativeArray() { + // Ensures that the user doesn't instantiate NativeArray with a + // const or reference type. + static_cast(StaticAssertTypeEqHelper()); + if (relation_to_source_ == kCopy) + delete[] array_; + } + + // STL-style container methods. + size_t size() const { return size_; } + const_iterator begin() const { return array_; } + const_iterator end() const { return array_ + size_; } + bool operator==(const NativeArray& rhs) const { + return size() == rhs.size() && + ArrayEq(begin(), size(), rhs.begin()); + } + + private: + // Initializes this object; makes a copy of the input array if + // 'relation' is kCopy. + void Init(const Element* array, size_t a_size, RelationToSource relation) { + if (relation == kReference) { + array_ = array; + } else { + Element* const copy = new Element[a_size]; + CopyArray(array, a_size, copy); + array_ = copy; + } + size_ = a_size; + relation_to_source_ = relation; + } + + const Element* array_; + size_t size_; + RelationToSource relation_to_source_; + + GTEST_DISALLOW_ASSIGN_(NativeArray); +}; + +} // namespace internal +} // namespace testing + +#define GTEST_MESSAGE_AT_(file, line, message, result_type) \ + ::testing::internal::AssertHelper(result_type, file, line, message) \ + = ::testing::Message() + +#define GTEST_MESSAGE_(message, result_type) \ + GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) + +#define GTEST_FATAL_FAILURE_(message) \ + return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure) + +#define GTEST_NONFATAL_FAILURE_(message) \ + GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure) + +#define GTEST_SUCCESS_(message) \ + GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess) + +// Suppresses MSVC warnings 4072 (unreachable code) for the code following +// statement if it returns or throws (or doesn't return or throw in some +// situations). +#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \ + if (::testing::internal::AlwaysTrue()) { statement; } + +#define GTEST_TEST_THROW_(statement, expected_exception, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::ConstCharPtr gtest_msg = "") { \ + bool gtest_caught_expected = false; \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } \ + catch (expected_exception const&) { \ + gtest_caught_expected = true; \ + } \ + catch (...) { \ + gtest_msg.value = \ + "Expected: " #statement " throws an exception of type " \ + #expected_exception ".\n Actual: it throws a different type."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ + } \ + if (!gtest_caught_expected) { \ + gtest_msg.value = \ + "Expected: " #statement " throws an exception of type " \ + #expected_exception ".\n Actual: it throws nothing."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ + fail(gtest_msg.value) + +#define GTEST_TEST_NO_THROW_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } \ + catch (...) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ + fail("Expected: " #statement " doesn't throw an exception.\n" \ + " Actual: it throws.") + +#define GTEST_TEST_ANY_THROW_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + bool gtest_caught_any = false; \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } \ + catch (...) { \ + gtest_caught_any = true; \ + } \ + if (!gtest_caught_any) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ + fail("Expected: " #statement " throws an exception.\n" \ + " Actual: it doesn't.") + + +// Implements Boolean test assertions such as EXPECT_TRUE. expression can be +// either a boolean expression or an AssertionResult. text is a textual +// represenation of expression as it was passed into the EXPECT_TRUE. +#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (const ::testing::AssertionResult gtest_ar_ = \ + ::testing::AssertionResult(expression)) \ + ; \ + else \ + fail(::testing::internal::GetBoolAssertionFailureMessage(\ + gtest_ar_, text, #actual, #expected).c_str()) + +#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ + fail("Expected: " #statement " doesn't generate new fatal " \ + "failures in the current thread.\n" \ + " Actual: it does.") + +// Expands to the name of the class that implements the given test. +#define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ + test_case_name##_##test_name##_Test + +// Helper macro for defining tests. +#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\ +class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\ + public:\ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\ + private:\ + virtual void TestBody();\ + static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\ + GTEST_DISALLOW_COPY_AND_ASSIGN_(\ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\ +};\ +\ +::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\ + ::test_info_ =\ + ::testing::internal::MakeAndRegisterTestInfo(\ + #test_case_name, #test_name, NULL, NULL, \ + (parent_id), \ + parent_class::SetUpTestCase, \ + parent_class::TearDownTestCase, \ + new ::testing::internal::TestFactoryImpl<\ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\ +void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ diff --git a/lib/gtest/include/gtest/internal/gtest-linked_ptr.h b/lib/gtest/include/gtest/internal/gtest-linked_ptr.h new file mode 100644 index 00000000..b1362cd0 --- /dev/null +++ b/lib/gtest/include/gtest/internal/gtest-linked_ptr.h @@ -0,0 +1,233 @@ +// Copyright 2003 Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: Dan Egnor (egnor@google.com) +// +// A "smart" pointer type with reference tracking. Every pointer to a +// particular object is kept on a circular linked list. When the last pointer +// to an object is destroyed or reassigned, the object is deleted. +// +// Used properly, this deletes the object when the last reference goes away. +// There are several caveats: +// - Like all reference counting schemes, cycles lead to leaks. +// - Each smart pointer is actually two pointers (8 bytes instead of 4). +// - Every time a pointer is assigned, the entire list of pointers to that +// object is traversed. This class is therefore NOT SUITABLE when there +// will often be more than two or three pointers to a particular object. +// - References are only tracked as long as linked_ptr<> objects are copied. +// If a linked_ptr<> is converted to a raw pointer and back, BAD THINGS +// will happen (double deletion). +// +// A good use of this class is storing object references in STL containers. +// You can safely put linked_ptr<> in a vector<>. +// Other uses may not be as good. +// +// Note: If you use an incomplete type with linked_ptr<>, the class +// *containing* linked_ptr<> must have a constructor and destructor (even +// if they do nothing!). +// +// Bill Gibbons suggested we use something like this. +// +// Thread Safety: +// Unlike other linked_ptr implementations, in this implementation +// a linked_ptr object is thread-safe in the sense that: +// - it's safe to copy linked_ptr objects concurrently, +// - it's safe to copy *from* a linked_ptr and read its underlying +// raw pointer (e.g. via get()) concurrently, and +// - it's safe to write to two linked_ptrs that point to the same +// shared object concurrently. +// TODO(wan@google.com): rename this to safe_linked_ptr to avoid +// confusion with normal linked_ptr. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ + +#include +#include + +#include "gtest/internal/gtest-port.h" + +namespace testing { +namespace internal { + +// Protects copying of all linked_ptr objects. +GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_linked_ptr_mutex); + +// This is used internally by all instances of linked_ptr<>. It needs to be +// a non-template class because different types of linked_ptr<> can refer to +// the same object (linked_ptr(obj) vs linked_ptr(obj)). +// So, it needs to be possible for different types of linked_ptr to participate +// in the same circular linked list, so we need a single class type here. +// +// DO NOT USE THIS CLASS DIRECTLY YOURSELF. Use linked_ptr. +class linked_ptr_internal { + public: + // Create a new circle that includes only this instance. + void join_new() { + next_ = this; + } + + // Many linked_ptr operations may change p.link_ for some linked_ptr + // variable p in the same circle as this object. Therefore we need + // to prevent two such operations from occurring concurrently. + // + // Note that different types of linked_ptr objects can coexist in a + // circle (e.g. linked_ptr, linked_ptr, and + // linked_ptr). Therefore we must use a single mutex to + // protect all linked_ptr objects. This can create serious + // contention in production code, but is acceptable in a testing + // framework. + + // Join an existing circle. + void join(linked_ptr_internal const* ptr) + GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { + MutexLock lock(&g_linked_ptr_mutex); + + linked_ptr_internal const* p = ptr; + while (p->next_ != ptr) p = p->next_; + p->next_ = this; + next_ = ptr; + } + + // Leave whatever circle we're part of. Returns true if we were the + // last member of the circle. Once this is done, you can join() another. + bool depart() + GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { + MutexLock lock(&g_linked_ptr_mutex); + + if (next_ == this) return true; + linked_ptr_internal const* p = next_; + while (p->next_ != this) p = p->next_; + p->next_ = next_; + return false; + } + + private: + mutable linked_ptr_internal const* next_; +}; + +template +class linked_ptr { + public: + typedef T element_type; + + // Take over ownership of a raw pointer. This should happen as soon as + // possible after the object is created. + explicit linked_ptr(T* ptr = NULL) { capture(ptr); } + ~linked_ptr() { depart(); } + + // Copy an existing linked_ptr<>, adding ourselves to the list of references. + template linked_ptr(linked_ptr const& ptr) { copy(&ptr); } + linked_ptr(linked_ptr const& ptr) { // NOLINT + assert(&ptr != this); + copy(&ptr); + } + + // Assignment releases the old value and acquires the new. + template linked_ptr& operator=(linked_ptr const& ptr) { + depart(); + copy(&ptr); + return *this; + } + + linked_ptr& operator=(linked_ptr const& ptr) { + if (&ptr != this) { + depart(); + copy(&ptr); + } + return *this; + } + + // Smart pointer members. + void reset(T* ptr = NULL) { + depart(); + capture(ptr); + } + T* get() const { return value_; } + T* operator->() const { return value_; } + T& operator*() const { return *value_; } + + bool operator==(T* p) const { return value_ == p; } + bool operator!=(T* p) const { return value_ != p; } + template + bool operator==(linked_ptr const& ptr) const { + return value_ == ptr.get(); + } + template + bool operator!=(linked_ptr const& ptr) const { + return value_ != ptr.get(); + } + + private: + template + friend class linked_ptr; + + T* value_; + linked_ptr_internal link_; + + void depart() { + if (link_.depart()) delete value_; + } + + void capture(T* ptr) { + value_ = ptr; + link_.join_new(); + } + + template void copy(linked_ptr const* ptr) { + value_ = ptr->get(); + if (value_) + link_.join(&ptr->link_); + else + link_.join_new(); + } +}; + +template inline +bool operator==(T* ptr, const linked_ptr& x) { + return ptr == x.get(); +} + +template inline +bool operator!=(T* ptr, const linked_ptr& x) { + return ptr != x.get(); +} + +// A function to convert T* into linked_ptr +// Doing e.g. make_linked_ptr(new FooBarBaz(arg)) is a shorter notation +// for linked_ptr >(new FooBarBaz(arg)) +template +linked_ptr make_linked_ptr(T* ptr) { + return linked_ptr(ptr); +} + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ diff --git a/lib/gtest/include/gtest/internal/gtest-param-util-generated.h b/lib/gtest/include/gtest/internal/gtest-param-util-generated.h new file mode 100644 index 00000000..e8054859 --- /dev/null +++ b/lib/gtest/include/gtest/internal/gtest-param-util-generated.h @@ -0,0 +1,5143 @@ +// This file was GENERATED by command: +// pump.py gtest-param-util-generated.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: vladl@google.com (Vlad Losev) + +// Type and function utilities for implementing parameterized tests. +// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +// Currently Google Test supports at most 50 arguments in Values, +// and at most 10 arguments in Combine. Please contact +// googletestframework@googlegroups.com if you need more. +// Please note that the number of arguments to Combine is limited +// by the maximum arity of the implementation of tr1::tuple which is +// currently set at 10. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ + +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. +#include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-port.h" + +#if GTEST_HAS_PARAM_TEST + +namespace testing { + +// Forward declarations of ValuesIn(), which is implemented in +// include/gtest/gtest-param-test.h. +template +internal::ParamGenerator< + typename ::testing::internal::IteratorTraits::value_type> +ValuesIn(ForwardIterator begin, ForwardIterator end); + +template +internal::ParamGenerator ValuesIn(const T (&array)[N]); + +template +internal::ParamGenerator ValuesIn( + const Container& container); + +namespace internal { + +// Used in the Values() function to provide polymorphic capabilities. +template +class ValueArray1 { + public: + explicit ValueArray1(T1 v1) : v1_(v1) {} + + template + operator ParamGenerator() const { return ValuesIn(&v1_, &v1_ + 1); } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray1& other); + + const T1 v1_; +}; + +template +class ValueArray2 { + public: + ValueArray2(T1 v1, T2 v2) : v1_(v1), v2_(v2) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray2& other); + + const T1 v1_; + const T2 v2_; +}; + +template +class ValueArray3 { + public: + ValueArray3(T1 v1, T2 v2, T3 v3) : v1_(v1), v2_(v2), v3_(v3) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray3& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; +}; + +template +class ValueArray4 { + public: + ValueArray4(T1 v1, T2 v2, T3 v3, T4 v4) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray4& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; +}; + +template +class ValueArray5 { + public: + ValueArray5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray5& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; +}; + +template +class ValueArray6 { + public: + ValueArray6(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray6& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; +}; + +template +class ValueArray7 { + public: + ValueArray7(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray7& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; +}; + +template +class ValueArray8 { + public: + ValueArray8(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray8& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; +}; + +template +class ValueArray9 { + public: + ValueArray9(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, + T9 v9) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray9& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; +}; + +template +class ValueArray10 { + public: + ValueArray10(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray10& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; +}; + +template +class ValueArray11 { + public: + ValueArray11(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray11& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; +}; + +template +class ValueArray12 { + public: + ValueArray12(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray12& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; +}; + +template +class ValueArray13 { + public: + ValueArray13(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray13& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; +}; + +template +class ValueArray14 { + public: + ValueArray14(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray14& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; +}; + +template +class ValueArray15 { + public: + ValueArray15(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray15& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; +}; + +template +class ValueArray16 { + public: + ValueArray16(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray16& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; +}; + +template +class ValueArray17 { + public: + ValueArray17(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, + T17 v17) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray17& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; +}; + +template +class ValueArray18 { + public: + ValueArray18(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray18& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; +}; + +template +class ValueArray19 { + public: + ValueArray19(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), + v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray19& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; +}; + +template +class ValueArray20 { + public: + ValueArray20(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), + v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), + v19_(v19), v20_(v20) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray20& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; +}; + +template +class ValueArray21 { + public: + ValueArray21(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), + v18_(v18), v19_(v19), v20_(v20), v21_(v21) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray21& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; +}; + +template +class ValueArray22 { + public: + ValueArray22(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray22& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; +}; + +template +class ValueArray23 { + public: + ValueArray23(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray23& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; +}; + +template +class ValueArray24 { + public: + ValueArray24(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), + v22_(v22), v23_(v23), v24_(v24) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray24& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; +}; + +template +class ValueArray25 { + public: + ValueArray25(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray25& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; +}; + +template +class ValueArray26 { + public: + ValueArray26(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray26& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; +}; + +template +class ValueArray27 { + public: + ValueArray27(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), + v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), + v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), + v26_(v26), v27_(v27) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray27& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; +}; + +template +class ValueArray28 { + public: + ValueArray28(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), + v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), + v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), + v25_(v25), v26_(v26), v27_(v27), v28_(v28) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray28& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; +}; + +template +class ValueArray29 { + public: + ValueArray29(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), + v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), + v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray29& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; +}; + +template +class ValueArray30 { + public: + ValueArray30(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray30& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; +}; + +template +class ValueArray31 { + public: + ValueArray31(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray31& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; +}; + +template +class ValueArray32 { + public: + ValueArray32(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), + v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), + v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray32& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; +}; + +template +class ValueArray33 { + public: + ValueArray33(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, + T33 v33) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray33& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; +}; + +template +class ValueArray34 { + public: + ValueArray34(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray34& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; +}; + +template +class ValueArray35 { + public: + ValueArray35(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), + v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), + v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), + v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), + v32_(v32), v33_(v33), v34_(v34), v35_(v35) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray35& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; +}; + +template +class ValueArray36 { + public: + ValueArray36(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), + v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), + v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), + v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), + v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray36& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; +}; + +template +class ValueArray37 { + public: + ValueArray37(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), + v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), + v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), + v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), + v36_(v36), v37_(v37) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray37& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; +}; + +template +class ValueArray38 { + public: + ValueArray38(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), + v35_(v35), v36_(v36), v37_(v37), v38_(v38) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray38& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; +}; + +template +class ValueArray39 { + public: + ValueArray39(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), + v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray39& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; +}; + +template +class ValueArray40 { + public: + ValueArray40(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), + v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), + v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), + v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), + v40_(v40) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray40& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; +}; + +template +class ValueArray41 { + public: + ValueArray41(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, + T41 v41) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), + v39_(v39), v40_(v40), v41_(v41) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray41& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; +}; + +template +class ValueArray42 { + public: + ValueArray42(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), + v39_(v39), v40_(v40), v41_(v41), v42_(v42) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray42& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; +}; + +template +class ValueArray43 { + public: + ValueArray43(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), + v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), + v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), + v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), + v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), + v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray43& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; +}; + +template +class ValueArray44 { + public: + ValueArray44(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), + v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), + v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), + v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), + v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), + v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), + v43_(v43), v44_(v44) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray44& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; +}; + +template +class ValueArray45 { + public: + ValueArray45(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), + v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), + v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), + v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), + v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), + v42_(v42), v43_(v43), v44_(v44), v45_(v45) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray45& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; +}; + +template +class ValueArray46 { + public: + ValueArray46(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), + v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), + v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray46& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; +}; + +template +class ValueArray47 { + public: + ValueArray47(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), + v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), + v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46), + v47_(v47) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_), static_cast(v47_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray47& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; + const T47 v47_; +}; + +template +class ValueArray48 { + public: + ValueArray48(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), + v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), + v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), + v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), + v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), + v46_(v46), v47_(v47), v48_(v48) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_), static_cast(v47_), + static_cast(v48_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray48& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; + const T47 v47_; + const T48 v48_; +}; + +template +class ValueArray49 { + public: + ValueArray49(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, + T49 v49) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), + v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), + v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_), static_cast(v47_), + static_cast(v48_), static_cast(v49_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray49& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; + const T47 v47_; + const T48 v48_; + const T49 v49_; +}; + +template +class ValueArray50 { + public: + ValueArray50(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49, + T50 v50) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), + v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), + v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49), v50_(v50) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_), static_cast(v47_), + static_cast(v48_), static_cast(v49_), static_cast(v50_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray50& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; + const T47 v47_; + const T48 v48_; + const T49 v49_; + const T50 v50_; +}; + +# if GTEST_HAS_COMBINE +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Generates values from the Cartesian product of values produced +// by the argument generators. +// +template +class CartesianProductGenerator2 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator2(const ParamGenerator& g1, + const ParamGenerator& g2) + : g1_(g1), g2_(g2) {} + virtual ~CartesianProductGenerator2() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current2_; + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + ParamType current_value_; + }; // class CartesianProductGenerator2::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator2& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; +}; // class CartesianProductGenerator2 + + +template +class CartesianProductGenerator3 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator3(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3) + : g1_(g1), g2_(g2), g3_(g3) {} + virtual ~CartesianProductGenerator3() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current3_; + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + ParamType current_value_; + }; // class CartesianProductGenerator3::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator3& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; +}; // class CartesianProductGenerator3 + + +template +class CartesianProductGenerator4 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator4(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} + virtual ~CartesianProductGenerator4() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current4_; + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + ParamType current_value_; + }; // class CartesianProductGenerator4::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator4& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; +}; // class CartesianProductGenerator4 + + +template +class CartesianProductGenerator5 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator5(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} + virtual ~CartesianProductGenerator5() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current5_; + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + ParamType current_value_; + }; // class CartesianProductGenerator5::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator5& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; +}; // class CartesianProductGenerator5 + + +template +class CartesianProductGenerator6 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator6(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} + virtual ~CartesianProductGenerator6() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current6_; + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + ParamType current_value_; + }; // class CartesianProductGenerator6::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator6& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; +}; // class CartesianProductGenerator6 + + +template +class CartesianProductGenerator7 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator7(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6, const ParamGenerator& g7) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} + virtual ~CartesianProductGenerator7() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, + g7_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, + const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6), + begin7_(g7.begin()), end7_(g7.end()), current7_(current7) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current7_; + if (current7_ == end7_) { + current7_ = begin7_; + ++current6_; + } + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_ && + current7_ == typed_other->current7_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_, *current7_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_ || + current7_ == end7_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + const typename ParamGenerator::iterator begin7_; + const typename ParamGenerator::iterator end7_; + typename ParamGenerator::iterator current7_; + ParamType current_value_; + }; // class CartesianProductGenerator7::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator7& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; + const ParamGenerator g7_; +}; // class CartesianProductGenerator7 + + +template +class CartesianProductGenerator8 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator8(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6, const ParamGenerator& g7, + const ParamGenerator& g8) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), + g8_(g8) {} + virtual ~CartesianProductGenerator8() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, + g7_.begin(), g8_, g8_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, + g8_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, + const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7, + const ParamGenerator& g8, + const typename ParamGenerator::iterator& current8) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6), + begin7_(g7.begin()), end7_(g7.end()), current7_(current7), + begin8_(g8.begin()), end8_(g8.end()), current8_(current8) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current8_; + if (current8_ == end8_) { + current8_ = begin8_; + ++current7_; + } + if (current7_ == end7_) { + current7_ = begin7_; + ++current6_; + } + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_ && + current7_ == typed_other->current7_ && + current8_ == typed_other->current8_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_), + begin8_(other.begin8_), + end8_(other.end8_), + current8_(other.current8_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_, *current7_, *current8_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_ || + current7_ == end7_ || + current8_ == end8_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + const typename ParamGenerator::iterator begin7_; + const typename ParamGenerator::iterator end7_; + typename ParamGenerator::iterator current7_; + const typename ParamGenerator::iterator begin8_; + const typename ParamGenerator::iterator end8_; + typename ParamGenerator::iterator current8_; + ParamType current_value_; + }; // class CartesianProductGenerator8::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator8& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; + const ParamGenerator g7_; + const ParamGenerator g8_; +}; // class CartesianProductGenerator8 + + +template +class CartesianProductGenerator9 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator9(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6, const ParamGenerator& g7, + const ParamGenerator& g8, const ParamGenerator& g9) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), + g9_(g9) {} + virtual ~CartesianProductGenerator9() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, + g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, + g8_.end(), g9_, g9_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, + const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7, + const ParamGenerator& g8, + const typename ParamGenerator::iterator& current8, + const ParamGenerator& g9, + const typename ParamGenerator::iterator& current9) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6), + begin7_(g7.begin()), end7_(g7.end()), current7_(current7), + begin8_(g8.begin()), end8_(g8.end()), current8_(current8), + begin9_(g9.begin()), end9_(g9.end()), current9_(current9) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current9_; + if (current9_ == end9_) { + current9_ = begin9_; + ++current8_; + } + if (current8_ == end8_) { + current8_ = begin8_; + ++current7_; + } + if (current7_ == end7_) { + current7_ = begin7_; + ++current6_; + } + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_ && + current7_ == typed_other->current7_ && + current8_ == typed_other->current8_ && + current9_ == typed_other->current9_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_), + begin8_(other.begin8_), + end8_(other.end8_), + current8_(other.current8_), + begin9_(other.begin9_), + end9_(other.end9_), + current9_(other.current9_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_, *current7_, *current8_, + *current9_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_ || + current7_ == end7_ || + current8_ == end8_ || + current9_ == end9_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + const typename ParamGenerator::iterator begin7_; + const typename ParamGenerator::iterator end7_; + typename ParamGenerator::iterator current7_; + const typename ParamGenerator::iterator begin8_; + const typename ParamGenerator::iterator end8_; + typename ParamGenerator::iterator current8_; + const typename ParamGenerator::iterator begin9_; + const typename ParamGenerator::iterator end9_; + typename ParamGenerator::iterator current9_; + ParamType current_value_; + }; // class CartesianProductGenerator9::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator9& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; + const ParamGenerator g7_; + const ParamGenerator g8_; + const ParamGenerator g9_; +}; // class CartesianProductGenerator9 + + +template +class CartesianProductGenerator10 + : public ParamGeneratorInterface< ::std::tr1::tuple > { + public: + typedef ::std::tr1::tuple ParamType; + + CartesianProductGenerator10(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6, const ParamGenerator& g7, + const ParamGenerator& g8, const ParamGenerator& g9, + const ParamGenerator& g10) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), + g9_(g9), g10_(g10) {} + virtual ~CartesianProductGenerator10() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, + g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin(), g10_, g10_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, + g8_.end(), g9_, g9_.end(), g10_, g10_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, + const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7, + const ParamGenerator& g8, + const typename ParamGenerator::iterator& current8, + const ParamGenerator& g9, + const typename ParamGenerator::iterator& current9, + const ParamGenerator& g10, + const typename ParamGenerator::iterator& current10) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6), + begin7_(g7.begin()), end7_(g7.end()), current7_(current7), + begin8_(g8.begin()), end8_(g8.end()), current8_(current8), + begin9_(g9.begin()), end9_(g9.end()), current9_(current9), + begin10_(g10.begin()), end10_(g10.end()), current10_(current10) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current10_; + if (current10_ == end10_) { + current10_ = begin10_; + ++current9_; + } + if (current9_ == end9_) { + current9_ = begin9_; + ++current8_; + } + if (current8_ == end8_) { + current8_ = begin8_; + ++current7_; + } + if (current7_ == end7_) { + current7_ = begin7_; + ++current6_; + } + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_ && + current7_ == typed_other->current7_ && + current8_ == typed_other->current8_ && + current9_ == typed_other->current9_ && + current10_ == typed_other->current10_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_), + begin8_(other.begin8_), + end8_(other.end8_), + current8_(other.current8_), + begin9_(other.begin9_), + end9_(other.end9_), + current9_(other.current9_), + begin10_(other.begin10_), + end10_(other.end10_), + current10_(other.current10_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_, *current7_, *current8_, + *current9_, *current10_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_ || + current7_ == end7_ || + current8_ == end8_ || + current9_ == end9_ || + current10_ == end10_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + const typename ParamGenerator::iterator begin7_; + const typename ParamGenerator::iterator end7_; + typename ParamGenerator::iterator current7_; + const typename ParamGenerator::iterator begin8_; + const typename ParamGenerator::iterator end8_; + typename ParamGenerator::iterator current8_; + const typename ParamGenerator::iterator begin9_; + const typename ParamGenerator::iterator end9_; + typename ParamGenerator::iterator current9_; + const typename ParamGenerator::iterator begin10_; + const typename ParamGenerator::iterator end10_; + typename ParamGenerator::iterator current10_; + ParamType current_value_; + }; // class CartesianProductGenerator10::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator10& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; + const ParamGenerator g7_; + const ParamGenerator g8_; + const ParamGenerator g9_; + const ParamGenerator g10_; +}; // class CartesianProductGenerator10 + + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Helper classes providing Combine() with polymorphic features. They allow +// casting CartesianProductGeneratorN to ParamGenerator if T is +// convertible to U. +// +template +class CartesianProductHolder2 { + public: +CartesianProductHolder2(const Generator1& g1, const Generator2& g2) + : g1_(g1), g2_(g2) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator2( + static_cast >(g1_), + static_cast >(g2_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder2& other); + + const Generator1 g1_; + const Generator2 g2_; +}; // class CartesianProductHolder2 + +template +class CartesianProductHolder3 { + public: +CartesianProductHolder3(const Generator1& g1, const Generator2& g2, + const Generator3& g3) + : g1_(g1), g2_(g2), g3_(g3) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator3( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder3& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; +}; // class CartesianProductHolder3 + +template +class CartesianProductHolder4 { + public: +CartesianProductHolder4(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator4( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder4& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; +}; // class CartesianProductHolder4 + +template +class CartesianProductHolder5 { + public: +CartesianProductHolder5(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator5( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder5& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; +}; // class CartesianProductHolder5 + +template +class CartesianProductHolder6 { + public: +CartesianProductHolder6(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator6( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder6& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; +}; // class CartesianProductHolder6 + +template +class CartesianProductHolder7 { + public: +CartesianProductHolder7(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator7( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_), + static_cast >(g7_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder7& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; + const Generator7 g7_; +}; // class CartesianProductHolder7 + +template +class CartesianProductHolder8 { + public: +CartesianProductHolder8(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7, const Generator8& g8) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), + g8_(g8) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator8( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_), + static_cast >(g7_), + static_cast >(g8_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder8& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; + const Generator7 g7_; + const Generator8 g8_; +}; // class CartesianProductHolder8 + +template +class CartesianProductHolder9 { + public: +CartesianProductHolder9(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7, const Generator8& g8, + const Generator9& g9) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), + g9_(g9) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator9( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_), + static_cast >(g7_), + static_cast >(g8_), + static_cast >(g9_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder9& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; + const Generator7 g7_; + const Generator8 g8_; + const Generator9 g9_; +}; // class CartesianProductHolder9 + +template +class CartesianProductHolder10 { + public: +CartesianProductHolder10(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7, const Generator8& g8, + const Generator9& g9, const Generator10& g10) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), + g9_(g9), g10_(g10) {} + template + operator ParamGenerator< ::std::tr1::tuple >() const { + return ParamGenerator< ::std::tr1::tuple >( + new CartesianProductGenerator10( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_), + static_cast >(g7_), + static_cast >(g8_), + static_cast >(g9_), + static_cast >(g10_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder10& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; + const Generator7 g7_; + const Generator8 g8_; + const Generator9 g9_; + const Generator10 g10_; +}; // class CartesianProductHolder10 + +# endif // GTEST_HAS_COMBINE + +} // namespace internal +} // namespace testing + +#endif // GTEST_HAS_PARAM_TEST + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ diff --git a/lib/gtest/include/gtest/internal/gtest-param-util-generated.h.pump b/lib/gtest/include/gtest/internal/gtest-param-util-generated.h.pump new file mode 100644 index 00000000..009206fd --- /dev/null +++ b/lib/gtest/include/gtest/internal/gtest-param-util-generated.h.pump @@ -0,0 +1,301 @@ +$$ -*- mode: c++; -*- +$var n = 50 $$ Maximum length of Values arguments we want to support. +$var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: vladl@google.com (Vlad Losev) + +// Type and function utilities for implementing parameterized tests. +// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +// Currently Google Test supports at most $n arguments in Values, +// and at most $maxtuple arguments in Combine. Please contact +// googletestframework@googlegroups.com if you need more. +// Please note that the number of arguments to Combine is limited +// by the maximum arity of the implementation of tr1::tuple which is +// currently set at $maxtuple. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ + +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. +#include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-port.h" + +#if GTEST_HAS_PARAM_TEST + +namespace testing { + +// Forward declarations of ValuesIn(), which is implemented in +// include/gtest/gtest-param-test.h. +template +internal::ParamGenerator< + typename ::testing::internal::IteratorTraits::value_type> +ValuesIn(ForwardIterator begin, ForwardIterator end); + +template +internal::ParamGenerator ValuesIn(const T (&array)[N]); + +template +internal::ParamGenerator ValuesIn( + const Container& container); + +namespace internal { + +// Used in the Values() function to provide polymorphic capabilities. +template +class ValueArray1 { + public: + explicit ValueArray1(T1 v1) : v1_(v1) {} + + template + operator ParamGenerator() const { return ValuesIn(&v1_, &v1_ + 1); } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray1& other); + + const T1 v1_; +}; + +$range i 2..n +$for i [[ +$range j 1..i + +template <$for j, [[typename T$j]]> +class ValueArray$i { + public: + ValueArray$i($for j, [[T$j v$j]]) : $for j, [[v$(j)_(v$j)]] {} + + template + operator ParamGenerator() const { + const T array[] = {$for j, [[static_cast(v$(j)_)]]}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray$i& other); + +$for j [[ + + const T$j v$(j)_; +]] + +}; + +]] + +# if GTEST_HAS_COMBINE +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Generates values from the Cartesian product of values produced +// by the argument generators. +// +$range i 2..maxtuple +$for i [[ +$range j 1..i +$range k 2..i + +template <$for j, [[typename T$j]]> +class CartesianProductGenerator$i + : public ParamGeneratorInterface< ::std::tr1::tuple<$for j, [[T$j]]> > { + public: + typedef ::std::tr1::tuple<$for j, [[T$j]]> ParamType; + + CartesianProductGenerator$i($for j, [[const ParamGenerator& g$j]]) + : $for j, [[g$(j)_(g$j)]] {} + virtual ~CartesianProductGenerator$i() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, $for j, [[g$(j)_, g$(j)_.begin()]]); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, $for j, [[g$(j)_, g$(j)_.end()]]); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, $for j, [[ + + const ParamGenerator& g$j, + const typename ParamGenerator::iterator& current$(j)]]) + : base_(base), +$for j, [[ + + begin$(j)_(g$j.begin()), end$(j)_(g$j.end()), current$(j)_(current$j) +]] { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current$(i)_; + +$for k [[ + if (current$(i+2-k)_ == end$(i+2-k)_) { + current$(i+2-k)_ = begin$(i+2-k)_; + ++current$(i+2-k-1)_; + } + +]] + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ($for j && [[ + + current$(j)_ == typed_other->current$(j)_ +]]); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), $for j, [[ + + begin$(j)_(other.begin$(j)_), + end$(j)_(other.end$(j)_), + current$(j)_(other.current$(j)_) +]] { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType($for j, [[*current$(j)_]]); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return +$for j || [[ + + current$(j)_ == end$(j)_ +]]; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. +$for j [[ + + const typename ParamGenerator::iterator begin$(j)_; + const typename ParamGenerator::iterator end$(j)_; + typename ParamGenerator::iterator current$(j)_; +]] + + ParamType current_value_; + }; // class CartesianProductGenerator$i::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator$i& other); + + +$for j [[ + const ParamGenerator g$(j)_; + +]] +}; // class CartesianProductGenerator$i + + +]] + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Helper classes providing Combine() with polymorphic features. They allow +// casting CartesianProductGeneratorN to ParamGenerator if T is +// convertible to U. +// +$range i 2..maxtuple +$for i [[ +$range j 1..i + +template <$for j, [[class Generator$j]]> +class CartesianProductHolder$i { + public: +CartesianProductHolder$i($for j, [[const Generator$j& g$j]]) + : $for j, [[g$(j)_(g$j)]] {} + template <$for j, [[typename T$j]]> + operator ParamGenerator< ::std::tr1::tuple<$for j, [[T$j]]> >() const { + return ParamGenerator< ::std::tr1::tuple<$for j, [[T$j]]> >( + new CartesianProductGenerator$i<$for j, [[T$j]]>( +$for j,[[ + + static_cast >(g$(j)_) +]])); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder$i& other); + + +$for j [[ + const Generator$j g$(j)_; + +]] +}; // class CartesianProductHolder$i + +]] + +# endif // GTEST_HAS_COMBINE + +} // namespace internal +} // namespace testing + +#endif // GTEST_HAS_PARAM_TEST + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ diff --git a/lib/gtest/include/gtest/internal/gtest-param-util.h b/lib/gtest/include/gtest/internal/gtest-param-util.h new file mode 100644 index 00000000..d5e1028b --- /dev/null +++ b/lib/gtest/include/gtest/internal/gtest-param-util.h @@ -0,0 +1,619 @@ +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: vladl@google.com (Vlad Losev) + +// Type and function utilities for implementing parameterized tests. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ + +#include +#include +#include + +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-linked_ptr.h" +#include "gtest/internal/gtest-port.h" +#include "gtest/gtest-printers.h" + +#if GTEST_HAS_PARAM_TEST + +namespace testing { +namespace internal { + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Outputs a message explaining invalid registration of different +// fixture class for the same test case. This may happen when +// TEST_P macro is used to define two tests with the same name +// but in different namespaces. +GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name, + const char* file, int line); + +template class ParamGeneratorInterface; +template class ParamGenerator; + +// Interface for iterating over elements provided by an implementation +// of ParamGeneratorInterface. +template +class ParamIteratorInterface { + public: + virtual ~ParamIteratorInterface() {} + // A pointer to the base generator instance. + // Used only for the purposes of iterator comparison + // to make sure that two iterators belong to the same generator. + virtual const ParamGeneratorInterface* BaseGenerator() const = 0; + // Advances iterator to point to the next element + // provided by the generator. The caller is responsible + // for not calling Advance() on an iterator equal to + // BaseGenerator()->End(). + virtual void Advance() = 0; + // Clones the iterator object. Used for implementing copy semantics + // of ParamIterator. + virtual ParamIteratorInterface* Clone() const = 0; + // Dereferences the current iterator and provides (read-only) access + // to the pointed value. It is the caller's responsibility not to call + // Current() on an iterator equal to BaseGenerator()->End(). + // Used for implementing ParamGenerator::operator*(). + virtual const T* Current() const = 0; + // Determines whether the given iterator and other point to the same + // element in the sequence generated by the generator. + // Used for implementing ParamGenerator::operator==(). + virtual bool Equals(const ParamIteratorInterface& other) const = 0; +}; + +// Class iterating over elements provided by an implementation of +// ParamGeneratorInterface. It wraps ParamIteratorInterface +// and implements the const forward iterator concept. +template +class ParamIterator { + public: + typedef T value_type; + typedef const T& reference; + typedef ptrdiff_t difference_type; + + // ParamIterator assumes ownership of the impl_ pointer. + ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} + ParamIterator& operator=(const ParamIterator& other) { + if (this != &other) + impl_.reset(other.impl_->Clone()); + return *this; + } + + const T& operator*() const { return *impl_->Current(); } + const T* operator->() const { return impl_->Current(); } + // Prefix version of operator++. + ParamIterator& operator++() { + impl_->Advance(); + return *this; + } + // Postfix version of operator++. + ParamIterator operator++(int /*unused*/) { + ParamIteratorInterface* clone = impl_->Clone(); + impl_->Advance(); + return ParamIterator(clone); + } + bool operator==(const ParamIterator& other) const { + return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_); + } + bool operator!=(const ParamIterator& other) const { + return !(*this == other); + } + + private: + friend class ParamGenerator; + explicit ParamIterator(ParamIteratorInterface* impl) : impl_(impl) {} + scoped_ptr > impl_; +}; + +// ParamGeneratorInterface is the binary interface to access generators +// defined in other translation units. +template +class ParamGeneratorInterface { + public: + typedef T ParamType; + + virtual ~ParamGeneratorInterface() {} + + // Generator interface definition + virtual ParamIteratorInterface* Begin() const = 0; + virtual ParamIteratorInterface* End() const = 0; +}; + +// Wraps ParamGeneratorInterface and provides general generator syntax +// compatible with the STL Container concept. +// This class implements copy initialization semantics and the contained +// ParamGeneratorInterface instance is shared among all copies +// of the original object. This is possible because that instance is immutable. +template +class ParamGenerator { + public: + typedef ParamIterator iterator; + + explicit ParamGenerator(ParamGeneratorInterface* impl) : impl_(impl) {} + ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {} + + ParamGenerator& operator=(const ParamGenerator& other) { + impl_ = other.impl_; + return *this; + } + + iterator begin() const { return iterator(impl_->Begin()); } + iterator end() const { return iterator(impl_->End()); } + + private: + linked_ptr > impl_; +}; + +// Generates values from a range of two comparable values. Can be used to +// generate sequences of user-defined types that implement operator+() and +// operator<(). +// This class is used in the Range() function. +template +class RangeGenerator : public ParamGeneratorInterface { + public: + RangeGenerator(T begin, T end, IncrementT step) + : begin_(begin), end_(end), + step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} + virtual ~RangeGenerator() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, begin_, 0, step_); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, end_, end_index_, step_); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, T value, int index, + IncrementT step) + : base_(base), value_(value), index_(index), step_(step) {} + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + virtual void Advance() { + value_ = value_ + step_; + index_++; + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const T* Current() const { return &value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const int other_index = + CheckedDowncastToActualType(&other)->index_; + return index_ == other_index; + } + + private: + Iterator(const Iterator& other) + : ParamIteratorInterface(), + base_(other.base_), value_(other.value_), index_(other.index_), + step_(other.step_) {} + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + T value_; + int index_; + const IncrementT step_; + }; // class RangeGenerator::Iterator + + static int CalculateEndIndex(const T& begin, + const T& end, + const IncrementT& step) { + int end_index = 0; + for (T i = begin; i < end; i = i + step) + end_index++; + return end_index; + } + + // No implementation - assignment is unsupported. + void operator=(const RangeGenerator& other); + + const T begin_; + const T end_; + const IncrementT step_; + // The index for the end() iterator. All the elements in the generated + // sequence are indexed (0-based) to aid iterator comparison. + const int end_index_; +}; // class RangeGenerator + + +// Generates values from a pair of STL-style iterators. Used in the +// ValuesIn() function. The elements are copied from the source range +// since the source can be located on the stack, and the generator +// is likely to persist beyond that stack frame. +template +class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { + public: + template + ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) + : container_(begin, end) {} + virtual ~ValuesInIteratorRangeGenerator() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, container_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, container_.end()); + } + + private: + typedef typename ::std::vector ContainerType; + + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + typename ContainerType::const_iterator iterator) + : base_(base), iterator_(iterator) {} + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + virtual void Advance() { + ++iterator_; + value_.reset(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + // We need to use cached value referenced by iterator_ because *iterator_ + // can return a temporary object (and of type other then T), so just + // having "return &*iterator_;" doesn't work. + // value_ is updated here and not in Advance() because Advance() + // can advance iterator_ beyond the end of the range, and we cannot + // detect that fact. The client code, on the other hand, is + // responsible for not calling Current() on an out-of-range iterator. + virtual const T* Current() const { + if (value_.get() == NULL) + value_.reset(new T(*iterator_)); + return value_.get(); + } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + return iterator_ == + CheckedDowncastToActualType(&other)->iterator_; + } + + private: + Iterator(const Iterator& other) + // The explicit constructor call suppresses a false warning + // emitted by gcc when supplied with the -Wextra option. + : ParamIteratorInterface(), + base_(other.base_), + iterator_(other.iterator_) {} + + const ParamGeneratorInterface* const base_; + typename ContainerType::const_iterator iterator_; + // A cached value of *iterator_. We keep it here to allow access by + // pointer in the wrapping iterator's operator->(). + // value_ needs to be mutable to be accessed in Current(). + // Use of scoped_ptr helps manage cached value's lifetime, + // which is bound by the lifespan of the iterator itself. + mutable scoped_ptr value_; + }; // class ValuesInIteratorRangeGenerator::Iterator + + // No implementation - assignment is unsupported. + void operator=(const ValuesInIteratorRangeGenerator& other); + + const ContainerType container_; +}; // class ValuesInIteratorRangeGenerator + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Stores a parameter value and later creates tests parameterized with that +// value. +template +class ParameterizedTestFactory : public TestFactoryBase { + public: + typedef typename TestClass::ParamType ParamType; + explicit ParameterizedTestFactory(ParamType parameter) : + parameter_(parameter) {} + virtual Test* CreateTest() { + TestClass::SetParam(¶meter_); + return new TestClass(); + } + + private: + const ParamType parameter_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory); +}; + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// TestMetaFactoryBase is a base class for meta-factories that create +// test factories for passing into MakeAndRegisterTestInfo function. +template +class TestMetaFactoryBase { + public: + virtual ~TestMetaFactoryBase() {} + + virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0; +}; + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// TestMetaFactory creates test factories for passing into +// MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives +// ownership of test factory pointer, same factory object cannot be passed +// into that method twice. But ParameterizedTestCaseInfo is going to call +// it for each Test/Parameter value combination. Thus it needs meta factory +// creator class. +template +class TestMetaFactory + : public TestMetaFactoryBase { + public: + typedef typename TestCase::ParamType ParamType; + + TestMetaFactory() {} + + virtual TestFactoryBase* CreateTestFactory(ParamType parameter) { + return new ParameterizedTestFactory(parameter); + } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory); +}; + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// ParameterizedTestCaseInfoBase is a generic interface +// to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase +// accumulates test information provided by TEST_P macro invocations +// and generators provided by INSTANTIATE_TEST_CASE_P macro invocations +// and uses that information to register all resulting test instances +// in RegisterTests method. The ParameterizeTestCaseRegistry class holds +// a collection of pointers to the ParameterizedTestCaseInfo objects +// and calls RegisterTests() on each of them when asked. +class ParameterizedTestCaseInfoBase { + public: + virtual ~ParameterizedTestCaseInfoBase() {} + + // Base part of test case name for display purposes. + virtual const string& GetTestCaseName() const = 0; + // Test case id to verify identity. + virtual TypeId GetTestCaseTypeId() const = 0; + // UnitTest class invokes this method to register tests in this + // test case right before running them in RUN_ALL_TESTS macro. + // This method should not be called more then once on any single + // instance of a ParameterizedTestCaseInfoBase derived class. + virtual void RegisterTests() = 0; + + protected: + ParameterizedTestCaseInfoBase() {} + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase); +}; + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// ParameterizedTestCaseInfo accumulates tests obtained from TEST_P +// macro invocations for a particular test case and generators +// obtained from INSTANTIATE_TEST_CASE_P macro invocations for that +// test case. It registers tests with all values generated by all +// generators when asked. +template +class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { + public: + // ParamType and GeneratorCreationFunc are private types but are required + // for declarations of public methods AddTestPattern() and + // AddTestCaseInstantiation(). + typedef typename TestCase::ParamType ParamType; + // A function that returns an instance of appropriate generator type. + typedef ParamGenerator(GeneratorCreationFunc)(); + + explicit ParameterizedTestCaseInfo(const char* name) + : test_case_name_(name) {} + + // Test case base name for display purposes. + virtual const string& GetTestCaseName() const { return test_case_name_; } + // Test case id to verify identity. + virtual TypeId GetTestCaseTypeId() const { return GetTypeId(); } + // TEST_P macro uses AddTestPattern() to record information + // about a single test in a LocalTestInfo structure. + // test_case_name is the base name of the test case (without invocation + // prefix). test_base_name is the name of an individual test without + // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is + // test case base name and DoBar is test base name. + void AddTestPattern(const char* test_case_name, + const char* test_base_name, + TestMetaFactoryBase* meta_factory) { + tests_.push_back(linked_ptr(new TestInfo(test_case_name, + test_base_name, + meta_factory))); + } + // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information + // about a generator. + int AddTestCaseInstantiation(const string& instantiation_name, + GeneratorCreationFunc* func, + const char* /* file */, + int /* line */) { + instantiations_.push_back(::std::make_pair(instantiation_name, func)); + return 0; // Return value used only to run this method in namespace scope. + } + // UnitTest class invokes this method to register tests in this test case + // test cases right before running tests in RUN_ALL_TESTS macro. + // This method should not be called more then once on any single + // instance of a ParameterizedTestCaseInfoBase derived class. + // UnitTest has a guard to prevent from calling this method more then once. + virtual void RegisterTests() { + for (typename TestInfoContainer::iterator test_it = tests_.begin(); + test_it != tests_.end(); ++test_it) { + linked_ptr test_info = *test_it; + for (typename InstantiationContainer::iterator gen_it = + instantiations_.begin(); gen_it != instantiations_.end(); + ++gen_it) { + const string& instantiation_name = gen_it->first; + ParamGenerator generator((*gen_it->second)()); + + string test_case_name; + if ( !instantiation_name.empty() ) + test_case_name = instantiation_name + "/"; + test_case_name += test_info->test_case_base_name; + + int i = 0; + for (typename ParamGenerator::iterator param_it = + generator.begin(); + param_it != generator.end(); ++param_it, ++i) { + Message test_name_stream; + test_name_stream << test_info->test_base_name << "/" << i; + MakeAndRegisterTestInfo( + test_case_name.c_str(), + test_name_stream.GetString().c_str(), + NULL, // No type parameter. + PrintToString(*param_it).c_str(), + GetTestCaseTypeId(), + TestCase::SetUpTestCase, + TestCase::TearDownTestCase, + test_info->test_meta_factory->CreateTestFactory(*param_it)); + } // for param_it + } // for gen_it + } // for test_it + } // RegisterTests + + private: + // LocalTestInfo structure keeps information about a single test registered + // with TEST_P macro. + struct TestInfo { + TestInfo(const char* a_test_case_base_name, + const char* a_test_base_name, + TestMetaFactoryBase* a_test_meta_factory) : + test_case_base_name(a_test_case_base_name), + test_base_name(a_test_base_name), + test_meta_factory(a_test_meta_factory) {} + + const string test_case_base_name; + const string test_base_name; + const scoped_ptr > test_meta_factory; + }; + typedef ::std::vector > TestInfoContainer; + // Keeps pairs of + // received from INSTANTIATE_TEST_CASE_P macros. + typedef ::std::vector > + InstantiationContainer; + + const string test_case_name_; + TestInfoContainer tests_; + InstantiationContainer instantiations_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo); +}; // class ParameterizedTestCaseInfo + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase +// classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P +// macros use it to locate their corresponding ParameterizedTestCaseInfo +// descriptors. +class ParameterizedTestCaseRegistry { + public: + ParameterizedTestCaseRegistry() {} + ~ParameterizedTestCaseRegistry() { + for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); + it != test_case_infos_.end(); ++it) { + delete *it; + } + } + + // Looks up or creates and returns a structure containing information about + // tests and instantiations of a particular test case. + template + ParameterizedTestCaseInfo* GetTestCasePatternHolder( + const char* test_case_name, + const char* file, + int line) { + ParameterizedTestCaseInfo* typed_test_info = NULL; + for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); + it != test_case_infos_.end(); ++it) { + if ((*it)->GetTestCaseName() == test_case_name) { + if ((*it)->GetTestCaseTypeId() != GetTypeId()) { + // Complain about incorrect usage of Google Test facilities + // and terminate the program since we cannot guaranty correct + // test case setup and tear-down in this case. + ReportInvalidTestCaseType(test_case_name, file, line); + posix::Abort(); + } else { + // At this point we are sure that the object we found is of the same + // type we are looking for, so we downcast it to that type + // without further checks. + typed_test_info = CheckedDowncastToActualType< + ParameterizedTestCaseInfo >(*it); + } + break; + } + } + if (typed_test_info == NULL) { + typed_test_info = new ParameterizedTestCaseInfo(test_case_name); + test_case_infos_.push_back(typed_test_info); + } + return typed_test_info; + } + void RegisterTests() { + for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); + it != test_case_infos_.end(); ++it) { + (*it)->RegisterTests(); + } + } + + private: + typedef ::std::vector TestCaseInfoContainer; + + TestCaseInfoContainer test_case_infos_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry); +}; + +} // namespace internal +} // namespace testing + +#endif // GTEST_HAS_PARAM_TEST + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ diff --git a/lib/gtest/include/gtest/internal/gtest-port.h b/lib/gtest/include/gtest/internal/gtest-port.h new file mode 100644 index 00000000..dc4fe0cb --- /dev/null +++ b/lib/gtest/include/gtest/internal/gtest-port.h @@ -0,0 +1,1947 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: wan@google.com (Zhanyong Wan) +// +// Low-level types and utilities for porting Google Test to various +// platforms. They are subject to change without notice. DO NOT USE +// THEM IN USER CODE. +// +// This file is fundamental to Google Test. All other Google Test source +// files are expected to #include this. Therefore, it cannot #include +// any other Google Test header. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ + +// The user can define the following macros in the build script to +// control Google Test's behavior. If the user doesn't define a macro +// in this list, Google Test will define it. +// +// GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2) +// is/isn't available. +// GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions +// are enabled. +// GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string +// is/isn't available (some systems define +// ::string, which is different to std::string). +// GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string +// is/isn't available (some systems define +// ::wstring, which is different to std::wstring). +// GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular +// expressions are/aren't available. +// GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that +// is/isn't available. +// GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't +// enabled. +// GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that +// std::wstring does/doesn't work (Google Test can +// be used where std::wstring is unavailable). +// GTEST_HAS_TR1_TUPLE - Define it to 1/0 to indicate tr1::tuple +// is/isn't available. +// GTEST_HAS_SEH - Define it to 1/0 to indicate whether the +// compiler supports Microsoft's "Structured +// Exception Handling". +// GTEST_HAS_STREAM_REDIRECTION +// - Define it to 1/0 to indicate whether the +// platform supports I/O stream redirection using +// dup() and dup2(). +// GTEST_USE_OWN_TR1_TUPLE - Define it to 1/0 to indicate whether Google +// Test's own tr1 tuple implementation should be +// used. Unused when the user sets +// GTEST_HAS_TR1_TUPLE to 0. +// GTEST_LANG_CXX11 - Define it to 1/0 to indicate that Google Test +// is building in C++11/C++98 mode. +// GTEST_LINKED_AS_SHARED_LIBRARY +// - Define to 1 when compiling tests that use +// Google Test as a shared library (known as +// DLL on Windows). +// GTEST_CREATE_SHARED_LIBRARY +// - Define to 1 when compiling Google Test itself +// as a shared library. + +// This header defines the following utilities: +// +// Macros indicating the current platform (defined to 1 if compiled on +// the given platform; otherwise undefined): +// GTEST_OS_AIX - IBM AIX +// GTEST_OS_CYGWIN - Cygwin +// GTEST_OS_HPUX - HP-UX +// GTEST_OS_LINUX - Linux +// GTEST_OS_LINUX_ANDROID - Google Android +// GTEST_OS_MAC - Mac OS X +// GTEST_OS_IOS - iOS +// GTEST_OS_IOS_SIMULATOR - iOS simulator +// GTEST_OS_NACL - Google Native Client (NaCl) +// GTEST_OS_OPENBSD - OpenBSD +// GTEST_OS_QNX - QNX +// GTEST_OS_SOLARIS - Sun Solaris +// GTEST_OS_SYMBIAN - Symbian +// GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) +// GTEST_OS_WINDOWS_DESKTOP - Windows Desktop +// GTEST_OS_WINDOWS_MINGW - MinGW +// GTEST_OS_WINDOWS_MOBILE - Windows Mobile +// GTEST_OS_ZOS - z/OS +// +// Among the platforms, Cygwin, Linux, Max OS X, and Windows have the +// most stable support. Since core members of the Google Test project +// don't have access to other platforms, support for them may be less +// stable. If you notice any problems on your platform, please notify +// googletestframework@googlegroups.com (patches for fixing them are +// even more welcome!). +// +// Note that it is possible that none of the GTEST_OS_* macros are defined. +// +// Macros indicating available Google Test features (defined to 1 if +// the corresponding feature is supported; otherwise undefined): +// GTEST_HAS_COMBINE - the Combine() function (for value-parameterized +// tests) +// GTEST_HAS_DEATH_TEST - death tests +// GTEST_HAS_PARAM_TEST - value-parameterized tests +// GTEST_HAS_TYPED_TEST - typed tests +// GTEST_HAS_TYPED_TEST_P - type-parameterized tests +// GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with +// GTEST_HAS_POSIX_RE (see above) which users can +// define themselves. +// GTEST_USES_SIMPLE_RE - our own simple regex is used; +// the above two are mutually exclusive. +// GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). +// +// Macros for basic C++ coding: +// GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. +// GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a +// variable don't have to be used. +// GTEST_DISALLOW_ASSIGN_ - disables operator=. +// GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. +// GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. +// +// Synchronization: +// Mutex, MutexLock, ThreadLocal, GetThreadCount() +// - synchronization primitives. +// GTEST_IS_THREADSAFE - defined to 1 to indicate that the above +// synchronization primitives have real implementations +// and Google Test is thread-safe; or 0 otherwise. +// +// Template meta programming: +// is_pointer - as in TR1; needed on Symbian and IBM XL C/C++ only. +// IteratorTraits - partial implementation of std::iterator_traits, which +// is not available in libCstd when compiled with Sun C++. +// +// Smart pointers: +// scoped_ptr - as in TR2. +// +// Regular expressions: +// RE - a simple regular expression class using the POSIX +// Extended Regular Expression syntax on UNIX-like +// platforms, or a reduced regular exception syntax on +// other platforms, including Windows. +// +// Logging: +// GTEST_LOG_() - logs messages at the specified severity level. +// LogToStderr() - directs all log messages to stderr. +// FlushInfoLog() - flushes informational log messages. +// +// Stdout and stderr capturing: +// CaptureStdout() - starts capturing stdout. +// GetCapturedStdout() - stops capturing stdout and returns the captured +// string. +// CaptureStderr() - starts capturing stderr. +// GetCapturedStderr() - stops capturing stderr and returns the captured +// string. +// +// Integer types: +// TypeWithSize - maps an integer to a int type. +// Int32, UInt32, Int64, UInt64, TimeInMillis +// - integers of known sizes. +// BiggestInt - the biggest signed integer type. +// +// Command-line utilities: +// GTEST_FLAG() - references a flag. +// GTEST_DECLARE_*() - declares a flag. +// GTEST_DEFINE_*() - defines a flag. +// GetInjectableArgvs() - returns the command line as a vector of strings. +// +// Environment variable utilities: +// GetEnv() - gets the value of an environment variable. +// BoolFromGTestEnv() - parses a bool environment variable. +// Int32FromGTestEnv() - parses an Int32 environment variable. +// StringFromGTestEnv() - parses a string environment variable. + +#include // for isspace, etc +#include // for ptrdiff_t +#include +#include +#include +#ifndef _WIN32_WCE +# include +# include +#endif // !_WIN32_WCE + +#if defined __APPLE__ +# include +# include +#endif + +#include // NOLINT +#include // NOLINT +#include // NOLINT + +#define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" +#define GTEST_FLAG_PREFIX_ "gtest_" +#define GTEST_FLAG_PREFIX_DASH_ "gtest-" +#define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" +#define GTEST_NAME_ "Google Test" +#define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/" + +// Determines the version of gcc that is used to compile this. +#ifdef __GNUC__ +// 40302 means version 4.3.2. +# define GTEST_GCC_VER_ \ + (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) +#endif // __GNUC__ + +// Determines the platform on which Google Test is compiled. +#ifdef __CYGWIN__ +# define GTEST_OS_CYGWIN 1 +#elif defined __SYMBIAN32__ +# define GTEST_OS_SYMBIAN 1 +#elif defined _WIN32 +# define GTEST_OS_WINDOWS 1 +# ifdef _WIN32_WCE +# define GTEST_OS_WINDOWS_MOBILE 1 +# elif defined(__MINGW__) || defined(__MINGW32__) +# define GTEST_OS_WINDOWS_MINGW 1 +# else +# define GTEST_OS_WINDOWS_DESKTOP 1 +# endif // _WIN32_WCE +#elif defined __APPLE__ +# define GTEST_OS_MAC 1 +# if TARGET_OS_IPHONE +# define GTEST_OS_IOS 1 +# if TARGET_IPHONE_SIMULATOR +# define GTEST_OS_IOS_SIMULATOR 1 +# endif +# endif +#elif defined __linux__ +# define GTEST_OS_LINUX 1 +# if defined __ANDROID__ +# define GTEST_OS_LINUX_ANDROID 1 +# endif +#elif defined __MVS__ +# define GTEST_OS_ZOS 1 +#elif defined(__sun) && defined(__SVR4) +# define GTEST_OS_SOLARIS 1 +#elif defined(_AIX) +# define GTEST_OS_AIX 1 +#elif defined(__hpux) +# define GTEST_OS_HPUX 1 +#elif defined __native_client__ +# define GTEST_OS_NACL 1 +#elif defined __OpenBSD__ +# define GTEST_OS_OPENBSD 1 +#elif defined __QNX__ +# define GTEST_OS_QNX 1 +#endif // __CYGWIN__ + +#ifndef GTEST_LANG_CXX11 +// gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when +// -std={c,gnu}++{0x,11} is passed. The C++11 standard specifies a +// value for __cplusplus, and recent versions of clang, gcc, and +// probably other compilers set that too in C++11 mode. +# if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L +// Compiling in at least C++11 mode. +# define GTEST_LANG_CXX11 1 +# else +# define GTEST_LANG_CXX11 0 +# endif +#endif + +// Brings in definitions for functions used in the testing::internal::posix +// namespace (read, write, close, chdir, isatty, stat). We do not currently +// use them on Windows Mobile. +#if !GTEST_OS_WINDOWS +// This assumes that non-Windows OSes provide unistd.h. For OSes where this +// is not the case, we need to include headers that provide the functions +// mentioned above. +# include +# include +#elif !GTEST_OS_WINDOWS_MOBILE +# include +# include +#endif + +#if GTEST_OS_LINUX_ANDROID +// Used to define __ANDROID_API__ matching the target NDK API level. +# include // NOLINT +#endif + +// Defines this to true iff Google Test can use POSIX regular expressions. +#ifndef GTEST_HAS_POSIX_RE +# if GTEST_OS_LINUX_ANDROID +// On Android, is only available starting with Gingerbread. +# define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) +# else +# define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) +# endif +#endif + +#if GTEST_HAS_POSIX_RE + +// On some platforms, needs someone to define size_t, and +// won't compile otherwise. We can #include it here as we already +// included , which is guaranteed to define size_t through +// . +# include // NOLINT + +# define GTEST_USES_POSIX_RE 1 + +#elif GTEST_OS_WINDOWS + +// is not available on Windows. Use our own simple regex +// implementation instead. +# define GTEST_USES_SIMPLE_RE 1 + +#else + +// may not be available on this platform. Use our own +// simple regex implementation instead. +# define GTEST_USES_SIMPLE_RE 1 + +#endif // GTEST_HAS_POSIX_RE + +#ifndef GTEST_HAS_EXCEPTIONS +// The user didn't tell us whether exceptions are enabled, so we need +// to figure it out. +# if defined(_MSC_VER) || defined(__BORLANDC__) +// MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS +// macro to enable exceptions, so we'll do the same. +// Assumes that exceptions are enabled by default. +# ifndef _HAS_EXCEPTIONS +# define _HAS_EXCEPTIONS 1 +# endif // _HAS_EXCEPTIONS +# define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS +# elif defined(__GNUC__) && __EXCEPTIONS +// gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. +# define GTEST_HAS_EXCEPTIONS 1 +# elif defined(__SUNPRO_CC) +// Sun Pro CC supports exceptions. However, there is no compile-time way of +// detecting whether they are enabled or not. Therefore, we assume that +// they are enabled unless the user tells us otherwise. +# define GTEST_HAS_EXCEPTIONS 1 +# elif defined(__IBMCPP__) && __EXCEPTIONS +// xlC defines __EXCEPTIONS to 1 iff exceptions are enabled. +# define GTEST_HAS_EXCEPTIONS 1 +# elif defined(__HP_aCC) +// Exception handling is in effect by default in HP aCC compiler. It has to +// be turned of by +noeh compiler option if desired. +# define GTEST_HAS_EXCEPTIONS 1 +# else +// For other compilers, we assume exceptions are disabled to be +// conservative. +# define GTEST_HAS_EXCEPTIONS 0 +# endif // defined(_MSC_VER) || defined(__BORLANDC__) +#endif // GTEST_HAS_EXCEPTIONS + +#if !defined(GTEST_HAS_STD_STRING) +// Even though we don't use this macro any longer, we keep it in case +// some clients still depend on it. +# define GTEST_HAS_STD_STRING 1 +#elif !GTEST_HAS_STD_STRING +// The user told us that ::std::string isn't available. +# error "Google Test cannot be used where ::std::string isn't available." +#endif // !defined(GTEST_HAS_STD_STRING) + +#ifndef GTEST_HAS_GLOBAL_STRING +// The user didn't tell us whether ::string is available, so we need +// to figure it out. + +# define GTEST_HAS_GLOBAL_STRING 0 + +#endif // GTEST_HAS_GLOBAL_STRING + +#ifndef GTEST_HAS_STD_WSTRING +// The user didn't tell us whether ::std::wstring is available, so we need +// to figure it out. +// TODO(wan@google.com): uses autoconf to detect whether ::std::wstring +// is available. + +// Cygwin 1.7 and below doesn't support ::std::wstring. +// Solaris' libc++ doesn't support it either. Android has +// no support for it at least as recent as Froyo (2.2). +# define GTEST_HAS_STD_WSTRING \ + (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS)) + +#endif // GTEST_HAS_STD_WSTRING + +#ifndef GTEST_HAS_GLOBAL_WSTRING +// The user didn't tell us whether ::wstring is available, so we need +// to figure it out. +# define GTEST_HAS_GLOBAL_WSTRING \ + (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING) +#endif // GTEST_HAS_GLOBAL_WSTRING + +// Determines whether RTTI is available. +#ifndef GTEST_HAS_RTTI +// The user didn't tell us whether RTTI is enabled, so we need to +// figure it out. + +# ifdef _MSC_VER + +# ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled. +# define GTEST_HAS_RTTI 1 +# else +# define GTEST_HAS_RTTI 0 +# endif + +// Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled. +# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) + +# ifdef __GXX_RTTI +// When building against STLport with the Android NDK and with +// -frtti -fno-exceptions, the build fails at link time with undefined +// references to __cxa_bad_typeid. Note sure if STL or toolchain bug, +// so disable RTTI when detected. +# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \ + !defined(__EXCEPTIONS) +# define GTEST_HAS_RTTI 0 +# else +# define GTEST_HAS_RTTI 1 +# endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS +# else +# define GTEST_HAS_RTTI 0 +# endif // __GXX_RTTI + +// Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends +// using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the +// first version with C++ support. +# elif defined(__clang__) + +# define GTEST_HAS_RTTI __has_feature(cxx_rtti) + +// Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if +// both the typeid and dynamic_cast features are present. +# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) + +# ifdef __RTTI_ALL__ +# define GTEST_HAS_RTTI 1 +# else +# define GTEST_HAS_RTTI 0 +# endif + +# else + +// For all other compilers, we assume RTTI is enabled. +# define GTEST_HAS_RTTI 1 + +# endif // _MSC_VER + +#endif // GTEST_HAS_RTTI + +// It's this header's responsibility to #include when RTTI +// is enabled. +#if GTEST_HAS_RTTI +# include +#endif + +// Determines whether Google Test can use the pthreads library. +#ifndef GTEST_HAS_PTHREAD +// The user didn't tell us explicitly, so we assume pthreads support is +// available on Linux and Mac. +// +// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 +// to your compiler flags. +# define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \ + || GTEST_OS_QNX) +#endif // GTEST_HAS_PTHREAD + +#if GTEST_HAS_PTHREAD +// gtest-port.h guarantees to #include when GTEST_HAS_PTHREAD is +// true. +# include // NOLINT + +// For timespec and nanosleep, used below. +# include // NOLINT +#endif + +// Determines whether Google Test can use tr1/tuple. You can define +// this macro to 0 to prevent Google Test from using tuple (any +// feature depending on tuple with be disabled in this mode). +#ifndef GTEST_HAS_TR1_TUPLE +# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) +// STLport, provided with the Android NDK, has neither or . +# define GTEST_HAS_TR1_TUPLE 0 +# else +// The user didn't tell us not to do it, so we assume it's OK. +# define GTEST_HAS_TR1_TUPLE 1 +# endif +#endif // GTEST_HAS_TR1_TUPLE + +// Determines whether Google Test's own tr1 tuple implementation +// should be used. +#ifndef GTEST_USE_OWN_TR1_TUPLE +// The user didn't tell us, so we need to figure it out. + +// We use our own TR1 tuple if we aren't sure the user has an +// implementation of it already. At this time, libstdc++ 4.0.0+ and +// MSVC 2010 are the only mainstream standard libraries that come +// with a TR1 tuple implementation. NVIDIA's CUDA NVCC compiler +// pretends to be GCC by defining __GNUC__ and friends, but cannot +// compile GCC's tuple implementation. MSVC 2008 (9.0) provides TR1 +// tuple in a 323 MB Feature Pack download, which we cannot assume the +// user has. QNX's QCC compiler is a modified GCC but it doesn't +// support TR1 tuple. libc++ only provides std::tuple, in C++11 mode, +// and it can be used with some compilers that define __GNUC__. +# if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \ + && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600 +# define GTEST_ENV_HAS_TR1_TUPLE_ 1 +# endif + +// C++11 specifies that provides std::tuple. Use that if gtest is used +// in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6 +// can build with clang but need to use gcc4.2's libstdc++). +# if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325) +# define GTEST_ENV_HAS_STD_TUPLE_ 1 +# endif + +# if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_ +# define GTEST_USE_OWN_TR1_TUPLE 0 +# else +# define GTEST_USE_OWN_TR1_TUPLE 1 +# endif + +#endif // GTEST_USE_OWN_TR1_TUPLE + +// To avoid conditional compilation everywhere, we make it +// gtest-port.h's responsibility to #include the header implementing +// tr1/tuple. +#if GTEST_HAS_TR1_TUPLE + +# if GTEST_USE_OWN_TR1_TUPLE +# include "gtest/internal/gtest-tuple.h" +# elif GTEST_ENV_HAS_STD_TUPLE_ +# include +// C++11 puts its tuple into the ::std namespace rather than +// ::std::tr1. gtest expects tuple to live in ::std::tr1, so put it there. +// This causes undefined behavior, but supported compilers react in +// the way we intend. +namespace std { +namespace tr1 { +using ::std::get; +using ::std::make_tuple; +using ::std::tuple; +using ::std::tuple_element; +using ::std::tuple_size; +} +} + +# elif GTEST_OS_SYMBIAN + +// On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to +// use STLport's tuple implementation, which unfortunately doesn't +// work as the copy of STLport distributed with Symbian is incomplete. +// By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to +// use its own tuple implementation. +# ifdef BOOST_HAS_TR1_TUPLE +# undef BOOST_HAS_TR1_TUPLE +# endif // BOOST_HAS_TR1_TUPLE + +// This prevents , which defines +// BOOST_HAS_TR1_TUPLE, from being #included by Boost's . +# define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED +# include + +# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000) +// GCC 4.0+ implements tr1/tuple in the header. This does +// not conform to the TR1 spec, which requires the header to be . + +# if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 +// Until version 4.3.2, gcc has a bug that causes , +// which is #included by , to not compile when RTTI is +// disabled. _TR1_FUNCTIONAL is the header guard for +// . Hence the following #define is a hack to prevent +// from being included. +# define _TR1_FUNCTIONAL 1 +# include +# undef _TR1_FUNCTIONAL // Allows the user to #include + // if he chooses to. +# else +# include // NOLINT +# endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 + +# else +// If the compiler is not GCC 4.0+, we assume the user is using a +// spec-conforming TR1 implementation. +# include // NOLINT +# endif // GTEST_USE_OWN_TR1_TUPLE + +#endif // GTEST_HAS_TR1_TUPLE + +// Determines whether clone(2) is supported. +// Usually it will only be available on Linux, excluding +// Linux on the Itanium architecture. +// Also see http://linux.die.net/man/2/clone. +#ifndef GTEST_HAS_CLONE +// The user didn't tell us, so we need to figure it out. + +# if GTEST_OS_LINUX && !defined(__ia64__) +# if GTEST_OS_LINUX_ANDROID +// On Android, clone() is only available on ARM starting with Gingerbread. +# if defined(__arm__) && __ANDROID_API__ >= 9 +# define GTEST_HAS_CLONE 1 +# else +# define GTEST_HAS_CLONE 0 +# endif +# else +# define GTEST_HAS_CLONE 1 +# endif +# else +# define GTEST_HAS_CLONE 0 +# endif // GTEST_OS_LINUX && !defined(__ia64__) + +#endif // GTEST_HAS_CLONE + +// Determines whether to support stream redirection. This is used to test +// output correctness and to implement death tests. +#ifndef GTEST_HAS_STREAM_REDIRECTION +// By default, we assume that stream redirection is supported on all +// platforms except known mobile ones. +# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN +# define GTEST_HAS_STREAM_REDIRECTION 0 +# else +# define GTEST_HAS_STREAM_REDIRECTION 1 +# endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN +#endif // GTEST_HAS_STREAM_REDIRECTION + +// Determines whether to support death tests. +// Google Test does not support death tests for VC 7.1 and earlier as +// abort() in a VC 7.1 application compiled as GUI in debug config +// pops up a dialog window that cannot be suppressed programmatically. +#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ + (GTEST_OS_MAC && !GTEST_OS_IOS) || GTEST_OS_IOS_SIMULATOR || \ + (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ + GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \ + GTEST_OS_OPENBSD || GTEST_OS_QNX) +# define GTEST_HAS_DEATH_TEST 1 +# include // NOLINT +#endif + +// We don't support MSVC 7.1 with exceptions disabled now. Therefore +// all the compilers we care about are adequate for supporting +// value-parameterized tests. +#define GTEST_HAS_PARAM_TEST 1 + +// Determines whether to support type-driven tests. + +// Typed tests need and variadic macros, which GCC, VC++ 8.0, +// Sun Pro CC, IBM Visual Age, and HP aCC support. +#if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \ + defined(__IBMCPP__) || defined(__HP_aCC) +# define GTEST_HAS_TYPED_TEST 1 +# define GTEST_HAS_TYPED_TEST_P 1 +#endif + +// Determines whether to support Combine(). This only makes sense when +// value-parameterized tests are enabled. The implementation doesn't +// work on Sun Studio since it doesn't understand templated conversion +// operators. +#if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC) +# define GTEST_HAS_COMBINE 1 +#endif + +// Determines whether the system compiler uses UTF-16 for encoding wide strings. +#define GTEST_WIDE_STRING_USES_UTF16_ \ + (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX) + +// Determines whether test results can be streamed to a socket. +#if GTEST_OS_LINUX +# define GTEST_CAN_STREAM_RESULTS_ 1 +#endif + +// Defines some utility macros. + +// The GNU compiler emits a warning if nested "if" statements are followed by +// an "else" statement and braces are not used to explicitly disambiguate the +// "else" binding. This leads to problems with code like: +// +// if (gate) +// ASSERT_*(condition) << "Some message"; +// +// The "switch (0) case 0:" idiom is used to suppress this. +#ifdef __INTEL_COMPILER +# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ +#else +# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT +#endif + +// Use this annotation at the end of a struct/class definition to +// prevent the compiler from optimizing away instances that are never +// used. This is useful when all interesting logic happens inside the +// c'tor and / or d'tor. Example: +// +// struct Foo { +// Foo() { ... } +// } GTEST_ATTRIBUTE_UNUSED_; +// +// Also use it after a variable or parameter declaration to tell the +// compiler the variable/parameter does not have to be used. +#if defined(__GNUC__) && !defined(COMPILER_ICC) +# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) +#else +# define GTEST_ATTRIBUTE_UNUSED_ +#endif + +// A macro to disallow operator= +// This should be used in the private: declarations for a class. +#define GTEST_DISALLOW_ASSIGN_(type)\ + void operator=(type const &) + +// A macro to disallow copy constructor and operator= +// This should be used in the private: declarations for a class. +#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\ + type(type const &);\ + GTEST_DISALLOW_ASSIGN_(type) + +// Tell the compiler to warn about unused return values for functions declared +// with this macro. The macro should be used on function declarations +// following the argument list: +// +// Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; +#if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC) +# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) +#else +# define GTEST_MUST_USE_RESULT_ +#endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC + +// Determine whether the compiler supports Microsoft's Structured Exception +// Handling. This is supported by several Windows compilers but generally +// does not exist on any other system. +#ifndef GTEST_HAS_SEH +// The user didn't tell us, so we need to figure it out. + +# if defined(_MSC_VER) || defined(__BORLANDC__) +// These two compilers are known to support SEH. +# define GTEST_HAS_SEH 1 +# else +// Assume no SEH. +# define GTEST_HAS_SEH 0 +# endif + +#endif // GTEST_HAS_SEH + +#ifdef _MSC_VER + +# if GTEST_LINKED_AS_SHARED_LIBRARY +# define GTEST_API_ __declspec(dllimport) +# elif GTEST_CREATE_SHARED_LIBRARY +# define GTEST_API_ __declspec(dllexport) +# endif + +#endif // _MSC_VER + +#ifndef GTEST_API_ +# define GTEST_API_ +#endif + +#ifdef __GNUC__ +// Ask the compiler to never inline a given function. +# define GTEST_NO_INLINE_ __attribute__((noinline)) +#else +# define GTEST_NO_INLINE_ +#endif + +// _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. +#if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION) +# define GTEST_HAS_CXXABI_H_ 1 +#else +# define GTEST_HAS_CXXABI_H_ 0 +#endif + +namespace testing { + +class Message; + +namespace internal { + +// A secret type that Google Test users don't know about. It has no +// definition on purpose. Therefore it's impossible to create a +// Secret object, which is what we want. +class Secret; + +// The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time +// expression is true. For example, you could use it to verify the +// size of a static array: +// +// GTEST_COMPILE_ASSERT_(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES, +// content_type_names_incorrect_size); +// +// or to make sure a struct is smaller than a certain size: +// +// GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large); +// +// The second argument to the macro is the name of the variable. If +// the expression is false, most compilers will issue a warning/error +// containing the name of the variable. + +template +struct CompileAssert { +}; + +#define GTEST_COMPILE_ASSERT_(expr, msg) \ + typedef ::testing::internal::CompileAssert<(static_cast(expr))> \ + msg[static_cast(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_ + +// Implementation details of GTEST_COMPILE_ASSERT_: +// +// - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1 +// elements (and thus is invalid) when the expression is false. +// +// - The simpler definition +// +// #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1] +// +// does not work, as gcc supports variable-length arrays whose sizes +// are determined at run-time (this is gcc's extension and not part +// of the C++ standard). As a result, gcc fails to reject the +// following code with the simple definition: +// +// int foo; +// GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is +// // not a compile-time constant. +// +// - By using the type CompileAssert<(bool(expr))>, we ensures that +// expr is a compile-time constant. (Template arguments must be +// determined at compile-time.) +// +// - The outter parentheses in CompileAssert<(bool(expr))> are necessary +// to work around a bug in gcc 3.4.4 and 4.0.1. If we had written +// +// CompileAssert +// +// instead, these compilers will refuse to compile +// +// GTEST_COMPILE_ASSERT_(5 > 0, some_message); +// +// (They seem to think the ">" in "5 > 0" marks the end of the +// template argument list.) +// +// - The array size is (bool(expr) ? 1 : -1), instead of simply +// +// ((expr) ? 1 : -1). +// +// This is to avoid running into a bug in MS VC 7.1, which +// causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. + +// StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h. +// +// This template is declared, but intentionally undefined. +template +struct StaticAssertTypeEqHelper; + +template +struct StaticAssertTypeEqHelper {}; + +#if GTEST_HAS_GLOBAL_STRING +typedef ::string string; +#else +typedef ::std::string string; +#endif // GTEST_HAS_GLOBAL_STRING + +#if GTEST_HAS_GLOBAL_WSTRING +typedef ::wstring wstring; +#elif GTEST_HAS_STD_WSTRING +typedef ::std::wstring wstring; +#endif // GTEST_HAS_GLOBAL_WSTRING + +// A helper for suppressing warnings on constant condition. It just +// returns 'condition'. +GTEST_API_ bool IsTrue(bool condition); + +// Defines scoped_ptr. + +// This implementation of scoped_ptr is PARTIAL - it only contains +// enough stuff to satisfy Google Test's need. +template +class scoped_ptr { + public: + typedef T element_type; + + explicit scoped_ptr(T* p = NULL) : ptr_(p) {} + ~scoped_ptr() { reset(); } + + T& operator*() const { return *ptr_; } + T* operator->() const { return ptr_; } + T* get() const { return ptr_; } + + T* release() { + T* const ptr = ptr_; + ptr_ = NULL; + return ptr; + } + + void reset(T* p = NULL) { + if (p != ptr_) { + if (IsTrue(sizeof(T) > 0)) { // Makes sure T is a complete type. + delete ptr_; + } + ptr_ = p; + } + } + + private: + T* ptr_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr); +}; + +// Defines RE. + +// A simple C++ wrapper for . It uses the POSIX Extended +// Regular Expression syntax. +class GTEST_API_ RE { + public: + // A copy constructor is required by the Standard to initialize object + // references from r-values. + RE(const RE& other) { Init(other.pattern()); } + + // Constructs an RE from a string. + RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT + +#if GTEST_HAS_GLOBAL_STRING + + RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT + +#endif // GTEST_HAS_GLOBAL_STRING + + RE(const char* regex) { Init(regex); } // NOLINT + ~RE(); + + // Returns the string representation of the regex. + const char* pattern() const { return pattern_; } + + // FullMatch(str, re) returns true iff regular expression re matches + // the entire str. + // PartialMatch(str, re) returns true iff regular expression re + // matches a substring of str (including str itself). + // + // TODO(wan@google.com): make FullMatch() and PartialMatch() work + // when str contains NUL characters. + static bool FullMatch(const ::std::string& str, const RE& re) { + return FullMatch(str.c_str(), re); + } + static bool PartialMatch(const ::std::string& str, const RE& re) { + return PartialMatch(str.c_str(), re); + } + +#if GTEST_HAS_GLOBAL_STRING + + static bool FullMatch(const ::string& str, const RE& re) { + return FullMatch(str.c_str(), re); + } + static bool PartialMatch(const ::string& str, const RE& re) { + return PartialMatch(str.c_str(), re); + } + +#endif // GTEST_HAS_GLOBAL_STRING + + static bool FullMatch(const char* str, const RE& re); + static bool PartialMatch(const char* str, const RE& re); + + private: + void Init(const char* regex); + + // We use a const char* instead of an std::string, as Google Test used to be + // used where std::string is not available. TODO(wan@google.com): change to + // std::string. + const char* pattern_; + bool is_valid_; + +#if GTEST_USES_POSIX_RE + + regex_t full_regex_; // For FullMatch(). + regex_t partial_regex_; // For PartialMatch(). + +#else // GTEST_USES_SIMPLE_RE + + const char* full_pattern_; // For FullMatch(); + +#endif + + GTEST_DISALLOW_ASSIGN_(RE); +}; + +// Formats a source file path and a line number as they would appear +// in an error message from the compiler used to compile this code. +GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); + +// Formats a file location for compiler-independent XML output. +// Although this function is not platform dependent, we put it next to +// FormatFileLocation in order to contrast the two functions. +GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, + int line); + +// Defines logging utilities: +// GTEST_LOG_(severity) - logs messages at the specified severity level. The +// message itself is streamed into the macro. +// LogToStderr() - directs all log messages to stderr. +// FlushInfoLog() - flushes informational log messages. + +enum GTestLogSeverity { + GTEST_INFO, + GTEST_WARNING, + GTEST_ERROR, + GTEST_FATAL +}; + +// Formats log entry severity, provides a stream object for streaming the +// log message, and terminates the message with a newline when going out of +// scope. +class GTEST_API_ GTestLog { + public: + GTestLog(GTestLogSeverity severity, const char* file, int line); + + // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. + ~GTestLog(); + + ::std::ostream& GetStream() { return ::std::cerr; } + + private: + const GTestLogSeverity severity_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog); +}; + +#define GTEST_LOG_(severity) \ + ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ + __FILE__, __LINE__).GetStream() + +inline void LogToStderr() {} +inline void FlushInfoLog() { fflush(NULL); } + +// INTERNAL IMPLEMENTATION - DO NOT USE. +// +// GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition +// is not satisfied. +// Synopsys: +// GTEST_CHECK_(boolean_condition); +// or +// GTEST_CHECK_(boolean_condition) << "Additional message"; +// +// This checks the condition and if the condition is not satisfied +// it prints message about the condition violation, including the +// condition itself, plus additional message streamed into it, if any, +// and then it aborts the program. It aborts the program irrespective of +// whether it is built in the debug mode or not. +#define GTEST_CHECK_(condition) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::IsTrue(condition)) \ + ; \ + else \ + GTEST_LOG_(FATAL) << "Condition " #condition " failed. " + +// An all-mode assert to verify that the given POSIX-style function +// call returns 0 (indicating success). Known limitation: this +// doesn't expand to a balanced 'if' statement, so enclose the macro +// in {} if you need to use it as the only statement in an 'if' +// branch. +#define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ + if (const int gtest_error = (posix_call)) \ + GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ + << gtest_error + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Use ImplicitCast_ as a safe version of static_cast for upcasting in +// the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a +// const Foo*). When you use ImplicitCast_, the compiler checks that +// the cast is safe. Such explicit ImplicitCast_s are necessary in +// surprisingly many situations where C++ demands an exact type match +// instead of an argument type convertable to a target type. +// +// The syntax for using ImplicitCast_ is the same as for static_cast: +// +// ImplicitCast_(expr) +// +// ImplicitCast_ would have been part of the C++ standard library, +// but the proposal was submitted too late. It will probably make +// its way into the language in the future. +// +// This relatively ugly name is intentional. It prevents clashes with +// similar functions users may have (e.g., implicit_cast). The internal +// namespace alone is not enough because the function can be found by ADL. +template +inline To ImplicitCast_(To x) { return x; } + +// When you upcast (that is, cast a pointer from type Foo to type +// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts +// always succeed. When you downcast (that is, cast a pointer from +// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because +// how do you know the pointer is really of type SubclassOfFoo? It +// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, +// when you downcast, you should use this macro. In debug mode, we +// use dynamic_cast<> to double-check the downcast is legal (we die +// if it's not). In normal mode, we do the efficient static_cast<> +// instead. Thus, it's important to test in debug mode to make sure +// the cast is legal! +// This is the only place in the code we should use dynamic_cast<>. +// In particular, you SHOULDN'T be using dynamic_cast<> in order to +// do RTTI (eg code like this: +// if (dynamic_cast(foo)) HandleASubclass1Object(foo); +// if (dynamic_cast(foo)) HandleASubclass2Object(foo); +// You should design the code some other way not to need this. +// +// This relatively ugly name is intentional. It prevents clashes with +// similar functions users may have (e.g., down_cast). The internal +// namespace alone is not enough because the function can be found by ADL. +template // use like this: DownCast_(foo); +inline To DownCast_(From* f) { // so we only accept pointers + // Ensures that To is a sub-type of From *. This test is here only + // for compile-time type checking, and has no overhead in an + // optimized build at run-time, as it will be optimized away + // completely. + if (false) { + const To to = NULL; + ::testing::internal::ImplicitCast_(to); + } + +#if GTEST_HAS_RTTI + // RTTI: debug mode only! + GTEST_CHECK_(f == NULL || dynamic_cast(f) != NULL); +#endif + return static_cast(f); +} + +// Downcasts the pointer of type Base to Derived. +// Derived must be a subclass of Base. The parameter MUST +// point to a class of type Derived, not any subclass of it. +// When RTTI is available, the function performs a runtime +// check to enforce this. +template +Derived* CheckedDowncastToActualType(Base* base) { +#if GTEST_HAS_RTTI + GTEST_CHECK_(typeid(*base) == typeid(Derived)); + return dynamic_cast(base); // NOLINT +#else + return static_cast(base); // Poor man's downcast. +#endif +} + +#if GTEST_HAS_STREAM_REDIRECTION + +// Defines the stderr capturer: +// CaptureStdout - starts capturing stdout. +// GetCapturedStdout - stops capturing stdout and returns the captured string. +// CaptureStderr - starts capturing stderr. +// GetCapturedStderr - stops capturing stderr and returns the captured string. +// +GTEST_API_ void CaptureStdout(); +GTEST_API_ std::string GetCapturedStdout(); +GTEST_API_ void CaptureStderr(); +GTEST_API_ std::string GetCapturedStderr(); + +#endif // GTEST_HAS_STREAM_REDIRECTION + + +#if GTEST_HAS_DEATH_TEST + +const ::std::vector& GetInjectableArgvs(); +void SetInjectableArgvs(const ::std::vector* + new_argvs); + +// A copy of all command line arguments. Set by InitGoogleTest(). +extern ::std::vector g_argvs; + +#endif // GTEST_HAS_DEATH_TEST + +// Defines synchronization primitives. + +#if GTEST_HAS_PTHREAD + +// Sleeps for (roughly) n milli-seconds. This function is only for +// testing Google Test's own constructs. Don't use it in user tests, +// either directly or indirectly. +inline void SleepMilliseconds(int n) { + const timespec time = { + 0, // 0 seconds. + n * 1000L * 1000L, // And n ms. + }; + nanosleep(&time, NULL); +} + +// Allows a controller thread to pause execution of newly created +// threads until notified. Instances of this class must be created +// and destroyed in the controller thread. +// +// This class is only for testing Google Test's own constructs. Do not +// use it in user tests, either directly or indirectly. +class Notification { + public: + Notification() : notified_(false) { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); + } + ~Notification() { + pthread_mutex_destroy(&mutex_); + } + + // Notifies all threads created with this notification to start. Must + // be called from the controller thread. + void Notify() { + pthread_mutex_lock(&mutex_); + notified_ = true; + pthread_mutex_unlock(&mutex_); + } + + // Blocks until the controller thread notifies. Must be called from a test + // thread. + void WaitForNotification() { + for (;;) { + pthread_mutex_lock(&mutex_); + const bool notified = notified_; + pthread_mutex_unlock(&mutex_); + if (notified) + break; + SleepMilliseconds(10); + } + } + + private: + pthread_mutex_t mutex_; + bool notified_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); +}; + +// As a C-function, ThreadFuncWithCLinkage cannot be templated itself. +// Consequently, it cannot select a correct instantiation of ThreadWithParam +// in order to call its Run(). Introducing ThreadWithParamBase as a +// non-templated base class for ThreadWithParam allows us to bypass this +// problem. +class ThreadWithParamBase { + public: + virtual ~ThreadWithParamBase() {} + virtual void Run() = 0; +}; + +// pthread_create() accepts a pointer to a function type with the C linkage. +// According to the Standard (7.5/1), function types with different linkages +// are different even if they are otherwise identical. Some compilers (for +// example, SunStudio) treat them as different types. Since class methods +// cannot be defined with C-linkage we need to define a free C-function to +// pass into pthread_create(). +extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { + static_cast(thread)->Run(); + return NULL; +} + +// Helper class for testing Google Test's multi-threading constructs. +// To use it, write: +// +// void ThreadFunc(int param) { /* Do things with param */ } +// Notification thread_can_start; +// ... +// // The thread_can_start parameter is optional; you can supply NULL. +// ThreadWithParam thread(&ThreadFunc, 5, &thread_can_start); +// thread_can_start.Notify(); +// +// These classes are only for testing Google Test's own constructs. Do +// not use them in user tests, either directly or indirectly. +template +class ThreadWithParam : public ThreadWithParamBase { + public: + typedef void (*UserThreadFunc)(T); + + ThreadWithParam( + UserThreadFunc func, T param, Notification* thread_can_start) + : func_(func), + param_(param), + thread_can_start_(thread_can_start), + finished_(false) { + ThreadWithParamBase* const base = this; + // The thread can be created only after all fields except thread_ + // have been initialized. + GTEST_CHECK_POSIX_SUCCESS_( + pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base)); + } + ~ThreadWithParam() { Join(); } + + void Join() { + if (!finished_) { + GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0)); + finished_ = true; + } + } + + virtual void Run() { + if (thread_can_start_ != NULL) + thread_can_start_->WaitForNotification(); + func_(param_); + } + + private: + const UserThreadFunc func_; // User-supplied thread function. + const T param_; // User-supplied parameter to the thread function. + // When non-NULL, used to block execution until the controller thread + // notifies. + Notification* const thread_can_start_; + bool finished_; // true iff we know that the thread function has finished. + pthread_t thread_; // The native thread object. + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); +}; + +// MutexBase and Mutex implement mutex on pthreads-based platforms. They +// are used in conjunction with class MutexLock: +// +// Mutex mutex; +// ... +// MutexLock lock(&mutex); // Acquires the mutex and releases it at the end +// // of the current scope. +// +// MutexBase implements behavior for both statically and dynamically +// allocated mutexes. Do not use MutexBase directly. Instead, write +// the following to define a static mutex: +// +// GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex); +// +// You can forward declare a static mutex like this: +// +// GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); +// +// To create a dynamic mutex, just define an object of type Mutex. +class MutexBase { + public: + // Acquires this mutex. + void Lock() { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); + owner_ = pthread_self(); + has_owner_ = true; + } + + // Releases this mutex. + void Unlock() { + // Since the lock is being released the owner_ field should no longer be + // considered valid. We don't protect writing to has_owner_ here, as it's + // the caller's responsibility to ensure that the current thread holds the + // mutex when this is called. + has_owner_ = false; + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_)); + } + + // Does nothing if the current thread holds the mutex. Otherwise, crashes + // with high probability. + void AssertHeld() const { + GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self())) + << "The current thread is not holding the mutex @" << this; + } + + // A static mutex may be used before main() is entered. It may even + // be used before the dynamic initialization stage. Therefore we + // must be able to initialize a static mutex object at link time. + // This means MutexBase has to be a POD and its member variables + // have to be public. + public: + pthread_mutex_t mutex_; // The underlying pthread mutex. + // has_owner_ indicates whether the owner_ field below contains a valid thread + // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All + // accesses to the owner_ field should be protected by a check of this field. + // An alternative might be to memset() owner_ to all zeros, but there's no + // guarantee that a zero'd pthread_t is necessarily invalid or even different + // from pthread_self(). + bool has_owner_; + pthread_t owner_; // The thread holding the mutex. +}; + +// Forward-declares a static mutex. +# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ + extern ::testing::internal::MutexBase mutex + +// Defines and statically (i.e. at link time) initializes a static mutex. +// The initialization list here does not explicitly initialize each field, +// instead relying on default initialization for the unspecified fields. In +// particular, the owner_ field (a pthread_t) is not explicitly initialized. +// This allows initialization to work whether pthread_t is a scalar or struct. +// The flag -Wmissing-field-initializers must not be specified for this to work. +# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ + ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false } + +// The Mutex class can only be used for mutexes created at runtime. It +// shares its API with MutexBase otherwise. +class Mutex : public MutexBase { + public: + Mutex() { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); + has_owner_ = false; + } + ~Mutex() { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); + } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); +}; + +// We cannot name this class MutexLock as the ctor declaration would +// conflict with a macro named MutexLock, which is defined on some +// platforms. Hence the typedef trick below. +class GTestMutexLock { + public: + explicit GTestMutexLock(MutexBase* mutex) + : mutex_(mutex) { mutex_->Lock(); } + + ~GTestMutexLock() { mutex_->Unlock(); } + + private: + MutexBase* const mutex_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); +}; + +typedef GTestMutexLock MutexLock; + +// Helpers for ThreadLocal. + +// pthread_key_create() requires DeleteThreadLocalValue() to have +// C-linkage. Therefore it cannot be templatized to access +// ThreadLocal. Hence the need for class +// ThreadLocalValueHolderBase. +class ThreadLocalValueHolderBase { + public: + virtual ~ThreadLocalValueHolderBase() {} +}; + +// Called by pthread to delete thread-local data stored by +// pthread_setspecific(). +extern "C" inline void DeleteThreadLocalValue(void* value_holder) { + delete static_cast(value_holder); +} + +// Implements thread-local storage on pthreads-based systems. +// +// // Thread 1 +// ThreadLocal tl(100); // 100 is the default value for each thread. +// +// // Thread 2 +// tl.set(150); // Changes the value for thread 2 only. +// EXPECT_EQ(150, tl.get()); +// +// // Thread 1 +// EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. +// tl.set(200); +// EXPECT_EQ(200, tl.get()); +// +// The template type argument T must have a public copy constructor. +// In addition, the default ThreadLocal constructor requires T to have +// a public default constructor. +// +// An object managed for a thread by a ThreadLocal instance is deleted +// when the thread exits. Or, if the ThreadLocal instance dies in +// that thread, when the ThreadLocal dies. It's the user's +// responsibility to ensure that all other threads using a ThreadLocal +// have exited when it dies, or the per-thread objects for those +// threads will not be deleted. +// +// Google Test only uses global ThreadLocal objects. That means they +// will die after main() has returned. Therefore, no per-thread +// object managed by Google Test will be leaked as long as all threads +// using Google Test have exited when main() returns. +template +class ThreadLocal { + public: + ThreadLocal() : key_(CreateKey()), + default_() {} + explicit ThreadLocal(const T& value) : key_(CreateKey()), + default_(value) {} + + ~ThreadLocal() { + // Destroys the managed object for the current thread, if any. + DeleteThreadLocalValue(pthread_getspecific(key_)); + + // Releases resources associated with the key. This will *not* + // delete managed objects for other threads. + GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_)); + } + + T* pointer() { return GetOrCreateValue(); } + const T* pointer() const { return GetOrCreateValue(); } + const T& get() const { return *pointer(); } + void set(const T& value) { *pointer() = value; } + + private: + // Holds a value of type T. + class ValueHolder : public ThreadLocalValueHolderBase { + public: + explicit ValueHolder(const T& value) : value_(value) {} + + T* pointer() { return &value_; } + + private: + T value_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); + }; + + static pthread_key_t CreateKey() { + pthread_key_t key; + // When a thread exits, DeleteThreadLocalValue() will be called on + // the object managed for that thread. + GTEST_CHECK_POSIX_SUCCESS_( + pthread_key_create(&key, &DeleteThreadLocalValue)); + return key; + } + + T* GetOrCreateValue() const { + ThreadLocalValueHolderBase* const holder = + static_cast(pthread_getspecific(key_)); + if (holder != NULL) { + return CheckedDowncastToActualType(holder)->pointer(); + } + + ValueHolder* const new_holder = new ValueHolder(default_); + ThreadLocalValueHolderBase* const holder_base = new_holder; + GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base)); + return new_holder->pointer(); + } + + // A key pthreads uses for looking up per-thread values. + const pthread_key_t key_; + const T default_; // The default value for each thread. + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); +}; + +# define GTEST_IS_THREADSAFE 1 + +#else // GTEST_HAS_PTHREAD + +// A dummy implementation of synchronization primitives (mutex, lock, +// and thread-local variable). Necessary for compiling Google Test where +// mutex is not supported - using Google Test in multiple threads is not +// supported on such platforms. + +class Mutex { + public: + Mutex() {} + void Lock() {} + void Unlock() {} + void AssertHeld() const {} +}; + +# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ + extern ::testing::internal::Mutex mutex + +# define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex + +class GTestMutexLock { + public: + explicit GTestMutexLock(Mutex*) {} // NOLINT +}; + +typedef GTestMutexLock MutexLock; + +template +class ThreadLocal { + public: + ThreadLocal() : value_() {} + explicit ThreadLocal(const T& value) : value_(value) {} + T* pointer() { return &value_; } + const T* pointer() const { return &value_; } + const T& get() const { return value_; } + void set(const T& value) { value_ = value; } + private: + T value_; +}; + +// The above synchronization primitives have dummy implementations. +// Therefore Google Test is not thread-safe. +# define GTEST_IS_THREADSAFE 0 + +#endif // GTEST_HAS_PTHREAD + +// Returns the number of threads running in the process, or 0 to indicate that +// we cannot detect it. +GTEST_API_ size_t GetThreadCount(); + +// Passing non-POD classes through ellipsis (...) crashes the ARM +// compiler and generates a warning in Sun Studio. The Nokia Symbian +// and the IBM XL C/C++ compiler try to instantiate a copy constructor +// for objects passed through ellipsis (...), failing for uncopyable +// objects. We define this to ensure that only POD is passed through +// ellipsis on these systems. +#if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC) +// We lose support for NULL detection where the compiler doesn't like +// passing non-POD classes through ellipsis (...). +# define GTEST_ELLIPSIS_NEEDS_POD_ 1 +#else +# define GTEST_CAN_COMPARE_NULL 1 +#endif + +// The Nokia Symbian and IBM XL C/C++ compilers cannot decide between +// const T& and const T* in a function template. These compilers +// _can_ decide between class template specializations for T and T*, +// so a tr1::type_traits-like is_pointer works. +#if defined(__SYMBIAN32__) || defined(__IBMCPP__) +# define GTEST_NEEDS_IS_POINTER_ 1 +#endif + +template +struct bool_constant { + typedef bool_constant type; + static const bool value = bool_value; +}; +template const bool bool_constant::value; + +typedef bool_constant false_type; +typedef bool_constant true_type; + +template +struct is_pointer : public false_type {}; + +template +struct is_pointer : public true_type {}; + +template +struct IteratorTraits { + typedef typename Iterator::value_type value_type; +}; + +template +struct IteratorTraits { + typedef T value_type; +}; + +template +struct IteratorTraits { + typedef T value_type; +}; + +#if GTEST_OS_WINDOWS +# define GTEST_PATH_SEP_ "\\" +# define GTEST_HAS_ALT_PATH_SEP_ 1 +// The biggest signed integer type the compiler supports. +typedef __int64 BiggestInt; +#else +# define GTEST_PATH_SEP_ "/" +# define GTEST_HAS_ALT_PATH_SEP_ 0 +typedef long long BiggestInt; // NOLINT +#endif // GTEST_OS_WINDOWS + +// Utilities for char. + +// isspace(int ch) and friends accept an unsigned char or EOF. char +// may be signed, depending on the compiler (or compiler flags). +// Therefore we need to cast a char to unsigned char before calling +// isspace(), etc. + +inline bool IsAlpha(char ch) { + return isalpha(static_cast(ch)) != 0; +} +inline bool IsAlNum(char ch) { + return isalnum(static_cast(ch)) != 0; +} +inline bool IsDigit(char ch) { + return isdigit(static_cast(ch)) != 0; +} +inline bool IsLower(char ch) { + return islower(static_cast(ch)) != 0; +} +inline bool IsSpace(char ch) { + return isspace(static_cast(ch)) != 0; +} +inline bool IsUpper(char ch) { + return isupper(static_cast(ch)) != 0; +} +inline bool IsXDigit(char ch) { + return isxdigit(static_cast(ch)) != 0; +} +inline bool IsXDigit(wchar_t ch) { + const unsigned char low_byte = static_cast(ch); + return ch == low_byte && isxdigit(low_byte) != 0; +} + +inline char ToLower(char ch) { + return static_cast(tolower(static_cast(ch))); +} +inline char ToUpper(char ch) { + return static_cast(toupper(static_cast(ch))); +} + +// The testing::internal::posix namespace holds wrappers for common +// POSIX functions. These wrappers hide the differences between +// Windows/MSVC and POSIX systems. Since some compilers define these +// standard functions as macros, the wrapper cannot have the same name +// as the wrapped function. + +namespace posix { + +// Functions with a different name on Windows. + +#if GTEST_OS_WINDOWS + +typedef struct _stat StatStruct; + +# ifdef __BORLANDC__ +inline int IsATTY(int fd) { return isatty(fd); } +inline int StrCaseCmp(const char* s1, const char* s2) { + return stricmp(s1, s2); +} +inline char* StrDup(const char* src) { return strdup(src); } +# else // !__BORLANDC__ +# if GTEST_OS_WINDOWS_MOBILE +inline int IsATTY(int /* fd */) { return 0; } +# else +inline int IsATTY(int fd) { return _isatty(fd); } +# endif // GTEST_OS_WINDOWS_MOBILE +inline int StrCaseCmp(const char* s1, const char* s2) { + return _stricmp(s1, s2); +} +inline char* StrDup(const char* src) { return _strdup(src); } +# endif // __BORLANDC__ + +# if GTEST_OS_WINDOWS_MOBILE +inline int FileNo(FILE* file) { return reinterpret_cast(_fileno(file)); } +// Stat(), RmDir(), and IsDir() are not needed on Windows CE at this +// time and thus not defined there. +# else +inline int FileNo(FILE* file) { return _fileno(file); } +inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } +inline int RmDir(const char* dir) { return _rmdir(dir); } +inline bool IsDir(const StatStruct& st) { + return (_S_IFDIR & st.st_mode) != 0; +} +# endif // GTEST_OS_WINDOWS_MOBILE + +#else + +typedef struct stat StatStruct; + +inline int FileNo(FILE* file) { return fileno(file); } +inline int IsATTY(int fd) { return isatty(fd); } +inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } +inline int StrCaseCmp(const char* s1, const char* s2) { + return strcasecmp(s1, s2); +} +inline char* StrDup(const char* src) { return strdup(src); } +inline int RmDir(const char* dir) { return rmdir(dir); } +inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } + +#endif // GTEST_OS_WINDOWS + +// Functions deprecated by MSVC 8.0. + +#ifdef _MSC_VER +// Temporarily disable warning 4996 (deprecated function). +# pragma warning(push) +# pragma warning(disable:4996) +#endif + +inline const char* StrNCpy(char* dest, const char* src, size_t n) { + return strncpy(dest, src, n); +} + +// ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and +// StrError() aren't needed on Windows CE at this time and thus not +// defined there. + +#if !GTEST_OS_WINDOWS_MOBILE +inline int ChDir(const char* dir) { return chdir(dir); } +#endif +inline FILE* FOpen(const char* path, const char* mode) { + return fopen(path, mode); +} +#if !GTEST_OS_WINDOWS_MOBILE +inline FILE *FReopen(const char* path, const char* mode, FILE* stream) { + return freopen(path, mode, stream); +} +inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } +#endif +inline int FClose(FILE* fp) { return fclose(fp); } +#if !GTEST_OS_WINDOWS_MOBILE +inline int Read(int fd, void* buf, unsigned int count) { + return static_cast(read(fd, buf, count)); +} +inline int Write(int fd, const void* buf, unsigned int count) { + return static_cast(write(fd, buf, count)); +} +inline int Close(int fd) { return close(fd); } +inline const char* StrError(int errnum) { return strerror(errnum); } +#endif +inline const char* GetEnv(const char* name) { +#if GTEST_OS_WINDOWS_MOBILE + // We are on Windows CE, which has no environment variables. + return NULL; +#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) + // Environment variables which we programmatically clear will be set to the + // empty string rather than unset (NULL). Handle that case. + const char* const env = getenv(name); + return (env != NULL && env[0] != '\0') ? env : NULL; +#else + return getenv(name); +#endif +} + +#ifdef _MSC_VER +# pragma warning(pop) // Restores the warning state. +#endif + +#if GTEST_OS_WINDOWS_MOBILE +// Windows CE has no C library. The abort() function is used in +// several places in Google Test. This implementation provides a reasonable +// imitation of standard behaviour. +void Abort(); +#else +inline void Abort() { abort(); } +#endif // GTEST_OS_WINDOWS_MOBILE + +} // namespace posix + +// MSVC "deprecates" snprintf and issues warnings wherever it is used. In +// order to avoid these warnings, we need to use _snprintf or _snprintf_s on +// MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate +// function in order to achieve that. We use macro definition here because +// snprintf is a variadic function. +#if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE +// MSVC 2005 and above support variadic macros. +# define GTEST_SNPRINTF_(buffer, size, format, ...) \ + _snprintf_s(buffer, size, size, format, __VA_ARGS__) +#elif defined(_MSC_VER) +// Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't +// complain about _snprintf. +# define GTEST_SNPRINTF_ _snprintf +#else +# define GTEST_SNPRINTF_ snprintf +#endif + +// The maximum number a BiggestInt can represent. This definition +// works no matter BiggestInt is represented in one's complement or +// two's complement. +// +// We cannot rely on numeric_limits in STL, as __int64 and long long +// are not part of standard C++ and numeric_limits doesn't need to be +// defined for them. +const BiggestInt kMaxBiggestInt = + ~(static_cast(1) << (8*sizeof(BiggestInt) - 1)); + +// This template class serves as a compile-time function from size to +// type. It maps a size in bytes to a primitive type with that +// size. e.g. +// +// TypeWithSize<4>::UInt +// +// is typedef-ed to be unsigned int (unsigned integer made up of 4 +// bytes). +// +// Such functionality should belong to STL, but I cannot find it +// there. +// +// Google Test uses this class in the implementation of floating-point +// comparison. +// +// For now it only handles UInt (unsigned int) as that's all Google Test +// needs. Other types can be easily added in the future if need +// arises. +template +class TypeWithSize { + public: + // This prevents the user from using TypeWithSize with incorrect + // values of N. + typedef void UInt; +}; + +// The specialization for size 4. +template <> +class TypeWithSize<4> { + public: + // unsigned int has size 4 in both gcc and MSVC. + // + // As base/basictypes.h doesn't compile on Windows, we cannot use + // uint32, uint64, and etc here. + typedef int Int; + typedef unsigned int UInt; +}; + +// The specialization for size 8. +template <> +class TypeWithSize<8> { + public: +#if GTEST_OS_WINDOWS + typedef __int64 Int; + typedef unsigned __int64 UInt; +#else + typedef long long Int; // NOLINT + typedef unsigned long long UInt; // NOLINT +#endif // GTEST_OS_WINDOWS +}; + +// Integer types of known sizes. +typedef TypeWithSize<4>::Int Int32; +typedef TypeWithSize<4>::UInt UInt32; +typedef TypeWithSize<8>::Int Int64; +typedef TypeWithSize<8>::UInt UInt64; +typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. + +// Utilities for command line flags and environment variables. + +// Macro for referencing flags. +#define GTEST_FLAG(name) FLAGS_gtest_##name + +// Macros for declaring flags. +#define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) +#define GTEST_DECLARE_int32_(name) \ + GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) +#define GTEST_DECLARE_string_(name) \ + GTEST_API_ extern ::std::string GTEST_FLAG(name) + +// Macros for defining flags. +#define GTEST_DEFINE_bool_(name, default_val, doc) \ + GTEST_API_ bool GTEST_FLAG(name) = (default_val) +#define GTEST_DEFINE_int32_(name, default_val, doc) \ + GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) +#define GTEST_DEFINE_string_(name, default_val, doc) \ + GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val) + +// Thread annotations +#define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) +#define GTEST_LOCK_EXCLUDED_(locks) + +// Parses 'str' for a 32-bit signed integer. If successful, writes the result +// to *value and returns true; otherwise leaves *value unchanged and returns +// false. +// TODO(chandlerc): Find a better way to refactor flag and environment parsing +// out of both gtest-port.cc and gtest.cc to avoid exporting this utility +// function. +bool ParseInt32(const Message& src_text, const char* str, Int32* value); + +// Parses a bool/Int32/string from the environment variable +// corresponding to the given Google Test flag. +bool BoolFromGTestEnv(const char* flag, bool default_val); +GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); +const char* StringFromGTestEnv(const char* flag, const char* default_val); + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ diff --git a/lib/gtest/include/gtest/internal/gtest-string.h b/lib/gtest/include/gtest/internal/gtest-string.h new file mode 100644 index 00000000..97f1a7fd --- /dev/null +++ b/lib/gtest/include/gtest/internal/gtest-string.h @@ -0,0 +1,167 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file declares the String class and functions used internally by +// Google Test. They are subject to change without notice. They should not used +// by code external to Google Test. +// +// This header file is #included by . +// It should not be #included by other files. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ + +#ifdef __BORLANDC__ +// string.h is not guaranteed to provide strcpy on C++ Builder. +# include +#endif + +#include +#include + +#include "gtest/internal/gtest-port.h" + +namespace testing { +namespace internal { + +// String - an abstract class holding static string utilities. +class GTEST_API_ String { + public: + // Static utility methods + + // Clones a 0-terminated C string, allocating memory using new. The + // caller is responsible for deleting the return value using + // delete[]. Returns the cloned string, or NULL if the input is + // NULL. + // + // This is different from strdup() in string.h, which allocates + // memory using malloc(). + static const char* CloneCString(const char* c_str); + +#if GTEST_OS_WINDOWS_MOBILE + // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be + // able to pass strings to Win32 APIs on CE we need to convert them + // to 'Unicode', UTF-16. + + // Creates a UTF-16 wide string from the given ANSI string, allocating + // memory using new. The caller is responsible for deleting the return + // value using delete[]. Returns the wide string, or NULL if the + // input is NULL. + // + // The wide string is created using the ANSI codepage (CP_ACP) to + // match the behaviour of the ANSI versions of Win32 calls and the + // C runtime. + static LPCWSTR AnsiToUtf16(const char* c_str); + + // Creates an ANSI string from the given wide string, allocating + // memory using new. The caller is responsible for deleting the return + // value using delete[]. Returns the ANSI string, or NULL if the + // input is NULL. + // + // The returned string is created using the ANSI codepage (CP_ACP) to + // match the behaviour of the ANSI versions of Win32 calls and the + // C runtime. + static const char* Utf16ToAnsi(LPCWSTR utf16_str); +#endif + + // Compares two C strings. Returns true iff they have the same content. + // + // Unlike strcmp(), this function can handle NULL argument(s). A + // NULL C string is considered different to any non-NULL C string, + // including the empty string. + static bool CStringEquals(const char* lhs, const char* rhs); + + // Converts a wide C string to a String using the UTF-8 encoding. + // NULL will be converted to "(null)". If an error occurred during + // the conversion, "(failed to convert from wide string)" is + // returned. + static std::string ShowWideCString(const wchar_t* wide_c_str); + + // Compares two wide C strings. Returns true iff they have the same + // content. + // + // Unlike wcscmp(), this function can handle NULL argument(s). A + // NULL C string is considered different to any non-NULL C string, + // including the empty string. + static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); + + // Compares two C strings, ignoring case. Returns true iff they + // have the same content. + // + // Unlike strcasecmp(), this function can handle NULL argument(s). + // A NULL C string is considered different to any non-NULL C string, + // including the empty string. + static bool CaseInsensitiveCStringEquals(const char* lhs, + const char* rhs); + + // Compares two wide C strings, ignoring case. Returns true iff they + // have the same content. + // + // Unlike wcscasecmp(), this function can handle NULL argument(s). + // A NULL C string is considered different to any non-NULL wide C string, + // including the empty string. + // NB: The implementations on different platforms slightly differ. + // On windows, this method uses _wcsicmp which compares according to LC_CTYPE + // environment variable. On GNU platform this method uses wcscasecmp + // which compares according to LC_CTYPE category of the current locale. + // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the + // current locale. + static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, + const wchar_t* rhs); + + // Returns true iff the given string ends with the given suffix, ignoring + // case. Any string is considered to end with an empty suffix. + static bool EndsWithCaseInsensitive( + const std::string& str, const std::string& suffix); + + // Formats an int value as "%02d". + static std::string FormatIntWidth2(int value); // "%02d" for width == 2 + + // Formats an int value as "%X". + static std::string FormatHexInt(int value); + + // Formats a byte as "%02X". + static std::string FormatByte(unsigned char value); + + private: + String(); // Not meant to be instantiated. +}; // class String + +// Gets the content of the stringstream's buffer as an std::string. Each '\0' +// character in the buffer is replaced with "\\0". +GTEST_API_ std::string StringStreamToString(::std::stringstream* stream); + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ diff --git a/lib/gtest/include/gtest/internal/gtest-tuple.h b/lib/gtest/include/gtest/internal/gtest-tuple.h new file mode 100644 index 00000000..7b3dfc31 --- /dev/null +++ b/lib/gtest/include/gtest/internal/gtest-tuple.h @@ -0,0 +1,1012 @@ +// This file was GENERATED by command: +// pump.py gtest-tuple.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2009 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Implements a subset of TR1 tuple needed by Google Test and Google Mock. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ + +#include // For ::std::pair. + +// The compiler used in Symbian has a bug that prevents us from declaring the +// tuple template as a friend (it complains that tuple is redefined). This +// hack bypasses the bug by declaring the members that should otherwise be +// private as public. +// Sun Studio versions < 12 also have the above bug. +#if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) +# define GTEST_DECLARE_TUPLE_AS_FRIEND_ public: +#else +# define GTEST_DECLARE_TUPLE_AS_FRIEND_ \ + template friend class tuple; \ + private: +#endif + +// GTEST_n_TUPLE_(T) is the type of an n-tuple. +#define GTEST_0_TUPLE_(T) tuple<> +#define GTEST_1_TUPLE_(T) tuple +#define GTEST_2_TUPLE_(T) tuple +#define GTEST_3_TUPLE_(T) tuple +#define GTEST_4_TUPLE_(T) tuple +#define GTEST_5_TUPLE_(T) tuple +#define GTEST_6_TUPLE_(T) tuple +#define GTEST_7_TUPLE_(T) tuple +#define GTEST_8_TUPLE_(T) tuple +#define GTEST_9_TUPLE_(T) tuple +#define GTEST_10_TUPLE_(T) tuple + +// GTEST_n_TYPENAMES_(T) declares a list of n typenames. +#define GTEST_0_TYPENAMES_(T) +#define GTEST_1_TYPENAMES_(T) typename T##0 +#define GTEST_2_TYPENAMES_(T) typename T##0, typename T##1 +#define GTEST_3_TYPENAMES_(T) typename T##0, typename T##1, typename T##2 +#define GTEST_4_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3 +#define GTEST_5_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4 +#define GTEST_6_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5 +#define GTEST_7_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5, typename T##6 +#define GTEST_8_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5, typename T##6, typename T##7 +#define GTEST_9_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5, typename T##6, \ + typename T##7, typename T##8 +#define GTEST_10_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5, typename T##6, \ + typename T##7, typename T##8, typename T##9 + +// In theory, defining stuff in the ::std namespace is undefined +// behavior. We can do this as we are playing the role of a standard +// library vendor. +namespace std { +namespace tr1 { + +template +class tuple; + +// Anything in namespace gtest_internal is Google Test's INTERNAL +// IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code. +namespace gtest_internal { + +// ByRef::type is T if T is a reference; otherwise it's const T&. +template +struct ByRef { typedef const T& type; }; // NOLINT +template +struct ByRef { typedef T& type; }; // NOLINT + +// A handy wrapper for ByRef. +#define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef::type + +// AddRef::type is T if T is a reference; otherwise it's T&. This +// is the same as tr1::add_reference::type. +template +struct AddRef { typedef T& type; }; // NOLINT +template +struct AddRef { typedef T& type; }; // NOLINT + +// A handy wrapper for AddRef. +#define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef::type + +// A helper for implementing get(). +template class Get; + +// A helper for implementing tuple_element. kIndexValid is true +// iff k < the number of fields in tuple type T. +template +struct TupleElement; + +template +struct TupleElement { + typedef T0 type; +}; + +template +struct TupleElement { + typedef T1 type; +}; + +template +struct TupleElement { + typedef T2 type; +}; + +template +struct TupleElement { + typedef T3 type; +}; + +template +struct TupleElement { + typedef T4 type; +}; + +template +struct TupleElement { + typedef T5 type; +}; + +template +struct TupleElement { + typedef T6 type; +}; + +template +struct TupleElement { + typedef T7 type; +}; + +template +struct TupleElement { + typedef T8 type; +}; + +template +struct TupleElement { + typedef T9 type; +}; + +} // namespace gtest_internal + +template <> +class tuple<> { + public: + tuple() {} + tuple(const tuple& /* t */) {} + tuple& operator=(const tuple& /* t */) { return *this; } +}; + +template +class GTEST_1_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0) : f0_(f0) {} + + tuple(const tuple& t) : f0_(t.f0_) {} + + template + tuple(const GTEST_1_TUPLE_(U)& t) : f0_(t.f0_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_1_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_1_TUPLE_(U)& t) { + f0_ = t.f0_; + return *this; + } + + T0 f0_; +}; + +template +class GTEST_2_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1) : f0_(f0), + f1_(f1) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_) {} + + template + tuple(const GTEST_2_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_) {} + template + tuple(const ::std::pair& p) : f0_(p.first), f1_(p.second) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_2_TUPLE_(U)& t) { + return CopyFrom(t); + } + template + tuple& operator=(const ::std::pair& p) { + f0_ = p.first; + f1_ = p.second; + return *this; + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_2_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + return *this; + } + + T0 f0_; + T1 f1_; +}; + +template +class GTEST_3_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2) : f0_(f0), f1_(f1), f2_(f2) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} + + template + tuple(const GTEST_3_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_3_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_3_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; +}; + +template +class GTEST_4_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3) : f0_(f0), f1_(f1), f2_(f2), + f3_(f3) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_) {} + + template + tuple(const GTEST_4_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_4_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_4_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; +}; + +template +class GTEST_5_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, + GTEST_BY_REF_(T4) f4) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_) {} + + template + tuple(const GTEST_5_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_5_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_5_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; +}; + +template +class GTEST_6_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), + f5_(f5) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_) {} + + template + tuple(const GTEST_6_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_6_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_6_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; +}; + +template +class GTEST_7_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6) : f0_(f0), f1_(f1), f2_(f2), + f3_(f3), f4_(f4), f5_(f5), f6_(f6) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} + + template + tuple(const GTEST_7_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_7_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_7_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + f6_ = t.f6_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; + T6 f6_; +}; + +template +class GTEST_8_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, + GTEST_BY_REF_(T7) f7) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), + f5_(f5), f6_(f6), f7_(f7) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} + + template + tuple(const GTEST_8_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_8_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_8_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + f6_ = t.f6_; + f7_ = t.f7_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; + T6 f6_; + T7 f7_; +}; + +template +class GTEST_9_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, + GTEST_BY_REF_(T8) f8) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), + f5_(f5), f6_(f6), f7_(f7), f8_(f8) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} + + template + tuple(const GTEST_9_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_9_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_9_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + f6_ = t.f6_; + f7_ = t.f7_; + f8_ = t.f8_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; + T6 f6_; + T7 f7_; + T8 f8_; +}; + +template +class tuple { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_(), + f9_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, + GTEST_BY_REF_(T8) f8, GTEST_BY_REF_(T9) f9) : f0_(f0), f1_(f1), f2_(f2), + f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8), f9_(f9) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), f9_(t.f9_) {} + + template + tuple(const GTEST_10_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), + f9_(t.f9_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_10_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_10_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + f6_ = t.f6_; + f7_ = t.f7_; + f8_ = t.f8_; + f9_ = t.f9_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; + T6 f6_; + T7 f7_; + T8 f8_; + T9 f9_; +}; + +// 6.1.3.2 Tuple creation functions. + +// Known limitations: we don't support passing an +// std::tr1::reference_wrapper to make_tuple(). And we don't +// implement tie(). + +inline tuple<> make_tuple() { return tuple<>(); } + +template +inline GTEST_1_TUPLE_(T) make_tuple(const T0& f0) { + return GTEST_1_TUPLE_(T)(f0); +} + +template +inline GTEST_2_TUPLE_(T) make_tuple(const T0& f0, const T1& f1) { + return GTEST_2_TUPLE_(T)(f0, f1); +} + +template +inline GTEST_3_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2) { + return GTEST_3_TUPLE_(T)(f0, f1, f2); +} + +template +inline GTEST_4_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3) { + return GTEST_4_TUPLE_(T)(f0, f1, f2, f3); +} + +template +inline GTEST_5_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4) { + return GTEST_5_TUPLE_(T)(f0, f1, f2, f3, f4); +} + +template +inline GTEST_6_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5) { + return GTEST_6_TUPLE_(T)(f0, f1, f2, f3, f4, f5); +} + +template +inline GTEST_7_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5, const T6& f6) { + return GTEST_7_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6); +} + +template +inline GTEST_8_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7) { + return GTEST_8_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7); +} + +template +inline GTEST_9_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, + const T8& f8) { + return GTEST_9_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8); +} + +template +inline GTEST_10_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, + const T8& f8, const T9& f9) { + return GTEST_10_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9); +} + +// 6.1.3.3 Tuple helper classes. + +template struct tuple_size; + +template +struct tuple_size { + static const int value = 0; +}; + +template +struct tuple_size { + static const int value = 1; +}; + +template +struct tuple_size { + static const int value = 2; +}; + +template +struct tuple_size { + static const int value = 3; +}; + +template +struct tuple_size { + static const int value = 4; +}; + +template +struct tuple_size { + static const int value = 5; +}; + +template +struct tuple_size { + static const int value = 6; +}; + +template +struct tuple_size { + static const int value = 7; +}; + +template +struct tuple_size { + static const int value = 8; +}; + +template +struct tuple_size { + static const int value = 9; +}; + +template +struct tuple_size { + static const int value = 10; +}; + +template +struct tuple_element { + typedef typename gtest_internal::TupleElement< + k < (tuple_size::value), k, Tuple>::type type; +}; + +#define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element::type + +// 6.1.3.4 Element access. + +namespace gtest_internal { + +template <> +class Get<0> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) + Field(Tuple& t) { return t.f0_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) + ConstField(const Tuple& t) { return t.f0_; } +}; + +template <> +class Get<1> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) + Field(Tuple& t) { return t.f1_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) + ConstField(const Tuple& t) { return t.f1_; } +}; + +template <> +class Get<2> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) + Field(Tuple& t) { return t.f2_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) + ConstField(const Tuple& t) { return t.f2_; } +}; + +template <> +class Get<3> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) + Field(Tuple& t) { return t.f3_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) + ConstField(const Tuple& t) { return t.f3_; } +}; + +template <> +class Get<4> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) + Field(Tuple& t) { return t.f4_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) + ConstField(const Tuple& t) { return t.f4_; } +}; + +template <> +class Get<5> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) + Field(Tuple& t) { return t.f5_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) + ConstField(const Tuple& t) { return t.f5_; } +}; + +template <> +class Get<6> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) + Field(Tuple& t) { return t.f6_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) + ConstField(const Tuple& t) { return t.f6_; } +}; + +template <> +class Get<7> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) + Field(Tuple& t) { return t.f7_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) + ConstField(const Tuple& t) { return t.f7_; } +}; + +template <> +class Get<8> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) + Field(Tuple& t) { return t.f8_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) + ConstField(const Tuple& t) { return t.f8_; } +}; + +template <> +class Get<9> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) + Field(Tuple& t) { return t.f9_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) + ConstField(const Tuple& t) { return t.f9_; } +}; + +} // namespace gtest_internal + +template +GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) +get(GTEST_10_TUPLE_(T)& t) { + return gtest_internal::Get::Field(t); +} + +template +GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) +get(const GTEST_10_TUPLE_(T)& t) { + return gtest_internal::Get::ConstField(t); +} + +// 6.1.3.5 Relational operators + +// We only implement == and !=, as we don't have a need for the rest yet. + +namespace gtest_internal { + +// SameSizeTuplePrefixComparator::Eq(t1, t2) returns true if the +// first k fields of t1 equals the first k fields of t2. +// SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if +// k1 != k2. +template +struct SameSizeTuplePrefixComparator; + +template <> +struct SameSizeTuplePrefixComparator<0, 0> { + template + static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) { + return true; + } +}; + +template +struct SameSizeTuplePrefixComparator { + template + static bool Eq(const Tuple1& t1, const Tuple2& t2) { + return SameSizeTuplePrefixComparator::Eq(t1, t2) && + ::std::tr1::get(t1) == ::std::tr1::get(t2); + } +}; + +} // namespace gtest_internal + +template +inline bool operator==(const GTEST_10_TUPLE_(T)& t, + const GTEST_10_TUPLE_(U)& u) { + return gtest_internal::SameSizeTuplePrefixComparator< + tuple_size::value, + tuple_size::value>::Eq(t, u); +} + +template +inline bool operator!=(const GTEST_10_TUPLE_(T)& t, + const GTEST_10_TUPLE_(U)& u) { return !(t == u); } + +// 6.1.4 Pairs. +// Unimplemented. + +} // namespace tr1 +} // namespace std + +#undef GTEST_0_TUPLE_ +#undef GTEST_1_TUPLE_ +#undef GTEST_2_TUPLE_ +#undef GTEST_3_TUPLE_ +#undef GTEST_4_TUPLE_ +#undef GTEST_5_TUPLE_ +#undef GTEST_6_TUPLE_ +#undef GTEST_7_TUPLE_ +#undef GTEST_8_TUPLE_ +#undef GTEST_9_TUPLE_ +#undef GTEST_10_TUPLE_ + +#undef GTEST_0_TYPENAMES_ +#undef GTEST_1_TYPENAMES_ +#undef GTEST_2_TYPENAMES_ +#undef GTEST_3_TYPENAMES_ +#undef GTEST_4_TYPENAMES_ +#undef GTEST_5_TYPENAMES_ +#undef GTEST_6_TYPENAMES_ +#undef GTEST_7_TYPENAMES_ +#undef GTEST_8_TYPENAMES_ +#undef GTEST_9_TYPENAMES_ +#undef GTEST_10_TYPENAMES_ + +#undef GTEST_DECLARE_TUPLE_AS_FRIEND_ +#undef GTEST_BY_REF_ +#undef GTEST_ADD_REF_ +#undef GTEST_TUPLE_ELEMENT_ + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ diff --git a/lib/gtest/include/gtest/internal/gtest-tuple.h.pump b/lib/gtest/include/gtest/internal/gtest-tuple.h.pump new file mode 100644 index 00000000..c7d9e039 --- /dev/null +++ b/lib/gtest/include/gtest/internal/gtest-tuple.h.pump @@ -0,0 +1,339 @@ +$$ -*- mode: c++; -*- +$var n = 10 $$ Maximum number of tuple fields we want to support. +$$ This meta comment fixes auto-indentation in Emacs. }} +// Copyright 2009 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Implements a subset of TR1 tuple needed by Google Test and Google Mock. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ + +#include // For ::std::pair. + +// The compiler used in Symbian has a bug that prevents us from declaring the +// tuple template as a friend (it complains that tuple is redefined). This +// hack bypasses the bug by declaring the members that should otherwise be +// private as public. +// Sun Studio versions < 12 also have the above bug. +#if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) +# define GTEST_DECLARE_TUPLE_AS_FRIEND_ public: +#else +# define GTEST_DECLARE_TUPLE_AS_FRIEND_ \ + template friend class tuple; \ + private: +#endif + + +$range i 0..n-1 +$range j 0..n +$range k 1..n +// GTEST_n_TUPLE_(T) is the type of an n-tuple. +#define GTEST_0_TUPLE_(T) tuple<> + +$for k [[ +$range m 0..k-1 +$range m2 k..n-1 +#define GTEST_$(k)_TUPLE_(T) tuple<$for m, [[T##$m]]$for m2 [[, void]]> + +]] + +// GTEST_n_TYPENAMES_(T) declares a list of n typenames. + +$for j [[ +$range m 0..j-1 +#define GTEST_$(j)_TYPENAMES_(T) $for m, [[typename T##$m]] + + +]] + +// In theory, defining stuff in the ::std namespace is undefined +// behavior. We can do this as we are playing the role of a standard +// library vendor. +namespace std { +namespace tr1 { + +template <$for i, [[typename T$i = void]]> +class tuple; + +// Anything in namespace gtest_internal is Google Test's INTERNAL +// IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code. +namespace gtest_internal { + +// ByRef::type is T if T is a reference; otherwise it's const T&. +template +struct ByRef { typedef const T& type; }; // NOLINT +template +struct ByRef { typedef T& type; }; // NOLINT + +// A handy wrapper for ByRef. +#define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef::type + +// AddRef::type is T if T is a reference; otherwise it's T&. This +// is the same as tr1::add_reference::type. +template +struct AddRef { typedef T& type; }; // NOLINT +template +struct AddRef { typedef T& type; }; // NOLINT + +// A handy wrapper for AddRef. +#define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef::type + +// A helper for implementing get(). +template class Get; + +// A helper for implementing tuple_element. kIndexValid is true +// iff k < the number of fields in tuple type T. +template +struct TupleElement; + + +$for i [[ +template +struct TupleElement { + typedef T$i type; +}; + + +]] +} // namespace gtest_internal + +template <> +class tuple<> { + public: + tuple() {} + tuple(const tuple& /* t */) {} + tuple& operator=(const tuple& /* t */) { return *this; } +}; + + +$for k [[ +$range m 0..k-1 +template +class $if k < n [[GTEST_$(k)_TUPLE_(T)]] $else [[tuple]] { + public: + template friend class gtest_internal::Get; + + tuple() : $for m, [[f$(m)_()]] {} + + explicit tuple($for m, [[GTEST_BY_REF_(T$m) f$m]]) : [[]] +$for m, [[f$(m)_(f$m)]] {} + + tuple(const tuple& t) : $for m, [[f$(m)_(t.f$(m)_)]] {} + + template + tuple(const GTEST_$(k)_TUPLE_(U)& t) : $for m, [[f$(m)_(t.f$(m)_)]] {} + +$if k == 2 [[ + template + tuple(const ::std::pair& p) : f0_(p.first), f1_(p.second) {} + +]] + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_$(k)_TUPLE_(U)& t) { + return CopyFrom(t); + } + +$if k == 2 [[ + template + tuple& operator=(const ::std::pair& p) { + f0_ = p.first; + f1_ = p.second; + return *this; + } + +]] + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_$(k)_TUPLE_(U)& t) { + +$for m [[ + f$(m)_ = t.f$(m)_; + +]] + return *this; + } + + +$for m [[ + T$m f$(m)_; + +]] +}; + + +]] +// 6.1.3.2 Tuple creation functions. + +// Known limitations: we don't support passing an +// std::tr1::reference_wrapper to make_tuple(). And we don't +// implement tie(). + +inline tuple<> make_tuple() { return tuple<>(); } + +$for k [[ +$range m 0..k-1 + +template +inline GTEST_$(k)_TUPLE_(T) make_tuple($for m, [[const T$m& f$m]]) { + return GTEST_$(k)_TUPLE_(T)($for m, [[f$m]]); +} + +]] + +// 6.1.3.3 Tuple helper classes. + +template struct tuple_size; + + +$for j [[ +template +struct tuple_size { + static const int value = $j; +}; + + +]] +template +struct tuple_element { + typedef typename gtest_internal::TupleElement< + k < (tuple_size::value), k, Tuple>::type type; +}; + +#define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element::type + +// 6.1.3.4 Element access. + +namespace gtest_internal { + + +$for i [[ +template <> +class Get<$i> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_($i, Tuple)) + Field(Tuple& t) { return t.f$(i)_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_($i, Tuple)) + ConstField(const Tuple& t) { return t.f$(i)_; } +}; + + +]] +} // namespace gtest_internal + +template +GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_$(n)_TUPLE_(T))) +get(GTEST_$(n)_TUPLE_(T)& t) { + return gtest_internal::Get::Field(t); +} + +template +GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_$(n)_TUPLE_(T))) +get(const GTEST_$(n)_TUPLE_(T)& t) { + return gtest_internal::Get::ConstField(t); +} + +// 6.1.3.5 Relational operators + +// We only implement == and !=, as we don't have a need for the rest yet. + +namespace gtest_internal { + +// SameSizeTuplePrefixComparator::Eq(t1, t2) returns true if the +// first k fields of t1 equals the first k fields of t2. +// SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if +// k1 != k2. +template +struct SameSizeTuplePrefixComparator; + +template <> +struct SameSizeTuplePrefixComparator<0, 0> { + template + static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) { + return true; + } +}; + +template +struct SameSizeTuplePrefixComparator { + template + static bool Eq(const Tuple1& t1, const Tuple2& t2) { + return SameSizeTuplePrefixComparator::Eq(t1, t2) && + ::std::tr1::get(t1) == ::std::tr1::get(t2); + } +}; + +} // namespace gtest_internal + +template +inline bool operator==(const GTEST_$(n)_TUPLE_(T)& t, + const GTEST_$(n)_TUPLE_(U)& u) { + return gtest_internal::SameSizeTuplePrefixComparator< + tuple_size::value, + tuple_size::value>::Eq(t, u); +} + +template +inline bool operator!=(const GTEST_$(n)_TUPLE_(T)& t, + const GTEST_$(n)_TUPLE_(U)& u) { return !(t == u); } + +// 6.1.4 Pairs. +// Unimplemented. + +} // namespace tr1 +} // namespace std + + +$for j [[ +#undef GTEST_$(j)_TUPLE_ + +]] + + +$for j [[ +#undef GTEST_$(j)_TYPENAMES_ + +]] + +#undef GTEST_DECLARE_TUPLE_AS_FRIEND_ +#undef GTEST_BY_REF_ +#undef GTEST_ADD_REF_ +#undef GTEST_TUPLE_ELEMENT_ + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ diff --git a/lib/gtest/include/gtest/internal/gtest-type-util.h b/lib/gtest/include/gtest/internal/gtest-type-util.h new file mode 100644 index 00000000..e46f7cfc --- /dev/null +++ b/lib/gtest/include/gtest/internal/gtest-type-util.h @@ -0,0 +1,3331 @@ +// This file was GENERATED by command: +// pump.py gtest-type-util.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Type utilities needed for implementing typed and type-parameterized +// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +// Currently we support at most 50 types in a list, and at most 50 +// type-parameterized tests in one type-parameterized test case. +// Please contact googletestframework@googlegroups.com if you need +// more. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ + +#include "gtest/internal/gtest-port.h" + +// #ifdef __GNUC__ is too general here. It is possible to use gcc without using +// libstdc++ (which is where cxxabi.h comes from). +# if GTEST_HAS_CXXABI_H_ +# include +# elif defined(__HP_aCC) +# include +# endif // GTEST_HASH_CXXABI_H_ + +namespace testing { +namespace internal { + +// GetTypeName() returns a human-readable name of type T. +// NB: This function is also used in Google Mock, so don't move it inside of +// the typed-test-only section below. +template +std::string GetTypeName() { +# if GTEST_HAS_RTTI + + const char* const name = typeid(T).name(); +# if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC) + int status = 0; + // gcc's implementation of typeid(T).name() mangles the type name, + // so we have to demangle it. +# if GTEST_HAS_CXXABI_H_ + using abi::__cxa_demangle; +# endif // GTEST_HAS_CXXABI_H_ + char* const readable_name = __cxa_demangle(name, 0, 0, &status); + const std::string name_str(status == 0 ? readable_name : name); + free(readable_name); + return name_str; +# else + return name; +# endif // GTEST_HAS_CXXABI_H_ || __HP_aCC + +# else + + return ""; + +# endif // GTEST_HAS_RTTI +} + +#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +// AssertyTypeEq::type is defined iff T1 and T2 are the same +// type. This can be used as a compile-time assertion to ensure that +// two types are equal. + +template +struct AssertTypeEq; + +template +struct AssertTypeEq { + typedef bool type; +}; + +// A unique type used as the default value for the arguments of class +// template Types. This allows us to simulate variadic templates +// (e.g. Types, Type, and etc), which C++ doesn't +// support directly. +struct None {}; + +// The following family of struct and struct templates are used to +// represent type lists. In particular, TypesN +// represents a type list with N types (T1, T2, ..., and TN) in it. +// Except for Types0, every struct in the family has two member types: +// Head for the first type in the list, and Tail for the rest of the +// list. + +// The empty type list. +struct Types0 {}; + +// Type lists of length 1, 2, 3, and so on. + +template +struct Types1 { + typedef T1 Head; + typedef Types0 Tail; +}; +template +struct Types2 { + typedef T1 Head; + typedef Types1 Tail; +}; + +template +struct Types3 { + typedef T1 Head; + typedef Types2 Tail; +}; + +template +struct Types4 { + typedef T1 Head; + typedef Types3 Tail; +}; + +template +struct Types5 { + typedef T1 Head; + typedef Types4 Tail; +}; + +template +struct Types6 { + typedef T1 Head; + typedef Types5 Tail; +}; + +template +struct Types7 { + typedef T1 Head; + typedef Types6 Tail; +}; + +template +struct Types8 { + typedef T1 Head; + typedef Types7 Tail; +}; + +template +struct Types9 { + typedef T1 Head; + typedef Types8 Tail; +}; + +template +struct Types10 { + typedef T1 Head; + typedef Types9 Tail; +}; + +template +struct Types11 { + typedef T1 Head; + typedef Types10 Tail; +}; + +template +struct Types12 { + typedef T1 Head; + typedef Types11 Tail; +}; + +template +struct Types13 { + typedef T1 Head; + typedef Types12 Tail; +}; + +template +struct Types14 { + typedef T1 Head; + typedef Types13 Tail; +}; + +template +struct Types15 { + typedef T1 Head; + typedef Types14 Tail; +}; + +template +struct Types16 { + typedef T1 Head; + typedef Types15 Tail; +}; + +template +struct Types17 { + typedef T1 Head; + typedef Types16 Tail; +}; + +template +struct Types18 { + typedef T1 Head; + typedef Types17 Tail; +}; + +template +struct Types19 { + typedef T1 Head; + typedef Types18 Tail; +}; + +template +struct Types20 { + typedef T1 Head; + typedef Types19 Tail; +}; + +template +struct Types21 { + typedef T1 Head; + typedef Types20 Tail; +}; + +template +struct Types22 { + typedef T1 Head; + typedef Types21 Tail; +}; + +template +struct Types23 { + typedef T1 Head; + typedef Types22 Tail; +}; + +template +struct Types24 { + typedef T1 Head; + typedef Types23 Tail; +}; + +template +struct Types25 { + typedef T1 Head; + typedef Types24 Tail; +}; + +template +struct Types26 { + typedef T1 Head; + typedef Types25 Tail; +}; + +template +struct Types27 { + typedef T1 Head; + typedef Types26 Tail; +}; + +template +struct Types28 { + typedef T1 Head; + typedef Types27 Tail; +}; + +template +struct Types29 { + typedef T1 Head; + typedef Types28 Tail; +}; + +template +struct Types30 { + typedef T1 Head; + typedef Types29 Tail; +}; + +template +struct Types31 { + typedef T1 Head; + typedef Types30 Tail; +}; + +template +struct Types32 { + typedef T1 Head; + typedef Types31 Tail; +}; + +template +struct Types33 { + typedef T1 Head; + typedef Types32 Tail; +}; + +template +struct Types34 { + typedef T1 Head; + typedef Types33 Tail; +}; + +template +struct Types35 { + typedef T1 Head; + typedef Types34 Tail; +}; + +template +struct Types36 { + typedef T1 Head; + typedef Types35 Tail; +}; + +template +struct Types37 { + typedef T1 Head; + typedef Types36 Tail; +}; + +template +struct Types38 { + typedef T1 Head; + typedef Types37 Tail; +}; + +template +struct Types39 { + typedef T1 Head; + typedef Types38 Tail; +}; + +template +struct Types40 { + typedef T1 Head; + typedef Types39 Tail; +}; + +template +struct Types41 { + typedef T1 Head; + typedef Types40 Tail; +}; + +template +struct Types42 { + typedef T1 Head; + typedef Types41 Tail; +}; + +template +struct Types43 { + typedef T1 Head; + typedef Types42 Tail; +}; + +template +struct Types44 { + typedef T1 Head; + typedef Types43 Tail; +}; + +template +struct Types45 { + typedef T1 Head; + typedef Types44 Tail; +}; + +template +struct Types46 { + typedef T1 Head; + typedef Types45 Tail; +}; + +template +struct Types47 { + typedef T1 Head; + typedef Types46 Tail; +}; + +template +struct Types48 { + typedef T1 Head; + typedef Types47 Tail; +}; + +template +struct Types49 { + typedef T1 Head; + typedef Types48 Tail; +}; + +template +struct Types50 { + typedef T1 Head; + typedef Types49 Tail; +}; + + +} // namespace internal + +// We don't want to require the users to write TypesN<...> directly, +// as that would require them to count the length. Types<...> is much +// easier to write, but generates horrible messages when there is a +// compiler error, as gcc insists on printing out each template +// argument, even if it has the default value (this means Types +// will appear as Types in the compiler +// errors). +// +// Our solution is to combine the best part of the two approaches: a +// user would write Types, and Google Test will translate +// that to TypesN internally to make error messages +// readable. The translation is done by the 'type' member of the +// Types template. +template +struct Types { + typedef internal::Types50 type; +}; + +template <> +struct Types { + typedef internal::Types0 type; +}; +template +struct Types { + typedef internal::Types1 type; +}; +template +struct Types { + typedef internal::Types2 type; +}; +template +struct Types { + typedef internal::Types3 type; +}; +template +struct Types { + typedef internal::Types4 type; +}; +template +struct Types { + typedef internal::Types5 type; +}; +template +struct Types { + typedef internal::Types6 type; +}; +template +struct Types { + typedef internal::Types7 type; +}; +template +struct Types { + typedef internal::Types8 type; +}; +template +struct Types { + typedef internal::Types9 type; +}; +template +struct Types { + typedef internal::Types10 type; +}; +template +struct Types { + typedef internal::Types11 type; +}; +template +struct Types { + typedef internal::Types12 type; +}; +template +struct Types { + typedef internal::Types13 type; +}; +template +struct Types { + typedef internal::Types14 type; +}; +template +struct Types { + typedef internal::Types15 type; +}; +template +struct Types { + typedef internal::Types16 type; +}; +template +struct Types { + typedef internal::Types17 type; +}; +template +struct Types { + typedef internal::Types18 type; +}; +template +struct Types { + typedef internal::Types19 type; +}; +template +struct Types { + typedef internal::Types20 type; +}; +template +struct Types { + typedef internal::Types21 type; +}; +template +struct Types { + typedef internal::Types22 type; +}; +template +struct Types { + typedef internal::Types23 type; +}; +template +struct Types { + typedef internal::Types24 type; +}; +template +struct Types { + typedef internal::Types25 type; +}; +template +struct Types { + typedef internal::Types26 type; +}; +template +struct Types { + typedef internal::Types27 type; +}; +template +struct Types { + typedef internal::Types28 type; +}; +template +struct Types { + typedef internal::Types29 type; +}; +template +struct Types { + typedef internal::Types30 type; +}; +template +struct Types { + typedef internal::Types31 type; +}; +template +struct Types { + typedef internal::Types32 type; +}; +template +struct Types { + typedef internal::Types33 type; +}; +template +struct Types { + typedef internal::Types34 type; +}; +template +struct Types { + typedef internal::Types35 type; +}; +template +struct Types { + typedef internal::Types36 type; +}; +template +struct Types { + typedef internal::Types37 type; +}; +template +struct Types { + typedef internal::Types38 type; +}; +template +struct Types { + typedef internal::Types39 type; +}; +template +struct Types { + typedef internal::Types40 type; +}; +template +struct Types { + typedef internal::Types41 type; +}; +template +struct Types { + typedef internal::Types42 type; +}; +template +struct Types { + typedef internal::Types43 type; +}; +template +struct Types { + typedef internal::Types44 type; +}; +template +struct Types { + typedef internal::Types45 type; +}; +template +struct Types { + typedef internal::Types46 type; +}; +template +struct Types { + typedef internal::Types47 type; +}; +template +struct Types { + typedef internal::Types48 type; +}; +template +struct Types { + typedef internal::Types49 type; +}; + +namespace internal { + +# define GTEST_TEMPLATE_ template class + +// The template "selector" struct TemplateSel is used to +// represent Tmpl, which must be a class template with one type +// parameter, as a type. TemplateSel::Bind::type is defined +// as the type Tmpl. This allows us to actually instantiate the +// template "selected" by TemplateSel. +// +// This trick is necessary for simulating typedef for class templates, +// which C++ doesn't support directly. +template +struct TemplateSel { + template + struct Bind { + typedef Tmpl type; + }; +}; + +# define GTEST_BIND_(TmplSel, T) \ + TmplSel::template Bind::type + +// A unique struct template used as the default value for the +// arguments of class template Templates. This allows us to simulate +// variadic templates (e.g. Templates, Templates, +// and etc), which C++ doesn't support directly. +template +struct NoneT {}; + +// The following family of struct and struct templates are used to +// represent template lists. In particular, TemplatesN represents a list of N templates (T1, T2, ..., and TN). Except +// for Templates0, every struct in the family has two member types: +// Head for the selector of the first template in the list, and Tail +// for the rest of the list. + +// The empty template list. +struct Templates0 {}; + +// Template lists of length 1, 2, 3, and so on. + +template +struct Templates1 { + typedef TemplateSel Head; + typedef Templates0 Tail; +}; +template +struct Templates2 { + typedef TemplateSel Head; + typedef Templates1 Tail; +}; + +template +struct Templates3 { + typedef TemplateSel Head; + typedef Templates2 Tail; +}; + +template +struct Templates4 { + typedef TemplateSel Head; + typedef Templates3 Tail; +}; + +template +struct Templates5 { + typedef TemplateSel Head; + typedef Templates4 Tail; +}; + +template +struct Templates6 { + typedef TemplateSel Head; + typedef Templates5 Tail; +}; + +template +struct Templates7 { + typedef TemplateSel Head; + typedef Templates6 Tail; +}; + +template +struct Templates8 { + typedef TemplateSel Head; + typedef Templates7 Tail; +}; + +template +struct Templates9 { + typedef TemplateSel Head; + typedef Templates8 Tail; +}; + +template +struct Templates10 { + typedef TemplateSel Head; + typedef Templates9 Tail; +}; + +template +struct Templates11 { + typedef TemplateSel Head; + typedef Templates10 Tail; +}; + +template +struct Templates12 { + typedef TemplateSel Head; + typedef Templates11 Tail; +}; + +template +struct Templates13 { + typedef TemplateSel Head; + typedef Templates12 Tail; +}; + +template +struct Templates14 { + typedef TemplateSel Head; + typedef Templates13 Tail; +}; + +template +struct Templates15 { + typedef TemplateSel Head; + typedef Templates14 Tail; +}; + +template +struct Templates16 { + typedef TemplateSel Head; + typedef Templates15 Tail; +}; + +template +struct Templates17 { + typedef TemplateSel Head; + typedef Templates16 Tail; +}; + +template +struct Templates18 { + typedef TemplateSel Head; + typedef Templates17 Tail; +}; + +template +struct Templates19 { + typedef TemplateSel Head; + typedef Templates18 Tail; +}; + +template +struct Templates20 { + typedef TemplateSel Head; + typedef Templates19 Tail; +}; + +template +struct Templates21 { + typedef TemplateSel Head; + typedef Templates20 Tail; +}; + +template +struct Templates22 { + typedef TemplateSel Head; + typedef Templates21 Tail; +}; + +template +struct Templates23 { + typedef TemplateSel Head; + typedef Templates22 Tail; +}; + +template +struct Templates24 { + typedef TemplateSel Head; + typedef Templates23 Tail; +}; + +template +struct Templates25 { + typedef TemplateSel Head; + typedef Templates24 Tail; +}; + +template +struct Templates26 { + typedef TemplateSel Head; + typedef Templates25 Tail; +}; + +template +struct Templates27 { + typedef TemplateSel Head; + typedef Templates26 Tail; +}; + +template +struct Templates28 { + typedef TemplateSel Head; + typedef Templates27 Tail; +}; + +template +struct Templates29 { + typedef TemplateSel Head; + typedef Templates28 Tail; +}; + +template +struct Templates30 { + typedef TemplateSel Head; + typedef Templates29 Tail; +}; + +template +struct Templates31 { + typedef TemplateSel Head; + typedef Templates30 Tail; +}; + +template +struct Templates32 { + typedef TemplateSel Head; + typedef Templates31 Tail; +}; + +template +struct Templates33 { + typedef TemplateSel Head; + typedef Templates32 Tail; +}; + +template +struct Templates34 { + typedef TemplateSel Head; + typedef Templates33 Tail; +}; + +template +struct Templates35 { + typedef TemplateSel Head; + typedef Templates34 Tail; +}; + +template +struct Templates36 { + typedef TemplateSel Head; + typedef Templates35 Tail; +}; + +template +struct Templates37 { + typedef TemplateSel Head; + typedef Templates36 Tail; +}; + +template +struct Templates38 { + typedef TemplateSel Head; + typedef Templates37 Tail; +}; + +template +struct Templates39 { + typedef TemplateSel Head; + typedef Templates38 Tail; +}; + +template +struct Templates40 { + typedef TemplateSel Head; + typedef Templates39 Tail; +}; + +template +struct Templates41 { + typedef TemplateSel Head; + typedef Templates40 Tail; +}; + +template +struct Templates42 { + typedef TemplateSel Head; + typedef Templates41 Tail; +}; + +template +struct Templates43 { + typedef TemplateSel Head; + typedef Templates42 Tail; +}; + +template +struct Templates44 { + typedef TemplateSel Head; + typedef Templates43 Tail; +}; + +template +struct Templates45 { + typedef TemplateSel Head; + typedef Templates44 Tail; +}; + +template +struct Templates46 { + typedef TemplateSel Head; + typedef Templates45 Tail; +}; + +template +struct Templates47 { + typedef TemplateSel Head; + typedef Templates46 Tail; +}; + +template +struct Templates48 { + typedef TemplateSel Head; + typedef Templates47 Tail; +}; + +template +struct Templates49 { + typedef TemplateSel Head; + typedef Templates48 Tail; +}; + +template +struct Templates50 { + typedef TemplateSel Head; + typedef Templates49 Tail; +}; + + +// We don't want to require the users to write TemplatesN<...> directly, +// as that would require them to count the length. Templates<...> is much +// easier to write, but generates horrible messages when there is a +// compiler error, as gcc insists on printing out each template +// argument, even if it has the default value (this means Templates +// will appear as Templates in the compiler +// errors). +// +// Our solution is to combine the best part of the two approaches: a +// user would write Templates, and Google Test will translate +// that to TemplatesN internally to make error messages +// readable. The translation is done by the 'type' member of the +// Templates template. +template +struct Templates { + typedef Templates50 type; +}; + +template <> +struct Templates { + typedef Templates0 type; +}; +template +struct Templates { + typedef Templates1 type; +}; +template +struct Templates { + typedef Templates2 type; +}; +template +struct Templates { + typedef Templates3 type; +}; +template +struct Templates { + typedef Templates4 type; +}; +template +struct Templates { + typedef Templates5 type; +}; +template +struct Templates { + typedef Templates6 type; +}; +template +struct Templates { + typedef Templates7 type; +}; +template +struct Templates { + typedef Templates8 type; +}; +template +struct Templates { + typedef Templates9 type; +}; +template +struct Templates { + typedef Templates10 type; +}; +template +struct Templates { + typedef Templates11 type; +}; +template +struct Templates { + typedef Templates12 type; +}; +template +struct Templates { + typedef Templates13 type; +}; +template +struct Templates { + typedef Templates14 type; +}; +template +struct Templates { + typedef Templates15 type; +}; +template +struct Templates { + typedef Templates16 type; +}; +template +struct Templates { + typedef Templates17 type; +}; +template +struct Templates { + typedef Templates18 type; +}; +template +struct Templates { + typedef Templates19 type; +}; +template +struct Templates { + typedef Templates20 type; +}; +template +struct Templates { + typedef Templates21 type; +}; +template +struct Templates { + typedef Templates22 type; +}; +template +struct Templates { + typedef Templates23 type; +}; +template +struct Templates { + typedef Templates24 type; +}; +template +struct Templates { + typedef Templates25 type; +}; +template +struct Templates { + typedef Templates26 type; +}; +template +struct Templates { + typedef Templates27 type; +}; +template +struct Templates { + typedef Templates28 type; +}; +template +struct Templates { + typedef Templates29 type; +}; +template +struct Templates { + typedef Templates30 type; +}; +template +struct Templates { + typedef Templates31 type; +}; +template +struct Templates { + typedef Templates32 type; +}; +template +struct Templates { + typedef Templates33 type; +}; +template +struct Templates { + typedef Templates34 type; +}; +template +struct Templates { + typedef Templates35 type; +}; +template +struct Templates { + typedef Templates36 type; +}; +template +struct Templates { + typedef Templates37 type; +}; +template +struct Templates { + typedef Templates38 type; +}; +template +struct Templates { + typedef Templates39 type; +}; +template +struct Templates { + typedef Templates40 type; +}; +template +struct Templates { + typedef Templates41 type; +}; +template +struct Templates { + typedef Templates42 type; +}; +template +struct Templates { + typedef Templates43 type; +}; +template +struct Templates { + typedef Templates44 type; +}; +template +struct Templates { + typedef Templates45 type; +}; +template +struct Templates { + typedef Templates46 type; +}; +template +struct Templates { + typedef Templates47 type; +}; +template +struct Templates { + typedef Templates48 type; +}; +template +struct Templates { + typedef Templates49 type; +}; + +// The TypeList template makes it possible to use either a single type +// or a Types<...> list in TYPED_TEST_CASE() and +// INSTANTIATE_TYPED_TEST_CASE_P(). + +template +struct TypeList { + typedef Types1 type; +}; + +template +struct TypeList > { + typedef typename Types::type type; +}; + +#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ diff --git a/lib/gtest/include/gtest/internal/gtest-type-util.h.pump b/lib/gtest/include/gtest/internal/gtest-type-util.h.pump new file mode 100644 index 00000000..251fdf02 --- /dev/null +++ b/lib/gtest/include/gtest/internal/gtest-type-util.h.pump @@ -0,0 +1,297 @@ +$$ -*- mode: c++; -*- +$var n = 50 $$ Maximum length of type lists we want to support. +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Type utilities needed for implementing typed and type-parameterized +// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +// Currently we support at most $n types in a list, and at most $n +// type-parameterized tests in one type-parameterized test case. +// Please contact googletestframework@googlegroups.com if you need +// more. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ + +#include "gtest/internal/gtest-port.h" + +// #ifdef __GNUC__ is too general here. It is possible to use gcc without using +// libstdc++ (which is where cxxabi.h comes from). +# if GTEST_HAS_CXXABI_H_ +# include +# elif defined(__HP_aCC) +# include +# endif // GTEST_HASH_CXXABI_H_ + +namespace testing { +namespace internal { + +// GetTypeName() returns a human-readable name of type T. +// NB: This function is also used in Google Mock, so don't move it inside of +// the typed-test-only section below. +template +std::string GetTypeName() { +# if GTEST_HAS_RTTI + + const char* const name = typeid(T).name(); +# if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC) + int status = 0; + // gcc's implementation of typeid(T).name() mangles the type name, + // so we have to demangle it. +# if GTEST_HAS_CXXABI_H_ + using abi::__cxa_demangle; +# endif // GTEST_HAS_CXXABI_H_ + char* const readable_name = __cxa_demangle(name, 0, 0, &status); + const std::string name_str(status == 0 ? readable_name : name); + free(readable_name); + return name_str; +# else + return name; +# endif // GTEST_HAS_CXXABI_H_ || __HP_aCC + +# else + + return ""; + +# endif // GTEST_HAS_RTTI +} + +#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +// AssertyTypeEq::type is defined iff T1 and T2 are the same +// type. This can be used as a compile-time assertion to ensure that +// two types are equal. + +template +struct AssertTypeEq; + +template +struct AssertTypeEq { + typedef bool type; +}; + +// A unique type used as the default value for the arguments of class +// template Types. This allows us to simulate variadic templates +// (e.g. Types, Type, and etc), which C++ doesn't +// support directly. +struct None {}; + +// The following family of struct and struct templates are used to +// represent type lists. In particular, TypesN +// represents a type list with N types (T1, T2, ..., and TN) in it. +// Except for Types0, every struct in the family has two member types: +// Head for the first type in the list, and Tail for the rest of the +// list. + +// The empty type list. +struct Types0 {}; + +// Type lists of length 1, 2, 3, and so on. + +template +struct Types1 { + typedef T1 Head; + typedef Types0 Tail; +}; + +$range i 2..n + +$for i [[ +$range j 1..i +$range k 2..i +template <$for j, [[typename T$j]]> +struct Types$i { + typedef T1 Head; + typedef Types$(i-1)<$for k, [[T$k]]> Tail; +}; + + +]] + +} // namespace internal + +// We don't want to require the users to write TypesN<...> directly, +// as that would require them to count the length. Types<...> is much +// easier to write, but generates horrible messages when there is a +// compiler error, as gcc insists on printing out each template +// argument, even if it has the default value (this means Types +// will appear as Types in the compiler +// errors). +// +// Our solution is to combine the best part of the two approaches: a +// user would write Types, and Google Test will translate +// that to TypesN internally to make error messages +// readable. The translation is done by the 'type' member of the +// Types template. + +$range i 1..n +template <$for i, [[typename T$i = internal::None]]> +struct Types { + typedef internal::Types$n<$for i, [[T$i]]> type; +}; + +template <> +struct Types<$for i, [[internal::None]]> { + typedef internal::Types0 type; +}; + +$range i 1..n-1 +$for i [[ +$range j 1..i +$range k i+1..n +template <$for j, [[typename T$j]]> +struct Types<$for j, [[T$j]]$for k[[, internal::None]]> { + typedef internal::Types$i<$for j, [[T$j]]> type; +}; + +]] + +namespace internal { + +# define GTEST_TEMPLATE_ template class + +// The template "selector" struct TemplateSel is used to +// represent Tmpl, which must be a class template with one type +// parameter, as a type. TemplateSel::Bind::type is defined +// as the type Tmpl. This allows us to actually instantiate the +// template "selected" by TemplateSel. +// +// This trick is necessary for simulating typedef for class templates, +// which C++ doesn't support directly. +template +struct TemplateSel { + template + struct Bind { + typedef Tmpl type; + }; +}; + +# define GTEST_BIND_(TmplSel, T) \ + TmplSel::template Bind::type + +// A unique struct template used as the default value for the +// arguments of class template Templates. This allows us to simulate +// variadic templates (e.g. Templates, Templates, +// and etc), which C++ doesn't support directly. +template +struct NoneT {}; + +// The following family of struct and struct templates are used to +// represent template lists. In particular, TemplatesN represents a list of N templates (T1, T2, ..., and TN). Except +// for Templates0, every struct in the family has two member types: +// Head for the selector of the first template in the list, and Tail +// for the rest of the list. + +// The empty template list. +struct Templates0 {}; + +// Template lists of length 1, 2, 3, and so on. + +template +struct Templates1 { + typedef TemplateSel Head; + typedef Templates0 Tail; +}; + +$range i 2..n + +$for i [[ +$range j 1..i +$range k 2..i +template <$for j, [[GTEST_TEMPLATE_ T$j]]> +struct Templates$i { + typedef TemplateSel Head; + typedef Templates$(i-1)<$for k, [[T$k]]> Tail; +}; + + +]] + +// We don't want to require the users to write TemplatesN<...> directly, +// as that would require them to count the length. Templates<...> is much +// easier to write, but generates horrible messages when there is a +// compiler error, as gcc insists on printing out each template +// argument, even if it has the default value (this means Templates +// will appear as Templates in the compiler +// errors). +// +// Our solution is to combine the best part of the two approaches: a +// user would write Templates, and Google Test will translate +// that to TemplatesN internally to make error messages +// readable. The translation is done by the 'type' member of the +// Templates template. + +$range i 1..n +template <$for i, [[GTEST_TEMPLATE_ T$i = NoneT]]> +struct Templates { + typedef Templates$n<$for i, [[T$i]]> type; +}; + +template <> +struct Templates<$for i, [[NoneT]]> { + typedef Templates0 type; +}; + +$range i 1..n-1 +$for i [[ +$range j 1..i +$range k i+1..n +template <$for j, [[GTEST_TEMPLATE_ T$j]]> +struct Templates<$for j, [[T$j]]$for k[[, NoneT]]> { + typedef Templates$i<$for j, [[T$j]]> type; +}; + +]] + +// The TypeList template makes it possible to use either a single type +// or a Types<...> list in TYPED_TEST_CASE() and +// INSTANTIATE_TYPED_TEST_CASE_P(). + +template +struct TypeList { + typedef Types1 type; +}; + + +$range i 1..n +template <$for i, [[typename T$i]]> +struct TypeList > { + typedef typename Types<$for i, [[T$i]]>::type type; +}; + +#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ diff --git a/lib/gtest/msvc/gtest-md.sln b/lib/gtest/msvc/gtest-md.sln new file mode 100644 index 00000000..829b4019 --- /dev/null +++ b/lib/gtest/msvc/gtest-md.sln @@ -0,0 +1,45 @@ +Microsoft Visual Studio Solution File, Format Version 8.00 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest-md", "gtest-md.vcproj", "{C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_main-md", "gtest_main-md.vcproj", "{3AF54C8A-10BF-4332-9147-F68ED9862033}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_prod_test-md", "gtest_prod_test-md.vcproj", "{24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_unittest-md", "gtest_unittest-md.vcproj", "{4D9FDFB5-986A-4139-823C-F4EE0ED481A2}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + Debug = Debug + Release = Release + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Debug.ActiveCfg = Debug|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Debug.Build.0 = Debug|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Release.ActiveCfg = Release|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE8}.Release.Build.0 = Release|Win32 + {3AF54C8A-10BF-4332-9147-F68ED9862033}.Debug.ActiveCfg = Debug|Win32 + {3AF54C8A-10BF-4332-9147-F68ED9862033}.Debug.Build.0 = Debug|Win32 + {3AF54C8A-10BF-4332-9147-F68ED9862033}.Release.ActiveCfg = Release|Win32 + {3AF54C8A-10BF-4332-9147-F68ED9862033}.Release.Build.0 = Release|Win32 + {24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Debug.ActiveCfg = Debug|Win32 + {24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Debug.Build.0 = Debug|Win32 + {24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Release.ActiveCfg = Release|Win32 + {24848551-EF4F-47E8-9A9D-EA4D49BC3ECB}.Release.Build.0 = Release|Win32 + {4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Debug.ActiveCfg = Debug|Win32 + {4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Debug.Build.0 = Debug|Win32 + {4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Release.ActiveCfg = Release|Win32 + {4D9FDFB5-986A-4139-823C-F4EE0ED481A2}.Release.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/lib/gtest/msvc/gtest.sln b/lib/gtest/msvc/gtest.sln new file mode 100644 index 00000000..4f0e9015 --- /dev/null +++ b/lib/gtest/msvc/gtest.sln @@ -0,0 +1,57 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2013 +VisualStudioVersion = 12.0.31101.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest", "gtest.vcxproj", "{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_main", "gtest_main.vcxproj", "{3AF54C8A-10BF-4332-9147-F68ED9862032}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_unittest", "gtest_unittest.vcxproj", "{4D9FDFB5-986A-4139-823C-F4EE0ED481A1}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gtest_prod_test", "gtest_prod_test.vcxproj", "{24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|x64.ActiveCfg = Debug|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|x64.Build.0 = Debug|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|x86.ActiveCfg = Debug|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|x86.Build.0 = Debug|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|x64.ActiveCfg = Release|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|x64.Build.0 = Release|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|x86.ActiveCfg = Release|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|x86.Build.0 = Release|Win32 + {3AF54C8A-10BF-4332-9147-F68ED9862032}.Debug|x64.ActiveCfg = Debug|x64 + {3AF54C8A-10BF-4332-9147-F68ED9862032}.Debug|x64.Build.0 = Debug|x64 + {3AF54C8A-10BF-4332-9147-F68ED9862032}.Debug|x86.ActiveCfg = Debug|Win32 + {3AF54C8A-10BF-4332-9147-F68ED9862032}.Debug|x86.Build.0 = Debug|Win32 + {3AF54C8A-10BF-4332-9147-F68ED9862032}.Release|x64.ActiveCfg = Release|x64 + {3AF54C8A-10BF-4332-9147-F68ED9862032}.Release|x64.Build.0 = Release|x64 + {3AF54C8A-10BF-4332-9147-F68ED9862032}.Release|x86.ActiveCfg = Release|Win32 + {3AF54C8A-10BF-4332-9147-F68ED9862032}.Release|x86.Build.0 = Release|Win32 + {4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Debug|x64.ActiveCfg = Debug|x64 + {4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Debug|x64.Build.0 = Debug|x64 + {4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Debug|x86.ActiveCfg = Debug|Win32 + {4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Debug|x86.Build.0 = Debug|Win32 + {4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Release|x64.ActiveCfg = Release|x64 + {4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Release|x64.Build.0 = Release|x64 + {4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Release|x86.ActiveCfg = Release|Win32 + {4D9FDFB5-986A-4139-823C-F4EE0ED481A1}.Release|x86.Build.0 = Release|Win32 + {24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Debug|x64.ActiveCfg = Debug|x64 + {24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Debug|x64.Build.0 = Debug|x64 + {24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Debug|x86.ActiveCfg = Debug|Win32 + {24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Debug|x86.Build.0 = Debug|Win32 + {24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Release|x64.ActiveCfg = Release|x64 + {24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Release|x64.Build.0 = Release|x64 + {24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Release|x86.ActiveCfg = Release|Win32 + {24848551-EF4F-47E8-9A9D-EA4D49BC3ECA}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/lib/gtest/msvc/gtest.vcxproj b/lib/gtest/msvc/gtest.vcxproj new file mode 100644 index 00000000..69a54247 --- /dev/null +++ b/lib/gtest/msvc/gtest.vcxproj @@ -0,0 +1,134 @@ + + + + + Debug_StaticCrt + Win32 + + + Debug_StaticCrt + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_StaticCrt + Win32 + + + Release_StaticCrt + x64 + + + Release + Win32 + + + Release + x64 + + + + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7} + Win32Proj + libgtest + 8.1 + libgtest + + + + StaticLibrary + v140_xp + MultiByte + + + + + + + + + + <_ProjectFileVersion>14.0.22823.1 + $(SolutionDir)src\bin\$(Platform)\$(Configuration)-v$(PlatformToolsetVersion)\ + $(SolutionDir)src\obj\$(Platform)\$(Configuration)-v$(PlatformToolsetVersion)\$(ProjectName)\ + + + + Disabled + WIN32;_VARIADIC_MAX=10;_DEBUG;_LIB;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + Level3 + + + + + Disabled + WIN32;_VARIADIC_MAX=10;_DEBUG;_LIB;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebug + Level3 + + + + + Disabled + WIN32;_VARIADIC_MAX=10;_DEBUG;_LIB;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + Level3 + + + + + Disabled + WIN32;_VARIADIC_MAX=10;_DEBUG;_LIB;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebug + Level3 + + + + + WIN32;_VARIADIC_MAX=10;NDEBUG;_LIB;%(PreprocessorDefinitions) + MultiThreadedDLL + Level3 + + + + + WIN32;_VARIADIC_MAX=10;NDEBUG;_LIB;%(PreprocessorDefinitions) + MultiThreaded + Level3 + + + + + WIN32;_VARIADIC_MAX=10;NDEBUG;_LIB;%(PreprocessorDefinitions) + MultiThreadedDLL + Level3 + + + + + WIN32;_VARIADIC_MAX=10;NDEBUG;_LIB;%(PreprocessorDefinitions) + MultiThreaded + Level3 + + + + + ..;..\include;%(AdditionalIncludeDirectories) + + + + + + \ No newline at end of file diff --git a/lib/gtest/msvc/gtest.vcxproj.filters b/lib/gtest/msvc/gtest.vcxproj.filters new file mode 100644 index 00000000..b566f891 --- /dev/null +++ b/lib/gtest/msvc/gtest.vcxproj.filters @@ -0,0 +1,18 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + + + Source Files + + + \ No newline at end of file diff --git a/lib/gtest/msvc/gtest_main.vcxproj b/lib/gtest/msvc/gtest_main.vcxproj new file mode 100644 index 00000000..10527154 --- /dev/null +++ b/lib/gtest/msvc/gtest_main.vcxproj @@ -0,0 +1,152 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {3AF54C8A-10BF-4332-9147-F68ED9862032} + Win32Proj + + + + StaticLibrary + v120 + MultiByte + + + StaticLibrary + v120 + MultiByte + + + StaticLibrary + v120 + MultiByte + + + StaticLibrary + v120 + MultiByte + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>14.0.22823.1 + + + $(SolutionDir)bin\$(Platform)-$(Configuration)\ + obj\$(Platform)-$(Configuration)\$(ProjectName)\ + + + $(SolutionDir)bin\$(Platform)-$(Configuration)\ + obj\$(Platform)-$(Configuration)\$(ProjectName)\ + + + $(SolutionDir)bin\$(Platform)-$(Configuration)\ + obj\$(Platform)-$(Configuration)\$(ProjectName)\ + + + $(SolutionDir)bin\$(Platform)-$(Configuration)\ + obj\$(Platform)-$(Configuration)\$(ProjectName)\ + + + + Disabled + WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebug + + Level3 + EditAndContinue + + + $(OutDir)$(ProjectName)d.lib + + + + + Disabled + WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebug + + + Level3 + ProgramDatabase + + + $(OutDir)$(ProjectName)d.lib + + + + + WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) + MultiThreaded + + Level3 + ProgramDatabase + + + $(OutDir)$(ProjectName).lib + + + + + WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) + MultiThreaded + + + Level3 + ProgramDatabase + + + $(OutDir)$(ProjectName).lib + + + + + ..;..\include;%(AdditionalIncludeDirectories) + ..;..\include;%(AdditionalIncludeDirectories) + ..;..\include;%(AdditionalIncludeDirectories) + ..;..\include;%(AdditionalIncludeDirectories) + + + + + {c8f6c172-56f2-4e76-b5fa-c3b423b31be7} + + + + + + \ No newline at end of file diff --git a/lib/gtest/msvc/gtest_main.vcxproj.filters b/lib/gtest/msvc/gtest_main.vcxproj.filters new file mode 100644 index 00000000..b602e802 --- /dev/null +++ b/lib/gtest/msvc/gtest_main.vcxproj.filters @@ -0,0 +1,18 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + + + Source Files + + + \ No newline at end of file diff --git a/lib/gtest/msvc/gtest_prod_test.vcxproj b/lib/gtest/msvc/gtest_prod_test.vcxproj new file mode 100644 index 00000000..6894fdd0 --- /dev/null +++ b/lib/gtest/msvc/gtest_prod_test.vcxproj @@ -0,0 +1,195 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {24848551-EF4F-47E8-9A9D-EA4D49BC3ECA} + Win32Proj + + + + Application + v120 + MultiByte + + + Application + v120 + MultiByte + + + Application + v120 + MultiByte + + + Application + v120 + MultiByte + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>14.0.22823.1 + + + $(SolutionDir)bin\$(Platform)-$(Configuration)\ + obj\$(Platform)-$(Configuration)\$(ProjectName)\ + true + + + true + $(SolutionDir)bin\$(Platform)-$(Configuration)\ + obj\$(Platform)-$(Configuration)\$(ProjectName)\ + + + $(SolutionDir)bin\$(Platform)-$(Configuration)\ + obj\$(Platform)-$(Configuration)\$(ProjectName)\ + false + + + false + $(SolutionDir)bin\$(Platform)-$(Configuration)\ + obj\$(Platform)-$(Configuration)\$(ProjectName)\ + + + + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebug + Use + Level3 + EditAndContinue + + + $(OutDir)gtest_prod_test.exe + true + $(OutDir)gtest_prod_test.pdb + Console + MachineX86 + + + + + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebug + Use + Level3 + ProgramDatabase + + + $(OutDir)gtest_prod_test.exe + true + $(OutDir)gtest_prod_test.pdb + Console + + + + + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + Use + Level3 + ProgramDatabase + + + $(OutDir)gtest_prod_test.exe + true + Console + true + true + MachineX86 + + + + + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + Use + Level3 + ProgramDatabase + + + $(OutDir)gtest_prod_test.exe + true + Console + true + true + + + + + ..;..\include;%(AdditionalIncludeDirectories) + ..;..\include;%(AdditionalIncludeDirectories) + + + + + ..;..\include;%(AdditionalIncludeDirectories) + ..;..\include;%(AdditionalIncludeDirectories) + + + + + + + ..;..\include;%(AdditionalIncludeDirectories) + ..;..\include;%(AdditionalIncludeDirectories) + + + + + ..;..\include;%(AdditionalIncludeDirectories) + ..;..\include;%(AdditionalIncludeDirectories) + + + + + + + + + + + + {3af54c8a-10bf-4332-9147-f68ed9862032} + + + + + + \ No newline at end of file diff --git a/lib/gtest/msvc/gtest_prod_test.vcxproj.filters b/lib/gtest/msvc/gtest_prod_test.vcxproj.filters new file mode 100644 index 00000000..e4089cdd --- /dev/null +++ b/lib/gtest/msvc/gtest_prod_test.vcxproj.filters @@ -0,0 +1,26 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + + + Source Files + + + Source Files + + + + + Header Files + + + \ No newline at end of file diff --git a/lib/gtest/msvc/gtest_unittest.vcxproj b/lib/gtest/msvc/gtest_unittest.vcxproj new file mode 100644 index 00000000..5f224934 --- /dev/null +++ b/lib/gtest/msvc/gtest_unittest.vcxproj @@ -0,0 +1,184 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {4D9FDFB5-986A-4139-823C-F4EE0ED481A1} + Win32Proj + + + + Application + v120 + MultiByte + + + Application + v120 + MultiByte + + + Application + v120 + MultiByte + + + Application + v120 + MultiByte + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>14.0.22823.1 + + + $(SolutionDir)bin\$(Platform)-$(Configuration)\ + obj\$(Platform)-$(Configuration)\$(ProjectName)\ + true + + + true + $(SolutionDir)bin\$(Platform)-$(Configuration)\ + obj\$(Platform)-$(Configuration)\$(ProjectName)\ + + + $(SolutionDir)bin\$(Platform)-$(Configuration)\ + obj\$(Platform)-$(Configuration)\$(ProjectName)\ + false + + + false + $(SolutionDir)bin\$(Platform)-$(Configuration)\ + obj\$(Platform)-$(Configuration)\$(ProjectName)\ + + + + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebug + Use + Level3 + EditAndContinue + + + $(OutDir)gtest_unittest.exe + true + $(OutDir)gtest_unittest.pdb + Console + MachineX86 + + + + + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebug + Use + Level3 + ProgramDatabase + + + $(OutDir)gtest_unittest.exe + true + $(OutDir)gtest_unittest.pdb + Console + + + + + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + Use + Level3 + ProgramDatabase + + + $(OutDir)gtest_unittest.exe + true + Console + true + true + MachineX86 + + + + + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + Use + Level3 + ProgramDatabase + + + $(OutDir)gtest_unittest.exe + true + Console + true + true + + + + + MinSpace + MinSpace + ..;..\include;%(AdditionalIncludeDirectories) + ..;..\include;%(AdditionalIncludeDirectories) + Default + Default + + + + + ProgramDatabase + ProgramDatabase + ..;..\include;%(AdditionalIncludeDirectories) + ..;..\include;%(AdditionalIncludeDirectories) + + + + + + + + + {3af54c8a-10bf-4332-9147-f68ed9862032} + + + + + + \ No newline at end of file diff --git a/lib/gtest/msvc/gtest_unittest.vcxproj.filters b/lib/gtest/msvc/gtest_unittest.vcxproj.filters new file mode 100644 index 00000000..d3d56065 --- /dev/null +++ b/lib/gtest/msvc/gtest_unittest.vcxproj.filters @@ -0,0 +1,18 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + + + Source Files + + + \ No newline at end of file diff --git a/lib/gtest/src/gtest-all.cc b/lib/gtest/src/gtest-all.cc new file mode 100644 index 00000000..0a9cee52 --- /dev/null +++ b/lib/gtest/src/gtest-all.cc @@ -0,0 +1,48 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: mheule@google.com (Markus Heule) +// +// Google C++ Testing Framework (Google Test) +// +// Sometimes it's desirable to build Google Test by compiling a single file. +// This file serves this purpose. + +// This line ensures that gtest.h can be compiled on its own, even +// when it's fused. +#include "gtest/gtest.h" + +// The following lines pull in the real gtest *.cc files. +#include "src/gtest.cc" +#include "src/gtest-death-test.cc" +#include "src/gtest-filepath.cc" +#include "src/gtest-port.cc" +#include "src/gtest-printers.cc" +#include "src/gtest-test-part.cc" +#include "src/gtest-typed-test.cc" diff --git a/lib/gtest/src/gtest-death-test.cc b/lib/gtest/src/gtest-death-test.cc new file mode 100644 index 00000000..a6023fce --- /dev/null +++ b/lib/gtest/src/gtest-death-test.cc @@ -0,0 +1,1344 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) +// +// This file implements death tests. + +#include "gtest/gtest-death-test.h" +#include "gtest/internal/gtest-port.h" + +#if GTEST_HAS_DEATH_TEST + +# if GTEST_OS_MAC +# include +# endif // GTEST_OS_MAC + +# include +# include +# include + +# if GTEST_OS_LINUX +# include +# endif // GTEST_OS_LINUX + +# include + +# if GTEST_OS_WINDOWS +# include +# else +# include +# include +# endif // GTEST_OS_WINDOWS + +# if GTEST_OS_QNX +# include +# endif // GTEST_OS_QNX + +#endif // GTEST_HAS_DEATH_TEST + +#include "gtest/gtest-message.h" +#include "gtest/internal/gtest-string.h" + +// Indicates that this translation unit is part of Google Test's +// implementation. It must come before gtest-internal-inl.h is +// included, or there will be a compiler error. This trick is to +// prevent a user from accidentally including gtest-internal-inl.h in +// his code. +#define GTEST_IMPLEMENTATION_ 1 +#include "src/gtest-internal-inl.h" +#undef GTEST_IMPLEMENTATION_ + +namespace testing { + +// Constants. + +// The default death test style. +static const char kDefaultDeathTestStyle[] = "fast"; + +GTEST_DEFINE_string_( + death_test_style, + internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), + "Indicates how to run a death test in a forked child process: " + "\"threadsafe\" (child process re-executes the test binary " + "from the beginning, running only the specific death test) or " + "\"fast\" (child process runs the death test immediately " + "after forking)."); + +GTEST_DEFINE_bool_( + death_test_use_fork, + internal::BoolFromGTestEnv("death_test_use_fork", false), + "Instructs to use fork()/_exit() instead of clone() in death tests. " + "Ignored and always uses fork() on POSIX systems where clone() is not " + "implemented. Useful when running under valgrind or similar tools if " + "those do not support clone(). Valgrind 3.3.1 will just fail if " + "it sees an unsupported combination of clone() flags. " + "It is not recommended to use this flag w/o valgrind though it will " + "work in 99% of the cases. Once valgrind is fixed, this flag will " + "most likely be removed."); + +namespace internal { +GTEST_DEFINE_string_( + internal_run_death_test, "", + "Indicates the file, line number, temporal index of " + "the single death test to run, and a file descriptor to " + "which a success code may be sent, all separated by " + "the '|' characters. This flag is specified if and only if the current " + "process is a sub-process launched for running a thread-safe " + "death test. FOR INTERNAL USE ONLY."); +} // namespace internal + +#if GTEST_HAS_DEATH_TEST + +namespace internal { + +// Valid only for fast death tests. Indicates the code is running in the +// child process of a fast style death test. +static bool g_in_fast_death_test_child = false; + +// Returns a Boolean value indicating whether the caller is currently +// executing in the context of the death test child process. Tools such as +// Valgrind heap checkers may need this to modify their behavior in death +// tests. IMPORTANT: This is an internal utility. Using it may break the +// implementation of death tests. User code MUST NOT use it. +bool InDeathTestChild() { +# if GTEST_OS_WINDOWS + + // On Windows, death tests are thread-safe regardless of the value of the + // death_test_style flag. + return !GTEST_FLAG(internal_run_death_test).empty(); + +# else + + if (GTEST_FLAG(death_test_style) == "threadsafe") + return !GTEST_FLAG(internal_run_death_test).empty(); + else + return g_in_fast_death_test_child; +#endif +} + +} // namespace internal + +// ExitedWithCode constructor. +ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { +} + +// ExitedWithCode function-call operator. +bool ExitedWithCode::operator()(int exit_status) const { +# if GTEST_OS_WINDOWS + + return exit_status == exit_code_; + +# else + + return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; + +# endif // GTEST_OS_WINDOWS +} + +# if !GTEST_OS_WINDOWS +// KilledBySignal constructor. +KilledBySignal::KilledBySignal(int signum) : signum_(signum) { +} + +// KilledBySignal function-call operator. +bool KilledBySignal::operator()(int exit_status) const { + return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; +} +# endif // !GTEST_OS_WINDOWS + +namespace internal { + +// Utilities needed for death tests. + +// Generates a textual description of a given exit code, in the format +// specified by wait(2). +static std::string ExitSummary(int exit_code) { + Message m; + +# if GTEST_OS_WINDOWS + + m << "Exited with exit status " << exit_code; + +# else + + if (WIFEXITED(exit_code)) { + m << "Exited with exit status " << WEXITSTATUS(exit_code); + } else if (WIFSIGNALED(exit_code)) { + m << "Terminated by signal " << WTERMSIG(exit_code); + } +# ifdef WCOREDUMP + if (WCOREDUMP(exit_code)) { + m << " (core dumped)"; + } +# endif +# endif // GTEST_OS_WINDOWS + + return m.GetString(); +} + +// Returns true if exit_status describes a process that was terminated +// by a signal, or exited normally with a nonzero exit code. +bool ExitedUnsuccessfully(int exit_status) { + return !ExitedWithCode(0)(exit_status); +} + +# if !GTEST_OS_WINDOWS +// Generates a textual failure message when a death test finds more than +// one thread running, or cannot determine the number of threads, prior +// to executing the given statement. It is the responsibility of the +// caller not to pass a thread_count of 1. +static std::string DeathTestThreadWarning(size_t thread_count) { + Message msg; + msg << "Death tests use fork(), which is unsafe particularly" + << " in a threaded context. For this test, " << GTEST_NAME_ << " "; + if (thread_count == 0) + msg << "couldn't detect the number of threads."; + else + msg << "detected " << thread_count << " threads."; + return msg.GetString(); +} +# endif // !GTEST_OS_WINDOWS + +// Flag characters for reporting a death test that did not die. +static const char kDeathTestLived = 'L'; +static const char kDeathTestReturned = 'R'; +static const char kDeathTestThrew = 'T'; +static const char kDeathTestInternalError = 'I'; + +// An enumeration describing all of the possible ways that a death test can +// conclude. DIED means that the process died while executing the test +// code; LIVED means that process lived beyond the end of the test code; +// RETURNED means that the test statement attempted to execute a return +// statement, which is not allowed; THREW means that the test statement +// returned control by throwing an exception. IN_PROGRESS means the test +// has not yet concluded. +// TODO(vladl@google.com): Unify names and possibly values for +// AbortReason, DeathTestOutcome, and flag characters above. +enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; + +// Routine for aborting the program which is safe to call from an +// exec-style death test child process, in which case the error +// message is propagated back to the parent process. Otherwise, the +// message is simply printed to stderr. In either case, the program +// then exits with status 1. +void DeathTestAbort(const std::string& message) { + // On a POSIX system, this function may be called from a threadsafe-style + // death test child process, which operates on a very small stack. Use + // the heap for any additional non-minuscule memory requirements. + const InternalRunDeathTestFlag* const flag = + GetUnitTestImpl()->internal_run_death_test_flag(); + if (flag != NULL) { + FILE* parent = posix::FDOpen(flag->write_fd(), "w"); + fputc(kDeathTestInternalError, parent); + fprintf(parent, "%s", message.c_str()); + fflush(parent); + _exit(1); + } else { + fprintf(stderr, "%s", message.c_str()); + fflush(stderr); + posix::Abort(); + } +} + +// A replacement for CHECK that calls DeathTestAbort if the assertion +// fails. +# define GTEST_DEATH_TEST_CHECK_(expression) \ + do { \ + if (!::testing::internal::IsTrue(expression)) { \ + DeathTestAbort( \ + ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ + + ::testing::internal::StreamableToString(__LINE__) + ": " \ + + #expression); \ + } \ + } while (::testing::internal::AlwaysFalse()) + +// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for +// evaluating any system call that fulfills two conditions: it must return +// -1 on failure, and set errno to EINTR when it is interrupted and +// should be tried again. The macro expands to a loop that repeatedly +// evaluates the expression as long as it evaluates to -1 and sets +// errno to EINTR. If the expression evaluates to -1 but errno is +// something other than EINTR, DeathTestAbort is called. +# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ + do { \ + int gtest_retval; \ + do { \ + gtest_retval = (expression); \ + } while (gtest_retval == -1 && errno == EINTR); \ + if (gtest_retval == -1) { \ + DeathTestAbort( \ + ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ + + ::testing::internal::StreamableToString(__LINE__) + ": " \ + + #expression + " != -1"); \ + } \ + } while (::testing::internal::AlwaysFalse()) + +// Returns the message describing the last system error in errno. +std::string GetLastErrnoDescription() { + return errno == 0 ? "" : posix::StrError(errno); +} + +// This is called from a death test parent process to read a failure +// message from the death test child process and log it with the FATAL +// severity. On Windows, the message is read from a pipe handle. On other +// platforms, it is read from a file descriptor. +static void FailFromInternalError(int fd) { + Message error; + char buffer[256]; + int num_read; + + do { + while ((num_read = posix::Read(fd, buffer, 255)) > 0) { + buffer[num_read] = '\0'; + error << buffer; + } + } while (num_read == -1 && errno == EINTR); + + if (num_read == 0) { + GTEST_LOG_(FATAL) << error.GetString(); + } else { + const int last_error = errno; + GTEST_LOG_(FATAL) << "Error while reading death test internal: " + << GetLastErrnoDescription() << " [" << last_error << "]"; + } +} + +// Death test constructor. Increments the running death test count +// for the current test. +DeathTest::DeathTest() { + TestInfo* const info = GetUnitTestImpl()->current_test_info(); + if (info == NULL) { + DeathTestAbort("Cannot run a death test outside of a TEST or " + "TEST_F construct"); + } +} + +// Creates and returns a death test by dispatching to the current +// death test factory. +bool DeathTest::Create(const char* statement, const RE* regex, + const char* file, int line, DeathTest** test) { + return GetUnitTestImpl()->death_test_factory()->Create( + statement, regex, file, line, test); +} + +const char* DeathTest::LastMessage() { + return last_death_test_message_.c_str(); +} + +void DeathTest::set_last_death_test_message(const std::string& message) { + last_death_test_message_ = message; +} + +std::string DeathTest::last_death_test_message_; + +// Provides cross platform implementation for some death functionality. +class DeathTestImpl : public DeathTest { + protected: + DeathTestImpl(const char* a_statement, const RE* a_regex) + : statement_(a_statement), + regex_(a_regex), + spawned_(false), + status_(-1), + outcome_(IN_PROGRESS), + read_fd_(-1), + write_fd_(-1) {} + + // read_fd_ is expected to be closed and cleared by a derived class. + ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } + + void Abort(AbortReason reason); + virtual bool Passed(bool status_ok); + + const char* statement() const { return statement_; } + const RE* regex() const { return regex_; } + bool spawned() const { return spawned_; } + void set_spawned(bool is_spawned) { spawned_ = is_spawned; } + int status() const { return status_; } + void set_status(int a_status) { status_ = a_status; } + DeathTestOutcome outcome() const { return outcome_; } + void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; } + int read_fd() const { return read_fd_; } + void set_read_fd(int fd) { read_fd_ = fd; } + int write_fd() const { return write_fd_; } + void set_write_fd(int fd) { write_fd_ = fd; } + + // Called in the parent process only. Reads the result code of the death + // test child process via a pipe, interprets it to set the outcome_ + // member, and closes read_fd_. Outputs diagnostics and terminates in + // case of unexpected codes. + void ReadAndInterpretStatusByte(); + + private: + // The textual content of the code this object is testing. This class + // doesn't own this string and should not attempt to delete it. + const char* const statement_; + // The regular expression which test output must match. DeathTestImpl + // doesn't own this object and should not attempt to delete it. + const RE* const regex_; + // True if the death test child process has been successfully spawned. + bool spawned_; + // The exit status of the child process. + int status_; + // How the death test concluded. + DeathTestOutcome outcome_; + // Descriptor to the read end of the pipe to the child process. It is + // always -1 in the child process. The child keeps its write end of the + // pipe in write_fd_. + int read_fd_; + // Descriptor to the child's write end of the pipe to the parent process. + // It is always -1 in the parent process. The parent keeps its end of the + // pipe in read_fd_. + int write_fd_; +}; + +// Called in the parent process only. Reads the result code of the death +// test child process via a pipe, interprets it to set the outcome_ +// member, and closes read_fd_. Outputs diagnostics and terminates in +// case of unexpected codes. +void DeathTestImpl::ReadAndInterpretStatusByte() { + char flag; + int bytes_read; + + // The read() here blocks until data is available (signifying the + // failure of the death test) or until the pipe is closed (signifying + // its success), so it's okay to call this in the parent before + // the child process has exited. + do { + bytes_read = posix::Read(read_fd(), &flag, 1); + } while (bytes_read == -1 && errno == EINTR); + + if (bytes_read == 0) { + set_outcome(DIED); + } else if (bytes_read == 1) { + switch (flag) { + case kDeathTestReturned: + set_outcome(RETURNED); + break; + case kDeathTestThrew: + set_outcome(THREW); + break; + case kDeathTestLived: + set_outcome(LIVED); + break; + case kDeathTestInternalError: + FailFromInternalError(read_fd()); // Does not return. + break; + default: + GTEST_LOG_(FATAL) << "Death test child process reported " + << "unexpected status byte (" + << static_cast(flag) << ")"; + } + } else { + GTEST_LOG_(FATAL) << "Read from death test child process failed: " + << GetLastErrnoDescription(); + } + GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd())); + set_read_fd(-1); +} + +// Signals that the death test code which should have exited, didn't. +// Should be called only in a death test child process. +// Writes a status byte to the child's status file descriptor, then +// calls _exit(1). +void DeathTestImpl::Abort(AbortReason reason) { + // The parent process considers the death test to be a failure if + // it finds any data in our pipe. So, here we write a single flag byte + // to the pipe, then exit. + const char status_ch = + reason == TEST_DID_NOT_DIE ? kDeathTestLived : + reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; + + GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); + // We are leaking the descriptor here because on some platforms (i.e., + // when built as Windows DLL), destructors of global objects will still + // run after calling _exit(). On such systems, write_fd_ will be + // indirectly closed from the destructor of UnitTestImpl, causing double + // close if it is also closed here. On debug configurations, double close + // may assert. As there are no in-process buffers to flush here, we are + // relying on the OS to close the descriptor after the process terminates + // when the destructors are not run. + _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) +} + +// Returns an indented copy of stderr output for a death test. +// This makes distinguishing death test output lines from regular log lines +// much easier. +static ::std::string FormatDeathTestOutput(const ::std::string& output) { + ::std::string ret; + for (size_t at = 0; ; ) { + const size_t line_end = output.find('\n', at); + ret += "[ DEATH ] "; + if (line_end == ::std::string::npos) { + ret += output.substr(at); + break; + } + ret += output.substr(at, line_end + 1 - at); + at = line_end + 1; + } + return ret; +} + +// Assesses the success or failure of a death test, using both private +// members which have previously been set, and one argument: +// +// Private data members: +// outcome: An enumeration describing how the death test +// concluded: DIED, LIVED, THREW, or RETURNED. The death test +// fails in the latter three cases. +// status: The exit status of the child process. On *nix, it is in the +// in the format specified by wait(2). On Windows, this is the +// value supplied to the ExitProcess() API or a numeric code +// of the exception that terminated the program. +// regex: A regular expression object to be applied to +// the test's captured standard error output; the death test +// fails if it does not match. +// +// Argument: +// status_ok: true if exit_status is acceptable in the context of +// this particular death test, which fails if it is false +// +// Returns true iff all of the above conditions are met. Otherwise, the +// first failing condition, in the order given above, is the one that is +// reported. Also sets the last death test message string. +bool DeathTestImpl::Passed(bool status_ok) { + if (!spawned()) + return false; + + const std::string error_message = GetCapturedStderr(); + + bool success = false; + Message buffer; + + buffer << "Death test: " << statement() << "\n"; + switch (outcome()) { + case LIVED: + buffer << " Result: failed to die.\n" + << " Error msg:\n" << FormatDeathTestOutput(error_message); + break; + case THREW: + buffer << " Result: threw an exception.\n" + << " Error msg:\n" << FormatDeathTestOutput(error_message); + break; + case RETURNED: + buffer << " Result: illegal return in test statement.\n" + << " Error msg:\n" << FormatDeathTestOutput(error_message); + break; + case DIED: + if (status_ok) { + const bool matched = RE::PartialMatch(error_message.c_str(), *regex()); + if (matched) { + success = true; + } else { + buffer << " Result: died but not with expected error.\n" + << " Expected: " << regex()->pattern() << "\n" + << "Actual msg:\n" << FormatDeathTestOutput(error_message); + } + } else { + buffer << " Result: died but not with expected exit code:\n" + << " " << ExitSummary(status()) << "\n" + << "Actual msg:\n" << FormatDeathTestOutput(error_message); + } + break; + case IN_PROGRESS: + default: + GTEST_LOG_(FATAL) + << "DeathTest::Passed somehow called before conclusion of test"; + } + + DeathTest::set_last_death_test_message(buffer.GetString()); + return success; +} + +# if GTEST_OS_WINDOWS +// WindowsDeathTest implements death tests on Windows. Due to the +// specifics of starting new processes on Windows, death tests there are +// always threadsafe, and Google Test considers the +// --gtest_death_test_style=fast setting to be equivalent to +// --gtest_death_test_style=threadsafe there. +// +// A few implementation notes: Like the Linux version, the Windows +// implementation uses pipes for child-to-parent communication. But due to +// the specifics of pipes on Windows, some extra steps are required: +// +// 1. The parent creates a communication pipe and stores handles to both +// ends of it. +// 2. The parent starts the child and provides it with the information +// necessary to acquire the handle to the write end of the pipe. +// 3. The child acquires the write end of the pipe and signals the parent +// using a Windows event. +// 4. Now the parent can release the write end of the pipe on its side. If +// this is done before step 3, the object's reference count goes down to +// 0 and it is destroyed, preventing the child from acquiring it. The +// parent now has to release it, or read operations on the read end of +// the pipe will not return when the child terminates. +// 5. The parent reads child's output through the pipe (outcome code and +// any possible error messages) from the pipe, and its stderr and then +// determines whether to fail the test. +// +// Note: to distinguish Win32 API calls from the local method and function +// calls, the former are explicitly resolved in the global namespace. +// +class WindowsDeathTest : public DeathTestImpl { + public: + WindowsDeathTest(const char* a_statement, + const RE* a_regex, + const char* file, + int line) + : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {} + + // All of these virtual functions are inherited from DeathTest. + virtual int Wait(); + virtual TestRole AssumeRole(); + + private: + // The name of the file in which the death test is located. + const char* const file_; + // The line number on which the death test is located. + const int line_; + // Handle to the write end of the pipe to the child process. + AutoHandle write_handle_; + // Child process handle. + AutoHandle child_handle_; + // Event the child process uses to signal the parent that it has + // acquired the handle to the write end of the pipe. After seeing this + // event the parent can release its own handles to make sure its + // ReadFile() calls return when the child terminates. + AutoHandle event_handle_; +}; + +// Waits for the child in a death test to exit, returning its exit +// status, or 0 if no child process exists. As a side effect, sets the +// outcome data member. +int WindowsDeathTest::Wait() { + if (!spawned()) + return 0; + + // Wait until the child either signals that it has acquired the write end + // of the pipe or it dies. + const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; + switch (::WaitForMultipleObjects(2, + wait_handles, + FALSE, // Waits for any of the handles. + INFINITE)) { + case WAIT_OBJECT_0: + case WAIT_OBJECT_0 + 1: + break; + default: + GTEST_DEATH_TEST_CHECK_(false); // Should not get here. + } + + // The child has acquired the write end of the pipe or exited. + // We release the handle on our side and continue. + write_handle_.Reset(); + event_handle_.Reset(); + + ReadAndInterpretStatusByte(); + + // Waits for the child process to exit if it haven't already. This + // returns immediately if the child has already exited, regardless of + // whether previous calls to WaitForMultipleObjects synchronized on this + // handle or not. + GTEST_DEATH_TEST_CHECK_( + WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), + INFINITE)); + DWORD status_code; + GTEST_DEATH_TEST_CHECK_( + ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); + child_handle_.Reset(); + set_status(static_cast(status_code)); + return status(); +} + +// The AssumeRole process for a Windows death test. It creates a child +// process with the same executable as the current process to run the +// death test. The child process is given the --gtest_filter and +// --gtest_internal_run_death_test flags such that it knows to run the +// current death test only. +DeathTest::TestRole WindowsDeathTest::AssumeRole() { + const UnitTestImpl* const impl = GetUnitTestImpl(); + const InternalRunDeathTestFlag* const flag = + impl->internal_run_death_test_flag(); + const TestInfo* const info = impl->current_test_info(); + const int death_test_index = info->result()->death_test_count(); + + if (flag != NULL) { + // ParseInternalRunDeathTestFlag() has performed all the necessary + // processing. + set_write_fd(flag->write_fd()); + return EXECUTE_TEST; + } + + // WindowsDeathTest uses an anonymous pipe to communicate results of + // a death test. + SECURITY_ATTRIBUTES handles_are_inheritable = { + sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; + HANDLE read_handle, write_handle; + GTEST_DEATH_TEST_CHECK_( + ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, + 0) // Default buffer size. + != FALSE); + set_read_fd(::_open_osfhandle(reinterpret_cast(read_handle), + O_RDONLY)); + write_handle_.Reset(write_handle); + event_handle_.Reset(::CreateEvent( + &handles_are_inheritable, + TRUE, // The event will automatically reset to non-signaled state. + FALSE, // The initial state is non-signalled. + NULL)); // The even is unnamed. + GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); + const std::string filter_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + + info->test_case_name() + "." + info->name(); + const std::string internal_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + + "=" + file_ + "|" + StreamableToString(line_) + "|" + + StreamableToString(death_test_index) + "|" + + StreamableToString(static_cast(::GetCurrentProcessId())) + + // size_t has the same width as pointers on both 32-bit and 64-bit + // Windows platforms. + // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. + "|" + StreamableToString(reinterpret_cast(write_handle)) + + "|" + StreamableToString(reinterpret_cast(event_handle_.Get())); + + char executable_path[_MAX_PATH + 1]; // NOLINT + GTEST_DEATH_TEST_CHECK_( + _MAX_PATH + 1 != ::GetModuleFileNameA(NULL, + executable_path, + _MAX_PATH)); + + std::string command_line = + std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + + internal_flag + "\""; + + DeathTest::set_last_death_test_message(""); + + CaptureStderr(); + // Flush the log buffers since the log streams are shared with the child. + FlushInfoLog(); + + // The child process will share the standard handles with the parent. + STARTUPINFOA startup_info; + memset(&startup_info, 0, sizeof(STARTUPINFO)); + startup_info.dwFlags = STARTF_USESTDHANDLES; + startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); + startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE); + startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); + + PROCESS_INFORMATION process_info; + GTEST_DEATH_TEST_CHECK_(::CreateProcessA( + executable_path, + const_cast(command_line.c_str()), + NULL, // Retuned process handle is not inheritable. + NULL, // Retuned thread handle is not inheritable. + TRUE, // Child inherits all inheritable handles (for write_handle_). + 0x0, // Default creation flags. + NULL, // Inherit the parent's environment. + UnitTest::GetInstance()->original_working_dir(), + &startup_info, + &process_info) != FALSE); + child_handle_.Reset(process_info.hProcess); + ::CloseHandle(process_info.hThread); + set_spawned(true); + return OVERSEE_TEST; +} +# else // We are not on Windows. + +// ForkingDeathTest provides implementations for most of the abstract +// methods of the DeathTest interface. Only the AssumeRole method is +// left undefined. +class ForkingDeathTest : public DeathTestImpl { + public: + ForkingDeathTest(const char* statement, const RE* regex); + + // All of these virtual functions are inherited from DeathTest. + virtual int Wait(); + + protected: + void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; } + + private: + // PID of child process during death test; 0 in the child process itself. + pid_t child_pid_; +}; + +// Constructs a ForkingDeathTest. +ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex) + : DeathTestImpl(a_statement, a_regex), + child_pid_(-1) {} + +// Waits for the child in a death test to exit, returning its exit +// status, or 0 if no child process exists. As a side effect, sets the +// outcome data member. +int ForkingDeathTest::Wait() { + if (!spawned()) + return 0; + + ReadAndInterpretStatusByte(); + + int status_value; + GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0)); + set_status(status_value); + return status_value; +} + +// A concrete death test class that forks, then immediately runs the test +// in the child process. +class NoExecDeathTest : public ForkingDeathTest { + public: + NoExecDeathTest(const char* a_statement, const RE* a_regex) : + ForkingDeathTest(a_statement, a_regex) { } + virtual TestRole AssumeRole(); +}; + +// The AssumeRole process for a fork-and-run death test. It implements a +// straightforward fork, with a simple pipe to transmit the status byte. +DeathTest::TestRole NoExecDeathTest::AssumeRole() { + const size_t thread_count = GetThreadCount(); + if (thread_count != 1) { + GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count); + } + + int pipe_fd[2]; + GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); + + DeathTest::set_last_death_test_message(""); + CaptureStderr(); + // When we fork the process below, the log file buffers are copied, but the + // file descriptors are shared. We flush all log files here so that closing + // the file descriptors in the child process doesn't throw off the + // synchronization between descriptors and buffers in the parent process. + // This is as close to the fork as possible to avoid a race condition in case + // there are multiple threads running before the death test, and another + // thread writes to the log file. + FlushInfoLog(); + + const pid_t child_pid = fork(); + GTEST_DEATH_TEST_CHECK_(child_pid != -1); + set_child_pid(child_pid); + if (child_pid == 0) { + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0])); + set_write_fd(pipe_fd[1]); + // Redirects all logging to stderr in the child process to prevent + // concurrent writes to the log files. We capture stderr in the parent + // process and append the child process' output to a log. + LogToStderr(); + // Event forwarding to the listeners of event listener API mush be shut + // down in death test subprocesses. + GetUnitTestImpl()->listeners()->SuppressEventForwarding(); + g_in_fast_death_test_child = true; + return EXECUTE_TEST; + } else { + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); + set_read_fd(pipe_fd[0]); + set_spawned(true); + return OVERSEE_TEST; + } +} + +// A concrete death test class that forks and re-executes the main +// program from the beginning, with command-line flags set that cause +// only this specific death test to be run. +class ExecDeathTest : public ForkingDeathTest { + public: + ExecDeathTest(const char* a_statement, const RE* a_regex, + const char* file, int line) : + ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { } + virtual TestRole AssumeRole(); + private: + static ::std::vector + GetArgvsForDeathTestChildProcess() { + ::std::vector args = GetInjectableArgvs(); + return args; + } + // The name of the file in which the death test is located. + const char* const file_; + // The line number on which the death test is located. + const int line_; +}; + +// Utility class for accumulating command-line arguments. +class Arguments { + public: + Arguments() { + args_.push_back(NULL); + } + + ~Arguments() { + for (std::vector::iterator i = args_.begin(); i != args_.end(); + ++i) { + free(*i); + } + } + void AddArgument(const char* argument) { + args_.insert(args_.end() - 1, posix::StrDup(argument)); + } + + template + void AddArguments(const ::std::vector& arguments) { + for (typename ::std::vector::const_iterator i = arguments.begin(); + i != arguments.end(); + ++i) { + args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); + } + } + char* const* Argv() { + return &args_[0]; + } + + private: + std::vector args_; +}; + +// A struct that encompasses the arguments to the child process of a +// threadsafe-style death test process. +struct ExecDeathTestArgs { + char* const* argv; // Command-line arguments for the child's call to exec + int close_fd; // File descriptor to close; the read end of a pipe +}; + +# if GTEST_OS_MAC +inline char** GetEnviron() { + // When Google Test is built as a framework on MacOS X, the environ variable + // is unavailable. Apple's documentation (man environ) recommends using + // _NSGetEnviron() instead. + return *_NSGetEnviron(); +} +# else +// Some POSIX platforms expect you to declare environ. extern "C" makes +// it reside in the global namespace. +extern "C" char** environ; +inline char** GetEnviron() { return environ; } +# endif // GTEST_OS_MAC + +# if !GTEST_OS_QNX +// The main function for a threadsafe-style death test child process. +// This function is called in a clone()-ed process and thus must avoid +// any potentially unsafe operations like malloc or libc functions. +static int ExecDeathTestChildMain(void* child_arg) { + ExecDeathTestArgs* const args = static_cast(child_arg); + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd)); + + // We need to execute the test program in the same environment where + // it was originally invoked. Therefore we change to the original + // working directory first. + const char* const original_dir = + UnitTest::GetInstance()->original_working_dir(); + // We can safely call chdir() as it's a direct system call. + if (chdir(original_dir) != 0) { + DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + + GetLastErrnoDescription()); + return EXIT_FAILURE; + } + + // We can safely call execve() as it's a direct system call. We + // cannot use execvp() as it's a libc function and thus potentially + // unsafe. Since execve() doesn't search the PATH, the user must + // invoke the test program via a valid path that contains at least + // one path separator. + execve(args->argv[0], args->argv, GetEnviron()); + DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " + + original_dir + " failed: " + + GetLastErrnoDescription()); + return EXIT_FAILURE; +} +# endif // !GTEST_OS_QNX + +// Two utility routines that together determine the direction the stack +// grows. +// This could be accomplished more elegantly by a single recursive +// function, but we want to guard against the unlikely possibility of +// a smart compiler optimizing the recursion away. +// +// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining +// StackLowerThanAddress into StackGrowsDown, which then doesn't give +// correct answer. +void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_; +void StackLowerThanAddress(const void* ptr, bool* result) { + int dummy; + *result = (&dummy < ptr); +} + +bool StackGrowsDown() { + int dummy; + bool result; + StackLowerThanAddress(&dummy, &result); + return result; +} + +// Spawns a child process with the same executable as the current process in +// a thread-safe manner and instructs it to run the death test. The +// implementation uses fork(2) + exec. On systems where clone(2) is +// available, it is used instead, being slightly more thread-safe. On QNX, +// fork supports only single-threaded environments, so this function uses +// spawn(2) there instead. The function dies with an error message if +// anything goes wrong. +static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { + ExecDeathTestArgs args = { argv, close_fd }; + pid_t child_pid = -1; + +# if GTEST_OS_QNX + // Obtains the current directory and sets it to be closed in the child + // process. + const int cwd_fd = open(".", O_RDONLY); + GTEST_DEATH_TEST_CHECK_(cwd_fd != -1); + GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC)); + // We need to execute the test program in the same environment where + // it was originally invoked. Therefore we change to the original + // working directory first. + const char* const original_dir = + UnitTest::GetInstance()->original_working_dir(); + // We can safely call chdir() as it's a direct system call. + if (chdir(original_dir) != 0) { + DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + + GetLastErrnoDescription()); + return EXIT_FAILURE; + } + + int fd_flags; + // Set close_fd to be closed after spawn. + GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD)); + GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, + fd_flags | FD_CLOEXEC)); + struct inheritance inherit = {0}; + // spawn is a system call. + child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron()); + // Restores the current working directory. + GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); + +# else // GTEST_OS_QNX +# if GTEST_OS_LINUX + // When a SIGPROF signal is received while fork() or clone() are executing, + // the process may hang. To avoid this, we ignore SIGPROF here and re-enable + // it after the call to fork()/clone() is complete. + struct sigaction saved_sigprof_action; + struct sigaction ignore_sigprof_action; + memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action)); + sigemptyset(&ignore_sigprof_action.sa_mask); + ignore_sigprof_action.sa_handler = SIG_IGN; + GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction( + SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); +# endif // GTEST_OS_LINUX + +# if GTEST_HAS_CLONE + const bool use_fork = GTEST_FLAG(death_test_use_fork); + + if (!use_fork) { + static const bool stack_grows_down = StackGrowsDown(); + const size_t stack_size = getpagesize(); + // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. + void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); + + // Maximum stack alignment in bytes: For a downward-growing stack, this + // amount is subtracted from size of the stack space to get an address + // that is within the stack space and is aligned on all systems we care + // about. As far as I know there is no ABI with stack alignment greater + // than 64. We assume stack and stack_size already have alignment of + // kMaxStackAlignment. + const size_t kMaxStackAlignment = 64; + void* const stack_top = + static_cast(stack) + + (stack_grows_down ? stack_size - kMaxStackAlignment : 0); + GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment && + reinterpret_cast(stack_top) % kMaxStackAlignment == 0); + + child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); + + GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); + } +# else + const bool use_fork = true; +# endif // GTEST_HAS_CLONE + + if (use_fork && (child_pid = fork()) == 0) { + ExecDeathTestChildMain(&args); + _exit(0); + } +# endif // GTEST_OS_QNX +# if GTEST_OS_LINUX + GTEST_DEATH_TEST_CHECK_SYSCALL_( + sigaction(SIGPROF, &saved_sigprof_action, NULL)); +# endif // GTEST_OS_LINUX + + GTEST_DEATH_TEST_CHECK_(child_pid != -1); + return child_pid; +} + +// The AssumeRole process for a fork-and-exec death test. It re-executes the +// main program from the beginning, setting the --gtest_filter +// and --gtest_internal_run_death_test flags to cause only the current +// death test to be re-run. +DeathTest::TestRole ExecDeathTest::AssumeRole() { + const UnitTestImpl* const impl = GetUnitTestImpl(); + const InternalRunDeathTestFlag* const flag = + impl->internal_run_death_test_flag(); + const TestInfo* const info = impl->current_test_info(); + const int death_test_index = info->result()->death_test_count(); + + if (flag != NULL) { + set_write_fd(flag->write_fd()); + return EXECUTE_TEST; + } + + int pipe_fd[2]; + GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); + // Clear the close-on-exec flag on the write end of the pipe, lest + // it be closed when the child process does an exec: + GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); + + const std::string filter_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + + info->test_case_name() + "." + info->name(); + const std::string internal_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + + file_ + "|" + StreamableToString(line_) + "|" + + StreamableToString(death_test_index) + "|" + + StreamableToString(pipe_fd[1]); + Arguments args; + args.AddArguments(GetArgvsForDeathTestChildProcess()); + args.AddArgument(filter_flag.c_str()); + args.AddArgument(internal_flag.c_str()); + + DeathTest::set_last_death_test_message(""); + + CaptureStderr(); + // See the comment in NoExecDeathTest::AssumeRole for why the next line + // is necessary. + FlushInfoLog(); + + const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]); + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); + set_child_pid(child_pid); + set_read_fd(pipe_fd[0]); + set_spawned(true); + return OVERSEE_TEST; +} + +# endif // !GTEST_OS_WINDOWS + +// Creates a concrete DeathTest-derived class that depends on the +// --gtest_death_test_style flag, and sets the pointer pointed to +// by the "test" argument to its address. If the test should be +// skipped, sets that pointer to NULL. Returns true, unless the +// flag is set to an invalid value. +bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, + const char* file, int line, + DeathTest** test) { + UnitTestImpl* const impl = GetUnitTestImpl(); + const InternalRunDeathTestFlag* const flag = + impl->internal_run_death_test_flag(); + const int death_test_index = impl->current_test_info() + ->increment_death_test_count(); + + if (flag != NULL) { + if (death_test_index > flag->index()) { + DeathTest::set_last_death_test_message( + "Death test count (" + StreamableToString(death_test_index) + + ") somehow exceeded expected maximum (" + + StreamableToString(flag->index()) + ")"); + return false; + } + + if (!(flag->file() == file && flag->line() == line && + flag->index() == death_test_index)) { + *test = NULL; + return true; + } + } + +# if GTEST_OS_WINDOWS + + if (GTEST_FLAG(death_test_style) == "threadsafe" || + GTEST_FLAG(death_test_style) == "fast") { + *test = new WindowsDeathTest(statement, regex, file, line); + } + +# else + + if (GTEST_FLAG(death_test_style) == "threadsafe") { + *test = new ExecDeathTest(statement, regex, file, line); + } else if (GTEST_FLAG(death_test_style) == "fast") { + *test = new NoExecDeathTest(statement, regex); + } + +# endif // GTEST_OS_WINDOWS + + else { // NOLINT - this is more readable than unbalanced brackets inside #if. + DeathTest::set_last_death_test_message( + "Unknown death test style \"" + GTEST_FLAG(death_test_style) + + "\" encountered"); + return false; + } + + return true; +} + +// Splits a given string on a given delimiter, populating a given +// vector with the fields. GTEST_HAS_DEATH_TEST implies that we have +// ::std::string, so we can use it here. +static void SplitString(const ::std::string& str, char delimiter, + ::std::vector< ::std::string>* dest) { + ::std::vector< ::std::string> parsed; + ::std::string::size_type pos = 0; + while (::testing::internal::AlwaysTrue()) { + const ::std::string::size_type colon = str.find(delimiter, pos); + if (colon == ::std::string::npos) { + parsed.push_back(str.substr(pos)); + break; + } else { + parsed.push_back(str.substr(pos, colon - pos)); + pos = colon + 1; + } + } + dest->swap(parsed); +} + +# if GTEST_OS_WINDOWS +// Recreates the pipe and event handles from the provided parameters, +// signals the event, and returns a file descriptor wrapped around the pipe +// handle. This function is called in the child process only. +int GetStatusFileDescriptor(unsigned int parent_process_id, + size_t write_handle_as_size_t, + size_t event_handle_as_size_t) { + AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, + FALSE, // Non-inheritable. + parent_process_id)); + if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { + DeathTestAbort("Unable to open parent process " + + StreamableToString(parent_process_id)); + } + + // TODO(vladl@google.com): Replace the following check with a + // compile-time assertion when available. + GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); + + const HANDLE write_handle = + reinterpret_cast(write_handle_as_size_t); + HANDLE dup_write_handle; + + // The newly initialized handle is accessible only in in the parent + // process. To obtain one accessible within the child, we need to use + // DuplicateHandle. + if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, + ::GetCurrentProcess(), &dup_write_handle, + 0x0, // Requested privileges ignored since + // DUPLICATE_SAME_ACCESS is used. + FALSE, // Request non-inheritable handler. + DUPLICATE_SAME_ACCESS)) { + DeathTestAbort("Unable to duplicate the pipe handle " + + StreamableToString(write_handle_as_size_t) + + " from the parent process " + + StreamableToString(parent_process_id)); + } + + const HANDLE event_handle = reinterpret_cast(event_handle_as_size_t); + HANDLE dup_event_handle; + + if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, + ::GetCurrentProcess(), &dup_event_handle, + 0x0, + FALSE, + DUPLICATE_SAME_ACCESS)) { + DeathTestAbort("Unable to duplicate the event handle " + + StreamableToString(event_handle_as_size_t) + + " from the parent process " + + StreamableToString(parent_process_id)); + } + + const int write_fd = + ::_open_osfhandle(reinterpret_cast(dup_write_handle), O_APPEND); + if (write_fd == -1) { + DeathTestAbort("Unable to convert pipe handle " + + StreamableToString(write_handle_as_size_t) + + " to a file descriptor"); + } + + // Signals the parent that the write end of the pipe has been acquired + // so the parent can release its own write end. + ::SetEvent(dup_event_handle); + + return write_fd; +} +# endif // GTEST_OS_WINDOWS + +// Returns a newly created InternalRunDeathTestFlag object with fields +// initialized from the GTEST_FLAG(internal_run_death_test) flag if +// the flag is specified; otherwise returns NULL. +InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { + if (GTEST_FLAG(internal_run_death_test) == "") return NULL; + + // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we + // can use it here. + int line = -1; + int index = -1; + ::std::vector< ::std::string> fields; + SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); + int write_fd = -1; + +# if GTEST_OS_WINDOWS + + unsigned int parent_process_id = 0; + size_t write_handle_as_size_t = 0; + size_t event_handle_as_size_t = 0; + + if (fields.size() != 6 + || !ParseNaturalNumber(fields[1], &line) + || !ParseNaturalNumber(fields[2], &index) + || !ParseNaturalNumber(fields[3], &parent_process_id) + || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) + || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + + GTEST_FLAG(internal_run_death_test)); + } + write_fd = GetStatusFileDescriptor(parent_process_id, + write_handle_as_size_t, + event_handle_as_size_t); +# else + + if (fields.size() != 4 + || !ParseNaturalNumber(fields[1], &line) + || !ParseNaturalNumber(fields[2], &index) + || !ParseNaturalNumber(fields[3], &write_fd)) { + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + + GTEST_FLAG(internal_run_death_test)); + } + +# endif // GTEST_OS_WINDOWS + + return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); +} + +} // namespace internal + +#endif // GTEST_HAS_DEATH_TEST + +} // namespace testing diff --git a/lib/gtest/src/gtest-filepath.cc b/lib/gtest/src/gtest-filepath.cc new file mode 100644 index 00000000..6be58b6f --- /dev/null +++ b/lib/gtest/src/gtest-filepath.cc @@ -0,0 +1,382 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: keith.ray@gmail.com (Keith Ray) + +#include "gtest/gtest-message.h" +#include "gtest/internal/gtest-filepath.h" +#include "gtest/internal/gtest-port.h" + +#include + +#if GTEST_OS_WINDOWS_MOBILE +# include +#elif GTEST_OS_WINDOWS +# include +# include +#elif GTEST_OS_SYMBIAN +// Symbian OpenC has PATH_MAX in sys/syslimits.h +# include +#else +# include +# include // Some Linux distributions define PATH_MAX here. +#endif // GTEST_OS_WINDOWS_MOBILE + +#if GTEST_OS_WINDOWS +# define GTEST_PATH_MAX_ _MAX_PATH +#elif defined(PATH_MAX) +# define GTEST_PATH_MAX_ PATH_MAX +#elif defined(_XOPEN_PATH_MAX) +# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX +#else +# define GTEST_PATH_MAX_ _POSIX_PATH_MAX +#endif // GTEST_OS_WINDOWS + +#include "gtest/internal/gtest-string.h" + +namespace testing { +namespace internal { + +#if GTEST_OS_WINDOWS +// On Windows, '\\' is the standard path separator, but many tools and the +// Windows API also accept '/' as an alternate path separator. Unless otherwise +// noted, a file path can contain either kind of path separators, or a mixture +// of them. +const char kPathSeparator = '\\'; +const char kAlternatePathSeparator = '/'; +const char kPathSeparatorString[] = "\\"; +const char kAlternatePathSeparatorString[] = "/"; +# if GTEST_OS_WINDOWS_MOBILE +// Windows CE doesn't have a current directory. You should not use +// the current directory in tests on Windows CE, but this at least +// provides a reasonable fallback. +const char kCurrentDirectoryString[] = "\\"; +// Windows CE doesn't define INVALID_FILE_ATTRIBUTES +const DWORD kInvalidFileAttributes = 0xffffffff; +# else +const char kCurrentDirectoryString[] = ".\\"; +# endif // GTEST_OS_WINDOWS_MOBILE +#else +const char kPathSeparator = '/'; +const char kPathSeparatorString[] = "/"; +const char kCurrentDirectoryString[] = "./"; +#endif // GTEST_OS_WINDOWS + +// Returns whether the given character is a valid path separator. +static bool IsPathSeparator(char c) { +#if GTEST_HAS_ALT_PATH_SEP_ + return (c == kPathSeparator) || (c == kAlternatePathSeparator); +#else + return c == kPathSeparator; +#endif +} + +// Returns the current working directory, or "" if unsuccessful. +FilePath FilePath::GetCurrentDir() { +#if GTEST_OS_WINDOWS_MOBILE + // Windows CE doesn't have a current directory, so we just return + // something reasonable. + return FilePath(kCurrentDirectoryString); +#elif GTEST_OS_WINDOWS + char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; + return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); +#else + char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; + return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); +#endif // GTEST_OS_WINDOWS_MOBILE +} + +// Returns a copy of the FilePath with the case-insensitive extension removed. +// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns +// FilePath("dir/file"). If a case-insensitive extension is not +// found, returns a copy of the original FilePath. +FilePath FilePath::RemoveExtension(const char* extension) const { + const std::string dot_extension = std::string(".") + extension; + if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { + return FilePath(pathname_.substr( + 0, pathname_.length() - dot_extension.length())); + } + return *this; +} + +// Returns a pointer to the last occurence of a valid path separator in +// the FilePath. On Windows, for example, both '/' and '\' are valid path +// separators. Returns NULL if no path separator was found. +const char* FilePath::FindLastPathSeparator() const { + const char* const last_sep = strrchr(c_str(), kPathSeparator); +#if GTEST_HAS_ALT_PATH_SEP_ + const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); + // Comparing two pointers of which only one is NULL is undefined. + if (last_alt_sep != NULL && + (last_sep == NULL || last_alt_sep > last_sep)) { + return last_alt_sep; + } +#endif + return last_sep; +} + +// Returns a copy of the FilePath with the directory part removed. +// Example: FilePath("path/to/file").RemoveDirectoryName() returns +// FilePath("file"). If there is no directory part ("just_a_file"), it returns +// the FilePath unmodified. If there is no file part ("just_a_dir/") it +// returns an empty FilePath (""). +// On Windows platform, '\' is the path separator, otherwise it is '/'. +FilePath FilePath::RemoveDirectoryName() const { + const char* const last_sep = FindLastPathSeparator(); + return last_sep ? FilePath(last_sep + 1) : *this; +} + +// RemoveFileName returns the directory path with the filename removed. +// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". +// If the FilePath is "a_file" or "/a_file", RemoveFileName returns +// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does +// not have a file, like "just/a/dir/", it returns the FilePath unmodified. +// On Windows platform, '\' is the path separator, otherwise it is '/'. +FilePath FilePath::RemoveFileName() const { + const char* const last_sep = FindLastPathSeparator(); + std::string dir; + if (last_sep) { + dir = std::string(c_str(), last_sep + 1 - c_str()); + } else { + dir = kCurrentDirectoryString; + } + return FilePath(dir); +} + +// Helper functions for naming files in a directory for xml output. + +// Given directory = "dir", base_name = "test", number = 0, +// extension = "xml", returns "dir/test.xml". If number is greater +// than zero (e.g., 12), returns "dir/test_12.xml". +// On Windows platform, uses \ as the separator rather than /. +FilePath FilePath::MakeFileName(const FilePath& directory, + const FilePath& base_name, + int number, + const char* extension) { + std::string file; + if (number == 0) { + file = base_name.string() + "." + extension; + } else { + file = base_name.string() + "_" + StreamableToString(number) + + "." + extension; + } + return ConcatPaths(directory, FilePath(file)); +} + +// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml". +// On Windows, uses \ as the separator rather than /. +FilePath FilePath::ConcatPaths(const FilePath& directory, + const FilePath& relative_path) { + if (directory.IsEmpty()) + return relative_path; + const FilePath dir(directory.RemoveTrailingPathSeparator()); + return FilePath(dir.string() + kPathSeparator + relative_path.string()); +} + +// Returns true if pathname describes something findable in the file-system, +// either a file, directory, or whatever. +bool FilePath::FileOrDirectoryExists() const { +#if GTEST_OS_WINDOWS_MOBILE + LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); + const DWORD attributes = GetFileAttributes(unicode); + delete [] unicode; + return attributes != kInvalidFileAttributes; +#else + posix::StatStruct file_stat; + return posix::Stat(pathname_.c_str(), &file_stat) == 0; +#endif // GTEST_OS_WINDOWS_MOBILE +} + +// Returns true if pathname describes a directory in the file-system +// that exists. +bool FilePath::DirectoryExists() const { + bool result = false; +#if GTEST_OS_WINDOWS + // Don't strip off trailing separator if path is a root directory on + // Windows (like "C:\\"). + const FilePath& path(IsRootDirectory() ? *this : + RemoveTrailingPathSeparator()); +#else + const FilePath& path(*this); +#endif + +#if GTEST_OS_WINDOWS_MOBILE + LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); + const DWORD attributes = GetFileAttributes(unicode); + delete [] unicode; + if ((attributes != kInvalidFileAttributes) && + (attributes & FILE_ATTRIBUTE_DIRECTORY)) { + result = true; + } +#else + posix::StatStruct file_stat; + result = posix::Stat(path.c_str(), &file_stat) == 0 && + posix::IsDir(file_stat); +#endif // GTEST_OS_WINDOWS_MOBILE + + return result; +} + +// Returns true if pathname describes a root directory. (Windows has one +// root directory per disk drive.) +bool FilePath::IsRootDirectory() const { +#if GTEST_OS_WINDOWS + // TODO(wan@google.com): on Windows a network share like + // \\server\share can be a root directory, although it cannot be the + // current directory. Handle this properly. + return pathname_.length() == 3 && IsAbsolutePath(); +#else + return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]); +#endif +} + +// Returns true if pathname describes an absolute path. +bool FilePath::IsAbsolutePath() const { + const char* const name = pathname_.c_str(); +#if GTEST_OS_WINDOWS + return pathname_.length() >= 3 && + ((name[0] >= 'a' && name[0] <= 'z') || + (name[0] >= 'A' && name[0] <= 'Z')) && + name[1] == ':' && + IsPathSeparator(name[2]); +#else + return IsPathSeparator(name[0]); +#endif +} + +// Returns a pathname for a file that does not currently exist. The pathname +// will be directory/base_name.extension or +// directory/base_name_.extension if directory/base_name.extension +// already exists. The number will be incremented until a pathname is found +// that does not already exist. +// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. +// There could be a race condition if two or more processes are calling this +// function at the same time -- they could both pick the same filename. +FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, + const FilePath& base_name, + const char* extension) { + FilePath full_pathname; + int number = 0; + do { + full_pathname.Set(MakeFileName(directory, base_name, number++, extension)); + } while (full_pathname.FileOrDirectoryExists()); + return full_pathname; +} + +// Returns true if FilePath ends with a path separator, which indicates that +// it is intended to represent a directory. Returns false otherwise. +// This does NOT check that a directory (or file) actually exists. +bool FilePath::IsDirectory() const { + return !pathname_.empty() && + IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); +} + +// Create directories so that path exists. Returns true if successful or if +// the directories already exist; returns false if unable to create directories +// for any reason. +bool FilePath::CreateDirectoriesRecursively() const { + if (!this->IsDirectory()) { + return false; + } + + if (pathname_.length() == 0 || this->DirectoryExists()) { + return true; + } + + const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName()); + return parent.CreateDirectoriesRecursively() && this->CreateFolder(); +} + +// Create the directory so that path exists. Returns true if successful or +// if the directory already exists; returns false if unable to create the +// directory for any reason, including if the parent directory does not +// exist. Not named "CreateDirectory" because that's a macro on Windows. +bool FilePath::CreateFolder() const { +#if GTEST_OS_WINDOWS_MOBILE + FilePath removed_sep(this->RemoveTrailingPathSeparator()); + LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); + int result = CreateDirectory(unicode, NULL) ? 0 : -1; + delete [] unicode; +#elif GTEST_OS_WINDOWS + int result = _mkdir(pathname_.c_str()); +#else + int result = mkdir(pathname_.c_str(), 0777); +#endif // GTEST_OS_WINDOWS_MOBILE + + if (result == -1) { + return this->DirectoryExists(); // An error is OK if the directory exists. + } + return true; // No error. +} + +// If input name has a trailing separator character, remove it and return the +// name, otherwise return the name string unmodified. +// On Windows platform, uses \ as the separator, other platforms use /. +FilePath FilePath::RemoveTrailingPathSeparator() const { + return IsDirectory() + ? FilePath(pathname_.substr(0, pathname_.length() - 1)) + : *this; +} + +// Removes any redundant separators that might be in the pathname. +// For example, "bar///foo" becomes "bar/foo". Does not eliminate other +// redundancies that might be in a pathname involving "." or "..". +// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share). +void FilePath::Normalize() { + if (pathname_.c_str() == NULL) { + pathname_ = ""; + return; + } + const char* src = pathname_.c_str(); + char* const dest = new char[pathname_.length() + 1]; + char* dest_ptr = dest; + memset(dest_ptr, 0, pathname_.length() + 1); + + while (*src != '\0') { + *dest_ptr = *src; + if (!IsPathSeparator(*src)) { + src++; + } else { +#if GTEST_HAS_ALT_PATH_SEP_ + if (*dest_ptr == kAlternatePathSeparator) { + *dest_ptr = kPathSeparator; + } +#endif + while (IsPathSeparator(*src)) + src++; + } + dest_ptr++; + } + *dest_ptr = '\0'; + pathname_ = dest; + delete[] dest; +} + +} // namespace internal +} // namespace testing diff --git a/lib/gtest/src/gtest-internal-inl.h b/lib/gtest/src/gtest-internal-inl.h new file mode 100644 index 00000000..35df303c --- /dev/null +++ b/lib/gtest/src/gtest-internal-inl.h @@ -0,0 +1,1218 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Utility functions and classes used by the Google C++ testing framework. +// +// Author: wan@google.com (Zhanyong Wan) +// +// This file contains purely Google Test's internal implementation. Please +// DO NOT #INCLUDE IT IN A USER PROGRAM. + +#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ +#define GTEST_SRC_GTEST_INTERNAL_INL_H_ + +// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is +// part of Google Test's implementation; otherwise it's undefined. +#if !GTEST_IMPLEMENTATION_ +// A user is trying to include this from his code - just say no. +# error "gtest-internal-inl.h is part of Google Test's internal implementation." +# error "It must not be included except by Google Test itself." +#endif // GTEST_IMPLEMENTATION_ + +#ifndef _WIN32_WCE +# include +#endif // !_WIN32_WCE +#include +#include // For strtoll/_strtoul64/malloc/free. +#include // For memmove. + +#include +#include +#include + +#include "gtest/internal/gtest-port.h" + +#if GTEST_CAN_STREAM_RESULTS_ +# include // NOLINT +# include // NOLINT +#endif + +#if GTEST_OS_WINDOWS +# include // NOLINT +#endif // GTEST_OS_WINDOWS + +#include "gtest/gtest.h" // NOLINT +#include "gtest/gtest-spi.h" + +namespace testing { + +// Declares the flags. +// +// We don't want the users to modify this flag in the code, but want +// Google Test's own unit tests to be able to access it. Therefore we +// declare it here as opposed to in gtest.h. +GTEST_DECLARE_bool_(death_test_use_fork); + +namespace internal { + +// The value of GetTestTypeId() as seen from within the Google Test +// library. This is solely for testing GetTestTypeId(). +GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; + +// Names of the flags (needed for parsing Google Test flags). +const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; +const char kBreakOnFailureFlag[] = "break_on_failure"; +const char kCatchExceptionsFlag[] = "catch_exceptions"; +const char kColorFlag[] = "color"; +const char kFilterFlag[] = "filter"; +const char kListTestsFlag[] = "list_tests"; +const char kOutputFlag[] = "output"; +const char kPrintTimeFlag[] = "print_time"; +const char kRandomSeedFlag[] = "random_seed"; +const char kRepeatFlag[] = "repeat"; +const char kShuffleFlag[] = "shuffle"; +const char kStackTraceDepthFlag[] = "stack_trace_depth"; +const char kStreamResultToFlag[] = "stream_result_to"; +const char kThrowOnFailureFlag[] = "throw_on_failure"; + +// A valid random seed must be in [1, kMaxRandomSeed]. +const int kMaxRandomSeed = 99999; + +// g_help_flag is true iff the --help flag or an equivalent form is +// specified on the command line. +GTEST_API_ extern bool g_help_flag; + +// Returns the current time in milliseconds. +GTEST_API_ TimeInMillis GetTimeInMillis(); + +// Returns true iff Google Test should use colors in the output. +GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); + +// Formats the given time in milliseconds as seconds. +GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); + +// Converts the given time in milliseconds to a date string in the ISO 8601 +// format, without the timezone information. N.B.: due to the use the +// non-reentrant localtime() function, this function is not thread safe. Do +// not use it in any code that can be called from multiple threads. +GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms); + +// Parses a string for an Int32 flag, in the form of "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +GTEST_API_ bool ParseInt32Flag( + const char* str, const char* flag, Int32* value); + +// Returns a random seed in range [1, kMaxRandomSeed] based on the +// given --gtest_random_seed flag value. +inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { + const unsigned int raw_seed = (random_seed_flag == 0) ? + static_cast(GetTimeInMillis()) : + static_cast(random_seed_flag); + + // Normalizes the actual seed to range [1, kMaxRandomSeed] such that + // it's easy to type. + const int normalized_seed = + static_cast((raw_seed - 1U) % + static_cast(kMaxRandomSeed)) + 1; + return normalized_seed; +} + +// Returns the first valid random seed after 'seed'. The behavior is +// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is +// considered to be 1. +inline int GetNextRandomSeed(int seed) { + GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) + << "Invalid random seed " << seed << " - must be in [1, " + << kMaxRandomSeed << "]."; + const int next_seed = seed + 1; + return (next_seed > kMaxRandomSeed) ? 1 : next_seed; +} + +// This class saves the values of all Google Test flags in its c'tor, and +// restores them in its d'tor. +class GTestFlagSaver { + public: + // The c'tor. + GTestFlagSaver() { + also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); + break_on_failure_ = GTEST_FLAG(break_on_failure); + catch_exceptions_ = GTEST_FLAG(catch_exceptions); + color_ = GTEST_FLAG(color); + death_test_style_ = GTEST_FLAG(death_test_style); + death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); + filter_ = GTEST_FLAG(filter); + internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); + list_tests_ = GTEST_FLAG(list_tests); + output_ = GTEST_FLAG(output); + print_time_ = GTEST_FLAG(print_time); + random_seed_ = GTEST_FLAG(random_seed); + repeat_ = GTEST_FLAG(repeat); + shuffle_ = GTEST_FLAG(shuffle); + stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); + stream_result_to_ = GTEST_FLAG(stream_result_to); + throw_on_failure_ = GTEST_FLAG(throw_on_failure); + } + + // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. + ~GTestFlagSaver() { + GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; + GTEST_FLAG(break_on_failure) = break_on_failure_; + GTEST_FLAG(catch_exceptions) = catch_exceptions_; + GTEST_FLAG(color) = color_; + GTEST_FLAG(death_test_style) = death_test_style_; + GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; + GTEST_FLAG(filter) = filter_; + GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; + GTEST_FLAG(list_tests) = list_tests_; + GTEST_FLAG(output) = output_; + GTEST_FLAG(print_time) = print_time_; + GTEST_FLAG(random_seed) = random_seed_; + GTEST_FLAG(repeat) = repeat_; + GTEST_FLAG(shuffle) = shuffle_; + GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; + GTEST_FLAG(stream_result_to) = stream_result_to_; + GTEST_FLAG(throw_on_failure) = throw_on_failure_; + } + + private: + // Fields for saving the original values of flags. + bool also_run_disabled_tests_; + bool break_on_failure_; + bool catch_exceptions_; + std::string color_; + std::string death_test_style_; + bool death_test_use_fork_; + std::string filter_; + std::string internal_run_death_test_; + bool list_tests_; + std::string output_; + bool print_time_; + internal::Int32 random_seed_; + internal::Int32 repeat_; + bool shuffle_; + internal::Int32 stack_trace_depth_; + std::string stream_result_to_; + bool throw_on_failure_; +} GTEST_ATTRIBUTE_UNUSED_; + +// Converts a Unicode code point to a narrow string in UTF-8 encoding. +// code_point parameter is of type UInt32 because wchar_t may not be +// wide enough to contain a code point. +// If the code_point is not a valid Unicode code point +// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted +// to "(Invalid Unicode 0xXXXXXXXX)". +GTEST_API_ std::string CodePointToUtf8(UInt32 code_point); + +// Converts a wide string to a narrow string in UTF-8 encoding. +// The wide string is assumed to have the following encoding: +// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) +// UTF-32 if sizeof(wchar_t) == 4 (on Linux) +// Parameter str points to a null-terminated wide string. +// Parameter num_chars may additionally limit the number +// of wchar_t characters processed. -1 is used when the entire string +// should be processed. +// If the string contains code points that are not valid Unicode code points +// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output +// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding +// and contains invalid UTF-16 surrogate pairs, values in those pairs +// will be encoded as individual Unicode characters from Basic Normal Plane. +GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars); + +// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file +// if the variable is present. If a file already exists at this location, this +// function will write over it. If the variable is present, but the file cannot +// be created, prints an error and exits. +void WriteToShardStatusFileIfNeeded(); + +// Checks whether sharding is enabled by examining the relevant +// environment variable values. If the variables are present, +// but inconsistent (e.g., shard_index >= total_shards), prints +// an error and exits. If in_subprocess_for_death_test, sharding is +// disabled because it must only be applied to the original test +// process. Otherwise, we could filter out death tests we intended to execute. +GTEST_API_ bool ShouldShard(const char* total_shards_str, + const char* shard_index_str, + bool in_subprocess_for_death_test); + +// Parses the environment variable var as an Int32. If it is unset, +// returns default_val. If it is not an Int32, prints an error and +// and aborts. +GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); + +// Given the total number of shards, the shard index, and the test id, +// returns true iff the test should be run on this shard. The test id is +// some arbitrary but unique non-negative integer assigned to each test +// method. Assumes that 0 <= shard_index < total_shards. +GTEST_API_ bool ShouldRunTestOnShard( + int total_shards, int shard_index, int test_id); + +// STL container utilities. + +// Returns the number of elements in the given container that satisfy +// the given predicate. +template +inline int CountIf(const Container& c, Predicate predicate) { + // Implemented as an explicit loop since std::count_if() in libCstd on + // Solaris has a non-standard signature. + int count = 0; + for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) { + if (predicate(*it)) + ++count; + } + return count; +} + +// Applies a function/functor to each element in the container. +template +void ForEach(const Container& c, Functor functor) { + std::for_each(c.begin(), c.end(), functor); +} + +// Returns the i-th element of the vector, or default_value if i is not +// in range [0, v.size()). +template +inline E GetElementOr(const std::vector& v, int i, E default_value) { + return (i < 0 || i >= static_cast(v.size())) ? default_value : v[i]; +} + +// Performs an in-place shuffle of a range of the vector's elements. +// 'begin' and 'end' are element indices as an STL-style range; +// i.e. [begin, end) are shuffled, where 'end' == size() means to +// shuffle to the end of the vector. +template +void ShuffleRange(internal::Random* random, int begin, int end, + std::vector* v) { + const int size = static_cast(v->size()); + GTEST_CHECK_(0 <= begin && begin <= size) + << "Invalid shuffle range start " << begin << ": must be in range [0, " + << size << "]."; + GTEST_CHECK_(begin <= end && end <= size) + << "Invalid shuffle range finish " << end << ": must be in range [" + << begin << ", " << size << "]."; + + // Fisher-Yates shuffle, from + // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle + for (int range_width = end - begin; range_width >= 2; range_width--) { + const int last_in_range = begin + range_width - 1; + const int selected = begin + random->Generate(range_width); + std::swap((*v)[selected], (*v)[last_in_range]); + } +} + +// Performs an in-place shuffle of the vector's elements. +template +inline void Shuffle(internal::Random* random, std::vector* v) { + ShuffleRange(random, 0, static_cast(v->size()), v); +} + +// A function for deleting an object. Handy for being used as a +// functor. +template +static void Delete(T* x) { + delete x; +} + +// A predicate that checks the key of a TestProperty against a known key. +// +// TestPropertyKeyIs is copyable. +class TestPropertyKeyIs { + public: + // Constructor. + // + // TestPropertyKeyIs has NO default constructor. + explicit TestPropertyKeyIs(const std::string& key) : key_(key) {} + + // Returns true iff the test name of test property matches on key_. + bool operator()(const TestProperty& test_property) const { + return test_property.key() == key_; + } + + private: + std::string key_; +}; + +// Class UnitTestOptions. +// +// This class contains functions for processing options the user +// specifies when running the tests. It has only static members. +// +// In most cases, the user can specify an option using either an +// environment variable or a command line flag. E.g. you can set the +// test filter using either GTEST_FILTER or --gtest_filter. If both +// the variable and the flag are present, the latter overrides the +// former. +class GTEST_API_ UnitTestOptions { + public: + // Functions for processing the gtest_output flag. + + // Returns the output format, or "" for normal printed output. + static std::string GetOutputFormat(); + + // Returns the absolute path of the requested output file, or the + // default (test_detail.xml in the original working directory) if + // none was explicitly specified. + static std::string GetAbsolutePathToOutputFile(); + + // Functions for processing the gtest_filter flag. + + // Returns true iff the wildcard pattern matches the string. The + // first ':' or '\0' character in pattern marks the end of it. + // + // This recursive algorithm isn't very efficient, but is clear and + // works well enough for matching test names, which are short. + static bool PatternMatchesString(const char *pattern, const char *str); + + // Returns true iff the user-specified filter matches the test case + // name and the test name. + static bool FilterMatchesTest(const std::string &test_case_name, + const std::string &test_name); + +#if GTEST_OS_WINDOWS + // Function for supporting the gtest_catch_exception flag. + + // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the + // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. + // This function is useful as an __except condition. + static int GTestShouldProcessSEH(DWORD exception_code); +#endif // GTEST_OS_WINDOWS + + // Returns true if "name" matches the ':' separated list of glob-style + // filters in "filter". + static bool MatchesFilter(const std::string& name, const char* filter); +}; + +// Returns the current application's name, removing directory path if that +// is present. Used by UnitTestOptions::GetOutputFile. +GTEST_API_ FilePath GetCurrentExecutableName(); + +// The role interface for getting the OS stack trace as a string. +class OsStackTraceGetterInterface { + public: + OsStackTraceGetterInterface() {} + virtual ~OsStackTraceGetterInterface() {} + + // Returns the current OS stack trace as an std::string. Parameters: + // + // max_depth - the maximum number of stack frames to be included + // in the trace. + // skip_count - the number of top frames to be skipped; doesn't count + // against max_depth. + virtual string CurrentStackTrace(int max_depth, int skip_count) = 0; + + // UponLeavingGTest() should be called immediately before Google Test calls + // user code. It saves some information about the current stack that + // CurrentStackTrace() will use to find and hide Google Test stack frames. + virtual void UponLeavingGTest() = 0; + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); +}; + +// A working implementation of the OsStackTraceGetterInterface interface. +class OsStackTraceGetter : public OsStackTraceGetterInterface { + public: + OsStackTraceGetter() : caller_frame_(NULL) {} + + virtual string CurrentStackTrace(int max_depth, int skip_count) + GTEST_LOCK_EXCLUDED_(mutex_); + + virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_); + + // This string is inserted in place of stack frames that are part of + // Google Test's implementation. + static const char* const kElidedFramesMarker; + + private: + Mutex mutex_; // protects all internal state + + // We save the stack frame below the frame that calls user code. + // We do this because the address of the frame immediately below + // the user code changes between the call to UponLeavingGTest() + // and any calls to CurrentStackTrace() from within the user code. + void* caller_frame_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); +}; + +// Information about a Google Test trace point. +struct TraceInfo { + const char* file; + int line; + std::string message; +}; + +// This is the default global test part result reporter used in UnitTestImpl. +// This class should only be used by UnitTestImpl. +class DefaultGlobalTestPartResultReporter + : public TestPartResultReporterInterface { + public: + explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); + // Implements the TestPartResultReporterInterface. Reports the test part + // result in the current test. + virtual void ReportTestPartResult(const TestPartResult& result); + + private: + UnitTestImpl* const unit_test_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); +}; + +// This is the default per thread test part result reporter used in +// UnitTestImpl. This class should only be used by UnitTestImpl. +class DefaultPerThreadTestPartResultReporter + : public TestPartResultReporterInterface { + public: + explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); + // Implements the TestPartResultReporterInterface. The implementation just + // delegates to the current global test part result reporter of *unit_test_. + virtual void ReportTestPartResult(const TestPartResult& result); + + private: + UnitTestImpl* const unit_test_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); +}; + +// The private implementation of the UnitTest class. We don't protect +// the methods under a mutex, as this class is not accessible by a +// user and the UnitTest class that delegates work to this class does +// proper locking. +class GTEST_API_ UnitTestImpl { + public: + explicit UnitTestImpl(UnitTest* parent); + virtual ~UnitTestImpl(); + + // There are two different ways to register your own TestPartResultReporter. + // You can register your own repoter to listen either only for test results + // from the current thread or for results from all threads. + // By default, each per-thread test result repoter just passes a new + // TestPartResult to the global test result reporter, which registers the + // test part result for the currently running test. + + // Returns the global test part result reporter. + TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); + + // Sets the global test part result reporter. + void SetGlobalTestPartResultReporter( + TestPartResultReporterInterface* reporter); + + // Returns the test part result reporter for the current thread. + TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); + + // Sets the test part result reporter for the current thread. + void SetTestPartResultReporterForCurrentThread( + TestPartResultReporterInterface* reporter); + + // Gets the number of successful test cases. + int successful_test_case_count() const; + + // Gets the number of failed test cases. + int failed_test_case_count() const; + + // Gets the number of all test cases. + int total_test_case_count() const; + + // Gets the number of all test cases that contain at least one test + // that should run. + int test_case_to_run_count() const; + + // Gets the number of successful tests. + int successful_test_count() const; + + // Gets the number of failed tests. + int failed_test_count() const; + + // Gets the number of disabled tests that will be reported in the XML report. + int reportable_disabled_test_count() const; + + // Gets the number of disabled tests. + int disabled_test_count() const; + + // Gets the number of tests to be printed in the XML report. + int reportable_test_count() const; + + // Gets the number of all tests. + int total_test_count() const; + + // Gets the number of tests that should run. + int test_to_run_count() const; + + // Gets the time of the test program start, in ms from the start of the + // UNIX epoch. + TimeInMillis start_timestamp() const { return start_timestamp_; } + + // Gets the elapsed time, in milliseconds. + TimeInMillis elapsed_time() const { return elapsed_time_; } + + // Returns true iff the unit test passed (i.e. all test cases passed). + bool Passed() const { return !Failed(); } + + // Returns true iff the unit test failed (i.e. some test case failed + // or something outside of all tests failed). + bool Failed() const { + return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); + } + + // Gets the i-th test case among all the test cases. i can range from 0 to + // total_test_case_count() - 1. If i is not in that range, returns NULL. + const TestCase* GetTestCase(int i) const { + const int index = GetElementOr(test_case_indices_, i, -1); + return index < 0 ? NULL : test_cases_[i]; + } + + // Gets the i-th test case among all the test cases. i can range from 0 to + // total_test_case_count() - 1. If i is not in that range, returns NULL. + TestCase* GetMutableTestCase(int i) { + const int index = GetElementOr(test_case_indices_, i, -1); + return index < 0 ? NULL : test_cases_[index]; + } + + // Provides access to the event listener list. + TestEventListeners* listeners() { return &listeners_; } + + // Returns the TestResult for the test that's currently running, or + // the TestResult for the ad hoc test if no test is running. + TestResult* current_test_result(); + + // Returns the TestResult for the ad hoc test. + const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; } + + // Sets the OS stack trace getter. + // + // Does nothing if the input and the current OS stack trace getter + // are the same; otherwise, deletes the old getter and makes the + // input the current getter. + void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); + + // Returns the current OS stack trace getter if it is not NULL; + // otherwise, creates an OsStackTraceGetter, makes it the current + // getter, and returns it. + OsStackTraceGetterInterface* os_stack_trace_getter(); + + // Returns the current OS stack trace as an std::string. + // + // The maximum number of stack frames to be included is specified by + // the gtest_stack_trace_depth flag. The skip_count parameter + // specifies the number of top frames to be skipped, which doesn't + // count against the number of frames to be included. + // + // For example, if Foo() calls Bar(), which in turn calls + // CurrentOsStackTraceExceptTop(1), Foo() will be included in the + // trace but Bar() and CurrentOsStackTraceExceptTop() won't. + std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_; + + // Finds and returns a TestCase with the given name. If one doesn't + // exist, creates one and returns it. + // + // Arguments: + // + // test_case_name: name of the test case + // type_param: the name of the test's type parameter, or NULL if + // this is not a typed or a type-parameterized test. + // set_up_tc: pointer to the function that sets up the test case + // tear_down_tc: pointer to the function that tears down the test case + TestCase* GetTestCase(const char* test_case_name, + const char* type_param, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc); + + // Adds a TestInfo to the unit test. + // + // Arguments: + // + // set_up_tc: pointer to the function that sets up the test case + // tear_down_tc: pointer to the function that tears down the test case + // test_info: the TestInfo object + void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc, + TestInfo* test_info) { + // In order to support thread-safe death tests, we need to + // remember the original working directory when the test program + // was first invoked. We cannot do this in RUN_ALL_TESTS(), as + // the user may have changed the current directory before calling + // RUN_ALL_TESTS(). Therefore we capture the current directory in + // AddTestInfo(), which is called to register a TEST or TEST_F + // before main() is reached. + if (original_working_dir_.IsEmpty()) { + original_working_dir_.Set(FilePath::GetCurrentDir()); + GTEST_CHECK_(!original_working_dir_.IsEmpty()) + << "Failed to get the current working directory."; + } + + GetTestCase(test_info->test_case_name(), + test_info->type_param(), + set_up_tc, + tear_down_tc)->AddTestInfo(test_info); + } + +#if GTEST_HAS_PARAM_TEST + // Returns ParameterizedTestCaseRegistry object used to keep track of + // value-parameterized tests and instantiate and register them. + internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { + return parameterized_test_registry_; + } +#endif // GTEST_HAS_PARAM_TEST + + // Sets the TestCase object for the test that's currently running. + void set_current_test_case(TestCase* a_current_test_case) { + current_test_case_ = a_current_test_case; + } + + // Sets the TestInfo object for the test that's currently running. If + // current_test_info is NULL, the assertion results will be stored in + // ad_hoc_test_result_. + void set_current_test_info(TestInfo* a_current_test_info) { + current_test_info_ = a_current_test_info; + } + + // Registers all parameterized tests defined using TEST_P and + // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter + // combination. This method can be called more then once; it has guards + // protecting from registering the tests more then once. If + // value-parameterized tests are disabled, RegisterParameterizedTests is + // present but does nothing. + void RegisterParameterizedTests(); + + // Runs all tests in this UnitTest object, prints the result, and + // returns true if all tests are successful. If any exception is + // thrown during a test, this test is considered to be failed, but + // the rest of the tests will still be run. + bool RunAllTests(); + + // Clears the results of all tests, except the ad hoc tests. + void ClearNonAdHocTestResult() { + ForEach(test_cases_, TestCase::ClearTestCaseResult); + } + + // Clears the results of ad-hoc test assertions. + void ClearAdHocTestResult() { + ad_hoc_test_result_.Clear(); + } + + // Adds a TestProperty to the current TestResult object when invoked in a + // context of a test or a test case, or to the global property set. If the + // result already contains a property with the same key, the value will be + // updated. + void RecordProperty(const TestProperty& test_property); + + enum ReactionToSharding { + HONOR_SHARDING_PROTOCOL, + IGNORE_SHARDING_PROTOCOL + }; + + // Matches the full name of each test against the user-specified + // filter to decide whether the test should run, then records the + // result in each TestCase and TestInfo object. + // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests + // based on sharding variables in the environment. + // Returns the number of tests that should run. + int FilterTests(ReactionToSharding shard_tests); + + // Prints the names of the tests matching the user-specified filter flag. + void ListTestsMatchingFilter(); + + const TestCase* current_test_case() const { return current_test_case_; } + TestInfo* current_test_info() { return current_test_info_; } + const TestInfo* current_test_info() const { return current_test_info_; } + + // Returns the vector of environments that need to be set-up/torn-down + // before/after the tests are run. + std::vector& environments() { return environments_; } + + // Getters for the per-thread Google Test trace stack. + std::vector& gtest_trace_stack() { + return *(gtest_trace_stack_.pointer()); + } + const std::vector& gtest_trace_stack() const { + return gtest_trace_stack_.get(); + } + +#if GTEST_HAS_DEATH_TEST + void InitDeathTestSubprocessControlInfo() { + internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); + } + // Returns a pointer to the parsed --gtest_internal_run_death_test + // flag, or NULL if that flag was not specified. + // This information is useful only in a death test child process. + // Must not be called before a call to InitGoogleTest. + const InternalRunDeathTestFlag* internal_run_death_test_flag() const { + return internal_run_death_test_flag_.get(); + } + + // Returns a pointer to the current death test factory. + internal::DeathTestFactory* death_test_factory() { + return death_test_factory_.get(); + } + + void SuppressTestEventsIfInSubprocess(); + + friend class ReplaceDeathTestFactory; +#endif // GTEST_HAS_DEATH_TEST + + // Initializes the event listener performing XML output as specified by + // UnitTestOptions. Must not be called before InitGoogleTest. + void ConfigureXmlOutput(); + +#if GTEST_CAN_STREAM_RESULTS_ + // Initializes the event listener for streaming test results to a socket. + // Must not be called before InitGoogleTest. + void ConfigureStreamingOutput(); +#endif + + // Performs initialization dependent upon flag values obtained in + // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to + // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest + // this function is also called from RunAllTests. Since this function can be + // called more than once, it has to be idempotent. + void PostFlagParsingInit(); + + // Gets the random seed used at the start of the current test iteration. + int random_seed() const { return random_seed_; } + + // Gets the random number generator. + internal::Random* random() { return &random_; } + + // Shuffles all test cases, and the tests within each test case, + // making sure that death tests are still run first. + void ShuffleTests(); + + // Restores the test cases and tests to their order before the first shuffle. + void UnshuffleTests(); + + // Returns the value of GTEST_FLAG(catch_exceptions) at the moment + // UnitTest::Run() starts. + bool catch_exceptions() const { return catch_exceptions_; } + + private: + friend class ::testing::UnitTest; + + // Used by UnitTest::Run() to capture the state of + // GTEST_FLAG(catch_exceptions) at the moment it starts. + void set_catch_exceptions(bool value) { catch_exceptions_ = value; } + + // The UnitTest object that owns this implementation object. + UnitTest* const parent_; + + // The working directory when the first TEST() or TEST_F() was + // executed. + internal::FilePath original_working_dir_; + + // The default test part result reporters. + DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; + DefaultPerThreadTestPartResultReporter + default_per_thread_test_part_result_reporter_; + + // Points to (but doesn't own) the global test part result reporter. + TestPartResultReporterInterface* global_test_part_result_repoter_; + + // Protects read and write access to global_test_part_result_reporter_. + internal::Mutex global_test_part_result_reporter_mutex_; + + // Points to (but doesn't own) the per-thread test part result reporter. + internal::ThreadLocal + per_thread_test_part_result_reporter_; + + // The vector of environments that need to be set-up/torn-down + // before/after the tests are run. + std::vector environments_; + + // The vector of TestCases in their original order. It owns the + // elements in the vector. + std::vector test_cases_; + + // Provides a level of indirection for the test case list to allow + // easy shuffling and restoring the test case order. The i-th + // element of this vector is the index of the i-th test case in the + // shuffled order. + std::vector test_case_indices_; + +#if GTEST_HAS_PARAM_TEST + // ParameterizedTestRegistry object used to register value-parameterized + // tests. + internal::ParameterizedTestCaseRegistry parameterized_test_registry_; + + // Indicates whether RegisterParameterizedTests() has been called already. + bool parameterized_tests_registered_; +#endif // GTEST_HAS_PARAM_TEST + + // Index of the last death test case registered. Initially -1. + int last_death_test_case_; + + // This points to the TestCase for the currently running test. It + // changes as Google Test goes through one test case after another. + // When no test is running, this is set to NULL and Google Test + // stores assertion results in ad_hoc_test_result_. Initially NULL. + TestCase* current_test_case_; + + // This points to the TestInfo for the currently running test. It + // changes as Google Test goes through one test after another. When + // no test is running, this is set to NULL and Google Test stores + // assertion results in ad_hoc_test_result_. Initially NULL. + TestInfo* current_test_info_; + + // Normally, a user only writes assertions inside a TEST or TEST_F, + // or inside a function called by a TEST or TEST_F. Since Google + // Test keeps track of which test is current running, it can + // associate such an assertion with the test it belongs to. + // + // If an assertion is encountered when no TEST or TEST_F is running, + // Google Test attributes the assertion result to an imaginary "ad hoc" + // test, and records the result in ad_hoc_test_result_. + TestResult ad_hoc_test_result_; + + // The list of event listeners that can be used to track events inside + // Google Test. + TestEventListeners listeners_; + + // The OS stack trace getter. Will be deleted when the UnitTest + // object is destructed. By default, an OsStackTraceGetter is used, + // but the user can set this field to use a custom getter if that is + // desired. + OsStackTraceGetterInterface* os_stack_trace_getter_; + + // True iff PostFlagParsingInit() has been called. + bool post_flag_parse_init_performed_; + + // The random number seed used at the beginning of the test run. + int random_seed_; + + // Our random number generator. + internal::Random random_; + + // The time of the test program start, in ms from the start of the + // UNIX epoch. + TimeInMillis start_timestamp_; + + // How long the test took to run, in milliseconds. + TimeInMillis elapsed_time_; + +#if GTEST_HAS_DEATH_TEST + // The decomposed components of the gtest_internal_run_death_test flag, + // parsed when RUN_ALL_TESTS is called. + internal::scoped_ptr internal_run_death_test_flag_; + internal::scoped_ptr death_test_factory_; +#endif // GTEST_HAS_DEATH_TEST + + // A per-thread stack of traces created by the SCOPED_TRACE() macro. + internal::ThreadLocal > gtest_trace_stack_; + + // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests() + // starts. + bool catch_exceptions_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); +}; // class UnitTestImpl + +// Convenience function for accessing the global UnitTest +// implementation object. +inline UnitTestImpl* GetUnitTestImpl() { + return UnitTest::GetInstance()->impl(); +} + +#if GTEST_USES_SIMPLE_RE + +// Internal helper functions for implementing the simple regular +// expression matcher. +GTEST_API_ bool IsInSet(char ch, const char* str); +GTEST_API_ bool IsAsciiDigit(char ch); +GTEST_API_ bool IsAsciiPunct(char ch); +GTEST_API_ bool IsRepeat(char ch); +GTEST_API_ bool IsAsciiWhiteSpace(char ch); +GTEST_API_ bool IsAsciiWordChar(char ch); +GTEST_API_ bool IsValidEscape(char ch); +GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); +GTEST_API_ bool ValidateRegex(const char* regex); +GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); +GTEST_API_ bool MatchRepetitionAndRegexAtHead( + bool escaped, char ch, char repeat, const char* regex, const char* str); +GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); + +#endif // GTEST_USES_SIMPLE_RE + +// Parses the command line for Google Test flags, without initializing +// other parts of Google Test. +GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); +GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); + +#if GTEST_HAS_DEATH_TEST + +// Returns the message describing the last system error, regardless of the +// platform. +GTEST_API_ std::string GetLastErrnoDescription(); + +# if GTEST_OS_WINDOWS +// Provides leak-safe Windows kernel handle ownership. +class AutoHandle { + public: + AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} + explicit AutoHandle(HANDLE handle) : handle_(handle) {} + + ~AutoHandle() { Reset(); } + + HANDLE Get() const { return handle_; } + void Reset() { Reset(INVALID_HANDLE_VALUE); } + void Reset(HANDLE handle) { + if (handle != handle_) { + if (handle_ != INVALID_HANDLE_VALUE) + ::CloseHandle(handle_); + handle_ = handle; + } + } + + private: + HANDLE handle_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); +}; +# endif // GTEST_OS_WINDOWS + +// Attempts to parse a string into a positive integer pointed to by the +// number parameter. Returns true if that is possible. +// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use +// it here. +template +bool ParseNaturalNumber(const ::std::string& str, Integer* number) { + // Fail fast if the given string does not begin with a digit; + // this bypasses strtoXXX's "optional leading whitespace and plus + // or minus sign" semantics, which are undesirable here. + if (str.empty() || !IsDigit(str[0])) { + return false; + } + errno = 0; + + char* end; + // BiggestConvertible is the largest integer type that system-provided + // string-to-number conversion routines can return. + +# if GTEST_OS_WINDOWS && !defined(__GNUC__) + + // MSVC and C++ Builder define __int64 instead of the standard long long. + typedef unsigned __int64 BiggestConvertible; + const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); + +# else + + typedef unsigned long long BiggestConvertible; // NOLINT + const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); + +# endif // GTEST_OS_WINDOWS && !defined(__GNUC__) + + const bool parse_success = *end == '\0' && errno == 0; + + // TODO(vladl@google.com): Convert this to compile time assertion when it is + // available. + GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); + + const Integer result = static_cast(parsed); + if (parse_success && static_cast(result) == parsed) { + *number = result; + return true; + } + return false; +} +#endif // GTEST_HAS_DEATH_TEST + +// TestResult contains some private methods that should be hidden from +// Google Test user but are required for testing. This class allow our tests +// to access them. +// +// This class is supplied only for the purpose of testing Google Test's own +// constructs. Do not use it in user tests, either directly or indirectly. +class TestResultAccessor { + public: + static void RecordProperty(TestResult* test_result, + const std::string& xml_element, + const TestProperty& property) { + test_result->RecordProperty(xml_element, property); + } + + static void ClearTestPartResults(TestResult* test_result) { + test_result->ClearTestPartResults(); + } + + static const std::vector& test_part_results( + const TestResult& test_result) { + return test_result.test_part_results(); + } +}; + +#if GTEST_CAN_STREAM_RESULTS_ + +// Streams test results to the given port on the given host machine. +class StreamingListener : public EmptyTestEventListener { + public: + // Abstract base class for writing strings to a socket. + class AbstractSocketWriter { + public: + virtual ~AbstractSocketWriter() {} + + // Sends a string to the socket. + virtual void Send(const string& message) = 0; + + // Closes the socket. + virtual void CloseConnection() {} + + // Sends a string and a newline to the socket. + void SendLn(const string& message) { + Send(message + "\n"); + } + }; + + // Concrete class for actually writing strings to a socket. + class SocketWriter : public AbstractSocketWriter { + public: + SocketWriter(const string& host, const string& port) + : sockfd_(-1), host_name_(host), port_num_(port) { + MakeConnection(); + } + + virtual ~SocketWriter() { + if (sockfd_ != -1) + CloseConnection(); + } + + // Sends a string to the socket. + virtual void Send(const string& message) { + GTEST_CHECK_(sockfd_ != -1) + << "Send() can be called only when there is a connection."; + + const int len = static_cast(message.length()); + if (write(sockfd_, message.c_str(), len) != len) { + GTEST_LOG_(WARNING) + << "stream_result_to: failed to stream to " + << host_name_ << ":" << port_num_; + } + } + + private: + // Creates a client socket and connects to the server. + void MakeConnection(); + + // Closes the socket. + void CloseConnection() { + GTEST_CHECK_(sockfd_ != -1) + << "CloseConnection() can be called only when there is a connection."; + + close(sockfd_); + sockfd_ = -1; + } + + int sockfd_; // socket file descriptor + const string host_name_; + const string port_num_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter); + }; // class SocketWriter + + // Escapes '=', '&', '%', and '\n' characters in str as "%xx". + static string UrlEncode(const char* str); + + StreamingListener(const string& host, const string& port) + : socket_writer_(new SocketWriter(host, port)) { Start(); } + + explicit StreamingListener(AbstractSocketWriter* socket_writer) + : socket_writer_(socket_writer) { Start(); } + + void OnTestProgramStart(const UnitTest& /* unit_test */) { + SendLn("event=TestProgramStart"); + } + + void OnTestProgramEnd(const UnitTest& unit_test) { + // Note that Google Test current only report elapsed time for each + // test iteration, not for the entire test program. + SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed())); + + // Notify the streaming server to stop. + socket_writer_->CloseConnection(); + } + + void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) { + SendLn("event=TestIterationStart&iteration=" + + StreamableToString(iteration)); + } + + void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) { + SendLn("event=TestIterationEnd&passed=" + + FormatBool(unit_test.Passed()) + "&elapsed_time=" + + StreamableToString(unit_test.elapsed_time()) + "ms"); + } + + void OnTestCaseStart(const TestCase& test_case) { + SendLn(std::string("event=TestCaseStart&name=") + test_case.name()); + } + + void OnTestCaseEnd(const TestCase& test_case) { + SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) + + "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) + + "ms"); + } + + void OnTestStart(const TestInfo& test_info) { + SendLn(std::string("event=TestStart&name=") + test_info.name()); + } + + void OnTestEnd(const TestInfo& test_info) { + SendLn("event=TestEnd&passed=" + + FormatBool((test_info.result())->Passed()) + + "&elapsed_time=" + + StreamableToString((test_info.result())->elapsed_time()) + "ms"); + } + + void OnTestPartResult(const TestPartResult& test_part_result) { + const char* file_name = test_part_result.file_name(); + if (file_name == NULL) + file_name = ""; + SendLn("event=TestPartResult&file=" + UrlEncode(file_name) + + "&line=" + StreamableToString(test_part_result.line_number()) + + "&message=" + UrlEncode(test_part_result.message())); + } + + private: + // Sends the given message and a newline to the socket. + void SendLn(const string& message) { socket_writer_->SendLn(message); } + + // Called at the start of streaming to notify the receiver what + // protocol we are using. + void Start() { SendLn("gtest_streaming_protocol_version=1.0"); } + + string FormatBool(bool value) { return value ? "1" : "0"; } + + const scoped_ptr socket_writer_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); +}; // class StreamingListener + +#endif // GTEST_CAN_STREAM_RESULTS_ + +} // namespace internal +} // namespace testing + +#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ diff --git a/lib/gtest/src/gtest-port.cc b/lib/gtest/src/gtest-port.cc new file mode 100644 index 00000000..0c4df5f2 --- /dev/null +++ b/lib/gtest/src/gtest-port.cc @@ -0,0 +1,805 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +#include "gtest/internal/gtest-port.h" + +#include +#include +#include +#include + +#if GTEST_OS_WINDOWS_MOBILE +# include // For TerminateProcess() +#elif GTEST_OS_WINDOWS +# include +# include +#else +# include +#endif // GTEST_OS_WINDOWS_MOBILE + +#if GTEST_OS_MAC +# include +# include +# include +#endif // GTEST_OS_MAC + +#if GTEST_OS_QNX +# include +# include +#endif // GTEST_OS_QNX + +#include "gtest/gtest-spi.h" +#include "gtest/gtest-message.h" +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-string.h" + +// Indicates that this translation unit is part of Google Test's +// implementation. It must come before gtest-internal-inl.h is +// included, or there will be a compiler error. This trick is to +// prevent a user from accidentally including gtest-internal-inl.h in +// his code. +#define GTEST_IMPLEMENTATION_ 1 +#include "src/gtest-internal-inl.h" +#undef GTEST_IMPLEMENTATION_ + +namespace testing { +namespace internal { + +#if defined(_MSC_VER) || defined(__BORLANDC__) +// MSVC and C++Builder do not provide a definition of STDERR_FILENO. +const int kStdOutFileno = 1; +const int kStdErrFileno = 2; +#else +const int kStdOutFileno = STDOUT_FILENO; +const int kStdErrFileno = STDERR_FILENO; +#endif // _MSC_VER + +#if GTEST_OS_MAC + +// Returns the number of threads running in the process, or 0 to indicate that +// we cannot detect it. +size_t GetThreadCount() { + const task_t task = mach_task_self(); + mach_msg_type_number_t thread_count; + thread_act_array_t thread_list; + const kern_return_t status = task_threads(task, &thread_list, &thread_count); + if (status == KERN_SUCCESS) { + // task_threads allocates resources in thread_list and we need to free them + // to avoid leaks. + vm_deallocate(task, + reinterpret_cast(thread_list), + sizeof(thread_t) * thread_count); + return static_cast(thread_count); + } else { + return 0; + } +} + +#elif GTEST_OS_QNX + +// Returns the number of threads running in the process, or 0 to indicate that +// we cannot detect it. +size_t GetThreadCount() { + const int fd = open("/proc/self/as", O_RDONLY); + if (fd < 0) { + return 0; + } + procfs_info process_info; + const int status = + devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL); + close(fd); + if (status == EOK) { + return static_cast(process_info.num_threads); + } else { + return 0; + } +} + +#else + +size_t GetThreadCount() { + // There's no portable way to detect the number of threads, so we just + // return 0 to indicate that we cannot detect it. + return 0; +} + +#endif // GTEST_OS_MAC + +#if GTEST_USES_POSIX_RE + +// Implements RE. Currently only needed for death tests. + +RE::~RE() { + if (is_valid_) { + // regfree'ing an invalid regex might crash because the content + // of the regex is undefined. Since the regex's are essentially + // the same, one cannot be valid (or invalid) without the other + // being so too. + regfree(&partial_regex_); + regfree(&full_regex_); + } + free(const_cast(pattern_)); +} + +// Returns true iff regular expression re matches the entire str. +bool RE::FullMatch(const char* str, const RE& re) { + if (!re.is_valid_) return false; + + regmatch_t match; + return regexec(&re.full_regex_, str, 1, &match, 0) == 0; +} + +// Returns true iff regular expression re matches a substring of str +// (including str itself). +bool RE::PartialMatch(const char* str, const RE& re) { + if (!re.is_valid_) return false; + + regmatch_t match; + return regexec(&re.partial_regex_, str, 1, &match, 0) == 0; +} + +// Initializes an RE from its string representation. +void RE::Init(const char* regex) { + pattern_ = posix::StrDup(regex); + + // Reserves enough bytes to hold the regular expression used for a + // full match. + const size_t full_regex_len = strlen(regex) + 10; + char* const full_pattern = new char[full_regex_len]; + + snprintf(full_pattern, full_regex_len, "^(%s)$", regex); + is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; + // We want to call regcomp(&partial_regex_, ...) even if the + // previous expression returns false. Otherwise partial_regex_ may + // not be properly initialized can may cause trouble when it's + // freed. + // + // Some implementation of POSIX regex (e.g. on at least some + // versions of Cygwin) doesn't accept the empty string as a valid + // regex. We change it to an equivalent form "()" to be safe. + if (is_valid_) { + const char* const partial_regex = (*regex == '\0') ? "()" : regex; + is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; + } + EXPECT_TRUE(is_valid_) + << "Regular expression \"" << regex + << "\" is not a valid POSIX Extended regular expression."; + + delete[] full_pattern; +} + +#elif GTEST_USES_SIMPLE_RE + +// Returns true iff ch appears anywhere in str (excluding the +// terminating '\0' character). +bool IsInSet(char ch, const char* str) { + return ch != '\0' && strchr(str, ch) != NULL; +} + +// Returns true iff ch belongs to the given classification. Unlike +// similar functions in , these aren't affected by the +// current locale. +bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } +bool IsAsciiPunct(char ch) { + return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); +} +bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } +bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } +bool IsAsciiWordChar(char ch) { + return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || + ('0' <= ch && ch <= '9') || ch == '_'; +} + +// Returns true iff "\\c" is a supported escape sequence. +bool IsValidEscape(char c) { + return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); +} + +// Returns true iff the given atom (specified by escaped and pattern) +// matches ch. The result is undefined if the atom is invalid. +bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { + if (escaped) { // "\\p" where p is pattern_char. + switch (pattern_char) { + case 'd': return IsAsciiDigit(ch); + case 'D': return !IsAsciiDigit(ch); + case 'f': return ch == '\f'; + case 'n': return ch == '\n'; + case 'r': return ch == '\r'; + case 's': return IsAsciiWhiteSpace(ch); + case 'S': return !IsAsciiWhiteSpace(ch); + case 't': return ch == '\t'; + case 'v': return ch == '\v'; + case 'w': return IsAsciiWordChar(ch); + case 'W': return !IsAsciiWordChar(ch); + } + return IsAsciiPunct(pattern_char) && pattern_char == ch; + } + + return (pattern_char == '.' && ch != '\n') || pattern_char == ch; +} + +// Helper function used by ValidateRegex() to format error messages. +std::string FormatRegexSyntaxError(const char* regex, int index) { + return (Message() << "Syntax error at index " << index + << " in simple regular expression \"" << regex << "\": ").GetString(); +} + +// Generates non-fatal failures and returns false if regex is invalid; +// otherwise returns true. +bool ValidateRegex(const char* regex) { + if (regex == NULL) { + // TODO(wan@google.com): fix the source file location in the + // assertion failures to match where the regex is used in user + // code. + ADD_FAILURE() << "NULL is not a valid simple regular expression."; + return false; + } + + bool is_valid = true; + + // True iff ?, *, or + can follow the previous atom. + bool prev_repeatable = false; + for (int i = 0; regex[i]; i++) { + if (regex[i] == '\\') { // An escape sequence + i++; + if (regex[i] == '\0') { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) + << "'\\' cannot appear at the end."; + return false; + } + + if (!IsValidEscape(regex[i])) { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) + << "invalid escape sequence \"\\" << regex[i] << "\"."; + is_valid = false; + } + prev_repeatable = true; + } else { // Not an escape sequence. + const char ch = regex[i]; + + if (ch == '^' && i > 0) { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) + << "'^' can only appear at the beginning."; + is_valid = false; + } else if (ch == '$' && regex[i + 1] != '\0') { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) + << "'$' can only appear at the end."; + is_valid = false; + } else if (IsInSet(ch, "()[]{}|")) { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) + << "'" << ch << "' is unsupported."; + is_valid = false; + } else if (IsRepeat(ch) && !prev_repeatable) { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) + << "'" << ch << "' can only follow a repeatable token."; + is_valid = false; + } + + prev_repeatable = !IsInSet(ch, "^$?*+"); + } + } + + return is_valid; +} + +// Matches a repeated regex atom followed by a valid simple regular +// expression. The regex atom is defined as c if escaped is false, +// or \c otherwise. repeat is the repetition meta character (?, *, +// or +). The behavior is undefined if str contains too many +// characters to be indexable by size_t, in which case the test will +// probably time out anyway. We are fine with this limitation as +// std::string has it too. +bool MatchRepetitionAndRegexAtHead( + bool escaped, char c, char repeat, const char* regex, + const char* str) { + const size_t min_count = (repeat == '+') ? 1 : 0; + const size_t max_count = (repeat == '?') ? 1 : + static_cast(-1) - 1; + // We cannot call numeric_limits::max() as it conflicts with the + // max() macro on Windows. + + for (size_t i = 0; i <= max_count; ++i) { + // We know that the atom matches each of the first i characters in str. + if (i >= min_count && MatchRegexAtHead(regex, str + i)) { + // We have enough matches at the head, and the tail matches too. + // Since we only care about *whether* the pattern matches str + // (as opposed to *how* it matches), there is no need to find a + // greedy match. + return true; + } + if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) + return false; + } + return false; +} + +// Returns true iff regex matches a prefix of str. regex must be a +// valid simple regular expression and not start with "^", or the +// result is undefined. +bool MatchRegexAtHead(const char* regex, const char* str) { + if (*regex == '\0') // An empty regex matches a prefix of anything. + return true; + + // "$" only matches the end of a string. Note that regex being + // valid guarantees that there's nothing after "$" in it. + if (*regex == '$') + return *str == '\0'; + + // Is the first thing in regex an escape sequence? + const bool escaped = *regex == '\\'; + if (escaped) + ++regex; + if (IsRepeat(regex[1])) { + // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so + // here's an indirect recursion. It terminates as the regex gets + // shorter in each recursion. + return MatchRepetitionAndRegexAtHead( + escaped, regex[0], regex[1], regex + 2, str); + } else { + // regex isn't empty, isn't "$", and doesn't start with a + // repetition. We match the first atom of regex with the first + // character of str and recurse. + return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && + MatchRegexAtHead(regex + 1, str + 1); + } +} + +// Returns true iff regex matches any substring of str. regex must be +// a valid simple regular expression, or the result is undefined. +// +// The algorithm is recursive, but the recursion depth doesn't exceed +// the regex length, so we won't need to worry about running out of +// stack space normally. In rare cases the time complexity can be +// exponential with respect to the regex length + the string length, +// but usually it's must faster (often close to linear). +bool MatchRegexAnywhere(const char* regex, const char* str) { + if (regex == NULL || str == NULL) + return false; + + if (*regex == '^') + return MatchRegexAtHead(regex + 1, str); + + // A successful match can be anywhere in str. + do { + if (MatchRegexAtHead(regex, str)) + return true; + } while (*str++ != '\0'); + return false; +} + +// Implements the RE class. + +RE::~RE() { + free(const_cast(pattern_)); + free(const_cast(full_pattern_)); +} + +// Returns true iff regular expression re matches the entire str. +bool RE::FullMatch(const char* str, const RE& re) { + return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); +} + +// Returns true iff regular expression re matches a substring of str +// (including str itself). +bool RE::PartialMatch(const char* str, const RE& re) { + return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); +} + +// Initializes an RE from its string representation. +void RE::Init(const char* regex) { + pattern_ = full_pattern_ = NULL; + if (regex != NULL) { + pattern_ = posix::StrDup(regex); + } + + is_valid_ = ValidateRegex(regex); + if (!is_valid_) { + // No need to calculate the full pattern when the regex is invalid. + return; + } + + const size_t len = strlen(regex); + // Reserves enough bytes to hold the regular expression used for a + // full match: we need space to prepend a '^', append a '$', and + // terminate the string with '\0'. + char* buffer = static_cast(malloc(len + 3)); + full_pattern_ = buffer; + + if (*regex != '^') + *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. + + // We don't use snprintf or strncpy, as they trigger a warning when + // compiled with VC++ 8.0. + memcpy(buffer, regex, len); + buffer += len; + + if (len == 0 || regex[len - 1] != '$') + *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. + + *buffer = '\0'; +} + +#endif // GTEST_USES_POSIX_RE + +const char kUnknownFile[] = "unknown file"; + +// Formats a source file path and a line number as they would appear +// in an error message from the compiler used to compile this code. +GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { + const std::string file_name(file == NULL ? kUnknownFile : file); + + if (line < 0) { + return file_name + ":"; + } +#ifdef _MSC_VER + return file_name + "(" + StreamableToString(line) + "):"; +#else + return file_name + ":" + StreamableToString(line) + ":"; +#endif // _MSC_VER +} + +// Formats a file location for compiler-independent XML output. +// Although this function is not platform dependent, we put it next to +// FormatFileLocation in order to contrast the two functions. +// Note that FormatCompilerIndependentFileLocation() does NOT append colon +// to the file location it produces, unlike FormatFileLocation(). +GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( + const char* file, int line) { + const std::string file_name(file == NULL ? kUnknownFile : file); + + if (line < 0) + return file_name; + else + return file_name + ":" + StreamableToString(line); +} + + +GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) + : severity_(severity) { + const char* const marker = + severity == GTEST_INFO ? "[ INFO ]" : + severity == GTEST_WARNING ? "[WARNING]" : + severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; + GetStream() << ::std::endl << marker << " " + << FormatFileLocation(file, line).c_str() << ": "; +} + +// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. +GTestLog::~GTestLog() { + GetStream() << ::std::endl; + if (severity_ == GTEST_FATAL) { + fflush(stderr); + posix::Abort(); + } +} +// Disable Microsoft deprecation warnings for POSIX functions called from +// this class (creat, dup, dup2, and close) +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable: 4996) +#endif // _MSC_VER + +#if GTEST_HAS_STREAM_REDIRECTION + +// Object that captures an output stream (stdout/stderr). +class CapturedStream { + public: + // The ctor redirects the stream to a temporary file. + explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { +# if GTEST_OS_WINDOWS + char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT + char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT + + ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); + const UINT success = ::GetTempFileNameA(temp_dir_path, + "gtest_redir", + 0, // Generate unique file name. + temp_file_path); + GTEST_CHECK_(success != 0) + << "Unable to create a temporary file in " << temp_dir_path; + const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); + GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " + << temp_file_path; + filename_ = temp_file_path; +# else + // There's no guarantee that a test has write access to the current + // directory, so we create the temporary file in the /tmp directory + // instead. We use /tmp on most systems, and /sdcard on Android. + // That's because Android doesn't have /tmp. +# if GTEST_OS_LINUX_ANDROID + // Note: Android applications are expected to call the framework's + // Context.getExternalStorageDirectory() method through JNI to get + // the location of the world-writable SD Card directory. However, + // this requires a Context handle, which cannot be retrieved + // globally from native code. Doing so also precludes running the + // code as part of a regular standalone executable, which doesn't + // run in a Dalvik process (e.g. when running it through 'adb shell'). + // + // The location /sdcard is directly accessible from native code + // and is the only location (unofficially) supported by the Android + // team. It's generally a symlink to the real SD Card mount point + // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or + // other OEM-customized locations. Never rely on these, and always + // use /sdcard. + char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX"; +# else + char name_template[] = "/tmp/captured_stream.XXXXXX"; +# endif // GTEST_OS_LINUX_ANDROID + const int captured_fd = mkstemp(name_template); + filename_ = name_template; +# endif // GTEST_OS_WINDOWS + fflush(NULL); + dup2(captured_fd, fd_); + close(captured_fd); + } + + ~CapturedStream() { + remove(filename_.c_str()); + } + + std::string GetCapturedString() { + if (uncaptured_fd_ != -1) { + // Restores the original stream. + fflush(NULL); + dup2(uncaptured_fd_, fd_); + close(uncaptured_fd_); + uncaptured_fd_ = -1; + } + + FILE* const file = posix::FOpen(filename_.c_str(), "r"); + const std::string content = ReadEntireFile(file); + posix::FClose(file); + return content; + } + + private: + // Reads the entire content of a file as an std::string. + static std::string ReadEntireFile(FILE* file); + + // Returns the size (in bytes) of a file. + static size_t GetFileSize(FILE* file); + + const int fd_; // A stream to capture. + int uncaptured_fd_; + // Name of the temporary file holding the stderr output. + ::std::string filename_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); +}; + +// Returns the size (in bytes) of a file. +size_t CapturedStream::GetFileSize(FILE* file) { + fseek(file, 0, SEEK_END); + return static_cast(ftell(file)); +} + +// Reads the entire content of a file as a string. +std::string CapturedStream::ReadEntireFile(FILE* file) { + const size_t file_size = GetFileSize(file); + char* const buffer = new char[file_size]; + + size_t bytes_last_read = 0; // # of bytes read in the last fread() + size_t bytes_read = 0; // # of bytes read so far + + fseek(file, 0, SEEK_SET); + + // Keeps reading the file until we cannot read further or the + // pre-determined file size is reached. + do { + bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); + bytes_read += bytes_last_read; + } while (bytes_last_read > 0 && bytes_read < file_size); + + const std::string content(buffer, bytes_read); + delete[] buffer; + + return content; +} + +# ifdef _MSC_VER +# pragma warning(pop) +# endif // _MSC_VER + +static CapturedStream* g_captured_stderr = NULL; +static CapturedStream* g_captured_stdout = NULL; + +// Starts capturing an output stream (stdout/stderr). +void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { + if (*stream != NULL) { + GTEST_LOG_(FATAL) << "Only one " << stream_name + << " capturer can exist at a time."; + } + *stream = new CapturedStream(fd); +} + +// Stops capturing the output stream and returns the captured string. +std::string GetCapturedStream(CapturedStream** captured_stream) { + const std::string content = (*captured_stream)->GetCapturedString(); + + delete *captured_stream; + *captured_stream = NULL; + + return content; +} + +// Starts capturing stdout. +void CaptureStdout() { + CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); +} + +// Starts capturing stderr. +void CaptureStderr() { + CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); +} + +// Stops capturing stdout and returns the captured string. +std::string GetCapturedStdout() { + return GetCapturedStream(&g_captured_stdout); +} + +// Stops capturing stderr and returns the captured string. +std::string GetCapturedStderr() { + return GetCapturedStream(&g_captured_stderr); +} + +#endif // GTEST_HAS_STREAM_REDIRECTION + +#if GTEST_HAS_DEATH_TEST + +// A copy of all command line arguments. Set by InitGoogleTest(). +::std::vector g_argvs; + +static const ::std::vector* g_injected_test_argvs = + NULL; // Owned. + +void SetInjectableArgvs(const ::std::vector* argvs) { + if (g_injected_test_argvs != argvs) + delete g_injected_test_argvs; + g_injected_test_argvs = argvs; +} + +const ::std::vector& GetInjectableArgvs() { + if (g_injected_test_argvs != NULL) { + return *g_injected_test_argvs; + } + return g_argvs; +} +#endif // GTEST_HAS_DEATH_TEST + +#if GTEST_OS_WINDOWS_MOBILE +namespace posix { +void Abort() { + DebugBreak(); + TerminateProcess(GetCurrentProcess(), 1); +} +} // namespace posix +#endif // GTEST_OS_WINDOWS_MOBILE + +// Returns the name of the environment variable corresponding to the +// given flag. For example, FlagToEnvVar("foo") will return +// "GTEST_FOO" in the open-source version. +static std::string FlagToEnvVar(const char* flag) { + const std::string full_flag = + (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); + + Message env_var; + for (size_t i = 0; i != full_flag.length(); i++) { + env_var << ToUpper(full_flag.c_str()[i]); + } + + return env_var.GetString(); +} + +// Parses 'str' for a 32-bit signed integer. If successful, writes +// the result to *value and returns true; otherwise leaves *value +// unchanged and returns false. +bool ParseInt32(const Message& src_text, const char* str, Int32* value) { + // Parses the environment variable as a decimal integer. + char* end = NULL; + const long long_value = strtol(str, &end, 10); // NOLINT + + // Has strtol() consumed all characters in the string? + if (*end != '\0') { + // No - an invalid character was encountered. + Message msg; + msg << "WARNING: " << src_text + << " is expected to be a 32-bit integer, but actually" + << " has value \"" << str << "\".\n"; + printf("%s", msg.GetString().c_str()); + fflush(stdout); + return false; + } + + // Is the parsed value in the range of an Int32? + const Int32 result = static_cast(long_value); + if (long_value == LONG_MAX || long_value == LONG_MIN || + // The parsed value overflows as a long. (strtol() returns + // LONG_MAX or LONG_MIN when the input overflows.) + result != long_value + // The parsed value overflows as an Int32. + ) { + Message msg; + msg << "WARNING: " << src_text + << " is expected to be a 32-bit integer, but actually" + << " has value " << str << ", which overflows.\n"; + printf("%s", msg.GetString().c_str()); + fflush(stdout); + return false; + } + + *value = result; + return true; +} + +// Reads and returns the Boolean environment variable corresponding to +// the given flag; if it's not set, returns default_value. +// +// The value is considered true iff it's not "0". +bool BoolFromGTestEnv(const char* flag, bool default_value) { + const std::string env_var = FlagToEnvVar(flag); + const char* const string_value = posix::GetEnv(env_var.c_str()); + return string_value == NULL ? + default_value : strcmp(string_value, "0") != 0; +} + +// Reads and returns a 32-bit integer stored in the environment +// variable corresponding to the given flag; if it isn't set or +// doesn't represent a valid 32-bit integer, returns default_value. +Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { + const std::string env_var = FlagToEnvVar(flag); + const char* const string_value = posix::GetEnv(env_var.c_str()); + if (string_value == NULL) { + // The environment variable is not set. + return default_value; + } + + Int32 result = default_value; + if (!ParseInt32(Message() << "Environment variable " << env_var, + string_value, &result)) { + printf("The default value %s is used.\n", + (Message() << default_value).GetString().c_str()); + fflush(stdout); + return default_value; + } + + return result; +} + +// Reads and returns the string environment variable corresponding to +// the given flag; if it's not set, returns default_value. +const char* StringFromGTestEnv(const char* flag, const char* default_value) { + const std::string env_var = FlagToEnvVar(flag); + const char* const value = posix::GetEnv(env_var.c_str()); + return value == NULL ? default_value : value; +} + +} // namespace internal +} // namespace testing diff --git a/lib/gtest/src/gtest-printers.cc b/lib/gtest/src/gtest-printers.cc new file mode 100644 index 00000000..75fa4081 --- /dev/null +++ b/lib/gtest/src/gtest-printers.cc @@ -0,0 +1,363 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Test - The Google C++ Testing Framework +// +// This file implements a universal value printer that can print a +// value of any type T: +// +// void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr); +// +// It uses the << operator when possible, and prints the bytes in the +// object otherwise. A user can override its behavior for a class +// type Foo by defining either operator<<(::std::ostream&, const Foo&) +// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that +// defines Foo. + +#include "gtest/gtest-printers.h" +#include +#include +#include // NOLINT +#include +#include "gtest/internal/gtest-port.h" + +namespace testing { + +namespace { + +using ::std::ostream; + +// Prints a segment of bytes in the given object. +void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, + size_t count, ostream* os) { + char text[5] = ""; + for (size_t i = 0; i != count; i++) { + const size_t j = start + i; + if (i != 0) { + // Organizes the bytes into groups of 2 for easy parsing by + // human. + if ((j % 2) == 0) + *os << ' '; + else + *os << '-'; + } + GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]); + *os << text; + } +} + +// Prints the bytes in the given value to the given ostream. +void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, + ostream* os) { + // Tells the user how big the object is. + *os << count << "-byte object <"; + + const size_t kThreshold = 132; + const size_t kChunkSize = 64; + // If the object size is bigger than kThreshold, we'll have to omit + // some details by printing only the first and the last kChunkSize + // bytes. + // TODO(wan): let the user control the threshold using a flag. + if (count < kThreshold) { + PrintByteSegmentInObjectTo(obj_bytes, 0, count, os); + } else { + PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); + *os << " ... "; + // Rounds up to 2-byte boundary. + const size_t resume_pos = (count - kChunkSize + 1)/2*2; + PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); + } + *os << ">"; +} + +} // namespace + +namespace internal2 { + +// Delegates to PrintBytesInObjectToImpl() to print the bytes in the +// given object. The delegation simplifies the implementation, which +// uses the << operator and thus is easier done outside of the +// ::testing::internal namespace, which contains a << operator that +// sometimes conflicts with the one in STL. +void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, + ostream* os) { + PrintBytesInObjectToImpl(obj_bytes, count, os); +} + +} // namespace internal2 + +namespace internal { + +// Depending on the value of a char (or wchar_t), we print it in one +// of three formats: +// - as is if it's a printable ASCII (e.g. 'a', '2', ' '), +// - as a hexidecimal escape sequence (e.g. '\x7F'), or +// - as a special escape sequence (e.g. '\r', '\n'). +enum CharFormat { + kAsIs, + kHexEscape, + kSpecialEscape +}; + +// Returns true if c is a printable ASCII character. We test the +// value of c directly instead of calling isprint(), which is buggy on +// Windows Mobile. +inline bool IsPrintableAscii(wchar_t c) { + return 0x20 <= c && c <= 0x7E; +} + +// Prints a wide or narrow char c as a character literal without the +// quotes, escaping it when necessary; returns how c was formatted. +// The template argument UnsignedChar is the unsigned version of Char, +// which is the type of c. +template +static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) { + switch (static_cast(c)) { + case L'\0': + *os << "\\0"; + break; + case L'\'': + *os << "\\'"; + break; + case L'\\': + *os << "\\\\"; + break; + case L'\a': + *os << "\\a"; + break; + case L'\b': + *os << "\\b"; + break; + case L'\f': + *os << "\\f"; + break; + case L'\n': + *os << "\\n"; + break; + case L'\r': + *os << "\\r"; + break; + case L'\t': + *os << "\\t"; + break; + case L'\v': + *os << "\\v"; + break; + default: + if (IsPrintableAscii(c)) { + *os << static_cast(c); + return kAsIs; + } else { + *os << "\\x" + String::FormatHexInt(static_cast(c)); + return kHexEscape; + } + } + return kSpecialEscape; +} + +// Prints a wchar_t c as if it's part of a string literal, escaping it when +// necessary; returns how c was formatted. +static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) { + switch (c) { + case L'\'': + *os << "'"; + return kAsIs; + case L'"': + *os << "\\\""; + return kSpecialEscape; + default: + return PrintAsCharLiteralTo(c, os); + } +} + +// Prints a char c as if it's part of a string literal, escaping it when +// necessary; returns how c was formatted. +static CharFormat PrintAsStringLiteralTo(char c, ostream* os) { + return PrintAsStringLiteralTo( + static_cast(static_cast(c)), os); +} + +// Prints a wide or narrow character c and its code. '\0' is printed +// as "'\\0'", other unprintable characters are also properly escaped +// using the standard C++ escape sequence. The template argument +// UnsignedChar is the unsigned version of Char, which is the type of c. +template +void PrintCharAndCodeTo(Char c, ostream* os) { + // First, print c as a literal in the most readable form we can find. + *os << ((sizeof(c) > 1) ? "L'" : "'"); + const CharFormat format = PrintAsCharLiteralTo(c, os); + *os << "'"; + + // To aid user debugging, we also print c's code in decimal, unless + // it's 0 (in which case c was printed as '\\0', making the code + // obvious). + if (c == 0) + return; + *os << " (" << static_cast(c); + + // For more convenience, we print c's code again in hexidecimal, + // unless c was already printed in the form '\x##' or the code is in + // [1, 9]. + if (format == kHexEscape || (1 <= c && c <= 9)) { + // Do nothing. + } else { + *os << ", 0x" << String::FormatHexInt(static_cast(c)); + } + *os << ")"; +} + +void PrintTo(unsigned char c, ::std::ostream* os) { + PrintCharAndCodeTo(c, os); +} +void PrintTo(signed char c, ::std::ostream* os) { + PrintCharAndCodeTo(c, os); +} + +// Prints a wchar_t as a symbol if it is printable or as its internal +// code otherwise and also as its code. L'\0' is printed as "L'\\0'". +void PrintTo(wchar_t wc, ostream* os) { + PrintCharAndCodeTo(wc, os); +} + +// Prints the given array of characters to the ostream. CharType must be either +// char or wchar_t. +// The array starts at begin, the length is len, it may include '\0' characters +// and may not be NUL-terminated. +template +static void PrintCharsAsStringTo( + const CharType* begin, size_t len, ostream* os) { + const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\""; + *os << kQuoteBegin; + bool is_previous_hex = false; + for (size_t index = 0; index < len; ++index) { + const CharType cur = begin[index]; + if (is_previous_hex && IsXDigit(cur)) { + // Previous character is of '\x..' form and this character can be + // interpreted as another hexadecimal digit in its number. Break string to + // disambiguate. + *os << "\" " << kQuoteBegin; + } + is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape; + } + *os << "\""; +} + +// Prints a (const) char/wchar_t array of 'len' elements, starting at address +// 'begin'. CharType must be either char or wchar_t. +template +static void UniversalPrintCharArray( + const CharType* begin, size_t len, ostream* os) { + // The code + // const char kFoo[] = "foo"; + // generates an array of 4, not 3, elements, with the last one being '\0'. + // + // Therefore when printing a char array, we don't print the last element if + // it's '\0', such that the output matches the string literal as it's + // written in the source code. + if (len > 0 && begin[len - 1] == '\0') { + PrintCharsAsStringTo(begin, len - 1, os); + return; + } + + // If, however, the last element in the array is not '\0', e.g. + // const char kFoo[] = { 'f', 'o', 'o' }; + // we must print the entire array. We also print a message to indicate + // that the array is not NUL-terminated. + PrintCharsAsStringTo(begin, len, os); + *os << " (no terminating NUL)"; +} + +// Prints a (const) char array of 'len' elements, starting at address 'begin'. +void UniversalPrintArray(const char* begin, size_t len, ostream* os) { + UniversalPrintCharArray(begin, len, os); +} + +// Prints a (const) wchar_t array of 'len' elements, starting at address +// 'begin'. +void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) { + UniversalPrintCharArray(begin, len, os); +} + +// Prints the given C string to the ostream. +void PrintTo(const char* s, ostream* os) { + if (s == NULL) { + *os << "NULL"; + } else { + *os << ImplicitCast_(s) << " pointing to "; + PrintCharsAsStringTo(s, strlen(s), os); + } +} + +// MSVC compiler can be configured to define whar_t as a typedef +// of unsigned short. Defining an overload for const wchar_t* in that case +// would cause pointers to unsigned shorts be printed as wide strings, +// possibly accessing more memory than intended and causing invalid +// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when +// wchar_t is implemented as a native type. +#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) +// Prints the given wide C string to the ostream. +void PrintTo(const wchar_t* s, ostream* os) { + if (s == NULL) { + *os << "NULL"; + } else { + *os << ImplicitCast_(s) << " pointing to "; + PrintCharsAsStringTo(s, wcslen(s), os); + } +} +#endif // wchar_t is native + +// Prints a ::string object. +#if GTEST_HAS_GLOBAL_STRING +void PrintStringTo(const ::string& s, ostream* os) { + PrintCharsAsStringTo(s.data(), s.size(), os); +} +#endif // GTEST_HAS_GLOBAL_STRING + +void PrintStringTo(const ::std::string& s, ostream* os) { + PrintCharsAsStringTo(s.data(), s.size(), os); +} + +// Prints a ::wstring object. +#if GTEST_HAS_GLOBAL_WSTRING +void PrintWideStringTo(const ::wstring& s, ostream* os) { + PrintCharsAsStringTo(s.data(), s.size(), os); +} +#endif // GTEST_HAS_GLOBAL_WSTRING + +#if GTEST_HAS_STD_WSTRING +void PrintWideStringTo(const ::std::wstring& s, ostream* os) { + PrintCharsAsStringTo(s.data(), s.size(), os); +} +#endif // GTEST_HAS_STD_WSTRING + +} // namespace internal + +} // namespace testing diff --git a/lib/gtest/src/gtest-test-part.cc b/lib/gtest/src/gtest-test-part.cc new file mode 100644 index 00000000..c60eef3a --- /dev/null +++ b/lib/gtest/src/gtest-test-part.cc @@ -0,0 +1,110 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: mheule@google.com (Markus Heule) +// +// The Google C++ Testing Framework (Google Test) + +#include "gtest/gtest-test-part.h" + +// Indicates that this translation unit is part of Google Test's +// implementation. It must come before gtest-internal-inl.h is +// included, or there will be a compiler error. This trick is to +// prevent a user from accidentally including gtest-internal-inl.h in +// his code. +#define GTEST_IMPLEMENTATION_ 1 +#include "src/gtest-internal-inl.h" +#undef GTEST_IMPLEMENTATION_ + +namespace testing { + +using internal::GetUnitTestImpl; + +// Gets the summary of the failure message by omitting the stack trace +// in it. +std::string TestPartResult::ExtractSummary(const char* message) { + const char* const stack_trace = strstr(message, internal::kStackTraceMarker); + return stack_trace == NULL ? message : + std::string(message, stack_trace); +} + +// Prints a TestPartResult object. +std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { + return os + << result.file_name() << ":" << result.line_number() << ": " + << (result.type() == TestPartResult::kSuccess ? "Success" : + result.type() == TestPartResult::kFatalFailure ? "Fatal failure" : + "Non-fatal failure") << ":\n" + << result.message() << std::endl; +} + +// Appends a TestPartResult to the array. +void TestPartResultArray::Append(const TestPartResult& result) { + array_.push_back(result); +} + +// Returns the TestPartResult at the given index (0-based). +const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { + if (index < 0 || index >= size()) { + printf("\nInvalid index (%d) into TestPartResultArray.\n", index); + internal::posix::Abort(); + } + + return array_[index]; +} + +// Returns the number of TestPartResult objects in the array. +int TestPartResultArray::size() const { + return static_cast(array_.size()); +} + +namespace internal { + +HasNewFatalFailureHelper::HasNewFatalFailureHelper() + : has_new_fatal_failure_(false), + original_reporter_(GetUnitTestImpl()-> + GetTestPartResultReporterForCurrentThread()) { + GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); +} + +HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { + GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread( + original_reporter_); +} + +void HasNewFatalFailureHelper::ReportTestPartResult( + const TestPartResult& result) { + if (result.fatally_failed()) + has_new_fatal_failure_ = true; + original_reporter_->ReportTestPartResult(result); +} + +} // namespace internal + +} // namespace testing diff --git a/lib/gtest/src/gtest-typed-test.cc b/lib/gtest/src/gtest-typed-test.cc new file mode 100644 index 00000000..f0079f40 --- /dev/null +++ b/lib/gtest/src/gtest-typed-test.cc @@ -0,0 +1,110 @@ +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +#include "gtest/gtest-typed-test.h" +#include "gtest/gtest.h" + +namespace testing { +namespace internal { + +#if GTEST_HAS_TYPED_TEST_P + +// Skips to the first non-space char in str. Returns an empty string if str +// contains only whitespace characters. +static const char* SkipSpaces(const char* str) { + while (IsSpace(*str)) + str++; + return str; +} + +// Verifies that registered_tests match the test names in +// defined_test_names_; returns registered_tests if successful, or +// aborts the program otherwise. +const char* TypedTestCasePState::VerifyRegisteredTestNames( + const char* file, int line, const char* registered_tests) { + typedef ::std::set::const_iterator DefinedTestIter; + registered_ = true; + + // Skip initial whitespace in registered_tests since some + // preprocessors prefix stringizied literals with whitespace. + registered_tests = SkipSpaces(registered_tests); + + Message errors; + ::std::set tests; + for (const char* names = registered_tests; names != NULL; + names = SkipComma(names)) { + const std::string name = GetPrefixUntilComma(names); + if (tests.count(name) != 0) { + errors << "Test " << name << " is listed more than once.\n"; + continue; + } + + bool found = false; + for (DefinedTestIter it = defined_test_names_.begin(); + it != defined_test_names_.end(); + ++it) { + if (name == *it) { + found = true; + break; + } + } + + if (found) { + tests.insert(name); + } else { + errors << "No test named " << name + << " can be found in this test case.\n"; + } + } + + for (DefinedTestIter it = defined_test_names_.begin(); + it != defined_test_names_.end(); + ++it) { + if (tests.count(*it) == 0) { + errors << "You forgot to list test " << *it << ".\n"; + } + } + + const std::string& errors_str = errors.GetString(); + if (errors_str != "") { + fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), + errors_str.c_str()); + fflush(stderr); + posix::Abort(); + } + + return registered_tests; +} + +#endif // GTEST_HAS_TYPED_TEST_P + +} // namespace internal +} // namespace testing diff --git a/lib/gtest/src/gtest.cc b/lib/gtest/src/gtest.cc new file mode 100644 index 00000000..6de53dd0 --- /dev/null +++ b/lib/gtest/src/gtest.cc @@ -0,0 +1,5015 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// The Google C++ Testing Framework (Google Test) + +#include "gtest/gtest.h" +#include "gtest/gtest-spi.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include // NOLINT +#include +#include + +#if GTEST_OS_LINUX + +// TODO(kenton@google.com): Use autoconf to detect availability of +// gettimeofday(). +# define GTEST_HAS_GETTIMEOFDAY_ 1 + +# include // NOLINT +# include // NOLINT +# include // NOLINT +// Declares vsnprintf(). This header is not available on Windows. +# include // NOLINT +# include // NOLINT +# include // NOLINT +# include // NOLINT +# include + +#elif GTEST_OS_SYMBIAN +# define GTEST_HAS_GETTIMEOFDAY_ 1 +# include // NOLINT + +#elif GTEST_OS_ZOS +# define GTEST_HAS_GETTIMEOFDAY_ 1 +# include // NOLINT + +// On z/OS we additionally need strings.h for strcasecmp. +# include // NOLINT + +#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. + +# include // NOLINT + +#elif GTEST_OS_WINDOWS // We are on Windows proper. + +# include // NOLINT +# include // NOLINT +# include // NOLINT +# include // NOLINT + +# if GTEST_OS_WINDOWS_MINGW +// MinGW has gettimeofday() but not _ftime64(). +// TODO(kenton@google.com): Use autoconf to detect availability of +// gettimeofday(). +// TODO(kenton@google.com): There are other ways to get the time on +// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW +// supports these. consider using them instead. +# define GTEST_HAS_GETTIMEOFDAY_ 1 +# include // NOLINT +# endif // GTEST_OS_WINDOWS_MINGW + +// cpplint thinks that the header is already included, so we want to +// silence it. +# include // NOLINT + +#else + +// Assume other platforms have gettimeofday(). +// TODO(kenton@google.com): Use autoconf to detect availability of +// gettimeofday(). +# define GTEST_HAS_GETTIMEOFDAY_ 1 + +// cpplint thinks that the header is already included, so we want to +// silence it. +# include // NOLINT +# include // NOLINT + +#endif // GTEST_OS_LINUX + +#if GTEST_HAS_EXCEPTIONS +# include +#endif + +#if GTEST_CAN_STREAM_RESULTS_ +# include // NOLINT +# include // NOLINT +#endif + +// Indicates that this translation unit is part of Google Test's +// implementation. It must come before gtest-internal-inl.h is +// included, or there will be a compiler error. This trick is to +// prevent a user from accidentally including gtest-internal-inl.h in +// his code. +#define GTEST_IMPLEMENTATION_ 1 +#include "src/gtest-internal-inl.h" +#undef GTEST_IMPLEMENTATION_ + +#if GTEST_OS_WINDOWS +# define vsnprintf _vsnprintf +#endif // GTEST_OS_WINDOWS + +namespace testing { + +using internal::CountIf; +using internal::ForEach; +using internal::GetElementOr; +using internal::Shuffle; + +// Constants. + +// A test whose test case name or test name matches this filter is +// disabled and not run. +static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; + +// A test case whose name matches this filter is considered a death +// test case and will be run before test cases whose name doesn't +// match this filter. +static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*"; + +// A test filter that matches everything. +static const char kUniversalFilter[] = "*"; + +// The default output file for XML output. +static const char kDefaultOutputFile[] = "test_detail.xml"; + +// The environment variable name for the test shard index. +static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; +// The environment variable name for the total number of test shards. +static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; +// The environment variable name for the test shard status file. +static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; + +namespace internal { + +// The text used in failure messages to indicate the start of the +// stack trace. +const char kStackTraceMarker[] = "\nStack trace:\n"; + +// g_help_flag is true iff the --help flag or an equivalent form is +// specified on the command line. +bool g_help_flag = false; + +} // namespace internal + +static const char* GetDefaultFilter() { + return kUniversalFilter; +} + +GTEST_DEFINE_bool_( + also_run_disabled_tests, + internal::BoolFromGTestEnv("also_run_disabled_tests", false), + "Run disabled tests too, in addition to the tests normally being run."); + +GTEST_DEFINE_bool_( + break_on_failure, + internal::BoolFromGTestEnv("break_on_failure", false), + "True iff a failed assertion should be a debugger break-point."); + +GTEST_DEFINE_bool_( + catch_exceptions, + internal::BoolFromGTestEnv("catch_exceptions", true), + "True iff " GTEST_NAME_ + " should catch exceptions and treat them as test failures."); + +GTEST_DEFINE_string_( + color, + internal::StringFromGTestEnv("color", "auto"), + "Whether to use colors in the output. Valid values: yes, no, " + "and auto. 'auto' means to use colors if the output is " + "being sent to a terminal and the TERM environment variable " + "is set to a terminal type that supports colors."); + +GTEST_DEFINE_string_( + filter, + internal::StringFromGTestEnv("filter", GetDefaultFilter()), + "A colon-separated list of glob (not regex) patterns " + "for filtering the tests to run, optionally followed by a " + "'-' and a : separated list of negative patterns (tests to " + "exclude). A test is run if it matches one of the positive " + "patterns and does not match any of the negative patterns."); + +GTEST_DEFINE_bool_(list_tests, false, + "List all tests without running them."); + +GTEST_DEFINE_string_( + output, + internal::StringFromGTestEnv("output", ""), + "A format (currently must be \"xml\"), optionally followed " + "by a colon and an output file name or directory. A directory " + "is indicated by a trailing pathname separator. " + "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " + "If a directory is specified, output files will be created " + "within that directory, with file-names based on the test " + "executable's name and, if necessary, made unique by adding " + "digits."); + +GTEST_DEFINE_bool_( + print_time, + internal::BoolFromGTestEnv("print_time", true), + "True iff " GTEST_NAME_ + " should display elapsed time in text output."); + +GTEST_DEFINE_int32_( + random_seed, + internal::Int32FromGTestEnv("random_seed", 0), + "Random number seed to use when shuffling test orders. Must be in range " + "[1, 99999], or 0 to use a seed based on the current time."); + +GTEST_DEFINE_int32_( + repeat, + internal::Int32FromGTestEnv("repeat", 1), + "How many times to repeat each test. Specify a negative number " + "for repeating forever. Useful for shaking out flaky tests."); + +GTEST_DEFINE_bool_( + show_internal_stack_frames, false, + "True iff " GTEST_NAME_ " should include internal stack frames when " + "printing test failure stack traces."); + +GTEST_DEFINE_bool_( + shuffle, + internal::BoolFromGTestEnv("shuffle", false), + "True iff " GTEST_NAME_ + " should randomize tests' order on every run."); + +GTEST_DEFINE_int32_( + stack_trace_depth, + internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), + "The maximum number of stack frames to print when an " + "assertion fails. The valid range is 0 through 100, inclusive."); + +GTEST_DEFINE_string_( + stream_result_to, + internal::StringFromGTestEnv("stream_result_to", ""), + "This flag specifies the host name and the port number on which to stream " + "test results. Example: \"localhost:555\". The flag is effective only on " + "Linux."); + +GTEST_DEFINE_bool_( + throw_on_failure, + internal::BoolFromGTestEnv("throw_on_failure", false), + "When this flag is specified, a failed assertion will throw an exception " + "if exceptions are enabled or exit the program with a non-zero code " + "otherwise."); + +namespace internal { + +// Generates a random number from [0, range), using a Linear +// Congruential Generator (LCG). Crashes if 'range' is 0 or greater +// than kMaxRange. +UInt32 Random::Generate(UInt32 range) { + // These constants are the same as are used in glibc's rand(3). + state_ = (1103515245U*state_ + 12345U) % kMaxRange; + + GTEST_CHECK_(range > 0) + << "Cannot generate a number in the range [0, 0)."; + GTEST_CHECK_(range <= kMaxRange) + << "Generation of a number in [0, " << range << ") was requested, " + << "but this can only generate numbers in [0, " << kMaxRange << ")."; + + // Converting via modulus introduces a bit of downward bias, but + // it's simple, and a linear congruential generator isn't too good + // to begin with. + return state_ % range; +} + +// GTestIsInitialized() returns true iff the user has initialized +// Google Test. Useful for catching the user mistake of not initializing +// Google Test before calling RUN_ALL_TESTS(). +// +// A user must call testing::InitGoogleTest() to initialize Google +// Test. g_init_gtest_count is set to the number of times +// InitGoogleTest() has been called. We don't protect this variable +// under a mutex as it is only accessed in the main thread. +GTEST_API_ int g_init_gtest_count = 0; +static bool GTestIsInitialized() { return g_init_gtest_count != 0; } + +// Iterates over a vector of TestCases, keeping a running sum of the +// results of calling a given int-returning method on each. +// Returns the sum. +static int SumOverTestCaseList(const std::vector& case_list, + int (TestCase::*method)() const) { + int sum = 0; + for (size_t i = 0; i < case_list.size(); i++) { + sum += (case_list[i]->*method)(); + } + return sum; +} + +// Returns true iff the test case passed. +static bool TestCasePassed(const TestCase* test_case) { + return test_case->should_run() && test_case->Passed(); +} + +// Returns true iff the test case failed. +static bool TestCaseFailed(const TestCase* test_case) { + return test_case->should_run() && test_case->Failed(); +} + +// Returns true iff test_case contains at least one test that should +// run. +static bool ShouldRunTestCase(const TestCase* test_case) { + return test_case->should_run(); +} + +// AssertHelper constructor. +AssertHelper::AssertHelper(TestPartResult::Type type, + const char* file, + int line, + const char* message) + : data_(new AssertHelperData(type, file, line, message)) { +} + +AssertHelper::~AssertHelper() { + delete data_; +} + +// Message assignment, for assertion streaming support. +void AssertHelper::operator=(const Message& message) const { + UnitTest::GetInstance()-> + AddTestPartResult(data_->type, data_->file, data_->line, + AppendUserMessage(data_->message, message), + UnitTest::GetInstance()->impl() + ->CurrentOsStackTraceExceptTop(1) + // Skips the stack frame for this function itself. + ); // NOLINT +} + +// Mutex for linked pointers. +GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex); + +// Application pathname gotten in InitGoogleTest. +std::string g_executable_path; + +// Returns the current application's name, removing directory path if that +// is present. +FilePath GetCurrentExecutableName() { + FilePath result; + +#if GTEST_OS_WINDOWS + result.Set(FilePath(g_executable_path).RemoveExtension("exe")); +#else + result.Set(FilePath(g_executable_path)); +#endif // GTEST_OS_WINDOWS + + return result.RemoveDirectoryName(); +} + +// Functions for processing the gtest_output flag. + +// Returns the output format, or "" for normal printed output. +std::string UnitTestOptions::GetOutputFormat() { + const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); + if (gtest_output_flag == NULL) return std::string(""); + + const char* const colon = strchr(gtest_output_flag, ':'); + return (colon == NULL) ? + std::string(gtest_output_flag) : + std::string(gtest_output_flag, colon - gtest_output_flag); +} + +// Returns the name of the requested output file, or the default if none +// was explicitly specified. +std::string UnitTestOptions::GetAbsolutePathToOutputFile() { + const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); + if (gtest_output_flag == NULL) + return ""; + + const char* const colon = strchr(gtest_output_flag, ':'); + if (colon == NULL) + return internal::FilePath::ConcatPaths( + internal::FilePath( + UnitTest::GetInstance()->original_working_dir()), + internal::FilePath(kDefaultOutputFile)).string(); + + internal::FilePath output_name(colon + 1); + if (!output_name.IsAbsolutePath()) + // TODO(wan@google.com): on Windows \some\path is not an absolute + // path (as its meaning depends on the current drive), yet the + // following logic for turning it into an absolute path is wrong. + // Fix it. + output_name = internal::FilePath::ConcatPaths( + internal::FilePath(UnitTest::GetInstance()->original_working_dir()), + internal::FilePath(colon + 1)); + + if (!output_name.IsDirectory()) + return output_name.string(); + + internal::FilePath result(internal::FilePath::GenerateUniqueFileName( + output_name, internal::GetCurrentExecutableName(), + GetOutputFormat().c_str())); + return result.string(); +} + +// Returns true iff the wildcard pattern matches the string. The +// first ':' or '\0' character in pattern marks the end of it. +// +// This recursive algorithm isn't very efficient, but is clear and +// works well enough for matching test names, which are short. +bool UnitTestOptions::PatternMatchesString(const char *pattern, + const char *str) { + switch (*pattern) { + case '\0': + case ':': // Either ':' or '\0' marks the end of the pattern. + return *str == '\0'; + case '?': // Matches any single character. + return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); + case '*': // Matches any string (possibly empty) of characters. + return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || + PatternMatchesString(pattern + 1, str); + default: // Non-special character. Matches itself. + return *pattern == *str && + PatternMatchesString(pattern + 1, str + 1); + } +} + +bool UnitTestOptions::MatchesFilter( + const std::string& name, const char* filter) { + const char *cur_pattern = filter; + for (;;) { + if (PatternMatchesString(cur_pattern, name.c_str())) { + return true; + } + + // Finds the next pattern in the filter. + cur_pattern = strchr(cur_pattern, ':'); + + // Returns if no more pattern can be found. + if (cur_pattern == NULL) { + return false; + } + + // Skips the pattern separater (the ':' character). + cur_pattern++; + } +} + +// Returns true iff the user-specified filter matches the test case +// name and the test name. +bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name, + const std::string &test_name) { + const std::string& full_name = test_case_name + "." + test_name.c_str(); + + // Split --gtest_filter at '-', if there is one, to separate into + // positive filter and negative filter portions + const char* const p = GTEST_FLAG(filter).c_str(); + const char* const dash = strchr(p, '-'); + std::string positive; + std::string negative; + if (dash == NULL) { + positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter + negative = ""; + } else { + positive = std::string(p, dash); // Everything up to the dash + negative = std::string(dash + 1); // Everything after the dash + if (positive.empty()) { + // Treat '-test1' as the same as '*-test1' + positive = kUniversalFilter; + } + } + + // A filter is a colon-separated list of patterns. It matches a + // test if any pattern in it matches the test. + return (MatchesFilter(full_name, positive.c_str()) && + !MatchesFilter(full_name, negative.c_str())); +} + +#if GTEST_HAS_SEH +// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the +// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. +// This function is useful as an __except condition. +int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { + // Google Test should handle a SEH exception if: + // 1. the user wants it to, AND + // 2. this is not a breakpoint exception, AND + // 3. this is not a C++ exception (VC++ implements them via SEH, + // apparently). + // + // SEH exception code for C++ exceptions. + // (see http://support.microsoft.com/kb/185294 for more information). + const DWORD kCxxExceptionCode = 0xe06d7363; + + bool should_handle = true; + + if (!GTEST_FLAG(catch_exceptions)) + should_handle = false; + else if (exception_code == EXCEPTION_BREAKPOINT) + should_handle = false; + else if (exception_code == kCxxExceptionCode) + should_handle = false; + + return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; +} +#endif // GTEST_HAS_SEH + +} // namespace internal + +// The c'tor sets this object as the test part result reporter used by +// Google Test. The 'result' parameter specifies where to report the +// results. Intercepts only failures from the current thread. +ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( + TestPartResultArray* result) + : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), + result_(result) { + Init(); +} + +// The c'tor sets this object as the test part result reporter used by +// Google Test. The 'result' parameter specifies where to report the +// results. +ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( + InterceptMode intercept_mode, TestPartResultArray* result) + : intercept_mode_(intercept_mode), + result_(result) { + Init(); +} + +void ScopedFakeTestPartResultReporter::Init() { + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + if (intercept_mode_ == INTERCEPT_ALL_THREADS) { + old_reporter_ = impl->GetGlobalTestPartResultReporter(); + impl->SetGlobalTestPartResultReporter(this); + } else { + old_reporter_ = impl->GetTestPartResultReporterForCurrentThread(); + impl->SetTestPartResultReporterForCurrentThread(this); + } +} + +// The d'tor restores the test part result reporter used by Google Test +// before. +ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + if (intercept_mode_ == INTERCEPT_ALL_THREADS) { + impl->SetGlobalTestPartResultReporter(old_reporter_); + } else { + impl->SetTestPartResultReporterForCurrentThread(old_reporter_); + } +} + +// Increments the test part result count and remembers the result. +// This method is from the TestPartResultReporterInterface interface. +void ScopedFakeTestPartResultReporter::ReportTestPartResult( + const TestPartResult& result) { + result_->Append(result); +} + +namespace internal { + +// Returns the type ID of ::testing::Test. We should always call this +// instead of GetTypeId< ::testing::Test>() to get the type ID of +// testing::Test. This is to work around a suspected linker bug when +// using Google Test as a framework on Mac OS X. The bug causes +// GetTypeId< ::testing::Test>() to return different values depending +// on whether the call is from the Google Test framework itself or +// from user test code. GetTestTypeId() is guaranteed to always +// return the same value, as it always calls GetTypeId<>() from the +// gtest.cc, which is within the Google Test framework. +TypeId GetTestTypeId() { + return GetTypeId(); +} + +// The value of GetTestTypeId() as seen from within the Google Test +// library. This is solely for testing GetTestTypeId(). +extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); + +// This predicate-formatter checks that 'results' contains a test part +// failure of the given type and that the failure message contains the +// given substring. +AssertionResult HasOneFailure(const char* /* results_expr */, + const char* /* type_expr */, + const char* /* substr_expr */, + const TestPartResultArray& results, + TestPartResult::Type type, + const string& substr) { + const std::string expected(type == TestPartResult::kFatalFailure ? + "1 fatal failure" : + "1 non-fatal failure"); + Message msg; + if (results.size() != 1) { + msg << "Expected: " << expected << "\n" + << " Actual: " << results.size() << " failures"; + for (int i = 0; i < results.size(); i++) { + msg << "\n" << results.GetTestPartResult(i); + } + return AssertionFailure() << msg; + } + + const TestPartResult& r = results.GetTestPartResult(0); + if (r.type() != type) { + return AssertionFailure() << "Expected: " << expected << "\n" + << " Actual:\n" + << r; + } + + if (strstr(r.message(), substr.c_str()) == NULL) { + return AssertionFailure() << "Expected: " << expected << " containing \"" + << substr << "\"\n" + << " Actual:\n" + << r; + } + + return AssertionSuccess(); +} + +// The constructor of SingleFailureChecker remembers where to look up +// test part results, what type of failure we expect, and what +// substring the failure message should contain. +SingleFailureChecker:: SingleFailureChecker( + const TestPartResultArray* results, + TestPartResult::Type type, + const string& substr) + : results_(results), + type_(type), + substr_(substr) {} + +// The destructor of SingleFailureChecker verifies that the given +// TestPartResultArray contains exactly one failure that has the given +// type and contains the given substring. If that's not the case, a +// non-fatal failure will be generated. +SingleFailureChecker::~SingleFailureChecker() { + EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); +} + +DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( + UnitTestImpl* unit_test) : unit_test_(unit_test) {} + +void DefaultGlobalTestPartResultReporter::ReportTestPartResult( + const TestPartResult& result) { + unit_test_->current_test_result()->AddTestPartResult(result); + unit_test_->listeners()->repeater()->OnTestPartResult(result); +} + +DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( + UnitTestImpl* unit_test) : unit_test_(unit_test) {} + +void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( + const TestPartResult& result) { + unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); +} + +// Returns the global test part result reporter. +TestPartResultReporterInterface* +UnitTestImpl::GetGlobalTestPartResultReporter() { + internal::MutexLock lock(&global_test_part_result_reporter_mutex_); + return global_test_part_result_repoter_; +} + +// Sets the global test part result reporter. +void UnitTestImpl::SetGlobalTestPartResultReporter( + TestPartResultReporterInterface* reporter) { + internal::MutexLock lock(&global_test_part_result_reporter_mutex_); + global_test_part_result_repoter_ = reporter; +} + +// Returns the test part result reporter for the current thread. +TestPartResultReporterInterface* +UnitTestImpl::GetTestPartResultReporterForCurrentThread() { + return per_thread_test_part_result_reporter_.get(); +} + +// Sets the test part result reporter for the current thread. +void UnitTestImpl::SetTestPartResultReporterForCurrentThread( + TestPartResultReporterInterface* reporter) { + per_thread_test_part_result_reporter_.set(reporter); +} + +// Gets the number of successful test cases. +int UnitTestImpl::successful_test_case_count() const { + return CountIf(test_cases_, TestCasePassed); +} + +// Gets the number of failed test cases. +int UnitTestImpl::failed_test_case_count() const { + return CountIf(test_cases_, TestCaseFailed); +} + +// Gets the number of all test cases. +int UnitTestImpl::total_test_case_count() const { + return static_cast(test_cases_.size()); +} + +// Gets the number of all test cases that contain at least one test +// that should run. +int UnitTestImpl::test_case_to_run_count() const { + return CountIf(test_cases_, ShouldRunTestCase); +} + +// Gets the number of successful tests. +int UnitTestImpl::successful_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count); +} + +// Gets the number of failed tests. +int UnitTestImpl::failed_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); +} + +// Gets the number of disabled tests that will be reported in the XML report. +int UnitTestImpl::reportable_disabled_test_count() const { + return SumOverTestCaseList(test_cases_, + &TestCase::reportable_disabled_test_count); +} + +// Gets the number of disabled tests. +int UnitTestImpl::disabled_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count); +} + +// Gets the number of tests to be printed in the XML report. +int UnitTestImpl::reportable_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count); +} + +// Gets the number of all tests. +int UnitTestImpl::total_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); +} + +// Gets the number of tests that should run. +int UnitTestImpl::test_to_run_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); +} + +// Returns the current OS stack trace as an std::string. +// +// The maximum number of stack frames to be included is specified by +// the gtest_stack_trace_depth flag. The skip_count parameter +// specifies the number of top frames to be skipped, which doesn't +// count against the number of frames to be included. +// +// For example, if Foo() calls Bar(), which in turn calls +// CurrentOsStackTraceExceptTop(1), Foo() will be included in the +// trace but Bar() and CurrentOsStackTraceExceptTop() won't. +std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { + (void)skip_count; + return ""; +} + +// Returns the current time in milliseconds. +TimeInMillis GetTimeInMillis() { +#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) + // Difference between 1970-01-01 and 1601-01-01 in milliseconds. + // http://analogous.blogspot.com/2005/04/epoch.html + const TimeInMillis kJavaEpochToWinFileTimeDelta = + static_cast(116444736UL) * 100000UL; + const DWORD kTenthMicrosInMilliSecond = 10000; + + SYSTEMTIME now_systime; + FILETIME now_filetime; + ULARGE_INTEGER now_int64; + // TODO(kenton@google.com): Shouldn't this just use + // GetSystemTimeAsFileTime()? + GetSystemTime(&now_systime); + if (SystemTimeToFileTime(&now_systime, &now_filetime)) { + now_int64.LowPart = now_filetime.dwLowDateTime; + now_int64.HighPart = now_filetime.dwHighDateTime; + now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - + kJavaEpochToWinFileTimeDelta; + return now_int64.QuadPart; + } + return 0; +#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ + __timeb64 now; + +# ifdef _MSC_VER + + // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 + // (deprecated function) there. + // TODO(kenton@google.com): Use GetTickCount()? Or use + // SystemTimeToFileTime() +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4996) // Temporarily disables warning 4996. + _ftime64(&now); +# pragma warning(pop) // Restores the warning state. +# else + + _ftime64(&now); + +# endif // _MSC_VER + + return static_cast(now.time) * 1000 + now.millitm; +#elif GTEST_HAS_GETTIMEOFDAY_ + struct timeval now; + gettimeofday(&now, NULL); + return static_cast(now.tv_sec) * 1000 + now.tv_usec / 1000; +#else +# error "Don't know how to get the current time on your system." +#endif +} + +// Utilities + +// class String. + +#if GTEST_OS_WINDOWS_MOBILE +// Creates a UTF-16 wide string from the given ANSI string, allocating +// memory using new. The caller is responsible for deleting the return +// value using delete[]. Returns the wide string, or NULL if the +// input is NULL. +LPCWSTR String::AnsiToUtf16(const char* ansi) { + if (!ansi) return NULL; + const int length = strlen(ansi); + const int unicode_length = + MultiByteToWideChar(CP_ACP, 0, ansi, length, + NULL, 0); + WCHAR* unicode = new WCHAR[unicode_length + 1]; + MultiByteToWideChar(CP_ACP, 0, ansi, length, + unicode, unicode_length); + unicode[unicode_length] = 0; + return unicode; +} + +// Creates an ANSI string from the given wide string, allocating +// memory using new. The caller is responsible for deleting the return +// value using delete[]. Returns the ANSI string, or NULL if the +// input is NULL. +const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { + if (!utf16_str) return NULL; + const int ansi_length = + WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, + NULL, 0, NULL, NULL); + char* ansi = new char[ansi_length + 1]; + WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, + ansi, ansi_length, NULL, NULL); + ansi[ansi_length] = 0; + return ansi; +} + +#endif // GTEST_OS_WINDOWS_MOBILE + +// Compares two C strings. Returns true iff they have the same content. +// +// Unlike strcmp(), this function can handle NULL argument(s). A NULL +// C string is considered different to any non-NULL C string, +// including the empty string. +bool String::CStringEquals(const char * lhs, const char * rhs) { + if ( lhs == NULL ) return rhs == NULL; + + if ( rhs == NULL ) return false; + + return strcmp(lhs, rhs) == 0; +} + +#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING + +// Converts an array of wide chars to a narrow string using the UTF-8 +// encoding, and streams the result to the given Message object. +static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, + Message* msg) { + for (size_t i = 0; i != length; ) { // NOLINT + if (wstr[i] != L'\0') { + *msg << WideStringToUtf8(wstr + i, static_cast(length - i)); + while (i != length && wstr[i] != L'\0') + i++; + } else { + *msg << '\0'; + i++; + } + } +} + +#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING + +} // namespace internal + +// Constructs an empty Message. +// We allocate the stringstream separately because otherwise each use of +// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's +// stack frame leading to huge stack frames in some cases; gcc does not reuse +// the stack space. +Message::Message() : ss_(new ::std::stringstream) { + // By default, we want there to be enough precision when printing + // a double to a Message. + *ss_ << std::setprecision(std::numeric_limits::digits10 + 2); +} + +// These two overloads allow streaming a wide C string to a Message +// using the UTF-8 encoding. +Message& Message::operator <<(const wchar_t* wide_c_str) { + return *this << internal::String::ShowWideCString(wide_c_str); +} +Message& Message::operator <<(wchar_t* wide_c_str) { + return *this << internal::String::ShowWideCString(wide_c_str); +} + +#if GTEST_HAS_STD_WSTRING +// Converts the given wide string to a narrow string using the UTF-8 +// encoding, and streams the result to this Message object. +Message& Message::operator <<(const ::std::wstring& wstr) { + internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); + return *this; +} +#endif // GTEST_HAS_STD_WSTRING + +#if GTEST_HAS_GLOBAL_WSTRING +// Converts the given wide string to a narrow string using the UTF-8 +// encoding, and streams the result to this Message object. +Message& Message::operator <<(const ::wstring& wstr) { + internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); + return *this; +} +#endif // GTEST_HAS_GLOBAL_WSTRING + +// Gets the text streamed to this object so far as an std::string. +// Each '\0' character in the buffer is replaced with "\\0". +std::string Message::GetString() const { + return internal::StringStreamToString(ss_.get()); +} + +// AssertionResult constructors. +// Used in EXPECT_TRUE/FALSE(assertion_result). +AssertionResult::AssertionResult(const AssertionResult& other) + : success_(other.success_), + message_(other.message_.get() != NULL ? + new ::std::string(*other.message_) : + static_cast< ::std::string*>(NULL)) { +} + +// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. +AssertionResult AssertionResult::operator!() const { + AssertionResult negation(!success_); + if (message_.get() != NULL) + negation << *message_; + return negation; +} + +// Makes a successful assertion result. +AssertionResult AssertionSuccess() { + return AssertionResult(true); +} + +// Makes a failed assertion result. +AssertionResult AssertionFailure() { + return AssertionResult(false); +} + +// Makes a failed assertion result with the given failure message. +// Deprecated; use AssertionFailure() << message. +AssertionResult AssertionFailure(const Message& message) { + return AssertionFailure() << message; +} + +namespace internal { + +// Constructs and returns the message for an equality assertion +// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. +// +// The first four parameters are the expressions used in the assertion +// and their values, as strings. For example, for ASSERT_EQ(foo, bar) +// where foo is 5 and bar is 6, we have: +// +// expected_expression: "foo" +// actual_expression: "bar" +// expected_value: "5" +// actual_value: "6" +// +// The ignoring_case parameter is true iff the assertion is a +// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will +// be inserted into the message. +AssertionResult EqFailure(const char* expected_expression, + const char* actual_expression, + const std::string& expected_value, + const std::string& actual_value, + bool ignoring_case) { + Message msg; + msg << "Value of: " << actual_expression; + if (actual_value != actual_expression) { + msg << "\n Actual: " << actual_value; + } + + msg << "\nExpected: " << expected_expression; + if (ignoring_case) { + msg << " (ignoring case)"; + } + if (expected_value != expected_expression) { + msg << "\nWhich is: " << expected_value; + } + + return AssertionFailure() << msg; +} + +// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. +std::string GetBoolAssertionFailureMessage( + const AssertionResult& assertion_result, + const char* expression_text, + const char* actual_predicate_value, + const char* expected_predicate_value) { + const char* actual_message = assertion_result.message(); + Message msg; + msg << "Value of: " << expression_text + << "\n Actual: " << actual_predicate_value; + if (actual_message[0] != '\0') + msg << " (" << actual_message << ")"; + msg << "\nExpected: " << expected_predicate_value; + return msg.GetString(); +} + +// Helper function for implementing ASSERT_NEAR. +AssertionResult DoubleNearPredFormat(const char* expr1, + const char* expr2, + const char* abs_error_expr, + double val1, + double val2, + double abs_error) { + const double diff = fabs(val1 - val2); + if (diff <= abs_error) return AssertionSuccess(); + + // TODO(wan): do not print the value of an expression if it's + // already a literal. + return AssertionFailure() + << "The difference between " << expr1 << " and " << expr2 + << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" + << expr1 << " evaluates to " << val1 << ",\n" + << expr2 << " evaluates to " << val2 << ", and\n" + << abs_error_expr << " evaluates to " << abs_error << "."; +} + + +// Helper template for implementing FloatLE() and DoubleLE(). +template +AssertionResult FloatingPointLE(const char* expr1, + const char* expr2, + RawType val1, + RawType val2) { + // Returns success if val1 is less than val2, + if (val1 < val2) { + return AssertionSuccess(); + } + + // or if val1 is almost equal to val2. + const FloatingPoint lhs(val1), rhs(val2); + if (lhs.AlmostEquals(rhs)) { + return AssertionSuccess(); + } + + // Note that the above two checks will both fail if either val1 or + // val2 is NaN, as the IEEE floating-point standard requires that + // any predicate involving a NaN must return false. + + ::std::stringstream val1_ss; + val1_ss << std::setprecision(std::numeric_limits::digits10 + 2) + << val1; + + ::std::stringstream val2_ss; + val2_ss << std::setprecision(std::numeric_limits::digits10 + 2) + << val2; + + return AssertionFailure() + << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" + << " Actual: " << StringStreamToString(&val1_ss) << " vs " + << StringStreamToString(&val2_ss); +} + +} // namespace internal + +// Asserts that val1 is less than, or almost equal to, val2. Fails +// otherwise. In particular, it fails if either val1 or val2 is NaN. +AssertionResult FloatLE(const char* expr1, const char* expr2, + float val1, float val2) { + return internal::FloatingPointLE(expr1, expr2, val1, val2); +} + +// Asserts that val1 is less than, or almost equal to, val2. Fails +// otherwise. In particular, it fails if either val1 or val2 is NaN. +AssertionResult DoubleLE(const char* expr1, const char* expr2, + double val1, double val2) { + return internal::FloatingPointLE(expr1, expr2, val1, val2); +} + +namespace internal { + +// The helper function for {ASSERT|EXPECT}_EQ with int or enum +// arguments. +AssertionResult CmpHelperEQ(const char* expected_expression, + const char* actual_expression, + BiggestInt expected, + BiggestInt actual) { + if (expected == actual) { + return AssertionSuccess(); + } + + return EqFailure(expected_expression, + actual_expression, + FormatForComparisonFailureMessage(expected, actual), + FormatForComparisonFailureMessage(actual, expected), + false); +} + +// A macro for implementing the helper functions needed to implement +// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here +// just to avoid copy-and-paste of similar code. +#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ +AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ + BiggestInt val1, BiggestInt val2) {\ + if (val1 op val2) {\ + return AssertionSuccess();\ + } else {\ + return AssertionFailure() \ + << "Expected: (" << expr1 << ") " #op " (" << expr2\ + << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ + << " vs " << FormatForComparisonFailureMessage(val2, val1);\ + }\ +} + +// Implements the helper function for {ASSERT|EXPECT}_NE with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(NE, !=) +// Implements the helper function for {ASSERT|EXPECT}_LE with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(LE, <=) +// Implements the helper function for {ASSERT|EXPECT}_LT with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(LT, < ) +// Implements the helper function for {ASSERT|EXPECT}_GE with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(GE, >=) +// Implements the helper function for {ASSERT|EXPECT}_GT with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(GT, > ) + +#undef GTEST_IMPL_CMP_HELPER_ + +// The helper function for {ASSERT|EXPECT}_STREQ. +AssertionResult CmpHelperSTREQ(const char* expected_expression, + const char* actual_expression, + const char* expected, + const char* actual) { + if (String::CStringEquals(expected, actual)) { + return AssertionSuccess(); + } + + return EqFailure(expected_expression, + actual_expression, + PrintToString(expected), + PrintToString(actual), + false); +} + +// The helper function for {ASSERT|EXPECT}_STRCASEEQ. +AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, + const char* actual_expression, + const char* expected, + const char* actual) { + if (String::CaseInsensitiveCStringEquals(expected, actual)) { + return AssertionSuccess(); + } + + return EqFailure(expected_expression, + actual_expression, + PrintToString(expected), + PrintToString(actual), + true); +} + +// The helper function for {ASSERT|EXPECT}_STRNE. +AssertionResult CmpHelperSTRNE(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2) { + if (!String::CStringEquals(s1, s2)) { + return AssertionSuccess(); + } else { + return AssertionFailure() << "Expected: (" << s1_expression << ") != (" + << s2_expression << "), actual: \"" + << s1 << "\" vs \"" << s2 << "\""; + } +} + +// The helper function for {ASSERT|EXPECT}_STRCASENE. +AssertionResult CmpHelperSTRCASENE(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2) { + if (!String::CaseInsensitiveCStringEquals(s1, s2)) { + return AssertionSuccess(); + } else { + return AssertionFailure() + << "Expected: (" << s1_expression << ") != (" + << s2_expression << ") (ignoring case), actual: \"" + << s1 << "\" vs \"" << s2 << "\""; + } +} + +} // namespace internal + +namespace { + +// Helper functions for implementing IsSubString() and IsNotSubstring(). + +// This group of overloaded functions return true iff needle is a +// substring of haystack. NULL is considered a substring of itself +// only. + +bool IsSubstringPred(const char* needle, const char* haystack) { + if (needle == NULL || haystack == NULL) + return needle == haystack; + + return strstr(haystack, needle) != NULL; +} + +bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { + if (needle == NULL || haystack == NULL) + return needle == haystack; + + return wcsstr(haystack, needle) != NULL; +} + +// StringType here can be either ::std::string or ::std::wstring. +template +bool IsSubstringPred(const StringType& needle, + const StringType& haystack) { + return haystack.find(needle) != StringType::npos; +} + +// This function implements either IsSubstring() or IsNotSubstring(), +// depending on the value of the expected_to_be_substring parameter. +// StringType here can be const char*, const wchar_t*, ::std::string, +// or ::std::wstring. +template +AssertionResult IsSubstringImpl( + bool expected_to_be_substring, + const char* needle_expr, const char* haystack_expr, + const StringType& needle, const StringType& haystack) { + if (IsSubstringPred(needle, haystack) == expected_to_be_substring) + return AssertionSuccess(); + + const bool is_wide_string = sizeof(needle[0]) > 1; + const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; + return AssertionFailure() + << "Value of: " << needle_expr << "\n" + << " Actual: " << begin_string_quote << needle << "\"\n" + << "Expected: " << (expected_to_be_substring ? "" : "not ") + << "a substring of " << haystack_expr << "\n" + << "Which is: " << begin_string_quote << haystack << "\""; +} + +} // namespace + +// IsSubstring() and IsNotSubstring() check whether needle is a +// substring of haystack (NULL is considered a substring of itself +// only), and return an appropriate error message when they fail. + +AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const char* needle, const char* haystack) { + return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const wchar_t* needle, const wchar_t* haystack) { + return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const char* needle, const char* haystack) { + return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const wchar_t* needle, const wchar_t* haystack) { + return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, const ::std::string& haystack) { + return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, const ::std::string& haystack) { + return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); +} + +#if GTEST_HAS_STD_WSTRING +AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, const ::std::wstring& haystack) { + return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, const ::std::wstring& haystack) { + return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); +} +#endif // GTEST_HAS_STD_WSTRING + +namespace internal { + +#if GTEST_OS_WINDOWS + +namespace { + +// Helper function for IsHRESULT{SuccessFailure} predicates +AssertionResult HRESULTFailureHelper(const char* expr, + const char* expected, + long hr) { // NOLINT +# if GTEST_OS_WINDOWS_MOBILE + + // Windows CE doesn't support FormatMessage. + const char error_text[] = ""; + +# else + + // Looks up the human-readable system message for the HRESULT code + // and since we're not passing any params to FormatMessage, we don't + // want inserts expanded. + const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS; + const DWORD kBufSize = 4096; + // Gets the system's human readable message string for this HRESULT. + char error_text[kBufSize] = { '\0' }; + DWORD message_length = ::FormatMessageA(kFlags, + 0, // no source, we're asking system + hr, // the error + 0, // no line width restrictions + error_text, // output buffer + kBufSize, // buf size + NULL); // no arguments for inserts + // Trims tailing white space (FormatMessage leaves a trailing CR-LF) + for (; message_length && IsSpace(error_text[message_length - 1]); + --message_length) { + error_text[message_length - 1] = '\0'; + } + +# endif // GTEST_OS_WINDOWS_MOBILE + + const std::string error_hex("0x" + String::FormatHexInt(hr)); + return ::testing::AssertionFailure() + << "Expected: " << expr << " " << expected << ".\n" + << " Actual: " << error_hex << " " << error_text << "\n"; +} + +} // namespace + +AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT + if (SUCCEEDED(hr)) { + return AssertionSuccess(); + } + return HRESULTFailureHelper(expr, "succeeds", hr); +} + +AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT + if (FAILED(hr)) { + return AssertionSuccess(); + } + return HRESULTFailureHelper(expr, "fails", hr); +} + +#endif // GTEST_OS_WINDOWS + +// Utility functions for encoding Unicode text (wide strings) in +// UTF-8. + +// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8 +// like this: +// +// Code-point length Encoding +// 0 - 7 bits 0xxxxxxx +// 8 - 11 bits 110xxxxx 10xxxxxx +// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx +// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + +// The maximum code-point a one-byte UTF-8 sequence can represent. +const UInt32 kMaxCodePoint1 = (static_cast(1) << 7) - 1; + +// The maximum code-point a two-byte UTF-8 sequence can represent. +const UInt32 kMaxCodePoint2 = (static_cast(1) << (5 + 6)) - 1; + +// The maximum code-point a three-byte UTF-8 sequence can represent. +const UInt32 kMaxCodePoint3 = (static_cast(1) << (4 + 2*6)) - 1; + +// The maximum code-point a four-byte UTF-8 sequence can represent. +const UInt32 kMaxCodePoint4 = (static_cast(1) << (3 + 3*6)) - 1; + +// Chops off the n lowest bits from a bit pattern. Returns the n +// lowest bits. As a side effect, the original bit pattern will be +// shifted to the right by n bits. +inline UInt32 ChopLowBits(UInt32* bits, int n) { + const UInt32 low_bits = *bits & ((static_cast(1) << n) - 1); + *bits >>= n; + return low_bits; +} + +// Converts a Unicode code point to a narrow string in UTF-8 encoding. +// code_point parameter is of type UInt32 because wchar_t may not be +// wide enough to contain a code point. +// If the code_point is not a valid Unicode code point +// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted +// to "(Invalid Unicode 0xXXXXXXXX)". +std::string CodePointToUtf8(UInt32 code_point) { + if (code_point > kMaxCodePoint4) { + return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")"; + } + + char str[5]; // Big enough for the largest valid code point. + if (code_point <= kMaxCodePoint1) { + str[1] = '\0'; + str[0] = static_cast(code_point); // 0xxxxxxx + } else if (code_point <= kMaxCodePoint2) { + str[2] = '\0'; + str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[0] = static_cast(0xC0 | code_point); // 110xxxxx + } else if (code_point <= kMaxCodePoint3) { + str[3] = '\0'; + str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[0] = static_cast(0xE0 | code_point); // 1110xxxx + } else { // code_point <= kMaxCodePoint4 + str[4] = '\0'; + str[3] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[0] = static_cast(0xF0 | code_point); // 11110xxx + } + return str; +} + +// The following two functions only make sense if the the system +// uses UTF-16 for wide string encoding. All supported systems +// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16. + +// Determines if the arguments constitute UTF-16 surrogate pair +// and thus should be combined into a single Unicode code point +// using CreateCodePointFromUtf16SurrogatePair. +inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { + return sizeof(wchar_t) == 2 && + (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; +} + +// Creates a Unicode code point from UTF16 surrogate pair. +inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, + wchar_t second) { + const UInt32 mask = (1 << 10) - 1; + return (sizeof(wchar_t) == 2) ? + (((first & mask) << 10) | (second & mask)) + 0x10000 : + // This function should not be called when the condition is + // false, but we provide a sensible default in case it is. + static_cast(first); +} + +// Converts a wide string to a narrow string in UTF-8 encoding. +// The wide string is assumed to have the following encoding: +// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) +// UTF-32 if sizeof(wchar_t) == 4 (on Linux) +// Parameter str points to a null-terminated wide string. +// Parameter num_chars may additionally limit the number +// of wchar_t characters processed. -1 is used when the entire string +// should be processed. +// If the string contains code points that are not valid Unicode code points +// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output +// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding +// and contains invalid UTF-16 surrogate pairs, values in those pairs +// will be encoded as individual Unicode characters from Basic Normal Plane. +std::string WideStringToUtf8(const wchar_t* str, int num_chars) { + if (num_chars == -1) + num_chars = static_cast(wcslen(str)); + + ::std::stringstream stream; + for (int i = 0; i < num_chars; ++i) { + UInt32 unicode_code_point; + + if (str[i] == L'\0') { + break; + } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { + unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], + str[i + 1]); + i++; + } else { + unicode_code_point = static_cast(str[i]); + } + + stream << CodePointToUtf8(unicode_code_point); + } + return StringStreamToString(&stream); +} + +// Converts a wide C string to an std::string using the UTF-8 encoding. +// NULL will be converted to "(null)". +std::string String::ShowWideCString(const wchar_t * wide_c_str) { + if (wide_c_str == NULL) return "(null)"; + + return internal::WideStringToUtf8(wide_c_str, -1); +} + +// Compares two wide C strings. Returns true iff they have the same +// content. +// +// Unlike wcscmp(), this function can handle NULL argument(s). A NULL +// C string is considered different to any non-NULL C string, +// including the empty string. +bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { + if (lhs == NULL) return rhs == NULL; + + if (rhs == NULL) return false; + + return wcscmp(lhs, rhs) == 0; +} + +// Helper function for *_STREQ on wide strings. +AssertionResult CmpHelperSTREQ(const char* expected_expression, + const char* actual_expression, + const wchar_t* expected, + const wchar_t* actual) { + if (String::WideCStringEquals(expected, actual)) { + return AssertionSuccess(); + } + + return EqFailure(expected_expression, + actual_expression, + PrintToString(expected), + PrintToString(actual), + false); +} + +// Helper function for *_STRNE on wide strings. +AssertionResult CmpHelperSTRNE(const char* s1_expression, + const char* s2_expression, + const wchar_t* s1, + const wchar_t* s2) { + if (!String::WideCStringEquals(s1, s2)) { + return AssertionSuccess(); + } + + return AssertionFailure() << "Expected: (" << s1_expression << ") != (" + << s2_expression << "), actual: " + << PrintToString(s1) + << " vs " << PrintToString(s2); +} + +// Compares two C strings, ignoring case. Returns true iff they have +// the same content. +// +// Unlike strcasecmp(), this function can handle NULL argument(s). A +// NULL C string is considered different to any non-NULL C string, +// including the empty string. +bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { + if (lhs == NULL) + return rhs == NULL; + if (rhs == NULL) + return false; + return posix::StrCaseCmp(lhs, rhs) == 0; +} + + // Compares two wide C strings, ignoring case. Returns true iff they + // have the same content. + // + // Unlike wcscasecmp(), this function can handle NULL argument(s). + // A NULL C string is considered different to any non-NULL wide C string, + // including the empty string. + // NB: The implementations on different platforms slightly differ. + // On windows, this method uses _wcsicmp which compares according to LC_CTYPE + // environment variable. On GNU platform this method uses wcscasecmp + // which compares according to LC_CTYPE category of the current locale. + // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the + // current locale. +bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, + const wchar_t* rhs) { + if (lhs == NULL) return rhs == NULL; + + if (rhs == NULL) return false; + +#if GTEST_OS_WINDOWS + return _wcsicmp(lhs, rhs) == 0; +#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID + return wcscasecmp(lhs, rhs) == 0; +#else + // Android, Mac OS X and Cygwin don't define wcscasecmp. + // Other unknown OSes may not define it either. + wint_t left, right; + do { + left = towlower(*lhs++); + right = towlower(*rhs++); + } while (left && left == right); + return left == right; +#endif // OS selector +} + +// Returns true iff str ends with the given suffix, ignoring case. +// Any string is considered to end with an empty suffix. +bool String::EndsWithCaseInsensitive( + const std::string& str, const std::string& suffix) { + const size_t str_len = str.length(); + const size_t suffix_len = suffix.length(); + return (str_len >= suffix_len) && + CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len, + suffix.c_str()); +} + +// Formats an int value as "%02d". +std::string String::FormatIntWidth2(int value) { + std::stringstream ss; + ss << std::setfill('0') << std::setw(2) << value; + return ss.str(); +} + +// Formats an int value as "%X". +std::string String::FormatHexInt(int value) { + std::stringstream ss; + ss << std::hex << std::uppercase << value; + return ss.str(); +} + +// Formats a byte as "%02X". +std::string String::FormatByte(unsigned char value) { + std::stringstream ss; + ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase + << static_cast(value); + return ss.str(); +} + +// Converts the buffer in a stringstream to an std::string, converting NUL +// bytes to "\\0" along the way. +std::string StringStreamToString(::std::stringstream* ss) { + const ::std::string& str = ss->str(); + const char* const start = str.c_str(); + const char* const end = start + str.length(); + + std::string result; + result.reserve(2 * (end - start)); + for (const char* ch = start; ch != end; ++ch) { + if (*ch == '\0') { + result += "\\0"; // Replaces NUL with "\\0"; + } else { + result += *ch; + } + } + + return result; +} + +// Appends the user-supplied message to the Google-Test-generated message. +std::string AppendUserMessage(const std::string& gtest_msg, + const Message& user_msg) { + // Appends the user message if it's non-empty. + const std::string user_msg_string = user_msg.GetString(); + if (user_msg_string.empty()) { + return gtest_msg; + } + + return gtest_msg + "\n" + user_msg_string; +} + +} // namespace internal + +// class TestResult + +// Creates an empty TestResult. +TestResult::TestResult() + : death_test_count_(0), + elapsed_time_(0) { +} + +// D'tor. +TestResult::~TestResult() { +} + +// Returns the i-th test part result among all the results. i can +// range from 0 to total_part_count() - 1. If i is not in that range, +// aborts the program. +const TestPartResult& TestResult::GetTestPartResult(int i) const { + if (i < 0 || i >= total_part_count()) + internal::posix::Abort(); + return test_part_results_.at(i); +} + +// Returns the i-th test property. i can range from 0 to +// test_property_count() - 1. If i is not in that range, aborts the +// program. +const TestProperty& TestResult::GetTestProperty(int i) const { + if (i < 0 || i >= test_property_count()) + internal::posix::Abort(); + return test_properties_.at(i); +} + +// Clears the test part results. +void TestResult::ClearTestPartResults() { + test_part_results_.clear(); +} + +// Adds a test part result to the list. +void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { + test_part_results_.push_back(test_part_result); +} + +// Adds a test property to the list. If a property with the same key as the +// supplied property is already represented, the value of this test_property +// replaces the old value for that key. +void TestResult::RecordProperty(const std::string& xml_element, + const TestProperty& test_property) { + if (!ValidateTestProperty(xml_element, test_property)) { + return; + } + internal::MutexLock lock(&test_properites_mutex_); + const std::vector::iterator property_with_matching_key = + std::find_if(test_properties_.begin(), test_properties_.end(), + internal::TestPropertyKeyIs(test_property.key())); + if (property_with_matching_key == test_properties_.end()) { + test_properties_.push_back(test_property); + return; + } + property_with_matching_key->SetValue(test_property.value()); +} + +// The list of reserved attributes used in the element of XML +// output. +static const char* const kReservedTestSuitesAttributes[] = { + "disabled", + "errors", + "failures", + "name", + "random_seed", + "tests", + "time", + "timestamp" +}; + +// The list of reserved attributes used in the element of XML +// output. +static const char* const kReservedTestSuiteAttributes[] = { + "disabled", + "errors", + "failures", + "name", + "tests", + "time" +}; + +// The list of reserved attributes used in the element of XML output. +static const char* const kReservedTestCaseAttributes[] = { + "classname", + "name", + "status", + "time", + "type_param", + "value_param" +}; + +template +std::vector ArrayAsVector(const char* const (&array)[kSize]) { + return std::vector(array, array + kSize); +} + +static std::vector GetReservedAttributesForElement( + const std::string& xml_element) { + if (xml_element == "testsuites") { + return ArrayAsVector(kReservedTestSuitesAttributes); + } else if (xml_element == "testsuite") { + return ArrayAsVector(kReservedTestSuiteAttributes); + } else if (xml_element == "testcase") { + return ArrayAsVector(kReservedTestCaseAttributes); + } else { + GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; + } + // This code is unreachable but some compilers may not realizes that. + return std::vector(); +} + +static std::string FormatWordList(const std::vector& words) { + Message word_list; + for (size_t i = 0; i < words.size(); ++i) { + if (i > 0 && words.size() > 2) { + word_list << ", "; + } + if (i == words.size() - 1) { + word_list << "and "; + } + word_list << "'" << words[i] << "'"; + } + return word_list.GetString(); +} + +bool ValidateTestPropertyName(const std::string& property_name, + const std::vector& reserved_names) { + if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != + reserved_names.end()) { + ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name + << " (" << FormatWordList(reserved_names) + << " are reserved by " << GTEST_NAME_ << ")"; + return false; + } + return true; +} + +// Adds a failure if the key is a reserved attribute of the element named +// xml_element. Returns true if the property is valid. +bool TestResult::ValidateTestProperty(const std::string& xml_element, + const TestProperty& test_property) { + return ValidateTestPropertyName(test_property.key(), + GetReservedAttributesForElement(xml_element)); +} + +// Clears the object. +void TestResult::Clear() { + test_part_results_.clear(); + test_properties_.clear(); + death_test_count_ = 0; + elapsed_time_ = 0; +} + +// Returns true iff the test failed. +bool TestResult::Failed() const { + for (int i = 0; i < total_part_count(); ++i) { + if (GetTestPartResult(i).failed()) + return true; + } + return false; +} + +// Returns true iff the test part fatally failed. +static bool TestPartFatallyFailed(const TestPartResult& result) { + return result.fatally_failed(); +} + +// Returns true iff the test fatally failed. +bool TestResult::HasFatalFailure() const { + return CountIf(test_part_results_, TestPartFatallyFailed) > 0; +} + +// Returns true iff the test part non-fatally failed. +static bool TestPartNonfatallyFailed(const TestPartResult& result) { + return result.nonfatally_failed(); +} + +// Returns true iff the test has a non-fatal failure. +bool TestResult::HasNonfatalFailure() const { + return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; +} + +// Gets the number of all test parts. This is the sum of the number +// of successful test parts and the number of failed test parts. +int TestResult::total_part_count() const { + return static_cast(test_part_results_.size()); +} + +// Returns the number of the test properties. +int TestResult::test_property_count() const { + return static_cast(test_properties_.size()); +} + +// class Test + +// Creates a Test object. + +// The c'tor saves the values of all Google Test flags. +Test::Test() + : gtest_flag_saver_(new internal::GTestFlagSaver) { +} + +// The d'tor restores the values of all Google Test flags. +Test::~Test() { + delete gtest_flag_saver_; +} + +// Sets up the test fixture. +// +// A sub-class may override this. +void Test::SetUp() { +} + +// Tears down the test fixture. +// +// A sub-class may override this. +void Test::TearDown() { +} + +// Allows user supplied key value pairs to be recorded for later output. +void Test::RecordProperty(const std::string& key, const std::string& value) { + UnitTest::GetInstance()->RecordProperty(key, value); +} + +// Allows user supplied key value pairs to be recorded for later output. +void Test::RecordProperty(const std::string& key, int value) { + Message value_message; + value_message << value; + RecordProperty(key, value_message.GetString().c_str()); +} + +namespace internal { + +void ReportFailureInUnknownLocation(TestPartResult::Type result_type, + const std::string& message) { + // This function is a friend of UnitTest and as such has access to + // AddTestPartResult. + UnitTest::GetInstance()->AddTestPartResult( + result_type, + NULL, // No info about the source file where the exception occurred. + -1, // We have no info on which line caused the exception. + message, + ""); // No stack trace, either. +} + +} // namespace internal + +// Google Test requires all tests in the same test case to use the same test +// fixture class. This function checks if the current test has the +// same fixture class as the first test in the current test case. If +// yes, it returns true; otherwise it generates a Google Test failure and +// returns false. +bool Test::HasSameFixtureClass() { + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + const TestCase* const test_case = impl->current_test_case(); + + // Info about the first test in the current test case. + const TestInfo* const first_test_info = test_case->test_info_list()[0]; + const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; + const char* const first_test_name = first_test_info->name(); + + // Info about the current test. + const TestInfo* const this_test_info = impl->current_test_info(); + const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_; + const char* const this_test_name = this_test_info->name(); + + if (this_fixture_id != first_fixture_id) { + // Is the first test defined using TEST? + const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); + // Is this test defined using TEST? + const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); + + if (first_is_TEST || this_is_TEST) { + // The user mixed TEST and TEST_F in this test case - we'll tell + // him/her how to fix it. + + // Gets the name of the TEST and the name of the TEST_F. Note + // that first_is_TEST and this_is_TEST cannot both be true, as + // the fixture IDs are different for the two tests. + const char* const TEST_name = + first_is_TEST ? first_test_name : this_test_name; + const char* const TEST_F_name = + first_is_TEST ? this_test_name : first_test_name; + + ADD_FAILURE() + << "All tests in the same test case must use the same test fixture\n" + << "class, so mixing TEST_F and TEST in the same test case is\n" + << "illegal. In test case " << this_test_info->test_case_name() + << ",\n" + << "test " << TEST_F_name << " is defined using TEST_F but\n" + << "test " << TEST_name << " is defined using TEST. You probably\n" + << "want to change the TEST to TEST_F or move it to another test\n" + << "case."; + } else { + // The user defined two fixture classes with the same name in + // two namespaces - we'll tell him/her how to fix it. + ADD_FAILURE() + << "All tests in the same test case must use the same test fixture\n" + << "class. However, in test case " + << this_test_info->test_case_name() << ",\n" + << "you defined test " << first_test_name + << " and test " << this_test_name << "\n" + << "using two different test fixture classes. This can happen if\n" + << "the two classes are from different namespaces or translation\n" + << "units and have the same name. You should probably rename one\n" + << "of the classes to put the tests into different test cases."; + } + return false; + } + + return true; +} + +#if GTEST_HAS_SEH + +// Adds an "exception thrown" fatal failure to the current test. This +// function returns its result via an output parameter pointer because VC++ +// prohibits creation of objects with destructors on stack in functions +// using __try (see error C2712). +static std::string* FormatSehExceptionMessage(DWORD exception_code, + const char* location) { + Message message; + message << "SEH exception with code 0x" << std::setbase(16) << + exception_code << std::setbase(10) << " thrown in " << location << "."; + + return new std::string(message.GetString()); +} + +#endif // GTEST_HAS_SEH + +namespace internal { + +#if GTEST_HAS_EXCEPTIONS + +// Adds an "exception thrown" fatal failure to the current test. +static std::string FormatCxxExceptionMessage(const char* description, + const char* location) { + Message message; + if (description != NULL) { + message << "C++ exception with description \"" << description << "\""; + } else { + message << "Unknown C++ exception"; + } + message << " thrown in " << location << "."; + + return message.GetString(); +} + +static std::string PrintTestPartResultToString( + const TestPartResult& test_part_result); + +GoogleTestFailureException::GoogleTestFailureException( + const TestPartResult& failure) + : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} + +#endif // GTEST_HAS_EXCEPTIONS + +// We put these helper functions in the internal namespace as IBM's xlC +// compiler rejects the code if they were declared static. + +// Runs the given method and handles SEH exceptions it throws, when +// SEH is supported; returns the 0-value for type Result in case of an +// SEH exception. (Microsoft compilers cannot handle SEH and C++ +// exceptions in the same function. Therefore, we provide a separate +// wrapper function for handling SEH exceptions.) +template +Result HandleSehExceptionsInMethodIfSupported( + T* object, Result (T::*method)(), const char* location) { +#if GTEST_HAS_SEH + __try { + return (object->*method)(); + } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT + GetExceptionCode())) { + // We create the exception message on the heap because VC++ prohibits + // creation of objects with destructors on stack in functions using __try + // (see error C2712). + std::string* exception_message = FormatSehExceptionMessage( + GetExceptionCode(), location); + internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, + *exception_message); + delete exception_message; + return static_cast(0); + } +#else + (void)location; + return (object->*method)(); +#endif // GTEST_HAS_SEH +} + +// Runs the given method and catches and reports C++ and/or SEH-style +// exceptions, if they are supported; returns the 0-value for type +// Result in case of an SEH exception. +template +Result HandleExceptionsInMethodIfSupported( + T* object, Result (T::*method)(), const char* location) { + // NOTE: The user code can affect the way in which Google Test handles + // exceptions by setting GTEST_FLAG(catch_exceptions), but only before + // RUN_ALL_TESTS() starts. It is technically possible to check the flag + // after the exception is caught and either report or re-throw the + // exception based on the flag's value: + // + // try { + // // Perform the test method. + // } catch (...) { + // if (GTEST_FLAG(catch_exceptions)) + // // Report the exception as failure. + // else + // throw; // Re-throws the original exception. + // } + // + // However, the purpose of this flag is to allow the program to drop into + // the debugger when the exception is thrown. On most platforms, once the + // control enters the catch block, the exception origin information is + // lost and the debugger will stop the program at the point of the + // re-throw in this function -- instead of at the point of the original + // throw statement in the code under test. For this reason, we perform + // the check early, sacrificing the ability to affect Google Test's + // exception handling in the method where the exception is thrown. + if (internal::GetUnitTestImpl()->catch_exceptions()) { +#if GTEST_HAS_EXCEPTIONS + try { + return HandleSehExceptionsInMethodIfSupported(object, method, location); + } catch (const internal::GoogleTestFailureException&) { // NOLINT + // This exception type can only be thrown by a failed Google + // Test assertion with the intention of letting another testing + // framework catch it. Therefore we just re-throw it. + throw; + } catch (const std::exception& e) { // NOLINT + internal::ReportFailureInUnknownLocation( + TestPartResult::kFatalFailure, + FormatCxxExceptionMessage(e.what(), location)); + } catch (...) { // NOLINT + internal::ReportFailureInUnknownLocation( + TestPartResult::kFatalFailure, + FormatCxxExceptionMessage(NULL, location)); + } + return static_cast(0); +#else + return HandleSehExceptionsInMethodIfSupported(object, method, location); +#endif // GTEST_HAS_EXCEPTIONS + } else { + return (object->*method)(); + } +} + +} // namespace internal + +// Runs the test and updates the test result. +void Test::Run() { + if (!HasSameFixtureClass()) return; + + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); + // We will run the test only if SetUp() was successful. + if (!HasFatalFailure()) { + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + this, &Test::TestBody, "the test body"); + } + + // However, we want to clean up as much as possible. Hence we will + // always call TearDown(), even if SetUp() or the test body has + // failed. + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + this, &Test::TearDown, "TearDown()"); +} + +// Returns true iff the current test has a fatal failure. +bool Test::HasFatalFailure() { + return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); +} + +// Returns true iff the current test has a non-fatal failure. +bool Test::HasNonfatalFailure() { + return internal::GetUnitTestImpl()->current_test_result()-> + HasNonfatalFailure(); +} + +// class TestInfo + +// Constructs a TestInfo object. It assumes ownership of the test factory +// object. +TestInfo::TestInfo(const std::string& a_test_case_name, + const std::string& a_name, + const char* a_type_param, + const char* a_value_param, + internal::TypeId fixture_class_id, + internal::TestFactoryBase* factory) + : test_case_name_(a_test_case_name), + name_(a_name), + type_param_(a_type_param ? new std::string(a_type_param) : NULL), + value_param_(a_value_param ? new std::string(a_value_param) : NULL), + fixture_class_id_(fixture_class_id), + should_run_(false), + is_disabled_(false), + matches_filter_(false), + factory_(factory), + result_() {} + +// Destructs a TestInfo object. +TestInfo::~TestInfo() { delete factory_; } + +namespace internal { + +// Creates a new TestInfo object and registers it with Google Test; +// returns the created object. +// +// Arguments: +// +// test_case_name: name of the test case +// name: name of the test +// type_param: the name of the test's type parameter, or NULL if +// this is not a typed or a type-parameterized test. +// value_param: text representation of the test's value parameter, +// or NULL if this is not a value-parameterized test. +// fixture_class_id: ID of the test fixture class +// set_up_tc: pointer to the function that sets up the test case +// tear_down_tc: pointer to the function that tears down the test case +// factory: pointer to the factory that creates a test object. +// The newly created TestInfo instance will assume +// ownership of the factory object. +TestInfo* MakeAndRegisterTestInfo( + const char* test_case_name, + const char* name, + const char* type_param, + const char* value_param, + TypeId fixture_class_id, + SetUpTestCaseFunc set_up_tc, + TearDownTestCaseFunc tear_down_tc, + TestFactoryBase* factory) { + TestInfo* const test_info = + new TestInfo(test_case_name, name, type_param, value_param, + fixture_class_id, factory); + GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); + return test_info; +} + +#if GTEST_HAS_PARAM_TEST +void ReportInvalidTestCaseType(const char* test_case_name, + const char* file, int line) { + Message errors; + errors + << "Attempted redefinition of test case " << test_case_name << ".\n" + << "All tests in the same test case must use the same test fixture\n" + << "class. However, in test case " << test_case_name << ", you tried\n" + << "to define a test using a fixture class different from the one\n" + << "used earlier. This can happen if the two fixture classes are\n" + << "from different namespaces and have the same name. You should\n" + << "probably rename one of the classes to put the tests into different\n" + << "test cases."; + + fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), + errors.GetString().c_str()); +} +#endif // GTEST_HAS_PARAM_TEST + +} // namespace internal + +namespace { + +// A predicate that checks the test name of a TestInfo against a known +// value. +// +// This is used for implementation of the TestCase class only. We put +// it in the anonymous namespace to prevent polluting the outer +// namespace. +// +// TestNameIs is copyable. +class TestNameIs { + public: + // Constructor. + // + // TestNameIs has NO default constructor. + explicit TestNameIs(const char* name) + : name_(name) {} + + // Returns true iff the test name of test_info matches name_. + bool operator()(const TestInfo * test_info) const { + return test_info && test_info->name() == name_; + } + + private: + std::string name_; +}; + +} // namespace + +namespace internal { + +// This method expands all parameterized tests registered with macros TEST_P +// and INSTANTIATE_TEST_CASE_P into regular tests and registers those. +// This will be done just once during the program runtime. +void UnitTestImpl::RegisterParameterizedTests() { +#if GTEST_HAS_PARAM_TEST + if (!parameterized_tests_registered_) { + parameterized_test_registry_.RegisterTests(); + parameterized_tests_registered_ = true; + } +#endif +} + +} // namespace internal + +// Creates the test object, runs it, records its result, and then +// deletes it. +void TestInfo::Run() { + if (!should_run_) return; + + // Tells UnitTest where to store test result. + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + impl->set_current_test_info(this); + + TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); + + // Notifies the unit test event listeners that a test is about to start. + repeater->OnTestStart(*this); + + const TimeInMillis start = internal::GetTimeInMillis(); + + impl->os_stack_trace_getter()->UponLeavingGTest(); + + // Creates the test object. + Test* const test = internal::HandleExceptionsInMethodIfSupported( + factory_, &internal::TestFactoryBase::CreateTest, + "the test fixture's constructor"); + + // Runs the test only if the test object was created and its + // constructor didn't generate a fatal failure. + if ((test != NULL) && !Test::HasFatalFailure()) { + // This doesn't throw as all user code that can throw are wrapped into + // exception handling code. + test->Run(); + } + + // Deletes the test object. + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + test, &Test::DeleteSelf_, "the test fixture's destructor"); + + result_.set_elapsed_time(internal::GetTimeInMillis() - start); + + // Notifies the unit test event listener that a test has just finished. + repeater->OnTestEnd(*this); + + // Tells UnitTest to stop associating assertion results to this + // test. + impl->set_current_test_info(NULL); +} + +// class TestCase + +// Gets the number of successful tests in this test case. +int TestCase::successful_test_count() const { + return CountIf(test_info_list_, TestPassed); +} + +// Gets the number of failed tests in this test case. +int TestCase::failed_test_count() const { + return CountIf(test_info_list_, TestFailed); +} + +// Gets the number of disabled tests that will be reported in the XML report. +int TestCase::reportable_disabled_test_count() const { + return CountIf(test_info_list_, TestReportableDisabled); +} + +// Gets the number of disabled tests in this test case. +int TestCase::disabled_test_count() const { + return CountIf(test_info_list_, TestDisabled); +} + +// Gets the number of tests to be printed in the XML report. +int TestCase::reportable_test_count() const { + return CountIf(test_info_list_, TestReportable); +} + +// Get the number of tests in this test case that should run. +int TestCase::test_to_run_count() const { + return CountIf(test_info_list_, ShouldRunTest); +} + +// Gets the number of all tests. +int TestCase::total_test_count() const { + return static_cast(test_info_list_.size()); +} + +// Creates a TestCase with the given name. +// +// Arguments: +// +// name: name of the test case +// a_type_param: the name of the test case's type parameter, or NULL if +// this is not a typed or a type-parameterized test case. +// set_up_tc: pointer to the function that sets up the test case +// tear_down_tc: pointer to the function that tears down the test case +TestCase::TestCase(const char* a_name, const char* a_type_param, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc) + : name_(a_name), + type_param_(a_type_param ? new std::string(a_type_param) : NULL), + set_up_tc_(set_up_tc), + tear_down_tc_(tear_down_tc), + should_run_(false), + elapsed_time_(0) { +} + +// Destructor of TestCase. +TestCase::~TestCase() { + // Deletes every Test in the collection. + ForEach(test_info_list_, internal::Delete); +} + +// Returns the i-th test among all the tests. i can range from 0 to +// total_test_count() - 1. If i is not in that range, returns NULL. +const TestInfo* TestCase::GetTestInfo(int i) const { + const int index = GetElementOr(test_indices_, i, -1); + return index < 0 ? NULL : test_info_list_[index]; +} + +// Returns the i-th test among all the tests. i can range from 0 to +// total_test_count() - 1. If i is not in that range, returns NULL. +TestInfo* TestCase::GetMutableTestInfo(int i) { + const int index = GetElementOr(test_indices_, i, -1); + return index < 0 ? NULL : test_info_list_[index]; +} + +// Adds a test to this test case. Will delete the test upon +// destruction of the TestCase object. +void TestCase::AddTestInfo(TestInfo * test_info) { + test_info_list_.push_back(test_info); + test_indices_.push_back(static_cast(test_indices_.size())); +} + +// Runs every test in this TestCase. +void TestCase::Run() { + if (!should_run_) return; + + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + impl->set_current_test_case(this); + + TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); + + repeater->OnTestCaseStart(*this); + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + this, &TestCase::RunSetUpTestCase, "SetUpTestCase()"); + + const internal::TimeInMillis start = internal::GetTimeInMillis(); + for (int i = 0; i < total_test_count(); i++) { + GetMutableTestInfo(i)->Run(); + } + elapsed_time_ = internal::GetTimeInMillis() - start; + + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + this, &TestCase::RunTearDownTestCase, "TearDownTestCase()"); + + repeater->OnTestCaseEnd(*this); + impl->set_current_test_case(NULL); +} + +// Clears the results of all tests in this test case. +void TestCase::ClearResult() { + ad_hoc_test_result_.Clear(); + ForEach(test_info_list_, TestInfo::ClearTestResult); +} + +// Shuffles the tests in this test case. +void TestCase::ShuffleTests(internal::Random* random) { + Shuffle(random, &test_indices_); +} + +// Restores the test order to before the first shuffle. +void TestCase::UnshuffleTests() { + for (size_t i = 0; i < test_indices_.size(); i++) { + test_indices_[i] = static_cast(i); + } +} + +// Formats a countable noun. Depending on its quantity, either the +// singular form or the plural form is used. e.g. +// +// FormatCountableNoun(1, "formula", "formuli") returns "1 formula". +// FormatCountableNoun(5, "book", "books") returns "5 books". +static std::string FormatCountableNoun(int count, + const char * singular_form, + const char * plural_form) { + return internal::StreamableToString(count) + " " + + (count == 1 ? singular_form : plural_form); +} + +// Formats the count of tests. +static std::string FormatTestCount(int test_count) { + return FormatCountableNoun(test_count, "test", "tests"); +} + +// Formats the count of test cases. +static std::string FormatTestCaseCount(int test_case_count) { + return FormatCountableNoun(test_case_count, "test case", "test cases"); +} + +// Converts a TestPartResult::Type enum to human-friendly string +// representation. Both kNonFatalFailure and kFatalFailure are translated +// to "Failure", as the user usually doesn't care about the difference +// between the two when viewing the test result. +static const char * TestPartResultTypeToString(TestPartResult::Type type) { + switch (type) { + case TestPartResult::kSuccess: + return "Success"; + + case TestPartResult::kNonFatalFailure: + case TestPartResult::kFatalFailure: +#ifdef _MSC_VER + return "error: "; +#else + return "Failure\n"; +#endif + default: + return "Unknown result type"; + } +} + +namespace internal { + +// Prints a TestPartResult to an std::string. +static std::string PrintTestPartResultToString( + const TestPartResult& test_part_result) { + return (Message() + << internal::FormatFileLocation(test_part_result.file_name(), + test_part_result.line_number()) + << " " << TestPartResultTypeToString(test_part_result.type()) + << test_part_result.message()).GetString(); +} + +// Prints a TestPartResult. +static void PrintTestPartResult(const TestPartResult& test_part_result) { + const std::string& result = + PrintTestPartResultToString(test_part_result); + printf("%s\n", result.c_str()); + fflush(stdout); + // If the test program runs in Visual Studio or a debugger, the + // following statements add the test part result message to the Output + // window such that the user can double-click on it to jump to the + // corresponding source code location; otherwise they do nothing. +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE + // We don't call OutputDebugString*() on Windows Mobile, as printing + // to stdout is done by OutputDebugString() there already - we don't + // want the same message printed twice. + ::OutputDebugStringA(result.c_str()); + ::OutputDebugStringA("\n"); +#endif +} + +// class PrettyUnitTestResultPrinter + +enum GTestColor { + COLOR_DEFAULT, + COLOR_RED, + COLOR_GREEN, + COLOR_YELLOW +}; + +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE + +// Returns the character attribute for the given color. +WORD GetColorAttribute(GTestColor color) { + switch (color) { + case COLOR_RED: return FOREGROUND_RED; + case COLOR_GREEN: return FOREGROUND_GREEN; + case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; + default: return 0; + } +} + +#else + +// Returns the ANSI color code for the given color. COLOR_DEFAULT is +// an invalid input. +const char* GetAnsiColorCode(GTestColor color) { + switch (color) { + case COLOR_RED: return "1"; + case COLOR_GREEN: return "2"; + case COLOR_YELLOW: return "3"; + default: return NULL; + }; +} + +#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE + +// Returns true iff Google Test should use colors in the output. +bool ShouldUseColor(bool stdout_is_tty) { + const char* const gtest_color = GTEST_FLAG(color).c_str(); + + if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { +#if GTEST_OS_WINDOWS + // On Windows the TERM variable is usually not set, but the + // console there does support colors. + return stdout_is_tty; +#else + // On non-Windows platforms, we rely on the TERM variable. + const char* const term = posix::GetEnv("TERM"); + const bool term_supports_color = + String::CStringEquals(term, "xterm") || + String::CStringEquals(term, "xterm-color") || + String::CStringEquals(term, "xterm-256color") || + String::CStringEquals(term, "screen") || + String::CStringEquals(term, "screen-256color") || + String::CStringEquals(term, "linux") || + String::CStringEquals(term, "cygwin"); + return stdout_is_tty && term_supports_color; +#endif // GTEST_OS_WINDOWS + } + + return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || + String::CaseInsensitiveCStringEquals(gtest_color, "true") || + String::CaseInsensitiveCStringEquals(gtest_color, "t") || + String::CStringEquals(gtest_color, "1"); + // We take "yes", "true", "t", and "1" as meaning "yes". If the + // value is neither one of these nor "auto", we treat it as "no" to + // be conservative. +} + +// Helpers for printing colored strings to stdout. Note that on Windows, we +// cannot simply emit special characters and have the terminal change colors. +// This routine must actually emit the characters rather than return a string +// that would be colored when printed, as can be done on Linux. +void ColoredPrintf(GTestColor color, const char* fmt, ...) { + va_list args; + va_start(args, fmt); + +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS + const bool use_color = false; +#else + static const bool in_color_mode = + ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); + const bool use_color = in_color_mode && (color != COLOR_DEFAULT); +#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS + // The '!= 0' comparison is necessary to satisfy MSVC 7.1. + + if (!use_color) { + vprintf(fmt, args); + va_end(args); + return; + } + +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE + const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); + + // Gets the current text color. + CONSOLE_SCREEN_BUFFER_INFO buffer_info; + GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); + const WORD old_color_attrs = buffer_info.wAttributes; + + // We need to flush the stream buffers into the console before each + // SetConsoleTextAttribute call lest it affect the text that is already + // printed but has not yet reached the console. + fflush(stdout); + SetConsoleTextAttribute(stdout_handle, + GetColorAttribute(color) | FOREGROUND_INTENSITY); + vprintf(fmt, args); + + fflush(stdout); + // Restores the text color. + SetConsoleTextAttribute(stdout_handle, old_color_attrs); +#else + printf("\033[0;3%sm", GetAnsiColorCode(color)); + vprintf(fmt, args); + printf("\033[m"); // Resets the terminal to default. +#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE + va_end(args); +} + +// Text printed in Google Test's text output and --gunit_list_tests +// output to label the type parameter and value parameter for a test. +static const char kTypeParamLabel[] = "TypeParam"; +static const char kValueParamLabel[] = "GetParam()"; + +void PrintFullTestCommentIfPresent(const TestInfo& test_info) { + const char* const type_param = test_info.type_param(); + const char* const value_param = test_info.value_param(); + + if (type_param != NULL || value_param != NULL) { + printf(", where "); + if (type_param != NULL) { + printf("%s = %s", kTypeParamLabel, type_param); + if (value_param != NULL) + printf(" and "); + } + if (value_param != NULL) { + printf("%s = %s", kValueParamLabel, value_param); + } + } +} + +// This class implements the TestEventListener interface. +// +// Class PrettyUnitTestResultPrinter is copyable. +class PrettyUnitTestResultPrinter : public TestEventListener { + public: + PrettyUnitTestResultPrinter() {} + static void PrintTestName(const char * test_case, const char * test) { + printf("%s.%s", test_case, test); + } + + // The following methods override what's in the TestEventListener class. + virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); + virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); + virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestCaseStart(const TestCase& test_case); + virtual void OnTestStart(const TestInfo& test_info); + virtual void OnTestPartResult(const TestPartResult& result); + virtual void OnTestEnd(const TestInfo& test_info); + virtual void OnTestCaseEnd(const TestCase& test_case); + virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); + virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); + virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} + + private: + static void PrintFailedTests(const UnitTest& unit_test); +}; + + // Fired before each iteration of tests starts. +void PrettyUnitTestResultPrinter::OnTestIterationStart( + const UnitTest& unit_test, int iteration) { + if (GTEST_FLAG(repeat) != 1) + printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); + + const char* const filter = GTEST_FLAG(filter).c_str(); + + // Prints the filter if it's not *. This reminds the user that some + // tests may be skipped. + if (!String::CStringEquals(filter, kUniversalFilter)) { + ColoredPrintf(COLOR_YELLOW, + "Note: %s filter = %s\n", GTEST_NAME_, filter); + } + + if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { + const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); + ColoredPrintf(COLOR_YELLOW, + "Note: This is test shard %d of %s.\n", + static_cast(shard_index) + 1, + internal::posix::GetEnv(kTestTotalShards)); + } + + if (GTEST_FLAG(shuffle)) { + ColoredPrintf(COLOR_YELLOW, + "Note: Randomizing tests' orders with a seed of %d .\n", + unit_test.random_seed()); + } + + ColoredPrintf(COLOR_GREEN, "[==========] "); + printf("Running %s from %s.\n", + FormatTestCount(unit_test.test_to_run_count()).c_str(), + FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( + const UnitTest& /*unit_test*/) { + ColoredPrintf(COLOR_GREEN, "[----------] "); + printf("Global test environment set-up.\n"); + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { + const std::string counts = + FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); + ColoredPrintf(COLOR_GREEN, "[----------] "); + printf("%s from %s", counts.c_str(), test_case.name()); + if (test_case.type_param() == NULL) { + printf("\n"); + } else { + printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param()); + } + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { + ColoredPrintf(COLOR_GREEN, "[ RUN ] "); + PrintTestName(test_info.test_case_name(), test_info.name()); + printf("\n"); + fflush(stdout); +} + +// Called after an assertion failure. +void PrettyUnitTestResultPrinter::OnTestPartResult( + const TestPartResult& result) { + // If the test part succeeded, we don't need to do anything. + if (result.type() == TestPartResult::kSuccess) + return; + + // Print failure message from the assertion (e.g. expected this and got that). + PrintTestPartResult(result); + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { + if (test_info.result()->Passed()) { + ColoredPrintf(COLOR_GREEN, "[ OK ] "); + } else { + ColoredPrintf(COLOR_RED, "[ FAILED ] "); + } + PrintTestName(test_info.test_case_name(), test_info.name()); + if (test_info.result()->Failed()) + PrintFullTestCommentIfPresent(test_info); + + if (GTEST_FLAG(print_time)) { + printf(" (%s ms)\n", internal::StreamableToString( + test_info.result()->elapsed_time()).c_str()); + } else { + printf("\n"); + } + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { + if (!GTEST_FLAG(print_time)) return; + + const std::string counts = + FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); + ColoredPrintf(COLOR_GREEN, "[----------] "); + printf("%s from %s (%s ms total)\n\n", + counts.c_str(), test_case.name(), + internal::StreamableToString(test_case.elapsed_time()).c_str()); + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( + const UnitTest& /*unit_test*/) { + ColoredPrintf(COLOR_GREEN, "[----------] "); + printf("Global test environment tear-down\n"); + fflush(stdout); +} + +// Internal helper for printing the list of failed tests. +void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { + const int failed_test_count = unit_test.failed_test_count(); + if (failed_test_count == 0) { + return; + } + + for (int i = 0; i < unit_test.total_test_case_count(); ++i) { + const TestCase& test_case = *unit_test.GetTestCase(i); + if (!test_case.should_run() || (test_case.failed_test_count() == 0)) { + continue; + } + for (int j = 0; j < test_case.total_test_count(); ++j) { + const TestInfo& test_info = *test_case.GetTestInfo(j); + if (!test_info.should_run() || test_info.result()->Passed()) { + continue; + } + ColoredPrintf(COLOR_RED, "[ FAILED ] "); + printf("%s.%s", test_case.name(), test_info.name()); + PrintFullTestCommentIfPresent(test_info); + printf("\n"); + } + } +} + +void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, + int /*iteration*/) { + ColoredPrintf(COLOR_GREEN, "[==========] "); + printf("%s from %s ran.", + FormatTestCount(unit_test.test_to_run_count()).c_str(), + FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); + if (GTEST_FLAG(print_time)) { + printf(" (%s ms total)", + internal::StreamableToString(unit_test.elapsed_time()).c_str()); + } + printf("\n"); + ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); + printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); + + int num_failures = unit_test.failed_test_count(); + if (!unit_test.Passed()) { + const int failed_test_count = unit_test.failed_test_count(); + ColoredPrintf(COLOR_RED, "[ FAILED ] "); + printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); + PrintFailedTests(unit_test); + printf("\n%2d FAILED %s\n", num_failures, + num_failures == 1 ? "TEST" : "TESTS"); + } + + int num_disabled = unit_test.reportable_disabled_test_count(); + if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { + if (!num_failures) { + printf("\n"); // Add a spacer if no FAILURE banner is displayed. + } + ColoredPrintf(COLOR_YELLOW, + " YOU HAVE %d DISABLED %s\n\n", + num_disabled, + num_disabled == 1 ? "TEST" : "TESTS"); + } + // Ensure that Google Test output is printed before, e.g., heapchecker output. + fflush(stdout); +} + +// End PrettyUnitTestResultPrinter + +// class TestEventRepeater +// +// This class forwards events to other event listeners. +class TestEventRepeater : public TestEventListener { + public: + TestEventRepeater() : forwarding_enabled_(true) {} + virtual ~TestEventRepeater(); + void Append(TestEventListener *listener); + TestEventListener* Release(TestEventListener* listener); + + // Controls whether events will be forwarded to listeners_. Set to false + // in death test child processes. + bool forwarding_enabled() const { return forwarding_enabled_; } + void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } + + virtual void OnTestProgramStart(const UnitTest& unit_test); + virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); + virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); + virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test); + virtual void OnTestCaseStart(const TestCase& test_case); + virtual void OnTestStart(const TestInfo& test_info); + virtual void OnTestPartResult(const TestPartResult& result); + virtual void OnTestEnd(const TestInfo& test_info); + virtual void OnTestCaseEnd(const TestCase& test_case); + virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); + virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test); + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); + virtual void OnTestProgramEnd(const UnitTest& unit_test); + + private: + // Controls whether events will be forwarded to listeners_. Set to false + // in death test child processes. + bool forwarding_enabled_; + // The list of listeners that receive events. + std::vector listeners_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); +}; + +TestEventRepeater::~TestEventRepeater() { + ForEach(listeners_, Delete); +} + +void TestEventRepeater::Append(TestEventListener *listener) { + listeners_.push_back(listener); +} + +// TODO(vladl@google.com): Factor the search functionality into Vector::Find. +TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { + for (size_t i = 0; i < listeners_.size(); ++i) { + if (listeners_[i] == listener) { + listeners_.erase(listeners_.begin() + i); + return listener; + } + } + + return NULL; +} + +// Since most methods are very similar, use macros to reduce boilerplate. +// This defines a member that forwards the call to all listeners. +#define GTEST_REPEATER_METHOD_(Name, Type) \ +void TestEventRepeater::Name(const Type& parameter) { \ + if (forwarding_enabled_) { \ + for (size_t i = 0; i < listeners_.size(); i++) { \ + listeners_[i]->Name(parameter); \ + } \ + } \ +} +// This defines a member that forwards the call to all listeners in reverse +// order. +#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ +void TestEventRepeater::Name(const Type& parameter) { \ + if (forwarding_enabled_) { \ + for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { \ + listeners_[i]->Name(parameter); \ + } \ + } \ +} + +GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) +GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) +GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase) +GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) +GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) +GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) +GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) +GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) +GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) +GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase) +GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) + +#undef GTEST_REPEATER_METHOD_ +#undef GTEST_REVERSE_REPEATER_METHOD_ + +void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, + int iteration) { + if (forwarding_enabled_) { + for (size_t i = 0; i < listeners_.size(); i++) { + listeners_[i]->OnTestIterationStart(unit_test, iteration); + } + } +} + +void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, + int iteration) { + if (forwarding_enabled_) { + for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { + listeners_[i]->OnTestIterationEnd(unit_test, iteration); + } + } +} + +// End TestEventRepeater + +// This class generates an XML output file. +class XmlUnitTestResultPrinter : public EmptyTestEventListener { + public: + explicit XmlUnitTestResultPrinter(const char* output_file); + + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); + + private: + // Is c a whitespace character that is normalized to a space character + // when it appears in an XML attribute value? + static bool IsNormalizableWhitespace(char c) { + return c == 0x9 || c == 0xA || c == 0xD; + } + + // May c appear in a well-formed XML document? + static bool IsValidXmlCharacter(char c) { + return IsNormalizableWhitespace(c) || c >= 0x20; + } + + // Returns an XML-escaped copy of the input string str. If + // is_attribute is true, the text is meant to appear as an attribute + // value, and normalizable whitespace is preserved by replacing it + // with character references. + static std::string EscapeXml(const std::string& str, bool is_attribute); + + // Returns the given string with all characters invalid in XML removed. + static std::string RemoveInvalidXmlCharacters(const std::string& str); + + // Convenience wrapper around EscapeXml when str is an attribute value. + static std::string EscapeXmlAttribute(const std::string& str) { + return EscapeXml(str, true); + } + + // Convenience wrapper around EscapeXml when str is not an attribute value. + static std::string EscapeXmlText(const char* str) { + return EscapeXml(str, false); + } + + // Verifies that the given attribute belongs to the given element and + // streams the attribute as XML. + static void OutputXmlAttribute(std::ostream* stream, + const std::string& element_name, + const std::string& name, + const std::string& value); + + // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. + static void OutputXmlCDataSection(::std::ostream* stream, const char* data); + + // Streams an XML representation of a TestInfo object. + static void OutputXmlTestInfo(::std::ostream* stream, + const char* test_case_name, + const TestInfo& test_info); + + // Prints an XML representation of a TestCase object + static void PrintXmlTestCase(::std::ostream* stream, + const TestCase& test_case); + + // Prints an XML summary of unit_test to output stream out. + static void PrintXmlUnitTest(::std::ostream* stream, + const UnitTest& unit_test); + + // Produces a string representing the test properties in a result as space + // delimited XML attributes based on the property key="value" pairs. + // When the std::string is not empty, it includes a space at the beginning, + // to delimit this attribute from prior attributes. + static std::string TestPropertiesAsXmlAttributes(const TestResult& result); + + // The output file. + const std::string output_file_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); +}; + +// Creates a new XmlUnitTestResultPrinter. +XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) + : output_file_(output_file) { + if (output_file_.c_str() == NULL || output_file_.empty()) { + fprintf(stderr, "XML output file may not be null\n"); + fflush(stderr); + exit(EXIT_FAILURE); + } +} + +// Called after the unit test ends. +void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, + int /*iteration*/) { + FILE* xmlout = NULL; + FilePath output_file(output_file_); + FilePath output_dir(output_file.RemoveFileName()); + + if (output_dir.CreateDirectoriesRecursively()) { + xmlout = posix::FOpen(output_file_.c_str(), "w"); + } + if (xmlout == NULL) { + // TODO(wan): report the reason of the failure. + // + // We don't do it for now as: + // + // 1. There is no urgent need for it. + // 2. It's a bit involved to make the errno variable thread-safe on + // all three operating systems (Linux, Windows, and Mac OS). + // 3. To interpret the meaning of errno in a thread-safe way, + // we need the strerror_r() function, which is not available on + // Windows. + fprintf(stderr, + "Unable to open file \"%s\"\n", + output_file_.c_str()); + fflush(stderr); + exit(EXIT_FAILURE); + } + std::stringstream stream; + PrintXmlUnitTest(&stream, unit_test); + fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); + fclose(xmlout); +} + +// Returns an XML-escaped copy of the input string str. If is_attribute +// is true, the text is meant to appear as an attribute value, and +// normalizable whitespace is preserved by replacing it with character +// references. +// +// Invalid XML characters in str, if any, are stripped from the output. +// It is expected that most, if not all, of the text processed by this +// module will consist of ordinary English text. +// If this module is ever modified to produce version 1.1 XML output, +// most invalid characters can be retained using character references. +// TODO(wan): It might be nice to have a minimally invasive, human-readable +// escaping scheme for invalid characters, rather than dropping them. +std::string XmlUnitTestResultPrinter::EscapeXml( + const std::string& str, bool is_attribute) { + Message m; + + for (size_t i = 0; i < str.size(); ++i) { + const char ch = str[i]; + switch (ch) { + case '<': + m << "<"; + break; + case '>': + m << ">"; + break; + case '&': + m << "&"; + break; + case '\'': + if (is_attribute) + m << "'"; + else + m << '\''; + break; + case '"': + if (is_attribute) + m << """; + else + m << '"'; + break; + default: + if (IsValidXmlCharacter(ch)) { + if (is_attribute && IsNormalizableWhitespace(ch)) + m << "&#x" << String::FormatByte(static_cast(ch)) + << ";"; + else + m << ch; + } + break; + } + } + + return m.GetString(); +} + +// Returns the given string with all characters invalid in XML removed. +// Currently invalid characters are dropped from the string. An +// alternative is to replace them with certain characters such as . or ?. +std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( + const std::string& str) { + std::string output; + output.reserve(str.size()); + for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) + if (IsValidXmlCharacter(*it)) + output.push_back(*it); + + return output; +} + +// The following routines generate an XML representation of a UnitTest +// object. +// +// This is how Google Test concepts map to the DTD: +// +// <-- corresponds to a UnitTest object +// <-- corresponds to a TestCase object +// <-- corresponds to a TestInfo object +// ... +// ... +// ... +// <-- individual assertion failures +// +// +// + +// Formats the given time in milliseconds as seconds. +std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { + ::std::stringstream ss; + ss << ms/1000.0; + return ss.str(); +} + +// Converts the given epoch time in milliseconds to a date string in the ISO +// 8601 format, without the timezone information. +std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { + // Using non-reentrant version as localtime_r is not portable. + time_t seconds = static_cast(ms / 1000); +#ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4996) // Temporarily disables warning 4996 + // (function or variable may be unsafe). + const struct tm* const time_struct = localtime(&seconds); // NOLINT +# pragma warning(pop) // Restores the warning state again. +#else + const struct tm* const time_struct = localtime(&seconds); // NOLINT +#endif + if (time_struct == NULL) + return ""; // Invalid ms value + + // YYYY-MM-DDThh:mm:ss + return StreamableToString(time_struct->tm_year + 1900) + "-" + + String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" + + String::FormatIntWidth2(time_struct->tm_mday) + "T" + + String::FormatIntWidth2(time_struct->tm_hour) + ":" + + String::FormatIntWidth2(time_struct->tm_min) + ":" + + String::FormatIntWidth2(time_struct->tm_sec); +} + +// Streams an XML CDATA section, escaping invalid CDATA sequences as needed. +void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, + const char* data) { + const char* segment = data; + *stream << ""); + if (next_segment != NULL) { + stream->write( + segment, static_cast(next_segment - segment)); + *stream << "]]>]]>"); + } else { + *stream << segment; + break; + } + } + *stream << "]]>"; +} + +void XmlUnitTestResultPrinter::OutputXmlAttribute( + std::ostream* stream, + const std::string& element_name, + const std::string& name, + const std::string& value) { + const std::vector& allowed_names = + GetReservedAttributesForElement(element_name); + + GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != + allowed_names.end()) + << "Attribute " << name << " is not allowed for element <" << element_name + << ">."; + + *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\""; +} + +// Prints an XML representation of a TestInfo object. +// TODO(wan): There is also value in printing properties with the plain printer. +void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, + const char* test_case_name, + const TestInfo& test_info) { + const TestResult& result = *test_info.result(); + const std::string kTestcase = "testcase"; + + *stream << " \n"; + } + const string location = internal::FormatCompilerIndependentFileLocation( + part.file_name(), part.line_number()); + const string summary = location + "\n" + part.summary(); + *stream << " "; + const string detail = location + "\n" + part.message(); + OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); + *stream << "\n"; + } + } + + if (failures == 0) + *stream << " />\n"; + else + *stream << " \n"; +} + +// Prints an XML representation of a TestCase object +void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream, + const TestCase& test_case) { + const std::string kTestsuite = "testsuite"; + *stream << " <" << kTestsuite; + OutputXmlAttribute(stream, kTestsuite, "name", test_case.name()); + OutputXmlAttribute(stream, kTestsuite, "tests", + StreamableToString(test_case.reportable_test_count())); + OutputXmlAttribute(stream, kTestsuite, "failures", + StreamableToString(test_case.failed_test_count())); + OutputXmlAttribute( + stream, kTestsuite, "disabled", + StreamableToString(test_case.reportable_disabled_test_count())); + OutputXmlAttribute(stream, kTestsuite, "errors", "0"); + OutputXmlAttribute(stream, kTestsuite, "time", + FormatTimeInMillisAsSeconds(test_case.elapsed_time())); + *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result()) + << ">\n"; + + for (int i = 0; i < test_case.total_test_count(); ++i) { + if (test_case.GetTestInfo(i)->is_reportable()) + OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i)); + } + *stream << " \n"; +} + +// Prints an XML summary of unit_test to output stream out. +void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, + const UnitTest& unit_test) { + const std::string kTestsuites = "testsuites"; + + *stream << "\n"; + *stream << "<" << kTestsuites; + + OutputXmlAttribute(stream, kTestsuites, "tests", + StreamableToString(unit_test.reportable_test_count())); + OutputXmlAttribute(stream, kTestsuites, "failures", + StreamableToString(unit_test.failed_test_count())); + OutputXmlAttribute( + stream, kTestsuites, "disabled", + StreamableToString(unit_test.reportable_disabled_test_count())); + OutputXmlAttribute(stream, kTestsuites, "errors", "0"); + OutputXmlAttribute( + stream, kTestsuites, "timestamp", + FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp())); + OutputXmlAttribute(stream, kTestsuites, "time", + FormatTimeInMillisAsSeconds(unit_test.elapsed_time())); + + if (GTEST_FLAG(shuffle)) { + OutputXmlAttribute(stream, kTestsuites, "random_seed", + StreamableToString(unit_test.random_seed())); + } + + *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result()); + + OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); + *stream << ">\n"; + + for (int i = 0; i < unit_test.total_test_case_count(); ++i) { + if (unit_test.GetTestCase(i)->reportable_test_count() > 0) + PrintXmlTestCase(stream, *unit_test.GetTestCase(i)); + } + *stream << "\n"; +} + +// Produces a string representing the test properties in a result as space +// delimited XML attributes based on the property key="value" pairs. +std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( + const TestResult& result) { + Message attributes; + for (int i = 0; i < result.test_property_count(); ++i) { + const TestProperty& property = result.GetTestProperty(i); + attributes << " " << property.key() << "=" + << "\"" << EscapeXmlAttribute(property.value()) << "\""; + } + return attributes.GetString(); +} + +// End XmlUnitTestResultPrinter + +#if GTEST_CAN_STREAM_RESULTS_ + +// Checks if str contains '=', '&', '%' or '\n' characters. If yes, +// replaces them by "%xx" where xx is their hexadecimal value. For +// example, replaces "=" with "%3D". This algorithm is O(strlen(str)) +// in both time and space -- important as the input str may contain an +// arbitrarily long test failure message and stack trace. +string StreamingListener::UrlEncode(const char* str) { + string result; + result.reserve(strlen(str) + 1); + for (char ch = *str; ch != '\0'; ch = *++str) { + switch (ch) { + case '%': + case '=': + case '&': + case '\n': + result.append("%" + String::FormatByte(static_cast(ch))); + break; + default: + result.push_back(ch); + break; + } + } + return result; +} + +void StreamingListener::SocketWriter::MakeConnection() { + GTEST_CHECK_(sockfd_ == -1) + << "MakeConnection() can't be called when there is already a connection."; + + addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. + hints.ai_socktype = SOCK_STREAM; + addrinfo* servinfo = NULL; + + // Use the getaddrinfo() to get a linked list of IP addresses for + // the given host name. + const int error_num = getaddrinfo( + host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); + if (error_num != 0) { + GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " + << gai_strerror(error_num); + } + + // Loop through all the results and connect to the first we can. + for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL; + cur_addr = cur_addr->ai_next) { + sockfd_ = socket( + cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); + if (sockfd_ != -1) { + // Connect the client socket to the server socket. + if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { + close(sockfd_); + sockfd_ = -1; + } + } + } + + freeaddrinfo(servinfo); // all done with this structure + + if (sockfd_ == -1) { + GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " + << host_name_ << ":" << port_num_; + } +} + +// End of class Streaming Listener +#endif // GTEST_CAN_STREAM_RESULTS__ + +// Class ScopedTrace + +// Pushes the given source file location and message onto a per-thread +// trace stack maintained by Google Test. +ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) + GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { + TraceInfo trace; + trace.file = file; + trace.line = line; + trace.message = message.GetString(); + + UnitTest::GetInstance()->PushGTestTrace(trace); +} + +// Pops the info pushed by the c'tor. +ScopedTrace::~ScopedTrace() + GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { + UnitTest::GetInstance()->PopGTestTrace(); +} + + +// class OsStackTraceGetter + +// Returns the current OS stack trace as an std::string. Parameters: +// +// max_depth - the maximum number of stack frames to be included +// in the trace. +// skip_count - the number of top frames to be skipped; doesn't count +// against max_depth. +// +string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */, + int /* skip_count */) + GTEST_LOCK_EXCLUDED_(mutex_) { + return ""; +} + +void OsStackTraceGetter::UponLeavingGTest() + GTEST_LOCK_EXCLUDED_(mutex_) { +} + +const char* const +OsStackTraceGetter::kElidedFramesMarker = + "... " GTEST_NAME_ " internal frames ..."; + +// A helper class that creates the premature-exit file in its +// constructor and deletes the file in its destructor. +class ScopedPrematureExitFile { + public: + explicit ScopedPrematureExitFile(const char* premature_exit_filepath) + : premature_exit_filepath_(premature_exit_filepath) { + // If a path to the premature-exit file is specified... + if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') { + // create the file with a single "0" character in it. I/O + // errors are ignored as there's nothing better we can do and we + // don't want to fail the test because of this. + FILE* pfile = posix::FOpen(premature_exit_filepath, "w"); + fwrite("0", 1, 1, pfile); + fclose(pfile); + } + } + + ~ScopedPrematureExitFile() { + if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') { + remove(premature_exit_filepath_); + } + } + + private: + const char* const premature_exit_filepath_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile); +}; + +} // namespace internal + +// class TestEventListeners + +TestEventListeners::TestEventListeners() + : repeater_(new internal::TestEventRepeater()), + default_result_printer_(NULL), + default_xml_generator_(NULL) { +} + +TestEventListeners::~TestEventListeners() { delete repeater_; } + +// Returns the standard listener responsible for the default console +// output. Can be removed from the listeners list to shut down default +// console output. Note that removing this object from the listener list +// with Release transfers its ownership to the user. +void TestEventListeners::Append(TestEventListener* listener) { + repeater_->Append(listener); +} + +// Removes the given event listener from the list and returns it. It then +// becomes the caller's responsibility to delete the listener. Returns +// NULL if the listener is not found in the list. +TestEventListener* TestEventListeners::Release(TestEventListener* listener) { + if (listener == default_result_printer_) + default_result_printer_ = NULL; + else if (listener == default_xml_generator_) + default_xml_generator_ = NULL; + return repeater_->Release(listener); +} + +// Returns repeater that broadcasts the TestEventListener events to all +// subscribers. +TestEventListener* TestEventListeners::repeater() { return repeater_; } + +// Sets the default_result_printer attribute to the provided listener. +// The listener is also added to the listener list and previous +// default_result_printer is removed from it and deleted. The listener can +// also be NULL in which case it will not be added to the list. Does +// nothing if the previous and the current listener objects are the same. +void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { + if (default_result_printer_ != listener) { + // It is an error to pass this method a listener that is already in the + // list. + delete Release(default_result_printer_); + default_result_printer_ = listener; + if (listener != NULL) + Append(listener); + } +} + +// Sets the default_xml_generator attribute to the provided listener. The +// listener is also added to the listener list and previous +// default_xml_generator is removed from it and deleted. The listener can +// also be NULL in which case it will not be added to the list. Does +// nothing if the previous and the current listener objects are the same. +void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { + if (default_xml_generator_ != listener) { + // It is an error to pass this method a listener that is already in the + // list. + delete Release(default_xml_generator_); + default_xml_generator_ = listener; + if (listener != NULL) + Append(listener); + } +} + +// Controls whether events will be forwarded by the repeater to the +// listeners in the list. +bool TestEventListeners::EventForwardingEnabled() const { + return repeater_->forwarding_enabled(); +} + +void TestEventListeners::SuppressEventForwarding() { + repeater_->set_forwarding_enabled(false); +} + +// class UnitTest + +// Gets the singleton UnitTest object. The first time this method is +// called, a UnitTest object is constructed and returned. Consecutive +// calls will return the same object. +// +// We don't protect this under mutex_ as a user is not supposed to +// call this before main() starts, from which point on the return +// value will never change. +UnitTest* UnitTest::GetInstance() { + // When compiled with MSVC 7.1 in optimized mode, destroying the + // UnitTest object upon exiting the program messes up the exit code, + // causing successful tests to appear failed. We have to use a + // different implementation in this case to bypass the compiler bug. + // This implementation makes the compiler happy, at the cost of + // leaking the UnitTest object. + + // CodeGear C++Builder insists on a public destructor for the + // default implementation. Use this implementation to keep good OO + // design with private destructor. + +#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) + static UnitTest* const instance = new UnitTest; + return instance; +#else + static UnitTest instance; + return &instance; +#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) +} + +// Gets the number of successful test cases. +int UnitTest::successful_test_case_count() const { + return impl()->successful_test_case_count(); +} + +// Gets the number of failed test cases. +int UnitTest::failed_test_case_count() const { + return impl()->failed_test_case_count(); +} + +// Gets the number of all test cases. +int UnitTest::total_test_case_count() const { + return impl()->total_test_case_count(); +} + +// Gets the number of all test cases that contain at least one test +// that should run. +int UnitTest::test_case_to_run_count() const { + return impl()->test_case_to_run_count(); +} + +// Gets the number of successful tests. +int UnitTest::successful_test_count() const { + return impl()->successful_test_count(); +} + +// Gets the number of failed tests. +int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } + +// Gets the number of disabled tests that will be reported in the XML report. +int UnitTest::reportable_disabled_test_count() const { + return impl()->reportable_disabled_test_count(); +} + +// Gets the number of disabled tests. +int UnitTest::disabled_test_count() const { + return impl()->disabled_test_count(); +} + +// Gets the number of tests to be printed in the XML report. +int UnitTest::reportable_test_count() const { + return impl()->reportable_test_count(); +} + +// Gets the number of all tests. +int UnitTest::total_test_count() const { return impl()->total_test_count(); } + +// Gets the number of tests that should run. +int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } + +// Gets the time of the test program start, in ms from the start of the +// UNIX epoch. +internal::TimeInMillis UnitTest::start_timestamp() const { + return impl()->start_timestamp(); +} + +// Gets the elapsed time, in milliseconds. +internal::TimeInMillis UnitTest::elapsed_time() const { + return impl()->elapsed_time(); +} + +// Returns true iff the unit test passed (i.e. all test cases passed). +bool UnitTest::Passed() const { return impl()->Passed(); } + +// Returns true iff the unit test failed (i.e. some test case failed +// or something outside of all tests failed). +bool UnitTest::Failed() const { return impl()->Failed(); } + +// Gets the i-th test case among all the test cases. i can range from 0 to +// total_test_case_count() - 1. If i is not in that range, returns NULL. +const TestCase* UnitTest::GetTestCase(int i) const { + return impl()->GetTestCase(i); +} + +// Returns the TestResult containing information on test failures and +// properties logged outside of individual test cases. +const TestResult& UnitTest::ad_hoc_test_result() const { + return *impl()->ad_hoc_test_result(); +} + +// Gets the i-th test case among all the test cases. i can range from 0 to +// total_test_case_count() - 1. If i is not in that range, returns NULL. +TestCase* UnitTest::GetMutableTestCase(int i) { + return impl()->GetMutableTestCase(i); +} + +// Returns the list of event listeners that can be used to track events +// inside Google Test. +TestEventListeners& UnitTest::listeners() { + return *impl()->listeners(); +} + +// Registers and returns a global test environment. When a test +// program is run, all global test environments will be set-up in the +// order they were registered. After all tests in the program have +// finished, all global test environments will be torn-down in the +// *reverse* order they were registered. +// +// The UnitTest object takes ownership of the given environment. +// +// We don't protect this under mutex_, as we only support calling it +// from the main thread. +Environment* UnitTest::AddEnvironment(Environment* env) { + if (env == NULL) { + return NULL; + } + + impl_->environments().push_back(env); + return env; +} + +// Adds a TestPartResult to the current TestResult object. All Google Test +// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call +// this to report their results. The user code should use the +// assertion macros instead of calling this directly. +void UnitTest::AddTestPartResult( + TestPartResult::Type result_type, + const char* file_name, + int line_number, + const std::string& message, + const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { + Message msg; + msg << message; + + internal::MutexLock lock(&mutex_); + if (impl_->gtest_trace_stack().size() > 0) { + msg << "\n" << GTEST_NAME_ << " trace:"; + + for (int i = static_cast(impl_->gtest_trace_stack().size()); + i > 0; --i) { + const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; + msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) + << " " << trace.message; + } + } + + if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) { + msg << internal::kStackTraceMarker << os_stack_trace; + } + + const TestPartResult result = + TestPartResult(result_type, file_name, line_number, + msg.GetString().c_str()); + impl_->GetTestPartResultReporterForCurrentThread()-> + ReportTestPartResult(result); + + if (result_type != TestPartResult::kSuccess) { + // gtest_break_on_failure takes precedence over + // gtest_throw_on_failure. This allows a user to set the latter + // in the code (perhaps in order to use Google Test assertions + // with another testing framework) and specify the former on the + // command line for debugging. + if (GTEST_FLAG(break_on_failure)) { +#if GTEST_OS_WINDOWS + // Using DebugBreak on Windows allows gtest to still break into a debugger + // when a failure happens and both the --gtest_break_on_failure and + // the --gtest_catch_exceptions flags are specified. + DebugBreak(); +#else + // Dereference NULL through a volatile pointer to prevent the compiler + // from removing. We use this rather than abort() or __builtin_trap() for + // portability: Symbian doesn't implement abort() well, and some debuggers + // don't correctly trap abort(). + *static_cast(NULL) = 1; +#endif // GTEST_OS_WINDOWS + } else if (GTEST_FLAG(throw_on_failure)) { +#if GTEST_HAS_EXCEPTIONS + throw internal::GoogleTestFailureException(result); +#else + // We cannot call abort() as it generates a pop-up in debug mode + // that cannot be suppressed in VC 7.1 or below. + exit(1); +#endif + } + } +} + +// Adds a TestProperty to the current TestResult object when invoked from +// inside a test, to current TestCase's ad_hoc_test_result_ when invoked +// from SetUpTestCase or TearDownTestCase, or to the global property set +// when invoked elsewhere. If the result already contains a property with +// the same key, the value will be updated. +void UnitTest::RecordProperty(const std::string& key, + const std::string& value) { + impl_->RecordProperty(TestProperty(key, value)); +} + +// Runs all tests in this UnitTest object and prints the result. +// Returns 0 if successful, or 1 otherwise. +// +// We don't protect this under mutex_, as we only support calling it +// from the main thread. +int UnitTest::Run() { + const bool in_death_test_child_process = + internal::GTEST_FLAG(internal_run_death_test).length() > 0; + + // Google Test implements this protocol for catching that a test + // program exits before returning control to Google Test: + // + // 1. Upon start, Google Test creates a file whose absolute path + // is specified by the environment variable + // TEST_PREMATURE_EXIT_FILE. + // 2. When Google Test has finished its work, it deletes the file. + // + // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before + // running a Google-Test-based test program and check the existence + // of the file at the end of the test execution to see if it has + // exited prematurely. + + // If we are in the child process of a death test, don't + // create/delete the premature exit file, as doing so is unnecessary + // and will confuse the parent process. Otherwise, create/delete + // the file upon entering/leaving this function. If the program + // somehow exits before this function has a chance to return, the + // premature-exit file will be left undeleted, causing a test runner + // that understands the premature-exit-file protocol to report the + // test as having failed. + const internal::ScopedPrematureExitFile premature_exit_file( + in_death_test_child_process ? + NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE")); + + // Captures the value of GTEST_FLAG(catch_exceptions). This value will be + // used for the duration of the program. + impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); + +#if GTEST_HAS_SEH + // Either the user wants Google Test to catch exceptions thrown by the + // tests or this is executing in the context of death test child + // process. In either case the user does not want to see pop-up dialogs + // about crashes - they are expected. + if (impl()->catch_exceptions() || in_death_test_child_process) { +# if !GTEST_OS_WINDOWS_MOBILE + // SetErrorMode doesn't exist on CE. + SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | + SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); +# endif // !GTEST_OS_WINDOWS_MOBILE + +# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE + // Death test children can be terminated with _abort(). On Windows, + // _abort() can show a dialog with a warning message. This forces the + // abort message to go to stderr instead. + _set_error_mode(_OUT_TO_STDERR); +# endif + +# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE + // In the debug version, Visual Studio pops up a separate dialog + // offering a choice to debug the aborted program. We need to suppress + // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement + // executed. Google Test will notify the user of any unexpected + // failure via stderr. + // + // VC++ doesn't define _set_abort_behavior() prior to the version 8.0. + // Users of prior VC versions shall suffer the agony and pain of + // clicking through the countless debug dialogs. + // TODO(vladl@google.com): find a way to suppress the abort dialog() in the + // debug mode when compiled with VC 7.1 or lower. + if (!GTEST_FLAG(break_on_failure)) + _set_abort_behavior( + 0x0, // Clear the following flags: + _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. +# endif + } +#endif // GTEST_HAS_SEH + + return internal::HandleExceptionsInMethodIfSupported( + impl(), + &internal::UnitTestImpl::RunAllTests, + "auxiliary test code (environments or event listeners)") ? 0 : 1; +} + +// Returns the working directory when the first TEST() or TEST_F() was +// executed. +const char* UnitTest::original_working_dir() const { + return impl_->original_working_dir_.c_str(); +} + +// Returns the TestCase object for the test that's currently running, +// or NULL if no test is running. +const TestCase* UnitTest::current_test_case() const + GTEST_LOCK_EXCLUDED_(mutex_) { + internal::MutexLock lock(&mutex_); + return impl_->current_test_case(); +} + +// Returns the TestInfo object for the test that's currently running, +// or NULL if no test is running. +const TestInfo* UnitTest::current_test_info() const + GTEST_LOCK_EXCLUDED_(mutex_) { + internal::MutexLock lock(&mutex_); + return impl_->current_test_info(); +} + +// Returns the random seed used at the start of the current test run. +int UnitTest::random_seed() const { return impl_->random_seed(); } + +#if GTEST_HAS_PARAM_TEST +// Returns ParameterizedTestCaseRegistry object used to keep track of +// value-parameterized tests and instantiate and register them. +internal::ParameterizedTestCaseRegistry& + UnitTest::parameterized_test_registry() + GTEST_LOCK_EXCLUDED_(mutex_) { + return impl_->parameterized_test_registry(); +} +#endif // GTEST_HAS_PARAM_TEST + +// Creates an empty UnitTest. +UnitTest::UnitTest() { + impl_ = new internal::UnitTestImpl(this); +} + +// Destructor of UnitTest. +UnitTest::~UnitTest() { + delete impl_; +} + +// Pushes a trace defined by SCOPED_TRACE() on to the per-thread +// Google Test trace stack. +void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) + GTEST_LOCK_EXCLUDED_(mutex_) { + internal::MutexLock lock(&mutex_); + impl_->gtest_trace_stack().push_back(trace); +} + +// Pops a trace from the per-thread Google Test trace stack. +void UnitTest::PopGTestTrace() + GTEST_LOCK_EXCLUDED_(mutex_) { + internal::MutexLock lock(&mutex_); + impl_->gtest_trace_stack().pop_back(); +} + +namespace internal { + +UnitTestImpl::UnitTestImpl(UnitTest* parent) + : parent_(parent), +#ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable:4355) // Temporarily disables warning 4355 + // (using this in initializer). + default_global_test_part_result_reporter_(this), + default_per_thread_test_part_result_reporter_(this), +# pragma warning(pop) // Restores the warning state again. +#else + default_global_test_part_result_reporter_(this), + default_per_thread_test_part_result_reporter_(this), +#endif // _MSC_VER + global_test_part_result_repoter_( + &default_global_test_part_result_reporter_), + per_thread_test_part_result_reporter_( + &default_per_thread_test_part_result_reporter_), +#if GTEST_HAS_PARAM_TEST + parameterized_test_registry_(), + parameterized_tests_registered_(false), +#endif // GTEST_HAS_PARAM_TEST + last_death_test_case_(-1), + current_test_case_(NULL), + current_test_info_(NULL), + ad_hoc_test_result_(), + os_stack_trace_getter_(NULL), + post_flag_parse_init_performed_(false), + random_seed_(0), // Will be overridden by the flag before first use. + random_(0), // Will be reseeded before first use. + start_timestamp_(0), + elapsed_time_(0), +#if GTEST_HAS_DEATH_TEST + death_test_factory_(new DefaultDeathTestFactory), +#endif + // Will be overridden by the flag before first use. + catch_exceptions_(false) { + listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); +} + +UnitTestImpl::~UnitTestImpl() { + // Deletes every TestCase. + ForEach(test_cases_, internal::Delete); + + // Deletes every Environment. + ForEach(environments_, internal::Delete); + + delete os_stack_trace_getter_; +} + +// Adds a TestProperty to the current TestResult object when invoked in a +// context of a test, to current test case's ad_hoc_test_result when invoke +// from SetUpTestCase/TearDownTestCase, or to the global property set +// otherwise. If the result already contains a property with the same key, +// the value will be updated. +void UnitTestImpl::RecordProperty(const TestProperty& test_property) { + std::string xml_element; + TestResult* test_result; // TestResult appropriate for property recording. + + if (current_test_info_ != NULL) { + xml_element = "testcase"; + test_result = &(current_test_info_->result_); + } else if (current_test_case_ != NULL) { + xml_element = "testsuite"; + test_result = &(current_test_case_->ad_hoc_test_result_); + } else { + xml_element = "testsuites"; + test_result = &ad_hoc_test_result_; + } + test_result->RecordProperty(xml_element, test_property); +} + +#if GTEST_HAS_DEATH_TEST +// Disables event forwarding if the control is currently in a death test +// subprocess. Must not be called before InitGoogleTest. +void UnitTestImpl::SuppressTestEventsIfInSubprocess() { + if (internal_run_death_test_flag_.get() != NULL) + listeners()->SuppressEventForwarding(); +} +#endif // GTEST_HAS_DEATH_TEST + +// Initializes event listeners performing XML output as specified by +// UnitTestOptions. Must not be called before InitGoogleTest. +void UnitTestImpl::ConfigureXmlOutput() { + const std::string& output_format = UnitTestOptions::GetOutputFormat(); + if (output_format == "xml") { + listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( + UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); + } else if (output_format != "") { + printf("WARNING: unrecognized output format \"%s\" ignored.\n", + output_format.c_str()); + fflush(stdout); + } +} + +#if GTEST_CAN_STREAM_RESULTS_ +// Initializes event listeners for streaming test results in string form. +// Must not be called before InitGoogleTest. +void UnitTestImpl::ConfigureStreamingOutput() { + const std::string& target = GTEST_FLAG(stream_result_to); + if (!target.empty()) { + const size_t pos = target.find(':'); + if (pos != std::string::npos) { + listeners()->Append(new StreamingListener(target.substr(0, pos), + target.substr(pos+1))); + } else { + printf("WARNING: unrecognized streaming target \"%s\" ignored.\n", + target.c_str()); + fflush(stdout); + } + } +} +#endif // GTEST_CAN_STREAM_RESULTS_ + +// Performs initialization dependent upon flag values obtained in +// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to +// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest +// this function is also called from RunAllTests. Since this function can be +// called more than once, it has to be idempotent. +void UnitTestImpl::PostFlagParsingInit() { + // Ensures that this function does not execute more than once. + if (!post_flag_parse_init_performed_) { + post_flag_parse_init_performed_ = true; + +#if GTEST_HAS_DEATH_TEST + InitDeathTestSubprocessControlInfo(); + SuppressTestEventsIfInSubprocess(); +#endif // GTEST_HAS_DEATH_TEST + + // Registers parameterized tests. This makes parameterized tests + // available to the UnitTest reflection API without running + // RUN_ALL_TESTS. + RegisterParameterizedTests(); + + // Configures listeners for XML output. This makes it possible for users + // to shut down the default XML output before invoking RUN_ALL_TESTS. + ConfigureXmlOutput(); + +#if GTEST_CAN_STREAM_RESULTS_ + // Configures listeners for streaming test results to the specified server. + ConfigureStreamingOutput(); +#endif // GTEST_CAN_STREAM_RESULTS_ + } +} + +// A predicate that checks the name of a TestCase against a known +// value. +// +// This is used for implementation of the UnitTest class only. We put +// it in the anonymous namespace to prevent polluting the outer +// namespace. +// +// TestCaseNameIs is copyable. +class TestCaseNameIs { + public: + // Constructor. + explicit TestCaseNameIs(const std::string& name) + : name_(name) {} + + // Returns true iff the name of test_case matches name_. + bool operator()(const TestCase* test_case) const { + return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0; + } + + private: + std::string name_; +}; + +// Finds and returns a TestCase with the given name. If one doesn't +// exist, creates one and returns it. It's the CALLER'S +// RESPONSIBILITY to ensure that this function is only called WHEN THE +// TESTS ARE NOT SHUFFLED. +// +// Arguments: +// +// test_case_name: name of the test case +// type_param: the name of the test case's type parameter, or NULL if +// this is not a typed or a type-parameterized test case. +// set_up_tc: pointer to the function that sets up the test case +// tear_down_tc: pointer to the function that tears down the test case +TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, + const char* type_param, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc) { + // Can we find a TestCase with the given name? + const std::vector::const_iterator test_case = + std::find_if(test_cases_.begin(), test_cases_.end(), + TestCaseNameIs(test_case_name)); + + if (test_case != test_cases_.end()) + return *test_case; + + // No. Let's create one. + TestCase* const new_test_case = + new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc); + + // Is this a death test case? + if (internal::UnitTestOptions::MatchesFilter(test_case_name, + kDeathTestCaseFilter)) { + // Yes. Inserts the test case after the last death test case + // defined so far. This only works when the test cases haven't + // been shuffled. Otherwise we may end up running a death test + // after a non-death test. + ++last_death_test_case_; + test_cases_.insert(test_cases_.begin() + last_death_test_case_, + new_test_case); + } else { + // No. Appends to the end of the list. + test_cases_.push_back(new_test_case); + } + + test_case_indices_.push_back(static_cast(test_case_indices_.size())); + return new_test_case; +} + +// Helpers for setting up / tearing down the given environment. They +// are for use in the ForEach() function. +static void SetUpEnvironment(Environment* env) { env->SetUp(); } +static void TearDownEnvironment(Environment* env) { env->TearDown(); } + +// Runs all tests in this UnitTest object, prints the result, and +// returns true if all tests are successful. If any exception is +// thrown during a test, the test is considered to be failed, but the +// rest of the tests will still be run. +// +// When parameterized tests are enabled, it expands and registers +// parameterized tests first in RegisterParameterizedTests(). +// All other functions called from RunAllTests() may safely assume that +// parameterized tests are ready to be counted and run. +bool UnitTestImpl::RunAllTests() { + // Makes sure InitGoogleTest() was called. + if (!GTestIsInitialized()) { + printf("%s", + "\nThis test program did NOT call ::testing::InitGoogleTest " + "before calling RUN_ALL_TESTS(). Please fix it.\n"); + return false; + } + + // Do not run any test if the --help flag was specified. + if (g_help_flag) + return true; + + // Repeats the call to the post-flag parsing initialization in case the + // user didn't call InitGoogleTest. + PostFlagParsingInit(); + + // Even if sharding is not on, test runners may want to use the + // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding + // protocol. + internal::WriteToShardStatusFileIfNeeded(); + + // True iff we are in a subprocess for running a thread-safe-style + // death test. + bool in_subprocess_for_death_test = false; + +#if GTEST_HAS_DEATH_TEST + in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL); +#endif // GTEST_HAS_DEATH_TEST + + const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, + in_subprocess_for_death_test); + + // Compares the full test names with the filter to decide which + // tests to run. + const bool has_tests_to_run = FilterTests(should_shard + ? HONOR_SHARDING_PROTOCOL + : IGNORE_SHARDING_PROTOCOL) > 0; + + // Lists the tests and exits if the --gtest_list_tests flag was specified. + if (GTEST_FLAG(list_tests)) { + // This must be called *after* FilterTests() has been called. + ListTestsMatchingFilter(); + return true; + } + + random_seed_ = GTEST_FLAG(shuffle) ? + GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; + + // True iff at least one test has failed. + bool failed = false; + + TestEventListener* repeater = listeners()->repeater(); + + start_timestamp_ = GetTimeInMillis(); + repeater->OnTestProgramStart(*parent_); + + // How many times to repeat the tests? We don't want to repeat them + // when we are inside the subprocess of a death test. + const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); + // Repeats forever if the repeat count is negative. + const bool forever = repeat < 0; + for (int i = 0; forever || i != repeat; i++) { + // We want to preserve failures generated by ad-hoc test + // assertions executed before RUN_ALL_TESTS(). + ClearNonAdHocTestResult(); + + const TimeInMillis start = GetTimeInMillis(); + + // Shuffles test cases and tests if requested. + if (has_tests_to_run && GTEST_FLAG(shuffle)) { + random()->Reseed(random_seed_); + // This should be done before calling OnTestIterationStart(), + // such that a test event listener can see the actual test order + // in the event. + ShuffleTests(); + } + + // Tells the unit test event listeners that the tests are about to start. + repeater->OnTestIterationStart(*parent_, i); + + // Runs each test case if there is at least one test to run. + if (has_tests_to_run) { + // Sets up all environments beforehand. + repeater->OnEnvironmentsSetUpStart(*parent_); + ForEach(environments_, SetUpEnvironment); + repeater->OnEnvironmentsSetUpEnd(*parent_); + + // Runs the tests only if there was no fatal failure during global + // set-up. + if (!Test::HasFatalFailure()) { + for (int test_index = 0; test_index < total_test_case_count(); + test_index++) { + GetMutableTestCase(test_index)->Run(); + } + } + + // Tears down all environments in reverse order afterwards. + repeater->OnEnvironmentsTearDownStart(*parent_); + std::for_each(environments_.rbegin(), environments_.rend(), + TearDownEnvironment); + repeater->OnEnvironmentsTearDownEnd(*parent_); + } + + elapsed_time_ = GetTimeInMillis() - start; + + // Tells the unit test event listener that the tests have just finished. + repeater->OnTestIterationEnd(*parent_, i); + + // Gets the result and clears it. + if (!Passed()) { + failed = true; + } + + // Restores the original test order after the iteration. This + // allows the user to quickly repro a failure that happens in the + // N-th iteration without repeating the first (N - 1) iterations. + // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in + // case the user somehow changes the value of the flag somewhere + // (it's always safe to unshuffle the tests). + UnshuffleTests(); + + if (GTEST_FLAG(shuffle)) { + // Picks a new random seed for each iteration. + random_seed_ = GetNextRandomSeed(random_seed_); + } + } + + repeater->OnTestProgramEnd(*parent_); + + return !failed; +} + +// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file +// if the variable is present. If a file already exists at this location, this +// function will write over it. If the variable is present, but the file cannot +// be created, prints an error and exits. +void WriteToShardStatusFileIfNeeded() { + const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile); + if (test_shard_file != NULL) { + FILE* const file = posix::FOpen(test_shard_file, "w"); + if (file == NULL) { + ColoredPrintf(COLOR_RED, + "Could not write to the test shard status file \"%s\" " + "specified by the %s environment variable.\n", + test_shard_file, kTestShardStatusFile); + fflush(stdout); + exit(EXIT_FAILURE); + } + fclose(file); + } +} + +// Checks whether sharding is enabled by examining the relevant +// environment variable values. If the variables are present, +// but inconsistent (i.e., shard_index >= total_shards), prints +// an error and exits. If in_subprocess_for_death_test, sharding is +// disabled because it must only be applied to the original test +// process. Otherwise, we could filter out death tests we intended to execute. +bool ShouldShard(const char* total_shards_env, + const char* shard_index_env, + bool in_subprocess_for_death_test) { + if (in_subprocess_for_death_test) { + return false; + } + + const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); + const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); + + if (total_shards == -1 && shard_index == -1) { + return false; + } else if (total_shards == -1 && shard_index != -1) { + const Message msg = Message() + << "Invalid environment variables: you have " + << kTestShardIndex << " = " << shard_index + << ", but have left " << kTestTotalShards << " unset.\n"; + ColoredPrintf(COLOR_RED, msg.GetString().c_str()); + fflush(stdout); + exit(EXIT_FAILURE); + } else if (total_shards != -1 && shard_index == -1) { + const Message msg = Message() + << "Invalid environment variables: you have " + << kTestTotalShards << " = " << total_shards + << ", but have left " << kTestShardIndex << " unset.\n"; + ColoredPrintf(COLOR_RED, msg.GetString().c_str()); + fflush(stdout); + exit(EXIT_FAILURE); + } else if (shard_index < 0 || shard_index >= total_shards) { + const Message msg = Message() + << "Invalid environment variables: we require 0 <= " + << kTestShardIndex << " < " << kTestTotalShards + << ", but you have " << kTestShardIndex << "=" << shard_index + << ", " << kTestTotalShards << "=" << total_shards << ".\n"; + ColoredPrintf(COLOR_RED, msg.GetString().c_str()); + fflush(stdout); + exit(EXIT_FAILURE); + } + + return total_shards > 1; +} + +// Parses the environment variable var as an Int32. If it is unset, +// returns default_val. If it is not an Int32, prints an error +// and aborts. +Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) { + const char* str_val = posix::GetEnv(var); + if (str_val == NULL) { + return default_val; + } + + Int32 result; + if (!ParseInt32(Message() << "The value of environment variable " << var, + str_val, &result)) { + exit(EXIT_FAILURE); + } + return result; +} + +// Given the total number of shards, the shard index, and the test id, +// returns true iff the test should be run on this shard. The test id is +// some arbitrary but unique non-negative integer assigned to each test +// method. Assumes that 0 <= shard_index < total_shards. +bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { + return (test_id % total_shards) == shard_index; +} + +// Compares the name of each test with the user-specified filter to +// decide whether the test should be run, then records the result in +// each TestCase and TestInfo object. +// If shard_tests == true, further filters tests based on sharding +// variables in the environment - see +// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide. +// Returns the number of tests that should run. +int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { + const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? + Int32FromEnvOrDie(kTestTotalShards, -1) : -1; + const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? + Int32FromEnvOrDie(kTestShardIndex, -1) : -1; + + // num_runnable_tests are the number of tests that will + // run across all shards (i.e., match filter and are not disabled). + // num_selected_tests are the number of tests to be run on + // this shard. + int num_runnable_tests = 0; + int num_selected_tests = 0; + for (size_t i = 0; i < test_cases_.size(); i++) { + TestCase* const test_case = test_cases_[i]; + const std::string &test_case_name = test_case->name(); + test_case->set_should_run(false); + + for (size_t j = 0; j < test_case->test_info_list().size(); j++) { + TestInfo* const test_info = test_case->test_info_list()[j]; + const std::string test_name(test_info->name()); + // A test is disabled if test case name or test name matches + // kDisableTestFilter. + const bool is_disabled = + internal::UnitTestOptions::MatchesFilter(test_case_name, + kDisableTestFilter) || + internal::UnitTestOptions::MatchesFilter(test_name, + kDisableTestFilter); + test_info->is_disabled_ = is_disabled; + + const bool matches_filter = + internal::UnitTestOptions::FilterMatchesTest(test_case_name, + test_name); + test_info->matches_filter_ = matches_filter; + + const bool is_runnable = + (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && + matches_filter; + + const bool is_selected = is_runnable && + (shard_tests == IGNORE_SHARDING_PROTOCOL || + ShouldRunTestOnShard(total_shards, shard_index, + num_runnable_tests)); + + num_runnable_tests += is_runnable; + num_selected_tests += is_selected; + + test_info->should_run_ = is_selected; + test_case->set_should_run(test_case->should_run() || is_selected); + } + } + return num_selected_tests; +} + +// Prints the given C-string on a single line by replacing all '\n' +// characters with string "\\n". If the output takes more than +// max_length characters, only prints the first max_length characters +// and "...". +static void PrintOnOneLine(const char* str, int max_length) { + if (str != NULL) { + for (int i = 0; *str != '\0'; ++str) { + if (i >= max_length) { + printf("..."); + break; + } + if (*str == '\n') { + printf("\\n"); + i += 2; + } else { + printf("%c", *str); + ++i; + } + } + } +} + +// Prints the names of the tests matching the user-specified filter flag. +void UnitTestImpl::ListTestsMatchingFilter() { + // Print at most this many characters for each type/value parameter. + const int kMaxParamLength = 250; + + for (size_t i = 0; i < test_cases_.size(); i++) { + const TestCase* const test_case = test_cases_[i]; + bool printed_test_case_name = false; + + for (size_t j = 0; j < test_case->test_info_list().size(); j++) { + const TestInfo* const test_info = + test_case->test_info_list()[j]; + if (test_info->matches_filter_) { + if (!printed_test_case_name) { + printed_test_case_name = true; + printf("%s.", test_case->name()); + if (test_case->type_param() != NULL) { + printf(" # %s = ", kTypeParamLabel); + // We print the type parameter on a single line to make + // the output easy to parse by a program. + PrintOnOneLine(test_case->type_param(), kMaxParamLength); + } + printf("\n"); + } + printf(" %s", test_info->name()); + if (test_info->value_param() != NULL) { + printf(" # %s = ", kValueParamLabel); + // We print the value parameter on a single line to make the + // output easy to parse by a program. + PrintOnOneLine(test_info->value_param(), kMaxParamLength); + } + printf("\n"); + } + } + } + fflush(stdout); +} + +// Sets the OS stack trace getter. +// +// Does nothing if the input and the current OS stack trace getter are +// the same; otherwise, deletes the old getter and makes the input the +// current getter. +void UnitTestImpl::set_os_stack_trace_getter( + OsStackTraceGetterInterface* getter) { + if (os_stack_trace_getter_ != getter) { + delete os_stack_trace_getter_; + os_stack_trace_getter_ = getter; + } +} + +// Returns the current OS stack trace getter if it is not NULL; +// otherwise, creates an OsStackTraceGetter, makes it the current +// getter, and returns it. +OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { + if (os_stack_trace_getter_ == NULL) { + os_stack_trace_getter_ = new OsStackTraceGetter; + } + + return os_stack_trace_getter_; +} + +// Returns the TestResult for the test that's currently running, or +// the TestResult for the ad hoc test if no test is running. +TestResult* UnitTestImpl::current_test_result() { + return current_test_info_ ? + &(current_test_info_->result_) : &ad_hoc_test_result_; +} + +// Shuffles all test cases, and the tests within each test case, +// making sure that death tests are still run first. +void UnitTestImpl::ShuffleTests() { + // Shuffles the death test cases. + ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_); + + // Shuffles the non-death test cases. + ShuffleRange(random(), last_death_test_case_ + 1, + static_cast(test_cases_.size()), &test_case_indices_); + + // Shuffles the tests inside each test case. + for (size_t i = 0; i < test_cases_.size(); i++) { + test_cases_[i]->ShuffleTests(random()); + } +} + +// Restores the test cases and tests to their order before the first shuffle. +void UnitTestImpl::UnshuffleTests() { + for (size_t i = 0; i < test_cases_.size(); i++) { + // Unshuffles the tests in each test case. + test_cases_[i]->UnshuffleTests(); + // Resets the index of each test case. + test_case_indices_[i] = static_cast(i); + } +} + +// Returns the current OS stack trace as an std::string. +// +// The maximum number of stack frames to be included is specified by +// the gtest_stack_trace_depth flag. The skip_count parameter +// specifies the number of top frames to be skipped, which doesn't +// count against the number of frames to be included. +// +// For example, if Foo() calls Bar(), which in turn calls +// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in +// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. +std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, + int skip_count) { + // We pass skip_count + 1 to skip this wrapper function in addition + // to what the user really wants to skip. + return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); +} + +// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to +// suppress unreachable code warnings. +namespace { +class ClassUniqueToAlwaysTrue {}; +} + +bool IsTrue(bool condition) { return condition; } + +bool AlwaysTrue() { +#if GTEST_HAS_EXCEPTIONS + // This condition is always false so AlwaysTrue() never actually throws, + // but it makes the compiler think that it may throw. + if (IsTrue(false)) + throw ClassUniqueToAlwaysTrue(); +#endif // GTEST_HAS_EXCEPTIONS + return true; +} + +// If *pstr starts with the given prefix, modifies *pstr to be right +// past the prefix and returns true; otherwise leaves *pstr unchanged +// and returns false. None of pstr, *pstr, and prefix can be NULL. +bool SkipPrefix(const char* prefix, const char** pstr) { + const size_t prefix_len = strlen(prefix); + if (strncmp(*pstr, prefix, prefix_len) == 0) { + *pstr += prefix_len; + return true; + } + return false; +} + +// Parses a string as a command line flag. The string should have +// the format "--flag=value". When def_optional is true, the "=value" +// part can be omitted. +// +// Returns the value of the flag, or NULL if the parsing failed. +const char* ParseFlagValue(const char* str, + const char* flag, + bool def_optional) { + // str and flag must not be NULL. + if (str == NULL || flag == NULL) return NULL; + + // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. + const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag; + const size_t flag_len = flag_str.length(); + if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; + + // Skips the flag name. + const char* flag_end = str + flag_len; + + // When def_optional is true, it's OK to not have a "=value" part. + if (def_optional && (flag_end[0] == '\0')) { + return flag_end; + } + + // If def_optional is true and there are more characters after the + // flag name, or if def_optional is false, there must be a '=' after + // the flag name. + if (flag_end[0] != '=') return NULL; + + // Returns the string after "=". + return flag_end + 1; +} + +// Parses a string for a bool flag, in the form of either +// "--flag=value" or "--flag". +// +// In the former case, the value is taken as true as long as it does +// not start with '0', 'f', or 'F'. +// +// In the latter case, the value is taken as true. +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +bool ParseBoolFlag(const char* str, const char* flag, bool* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseFlagValue(str, flag, true); + + // Aborts if the parsing failed. + if (value_str == NULL) return false; + + // Converts the string value to a bool. + *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); + return true; +} + +// Parses a string for an Int32 flag, in the form of +// "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseFlagValue(str, flag, false); + + // Aborts if the parsing failed. + if (value_str == NULL) return false; + + // Sets *value to the value of the flag. + return ParseInt32(Message() << "The value of flag --" << flag, + value_str, value); +} + +// Parses a string for a string flag, in the form of +// "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +bool ParseStringFlag(const char* str, const char* flag, std::string* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseFlagValue(str, flag, false); + + // Aborts if the parsing failed. + if (value_str == NULL) return false; + + // Sets *value to the value of the flag. + *value = value_str; + return true; +} + +// Determines whether a string has a prefix that Google Test uses for its +// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. +// If Google Test detects that a command line flag has its prefix but is not +// recognized, it will print its help message. Flags starting with +// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test +// internal flags and do not trigger the help message. +static bool HasGoogleTestFlagPrefix(const char* str) { + return (SkipPrefix("--", &str) || + SkipPrefix("-", &str) || + SkipPrefix("/", &str)) && + !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && + (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || + SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); +} + +// Prints a string containing code-encoded text. The following escape +// sequences can be used in the string to control the text color: +// +// @@ prints a single '@' character. +// @R changes the color to red. +// @G changes the color to green. +// @Y changes the color to yellow. +// @D changes to the default terminal text color. +// +// TODO(wan@google.com): Write tests for this once we add stdout +// capturing to Google Test. +static void PrintColorEncoded(const char* str) { + GTestColor color = COLOR_DEFAULT; // The current color. + + // Conceptually, we split the string into segments divided by escape + // sequences. Then we print one segment at a time. At the end of + // each iteration, the str pointer advances to the beginning of the + // next segment. + for (;;) { + const char* p = strchr(str, '@'); + if (p == NULL) { + ColoredPrintf(color, "%s", str); + return; + } + + ColoredPrintf(color, "%s", std::string(str, p).c_str()); + + const char ch = p[1]; + str = p + 2; + if (ch == '@') { + ColoredPrintf(color, "@"); + } else if (ch == 'D') { + color = COLOR_DEFAULT; + } else if (ch == 'R') { + color = COLOR_RED; + } else if (ch == 'G') { + color = COLOR_GREEN; + } else if (ch == 'Y') { + color = COLOR_YELLOW; + } else { + --str; + } + } +} + +static const char kColorEncodedHelpMessage[] = +"This program contains tests written using " GTEST_NAME_ ". You can use the\n" +"following command line flags to control its behavior:\n" +"\n" +"Test Selection:\n" +" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" +" List the names of all tests instead of running them. The name of\n" +" TEST(Foo, Bar) is \"Foo.Bar\".\n" +" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS" + "[@G-@YNEGATIVE_PATTERNS]@D\n" +" Run only the tests whose name matches one of the positive patterns but\n" +" none of the negative patterns. '?' matches any single character; '*'\n" +" matches any substring; ':' separates two patterns.\n" +" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" +" Run all disabled tests too.\n" +"\n" +"Test Execution:\n" +" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" +" Run the tests repeatedly; use a negative count to repeat forever.\n" +" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n" +" Randomize tests' orders on every iteration.\n" +" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n" +" Random number seed to use for shuffling test orders (between 1 and\n" +" 99999, or 0 to use a seed based on the current time).\n" +"\n" +"Test Output:\n" +" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" +" Enable/disable colored output. The default is @Gauto@D.\n" +" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n" +" Don't print the elapsed time of each test.\n" +" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G" + GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" +" Generate an XML report in the given directory or with the given file\n" +" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" +#if GTEST_CAN_STREAM_RESULTS_ +" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" +" Stream test results to the given server.\n" +#endif // GTEST_CAN_STREAM_RESULTS_ +"\n" +"Assertion Behavior:\n" +#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS +" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" +" Set the default death test style.\n" +#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS +" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" +" Turn assertion failures into debugger break-points.\n" +" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" +" Turn assertion failures into C++ exceptions.\n" +" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n" +" Do not report exceptions as test failures. Instead, allow them\n" +" to crash the program or throw a pop-up (on Windows).\n" +"\n" +"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " + "the corresponding\n" +"environment variable of a flag (all letters in upper-case). For example, to\n" +"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_ + "color=no@D or set\n" +"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n" +"\n" +"For more information, please read the " GTEST_NAME_ " documentation at\n" +"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" +"(not one in your own code or tests), please report it to\n" +"@G<" GTEST_DEV_EMAIL_ ">@D.\n"; + +// Parses the command line for Google Test flags, without initializing +// other parts of Google Test. The type parameter CharType can be +// instantiated to either char or wchar_t. +template +void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { + for (int i = 1; i < *argc; i++) { + const std::string arg_string = StreamableToString(argv[i]); + const char* const arg = arg_string.c_str(); + + using internal::ParseBoolFlag; + using internal::ParseInt32Flag; + using internal::ParseStringFlag; + + // Do we see a Google Test flag? + if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, + >EST_FLAG(also_run_disabled_tests)) || + ParseBoolFlag(arg, kBreakOnFailureFlag, + >EST_FLAG(break_on_failure)) || + ParseBoolFlag(arg, kCatchExceptionsFlag, + >EST_FLAG(catch_exceptions)) || + ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || + ParseStringFlag(arg, kDeathTestStyleFlag, + >EST_FLAG(death_test_style)) || + ParseBoolFlag(arg, kDeathTestUseFork, + >EST_FLAG(death_test_use_fork)) || + ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || + ParseStringFlag(arg, kInternalRunDeathTestFlag, + >EST_FLAG(internal_run_death_test)) || + ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || + ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || + ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || + ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || + ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || + ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || + ParseInt32Flag(arg, kStackTraceDepthFlag, + >EST_FLAG(stack_trace_depth)) || + ParseStringFlag(arg, kStreamResultToFlag, + >EST_FLAG(stream_result_to)) || + ParseBoolFlag(arg, kThrowOnFailureFlag, + >EST_FLAG(throw_on_failure)) + ) { + // Yes. Shift the remainder of the argv list left by one. Note + // that argv has (*argc + 1) elements, the last one always being + // NULL. The following loop moves the trailing NULL element as + // well. + for (int j = i; j != *argc; j++) { + argv[j] = argv[j + 1]; + } + + // Decrements the argument count. + (*argc)--; + + // We also need to decrement the iterator as we just removed + // an element. + i--; + } else if (arg_string == "--help" || arg_string == "-h" || + arg_string == "-?" || arg_string == "/?" || + HasGoogleTestFlagPrefix(arg)) { + // Both help flag and unrecognized Google Test flags (excluding + // internal ones) trigger help display. + g_help_flag = true; + } + } + + if (g_help_flag) { + // We print the help here instead of in RUN_ALL_TESTS(), as the + // latter may not be called at all if the user is using Google + // Test with another testing framework. + PrintColorEncoded(kColorEncodedHelpMessage); + } +} + +// Parses the command line for Google Test flags, without initializing +// other parts of Google Test. +void ParseGoogleTestFlagsOnly(int* argc, char** argv) { + ParseGoogleTestFlagsOnlyImpl(argc, argv); +} +void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { + ParseGoogleTestFlagsOnlyImpl(argc, argv); +} + +// The internal implementation of InitGoogleTest(). +// +// The type parameter CharType can be instantiated to either char or +// wchar_t. +template +void InitGoogleTestImpl(int* argc, CharType** argv) { + g_init_gtest_count++; + + // We don't want to run the initialization code twice. + if (g_init_gtest_count != 1) return; + + if (*argc <= 0) return; + + internal::g_executable_path = internal::StreamableToString(argv[0]); + +#if GTEST_HAS_DEATH_TEST + + g_argvs.clear(); + for (int i = 0; i != *argc; i++) { + g_argvs.push_back(StreamableToString(argv[i])); + } + +#endif // GTEST_HAS_DEATH_TEST + + ParseGoogleTestFlagsOnly(argc, argv); + GetUnitTestImpl()->PostFlagParsingInit(); +} + +} // namespace internal + +// Initializes Google Test. This must be called before calling +// RUN_ALL_TESTS(). In particular, it parses a command line for the +// flags that Google Test recognizes. Whenever a Google Test flag is +// seen, it is removed from argv, and *argc is decremented. +// +// No value is returned. Instead, the Google Test flag variables are +// updated. +// +// Calling the function for the second time has no user-visible effect. +void InitGoogleTest(int* argc, char** argv) { + internal::InitGoogleTestImpl(argc, argv); +} + +// This overloaded version can be used in Windows programs compiled in +// UNICODE mode. +void InitGoogleTest(int* argc, wchar_t** argv) { + internal::InitGoogleTestImpl(argc, argv); +} + +} // namespace testing diff --git a/lib/gtest/src/gtest_main.cc b/lib/gtest/src/gtest_main.cc new file mode 100644 index 00000000..f3028225 --- /dev/null +++ b/lib/gtest/src/gtest_main.cc @@ -0,0 +1,38 @@ +// Copyright 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include + +#include "gtest/gtest.h" + +GTEST_API_ int main(int argc, char **argv) { + printf("Running main() from gtest_main.cc\n"); + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/mfc/README.txt b/mfc/README.txt deleted file mode 100644 index 2283ea35..00000000 --- a/mfc/README.txt +++ /dev/null @@ -1,28 +0,0 @@ -Visual Leak Detector MFC Example (Version 1.0.1) - - Example Program Using Visual Leak Detector in an MFC Application - - -About The MFC Example Program: ------------------------------- -This is an example Visual C++ 6.0 MFC project that implements the Visual -Leak Detector. - -To build the example project, simply open the project file and start a build. - -After the project is built, running the program will pop up a simple -dialog box. If you leave the "Leak Some Memory" box checked, the program -will leak a small amount of memory as it exits. If you run the program -under the Visual C++ debugger, you should see a memory leak report in the -debug output window after the program exits. The report will include -detailed stack traces of the calls that allocated the leaked memory blocks. - -Double-clicking on a source file/line number in the stack trace will take you to -that file and line in the editor. This allows you to quickly see where in the -program the memory was allocated and how it got there. - - -Documentation: --------------- - -See the README.html file for the complete Visual Leak Detector documentation. diff --git a/mfc/res/vldmfc.ico b/mfc/res/vldmfc.ico deleted file mode 100644 index 7eef0bcb..00000000 Binary files a/mfc/res/vldmfc.ico and /dev/null differ diff --git a/mfc/vldmfc.vcproj b/mfc/vldmfc.vcproj deleted file mode 100755 index 84a40fc5..00000000 --- a/mfc/vldmfc.vcproj +++ /dev/null @@ -1,353 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/mfc/StdAfx.cpp b/mfc_detect/StdAfx.cpp similarity index 96% rename from mfc/StdAfx.cpp rename to mfc_detect/StdAfx.cpp index fca51d9c..52f38aae 100644 --- a/mfc/StdAfx.cpp +++ b/mfc_detect/StdAfx.cpp @@ -1,8 +1,8 @@ -// source file that includes just the standard includes -// vldmfc.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - - - +// source file that includes just the standard includes +// vldmfc.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + + + diff --git a/mfc/StdAfx.h b/mfc_detect/StdAfx.h similarity index 97% rename from mfc/StdAfx.h rename to mfc_detect/StdAfx.h index 01a2e1ae..33d88926 100644 --- a/mfc/StdAfx.h +++ b/mfc_detect/StdAfx.h @@ -1,27 +1,27 @@ -// include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#if !defined(AFX_STDAFX_H__9884638E_0AE1_42F8_BFF0_840BD090BD42__INCLUDED_) -#define AFX_STDAFX_H__9884638E_0AE1_42F8_BFF0_840BD090BD42__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers - -#include // MFC core and standard components -#include // MFC extensions -#include // MFC support for Internet Explorer 4 Common Controls -#ifndef _AFX_NO_AFXCMN_SUPPORT -#include // MFC support for Windows Common Controls -#endif // _AFX_NO_AFXCMN_SUPPORT - - - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_STDAFX_H__9884638E_0AE1_42F8_BFF0_840BD090BD42__INCLUDED_) +// include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#if !defined(AFX_STDAFX_H__9884638E_0AE1_42F8_BFF0_840BD090BD42__INCLUDED_) +#define AFX_STDAFX_H__9884638E_0AE1_42F8_BFF0_840BD090BD42__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers + +#include // MFC core and standard components +#include // MFC extensions +#include // MFC support for Internet Explorer 4 Common Controls +#ifndef _AFX_NO_AFXCMN_SUPPORT +#include // MFC support for Windows Common Controls +#endif // _AFX_NO_AFXCMN_SUPPORT + + + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_STDAFX_H__9884638E_0AE1_42F8_BFF0_840BD090BD42__INCLUDED_) diff --git a/mfc_detect/res/vldmfc.ico b/mfc_detect/res/vldmfc.ico new file mode 100644 index 00000000..d56fbcdf Binary files /dev/null and b/mfc_detect/res/vldmfc.ico differ diff --git a/mfc/res/vldmfc.rc2 b/mfc_detect/res/vldmfc.rc2 similarity index 96% rename from mfc/res/vldmfc.rc2 rename to mfc_detect/res/vldmfc.rc2 index 803d2e47..99777388 100644 --- a/mfc/res/vldmfc.rc2 +++ b/mfc_detect/res/vldmfc.rc2 @@ -1,13 +1,13 @@ -// -// VLDMFC.RC2 - resources Microsoft Visual C++ does not edit directly -// - -#ifdef APSTUDIO_INVOKED - #error this file is not editable by Microsoft Visual C++ -#endif //APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// Add manually edited resources here... - -///////////////////////////////////////////////////////////////////////////// +// +// VLDMFC.RC2 - resources Microsoft Visual C++ does not edit directly +// + +#ifdef APSTUDIO_INVOKED + #error this file is not editable by Microsoft Visual C++ +#endif //APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// Add manually edited resources here... + +///////////////////////////////////////////////////////////////////////////// diff --git a/mfc_detect/resource.h b/mfc_detect/resource.h new file mode 100644 index 00000000..acd9140f --- /dev/null +++ b/mfc_detect/resource.h @@ -0,0 +1,18 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by vldmfc.rc +// +#define IDM_ABOUTBOX 0x0010 +#define IDS_ABOUTBOX 101 +#define IDR_MAINFRAME 128 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 129 +#define _APS_NEXT_COMMAND_VALUE 32771 +#define _APS_NEXT_CONTROL_VALUE 1003 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/mfc_detect/vldmfc.cpp b/mfc_detect/vldmfc.cpp new file mode 100644 index 00000000..7f5c7d87 --- /dev/null +++ b/mfc_detect/vldmfc.cpp @@ -0,0 +1,346 @@ +#include "stdafx.h" +#include "vldmfc.h" + +///////////////////////////////////////////////////////////////////////////// +// CMFCExampleApp + +BEGIN_MESSAGE_MAP(CMFCExampleApp, CWinApp) +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CMFCExampleApp construction + +CMFCExampleApp::CMFCExampleApp() +{ + // TODO: add construction code here, + // Place all significant initialization in InitInstance +} + +///////////////////////////////////////////////////////////////////////////// +// The one and only CMFCExampleApp object + +CMFCExampleApp theApp; + +///////////////////////////////////////////////////////////////////////////// +// CMFCExampleApp initialization +/// Efficiently searches a module's name pointer table (NPT) for the named +/// procedure. +/// +/// @param[in] npt Address of the NPT to search. +/// +/// @param[in] size Number of entries in the NPT. +/// +/// @param[in] base Base address of the module containing the NPT. This is +/// used to resolve addresses in the NPT (which are relative +/// to the module's base address). +/// +/// @param[in] proc String containing the name of the procedure to search +/// for. +/// +/// @return Returns the index into the NPT of the entry matching the named +/// procedure. If no such matching entry exists, the function returns +/// -1. +/// +DWORD FindNptProc (PDWORD npt, DWORD size, PBYTE base, void* proc) +{ + for (DWORD i = 0; i < size; i++) + { + void* p = (void*)(npt[i] + base); + if (p == proc) + return i; + } + + return -1; +} + +/// Gets a pointer to a module's export directory table (EDT). +/// +/// @param[in] module Handle to the module (as returned by GetModuleHandle). +/// +/// @return Returns a pointer to the module's EDT. If there is an error (e.g. +/// if the module handle is invalid or the module has no EDT) the +/// function will return NULL. +/// +PIMAGE_EXPORT_DIRECTORY GetExportDirectoryTable (HMODULE module) +{ + PBYTE base; // base address of module + PIMAGE_FILE_HEADER cfh; // COFF file header + PIMAGE_EXPORT_DIRECTORY edt; // export directory table (EDT) + DWORD rva; // relative virtual address of EDT + PIMAGE_DOS_HEADER mds; // MS-DOS stub + PIMAGE_OPTIONAL_HEADER oh; // so-called "optional" header + PDWORD sig; // PE signature + + // Start at the base of the module. The MS-DOS stub begins there. + base = (PBYTE)module; + mds = (PIMAGE_DOS_HEADER)module; + + // Get the PE signature and verify it. + sig = (DWORD *)(base + mds->e_lfanew); + if (IMAGE_NT_SIGNATURE != *sig) { + // Bad signature -- invalid image or module handle + return NULL; + } + + // Get the COFF file header. + cfh = (PIMAGE_FILE_HEADER)(sig + 1); + + // Get the "optional" header (it's not actually optional for executables). + oh = (PIMAGE_OPTIONAL_HEADER)(cfh + 1); + + // Finally, get the export directory table. + if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh->NumberOfRvaAndSizes) { + // This image doesn't have an export directory table. + return NULL; + } + rva = oh->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; + edt = (PIMAGE_EXPORT_DIRECTORY)(base + rva); + + return edt; +} + +/// Gets the o of an exported procedure. +/// +/// @param[in] module Handle (as returned by GetModuleHandle) of the module +/// that exports the procedure. +/// +/// @param[in] proc String containing the name of the procedure. +/// +/// @return Returns the procedure's o. If an o for the procedure +/// could not be located (e.g. if the named procedure is not exported +/// by the specified module) then the function will return -1. +/// +DWORD GetProcOrdinal (HMODULE module, void* proc) +{ + PBYTE base; // module base address + PIMAGE_EXPORT_DIRECTORY edt; // export directory table (EDT) + DWORD i; // index into NPT and/or EOT + PDWORD npt; // name pointer table (NPT) + + base = (PBYTE)module; + + // Get the export directory table, from which we can find the name pointer + // table and export o table. + edt = GetExportDirectoryTable(module); + + // Get the name pointer table and search it for the named procedure. + _ASSERT(edt->NumberOfFunctions); + npt = (DWORD *)(base + edt->AddressOfFunctions); + i = FindNptProc(npt, edt->NumberOfFunctions, base, proc); + if (-1 == i) { + // The procedure was not found in the module's name pointer table. + return -1; + } + + // Actual o is o from EOT plus "o base" from EDT. + return i + edt->Base; +} + +LPVOID FindRealCode(LPVOID pCode) +{ + LPVOID result = pCode; + if (pCode != NULL) + { + if (*(WORD *) pCode == 0x25ff) + { + DWORD addr = *((DWORD *) ((ULONG_PTR) pCode + 2)); +#ifdef _WIN64 + // RIP relative addressing + PBYTE pNextInst = (PBYTE) ((ULONG_PTR) pCode + 6); + pCode = *(LPVOID*) (pNextInst + addr); + return pCode; +#else + pCode = *(LPVOID*) (addr); + return FindRealCode(pCode); +#endif + } + else if (*(BYTE *) pCode == 0xE9) + { + // Relative next instruction + PBYTE pNextInst = (PBYTE) ((ULONG_PTR) pCode + 5); + LONG offset = *((LONG *) ((ULONG_PTR) pCode + 1)); + pCode = (LPVOID*)(pNextInst + offset); + return FindRealCode(pCode); + } + } + return result; +} + +void SetClipboardText(LPCTSTR pszText) +{ + const size_t len = (_tcslen(pszText) + 1) * sizeof(pszText[0]); + HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len); + memcpy(GlobalLock(hMem), pszText, len); + GlobalUnlock(hMem); + if(OpenClipboard(NULL)) + { + EmptyClipboard(); +#ifndef _UNICODE + HANDLE handle = SetClipboardData(CF_TEXT, hMem); +#else + HANDLE handle = SetClipboardData(CF_UNICODETEXT, hMem); +#endif + CloseClipboard(); + } +} + +#pragma optimize("", off) + +typedef void* (__cdecl *new_t) (size_t); +typedef void* (__cdecl *new_dbg_crt_t) (size_t, int, const char *, int); +typedef void* (__cdecl *new_dbg_mfc_t) (size_t, const char *, int); + +BOOL CMFCExampleApp::InitInstance() +{ + new_t new_array_f = &(::operator new[]); + new_dbg_crt_t new_dbg_crt_array_f = &(::operator new[]); +#ifdef _DEBUG + new_dbg_mfc_t new_dbg_mfc_array_f = &(::operator new[]); +#endif + new_t new_f = &(::operator new); + new_dbg_crt_t new_dbg_crt_f = &(::operator new); +#ifdef _DEBUG + new_dbg_mfc_t new_dbg_mfc_f = &(::operator new); +#endif + + void* p1 = FindRealCode(new_array_f); + void* p2 = FindRealCode(new_dbg_crt_array_f); +#ifdef _DEBUG + void* p3 = FindRealCode(new_dbg_mfc_array_f); +#endif + void* p4 = FindRealCode(new_f); + void* p5 = FindRealCode(new_dbg_crt_f); +#ifdef _DEBUG + void* p6 = FindRealCode(new_dbg_mfc_f); +#endif + +#ifdef _DEBUG +#ifndef _UNICODE +#if _MFC_VER == 0x0700 // VS 2003 +#define MFCDLLNAME _T("mfc70d.dll") +#elif _MFC_VER == 0x0800 // VS 2005 +#define MFCDLLNAME _T("mfc80d.dll") +#elif _MFC_VER == 0x0900 // VS 2008 +#define MFCDLLNAME _T("mfc90d.dll") +#elif _MFC_VER == 0x0A00 // VS 2010 +#define MFCDLLNAME _T("mfc100d.dll") +#elif _MFC_VER == 0x0B00 // VS 2012 +#define MFCDLLNAME _T("mfc110d.dll") +#elif _MFC_VER == 0x0C00 // VS 2013 +#define MFCDLLNAME _T("mfc120d.dll") +#elif _MFC_VER == 0x0D00 +#error MFC version not supported +#elif _MFC_VER == 0x0E00 // VS 2015 +#define MFCDLLNAME _T("mfc140d.dll") +#else +#error MFC version not supported +#endif +#else +#if _MFC_VER == 0x0700 // VS 2003 +#define MFCDLLNAME _T("mfc70ud.dll") +#elif _MFC_VER == 0x0800 // VS 2005 +#define MFCDLLNAME _T("mfc80ud.dll") +#elif _MFC_VER == 0x0900 // VS 2008 +#define MFCDLLNAME _T("mfc90ud.dll") +#elif _MFC_VER == 0x0A00 // VS 2010 +#define MFCDLLNAME _T("mfc100ud.dll") +#elif _MFC_VER == 0x0B00 // VS 2012 +#define MFCDLLNAME _T("mfc110ud.dll") +#elif _MFC_VER == 0x0C00 // VS 2013 +#define MFCDLLNAME _T("mfc120ud.dll") +#elif _MFC_VER == 0x0D00 +#error MFC version not supported +#elif _MFC_VER == 0x0E00 // VS 2015 +#define MFCDLLNAME _T("mfc140ud.dll") +#else +#error MFC version not supported +#endif +#endif +#else +#ifndef _UNICODE +#if _MFC_VER == 0x0700 // VS 2003 +#define MFCDLLNAME _T("mfc70.dll") +#elif _MFC_VER == 0x0800 // VS 2005 +#define MFCDLLNAME _T("mfc80.dll") +#elif _MFC_VER == 0x0900 // VS 2008 +#define MFCDLLNAME _T("mfc90.dll") +#elif _MFC_VER == 0x0A00 // VS 2010 +#define MFCDLLNAME _T("mfc100.dll") +#elif _MFC_VER == 0x0B00 // VS 2012 +#define MFCDLLNAME _T("mfc110.dll") +#elif _MFC_VER == 0x0C00 // VS 2013 +#define MFCDLLNAME _T("mfc120.dll") +#elif _MFC_VER == 0x0D00 +#error MFC version not supported +#elif _MFC_VER == 0x0E00 // VS 2015 +#define MFCDLLNAME _T("mfc140.dll") +#else +#error MFC version not supported +#endif +#else +#if _MFC_VER == 0x0700 // VS 2003 +#define MFCDLLNAME _T("mfc70u.dll") +#elif _MFC_VER == 0x0800 // VS 2005 +#define MFCDLLNAME _T("mfc80u.dll") +#elif _MFC_VER == 0x0900 // VS 2008 +#define MFCDLLNAME _T("mfc90u.dll") +#elif _MFC_VER == 0x0A00 // VS 2010 +#define MFCDLLNAME _T("mfc100u.dll") +#elif _MFC_VER == 0x0B00 // VS 2012 +#define MFCDLLNAME _T("mfc110u.dll") +#elif _MFC_VER == 0x0C00 // VS 2013 +#define MFCDLLNAME _T("mfc120u.dll") +#elif _MFC_VER == 0x0D00 +#error MFC version not supported +#elif _MFC_VER == 0x0E00 // VS 2015 +#define MFCDLLNAME _T("mfc140u.dll") +#else +#error MFC version not supported +#endif +#endif +#endif + + HMODULE module = GetModuleHandle(MFCDLLNAME); + if (NULL == module) + return FALSE; + + int o1 = GetProcOrdinal(module, p1); + int o2 = GetProcOrdinal(module, p2); +#ifdef _DEBUG + int o3 = GetProcOrdinal(module, p3); +#else + int o3 = -2; +#endif + int o4 = GetProcOrdinal(module, p4); + int o5 = GetProcOrdinal(module, p5); +#ifdef _DEBUG + int o6 = GetProcOrdinal(module, p6); +#else + int o6 = -2; +#endif + + TCHAR msg[256]; +#ifdef _UNICODE + #define CHARSET _T(" Unicode") +#elif defined( _MBCS ) + #define CHARSET _T(" MBCS") +#endif +#ifdef _DEBUG + #define CONF _T(" Debug") +#else + #define CONF _T(" Release") +#endif +#ifndef _WIN64 + #define PLATFORM _T(" Win32") +#else + #define PLATFORM _T(" x64") +#endif + TCHAR title[] = _T("MFC ordinals: ") CHARSET CONF PLATFORM; + _stprintf(msg, _T("%d, %d, %d, %d, %d, %d"), + o1, o2, o3, o4, o5, o6); + SetClipboardText(msg); + MessageBox(NULL, msg, title, + MB_ICONINFORMATION | MB_OK); + + return FALSE; +} diff --git a/mfc/vldmfc.h b/mfc_detect/vldmfc.h similarity index 96% rename from mfc/vldmfc.h rename to mfc_detect/vldmfc.h index 133f84bb..9edfd2aa 100644 --- a/mfc/vldmfc.h +++ b/mfc_detect/vldmfc.h @@ -1,46 +1,46 @@ -#if !defined(AFX_VLDMFC_H__9B6C7B98_B322_4E4F_9969_823D500649E9__INCLUDED_) -#define AFX_VLDMFC_H__9B6C7B98_B322_4E4F_9969_823D500649E9__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#ifndef __AFXWIN_H__ - #error include 'stdafx.h' before including this file for PCH -#endif - -#include "resource.h" // main symbols - -///////////////////////////////////////////////////////////////////////////// -// CMFCExampleApp: -// See vldmfc.cpp for the implementation of this class -// - -class CMFCExampleApp : public CWinApp -{ -public: - CMFCExampleApp(); - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CMFCExampleApp) - public: - virtual BOOL InitInstance(); - //}}AFX_VIRTUAL - -// Implementation - - //{{AFX_MSG(CMFCExampleApp) - // NOTE - the ClassWizard will add and remove member functions here. - // DO NOT EDIT what you see in these blocks of generated code ! - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - - -///////////////////////////////////////////////////////////////////////////// - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_VLDMFC_H__9B6C7B98_B322_4E4F_9969_823D500649E9__INCLUDED_) +#if !defined(AFX_VLDMFC_H__9B6C7B98_B322_4E4F_9969_823D500649E9__INCLUDED_) +#define AFX_VLDMFC_H__9B6C7B98_B322_4E4F_9969_823D500649E9__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#ifndef __AFXWIN_H__ + #error include 'stdafx.h' before including this file for PCH +#endif + +#include "resource.h" // main symbols + +///////////////////////////////////////////////////////////////////////////// +// CMFCExampleApp: +// See vldmfc.cpp for the implementation of this class +// + +class CMFCExampleApp : public CWinApp +{ +public: + CMFCExampleApp(); + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CMFCExampleApp) + public: + virtual BOOL InitInstance(); + //}}AFX_VIRTUAL + +// Implementation + + //{{AFX_MSG(CMFCExampleApp) + // NOTE - the ClassWizard will add and remove member functions here. + // DO NOT EDIT what you see in these blocks of generated code ! + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + + +///////////////////////////////////////////////////////////////////////////// + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_VLDMFC_H__9B6C7B98_B322_4E4F_9969_823D500649E9__INCLUDED_) diff --git a/mfc_detect/vldmfc.rc b/mfc_detect/vldmfc.rc new file mode 100644 index 00000000..a5cc45ce --- /dev/null +++ b/mfc_detect/vldmfc.rc @@ -0,0 +1,144 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "#define _AFX_NO_SPLITTER_RESOURCES\r\n" + "#define _AFX_NO_OLE_RESOURCES\r\n" + "#define _AFX_NO_TRACKER_RESOURCES\r\n" + "#define _AFX_NO_PROPERTY_RESOURCES\r\n" + "\r\n" + "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" + "#ifdef _WIN32\r\n" + "LANGUAGE 9, 1\r\n" + "#pragma code_page(1252)\r\n" + "#endif //_WIN32\r\n" + "#include ""res\\vldmfc.rc2"" // non-Microsoft Visual C++ edited resources\r\n" + "#include ""afxres.rc"" // Standard components\r\n" + "#endif\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDR_MAINFRAME ICON "res\\vldmfc.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,1,1 + PRODUCTVERSION 1,0,1,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "Comments", "This software is copyright (c) 2005 Dan Moulding and is distributed under the terms of the GNU Lesser Public License" + VALUE "FileDescription", "Visual Leak Detector MFC Example" + VALUE "FileVersion", "1, 0, 1, 1" + VALUE "InternalName", "vldmfc" + VALUE "LegalCopyright", "Copyright (C) 2005" + VALUE "OriginalFilename", "vldmfc.exe" + VALUE "ProductName", "Visual Leak Detector MFC Example" + VALUE "ProductVersion", "1, 0, 1, 1" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE +BEGIN + IDS_ABOUTBOX "&About Visual Leak Detector MFC Example..." +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#define _AFX_NO_SPLITTER_RESOURCES +#define _AFX_NO_OLE_RESOURCES +#define _AFX_NO_TRACKER_RESOURCES +#define _AFX_NO_PROPERTY_RESOURCES + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE 9, 1 +#pragma code_page(1252) +#endif //_WIN32 +#include "res\vldmfc.rc2" // non-Microsoft Visual C++ edited resources +#include "afxres.rc" // Standard components +#endif + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/mfc_detect/vldmfc_detect.sln b/mfc_detect/vldmfc_detect.sln new file mode 100644 index 00000000..482d5ced --- /dev/null +++ b/mfc_detect/vldmfc_detect.sln @@ -0,0 +1,26 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vldmfc_detect", "vldmfc_detect.vcproj", "{A231973E-072A-428E-982E-5363ADD1CDE2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug (Unicode)|Win32 = Debug (Unicode)|Win32 + Debug (Unicode)|x64 = Debug (Unicode)|x64 + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|Win32.ActiveCfg = Debug (Unicode)|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|Win32.Build.0 = Debug (Unicode)|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|x64.ActiveCfg = Release|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|x64.Build.0 = Release|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.ActiveCfg = Debug|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.Build.0 = Debug|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|x64.ActiveCfg = Debug|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|x64.Build.0 = Debug|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/mfc_detect/vldmfc_detect.vcxproj b/mfc_detect/vldmfc_detect.vcxproj new file mode 100644 index 00000000..55baf70e --- /dev/null +++ b/mfc_detect/vldmfc_detect.vcxproj @@ -0,0 +1,620 @@ + + + + + Debug (Unicode) + Win32 + + + Debug (Unicode) + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release (Unicode) + Win32 + + + Release (Unicode) + x64 + + + Release + Win32 + + + Release + x64 + + + + {A231973E-072A-428E-982E-5363ADD1CDE2} + MFCProj + 8.1 + + + + Application + Dynamic + Unicode + v140 + + + Application + Dynamic + MultiByte + v140 + + + Application + Dynamic + MultiByte + v140 + + + Application + Dynamic + Unicode + v140 + + + Application + Dynamic + Unicode + v140 + + + Application + Dynamic + MultiByte + v140 + + + Application + Dynamic + MultiByte + v140 + + + Application + Dynamic + Unicode + v140 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + false + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + false + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(Configuration)\ + $(Configuration)\ + true + $(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + AllRules.ruleset + + + + + AllRules.ruleset + AllRules.ruleset + + + + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Win32 + .\Release/vldmfc.tlb + + + + + MaxSpeed + OnlyExplicitInline + ..\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + MultiThreadedDLL + Use + stdafx.h + $(IntDir)$(TargetName).pch + $(IntDir) + $(IntDir) + $(IntDir) + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)$(ProjectName).exe + true + ..\Release;%(AdditionalLibraryDirectories) + $(TargetDir)$(TargetName).pdb + Windows + false + + + MachineX86 + true + + + true + .\Release/vldmfc.bsc + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Win32 + .\Release/vldmfc.tlb + + + + + MaxSpeed + OnlyExplicitInline + ..\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + MultiThreadedDLL + Use + stdafx.h + $(IntDir)$(TargetName).pch + $(IntDir) + $(IntDir) + $(IntDir) + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)$(ProjectName).exe + true + ..\Release;%(AdditionalLibraryDirectories) + $(TargetDir)$(TargetName).pdb + Windows + false + + + MachineX86 + true + + + true + .\Release/vldmfc.bsc + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + X64 + .\Release/vldmfc.tlb + + + + + MaxSpeed + OnlyExplicitInline + ..\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + MultiThreadedDLL + Use + stdafx.h + $(IntDir)$(TargetName).pch + $(IntDir) + $(IntDir) + $(IntDir) + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)$(ProjectName).exe + true + ..\Release;%(AdditionalLibraryDirectories) + $(TargetDir)$(TargetName).pdb + Windows + false + + + MachineX64 + true + + + true + .\Release/vldmfc.bsc + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + X64 + .\Release/vldmfc.tlb + + + + + MaxSpeed + OnlyExplicitInline + ..\;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + MultiThreadedDLL + Use + stdafx.h + $(IntDir)$(TargetName).pch + $(IntDir) + $(IntDir) + $(IntDir) + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)$(ProjectName).exe + true + ..\Release;%(AdditionalLibraryDirectories) + $(TargetDir)$(TargetName).pdb + Windows + false + + + MachineX64 + true + + + true + .\Release/vldmfc.bsc + + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + Win32 + .\Debug/vldmfc.tlb + + + + + Disabled + ..\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + Use + stdafx.h + $(IntDir)$(TargetName).pch + $(IntDir) + $(IntDir) + $(IntDir) + Level3 + true + EditAndContinue + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)$(ProjectName).exe + true + ..\Debug;%(AdditionalLibraryDirectories) + true + $(TargetDir)$(TargetName).pdb + Windows + false + + + MachineX86 + + + true + .\Debug/vldmfc.bsc + + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + X64 + .\Debug/vldmfc.tlb + + + + + Disabled + ..\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + Use + stdafx.h + $(IntDir)$(TargetName).pch + $(IntDir) + $(IntDir) + $(IntDir) + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)$(ProjectName).exe + true + ..\Debug;%(AdditionalLibraryDirectories) + true + $(TargetDir)$(TargetName).pdb + Windows + false + + + MachineX64 + + + true + .\Debug/vldmfc.bsc + + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + Win32 + .\Debug/vldmfc.tlb + + + + + Disabled + ..\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + Use + stdafx.h + $(IntDir)$(TargetName).pch + $(IntDir) + $(IntDir) + $(IntDir) + Level3 + true + EditAndContinue + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)$(ProjectName).exe + true + ..\Debug;%(AdditionalLibraryDirectories) + true + $(TargetDir)$(TargetName).pdb + Windows + false + + + MachineX86 + + + true + .\Debug/vldmfc.bsc + + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + X64 + .\Debug/vldmfc.tlb + + + + + Disabled + ..\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + Use + stdafx.h + $(IntDir)$(TargetName).pch + $(IntDir) + $(IntDir) + $(IntDir) + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)$(ProjectName).exe + true + ..\Debug;%(AdditionalLibraryDirectories) + true + $(TargetDir)$(TargetName).pdb + Windows + false + + + MachineX64 + + + true + .\Debug/vldmfc.bsc + + + + + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + Create + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + Create + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + Create + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + Create + %(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + Create + Create + %(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + Create + Create + + + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + + + + + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/mfc_detect/vldmfc_detect.vcxproj.filters b/mfc_detect/vldmfc_detect.vcxproj.filters new file mode 100644 index 00000000..a065821f --- /dev/null +++ b/mfc_detect/vldmfc_detect.vcxproj.filters @@ -0,0 +1,49 @@ + + + + + {ee1a072e-69ee-4e6d-b044-911ae029bbeb} + cpp;c;cxx;rc;def;r;odl;idl;hpj;bat + + + {ab9a8a11-b14d-470f-a7c5-88b379d3e731} + h;hpp;hxx;hm;inl + + + {65ba1fde-89d1-4036-9a69-3cfddfdc7de5} + ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + Source Files + + + Source Files + + + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + + + Resource Files + + + Resource Files + + + \ No newline at end of file diff --git a/mfc_detect/vldmfc_detect_vs10.sln b/mfc_detect/vldmfc_detect_vs10.sln new file mode 100644 index 00000000..ab163466 --- /dev/null +++ b/mfc_detect/vldmfc_detect_vs10.sln @@ -0,0 +1,38 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vldmfc_detect", "vldmfc_detect.vcxproj", "{A231973E-072A-428E-982E-5363ADD1CDE2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug (Unicode)|Win32 = Debug (Unicode)|Win32 + Debug (Unicode)|x64 = Debug (Unicode)|x64 + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release (Unicode)|Win32 = Release (Unicode)|Win32 + Release (Unicode)|x64 = Release (Unicode)|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|Win32.ActiveCfg = Debug (Unicode)|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|Win32.Build.0 = Debug (Unicode)|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|x64.ActiveCfg = Debug (Unicode)|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|x64.Build.0 = Debug (Unicode)|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.ActiveCfg = Debug|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.Build.0 = Debug|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|x64.ActiveCfg = Debug|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|x64.Build.0 = Debug|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release (Unicode)|Win32.ActiveCfg = Release (Unicode)|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release (Unicode)|Win32.Build.0 = Release (Unicode)|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release (Unicode)|x64.ActiveCfg = Release (Unicode)|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release (Unicode)|x64.Build.0 = Release (Unicode)|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|Win32.ActiveCfg = Release|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|Win32.Build.0 = Release|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|x64.ActiveCfg = Release|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/mfc_detect/vldmfc_detect_vs11.sln b/mfc_detect/vldmfc_detect_vs11.sln new file mode 100644 index 00000000..74958d5e --- /dev/null +++ b/mfc_detect/vldmfc_detect_vs11.sln @@ -0,0 +1,38 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vldmfc_detect", "vldmfc_detect.vcxproj", "{A231973E-072A-428E-982E-5363ADD1CDE2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug (Unicode)|Win32 = Debug (Unicode)|Win32 + Debug (Unicode)|x64 = Debug (Unicode)|x64 + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release (Unicode)|Win32 = Release (Unicode)|Win32 + Release (Unicode)|x64 = Release (Unicode)|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|Win32.ActiveCfg = Debug (Unicode)|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|Win32.Build.0 = Debug (Unicode)|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|x64.ActiveCfg = Debug (Unicode)|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|x64.Build.0 = Debug (Unicode)|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.ActiveCfg = Debug|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.Build.0 = Debug|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|x64.ActiveCfg = Debug|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|x64.Build.0 = Debug|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release (Unicode)|Win32.ActiveCfg = Release (Unicode)|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release (Unicode)|Win32.Build.0 = Release (Unicode)|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release (Unicode)|x64.ActiveCfg = Release (Unicode)|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release (Unicode)|x64.Build.0 = Release (Unicode)|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|Win32.ActiveCfg = Release|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|Win32.Build.0 = Release|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|x64.ActiveCfg = Release|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/mfc_detect/vldmfc_detect_vs14.sln b/mfc_detect/vldmfc_detect_vs14.sln new file mode 100644 index 00000000..a0e37a79 --- /dev/null +++ b/mfc_detect/vldmfc_detect_vs14.sln @@ -0,0 +1,40 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vldmfc_detect", "vldmfc_detect.vcxproj", "{A231973E-072A-428E-982E-5363ADD1CDE2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug (Unicode)|Win32 = Debug (Unicode)|Win32 + Debug (Unicode)|x64 = Debug (Unicode)|x64 + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release (Unicode)|Win32 = Release (Unicode)|Win32 + Release (Unicode)|x64 = Release (Unicode)|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|Win32.ActiveCfg = Debug (Unicode)|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|Win32.Build.0 = Debug (Unicode)|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|x64.ActiveCfg = Debug (Unicode)|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug (Unicode)|x64.Build.0 = Debug (Unicode)|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.ActiveCfg = Debug|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.Build.0 = Debug|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|x64.ActiveCfg = Debug|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|x64.Build.0 = Debug|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release (Unicode)|Win32.ActiveCfg = Release (Unicode)|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release (Unicode)|Win32.Build.0 = Release (Unicode)|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release (Unicode)|x64.ActiveCfg = Release (Unicode)|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release (Unicode)|x64.Build.0 = Release (Unicode)|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|Win32.ActiveCfg = Release|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|Win32.Build.0 = Release|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|x64.ActiveCfg = Release|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/setup/COPYING.txt b/setup/COPYING.txt deleted file mode 100644 index 82fa1daa..00000000 --- a/setup/COPYING.txt +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/setup/WizSmallImage.bmp b/setup/WizSmallImage.bmp new file mode 100644 index 00000000..c9191cb5 Binary files /dev/null and b/setup/WizSmallImage.bmp differ diff --git a/setup/build_version.bat b/setup/build_version.bat new file mode 100644 index 00000000..c2dfaa05 --- /dev/null +++ b/setup/build_version.bat @@ -0,0 +1,80 @@ +@ECHO OFF + +TITLE Building VLD... + +SETLOCAL ENABLEDELAYEDEXPANSION + +REM Check if the needed files are present +IF "%VS140COMNTOOLS%"=="" GOTO :BadPaths + +CD %~dp0/.. + +GOTO :GoodPaths + +:BadPaths +ECHO: "Not all build dependencies found. To build VLD you need:" +ECHO: "* Visual Studio 2015 installed" +PAUSE +GOTO :EndGood + +:GoodPaths +SET ProgFiles=%ProgramFiles% +IF /i "%PROCESSOR_ARCHITECTURE%" == "AMD64" SET ProgFiles=%ProgramFiles(x86)% + +SET BUILDTYPE=/%1 +IF "%1"=="" SET BUILDTYPE=/rebuild +rem IF "%1"=="build" SET BUILDTYPE= + +SET ORIGPATH="%CD%" +CALL "%VS140COMNTOOLS%vsvars32.bat" +CD %ORIGPATH% + +:: Store start time +FOR /f "tokens=1-4 delims=:.," %%T IN ("%TIME%") DO ( + SET StartTIME=%TIME% + :: Fix leading zero problem + SET /a Start100S=%%T*360000+1%%U*6000+1%%V*100+1%%W - 610100 +) + +devenv /nologo vld_vs14.sln %BUILDTYPE% "Release|Win32" /Project vld +IF %ERRORLEVEL% NEQ 0 GOTO EndBad +devenv /nologo vld_vs14.sln %BUILDTYPE% "Release|x64" /Project vld +IF %ERRORLEVEL% NEQ 0 GOTO EndBad + +if not exist "%ProgFiles%\Inno Setup 5\ISCC.exe" GOTO EndBad +"%ProgFiles%\Inno Setup 5\ISCC.exe" setup\vld-setup.iss +IF %ERRORLEVEL% NEQ 0 GOTO EndBad +CD setup + +ECHO  + +:: Retrieve Stop time +FOR /f "tokens=1-4 delims=:.," %%T IN ("%TIME%") DO ( + SET StopTIME=%TIME% + :: Fix leading zero problem + SET /a Stop100S=%%T*360000+1%%U*6000+1%%V*100+1%%W - 610100 +) + +:: Test midnight rollover. If so, add 1 day=8640000 1/100ths secs +IF %Stop100S% LSS %Start100S% SET /a Stop100S+=8640000 +SET /a TookTimeSec=(%Stop100S%-%Start100S%)/100 +SET /a TookTimeMin=TookTimeSec/60 +SET /a TookTimeSec=%TookTimeSec%-%TookTimeMin%*60 + +ECHO Started: %StartTime% +ECHO Stopped: %StopTime% +ECHO Elapsed: %TookTimeMin% min. %TookTimeSec% sec. + +PAUSE + +GOTO :EndGood + +:EndBad +CD setup +ECHO: " " +ECHO: ERROR: Build failed and aborted +PAUSE +GOTO :EOF + +:EndGood +GOTO :EOF \ No newline at end of file diff --git a/Microsoft.DTfW.DHL.manifest b/setup/dbghelp/x64/Microsoft.DTfW.DHL.manifest similarity index 82% rename from Microsoft.DTfW.DHL.manifest rename to setup/dbghelp/x64/Microsoft.DTfW.DHL.manifest index 55dc5d9c..1ea64d51 100644 --- a/Microsoft.DTfW.DHL.manifest +++ b/setup/dbghelp/x64/Microsoft.DTfW.DHL.manifest @@ -1,7 +1,7 @@ - - - - - - - + + + + + + + diff --git a/setup/dbghelp/x64/dbghelp.dll b/setup/dbghelp/x64/dbghelp.dll new file mode 100644 index 00000000..499fa290 Binary files /dev/null and b/setup/dbghelp/x64/dbghelp.dll differ diff --git a/setup/dbghelp/x86/Microsoft.DTfW.DHL.manifest b/setup/dbghelp/x86/Microsoft.DTfW.DHL.manifest new file mode 100644 index 00000000..e61222f0 --- /dev/null +++ b/setup/dbghelp/x86/Microsoft.DTfW.DHL.manifest @@ -0,0 +1,7 @@ + + + + + + + diff --git a/setup/dbghelp/x86/dbghelp.dll b/setup/dbghelp/x86/dbghelp.dll new file mode 100644 index 00000000..62d85086 Binary files /dev/null and b/setup/dbghelp/x86/dbghelp.dll differ diff --git a/setup/license-free.txt b/setup/license-free.txt index 32cb5cd6..96c15404 100755 --- a/setup/license-free.txt +++ b/setup/license-free.txt @@ -1,24 +1,24 @@ -Anybody may use Visual Leak Detector (this software). No license is required -to use it and you are not asked (or required) to accept any terms or conditions -before using it. - -Provided that you have received a legal copy of this software, you are the -owner of the copy that you have been given. Accordingly, the publisher of this -software has no authority to prevent you from using the software. In the -United States, your legal right to use this copy of software is codified in -17 USC Sec. 117. This statute allows you to use any software you own, without -special permission from the publisher, even if you must make incidental copies -(e.g. in RAM or on a hard disk) in order to use it. - -The publisher of this software still retains the copyright in the software. -As such, you may not make additional copies of the software without permission -from the publisher. - -The publisher grants you the right to copy and distribute this software -on the condition that you agree to the terms contained in the license file -(COPYING.txt) that accompanies this software. To be clear: you are not being -asked to agree to the terms in the license file if you simply wish to use this -software. You must agree to the license only if you wish to copy, distribute, -or make derivative works of, this software. - +Anybody may use Visual Leak Detector (this software). No license is required +to use it and you are not asked (or required) to accept any terms or conditions +before using it. + +Provided that you have received a legal copy of this software, you are the +owner of the copy that you have been given. Accordingly, the publisher of this +software has no authority to prevent you from using the software. In the +United States, your legal right to use this copy of software is codified in +17 USC Sec. 117. This statute allows you to use any software you own, without +special permission from the publisher, even if you must make incidental copies +(e.g. in RAM or on a hard disk) in order to use it. + +The publisher of this software still retains the copyright in the software. +As such, you may not make additional copies of the software without permission +from the publisher. + +The publisher grants you the right to copy and distribute this software +on the condition that you agree to the terms contained in the license file +(COPYING.txt) that accompanies this software. To be clear: you are not being +asked to agree to the terms in the license file if you simply wish to use this +software. You must agree to the license only if you wish to copy, distribute, +or make derivative works of, this software. + To learn more, visit: http://soldnotlicensed.blogspot.com \ No newline at end of file diff --git a/setup/modpath.iss b/setup/modpath.iss new file mode 100644 index 00000000..3a2e6c7c --- /dev/null +++ b/setup/modpath.iss @@ -0,0 +1,169 @@ +// ---------------------------------------------------------------------------- +// +// Inno Setup Ver: 5.4.2 +// Script Version: 1.4.2 +// Author: Jared Breland +// Homepage: http://www.legroom.net/software +// License: GNU Lesser General Public License (LGPL), version 3 +// http://www.gnu.org/licenses/lgpl.html +// +// Script Function: +// Allow modification of environmental path directly from Inno Setup installers +// +// Instructions: +// Copy modpath.iss to the same directory as your setup script +// +// Add this statement to your [Setup] section +// ChangesEnvironment=true +// +// Add this statement to your [Tasks] section +// You can change the Description or Flags +// You can change the Name, but it must match the ModPathName setting below +// Name: modifypath; Description: &Add application directory to your environmental path; Flags: unchecked +// +// Add the following to the end of your [Code] section +// ModPathName defines the name of the task defined above +// ModPathType defines whether the 'user' or 'system' path will be modified; +// this will default to user if anything other than system is set +// setArrayLength must specify the total number of dirs to be added +// Result[0] contains first directory, Result[1] contains second, etc. +// const +// ModPathName = 'modifypath'; +// ModPathType = 'user'; +// +// function ModPathDir(): TArrayOfString; +// begin +// setArrayLength(Result, 1); +// Result[0] := ExpandConstant('{app}'); +// end; +// #include "modpath.iss" +// ---------------------------------------------------------------------------- + +procedure ModPath(); +var + oldpath: String; + newpath: String; + updatepath: Boolean; + pathArr: TArrayOfString; + aExecFile: String; + aExecArr: TArrayOfString; + i, d: Integer; + pathdir: TArrayOfString; + regroot: Integer; + regpath: String; + +begin + // Get constants from main script and adjust behavior accordingly + // ModPathType MUST be 'system' or 'user'; force 'user' if invalid + if ModPathType = 'system' then begin + regroot := HKEY_LOCAL_MACHINE; + regpath := 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'; + end else begin + regroot := HKEY_CURRENT_USER; + regpath := 'Environment'; + end; + + // Get array of new directories and act on each individually + pathdir := ModPathDir(); + for d := 0 to GetArrayLength(pathdir)-1 do begin + updatepath := true; + + // Get current path, split into an array + RegQueryStringValue(regroot, regpath, 'Path', oldpath); + oldpath := oldpath + ';'; + i := 0; + + while (Pos(';', oldpath) > 0) do begin + SetArrayLength(pathArr, i+1); + pathArr[i] := Copy(oldpath, 0, Pos(';', oldpath)-1); + oldpath := Copy(oldpath, Pos(';', oldpath)+1, Length(oldpath)); + i := i + 1; + + // Check if current directory matches app dir + if pathdir[d] = pathArr[i-1] then begin + // if uninstalling, remove dir from path + if IsUninstaller() = true then begin + continue; + // if installing, flag that dir already exists in path + end else begin + updatepath := false; + end; + end; + + // Add current directory to new path + if i = 1 then begin + newpath := pathArr[i-1]; + end else begin + newpath := newpath + ';' + pathArr[i-1]; + end; + end; + + // Append app dir to path if not already included + if (IsUninstaller() = false) AND (updatepath = true) then + newpath := newpath + ';' + pathdir[d]; + + // Write new path + RegWriteStringValue(regroot, regpath, 'Path', newpath); + end; +end; + +// Split a string into an array using passed delimeter +procedure MPExplode(var Dest: TArrayOfString; Text: String; Separator: String); +var + i: Integer; +begin + i := 0; + repeat + SetArrayLength(Dest, i+1); + if Pos(Separator,Text) > 0 then begin + Dest[i] := Copy(Text, 1, Pos(Separator, Text)-1); + Text := Copy(Text, Pos(Separator,Text) + Length(Separator), Length(Text)); + i := i + 1; + end else begin + Dest[i] := Text; + Text := ''; + end; + until Length(Text)=0; +end; + +procedure CurStepChangedModPath(CurStep: TSetupStep); +var + taskname: String; +begin + taskname := ModPathName; + if CurStep = ssPostInstall then + if IsTaskSelected(taskname) then + ModPath(); +end; + +procedure CurUninstallStepChangedModPath(CurUninstallStep: TUninstallStep); +var + aSelectedTasks: TArrayOfString; + i: Integer; + taskname: String; + regpath: String; + regstring: String; + appid: String; +begin + // only run during actual uninstall + if CurUninstallStep = usUninstall then begin + // get list of selected tasks saved in registry at install time + appid := '{#emit SetupSetting("AppId")}'; + if appid = '' then appid := '{#emit SetupSetting("AppName")}'; + regpath := ExpandConstant('Software\Microsoft\Windows\CurrentVersion\Uninstall\'+appid+'_is1'); + RegQueryStringValue(HKLM, regpath, 'Inno Setup: Selected Tasks', regstring); + if regstring = '' then RegQueryStringValue(HKCU, regpath, 'Inno Setup: Selected Tasks', regstring); + + // check each task; if matches modpath taskname, trigger patch removal + if regstring <> '' then begin + taskname := ModPathName; + MPExplode(aSelectedTasks, regstring, ','); + if GetArrayLength(aSelectedTasks) > 0 then begin + for i := 0 to GetArrayLength(aSelectedTasks)-1 do begin + if comparetext(aSelectedTasks[i], taskname) = 0 then + ModPath(); + end; + end; + end; + end; +end; diff --git a/setup/version.h b/setup/version.h new file mode 100644 index 00000000..ef96d44f --- /dev/null +++ b/setup/version.h @@ -0,0 +1,9 @@ + +#define VLDVERSION L"2.5.1" +#define VERSION_NUMBER 2,5,1,0 +#define VERSION_STRING "2.5.1.0" +#define VERSION_COPYRIGHT "Copyright (C) 2005-2017" + +#ifndef __FILE__ +!define VLD_VERSION "2.5.1" // NSIS Script +#endif diff --git a/setup/vld-setup.iss b/setup/vld-setup.iss new file mode 100644 index 00000000..43cb32fe --- /dev/null +++ b/setup/vld-setup.iss @@ -0,0 +1,461 @@ +; Script generated by the Inno Setup Script Wizard. +; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES! + +#define MyAppName "Visual Leak Detector" +#define MyAppVersion "2.5.1" +#define MyAppPublisher "VLD Team" +#define MyAppURL "http://vld.codeplex.com/" +#define MyAppRegKey "Software\Visual Leak Detector" + +[Setup] +; NOTE: The value of AppId uniquely identifies this application. +; Do not use the same AppId value in installers for other applications. +; (To generate a new GUID, click Tools | Generate GUID inside the IDE.) +AppId={{851FBFF7-5148-40A2-A654-942BE80F5B90} +AppName={#MyAppName} +AppVersion={#MyAppVersion} +;AppVerName={#MyAppName} {#MyAppVersion} +AppPublisher={#MyAppPublisher} +AppPublisherURL={#MyAppURL} +AppSupportURL={#MyAppURL} +AppUpdatesURL={#MyAppURL} +DefaultDirName={reg:HKLM\{#MyAppRegKey},InstallPath|{pf}\{#MyAppName}} +DefaultGroupName={#MyAppName} +LicenseFile=license-free.txt +OutputBaseFilename=vld-{#MyAppVersion}-setup +Compression=lzma +SolidCompression=True +MinVersion=0,5.01 +; Tell Windows Explorer to reload the environment +ChangesEnvironment=yes +AllowNoIcons=yes +DisableDirPage=auto +DirExistsWarning=no +WizardImageFile=compiler:WizModernImage-IS.bmp +WizardSmallImageFile=WizSmallImage.bmp + +[Languages] +Name: "english"; MessagesFile: "compiler:Default.isl" + +[Icons] +Name: "{group}\View Documentation"; Filename: "http://vld.codeplex.com/documentation" + +[Files] +Source: "dbghelp\x64\dbghelp.dll"; DestDir: "{app}\bin\Win64"; Flags: ignoreversion +Source: "dbghelp\x64\Microsoft.DTfW.DHL.manifest"; DestDir: "{app}\bin\Win64"; Flags: ignoreversion +Source: "dbghelp\x86\dbghelp.dll"; DestDir: "{app}\bin\Win32"; Flags: ignoreversion +Source: "dbghelp\x86\Microsoft.DTfW.DHL.manifest"; DestDir: "{app}\bin\Win32"; Flags: ignoreversion +Source: "..\src\bin\Win32\Release-v140\vld.lib"; DestDir: "{app}\lib\Win32"; Flags: ignoreversion +Source: "..\src\bin\Win32\Release-v140\vld_x86.dll"; DestDir: "{app}\bin\Win32"; Flags: ignoreversion +Source: "..\src\bin\Win32\Release-v140\vld_x86.pdb"; DestDir: "{app}\bin\Win32"; Flags: ignoreversion +Source: "..\src\bin\x64\Release-v140\vld.lib"; DestDir: "{app}\lib\Win64"; Flags: ignoreversion +Source: "..\src\bin\x64\Release-v140\vld_x64.dll"; DestDir: "{app}\bin\Win64"; Flags: ignoreversion +Source: "..\src\bin\x64\Release-v140\vld_x64.pdb"; DestDir: "{app}\bin\Win64"; Flags: ignoreversion +Source: "..\src\vld.h"; DestDir: "{app}\include"; Flags: ignoreversion +Source: "..\src\vld_def.h"; DestDir: "{app}\include"; Flags: ignoreversion +Source: "..\vld.ini"; DestDir: "{app}"; Flags: ignoreversion +Source: "..\AUTHORS.txt"; DestDir: "{app}"; Flags: ignoreversion +Source: "..\CHANGES.txt"; DestDir: "{app}"; Flags: ignoreversion +Source: "..\COPYING.txt"; DestDir: "{app}"; Flags: ignoreversion + +[Tasks] +Name: "modifypath"; Description: "Add VLD directory to your environmental path" +Name: "modifyVS2008Props"; Description: "Add VLD directory to VS 2008" +Name: "modifyVS2010Props"; Description: "Add VLD directory to VS 2010 - VS 2015" + +[ThirdParty] +UseRelativePaths=True + +[Registry] +Root: "HKLM32"; Subkey: "{#MyAppRegKey}"; Flags: uninsdeletekeyifempty +Root: "HKLM32"; Subkey: "{#MyAppRegKey}"; ValueType: string; ValueName: "InstalledVersion"; ValueData: "{#MyAppVersion}" +Root: "HKLM32"; Subkey: "{#MyAppRegKey}"; ValueType: string; ValueName: "InstallPath"; ValueData: "{app}" +Root: "HKLM32"; Subkey: "{#MyAppRegKey}"; ValueType: string; ValueName: "IniFile"; ValueData: "{app}\vld.ini" + +Root: "HKLM64"; Subkey: "{#MyAppRegKey}"; Flags: uninsdeletekeyifempty +Root: "HKLM64"; Subkey: "{#MyAppRegKey}"; ValueType: string; ValueName: "InstalledVersion"; ValueData: "{#MyAppVersion}" +Root: "HKLM64"; Subkey: "{#MyAppRegKey}"; ValueType: string; ValueName: "InstallPath"; ValueData: "{app}" +Root: "HKLM64"; Subkey: "{#MyAppRegKey}"; ValueType: string; ValueName: "IniFile"; ValueData: "{app}\vld.ini" + +[Code] +type + TKey = string; + TValue = string; + TKeyValue = record + Key: TKey; + Value: TValue; + end; + TKeyValueList = array of TKeyValue; + +const + ModPathName = 'modifypath'; + ModPathType = 'system'; + +function ModPathDir(): TArrayOfString; +begin + setArrayLength(Result, 2); + Result[0] := ExpandConstant('{app}\bin\Win32'); + Result[1] := ExpandConstant('{app}\bin\Win64'); +end; + +#include "modpath.iss" + +function GetUninstallString(regPath: string): String; +var + sUnInstPath: String; + sUnInstString: String; +begin + sUnInstPath := ExpandConstant(regPath); + sUnInstString := ''; + if not RegQueryStringValue(HKLM, sUnInstPath, 'UninstallString', sUnInstString) then + RegQueryStringValue(HKCU, sUnInstPath, 'UninstallString', sUnInstString); + Result := sUnInstString; +end; + +function UninstallOldVersion(regPath: string; params: string): Boolean; +var + iResultCode: Integer; +begin + // default return value + Result := False; + + if SuppressibleMsgBox('VLD is already installed. Uninstall the current version?', + mbConfirmation, MB_YESNO, IDYES) = IDYES then + begin + regPath := RemoveQuotes(regPath); + if Exec(regPath, params,'', SW_HIDE, ewWaitUntilTerminated, iResultCode) then + Result := True; + end +end; + +function UninstallOldVersions(): Boolean; +var + nsisUnInstallString: String; + isUnInstallString: String; +begin + nsisUnInstallString := GetUninstallString('Software\Microsoft\Windows\CurrentVersion\Uninstall\Visual Leak Detector'); + isUnInstallString := GetUninstallString('Software\Microsoft\Windows\CurrentVersion\Uninstall\{#emit SetupSetting("AppId")}_is1'); + Result := True; + if (nsisUnInstallString <> '') then + begin + Result := UninstallOldVersion(nsisUnInstallString, '/S'); + end + else if (isUnInstallString <> '') then + begin + Result := UninstallOldVersion(isUnInstallString, '/SILENT /NORESTART /SUPPRESSMSGBOXES'); + end; +end; + +function Count(What, Where: String): Integer; +begin + Result := 0; + if Length(What) = 0 then + exit; + while Pos(What,Where)>0 do + begin + Where := Copy(Where,Pos(What,Where)+Length(What),Length(Where)); + Result := Result + 1; + end; +end; + +procedure Explode(var ADest: TKeyValueList; aText, aSeparator: String); +var tmp: Integer; + item: TKeyValue; +begin + SetArrayLength(ADest, (Count(aSeparator,aText) / 2) + 1); + tmp := 0; + repeat + item.Key := ''; + item.Value := ''; + if Pos(aSeparator,aText)>0 then + begin + item.Key := Copy(aText,1,Pos(aSeparator,aText)-1); + aText := Copy(aText,Pos(aSeparator,aText)+Length(aSeparator),Length(aText)); + end else + begin + item.Key := aText; + aText := ''; + end; + if Pos(aSeparator,aText)>0 then + begin + item.Value := Copy(aText,1,Pos(aSeparator,aText)-1); + aText := Copy(aText,Pos(aSeparator,aText)+Length(aSeparator),Length(aText)); + end else + begin + item.Value := aText; + aText := ''; + end; + ADest[tmp] := item; + tmp := tmp + 1; + until Length(aText)=0; +end; + +function Merge(ADest: TKeyValueList; aSeparator: String): String; +var i, n, l: Integer; + str: String; +begin + n := GetArrayLength(ADest); + l := n + (n - 1); + if l < 0 then l := 0; + Result := ''; + for i := 0 to n - 1 do + begin + str := ADest[i].Key + aSeparator + ADest[i].Value; + Result := Result + str; + if i < n - 1 then Result := Result + aSeparator; + end; +end; + +function UpdatePath(dirList: String; path: String): String; +begin + if dirList = '' then + Result := path + else if Pos(path, dirList) = 0 then + Result := path + ';' + dirList + else + Result := dirList; +end; + +procedure UpdatePaths(var dirList: string; path32: string; path64: string); +var map: TKeyValueList; + i: Integer; +begin + Explode(map, dirList, '|'); + for i := 0 to GetArrayLength(map) - 1 do + begin + if map[i].Key = 'Win32' then map[i].Value := UpdatePath(map[i].Value, path32) + else if map[i].Key = 'x64' then map[i].Value := UpdatePath(map[i].Value, path64); + end; + dirList := Merge(map, '|'); + Log(dirList); +end; + +procedure ModifySettings(filename: string); +var + XMLDocument: Variant; + XMLParent, XMLNode, XMLNodes: Variant; + IncludeDirectoriesNode: Variant; + AdditionalIncludeDirectories: string; + LibraryDirectoriesNode: Variant; + AdditionalLibraryDirectories: string; + libfolder: string; +begin + XMLDocument := CreateOleObject('Msxml2.DOMDocument.3.0'); + try + XMLDocument.async := False; + XMLDocument.load(filename); + if (XMLDocument.parseError.errorCode = 0) then + begin + XMLDocument.setProperty('SelectionLanguage', 'XPath'); + XMLNodes := XMLDocument.SelectNodes('//UserSettings/ToolsOptions/ToolsOptionsCategory[@name="Projects"]/ToolsOptionsSubCategory[@name="VCDirectories"]'); + if XMLNodes.Length = 0 then + Exit; + XMLParent := XMLNodes.Item[0]; + XMLNodes := XMLParent.SelectNodes('//PropertyValue[@name="LibraryDirectories"]'); + if XMLNodes.Length > 0 then + LibraryDirectoriesNode := XMLNodes.Item[0]; + XMLNodes := XMLParent.SelectNodes('//PropertyValue[@name="IncludeDirectories"]'); + if XMLNodes.Length > 0 then + IncludeDirectoriesNode := XMLNodes.Item[0]; + AdditionalIncludeDirectories := ''; + if not VarIsNull(IncludeDirectoriesNode) then + AdditionalIncludeDirectories := IncludeDirectoriesNode.Text; + AdditionalLibraryDirectories := ''; + if not VarIsNull(LibraryDirectoriesNode) then + AdditionalLibraryDirectories := LibraryDirectoriesNode.Text; + UpdatePaths(AdditionalIncludeDirectories, ExpandConstant('{app}\include'), ExpandConstant('{app}\include')); + UpdatePaths(AdditionalLibraryDirectories, ExpandConstant('{app}\lib\Win32'), ExpandConstant('{app}\lib\Win64')); + IncludeDirectoriesNode.Text := AdditionalIncludeDirectories; + LibraryDirectoriesNode.Text := AdditionalLibraryDirectories; + XMLDocument.save(filename); + end; + except + ShowExceptionMessage; + end; +end; + +procedure ModifyVS2008Settings(); +var + Path, CurSettings: string; +begin + if RegQueryStringValue(HKEY_CURRENT_USER, 'Software\Microsoft\VisualStudio\9.0', + 'VisualStudioLocation', Path) then + begin + StringChangeEx(Path, '%USERPROFILE%', GetEnv('USERPROFILE'), True); + if RegQueryStringValue(HKEY_CURRENT_USER, 'Software\Microsoft\VisualStudio\9.0\Profile', + 'AutoSaveFile', CurSettings) then + begin + StringChangeEx(CurSettings, '%vsspv_visualstudio_dir%', Path, True); + ModifySettings(CurSettings); + end; + end; +end; + +function EncodeString(str: string): string; +begin + Result := str; + StringChangeEx(Result, '(', '%28', True); + StringChangeEx(Result, ')', '%29', True); +end; + +procedure UpdateString(var dirList: string; path: string; suffix: string); +begin + if dirList = '' then + dirList := path + suffix + else if (Pos(path, dirList) = 0) and (Pos(EncodeString(path), dirList) = 0) then + dirList := path + dirList; + Log(dirList); +end; + +procedure ModifyProps(filename: string; libfolder: string); +var + XMLDocument: Variant; + XMLParent, IdgNode, XMLNode, XMLNodes: Variant; + IncludeDirectoriesNode: Variant; + AdditionalIncludeDirectories: string; + DynamicLibraryDirectoriesNode: Variant; + AdditionalDynamicLibraryDirectories: string; + StaticLibraryDirectoriesNode: Variant; + AdditionalStaticLibraryDirectories: string; +begin + if not FileExists(filename) then + Exit; + XMLDocument := CreateOleObject('Msxml2.DOMDocument.3.0'); + try + XMLDocument.async := False; + XMLDocument.load(filename); + if (XMLDocument.parseError.errorCode = 0) then + begin + XMLDocument.setProperty('SelectionLanguage', 'XPath'); + XMLDocument.setProperty('SelectionNamespaces', 'xmlns:b=''http://schemas.microsoft.com/developer/msbuild/2003'''); + XMLNodes := XMLDocument.SelectNodes('//b:Project'); + if XMLNodes.Length = 0 then + Exit; + IdgNode := XMLNodes.Item[0]; + XMLNodes := IdgNode.SelectNodes('//b:ItemDefinitionGroup'); + if XMLNodes.Length > 0 then + IdgNode := XMLNodes.Item[0] + else + begin + XMLNode := XMLDocument.CreateNode(1, 'ItemDefinitionGroup', + 'http://schemas.microsoft.com/developer/msbuild/2003'); + IdgNode := IdgNode.AppendChild(XMLNode); + end; + + XMLNodes := IdgNode.SelectNodes('//b:ClCompile'); + if XMLNodes.Length > 0 then + XMLParent := XMLNodes.Item[0] + else + begin + XMLNode := XMLDocument.CreateNode(1, 'ClCompile', + 'http://schemas.microsoft.com/developer/msbuild/2003'); + XMLParent := IdgNode.AppendChild(XMLNode); + end; + XMLNodes := XMLParent.SelectNodes('//b:ClCompile/b:AdditionalIncludeDirectories'); + if XMLNodes.Length > 0 then + IncludeDirectoriesNode := XMLNodes.Item[0] + else + begin + XMLNode := XMLDocument.CreateNode(1, 'AdditionalIncludeDirectories', + 'http://schemas.microsoft.com/developer/msbuild/2003'); + IncludeDirectoriesNode := XMLParent.AppendChild(XMLNode); + end; + + XMLNodes := IdgNode.SelectNodes('//b:Link'); + if XMLNodes.Length > 0 then + XMLParent := XMLNodes.Item[0] + else + begin + XMLNode := XMLDocument.CreateNode(1, 'Link', + 'http://schemas.microsoft.com/developer/msbuild/2003'); + XMLParent := IdgNode.AppendChild(XMLNode); + end; + XMLNodes := XMLParent.SelectNodes('//b:Link/b:AdditionalLibraryDirectories'); + if XMLNodes.Length > 0 then + DynamicLibraryDirectoriesNode := XMLNodes.Item[0] + else + begin + XMLNode := XMLDocument.CreateNode(1, 'AdditionalLibraryDirectories', + 'http://schemas.microsoft.com/developer/msbuild/2003'); + DynamicLibraryDirectoriesNode := XMLParent.AppendChild(XMLNode); + end; + + XMLNodes := IdgNode.SelectNodes('//b:Lib'); + if XMLNodes.Length > 0 then + XMLParent := XMLNodes.Item[0] + else + begin + XMLNode := XMLDocument.CreateNode(1, 'Lib', + 'http://schemas.microsoft.com/developer/msbuild/2003'); + XMLParent := IdgNode.AppendChild(XMLNode); + end; + XMLNodes := XMLParent.SelectNodes('//b:Lib/b:AdditionalLibraryDirectories'); + if XMLNodes.Length > 0 then + StaticLibraryDirectoriesNode := XMLNodes.Item[0] + else + begin + XMLNode := XMLDocument.CreateNode(1, 'AdditionalLibraryDirectories', + 'http://schemas.microsoft.com/developer/msbuild/2003'); + StaticLibraryDirectoriesNode := XMLParent.AppendChild(XMLNode); + end; + + AdditionalIncludeDirectories := ''; + if not VarIsNull(IncludeDirectoriesNode) then + AdditionalIncludeDirectories := IncludeDirectoriesNode.Text; + AdditionalDynamicLibraryDirectories := '';; + if not VarIsNull(DynamicLibraryDirectoriesNode) then + AdditionalDynamicLibraryDirectories := DynamicLibraryDirectoriesNode.Text; + AdditionalStaticLibraryDirectories := '';; + if not VarIsNull(StaticLibraryDirectoriesNode) then + AdditionalStaticLibraryDirectories := StaticLibraryDirectoriesNode.Text; + UpdateString(AdditionalIncludeDirectories, ExpandConstant('{app}\include;'), '%(AdditionalIncludeDirectories)'); + UpdateString(AdditionalDynamicLibraryDirectories, ExpandConstant('{app}\lib\' + libfolder + ';'), '%(AdditionalLibraryDirectories)'); + UpdateString(AdditionalStaticLibraryDirectories, ExpandConstant('{app}\lib\' + libfolder + ';'), '%(AdditionalLibraryDirectories)'); + IncludeDirectoriesNode.Text := AdditionalIncludeDirectories; + DynamicLibraryDirectoriesNode.Text := AdditionalDynamicLibraryDirectories; + StaticLibraryDirectoriesNode.Text := AdditionalStaticLibraryDirectories; + XMLDocument.save(filename); + end; + except + ShowExceptionMessage; + end; +end; + +procedure ModifyAllProps(); +var + Path: string; +begin + Path := GetEnv('LOCALAPPDATA')+'\Microsoft\MSBuild\v4.0\'; + if DirExists(Path) then + begin + ModifyProps(Path + 'Microsoft.Cpp.Win32.user.props', 'Win32'); + ModifyProps(Path + 'Microsoft.Cpp.x64.user.props', 'Win64'); + end; +end; + +procedure CurStepChanged(CurStep: TSetupStep); +begin + if CurStep = ssInstall then + begin + if not UninstallOldVersions() then + Abort(); + if IsTaskSelected('modifyVS2008Props') then + ModifyVS2008Settings(); + if IsTaskSelected('modifyVS2010Props') then + ModifyAllProps(); + end; + CurStepChangedModPath(CurStep); +end; + +procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep); +begin + CurUninstallStepChangedModPath(CurUninstallStep); +end; + +function NextButtonClick(CurPageID: Integer): Boolean; +begin + Result := True; + + if CurPageID = wpReady then + SuppressibleMsgBox('Please close Visual Studio before starting the installation.', mbInformation, MB_OK, IDOK); +end; \ No newline at end of file diff --git a/setup/vld-setup.nsi b/setup/vld-setup.nsi deleted file mode 100644 index 4a7820e2..00000000 --- a/setup/vld-setup.nsi +++ /dev/null @@ -1,269 +0,0 @@ -################################################################################ -# -# Visual Leak Detector - NSIS Installation Script -# Copyright (c) 2006-2009 Dan Moulding -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA -# -# See COPYING.txt for the full terms of the GNU General Public License. -# -################################################################################ - -!include "Library.nsh" # Provides the dynamic link library installation system -!include "LogicLib.nsh" # Provides useable conditional script syntax -!include "MUI.nsh" # Provides the modern user-interface - -# Version number -!define VLD_VERSION "1.9h" - -# Define build system paths -!define CRT_PATH "C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT" -!define DTFW_PATH "C:\Program Files\Debugging Tools for Windows (x86)" -!define EDITENV_PATH "editenv" - -# Define build system files -!define CRT_DLL "msvcr90.dll" -!define CRT_MANIFEST "Microsoft.VC90.CRT.manifest" -!define DHL_DLL "dbghelp.dll" -!define EDITENV_DLL "editenv.dll" - -# Define installer paths -!define BIN_PATH "$INSTDIR\bin" -!define INCLUDE_PATH "$INSTDIR\include" -!define LIB_PATH "$INSTDIR\lib" -!define LNK_PATH "$SMPROGRAMS\$SM_PATH" -!define SRC_PATH "$INSTDIR\src" - -# Define editenv system environment variable scope -!define ES_SYSTEM 1 - -# Define registry keys -!define REG_KEY_PRODUCT "Software\Visual Leak Detector" -!define REG_KEY_UNINSTALL "Software\Microsoft\Windows\CurrentVersion\Uninstall\Visual Leak Detector" - -# Define page settings -!define MUI_FINISHPAGE_NOAUTOCLOSE -!define MUI_FINISHPAGE_SHOWREADME "$INSTDIR\README.html" -!define MUI_FINISHPAGE_SHOWREADME_TEXT "View Documentation" -!define MUI_LICENSEPAGE_BUTTON "Continue" -!define MUI_LICENSEPAGE_TEXT_BOTTOM "Click the 'Continue' button to continue installing. Remember, you aren't required to (and are not being asked to) agree to anything before using this software." -!define MUI_LICENSEPAGE_TEXT_TOP "Press Page Down to see the rest of the text." -!define MUI_STARTMENUPAGE_DEFAULTFOLDER "Visual Leak Detector" -!define MUI_STARTMENUPAGE_REGISTRY_ROOT HKLM -!define MUI_STARTMENUPAGE_REGISTRY_KEY "${REG_KEY_PRODUCT}" -!define MUI_STARTMENUPAGE_REGISTRY_VALUENAME "LnkPath" -!define MUI_UNFINISHPAGE_NOAUTOCLOSE - -# Define installer attributes -InstallDir "$PROGRAMFILES\Visual Leak Detector" -InstallDirRegKey HKLM "${REG_KEY_PRODUCT}" "InstallPath" -Name "Visual Leak Detector ${VLD_VERSION}" -OutFile "vld-${VLD_VERSION}-setup.exe" -SetCompressor /SOLID lzma -ShowInstDetails show -ShowUninstDetails show - -# Declare global variables -Var INSTALLED_VERSION -Var SM_PATH - -# Define the installer pages -!insertmacro MUI_PAGE_WELCOME -!define MUI_PAGE_HEADER_TEXT "No License Required for Use" -!define MUI_PAGE_HEADER_SUBTEXT "This software is provided 'AS IS' without warranty of any kind." -!insertmacro MUI_PAGE_LICENSE "license-free.txt" -!insertmacro MUI_PAGE_DIRECTORY -!insertmacro MUI_PAGE_STARTMENU "Shortcuts" $SM_PATH -!insertmacro MUI_PAGE_INSTFILES -!insertmacro MUI_PAGE_FINISH - -# Define the uninstaller pages -!insertmacro MUI_UNPAGE_CONFIRM -!insertmacro MUI_UNPAGE_INSTFILES -!insertmacro MUI_UNPAGE_FINISH - -# Set the modern UI language -!insertmacro MUI_LANGUAGE "English" - -################################################################################ -# -# Installation -# -Function .onInit - ReadRegStr $INSTALLED_VERSION HKLM "${REG_KEY_PRODUCT}" "InstalledVersion" - ${UNLESS} $INSTALLED_VERSION == "" - ${IF} $INSTALLED_VERSION == ${VLD_VERSION} - MessageBox MB_ICONINFORMATION|MB_OKCANCEL "Setup has detected that Visual Leak Detector version $INSTALLED_VERSION is already installed on this computer.$\n$\nClick 'OK' if you want to continue and repair the existing installation. Click 'Cancel' if you want to abort installation." \ - IDOK continue IDCANCEL abort - ${ELSE} - MessageBox MB_ICONEXCLAMATION|MB_YESNO "Setup has detected that a different version of Visual Leak Detector is already installed on this computer.$\nIt is highly recommended that you first uninstall the version currently installed before proceeding.$\n$\nAre you sure you want to continue installing?" \ - IDYES continue IDNO abort - ${ENDIF} -abort: - Abort -continue: - ${ENDUNLESS} -FunctionEnd - -Section "Uninstaller" - SetOutPath "$INSTDIR" - WriteUninstaller "$INSTDIR\uninstall.exe" - WriteRegStr HKLM "${REG_KEY_UNINSTALL}" "DisplayName" "Visual Leak Detector ${VLD_VERSION}" - WriteRegStr HKLM "${REG_KEY_UNINSTALL}" "UninstallString" "$INSTDIR\uninstall.exe" - WriteRegStr HKLM "${REG_KEY_UNINSTALL}" "InstallLocation" "$INSTDIR" - WriteRegStr HKLM "${REG_KEY_UNINSTALL}" "Publisher" "Dan Moulding" - WriteRegStr HKLM "${REG_KEY_UNINSTALL}" "URLInfoAbout" "http://www.danm.net" - WriteRegStr HKLM "${REG_KEY_UNINSTALL}" "DisplayVersion" "${VLD_VERSION}" - WriteRegDWORD HKLM "${REG_KEY_UNINSTALL}" "NoModify" 1 - WriteRegDWORD HKLM "${REG_KEY_UNINSTALL}" "NoRepair" 1 -SectionEnd - -Section "Registry Keys" - WriteRegStr HKLM "${REG_KEY_PRODUCT}" "IniFile" "$INSTDIR\vld.ini" - WriteRegStr HKLM "${REG_KEY_PRODUCT}" "InstallPath" "$INSTDIR" - WriteRegStr HKLM "${REG_KEY_PRODUCT}" "InstalledVersion" "${VLD_VERSION}" -SectionEnd - -Section "Header File" - SetOutPath "${INCLUDE_PATH}" - File "..\vld.h" -SectionEnd - -Section "Import Library" - SetOutPath "${LIB_PATH}" - File "..\Release\vld.lib" -SectionEnd - -Section "Dynamic Link Libraries" - SetOutPath "${BIN_PATH}" - !insertmacro InstallLib DLL NOTSHARED NOREBOOT_NOTPROTECTED "..\Release\vld.dll" "${BIN_PATH}\vld.dll" $INSTDIR - MessageBox MB_YESNO "Visual Leak Detector needs the location of vld.dll to be added to your 'Path' environment variable.$\n$\nWould you like the installer to add it to the path now? If you select No, you'll need to add it to the path manually." \ - IDYES addtopath IDNO skipaddtopath -addtopath: - DetailPrint "Adding ${BIN_PATH} to the 'Path' system environment variable." - InitPluginsDir - SetOutPath "$PLUGINSDIR" - File "${EDITENV_PATH}\${EDITENV_DLL}" - System::Call "editenv::pathAdd(i ${ES_SYSTEM}, t '${BIN_PATH}') ? u" - Delete "$PLUGINSDIR\${EDITENV_DLL}" - SetOutPath "${BIN_PATH}" -skipaddtopath: - !insertmacro InstallLib DLL NOTSHARED NOREBOOT_NOTPROTECTED "${DTFW_PATH}\${DHL_DLL}" "${BIN_PATH}\${DHL_DLL}" $INSTDIR - !insertmacro InstallLib DLL NOTSHARED NOREBOOT_NOTPROTECTED "${CRT_PATH}\${CRT_DLL}" "${BIN_PATH}\${CRT_DLL}" $INSTDIR - File "..\Microsoft.DTfW.DHL.manifest" - File "${CRT_PATH}\${CRT_MANIFEST}" -SectionEnd - -Section "Configuration File" - SetOutPath "$INSTDIR" - File "..\vld.ini" -SectionEnd - -Section "Source Code" - SetOutPath "${SRC_PATH}" - File "..\*.cpp" - File "..\*.h" - File "..\vld.vcproj" - File "..\*.manifest" - File "..\*.rc" -SectionEnd - -Section "Documentation" - SetOutPath "$INSTDIR" - File "..\CHANGES.txt" - File "..\COPYING.txt" - File "..\README.html" -SectionEnd - -Section "Start Menu Shortcuts" - !insertmacro MUI_STARTMENU_WRITE_BEGIN "Shortcuts" - SetOutPath "$INSTDIR" - SetShellVarContext all - CreateDirectory "${LNK_PATH}" - CreateShortcut "${LNK_PATH}\Configure.lnk" "$INSTDIR\vld.ini" - CreateShortcut "${LNK_PATH}\Documentation.lnk" "$INSTDIR\README.html" - CreateShortcut "${LNK_PATH}\License.lnk" "$INSTDIR\COPYING.txt" - CreateShortcut "${LNK_PATH}\Uninstall.lnk" "$INSTDIR\uninstall.exe" - !insertmacro MUI_STARTMENU_WRITE_END -SectionEnd - - -################################################################################ -# -# Uninstallation -# -Section "un.Header File" - Delete "${INCLUDE_PATH}\vld.h" - RMDir "${INCLUDE_PATH}" -SectionEnd - -Section "un.Import Library" - Delete "${LIB_PATH}\vld.lib" - RMDir "${LIB_PATH}" -SectionEnd - -Section "un.Dynamic Link Libraries" - !insertmacro UnInstallLib DLL NOTSHARED NOREBOOT_NOTPROTECTED "${BIN_PATH}\vld.dll" - DetailPrint "Removing ${BIN_PATH} from the 'Path' system environment variable." - InitPluginsDir - SetOutPath "$PLUGINSDIR" - File "${EDITENV_PATH}\${EDITENV_DLL}" - System::Call "editenv::pathRemove(i ${ES_SYSTEM}, t '${BIN_PATH}') ? u" - Delete "$PLUGINSDIR\${EDITENV_DLL}" - !insertmacro UnInstallLib DLL NOTSHARED NOREBOOT_NOTPROTECTED "${BIN_PATH}\${DHL_DLL}" - !insertmacro UnInstallLib DLL NOTSHARED NOREBOOT_NOTPROTECTED "${BIN_PATH}\${CRT_DLL}" - Delete "${BIN_PATH}\Microsoft.DTfW.DHL.manifest" - Delete "${BIN_PATH}\${CRT_MANIFEST}" - RMDir "${BIN_PATH}" -SectionEnd - -Section "un.Configuration File" - Delete "$INSTDIR\vld.ini" -SectionEnd - -Section "un.Source Code" - Delete "${SRC_PATH}\*.cpp" - Delete "${SRC_PATH}\*.h" - Delete "${SRC_PATH}\vld.vcproj" - Delete "${SRC_PATH}\*.manifest" - Delete "${SRC_PATH}\*.rc" - RMDir "${SRC_PATH}" -SectionEnd - -Section "un.Documentation" - Delete "$INSTDIR\CHANGES.txt" - Delete "$INSTDIR\COPYING.txt" - Delete "$INSTDIR\README.html" -SectionEnd - -Section "un.Start Menu Shortcuts" - !insertmacro MUI_STARTMENU_GETFOLDER "Shortcuts" $SM_PATH - SetShellVarContext all - Delete "${LNK_PATH}\Configure.lnk" - Delete "${LNK_PATH}\Documentation.lnk" - Delete "${LNK_PATH}\License.lnk" - Delete "${LNK_PATH}\Uninstall.lnk" - RMDir "${LNK_PATH}" -SectionEnd - -Section "un.Registry Keys" - DeleteRegKey HKLM "${REG_KEY_PRODUCT}" -SectionEnd - -Section "un.Uninstaller" - Delete "$INSTDIR\uninstall.exe" - RMDir "$INSTDIR" - DeleteRegKey HKLM "${REG_KEY_UNINSTALL}" -SectionEnd diff --git a/src/callstack.cpp b/src/callstack.cpp new file mode 100644 index 00000000..a5404c31 --- /dev/null +++ b/src/callstack.cpp @@ -0,0 +1,789 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - CallStack Class Implementations +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#define VLDBUILD +#include "callstack.h" // This class' header. +#include "utility.h" // Provides various utility functions. +#include "vldheap.h" // Provides internal new and delete operators. +#include "vldint.h" // Provides access to VLD internals. +#include "cppformat\format.h" + +// Imported global variables. +extern HANDLE g_currentProcess; +extern HANDLE g_currentThread; +extern CriticalSection g_heapMapLock; +extern VisualLeakDetector g_vld; +extern DbgHelp g_DbgHelp; + +// Helper function to compare the begin of a string with a substring +// +template +bool beginWith(const LPCWSTR filename, size_t len, wchar_t const (&substr)[N]) +{ + size_t count = N - 1; + return ((len >= count) && wcsncmp(filename, substr, count) == 0); +} + +// Helper function to compare the end of a string with a substring +// +template +bool endWith(const LPCWSTR filename, size_t len, wchar_t const (&substr)[N]) +{ + size_t count = N - 1; + return ((len >= count) && wcsncmp(filename + len - count, substr, count) == 0); +} + +// Constructor - Initializes the CallStack with an initial size of zero and one +// Chunk of capacity. +// +CallStack::CallStack () +{ + m_capacity = CALLSTACK_CHUNK_SIZE; + m_size = 0; + m_status = 0x0; + m_store.next = NULL; + m_topChunk = &m_store; + m_topIndex = 0; + m_resolved = NULL; + m_resolvedCapacity = 0; + m_resolvedLength = 0; +} + +// Destructor - Frees all memory allocated to the CallStack. +// +CallStack::~CallStack () +{ + CallStack::chunk_t *chunk = m_store.next; + CallStack::chunk_t *temp; + + while (chunk) { + temp = chunk; + chunk = temp->next; + delete temp; + } + + delete [] m_resolved; + + m_resolved = NULL; + m_resolvedCapacity = 0; + m_resolvedLength = 0; +} + +CallStack* CallStack::Create() +{ + CallStack* result = NULL; + if (g_vld.GetOptions() & VLD_OPT_SAFE_STACK_WALK) { + result = new SafeCallStack(); + } + else { + result = new FastCallStack(); + } + return result; +} + +// operator == - Equality operator. Compares the CallStack to another CallStack +// for equality. Two CallStacks are equal if they are the same size and if +// every frame in each is identical to the corresponding frame in the other. +// +// other (IN) - Reference to the CallStack to compare the current CallStack +// against for equality. +// +// Return Value: +// +// Returns true if the two CallStacks are equal. Otherwise returns false. +// +BOOL CallStack::operator == (const CallStack &other) const +{ + if (m_size != other.m_size) { + // They can't be equal if the sizes are different. + return FALSE; + } + + // Walk the chunk list and within each chunk walk the frames array until we + // either find a mismatch, or until we reach the end of the call stacks. + const CallStack::chunk_t *prevChunk = NULL; + const CallStack::chunk_t *chunk = &m_store; + const CallStack::chunk_t *otherChunk = &other.m_store; + while (prevChunk != m_topChunk) { + UINT32 size = (chunk == m_topChunk) ? m_topIndex : CALLSTACK_CHUNK_SIZE; + for (UINT32 index = 0; index < size; index++) { + if (chunk->frames[index] != otherChunk->frames[index]) { + // Found a mismatch. They are not equal. + return FALSE; + } + } + prevChunk = chunk; + chunk = chunk->next; + otherChunk = otherChunk->next; + } + + // Reached the end of the call stacks. They are equal. + return TRUE; +} + +// operator [] - Random access operator. Retrieves the frame at the specified +// index. +// +// Note: We give up a bit of efficiency here, in favor of efficiency of push +// operations. This is because walking of a CallStack is done infrequently +// (only if a leak is found), whereas pushing is done very frequently (for +// each frame in the program's call stack when the program allocates some +// memory). +// +// - index (IN): Specifies the index of the frame to retrieve. +// +// Return Value: +// +// Returns the program counter for the frame at the specified index. If the +// specified index is out of range for the CallStack, the return value is +// undefined. +// +UINT_PTR CallStack::operator [] (UINT32 index) const +{ + UINT32 chunknumber = index / CALLSTACK_CHUNK_SIZE; + const CallStack::chunk_t *chunk = &m_store; + + for (UINT32 count = 0; count < chunknumber; count++) { + chunk = chunk->next; + } + + return chunk->frames[index % CALLSTACK_CHUNK_SIZE]; +} + +// clear - Resets the CallStack, returning it to a state where no frames have +// been pushed onto it, readying it for reuse. +// +// Note: Calling this function does not release any memory allocated to the +// CallStack. We give up a bit of memory-usage efficiency here in favor of +// performance of push operations. +// +// Return Value: +// +// None. +// +VOID CallStack::clear () +{ + m_size = 0; + m_topChunk = &m_store; + m_topIndex = 0; + if (m_resolved) + { + delete [] m_resolved; + m_resolved = NULL; + } + m_resolvedCapacity = 0; + m_resolvedLength = 0; +} + +LPCWSTR CallStack::getFunctionName(SIZE_T programCounter, DWORD64& displacement64, + SYMBOL_INFO* functionInfo, CriticalSectionLocker& locker) const +{ + // Initialize structures passed to the symbol handler. + functionInfo->SizeOfStruct = sizeof(SYMBOL_INFO); + functionInfo->MaxNameLen = MAX_SYMBOL_NAME_LENGTH; + + // Try to get the name of the function containing this program + // counter address. + displacement64 = 0; + LPCWSTR functionName; + DbgTrace(L"dbghelp32.dll %i: SymFromAddrW\n", GetCurrentThreadId()); + if (g_DbgHelp.SymFromAddrW(g_currentProcess, programCounter, &displacement64, functionInfo, locker)) { + functionName = functionInfo->Name; + } + else { + // GetFormattedMessage( GetLastError() ); + fmt::WArrayWriter wf(functionInfo->Name, MAX_SYMBOL_NAME_LENGTH); + wf.write(L"" ADDRESSCPPFORMAT, programCounter); + functionName = wf.c_str(); + displacement64 = 0; + } + return functionName; +} + +DWORD CallStack::resolveFunction(SIZE_T programCounter, IMAGEHLP_LINEW64* sourceInfo, DWORD displacement, + LPCWSTR functionName, LPWSTR stack_line, DWORD stackLineSize) const +{ + WCHAR callingModuleName[260]; + HMODULE hCallingModule = GetCallingModule(programCounter); + LPWSTR moduleName = L"(Module name unavailable)"; + if (hCallingModule && + GetModuleFileName(hCallingModule, callingModuleName, _countof(callingModuleName)) > 0) + { + moduleName = wcsrchr(callingModuleName, L'\\'); + if (moduleName == NULL) + moduleName = wcsrchr(callingModuleName, L'/'); + if (moduleName != NULL) + moduleName++; + else + moduleName = callingModuleName; + } + + fmt::WArrayWriter w(stack_line, stackLineSize); + // Display the current stack frame's information. + if (sourceInfo) + { + if (displacement == 0) + { + w.write(L" {} ({}): {}!{}()\n", + sourceInfo->FileName, sourceInfo->LineNumber, moduleName, + functionName); + } + else + { + w.write(L" {} ({}): {}!{}() + 0x{:X} bytes\n", + sourceInfo->FileName, sourceInfo->LineNumber, moduleName, + functionName, displacement); + } + } + else + { + if (displacement == 0) + { + w.write(L" {}!{}()\n", + moduleName, functionName); + } + else + { + w.write(L" {}!{}() + 0x{:X} bytes\n", + moduleName, functionName, displacement); + } + } + DWORD NumChars = (DWORD)w.size(); + stack_line[NumChars] = '\0'; + return NumChars; +} + + +// isCrtStartupAlloc - Determines whether the memory leak was generated from crt startup code. +// This is not an actual memory leaks as it is freed by crt after the VLD object has been destroyed. +// +// Return Value: +// +// true if isCrtStartupModule for any callstack frame returns true. +// +bool CallStack::isCrtStartupAlloc() +{ + if (m_status & CALLSTACK_STATUS_STARTUPCRT) { + return true; + } else if (m_status & CALLSTACK_STATUS_NOTSTARTUPCRT) { + return false; + } + + IMAGEHLP_LINE64 sourceInfo = { 0 }; + sourceInfo.SizeOfStruct = sizeof(IMAGEHLP_LINE64); + + BYTE symbolBuffer[sizeof(SYMBOL_INFO) + MAX_SYMBOL_NAME_SIZE] = { 0 }; + CriticalSectionLocker locker(g_DbgHelp); + + // Iterate through each frame in the call stack. + for (UINT32 frame = 0; frame < m_size; frame++) { + // Try to get the source file and line number associated with + // this program counter address. + SIZE_T programCounter = (*this)[frame]; + DWORD64 displacement64; + LPCWSTR functionName = getFunctionName(programCounter, displacement64, (SYMBOL_INFO*)&symbolBuffer, locker); + + m_status |= isCrtStartupFunction(functionName); + if (m_status & CALLSTACK_STATUS_STARTUPCRT) { + return true; + } else if (m_status & CALLSTACK_STATUS_NOTSTARTUPCRT) { + return false; + } + } + + m_status |= CALLSTACK_STATUS_NOTSTARTUPCRT; + return false; +} + + +// dump - Dumps a nicely formatted rendition of the CallStack, including +// symbolic information (function names and line numbers) if available. +// +// Note: The symbol handler must be initialized prior to calling this +// function. +// +// - showinternalframes (IN): If true, then all frames in the CallStack will be +// dumped. Otherwise, frames internal to the heap will not be dumped. +// +// Return Value: +// +// None. +// +void CallStack::dump(BOOL showInternalFrames) +{ + if (!m_resolved) { + resolve(showInternalFrames); + } + + // The stack was reoslved already + if (m_resolved) { + return Print(m_resolved); + } +} + +// Resolve - Creates a nicely formatted rendition of the CallStack, including +// symbolic information (function names and line numbers) if available. and +// saves it for later retrieval. +// +// Note: The symbol handler must be initialized prior to calling this +// function. +// +// - showInternalFrames (IN): If true, then all frames in the CallStack will be +// dumped. Otherwise, frames internal to the heap will not be dumped. +// +// Return Value: +// +// None. +// +int CallStack::resolve(BOOL showInternalFrames) +{ + if (m_resolved) + { + // already resolved, no need to do it again + // resolving twice may report an incorrect module for the stack frames + // if the memory was leaked in a dynamic library that was already unloaded. + return 0; + } + + if (m_status & CALLSTACK_STATUS_STARTUPCRT) { + // there is no need to resolve a leak that will not be reported + return 0; + } + + if (m_status & CALLSTACK_STATUS_INCOMPLETE) { + // This call stack appears to be incomplete. Using StackWalk64 may be + // more reliable. + Report(L" HINT: The following call stack may be incomplete. Setting \"StackWalkMethod\"\n" + L" in the vld.ini file to \"safe\" instead of \"fast\" may result in a more\n" + L" complete stack trace.\n"); + } + + int unresolvedFunctionsCount = 0; + IMAGEHLP_LINE64 sourceInfo = { 0 }; + sourceInfo.SizeOfStruct = sizeof(IMAGEHLP_LINE64); + + bool skipStartupLeaks = !!(g_vld.GetOptions() & VLD_OPT_SKIP_CRTSTARTUP_LEAKS); + + // Use static here to increase performance, and avoid heap allocs. + // It's thread safe because of g_heapMapLock lock. + static WCHAR stack_line[MAXREPORTLENGTH + 1] = L""; + bool isPrevFrameInternal = false; + DWORD NumChars = 0; + CriticalSectionLocker locker(g_DbgHelp); + + const size_t max_line_length = MAXREPORTLENGTH + 1; + m_resolvedCapacity = m_size * max_line_length; + const size_t allocedBytes = m_resolvedCapacity * sizeof(WCHAR); + m_resolved = new WCHAR[m_resolvedCapacity]; + if (m_resolved) { + ZeroMemory(m_resolved, allocedBytes); + } + + // Iterate through each frame in the call stack. + for (UINT32 frame = 0; frame < m_size; frame++) + { + // Try to get the source file and line number associated with + // this program counter address. + SIZE_T programCounter = (*this)[frame]; + if (GetCallingModule(programCounter) == g_vld.m_vldBase) + continue; + + DWORD64 displacement64; + BYTE symbolBuffer[sizeof(SYMBOL_INFO) + MAX_SYMBOL_NAME_SIZE]; + LPCWSTR functionName = getFunctionName(programCounter, displacement64, (SYMBOL_INFO*)&symbolBuffer, locker); + + if (skipStartupLeaks) { + if (!(m_status & (CALLSTACK_STATUS_STARTUPCRT | CALLSTACK_STATUS_NOTSTARTUPCRT))) { + m_status |= isCrtStartupFunction(functionName); + } + if (m_status & CALLSTACK_STATUS_STARTUPCRT) { + delete[] m_resolved; + m_resolved = NULL; + m_resolvedCapacity = 0; + m_resolvedLength = 0; + return 0; + } + } + + // It turns out that calls to SymGetLineFromAddrW64 may free the very memory we are scrutinizing here + // in this method. If this is the case, m_Resolved will be null after SymGetLineFromAddrW64 returns. + // When that happens there is nothing we can do except crash. + DWORD displacement = 0; + DbgTrace(L"dbghelp32.dll %i: SymGetLineFromAddrW64\n", GetCurrentThreadId()); + BOOL foundline = g_DbgHelp.SymGetLineFromAddrW64(g_currentProcess, programCounter, &displacement, &sourceInfo, locker); + + bool isFrameInternal = false; + if (foundline && !showInternalFrames) { + if (isInternalModule(sourceInfo.FileName)) { + // Don't show frames in files internal to the heap. + isFrameInternal = true; + } + } + + // show one allocation function for context + if (NumChars > 0 && !isFrameInternal && isPrevFrameInternal) { + m_resolvedLength += NumChars; + if (m_resolved) { + wcsncat_s(m_resolved, m_resolvedCapacity, stack_line, NumChars); + } + } + isPrevFrameInternal = isFrameInternal; + + if (!foundline) + displacement = (DWORD)displacement64; + NumChars = resolveFunction( programCounter, foundline ? &sourceInfo : NULL, + displacement, functionName, stack_line, _countof( stack_line )); + + if (NumChars > 0 && !isFrameInternal) { + m_resolvedLength += NumChars; + if (m_resolved) { + wcsncat_s(m_resolved, m_resolvedCapacity, stack_line, NumChars); + } + } + } // end for loop + + m_status |= CALLSTACK_STATUS_NOTSTARTUPCRT; + return unresolvedFunctionsCount; +} + +const WCHAR* CallStack::getResolvedCallstack( BOOL showinternalframes ) +{ + resolve(showinternalframes); + return m_resolved; +} + +// push_back - Pushes a frame's program counter onto the CallStack. Pushes are +// always appended to the back of the chunk list (aka the "top" chunk). +// +// Note: This function will allocate additional memory as necessary to make +// room for new program counter addresses. +// +// - programcounter (IN): The program counter address of the frame to be pushed +// onto the CallStack. +// +// Return Value: +// +// None. +// +VOID CallStack::push_back (const UINT_PTR programcounter) +{ + if (m_size == m_capacity) { + // At current capacity. Allocate additional storage. + CallStack::chunk_t *chunk = new CallStack::chunk_t; + chunk->next = NULL; + m_topChunk->next = chunk; + m_topChunk = chunk; + m_topIndex = 0; + m_capacity += CALLSTACK_CHUNK_SIZE; + } + else if (m_topIndex >= CALLSTACK_CHUNK_SIZE) { + // There is more capacity, but not in this chunk. Go to the next chunk. + // Note that this only happens if this CallStack has previously been + // cleared (clearing resets the data, but doesn't give up any allocated + // space). + m_topChunk = m_topChunk->next; + m_topIndex = 0; + } + + m_topChunk->frames[m_topIndex++] = programcounter; + m_size++; +} + +UINT CallStack::isCrtStartupFunction( LPCWSTR functionName ) const +{ + size_t len = wcslen(functionName); + + if (beginWith(functionName, len, L"_malloc_crt") + || beginWith(functionName, len, L"_calloc_crt") + || endWith(functionName, len, L"CRT_INIT") + || endWith(functionName, len, L"initterm_e") + || beginWith(functionName, len, L"_cinit") + || beginWith(functionName, len, L"std::`dynamic initializer for '") + // VS2008 Release + || (wcscmp(functionName, L"std::locale::facet::facet_Register") == 0) + // VS2010 Release + || (wcscmp(functionName, L"std::locale::facet::_Facet_Register") == 0) + // VS2012 Release + || beginWith(functionName, len, L"std::locale::_Init()") + || beginWith(functionName, len, L"std::basic_streambuf<") + // VS2015 + || beginWith(functionName, len, L"common_initialize_environment_nolock<") + || beginWith(functionName, len, L"common_configure_argv<") + || beginWith(functionName, len, L"__acrt_initialize") + || beginWith(functionName, len, L"__acrt_allocate_buffer_for_argv") + || beginWith(functionName, len, L"_register_onexit_function") + // VS2015 Release + || (wcscmp(functionName, L"setlocale") == 0) + || (wcscmp(functionName, L"_wsetlocale") == 0) + || (wcscmp(functionName, L"_Getctype") == 0) + || (wcscmp(functionName, L"std::_Facet_Register") == 0) + || endWith(functionName, len, L">::_Getcat") + ) { + return CALLSTACK_STATUS_STARTUPCRT; + } + + if (endWith(functionName, len, L"DllMainCRTStartup") + || endWith(functionName, len, L"mainCRTStartup") + || beginWith(functionName, len, L"`dynamic initializer for '")) { + // When we reach this point there is no reason going further down the stack + return CALLSTACK_STATUS_NOTSTARTUPCRT; + } + + return NULL; +} + +bool CallStack::isInternalModule( const PWSTR filename ) const +{ + size_t len = wcslen(filename); + return + // VS2015 + endWith(filename, len, L"\\atlmfc\\include\\atlsimpstr.h") || + endWith(filename, len, L"\\atlmfc\\include\\cstringt.h") || + endWith(filename, len, L"\\atlmfc\\src\\mfc\\afxmem.cpp") || + endWith(filename, len, L"\\atlmfc\\src\\mfc\\strcore.cpp") || + endWith(filename, len, L"\\vcstartup\\src\\heap\\new_scalar.cpp") || + endWith(filename, len, L"\\vcstartup\\src\\heap\\new_array.cpp") || + endWith(filename, len, L"\\vcstartup\\src\\heap\\new_debug.cpp") || + endWith(filename, len, L"\\ucrt\\src\\appcrt\\heap\\align.cpp") || + endWith(filename, len, L"\\ucrt\\src\\appcrt\\heap\\malloc.cpp") || + endWith(filename, len, L"\\ucrt\\src\\appcrt\\heap\\debug_heap.cpp") || + // VS2013 + beginWith(filename, len, L"f:\\dd\\vctools\\crt\\crtw32\\") || + //endWith(filename, len, L"\\crt\\crtw32\\misc\\dbgheap.c") || + //endWith(filename, len, L"\\crt\\crtw32\\misc\\dbgnew.cpp") || + //endWith(filename, len, L"\\crt\\crtw32\\misc\\dbgmalloc.c") || + //endWith(filename, len, L"\\crt\\crtw32\\misc\\dbgrealloc.c") || + //endWith(filename, len, L"\\crt\\crtw32\\heap\\new.cpp") || + //endWith(filename, len, L"\\crt\\crtw32\\heap\\new2.cpp") || + //endWith(filename, len, L"\\crt\\crtw32\\heap\\malloc.c") || + //endWith(filename, len, L"\\crt\\crtw32\\heap\\realloc.c") || + //endWith(filename, len, L"\\crt\\crtw32\\heap\\calloc.c") || + //endWith(filename, len, L"\\crt\\crtw32\\heap\\calloc_impl.c") || + //endWith(filename, len, L"\\crt\\crtw32\\string\\strdup.c") || + //endWith(filename, len, L"\\crt\\crtw32\\string\\wcsdup.c") || + // VS2010 + endWith(filename, len, L"\\crt\\src\\afxmem.cpp") || + endWith(filename, len, L"\\crt\\src\\dbgheap.c") || + endWith(filename, len, L"\\crt\\src\\dbgnew.cpp") || + endWith(filename, len, L"\\crt\\src\\dbgmalloc.c") || + endWith(filename, len, L"\\crt\\src\\dbgcalloc.c") || + endWith(filename, len, L"\\crt\\src\\dbgrealloc.c") || + endWith(filename, len, L"\\crt\\src\\dbgdel.cp") || + endWith(filename, len, L"\\crt\\src\\new.cpp") || + endWith(filename, len, L"\\crt\\src\\newaop.cpp") || + endWith(filename, len, L"\\crt\\src\\malloc.c") || + endWith(filename, len, L"\\crt\\src\\realloc.c") || + endWith(filename, len, L"\\crt\\src\\free.c") || + endWith(filename, len, L"\\crt\\src\\strdup.c") || + endWith(filename, len, L"\\crt\\src\\wcsdup.c") || + endWith(filename, len, L"\\vc\\include\\xmemory0") || + // default + (false); +} + +// getStackTrace - Traces the stack as far back as possible, or until 'maxdepth' +// frames have been traced. Populates the CallStack with one entry for each +// stack frame traced. +// +// Note: This function uses a very efficient method to walk the stack from +// frame to frame, so it is quite fast. However, unconventional stack frames +// (such as those created when frame pointer omission optimization is used) +// will not be successfully walked by this function and will cause the +// stack trace to terminate prematurely. +// +// - maxdepth (IN): Maximum number of frames to trace back. +// +// - framepointer (IN): Frame (base) pointer at which to begin the stack trace. +// If NULL, then the stack trace will begin at this function. +// +// Return Value: +// +// None. +// +VOID FastCallStack::getStackTrace (UINT32 maxdepth, const context_t& context) +{ + UINT32 count = 0; + UINT_PTR function = context.func; + if (function != NULL) + { + count++; + push_back(function); + } + +/*#if defined(_M_IX86) + UINT_PTR* framePointer = (UINT_PTR*)context.BPREG; + while (count < maxdepth) { + if (*framePointer < (UINT_PTR)framePointer) { + if (*framePointer == NULL) { + // Looks like we reached the end of the stack. + break; + } + else { + // Invalid frame pointer. Frame pointer addresses should always + // increase as we move up the stack. + m_status |= CALLSTACK_STATUS_INCOMPLETE; + break; + } + } + if (*framePointer & (sizeof(UINT_PTR*) - 1)) { + // Invalid frame pointer. Frame pointer addresses should always + // be aligned to the size of a pointer. This probably means that + // we've encountered a frame that was created by a module built with + // frame pointer omission (FPO) optimization turned on. + m_status |= CALLSTACK_STATUS_INCOMPLETE; + break; + } + if (IsBadReadPtr((UINT*)*framePointer, sizeof(UINT_PTR*))) { + // Bogus frame pointer. Again, this probably means that we've + // encountered a frame built with FPO optimization. + m_status |= CALLSTACK_STATUS_INCOMPLETE; + break; + } + count++; + push_back(*(framePointer + 1)); + framePointer = (UINT_PTR*)*framePointer; + } +#elif defined(_M_X64)*/ + UINT32 maxframes = min(62, maxdepth + 10); + UINT_PTR* myFrames = new UINT_PTR[maxframes]; + ZeroMemory(myFrames, sizeof(UINT_PTR) * maxframes); + ULONG BackTraceHash; + maxframes = RtlCaptureStackBackTrace(0, maxframes, reinterpret_cast(myFrames), &BackTraceHash); + m_hashValue = BackTraceHash; + UINT32 startIndex = 0; + while (count < maxframes) { + if (myFrames[count] == 0) + break; + if (myFrames[count] == context.fp) + startIndex = count; + count++; + } + count = startIndex; + while (count < maxframes) { + if (myFrames[count] == 0) + break; + push_back(myFrames[count]); + count++; + } + delete [] myFrames; +//#endif +} + +// getStackTrace - Traces the stack as far back as possible, or until 'maxdepth' +// frames have been traced. Populates the CallStack with one entry for each +// stack frame traced. +// +// Note: This function uses a documented Windows API to walk the stack. This +// API is supposed to be the most reliable way to walk the stack. It claims +// to be able to walk stack frames that do not follow the conventional stack +// frame layout. However, this robustness comes at a cost: it is *extremely* +// slow compared to walking frames by following frame (base) pointers. +// +// - maxdepth (IN): Maximum number of frames to trace back. +// +// - framepointer (IN): Frame (base) pointer at which to begin the stack trace. +// If NULL, then the stack trace will begin at this function. +// +// Return Value: +// +// None. +// +VOID SafeCallStack::getStackTrace (UINT32 maxdepth, const context_t& context) +{ + UINT32 count = 0; + UINT_PTR function = context.func; + if (function != NULL) + { + count++; + push_back(function); + } + + if (context.IPREG == NULL) + { + return; + } + + count++; + push_back(context.IPREG); + + DWORD architecture = X86X64ARCHITECTURE; + + // Get the required values for initialization of the STACKFRAME64 structure + // to be passed to StackWalk64(). Required fields are AddrPC and AddrFrame. + CONTEXT currentContext; + memset(¤tContext, 0, sizeof(currentContext)); + currentContext.SPREG = context.SPREG; + currentContext.BPREG = context.BPREG; + currentContext.IPREG = context.IPREG; + + // Initialize the STACKFRAME64 structure. + STACKFRAME64 frame; + memset(&frame, 0x0, sizeof(frame)); + frame.AddrPC.Offset = currentContext.IPREG; + frame.AddrPC.Mode = AddrModeFlat; + frame.AddrStack.Offset = currentContext.SPREG; + frame.AddrStack.Mode = AddrModeFlat; + frame.AddrFrame.Offset = currentContext.BPREG; + frame.AddrFrame.Mode = AddrModeFlat; + frame.Virtual = TRUE; + + CriticalSectionLocker<> cs(g_heapMapLock); + CriticalSectionLocker locker(g_DbgHelp); + + // Walk the stack. + while (count < maxdepth) { + count++; + DbgTrace(L"dbghelp32.dll %i: StackWalk64\n", GetCurrentThreadId()); + if (!g_DbgHelp.StackWalk64(architecture, g_currentProcess, g_currentThread, &frame, ¤tContext, NULL, + SymFunctionTableAccess64, SymGetModuleBase64, NULL, locker)) { + // Couldn't trace back through any more frames. + break; + } + if (frame.AddrFrame.Offset == 0) { + // End of stack. + break; + } + + // Push this frame's program counter onto the CallStack. + push_back((UINT_PTR)frame.AddrPC.Offset); + } +} + +// getHashValue - Generate callstack hash value. +// +// Return Value: +// +// None. +// +DWORD SafeCallStack::getHashValue() const +{ + DWORD hashcode = 0xD202EF8D; + + // Iterate through each frame in the call stack. + for (UINT32 frame = 0; frame < m_size; frame++) { + UINT_PTR programcounter = (*this)[frame]; + hashcode = CalculateCRC32(programcounter, hashcode); + } + return hashcode; +} diff --git a/src/callstack.h b/src/callstack.h new file mode 100644 index 00000000..9dfa353e --- /dev/null +++ b/src/callstack.h @@ -0,0 +1,178 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - CallStack Class Definitions +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef VLDBUILD +#error \ + "This header should only be included by Visual Leak Detector when building it from source. \ + Applications should never include this header." +#endif + +#include +#include "utility.h" + +#define CALLSTACK_CHUNK_SIZE 32 // Number of frame slots in each CallStack chunk. +#define MAX_SYMBOL_NAME_LENGTH 256 // Maximum symbol name length that we will allow. Longer names will be truncated. +#define MAX_SYMBOL_NAME_SIZE ((MAX_SYMBOL_NAME_LENGTH * sizeof(WCHAR)) - 1) + +//////////////////////////////////////////////////////////////////////////////// +// +// The CallStack Class +// +// CallStack objects can be used for obtaining, storing, and displaying the +// call stack at a given point during program execution. +// +// The primary data structure used by the CallStack is similar in concept to +// a STL vector, but is specifically tailored for use by VLD, making it more +// efficient than a standard STL vector. +// +// Inside the CallStack are a number of "chunks" which are arranged in a +// linked list. Each chunk contains an array of frames (each frame is +// represented by a program counter address). If we run out of space when +// pushing new frames onto an existing chunk in the CallStack chunk list, +// then a new chunk is allocated and appended to the end of the list. In this +// way, the CallStack can grow dynamically as needed. New frames are always +// pushed onto the chunk at the end of the list known as the "top" chunk. +// +// IMPORTANT NOTE: This class as originally written makes two fatal assumptions: +// First: That the application will never load modules (call LoadLibrary) during the +// lifetime of the app. +// Second: That modules will never get unloaded (call to FreeLibrary) +// during the lifetime of the app. +// The result of this assumption is that +// memory allocations whose call stacks goes through dynamically loaded modules +// will be incomplete. This is manifested by stack frames that cannot be resolved +// when the stack is 'dumped' because the binaries have been unloaded from the +// process. +// To rectify this situation, it is up to the caller to resolve or format the call stacks +// into human readable form, BEFORE the callers process unloads any modules. That is +// done by calling VisualLeakDetector::ResolveCallstacks, which can be called from +// external code by the exported VLDResolveCallstacks function. +// When this happens, the call stacks are formatted, and then cached for later dumping. +// This has performance penalties, as the current implementation saves all info to heap memory, +// and it is wasteful, as some of the 'converted' memory is not a true leak, but will get +// properly de-allocated at a later time. However there is no other way to work around the +// fact that the call stacks can only get formatted when the binary is loaded in the process. +// +class CallStack +{ +public: + CallStack (); + virtual ~CallStack (); + static CallStack* Create(); + // Public APIs - see each function definition for details. + VOID clear (); + // Prints the call stack to one of either / or the debug output window and or + // a log file. + VOID dump (BOOL showinternalframes); + // Formats the stack frame into a human readable format, and saves it for later retrieval. + int resolve(BOOL showinternalframes); + // Formats the stack frame into a human readable format, and saves it for later retrieval. + CONST WCHAR* getResolvedCallstack(BOOL showinternalframes); + virtual DWORD getHashValue() const = 0; + virtual VOID getStackTrace (UINT32 maxdepth, const context_t& context) = 0; + bool isCrtStartupAlloc(); + + BOOL operator == (const CallStack &other) const; + UINT_PTR operator [] (UINT32 index) const; + VOID push_back (const UINT_PTR programcounter); + +protected: + // Protected data. + UINT32 m_status; // Status flags: +#define CALLSTACK_STATUS_INCOMPLETE 0x1 // If set, the stack trace stored in this CallStack appears to be incomplete. +#define CALLSTACK_STATUS_STARTUPCRT 0x2 // If set, the stack trace is startup CRT. +#define CALLSTACK_STATUS_NOTSTARTUPCRT 0x4 // If set, the stack trace is not startup CRT. + + // The chunk list is made of a linked list of Chunks. + struct chunk_t { + chunk_t* next; // Pointer to the next chunk in the chunk list. + UINT_PTR frames[CALLSTACK_CHUNK_SIZE]; // Pushed frames (program counter addresses) are stored in this array. + }; + + // Private data. + UINT32 m_capacity; // Current capacity limit (in frames) + UINT32 m_size; // Current size (in frames) + CallStack::chunk_t m_store; // Pointer to the underlying data store (i.e. head of the chunk list) + CallStack::chunk_t* m_topChunk; // Pointer to the chunk at the top of the stack + UINT32 m_topIndex; // Index, within the top chunk, of the top of the stack + + // The string that contains the stack converted into a human readable format. + // This is always NULL if the callstack has not been 'converted'. + WCHAR* m_resolved; + int m_resolvedCapacity; + int m_resolvedLength; + + bool isInternalModule( const PWSTR filename ) const; + UINT isCrtStartupFunction( LPCWSTR functionName ) const; + LPCWSTR getFunctionName(SIZE_T programCounter, DWORD64& displacement64, + SYMBOL_INFO* functionInfo, CriticalSectionLocker& locker) const; + DWORD resolveFunction(SIZE_T programCounter, IMAGEHLP_LINEW64* sourceInfo, DWORD displacement, + LPCWSTR functionName, LPWSTR stack_line, DWORD stackLineSize) const; + +private: + // Don't allow this!! + CallStack(const CallStack &other); + // Don't allow this!! + CallStack& operator = (const CallStack &other); +}; + + +//////////////////////////////////////////////////////////////////////////////// +// +// The FastCallStack Class +// +// This class is a specialization of the CallStack class which provides a +// very fast stack tracing function. +// +class FastCallStack : public CallStack +{ +public: + FastCallStack() + : m_hashValue(0) + { + } + virtual VOID getStackTrace (UINT32 maxdepth, const context_t& context); + virtual DWORD getHashValue() const + { + return m_hashValue; + } + +private: + UINT32 m_hashValue; +}; + +//////////////////////////////////////////////////////////////////////////////// +// +// The SafeCallStack Class +// +// This class is a specialization of the CallStack class which provides a +// more robust, but quite slow, stack tracing function. +// +class SafeCallStack : public CallStack +{ +public: + virtual VOID getStackTrace (UINT32 maxdepth, const context_t& context); + virtual DWORD getHashValue() const; +}; diff --git a/src/criticalsection.h b/src/criticalsection.h new file mode 100644 index 00000000..76607bf7 --- /dev/null +++ b/src/criticalsection.h @@ -0,0 +1,89 @@ +#pragma once + +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include + +// you should consider CriticalSectionLocker<> whenever possible instead of +// directly working with CriticalSection class - it is safer +class CriticalSection +{ +public: + void Initialize() + { + m_critRegion.OwningThread = 0; + __try { + InitializeCriticalSection(&m_critRegion); + } __except (GetExceptionCode() == STATUS_NO_MEMORY ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + assert(FALSE); + } + } + void Delete() { DeleteCriticalSection(&m_critRegion); } + + // enter the section + void Enter() + { + ULONG_PTR ownerThreadId = (ULONG_PTR)m_critRegion.OwningThread; + UNREFERENCED_PARAMETER(ownerThreadId); + EnterCriticalSection(&m_critRegion); + } + + bool IsLocked() + { + return (m_critRegion.OwningThread != NULL); + } + + bool IsLockedByCurrentThread() + { + if (m_critRegion.OwningThread == NULL) + return false; + HANDLE ownerThreadId = (HANDLE)GetCurrentThreadId(); + return m_critRegion.OwningThread == ownerThreadId; + } + + // try enter the section + bool TryEnter() { return (TryEnterCriticalSection(&m_critRegion) != 0); } + + // leave the critical section + void Leave() { LeaveCriticalSection(&m_critRegion); } + +private: + CRITICAL_SECTION m_critRegion; +}; + +template +class CriticalSectionLocker +{ +public: + CriticalSectionLocker(T& cs) + : m_leave(false) + , m_critSect(cs) + { + m_critSect.Enter(); + } + + ~CriticalSectionLocker() + { + LeaveLock(); + } + + void Leave() + { + LeaveLock(); + } + +private: + void LeaveLock() + { + if (!m_leave) + { + m_critSect.Leave(); + m_leave = true; + } + } + CriticalSectionLocker(); // not allowed + CriticalSectionLocker( const CriticalSectionLocker & ); // not allowed + CriticalSectionLocker & operator=( const CriticalSectionLocker & ); // not allowed + bool m_leave; + T& m_critSect; +}; diff --git a/src/crtmfcpatch.h b/src/crtmfcpatch.h new file mode 100644 index 00000000..ef3a1fbb --- /dev/null +++ b/src/crtmfcpatch.h @@ -0,0 +1,1349 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - CRT and MFC IAT Patch Functions Header +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef VLDBUILD +#error \ +"This header should only be included by Visual Leak Detector when building it from source. \ +Applications should never include this header." +#endif + +#include "vldint.h" +extern __declspec(dllexport) VisualLeakDetector g_vld; + +//#define PRINTHOOKCALLS +//#define PRINTHOOKCALLS2 +#include + +#ifdef PRINTHOOKCALLS +#define PRINT_HOOKED_FUNCTION() DbgReport(_T(__FUNCTION__) _T( "\n")) +#else +#define PRINT_HOOKED_FUNCTION() +#endif +#ifdef PRINTHOOKCALLS2 +#define PRINT_HOOKED_FUNCTION2() DbgReport(_T(__FUNCTION__) _T( "\n")) +#else +#define PRINT_HOOKED_FUNCTION2() +#endif + +template +class CrtPatch +{ +public: + static CrtPatch data; + + static void* __cdecl crtd__calloc_dbg (size_t num, size_t size, int type, char const *file, int line); + static void* __cdecl crtd__malloc_dbg (size_t size, int type, const char *file, int line); + static void* __cdecl crtd__realloc_dbg (void *mem, size_t size, int type, char const *file, int line); + static void* __cdecl crtd__recalloc_dbg (void *mem, size_t num, size_t size, int type, char const *file, int line); + static void* __cdecl crtd__scalar_new_dbg (size_t size, int type, char const *file, int line); + static void* __cdecl crtd__vector_new_dbg (size_t size, int type, char const *file, int line); + static void* __cdecl crtd_calloc (size_t num, size_t size); + static void* __cdecl crtd_malloc (size_t size); + static void* __cdecl crtd_realloc (void *mem, size_t size); + static void* __cdecl crtd__recalloc (void *mem, size_t num, size_t size); + + static char* __cdecl crtd__strdup (const char* src); + static char* __cdecl crtd__strdup_dbg (const char* src, int type, char const *file, int line); + static wchar_t* __cdecl crtd__wcsdup (const wchar_t* src); + static wchar_t* __cdecl crtd__wcsdup_dbg (const wchar_t* src, int type, char const *file, int line); + + static void* __cdecl crtd_scalar_new (size_t size); + static void* __cdecl crtd_vector_new (size_t size); + + static void* __cdecl crtd__aligned_malloc_dbg (size_t size, size_t alignment, int type, const char *file, int line); + static void* __cdecl crtd__aligned_offset_malloc_dbg (size_t size, size_t alignment, size_t offset, int type, const char *file, int line); + static void* __cdecl crtd__aligned_realloc_dbg (void *mem, size_t size, size_t alignment, int type, char const *file, int line); + static void* __cdecl crtd__aligned_offset_realloc_dbg (void *mem, size_t size, size_t alignment, size_t offset, int type, char const *file, int line); + static void* __cdecl crtd__aligned_recalloc_dbg (void *mem, size_t num, size_t size, size_t alignment, int type, char const *file, int line); + static void* __cdecl crtd__aligned_offset_recalloc_dbg (void *mem, size_t num, size_t size, size_t alignment, size_t offset, int type, char const *file, int line); + static void* __cdecl crtd__aligned_malloc (size_t size, size_t alignment); + static void* __cdecl crtd__aligned_offset_malloc (size_t size, size_t alignment, size_t offset); + static void* __cdecl crtd__aligned_realloc (void *memblock, size_t size, size_t alignment); + static void* __cdecl crtd__aligned_offset_realloc (void *memblock, size_t size, size_t alignment, size_t offset); + static void* __cdecl crtd__aligned_recalloc (void *memblock, size_t num, size_t size, size_t alignment); + static void* __cdecl crtd__aligned_offset_recalloc (void *memblock, size_t num, size_t size, size_t alignment, size_t offset); + + union + { + void* function[28]; + struct + { + void* pcrtd__calloc_dbg; + void* pcrtd__malloc_dbg; + void* pcrtd__realloc_dbg; + void* pcrtd__recalloc_dbg; + void* pcrtd__strdup_dbg; + void* pcrtd__wcsdup_dbg; + void* pcrtd_calloc; + void* pcrtd_malloc; + void* pcrtd_realloc; + void* pcrtd_recalloc; + void* pcrtd__strdup; + void* pcrtd__wcsdup; + void* pcrtd__aligned_malloc_dbg; + void* pcrtd__aligned_offset_malloc_dbg; + void* pcrtd__aligned_realloc_dbg; + void* pcrtd__aligned_offset_realloc_dbg; + void* pcrtd__aligned_recalloc_dbg; + void* pcrtd__aligned_offset_recalloc_dbg; + void* pcrtd_aligned_malloc; + void* pcrtd_aligned_offset_malloc; + void* pcrtd_aligned_realloc; + void* pcrtd_aligned_offset_realloc; + void* pcrtd_aligned_recalloc; + void* pcrtd_aligned_offset_recalloc; + void* pcrtd__scalar_new_dbg; + void* pcrtd__vector_new_dbg; + void* pcrtd_scalar_new; + void* pcrtd_vector_new; + }; + }; +}; + +template +class MfcPatch +{ +public: + static MfcPatch data; + + static void* __cdecl mfcd_vector_new(size_t size); + static void* __cdecl mfcd__vector_new_dbg_4p(size_t size, int type, char const *file, int line); + static void* __cdecl mfcd__vector_new_dbg_3p(size_t size, char const *file, int line); + static void* __cdecl mfcd_scalar_new(size_t size); + static void* __cdecl mfcd__scalar_new_dbg_4p(size_t size, int type, char const *file, int line); + static void* __cdecl mfcd__scalar_new_dbg_3p(size_t size, char const *file, int line); + static void* __cdecl mfcud_vector_new(size_t size); + static void* __cdecl mfcud__vector_new_dbg_4p(size_t size, int type, char const *file, int line); + static void* __cdecl mfcud__vector_new_dbg_3p(size_t size, char const *file, int line); + static void* __cdecl mfcud_scalar_new(size_t size); + static void* __cdecl mfcud__scalar_new_dbg_4p(size_t size, int type, char const *file, int line); + static void* __cdecl mfcud__scalar_new_dbg_3p(size_t size, char const *file, int line); + + union + { + void* function[12]; + struct + { + void* pmfcd_scalar_new; + void* pmfcd_vector_new; + void* pmfcd__scalar_new_dbg_4p; + void* pmfcd__vector_new_dbg_4p; + void* pmfcd__scalar_new_dbg_3p; + void* pmfcd__vector_new_dbg_3p; + + void* pmfcud_scalar_new; + void* pmfcud_vector_new; + void* pmfcud__scalar_new_dbg_4p; + void* pmfcud__vector_new_dbg_4p; + void* pmfcud__scalar_new_dbg_3p; + void* pmfcud__vector_new_dbg_3p; + }; + }; +}; + +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Studio DLLs +// +//////////////////////////////////////////////////////////////////////////////// + +// crtd__calloc_dbg - Calls to _calloc_dbg from msvcrXXd.dll are patched +// through to this function. +// +// - mem (IN): Pointer to the memory block to be reallocated. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// - type (IN): The CRT "use type" of the block to be allocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by _calloc_dbg. +// +template +void* CrtPatch::crtd__calloc_dbg (size_t num, + size_t size, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + _calloc_dbg_t pcrtxxd__calloc_dbg = (_calloc_dbg_t)data.pcrtd__calloc_dbg; + assert(pcrtxxd__calloc_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd__calloc_dbg, context_, debug, (CRTVersion >= 140)); + + return pcrtxxd__calloc_dbg(num, size, type, file, line); +} + +// crtd__malloc_dbg - Calls to _malloc_dbg from msvcrXXd.dll are patched +// through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// - type (IN): The CRT "use type" of the block to be allocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by _malloc_dbg. +// +template +void* CrtPatch::crtd__malloc_dbg (size_t size, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + _malloc_dbg_t pcrtxxd__malloc_dbg = (_malloc_dbg_t)data.pcrtd__malloc_dbg; + assert(pcrtxxd__malloc_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd__malloc_dbg, context_, debug, (CRTVersion >= 140)); + return pcrtxxd__malloc_dbg(size, type, file, line); +} + +// crtd__realloc_dbg - Calls to _realloc_dbg from msvcrXXd.dll are patched +// through to this function. +// +// - mem (IN): Pointer to the memory block to be reallocated. +// +// - size (IN): The size of the memory block to reallocate. +// +// - type (IN): The CRT "use type" of the block to be reallocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by _realloc_dbg. +// +template +void* CrtPatch::crtd__realloc_dbg (void *mem, + size_t size, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + _realloc_dbg_t pcrtxxd__realloc_dbg = (_realloc_dbg_t)data.pcrtd__realloc_dbg; + assert(pcrtxxd__realloc_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd__realloc_dbg, context_, debug, (CRTVersion >= 140)); + return pcrtxxd__realloc_dbg(mem, size, type, file, line); +} + +// crtd__recalloc_dbg - Calls to _recalloc_dbg from msvcrXXd.dll are patched +// through to this function. +// +// - mem (IN): Pointer to the memory block to be reallocated. +// +// - size (IN): The size of the memory block to reallocate. +// +// - type (IN): The CRT "use type" of the block to be reallocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by _realloc_dbg. +// +template +void* CrtPatch::crtd__recalloc_dbg (void *mem, + size_t num, + size_t size, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + _recalloc_dbg_t pcrtxxd__recalloc_dbg = (_recalloc_dbg_t)data.pcrtd__recalloc_dbg; + assert(pcrtxxd__recalloc_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd__recalloc_dbg, context_, debug, (CRTVersion >= 140)); + return pcrtxxd__recalloc_dbg(mem, num, size, type, file, line); +} + + +template +char* CrtPatch::crtd__strdup_dbg (const char* src, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + _strdup_dbg_t pcrtxxd__strdup_dbg = (_strdup_dbg_t)data.pcrtd__strdup_dbg; + assert(pcrtxxd__strdup_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd__strdup_dbg, context_, debug, (CRTVersion >= 140)); + return pcrtxxd__strdup_dbg(src, type, file, line); +} + + +template +wchar_t* CrtPatch::crtd__wcsdup_dbg (const wchar_t* src, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + _wcsdup_dbg_t pcrtxxd__wcsdup_dbg = (_wcsdup_dbg_t)data.pcrtd__wcsdup_dbg; + assert(pcrtxxd__wcsdup_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd__wcsdup_dbg, context_, debug, (CRTVersion >= 140)); + return pcrtxxd__wcsdup_dbg(src, type, file, line); +} + +// crtd__scalar_new_dbg - Calls to the CRT's debug scalar new operator from +// msvcrXXd.dll are patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// - type (IN): The CRT "use type" of the block to be allocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by the CRT debug scalar new operator. +// +template +void* CrtPatch::crtd__scalar_new_dbg (size_t size, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + new_dbg_crt_t pcrtxxd_new_dbg = (new_dbg_crt_t)data.pcrtd__scalar_new_dbg; + assert(pcrtxxd_new_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_new_dbg, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_new_dbg(size, type, file, line); +} + +// crtd__vector_new_dbg - Calls to the CRT's debug vector new operator from +// msvcrXXd.dll are patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// - type (IN): The CRT "use type" of the block to be allocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by the CRT debug vector new operator. +// +template +void* CrtPatch::crtd__vector_new_dbg (size_t size, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + new_dbg_crt_t pcrtxxd_new_dbg = (new_dbg_crt_t)data.pcrtd__vector_new_dbg; + assert(pcrtxxd_new_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_new_dbg, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_new_dbg(size, type, file, line); +} + +// crtd_calloc - Calls to calloc from msvcrXXd.dll are patched through to +// this function. +// +// - dll (IN): The name of the dll +// +// - num (IN): The number of blocks, of size 'size', to be allocated. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// Return Value: +// +// Returns the valued returned from calloc. +// +template +void* CrtPatch::crtd_calloc (size_t num, size_t size) +{ + PRINT_HOOKED_FUNCTION(); + calloc_t pcrtxxd_calloc = (calloc_t)data.pcrtd_calloc; + assert(pcrtxxd_calloc); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_calloc, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_calloc(num, size); +} + +// crtd_malloc - Calls to malloc from msvcrXXd.dll are patched through to +// this function. +// +// - dll (IN): The name of the dll +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// Return Value: +// +// Returns the valued returned from malloc. +// +template +void* CrtPatch::crtd_malloc (size_t size) +{ + PRINT_HOOKED_FUNCTION(); + malloc_t pcrtxxd_malloc = (malloc_t)data.pcrtd_malloc; + assert(pcrtxxd_malloc); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_malloc, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_malloc(size); +} + +// crtd_realloc - Calls to realloc from msvcrXXd.dll are patched through to +// this function. +// +// - dll (IN): The name of the dll +// +// - mem (IN): Pointer to the memory block to reallocate. +// +// - size (IN): Size of the memory block to reallocate. +// +// Return Value: +// +// Returns the value returned from realloc. +// +template +void* CrtPatch::crtd_realloc (void *mem, size_t size) +{ + PRINT_HOOKED_FUNCTION(); + realloc_t pcrtxxd_realloc = (realloc_t)data.pcrtd_realloc; + assert(pcrtxxd_realloc); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_realloc, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_realloc(mem, size); +} + +// crtd__recalloc - Calls to _recalloc from msvcrXXd.dll are patched through to +// this function. +// +// - dll (IN): The name of the dll +// +// - mem (IN): Pointer to the memory block to reallocate. +// +// - size (IN): Size of the memory block to reallocate. +// +// Return Value: +// +// Returns the value returned from realloc. +// +template +void* CrtPatch::crtd__recalloc (void *mem, size_t num, size_t size) +{ + PRINT_HOOKED_FUNCTION(); + _recalloc_t pcrtxxd_recalloc = (_recalloc_t)data.pcrtd_recalloc; + assert(pcrtxxd_recalloc); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_recalloc, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_recalloc(mem, num, size); +} + + +template +char* CrtPatch::crtd__strdup (const char* src) +{ + PRINT_HOOKED_FUNCTION(); + _strdup_t pcrtxxd_strdup = (_strdup_t)data.pcrtd__strdup; + assert(pcrtxxd_strdup); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_strdup, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_strdup(src); +} + +template +wchar_t* CrtPatch::crtd__wcsdup (const wchar_t* src) +{ + PRINT_HOOKED_FUNCTION(); + _wcsdup_t pcrtxxd_wcsdup = (_wcsdup_t)data.pcrtd__wcsdup; + assert(pcrtxxd_wcsdup); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_wcsdup, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_wcsdup(src); +} + +// crtd__aligned_malloc_dbg - Calls to _aligned_malloc_dbg from msvcrXXd.dll are patched +// through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// - type (IN): The CRT "use type" of the block to be allocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by _aligned_malloc_dbg. +// +template +void* CrtPatch::crtd__aligned_malloc_dbg (size_t size, + size_t alignment, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + _aligned_malloc_dbg_t pcrtxxd__aligned_malloc_dbg = (_aligned_malloc_dbg_t)data.pcrtd__aligned_malloc_dbg; + assert(pcrtxxd__aligned_malloc_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd__aligned_malloc_dbg, context_, debug, (CRTVersion >= 140)); + return pcrtxxd__aligned_malloc_dbg(size, alignment, type, file, line); +} + +// crtd__aligned_offset_malloc_dbg - Calls to _aligned_offset_malloc_dbg from msvcrXXd.dll are patched +// through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// - type (IN): The CRT "use type" of the block to be allocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by _aligned_offset_malloc_dbg. +// +template +void* CrtPatch::crtd__aligned_offset_malloc_dbg (size_t size, + size_t alignment, + size_t offset, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + _aligned_offset_malloc_dbg_t pcrtxxd__malloc_dbg = (_aligned_offset_malloc_dbg_t)data.pcrtd__aligned_offset_malloc_dbg; + assert(pcrtxxd__malloc_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd__malloc_dbg, context_, debug, (CRTVersion >= 140)); + return pcrtxxd__malloc_dbg(size, alignment, offset, type, file, line); +} + +// crtd__aligned_realloc_dbg - Calls to _aligned_realloc_dbg from msvcrXXd.dll are patched +// through to this function. +// +// - mem (IN): Pointer to the memory block to be reallocated. +// +// - size (IN): The size of the memory block to reallocate. +// +// - type (IN): The CRT "use type" of the block to be reallocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by _aligned_realloc_dbg. +// +template +void* CrtPatch::crtd__aligned_realloc_dbg (void *mem, + size_t size, + size_t alignment, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + _aligned_realloc_dbg_t pcrtxxd__realloc_dbg = (_aligned_realloc_dbg_t)data.pcrtd__aligned_realloc_dbg; + assert(pcrtxxd__realloc_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd__realloc_dbg, context_, debug, (CRTVersion >= 140)); + return pcrtxxd__realloc_dbg(mem, size, alignment, type, file, line); +} + +// crtd__aligned_offset_realloc_dbg - Calls to _aligned_offset_realloc_dbg from msvcrXXd.dll are patched +// through to this function. +// +// - mem (IN): Pointer to the memory block to be reallocated. +// +// - size (IN): The size of the memory block to reallocate. +// +// - type (IN): The CRT "use type" of the block to be reallocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by _aligned_offset_realloc_dbg. +// +template +void* CrtPatch::crtd__aligned_offset_realloc_dbg (void *mem, + size_t size, + size_t alignment, + size_t offset, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + _aligned_offset_realloc_dbg_t pcrtxxd__realloc_dbg = (_aligned_offset_realloc_dbg_t)data.pcrtd__aligned_offset_realloc_dbg; + assert(pcrtxxd__realloc_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd__realloc_dbg, context_, debug, (CRTVersion >= 140)); + return pcrtxxd__realloc_dbg(mem, size, alignment, offset, type, file, line); +} + +// crtd__aligned_recalloc_dbg - Calls to _aligned_recalloc_dbg from msvcrXXd.dll are patched +// through to this function. +// +// - mem (IN): Pointer to the memory block to be reallocated. +// +// - num (IN): The count of the memory block to reallocate. +// +// - size (IN): The size of the memory block to reallocate. +// +// - type (IN): The CRT "use type" of the block to be reallocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by _aligned_realloc_dbg. +// +template +void* CrtPatch::crtd__aligned_recalloc_dbg (void *mem, + size_t num, + size_t size, + size_t alignment, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + _aligned_recalloc_dbg_t pcrtxxd__recalloc_dbg = (_aligned_recalloc_dbg_t)data.pcrtd__aligned_recalloc_dbg; + assert(pcrtxxd__recalloc_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd__recalloc_dbg, context_, debug, (CRTVersion >= 140)); + return pcrtxxd__recalloc_dbg(mem, num, size, alignment, type, file, line); +} + +// crtd__aligned_offset_recalloc_dbg - Calls to _aligned_offset_realloc_dbg from msvcrXXd.dll are patched +// through to this function. +// +// - mem (IN): Pointer to the memory block to be reallocated. +// +// - num (IN): The count of the memory block to reallocate. +// +// - size (IN): The size of the memory block to reallocate. +// +// - type (IN): The CRT "use type" of the block to be reallocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by _aligned_offset_realloc_dbg. +// +template +void* CrtPatch::crtd__aligned_offset_recalloc_dbg (void *mem, + size_t num, + size_t size, + size_t alignment, + size_t offset, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + _aligned_offset_recalloc_dbg_t pcrtxxd__recalloc_dbg = (_aligned_offset_recalloc_dbg_t)data.pcrtd__aligned_offset_recalloc_dbg; + assert(pcrtxxd__recalloc_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd__recalloc_dbg, context_, debug, (CRTVersion >= 140)); + return pcrtxxd__recalloc_dbg(mem, num, size, alignment, offset, type, file, line); +} + +// crtd__aligned_malloc - Calls to malloc from msvcrXXd.dll are patched through to +// this function. +// +// - dll (IN): The name of the dll +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// Return Value: +// +// Returns the valued returned from malloc. +// +template +void* CrtPatch::crtd__aligned_malloc (size_t size, size_t alignment) +{ + PRINT_HOOKED_FUNCTION(); + _aligned_malloc_t pcrtxxd_malloc = (_aligned_malloc_t)data.pcrtd_aligned_malloc; + assert(pcrtxxd_malloc); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_malloc, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_malloc(size, alignment); +} + +// crtd__aligned_offset_malloc - Calls to malloc from msvcrXXd.dll are patched through to +// this function. +// +// - dll (IN): The name of the dll +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// Return Value: +// +// Returns the valued returned from malloc. +// +template +void* CrtPatch::crtd__aligned_offset_malloc (size_t size, size_t alignment, size_t offset) +{ + PRINT_HOOKED_FUNCTION(); + _aligned_offset_malloc_t pcrtxxd_malloc = (_aligned_offset_malloc_t)data.pcrtd_aligned_offset_malloc; + assert(pcrtxxd_malloc); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_malloc, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_malloc(size, alignment, offset); +} + +// crtd__aligned_realloc - Calls to realloc from msvcrXXd.dll are patched through to +// this function. +// +// - dll (IN): The name of the dll +// +// - mem (IN): Pointer to the memory block to reallocate. +// +// - size (IN): Size of the memory block to reallocate. +// +// Return Value: +// +// Returns the value returned from realloc. +// +template +void* CrtPatch::crtd__aligned_realloc (void *mem, size_t size, size_t alignment) +{ + PRINT_HOOKED_FUNCTION(); + _aligned_realloc_t pcrtxxd_realloc = (_aligned_realloc_t)data.pcrtd_aligned_realloc; + assert(pcrtxxd_realloc); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_realloc, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_realloc(mem, size, alignment); +} + +// crtd__aligned_offset_realloc - Calls to realloc from msvcrXXd.dll are patched through to +// this function. +// +// - dll (IN): The name of the dll +// +// - mem (IN): Pointer to the memory block to reallocate. +// +// - size (IN): Size of the memory block to reallocate. +// +// Return Value: +// +// Returns the value returned from realloc. +// +template +void* CrtPatch::crtd__aligned_offset_realloc (void *mem, size_t size, size_t alignment, size_t offset) +{ + PRINT_HOOKED_FUNCTION(); + _aligned_offset_realloc_t pcrtxxd_realloc = (_aligned_offset_realloc_t)data.pcrtd_aligned_offset_realloc; + assert(pcrtxxd_realloc); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_realloc, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_realloc(mem, size, alignment, offset); +} + +// crtd__aligned_recalloc - Calls to realloc from msvcrXXd.dll are patched through to +// this function. +// +// - dll (IN): The name of the dll +// +// - num (IN): Count of the memory block to reallocate. +// +// - mem (IN): Pointer to the memory block to reallocate. +// +// - size (IN): Size of the memory block to reallocate. +// +// Return Value: +// +// Returns the value returned from realloc. +// +template +void* CrtPatch::crtd__aligned_recalloc (void *mem, size_t num, size_t size, size_t alignment) +{ + PRINT_HOOKED_FUNCTION(); + _aligned_recalloc_t pcrtxxd_recalloc = (_aligned_recalloc_t)data.pcrtd_aligned_recalloc; + assert(pcrtxxd_recalloc); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_recalloc, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_recalloc(mem, num, size, alignment); +} + +// crtd__aligned_offset_recalloc - Calls to realloc from msvcrXXd.dll are patched through to +// this function. +// +// - dll (IN): The name of the dll +// +// - mem (IN): Pointer to the memory block to reallocate. +// +// - num (IN): Count of the memory block to reallocate. +// +// - size (IN): Size of the memory block to reallocate. +// +// Return Value: +// +// Returns the value returned from realloc. +// +template +void* CrtPatch::crtd__aligned_offset_recalloc (void *mem, size_t num, size_t size, size_t alignment, size_t offset) +{ + PRINT_HOOKED_FUNCTION(); + _aligned_offset_recalloc_t pcrtxxd_recalloc = (_aligned_offset_recalloc_t)data.pcrtd_aligned_offset_recalloc; + assert(pcrtxxd_recalloc); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_recalloc, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_recalloc(mem, num, size, alignment, offset); +} + +// crtd_scalar_new - Calls to the CRT's scalar new operator from msvcrXXd.dll +// are patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// Return Value: +// +// Returns the value returned by the CRT scalar new operator. +// +template +void* CrtPatch::crtd_scalar_new (size_t size) +{ + PRINT_HOOKED_FUNCTION(); + new_t pcrtxxd_scalar_new = (new_t)data.pcrtd_scalar_new; + assert(pcrtxxd_scalar_new); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_scalar_new, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_scalar_new(size); +} + +// crtd_vector_new - Calls to the CRT's vector new operator from msvcrXXd.dll +// are patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// Return Value: +// +// Returns the value returned by the CRT vector new operator. +// +template +void* CrtPatch::crtd_vector_new (size_t size) +{ + PRINT_HOOKED_FUNCTION(); + new_t pcrtxxd_vector_new = (new_t)data.pcrtd_vector_new; + assert(pcrtxxd_vector_new); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pcrtxxd_vector_new, context_, debug, (CRTVersion >= 140)); + return pcrtxxd_vector_new(size); +} + +//////////////////////////////////////////////////////////////////////////////// +// +// MFC DLLs +// +//////////////////////////////////////////////////////////////////////////////// + +// mfcd__scalar_new_dbg_3p - Calls to the MFC debug scalar new operator from +// mfcXXd.dll are patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// - type (IN): The "use type" of the block to be allocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by the MFC debug scalar new operator. +// +template +void* MfcPatch::mfcd__scalar_new_dbg_4p (size_t size, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + new_dbg_crt_t pmfcxxd__new_dbg = (new_dbg_crt_t)data.pmfcd__scalar_new_dbg_4p; + assert(pmfcxxd__new_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pmfcxxd__new_dbg, context_, debug, (CRTVersion >= 140)); + return pmfcxxd__new_dbg(size, type, file, line); +} + +// mfcd__scalar_new_dbg_3p - Calls to the MFC debug scalar new operator from +// mfcXXd.dll are patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by the MFC debug scalar new operator. +// +template +void* MfcPatch::mfcd__scalar_new_dbg_3p (size_t size, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + new_dbg_mfc_t pmfcxxd__new_dbg = (new_dbg_mfc_t)data.pmfcd__scalar_new_dbg_3p; + assert(pmfcxxd__new_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pmfcxxd__new_dbg, context_, debug, (CRTVersion >= 140)); + return pmfcxxd__new_dbg(size, file, line); +} + +// mfcd__vector_new_dbg_4p - Calls to the MFC debug vector new operator from +// mfcXXd.dll are patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// - type (IN): The "use type" of the block to be allocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by the MFC debug vector new operator. +// +template +void* MfcPatch::mfcd__vector_new_dbg_4p (size_t size, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + new_dbg_crt_t pmfcxxd__new_dbg = (new_dbg_crt_t)data.pmfcd__vector_new_dbg_4p; + assert(pmfcxxd__new_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pmfcxxd__new_dbg, context_, debug, (CRTVersion >= 140)); + return pmfcxxd__new_dbg(size, type, file, line); +} + +// mfcd__vector_new_dbg_3p - Calls to the MFC debug vector new operator from +// mfcXXd.dll are patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by the MFC debug vector new operator. +// +template +void* MfcPatch::mfcd__vector_new_dbg_3p (size_t size, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + new_dbg_mfc_t pmfcxxd__new_dbg = (new_dbg_mfc_t)data.pmfcd__vector_new_dbg_3p; + assert(pmfcxxd__new_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pmfcxxd__new_dbg, context_, debug, (CRTVersion >= 140)); + return pmfcxxd__new_dbg(size, file, line); +} + +// mfcd_scalar_new - Calls to the MFC scalar new operator from mfcXXd.dll are +// patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// Return Value: +// +// Returns the value returned by the MFC scalar new operator. +// +template +void* MfcPatch::mfcd_scalar_new (size_t size) +{ + PRINT_HOOKED_FUNCTION(); + new_t pmfcxxd_new = (new_t)data.pmfcd_scalar_new; + assert(pmfcxxd_new); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pmfcxxd_new, context_, debug, (CRTVersion >= 140)); + return pmfcxxd_new(size); +} + +// mfcd_vector_new - Calls to the MFC vector new operator from mfcXXd.dll are +// patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// Return Value: +// +// Returns the value returned by the MFC vector new operator. +// +template +void* MfcPatch::mfcd_vector_new (size_t size) +{ + PRINT_HOOKED_FUNCTION(); + new_t pmfcxxd_new = (new_t)data.pmfcd_vector_new; + assert(pmfcxxd_new); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pmfcxxd_new, context_, debug, (CRTVersion >= 140)); + return pmfcxxd_new(size); +} + +// mfcud__scalar_new_dbg_4p - Calls to the MFC debug scalar new operator from +// mfcXXud.dll are patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// - type (IN): The "use type" of the block to be allocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by the MFC debug scalar new operator. +// +template +void* MfcPatch::mfcud__scalar_new_dbg_4p (size_t size, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + new_dbg_crt_t pmfcxxd__new_dbg = (new_dbg_crt_t)data.pmfcud__scalar_new_dbg_4p; + assert(pmfcxxd__new_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pmfcxxd__new_dbg, context_, debug, (CRTVersion >= 140)); + return pmfcxxd__new_dbg(size, type, file, line); +} + +// mfcud__scalar_new_dbg_3p - Calls to the MFC debug scalar new operator from +// mfcXXud.dll are patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by the MFC debug scalar new operator. +// +template +void* MfcPatch::mfcud__scalar_new_dbg_3p (size_t size, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + new_dbg_mfc_t pmfcxxd__new_dbg = (new_dbg_mfc_t)data.pmfcud__scalar_new_dbg_3p; + assert(pmfcxxd__new_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pmfcxxd__new_dbg, context_, debug, (CRTVersion >= 140)); + return pmfcxxd__new_dbg(size, file, line); +} + +// mfcud__vector_new_dbg_4p - Calls to the MFC debug vector new operator from +// mfcXXud.dll are patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// - type (IN): The "use type" of the block to be allocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by the MFC debug vector new operator. +// +template +void* MfcPatch::mfcud__vector_new_dbg_4p (size_t size, + int type, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + new_dbg_crt_t pmfcxxd__new_dbg = (new_dbg_crt_t)data.pmfcud__vector_new_dbg_4p; + assert(pmfcxxd__new_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pmfcxxd__new_dbg, context_, debug, (CRTVersion >= 140)); + + return pmfcxxd__new_dbg(size, type, file, line); +} + +// mfcud__vector_new_dbg_3p - Calls to the MFC debug vector new operator from +// mfcXXud.dll are patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// - file (IN): The name of the file from which this function is being called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// Returns the value returned by the MFC debug vector new operator. +// +template +void* MfcPatch::mfcud__vector_new_dbg_3p (size_t size, + char const *file, + int line) +{ + PRINT_HOOKED_FUNCTION(); + new_dbg_mfc_t pmfcxxd__new_dbg = (new_dbg_mfc_t)data.pmfcud__vector_new_dbg_3p; + assert(pmfcxxd__new_dbg); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pmfcxxd__new_dbg, context_, debug, (CRTVersion >= 140)); + return pmfcxxd__new_dbg(size, file, line); +} + +// mfcud_scalar_new - Calls to the MFC scalar new operator from mfcXXud.dll are +// patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// Return Value: +// +// Returns the value returned by the MFC scalar new operator. +// +template +void* MfcPatch::mfcud_scalar_new (size_t size) +{ + PRINT_HOOKED_FUNCTION(); + new_t pmfcxxd_new = (new_t)data.pmfcud_scalar_new; + assert(pmfcxxd_new); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pmfcxxd_new, context_, debug, (CRTVersion >= 140)); + return pmfcxxd_new(size); +} + +// mfcud_vector_new - Calls to the MFC vector new operator from mfcXXud.dll are +// patched through to this function. +// +// - size (IN): The size, in bytes, of the memory block to be allocated. +// +// Return Value: +// +// Returns the value returned by the MFC vector new operator. +// +template +void* MfcPatch::mfcud_vector_new (size_t size) +{ + PRINT_HOOKED_FUNCTION(); + new_t pmfcxxd_new = (new_t)data.pmfcud_vector_new; + assert(pmfcxxd_new); + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pmfcxxd_new, context_, debug, (CRTVersion >= 140)); + return pmfcxxd_new(size); +} + +// Visual Studio 6.0 +typedef CrtPatch<60> VS60; +typedef CrtPatch<60, true> VS60d; +// Visual Studio .NET 2002 +typedef CrtPatch<70> VS70; +typedef CrtPatch<70, true> VS70d; +// Visual Studio .NET 2003 +typedef CrtPatch<71> VS71; +typedef CrtPatch<71, true> VS71d; +// Visual Studio 2005 +typedef CrtPatch<80> VS80; +typedef CrtPatch<80, true> VS80d; +// Visual Studio 2008 +typedef CrtPatch<90> VS90; +typedef CrtPatch<90, true> VS90d; +// Visual Studio 2010 +typedef CrtPatch<100> VS100; +typedef CrtPatch<100, true> VS100d; +// Visual Studio 2012 +typedef CrtPatch<110> VS110; +typedef CrtPatch<110, true> VS110d; +// Visual Studio 2013 +typedef CrtPatch<120> VS120; +typedef CrtPatch<120, true> VS120d; +// Visual Studio 2015 and higher +typedef CrtPatch<140> UCRT; +typedef CrtPatch<140, true> UCRTd; + +VS60 VS60::data; +VS60d VS60d::data; +VS70 VS70::data; +VS70d VS70d::data; +VS71 VS71::data; +VS71d VS71d::data; +VS80 VS80::data; +VS80d VS80d::data; +VS90 VS90::data; +VS90d VS90d::data; +VS100 VS100::data; +VS100d VS100d::data; +VS110 VS110::data; +VS110d VS110d::data; +VS120 VS120::data; +VS120d VS120d::data; +UCRT UCRT::data; +UCRTd UCRTd::data; + + +// Visual Studio 6.0 +typedef MfcPatch<60> Mfc60; +typedef MfcPatch<60, true> Mfc60d; +// Visual Studio .NET 2002 +typedef MfcPatch<70> Mfc70; +typedef MfcPatch<70, true> Mfc70d; +// Visual Studio .NET 2003 +typedef MfcPatch<71> Mfc71; +typedef MfcPatch<71, true> Mfc71d; +// Visual Studio 2005 +typedef MfcPatch<80> Mfc80; +typedef MfcPatch<80, true> Mfc80d; +// Visual Studio 2008 +typedef MfcPatch<90> Mfc90; +typedef MfcPatch<90, true> Mfc90d; +// Visual Studio 2010 +typedef MfcPatch<100> Mfc100; +typedef MfcPatch<100, true> Mfc100d; +// Visual Studio 2012 +typedef MfcPatch<110> Mfc110; +typedef MfcPatch<110, true> Mfc110d; +// Visual Studio 2013 +typedef MfcPatch<120> Mfc120; +typedef MfcPatch<120, true> Mfc120d; +// Visual Studio 2015 +typedef MfcPatch<140> Mfc140; +typedef MfcPatch<140, true> Mfc140d; + +Mfc60 Mfc60::data; +Mfc60d Mfc60d::data; +Mfc70 Mfc70::data; +Mfc70d Mfc70d::data; +Mfc71 Mfc71::data; +Mfc71d Mfc71d::data; +Mfc80 Mfc80::data; +Mfc80d Mfc80d::data; +Mfc90 Mfc90::data; +Mfc90d Mfc90d::data; +Mfc100 Mfc100::data; +Mfc100d Mfc100d::data; +Mfc110 Mfc110::data; +Mfc110d Mfc110d::data; +Mfc120 Mfc120::data; +Mfc120d Mfc120d::data; +Mfc140 Mfc140::data; +Mfc140d Mfc140d::data; \ No newline at end of file diff --git a/src/dbghelp.h b/src/dbghelp.h new file mode 100644 index 00000000..23b54d88 --- /dev/null +++ b/src/dbghelp.h @@ -0,0 +1,181 @@ +#pragma once + +#define WIN32_LEAN_AND_MEAN +#include +#include +#include "criticalsection.h" + +class DbgHelp +{ +public: + DbgHelp() { + m_lock.Initialize(); + } + ~DbgHelp() { + m_lock.Delete(); + } + void Enter() + { + m_lock.Enter(); + } + void Leave() + { + m_lock.Leave(); + } + BOOL IsLockedByCurrentThread() { + return + m_lock.IsLockedByCurrentThread(); + } + BOOL SymInitializeW(_In_ HANDLE hProcess, _In_opt_ PCWSTR UserSearchPath, _In_ BOOL fInvadeProcess, CriticalSectionLocker&) { + return ::SymInitializeW(hProcess, UserSearchPath, fInvadeProcess); + } + BOOL SymInitializeW(_In_ HANDLE hProcess, _In_opt_ PCWSTR UserSearchPath, _In_ BOOL fInvadeProcess) { + CriticalSectionLocker cs(m_lock); + return ::SymInitializeW(hProcess, UserSearchPath, fInvadeProcess); + } + BOOL SymCleanup(_In_ HANDLE hProcess, CriticalSectionLocker&) { + return ::SymCleanup(hProcess); + } + BOOL SymCleanup(_In_ HANDLE hProcess) { + CriticalSectionLocker cs(m_lock); + return ::SymCleanup(hProcess); + } + DWORD SymSetOptions(__in DWORD SymOptions, CriticalSectionLocker&) { + return ::SymSetOptions(SymOptions); + } + DWORD SymSetOptions(__in DWORD SymOptions) { + CriticalSectionLocker cs(m_lock); + return ::SymSetOptions(SymOptions); + } + BOOL SymFromAddrW(_In_ HANDLE hProcess, _In_ DWORD64 Address, _Out_opt_ PDWORD64 Displacement, _Inout_ PSYMBOL_INFOW Symbol, CriticalSectionLocker&) { + return ::SymFromAddrW(hProcess, Address, Displacement, Symbol); + } + BOOL SymFromAddrW(_In_ HANDLE hProcess, _In_ DWORD64 Address, _Out_opt_ PDWORD64 Displacement, _Inout_ PSYMBOL_INFOW Symbol) { + CriticalSectionLocker cs(m_lock); + return ::SymFromAddrW(hProcess, Address, Displacement, Symbol); + } + BOOL SymGetLineFromAddrW64(_In_ HANDLE hProcess, _In_ DWORD64 dwAddr, _Out_ PDWORD pdwDisplacement, _Out_ PIMAGEHLP_LINEW64 Line, CriticalSectionLocker&) { + return ::SymGetLineFromAddrW64(hProcess, dwAddr, pdwDisplacement, Line); + } + BOOL SymGetLineFromAddrW64(_In_ HANDLE hProcess, _In_ DWORD64 dwAddr, _Out_ PDWORD pdwDisplacement, _Out_ PIMAGEHLP_LINEW64 Line) { + CriticalSectionLocker cs(m_lock); + return ::SymGetLineFromAddrW64(hProcess, dwAddr, pdwDisplacement, Line); + } + BOOL SymGetModuleInfoW64(_In_ HANDLE hProcess, _In_ DWORD64 qwAddr, _Out_ PIMAGEHLP_MODULEW64 ModuleInfo, CriticalSectionLocker&) { + return ::SymGetModuleInfoW64(hProcess, qwAddr, ModuleInfo); + } + BOOL SymGetModuleInfoW64(_In_ HANDLE hProcess, _In_ DWORD64 qwAddr, _Out_ PIMAGEHLP_MODULEW64 ModuleInfo) { + CriticalSectionLocker cs(m_lock); + return ::SymGetModuleInfoW64(hProcess, qwAddr, ModuleInfo); + } + DWORD64 SymLoadModuleExW(_In_ HANDLE hProcess, _In_opt_ HANDLE hFile, _In_opt_ PCWSTR ImageName, _In_opt_ PCWSTR ModuleName, _In_ DWORD64 BaseOfDll, _In_ DWORD DllSize, _In_opt_ PMODLOAD_DATA Data, _In_opt_ DWORD Flags, CriticalSectionLocker&) { + return ::SymLoadModuleExW(hProcess, hFile, ImageName, ModuleName, BaseOfDll, DllSize, Data, Flags); + } + DWORD64 SymLoadModuleExW(_In_ HANDLE hProcess, _In_opt_ HANDLE hFile, _In_opt_ PCWSTR ImageName, _In_opt_ PCWSTR ModuleName, _In_ DWORD64 BaseOfDll, _In_ DWORD DllSize, _In_opt_ PMODLOAD_DATA Data, _In_opt_ DWORD Flags) { + CriticalSectionLocker cs(m_lock); + return ::SymLoadModuleExW(hProcess, hFile, ImageName, ModuleName, BaseOfDll, DllSize, Data, Flags); + } + BOOL SymUnloadModule64(_In_ HANDLE hProcess, _In_ DWORD64 BaseOfDll, CriticalSectionLocker&) { + return ::SymUnloadModule64(hProcess, BaseOfDll); + } + BOOL SymUnloadModule64(_In_ HANDLE hProcess, _In_ DWORD64 BaseOfDll) { + CriticalSectionLocker cs(m_lock); + return ::SymUnloadModule64(hProcess, BaseOfDll); + } + BOOL StackWalk64(__in DWORD MachineType, __in HANDLE hProcess, __in HANDLE hThread, + __inout LPSTACKFRAME64 StackFrame, __inout PVOID ContextRecord, + __in_opt PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, + __in_opt PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, + __in_opt PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, + __in_opt PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress, CriticalSectionLocker&) + { + return ::StackWalk64(MachineType, hProcess, hThread, StackFrame, ContextRecord, ReadMemoryRoutine, + FunctionTableAccessRoutine, GetModuleBaseRoutine, TranslateAddress); + } + BOOL StackWalk64(__in DWORD MachineType, __in HANDLE hProcess, __in HANDLE hThread, + __inout LPSTACKFRAME64 StackFrame, __inout PVOID ContextRecord, + __in_opt PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, + __in_opt PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, + __in_opt PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, + __in_opt PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress) + { + CriticalSectionLocker cs(m_lock); + return ::StackWalk64(MachineType, hProcess, hThread, StackFrame, ContextRecord, ReadMemoryRoutine, + FunctionTableAccessRoutine, GetModuleBaseRoutine, TranslateAddress); + } +private: + // Disallow certain operations + DbgHelp(const DbgHelp&); + DbgHelp& operator=(const DbgHelp&); + +private: + CriticalSection m_lock; +}; + +class ImageDirectoryEntries +{ +public: + ImageDirectoryEntries() { + m_lock.Initialize(); + } + ~ImageDirectoryEntries() { + m_lock.Delete(); + } + void Enter() + { + m_lock.Enter(); + } + void Leave() + { + m_lock.Leave(); + } + BOOL IsLockedByCurrentThread() { + return + m_lock.IsLockedByCurrentThread(); + } + PVOID ImageDirectoryEntryToDataEx(__in PVOID Base, __in BOOLEAN MappedAsImage, __in USHORT DirectoryEntry, __out PULONG Size, __out_opt PIMAGE_SECTION_HEADER *FoundHeader) { + CriticalSectionLocker cs(m_lock); + return ::ImageDirectoryEntryToDataEx(Base, MappedAsImage, DirectoryEntry, Size, FoundHeader); + } +private: + // Disallow certain operations + ImageDirectoryEntries(const ImageDirectoryEntries&); + ImageDirectoryEntries& operator=(const ImageDirectoryEntries&); + +private: + CriticalSection m_lock; +}; + +class LoadedModules +{ +public: + LoadedModules() { + m_lock.Initialize(); + } + ~LoadedModules() { + m_lock.Delete(); + } + void Enter() + { + m_lock.Enter(); + } + void Leave() + { + m_lock.Leave(); + } + BOOL IsLockedByCurrentThread() { + return + m_lock.IsLockedByCurrentThread(); + } + BOOL EnumerateLoadedModulesW64(__in HANDLE hProcess, __in PENUMLOADED_MODULES_CALLBACKW64 EnumLoadedModulesCallback, __in_opt PVOID UserContext) { + CriticalSectionLocker cs(m_lock); + return ::EnumerateLoadedModulesW64(hProcess, EnumLoadedModulesCallback, UserContext); + } +private: + // Disallow certain operations + LoadedModules(const LoadedModules&); + LoadedModules& operator=(const LoadedModules&); + +private: + CriticalSection m_lock; +}; diff --git a/src/dllspatches.cpp b/src/dllspatches.cpp new file mode 100644 index 00000000..a997995f --- /dev/null +++ b/src/dllspatches.cpp @@ -0,0 +1,847 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - VisualLeakDetector Class Implementation +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" + +#define VLDBUILD // Declares that we are building Visual Leak Detector. +#include "crtmfcpatch.h" // Provides CRT and MFC patch functions. +#include "vldint.h" // Provides access to the Visual Leak Detector internals. + +#ifndef WIN64 +//void * __cdecl operator new(unsigned int,int,char const *,int) +const char scalar_new_dbg_name[] = "??2@YAPAXIHPBDH@Z"; +//void * __cdecl operator new[](unsigned int,int,char const *,int) +const char vector_new_dbg_name[] = "??_U@YAPAXIHPBDH@Z"; +//void * __cdecl operator new(unsigned int) +const char scalar_new_name[] = "??2@YAPAXI@Z"; +//void * __cdecl operator new[](unsigned int) +const char vector_new_name[] = "??_U@YAPAXI@Z"; +#else +//void * __ptr64 __cdecl operator new(unsigned __int64,int,char const * __ptr64,int) +const char scalar_new_dbg_name[] = "??2@YAPEAX_KHPEBDH@Z"; +//void * __ptr64 __cdecl operator new[](unsigned __int64,int,char const * __ptr64,int) +const char vector_new_dbg_name[] = "??_U@YAPEAX_KHPEBDH@Z"; +//void * __ptr64 __cdecl operator new(unsigned __int64) +const char scalar_new_name[] = "??2@YAPEAX_K@Z"; +//void * __ptr64 __cdecl operator new[](unsigned __int64) +const char vector_new_name[] = "??_U@YAPEAX_K@Z"; +#endif + +// Global function pointers for explicit dynamic linking with functions listed +// in the import patch table. Using explicit dynamic linking minimizes VLD's +// footprint by loading only modules that are actually used. These pointers will +// be linked to the real functions the first time they are used. + +// The import patch table: lists the heap-related API imports that VLD patches +// through to replacement functions provided by VLD. Having this table simply +// makes it more convenient to add additional IAT patches. +patchentry_t VisualLeakDetector::m_kernelbasePatch [] = { + "GetProcAddress", NULL, _GetProcAddress, // Not heap related, but can be used to obtain pointers to heap functions. + "GetProcAddressForCaller", NULL, _GetProcAddressForCaller, // Not heap related, but can be used to obtain pointers to heap functions. + "GetProcessHeap", (LPVOID*)&m_GetProcessHeap, _GetProcessHeap, + NULL, NULL, NULL +}; + +patchentry_t VisualLeakDetector::m_kernel32Patch [] = { + "GetProcAddress", NULL, _GetProcAddress, // Not heap related, but can be used to obtain pointers to heap functions. + "HeapAlloc", NULL, _HeapAlloc, + "HeapCreate", (LPVOID*)&m_HeapCreate, _HeapCreate, + "HeapDestroy", NULL, _HeapDestroy, + "HeapFree", (LPVOID*)&m_HeapFree, _HeapFree, + "HeapReAlloc", NULL, _HeapReAlloc, + NULL, NULL, NULL +}; + +#define ORDINAL(x) (LPCSTR)x +#if !defined(_M_X64) +#define ORDINAL2(x86, x64) (LPCSTR)x86 +#else +#define ORDINAL2(x86, x64) (LPCSTR)x64 +#endif + +GetProcAddress_t VisualLeakDetector::m_GetProcAddress = NULL; +GetProcAddressForCaller_t VisualLeakDetector::m_GetProcAddressForCaller = NULL; +GetProcessHeap_t VisualLeakDetector::m_GetProcessHeap = NULL; +HeapCreate_t VisualLeakDetector::m_HeapCreate = NULL; +HeapFree_t VisualLeakDetector::m_HeapFree = NULL; + +static patchentry_t mfc42Patch [] = { + // XXX why are the vector new operators missing for mfc42.dll? + //ORDINAL(711), &Mfc60::pmfcd_scalar_new, Mfc60::mfcd_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc42dPatch [] = { + // XXX why are the vector new operators missing for mfc42d.dll? + ORDINAL(711), &Mfc60d::data.pmfcd_scalar_new, Mfc60d::mfcd_scalar_new, + ORDINAL(712), &Mfc60d::data.pmfcd__scalar_new_dbg_4p, Mfc60d::mfcd__scalar_new_dbg_4p, + ORDINAL(714), &Mfc60d::data.pmfcd__scalar_new_dbg_3p, Mfc60d::mfcd__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc42uPatch [] = { + // XXX why are the vector new operators missing for mfc42u.dll? + //ORDINAL(711), &VS60::data.pmfcud_scalar_new, VS60::mfcud_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc42udPatch [] = { + // XXX why are the vector new operators missing for mfc42ud.dll? + ORDINAL(711), &Mfc60d::data.pmfcud_scalar_new, Mfc60d::mfcud_scalar_new, + ORDINAL(712), &Mfc60d::data.pmfcud__scalar_new_dbg_4p, Mfc60d::mfcud__scalar_new_dbg_4p, + ORDINAL(714), &Mfc60d::data.pmfcud__scalar_new_dbg_3p, Mfc60d::mfcud__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc70Patch [] = { + //ORDINAL(257), &Mfc70::data.pmfcd_vector_new, Mfc70::mfcd_vector_new, + //ORDINAL(832), &Mfc70::data.pmfcd_scalar_new, Mfc70::mfcd_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc70dPatch [] = { + ORDINAL(257), &Mfc70d::data.pmfcd_vector_new, Mfc70d::mfcd_vector_new, + ORDINAL(258), &Mfc70d::data.pmfcd__vector_new_dbg_4p, Mfc70d::mfcd__vector_new_dbg_4p, + ORDINAL(259), &Mfc70d::data.pmfcd__vector_new_dbg_3p, Mfc70d::mfcd__vector_new_dbg_3p, + ORDINAL(832), &Mfc70d::data.pmfcd_scalar_new, Mfc70d::mfcd_scalar_new, + ORDINAL(833), &Mfc70d::data.pmfcd__scalar_new_dbg_4p, Mfc70d::mfcd__scalar_new_dbg_4p, + ORDINAL(834), &Mfc70d::data.pmfcd__scalar_new_dbg_3p, Mfc70d::mfcd__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc70uPatch [] = { + //ORDINAL(258), &Mfc70::data.pmfcud_vector_new, Mfc70::mfcud_vector_new, + //ORDINAL(833), &Mfc70::data.pmfcud_scalar_new, Mfc70::mfcud_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc70udPatch [] = { + ORDINAL(258), &Mfc70d::data.pmfcud_vector_new, Mfc70d::mfcud_vector_new, + ORDINAL(259), &Mfc70d::data.pmfcud__vector_new_dbg_4p, Mfc70d::mfcud__vector_new_dbg_4p, + ORDINAL(260), &Mfc70d::data.pmfcud__vector_new_dbg_3p, Mfc70d::mfcud__vector_new_dbg_3p, + ORDINAL(833), &Mfc70d::data.pmfcud_scalar_new, Mfc70d::mfcud_scalar_new, + ORDINAL(834), &Mfc70d::data.pmfcud__scalar_new_dbg_4p, Mfc70d::mfcud__scalar_new_dbg_4p, + ORDINAL(835), &Mfc70d::data.pmfcud__scalar_new_dbg_3p, Mfc70d::mfcud__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc71Patch [] = { + //ORDINAL(267), &Mfc71::data.pmfcd_vector_new, MfcMfc71::mfcd_vector_new, + //ORDINAL(893), &Mfc71::data.pmfcd_scalar_new, MfcMfc71::mfcd_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc71dPatch [] = { + ORDINAL(267), &Mfc71d::data.pmfcd_vector_new, Mfc71d::mfcd_vector_new, + ORDINAL(268), &Mfc71d::data.pmfcd__vector_new_dbg_4p, Mfc71d::mfcd__vector_new_dbg_4p, + ORDINAL(269), &Mfc71d::data.pmfcd__vector_new_dbg_3p, Mfc71d::mfcd__vector_new_dbg_3p, + ORDINAL(893), &Mfc71d::data.pmfcd_scalar_new, Mfc71d::mfcd_scalar_new, + ORDINAL(894), &Mfc71d::data.pmfcd__scalar_new_dbg_4p, Mfc71d::mfcd__scalar_new_dbg_4p, + ORDINAL(895), &Mfc71d::data.pmfcd__scalar_new_dbg_3p, Mfc71d::mfcd__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc71uPatch [] = { + //ORDINAL(267), &Mfc71::data.pmfcud_vector_new, Mfc71::mfcud_vector_new, + //ORDINAL(893), &Mfc71::data.pmfcud_scalar_new, Mfc71::mfcud_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc71udPatch [] = { + ORDINAL(267), &Mfc71d::data.pmfcud_vector_new, Mfc71d::mfcud_vector_new, + ORDINAL(268), &Mfc71d::data.pmfcud__vector_new_dbg_4p, Mfc71d::mfcud__vector_new_dbg_4p, + ORDINAL(269), &Mfc71d::data.pmfcud__vector_new_dbg_3p, Mfc71d::mfcud__vector_new_dbg_3p, + ORDINAL(893), &Mfc71d::data.pmfcud_scalar_new, Mfc71d::mfcud_scalar_new, + ORDINAL(894), &Mfc71d::data.pmfcud__scalar_new_dbg_4p, Mfc71d::mfcud__scalar_new_dbg_4p, + ORDINAL(895), &Mfc71d::data.pmfcud__scalar_new_dbg_3p, Mfc71d::mfcud__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc80Patch [] = { + //ORDINAL(267), &Mfc80::data.pmfcd_vector_new, Mfc80::mfcd_vector_new, + //ORDINAL2(893,907), &Mfc80::data.pmfcd_scalar_new, Mfc80::mfcd_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc80dPatch [] = { + ORDINAL(267), &Mfc80d::data.pmfcd_vector_new, Mfc80d::mfcd_vector_new, + ORDINAL(268), &Mfc80d::data.pmfcd__vector_new_dbg_4p, Mfc80d::mfcd__vector_new_dbg_4p, + ORDINAL(269), &Mfc80d::data.pmfcd__vector_new_dbg_3p, Mfc80d::mfcd__vector_new_dbg_3p, + ORDINAL2(893,907), &Mfc80d::data.pmfcd_scalar_new, Mfc80d::mfcd_scalar_new, + ORDINAL2(894,908), &Mfc80d::data.pmfcd__scalar_new_dbg_4p, Mfc80d::mfcd__scalar_new_dbg_4p, + ORDINAL2(895,909), &Mfc80d::data.pmfcd__scalar_new_dbg_3p, Mfc80d::mfcd__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc80uPatch [] = { + //ORDINAL(267), &Mfc80::data.pmfcud_vector_new, Mfc80::mfcud_vector_new, + //ORDINAL2(893,907), &Mfc80::data.pmfcud_scalar_new, Mfc80::mfcud_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc80udPatch [] = { + ORDINAL(267), &Mfc80d::data.pmfcud_vector_new, Mfc80d::mfcud_vector_new, + ORDINAL(268), &Mfc80d::data.pmfcud__vector_new_dbg_4p, Mfc80d::mfcud__vector_new_dbg_4p, + ORDINAL(269), &Mfc80d::data.pmfcud__vector_new_dbg_3p, Mfc80d::mfcud__vector_new_dbg_3p, + ORDINAL2(893,907), &Mfc80d::data.pmfcud_scalar_new, Mfc80d::mfcud_scalar_new, + ORDINAL2(894,908), &Mfc80d::data.pmfcud__scalar_new_dbg_4p, Mfc80d::mfcud__scalar_new_dbg_4p, + ORDINAL2(895,909), &Mfc80d::data.pmfcud__scalar_new_dbg_3p, Mfc80d::mfcud__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc90Patch [] = { + ORDINAL(265), &Mfc90::data.pmfcd_vector_new, Mfc90::mfcd_vector_new, + ORDINAL2(798, 776), &Mfc90::data.pmfcd_scalar_new, Mfc90::mfcd_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc90dPatch [] = { + ORDINAL(267), &Mfc90d::data.pmfcd_vector_new, Mfc90d::mfcd_vector_new, + ORDINAL(268), &Mfc90d::data.pmfcd__vector_new_dbg_4p, Mfc90d::mfcd__vector_new_dbg_4p, + ORDINAL(269), &Mfc90d::data.pmfcd__vector_new_dbg_3p, Mfc90d::mfcd__vector_new_dbg_3p, + ORDINAL2(931, 909), &Mfc90d::data.pmfcd_scalar_new, Mfc90d::mfcd_scalar_new, + ORDINAL2(932, 910), &Mfc90d::data.pmfcd__scalar_new_dbg_4p, Mfc90d::mfcd__scalar_new_dbg_4p, + ORDINAL2(933, 911), &Mfc90d::data.pmfcd__scalar_new_dbg_3p, Mfc90d::mfcd__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc90uPatch [] = { + ORDINAL(265), &Mfc90::data.pmfcud_vector_new, Mfc90::mfcud_vector_new, + ORDINAL2(798, 776), &Mfc90::data.pmfcud_scalar_new, Mfc90::mfcud_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc90udPatch [] = { + ORDINAL(267), &Mfc90d::data.pmfcud_vector_new, Mfc90d::mfcud_vector_new, + ORDINAL(268), &Mfc90d::data.pmfcud__vector_new_dbg_4p, Mfc90d::mfcud__vector_new_dbg_4p, + ORDINAL(269), &Mfc90d::data.pmfcud__vector_new_dbg_3p, Mfc90d::mfcud__vector_new_dbg_3p, + ORDINAL2(935, 913), &Mfc90d::data.pmfcud_scalar_new, Mfc90d::mfcud_scalar_new, + ORDINAL2(936, 914), &Mfc90d::data.pmfcud__scalar_new_dbg_4p, Mfc90d::mfcud__scalar_new_dbg_4p, + ORDINAL2(937, 915), &Mfc90d::data.pmfcud__scalar_new_dbg_3p, Mfc90d::mfcud__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc100Patch [] = { + ORDINAL(265), &Mfc100::data.pmfcd_vector_new, Mfc100::mfcd_vector_new, + ORDINAL2(1294, 1272), &Mfc100::data.pmfcd_scalar_new, Mfc100::mfcd_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc100dPatch [] = { + ORDINAL(267), &Mfc100d::data.pmfcd_vector_new, Mfc100d::mfcd_vector_new, + ORDINAL(268), &Mfc100d::data.pmfcd__vector_new_dbg_4p, Mfc100d::mfcd__vector_new_dbg_4p, + ORDINAL(269), &Mfc100d::data.pmfcd__vector_new_dbg_3p, Mfc100d::mfcd__vector_new_dbg_3p, + ORDINAL2(1427, 1405), &Mfc100d::data.pmfcd_scalar_new, Mfc100d::mfcd_scalar_new, + ORDINAL2(1428, 1406), &Mfc100d::data.pmfcd__scalar_new_dbg_4p, Mfc100d::mfcd__scalar_new_dbg_4p, + ORDINAL2(1429, 1407), &Mfc100d::data.pmfcd__scalar_new_dbg_3p, Mfc100d::mfcd__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc100uPatch [] = { + ORDINAL(265), &Mfc100::data.pmfcud_vector_new, Mfc100::mfcud_vector_new, + ORDINAL2(1298, 1276), &Mfc100::data.pmfcud_scalar_new, Mfc100::mfcud_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc100udPatch [] = { + ORDINAL(267), &Mfc100d::data.pmfcud_vector_new, Mfc100d::mfcud_vector_new, + ORDINAL(268), &Mfc100d::data.pmfcud__vector_new_dbg_4p, Mfc100d::mfcud__vector_new_dbg_4p, + ORDINAL(269), &Mfc100d::data.pmfcud__vector_new_dbg_3p, Mfc100d::mfcud__vector_new_dbg_3p, + ORDINAL2(1434, 1412), &Mfc100d::data.pmfcud_scalar_new, Mfc100d::mfcud_scalar_new, + ORDINAL2(1435, 1413), &Mfc100d::data.pmfcud__scalar_new_dbg_4p, Mfc100d::mfcud__scalar_new_dbg_4p, + ORDINAL2(1436, 1414), &Mfc100d::data.pmfcud__scalar_new_dbg_3p, Mfc100d::mfcud__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc110Patch [] = { + ORDINAL(265), &Mfc110::data.pmfcd_vector_new, Mfc110::mfcd_vector_new, + ORDINAL2(1498, 1476), &Mfc110::data.pmfcd_scalar_new, Mfc110::mfcd_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc110dPatch [] = { + ORDINAL(267), &Mfc110d::data.pmfcd_vector_new, Mfc110d::mfcd_vector_new, + ORDINAL(268), &Mfc110d::data.pmfcd__vector_new_dbg_4p, Mfc110d::mfcd__vector_new_dbg_4p, + ORDINAL(269), &Mfc110d::data.pmfcd__vector_new_dbg_3p, Mfc110d::mfcd__vector_new_dbg_3p, + ORDINAL2(1629, 1607), &Mfc110d::data.pmfcd_scalar_new, Mfc110d::mfcd_scalar_new, + ORDINAL2(1630, 1608), &Mfc110d::data.pmfcd__scalar_new_dbg_4p, Mfc110d::mfcd__scalar_new_dbg_4p, + ORDINAL2(1631, 1609), &Mfc110d::data.pmfcd__scalar_new_dbg_3p, Mfc110d::mfcd__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc110uPatch [] = { + ORDINAL(265), &Mfc110::data.pmfcud_vector_new, Mfc110::mfcud_vector_new, + ORDINAL2(1502, 1480), &Mfc110::data.pmfcud_scalar_new, Mfc110::mfcud_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc110udPatch [] = { + ORDINAL(267), &Mfc110d::data.pmfcud_vector_new, Mfc110d::mfcud_vector_new, + ORDINAL(268), &Mfc110d::data.pmfcud__vector_new_dbg_4p, Mfc110d::mfcud__vector_new_dbg_4p, + ORDINAL(269), &Mfc110d::data.pmfcud__vector_new_dbg_3p, Mfc110d::mfcud__vector_new_dbg_3p, + ORDINAL2(1636, 1614), &Mfc110d::data.pmfcud_scalar_new, Mfc110d::mfcud_scalar_new, + ORDINAL2(1637, 1615), &Mfc110d::data.pmfcud__scalar_new_dbg_4p, Mfc110d::mfcud__scalar_new_dbg_4p, + ORDINAL2(1638, 1616), &Mfc110d::data.pmfcud__scalar_new_dbg_3p, Mfc110d::mfcud__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc120Patch [] = { + ORDINAL(265), &Mfc120::data.pmfcd_vector_new, Mfc120::mfcd_vector_new, + ORDINAL2(1502, 1480), &Mfc120::data.pmfcd_scalar_new, Mfc120::mfcd_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc120dPatch [] = { + ORDINAL(267), &Mfc120d::data.pmfcd_vector_new, Mfc120d::mfcd_vector_new, + ORDINAL(268), &Mfc120d::data.pmfcd__vector_new_dbg_4p, Mfc120d::mfcd__vector_new_dbg_4p, + ORDINAL(269), &Mfc120d::data.pmfcd__vector_new_dbg_3p, Mfc120d::mfcd__vector_new_dbg_3p, + ORDINAL2(1633, 1611), &Mfc120d::data.pmfcd_scalar_new, Mfc120d::mfcd_scalar_new, + ORDINAL2(1634, 1612), &Mfc120d::data.pmfcd__scalar_new_dbg_4p, Mfc120d::mfcd__scalar_new_dbg_4p, + ORDINAL2(1635, 1613), &Mfc120d::data.pmfcd__scalar_new_dbg_3p, Mfc120d::mfcd__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc120uPatch [] = { + ORDINAL(265), &Mfc120::data.pmfcud_vector_new, Mfc120::mfcud_vector_new, + ORDINAL2(1506, 1484), &Mfc120::data.pmfcud_scalar_new, Mfc120::mfcud_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc120udPatch [] = { + ORDINAL(267), &Mfc120d::data.pmfcud_vector_new, Mfc120d::mfcud_vector_new, + ORDINAL(268), &Mfc120d::data.pmfcud__vector_new_dbg_4p, Mfc120d::mfcud__vector_new_dbg_4p, + ORDINAL(269), &Mfc120d::data.pmfcud__vector_new_dbg_3p, Mfc120d::mfcud__vector_new_dbg_3p, + ORDINAL2(1640, 1618), &Mfc120d::data.pmfcud_scalar_new, Mfc120d::mfcud_scalar_new, + ORDINAL2(1641, 1619), &Mfc120d::data.pmfcud__scalar_new_dbg_4p, Mfc120d::mfcud__scalar_new_dbg_4p, + ORDINAL2(1642, 1620), &Mfc120d::data.pmfcud__scalar_new_dbg_3p, Mfc120d::mfcud__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc140Patch[] = { + ORDINAL(265), &Mfc140::data.pmfcd_vector_new, Mfc140::mfcd_vector_new, + ORDINAL2(1507, 1485), &Mfc140::data.pmfcd_scalar_new, Mfc140::mfcd_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc140dPatch[] = { + ORDINAL(267), &Mfc140d::data.pmfcd_vector_new, Mfc140d::mfcd_vector_new, + ORDINAL(268), &Mfc140d::data.pmfcd__vector_new_dbg_4p, Mfc140d::mfcd__vector_new_dbg_4p, + ORDINAL(269), &Mfc140d::data.pmfcd__vector_new_dbg_3p, Mfc140d::mfcd__vector_new_dbg_3p, + ORDINAL2(1638, 1616), &Mfc140d::data.pmfcd_scalar_new, Mfc140d::mfcd_scalar_new, + ORDINAL2(1639, 1617), &Mfc140d::data.pmfcd__scalar_new_dbg_4p, Mfc140d::mfcd__scalar_new_dbg_4p, + ORDINAL2(1640, 1618), &Mfc140d::data.pmfcd__scalar_new_dbg_3p, Mfc140d::mfcd__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t mfc140uPatch[] = { + ORDINAL(265), &Mfc140::data.pmfcud_vector_new, Mfc140::mfcud_vector_new, + ORDINAL2(1511, 1489), &Mfc140::data.pmfcud_scalar_new, Mfc140::mfcud_scalar_new, + NULL, NULL, NULL +}; + +static patchentry_t mfc140udPatch[] = { + ORDINAL(267), &Mfc140d::data.pmfcud_vector_new, Mfc140d::mfcud_vector_new, + ORDINAL(268), &Mfc140d::data.pmfcud__vector_new_dbg_4p, Mfc140d::mfcud__vector_new_dbg_4p, + ORDINAL(269), &Mfc140d::data.pmfcud__vector_new_dbg_3p, Mfc140d::mfcud__vector_new_dbg_3p, + ORDINAL2(1645, 1623), &Mfc140d::data.pmfcud_scalar_new, Mfc140d::mfcud_scalar_new, + ORDINAL2(1646, 1624), &Mfc140d::data.pmfcud__scalar_new_dbg_4p, Mfc140d::mfcud__scalar_new_dbg_4p, + ORDINAL2(1647, 1625), &Mfc140d::data.pmfcud__scalar_new_dbg_3p, Mfc140d::mfcud__scalar_new_dbg_3p, + NULL, NULL, NULL +}; + +static patchentry_t msvcrtPatch [] = { + "_calloc_dbg", &VS60::data.pcrtd__calloc_dbg, VS60::crtd__calloc_dbg, + "_malloc_dbg", &VS60::data.pcrtd__malloc_dbg, VS60::crtd__malloc_dbg, + "_realloc_dbg", &VS60::data.pcrtd__realloc_dbg, VS60::crtd__realloc_dbg, + scalar_new_dbg_name, &VS60::data.pcrtd__scalar_new_dbg, VS60::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS60::data.pcrtd__vector_new_dbg, VS60::crtd__vector_new_dbg, + "calloc", &VS60::data.pcrtd_calloc, VS60::crtd_calloc, + "malloc", &VS60::data.pcrtd_malloc, VS60::crtd_malloc, + "realloc", &VS60::data.pcrtd_realloc, VS60::crtd_realloc, + "_strdup", &VS60::data.pcrtd__strdup, VS60::crtd__strdup, + scalar_new_name, &VS60::data.pcrtd_scalar_new, VS60::crtd_scalar_new, + vector_new_name, &VS60::data.pcrtd_vector_new, VS60::crtd_vector_new, + NULL, NULL, NULL +}; + +static patchentry_t msvcrtdPatch [] = { + "_calloc_dbg", &VS60d::data.pcrtd__calloc_dbg, VS60d::crtd__calloc_dbg, + "_malloc_dbg", &VS60d::data.pcrtd__malloc_dbg, VS60d::crtd__malloc_dbg, + "_realloc_dbg", &VS60d::data.pcrtd__realloc_dbg, VS60d::crtd__realloc_dbg, + scalar_new_dbg_name, &VS60d::data.pcrtd__scalar_new_dbg, VS60d::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS60d::data.pcrtd__vector_new_dbg, VS60d::crtd__vector_new_dbg, + "calloc", &VS60d::data.pcrtd_calloc, VS60d::crtd_calloc, + "malloc", &VS60d::data.pcrtd_malloc, VS60d::crtd_malloc, + "realloc", &VS60d::data.pcrtd_realloc, VS60d::crtd_realloc, + "_strdup", &VS60d::data.pcrtd__strdup, VS60d::crtd__strdup, + scalar_new_name, &VS60d::data.pcrtd_scalar_new, VS60d::crtd_scalar_new, + vector_new_name, &VS60d::data.pcrtd_vector_new, VS60d::crtd_vector_new, + NULL, NULL, NULL +}; + +static patchentry_t msvcr70Patch [] = { + scalar_new_dbg_name, &VS70::data.pcrtd__scalar_new_dbg, VS70::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS70::data.pcrtd__vector_new_dbg, VS70::crtd__vector_new_dbg, + "calloc", &VS70::data.pcrtd_calloc, VS70::crtd_calloc, + "malloc", &VS70::data.pcrtd_malloc, VS70::crtd_malloc, + "realloc", &VS70::data.pcrtd_realloc, VS70::crtd_realloc, + "_strdup", &VS70::data.pcrtd__strdup, VS70::crtd__strdup, + "_wcsdup", &VS70::data.pcrtd__wcsdup, VS70::crtd__wcsdup, + scalar_new_name, &VS70::data.pcrtd_scalar_new, VS70::crtd_scalar_new, + vector_new_name, &VS70::data.pcrtd_vector_new, VS70::crtd_vector_new, + NULL, NULL, NULL +}; + +static patchentry_t msvcr70dPatch [] = { + "_calloc_dbg", &VS70d::data.pcrtd__calloc_dbg, VS70d::crtd__calloc_dbg, + "_malloc_dbg", &VS70d::data.pcrtd__malloc_dbg, VS70d::crtd__malloc_dbg, + "_realloc_dbg", &VS70d::data.pcrtd__realloc_dbg, VS70d::crtd__realloc_dbg, + scalar_new_dbg_name, &VS70d::data.pcrtd__scalar_new_dbg, VS70d::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS70d::data.pcrtd__vector_new_dbg, VS70d::crtd__vector_new_dbg, + "calloc", &VS70d::data.pcrtd_calloc, VS70d::crtd_calloc, + "malloc", &VS70d::data.pcrtd_malloc, VS70d::crtd_malloc, + "realloc", &VS70d::data.pcrtd_realloc, VS70d::crtd_realloc, + "_strdup", &VS70d::data.pcrtd__strdup, VS70d::crtd__strdup, + "_wcsdup", &VS70d::data.pcrtd__wcsdup, VS70d::crtd__wcsdup, + scalar_new_name, &VS70d::data.pcrtd_scalar_new, VS70d::crtd_scalar_new, + vector_new_name, &VS70d::data.pcrtd_vector_new, VS70d::crtd_vector_new, + NULL, NULL, NULL +}; + +static patchentry_t msvcr71Patch [] = { + scalar_new_dbg_name, &VS71::data.pcrtd__scalar_new_dbg, VS71::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS71::data.pcrtd__vector_new_dbg, VS71::crtd__vector_new_dbg, + "calloc", &VS71::data.pcrtd_calloc, VS71::crtd_calloc, + "malloc", &VS71::data.pcrtd_malloc, VS71::crtd_malloc, + "realloc", &VS71::data.pcrtd_realloc, VS71::crtd_realloc, + "_strdup", &VS71::data.pcrtd__strdup, VS71::crtd__strdup, + "_wcsdup", &VS71::data.pcrtd__wcsdup, VS71::crtd__wcsdup, + scalar_new_name, &VS71::data.pcrtd_scalar_new, VS71::crtd_scalar_new, + vector_new_name, &VS71::data.pcrtd_vector_new, VS71::crtd_vector_new, + NULL, NULL, NULL +}; + +static patchentry_t msvcr71dPatch [] = { + "_calloc_dbg", &VS71d::data.pcrtd__calloc_dbg, VS71d::crtd__calloc_dbg, + "_malloc_dbg", &VS71d::data.pcrtd__malloc_dbg, VS71d::crtd__malloc_dbg, + "_realloc_dbg", &VS71d::data.pcrtd__realloc_dbg, VS71d::crtd__realloc_dbg, + "_strdup_dbg", &VS71d::data.pcrtd__strdup_dbg, VS71d::crtd__strdup_dbg, + "_wcsdup_dbg", &VS71d::data.pcrtd__wcsdup_dbg, VS71d::crtd__wcsdup_dbg, + scalar_new_dbg_name, &VS71d::data.pcrtd__scalar_new_dbg, VS71d::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS71d::data.pcrtd__vector_new_dbg, VS71d::crtd__vector_new_dbg, + "calloc", &VS71d::data.pcrtd_calloc, VS71d::crtd_calloc, + "malloc", &VS71d::data.pcrtd_malloc, VS71d::crtd_malloc, + "realloc", &VS71d::data.pcrtd_realloc, VS71d::crtd_realloc, + "_strdup", &VS71d::data.pcrtd__strdup, VS71d::crtd__strdup, + "_wcsdup", &VS71d::data.pcrtd__wcsdup, VS71d::crtd__wcsdup, + scalar_new_name, &VS71d::data.pcrtd_scalar_new, VS71d::crtd_scalar_new, + vector_new_name, &VS71d::data.pcrtd_vector_new, VS71d::crtd_vector_new, + NULL, NULL, NULL +}; + +static patchentry_t msvcr80Patch [] = { + scalar_new_dbg_name, &VS80::data.pcrtd__scalar_new_dbg, VS80::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS80::data.pcrtd__vector_new_dbg, VS80::crtd__vector_new_dbg, + "calloc", &VS80::data.pcrtd_calloc, VS80::crtd_calloc, + "malloc", &VS80::data.pcrtd_malloc, VS80::crtd_malloc, + "realloc", &VS80::data.pcrtd_realloc, VS80::crtd_realloc, + "_strdup", &VS80::data.pcrtd__strdup, VS80::crtd__strdup, + "_wcsdup", &VS80::data.pcrtd__wcsdup, VS80::crtd__wcsdup, + scalar_new_name, &VS80::data.pcrtd_scalar_new, VS80::crtd_scalar_new, + vector_new_name, &VS80::data.pcrtd_vector_new, VS80::crtd_vector_new, + "_aligned_malloc", &VS80::data.pcrtd_aligned_malloc, VS80::crtd__aligned_malloc, + "_aligned_offset_malloc", &VS80::data.pcrtd_aligned_offset_malloc, VS80::crtd__aligned_offset_malloc, + "_aligned_realloc", &VS80::data.pcrtd_aligned_realloc, VS80::crtd__aligned_realloc, + "_aligned_offset_realloc", &VS80::data.pcrtd_aligned_offset_realloc, VS80::crtd__aligned_offset_realloc, + NULL, NULL, NULL +}; + +static patchentry_t msvcr80dPatch [] = { + "_calloc_dbg", &VS80d::data.pcrtd__calloc_dbg, VS80d::crtd__calloc_dbg, + "_malloc_dbg", &VS80d::data.pcrtd__malloc_dbg, VS80d::crtd__malloc_dbg, + "_realloc_dbg", &VS80d::data.pcrtd__realloc_dbg, VS80d::crtd__realloc_dbg, + "_strdup_dbg", &VS80d::data.pcrtd__strdup_dbg, VS80d::crtd__strdup_dbg, + "_wcsdup_dbg", &VS80d::data.pcrtd__wcsdup_dbg, VS80d::crtd__wcsdup_dbg, + scalar_new_dbg_name, &VS80d::data.pcrtd__scalar_new_dbg, VS80d::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS80d::data.pcrtd__vector_new_dbg, VS80d::crtd__vector_new_dbg, + "calloc", &VS80d::data.pcrtd_calloc, VS80d::crtd_calloc, + "malloc", &VS80d::data.pcrtd_malloc, VS80d::crtd_malloc, + "realloc", &VS80d::data.pcrtd_realloc, VS80d::crtd_realloc, + "_strdup", &VS80d::data.pcrtd__strdup, VS80d::crtd__strdup, + "_wcsdup", &VS80d::data.pcrtd__wcsdup, VS80d::crtd__wcsdup, + scalar_new_name, &VS80d::data.pcrtd_scalar_new, VS80d::crtd_scalar_new, + vector_new_name, &VS80d::data.pcrtd_vector_new, VS80d::crtd_vector_new, + "_aligned_malloc_dbg", &VS80d::data.pcrtd__aligned_malloc_dbg, VS80d::crtd__aligned_malloc_dbg, + "_aligned_offset_malloc_dbg", &VS80d::data.pcrtd__aligned_offset_malloc_dbg, VS80d::crtd__aligned_offset_malloc_dbg, + "_aligned_realloc_dbg", &VS80d::data.pcrtd__aligned_realloc_dbg, VS80d::crtd__aligned_realloc_dbg, + "_aligned_offset_realloc_dbg", &VS80d::data.pcrtd__aligned_offset_realloc_dbg, VS80d::crtd__aligned_offset_realloc_dbg, + "_aligned_malloc", &VS80d::data.pcrtd_aligned_malloc, VS80d::crtd__aligned_malloc, + "_aligned_offset_malloc", &VS80d::data.pcrtd_aligned_offset_malloc, VS80d::crtd__aligned_offset_malloc, + "_aligned_realloc", &VS80d::data.pcrtd_aligned_realloc, VS80d::crtd__aligned_realloc, + "_aligned_offset_realloc", &VS80d::data.pcrtd_aligned_offset_realloc, VS80d::crtd__aligned_offset_realloc, + NULL, NULL, NULL +}; + +static patchentry_t msvcr90Patch [] = { + scalar_new_dbg_name, &VS90::data.pcrtd__scalar_new_dbg, VS90::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS90::data.pcrtd__vector_new_dbg, VS90::crtd__vector_new_dbg, + "calloc", &VS90::data.pcrtd_calloc, VS90::crtd_calloc, + "malloc", &VS90::data.pcrtd_malloc, VS90::crtd_malloc, + "realloc", &VS90::data.pcrtd_realloc, VS90::crtd_realloc, + "_recalloc", &VS90::data.pcrtd_recalloc, VS90::crtd__recalloc, + "_strdup", &VS90::data.pcrtd__strdup, VS90::crtd__strdup, + "_wcsdup", &VS90::data.pcrtd__wcsdup, VS90::crtd__wcsdup, + scalar_new_name, &VS90::data.pcrtd_scalar_new, VS90::crtd_scalar_new, + vector_new_name, &VS90::data.pcrtd_vector_new, VS90::crtd_vector_new, + "_aligned_malloc", &VS90::data.pcrtd_aligned_malloc, VS90::crtd__aligned_malloc, + "_aligned_offset_malloc", &VS90::data.pcrtd_aligned_offset_malloc, VS90::crtd__aligned_offset_malloc, + "_aligned_realloc", &VS90::data.pcrtd_aligned_realloc, VS90::crtd__aligned_realloc, + "_aligned_offset_realloc", &VS90::data.pcrtd_aligned_offset_realloc, VS90::crtd__aligned_offset_realloc, + "_aligned_recalloc", &VS90::data.pcrtd_aligned_recalloc, VS90::crtd__aligned_recalloc, + "_aligned_offset_recalloc", &VS90::data.pcrtd_aligned_offset_recalloc, VS90::crtd__aligned_offset_recalloc, + NULL, NULL, NULL +}; + +static patchentry_t msvcr90dPatch [] = { + "_calloc_dbg", &VS90d::data.pcrtd__calloc_dbg, VS90d::crtd__calloc_dbg, + "_malloc_dbg", &VS90d::data.pcrtd__malloc_dbg, VS90d::crtd__malloc_dbg, + "_realloc_dbg", &VS90d::data.pcrtd__realloc_dbg, VS90d::crtd__realloc_dbg, + "_recalloc_dbg", &VS90d::data.pcrtd__recalloc_dbg, VS90d::crtd__recalloc_dbg, + "_strdup_dbg", &VS90d::data.pcrtd__strdup_dbg, VS90d::crtd__strdup_dbg, + "_wcsdup_dbg", &VS90d::data.pcrtd__wcsdup_dbg, VS90d::crtd__wcsdup_dbg, + scalar_new_dbg_name, &VS90d::data.pcrtd__scalar_new_dbg, VS90d::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS90d::data.pcrtd__vector_new_dbg, VS90d::crtd__vector_new_dbg, + "calloc", &VS90d::data.pcrtd_calloc, VS90d::crtd_calloc, + "malloc", &VS90d::data.pcrtd_malloc, VS90d::crtd_malloc, + "realloc", &VS90d::data.pcrtd_realloc, VS90d::crtd_realloc, + "_recalloc", &VS90d::data.pcrtd_recalloc, VS90d::crtd__recalloc, + "_strdup", &VS90d::data.pcrtd__strdup, VS90d::crtd__strdup, + "_wcsdup", &VS90d::data.pcrtd__wcsdup, VS90d::crtd__wcsdup, + scalar_new_name, &VS90d::data.pcrtd_scalar_new, VS90d::crtd_scalar_new, + vector_new_name, &VS90d::data.pcrtd_vector_new, VS90d::crtd_vector_new, + "_aligned_malloc_dbg", &VS90d::data.pcrtd__aligned_malloc_dbg, VS90d::crtd__aligned_malloc_dbg, + "_aligned_offset_malloc_dbg", &VS90d::data.pcrtd__aligned_offset_malloc_dbg, VS90d::crtd__aligned_offset_malloc_dbg, + "_aligned_realloc_dbg", &VS90d::data.pcrtd__aligned_realloc_dbg, VS90d::crtd__aligned_realloc_dbg, + "_aligned_offset_realloc_dbg", &VS90d::data.pcrtd__aligned_offset_realloc_dbg, VS90d::crtd__aligned_offset_realloc_dbg, + "_aligned_recalloc_dbg", &VS90d::data.pcrtd__aligned_recalloc_dbg, VS90d::crtd__aligned_recalloc_dbg, + "_aligned_offset_recalloc_dbg", &VS90d::data.pcrtd__aligned_offset_recalloc_dbg, VS90d::crtd__aligned_offset_recalloc_dbg, + "_aligned_malloc", &VS90d::data.pcrtd_aligned_malloc, VS90d::crtd__aligned_malloc, + "_aligned_offset_malloc", &VS90d::data.pcrtd_aligned_offset_malloc, VS90d::crtd__aligned_offset_malloc, + "_aligned_realloc", &VS90d::data.pcrtd_aligned_realloc, VS90d::crtd__aligned_realloc, + "_aligned_offset_realloc", &VS90d::data.pcrtd_aligned_offset_realloc, VS90d::crtd__aligned_offset_realloc, + "_aligned_recalloc", &VS90d::data.pcrtd_aligned_recalloc, VS90d::crtd__aligned_recalloc, + "_aligned_offset_recalloc", &VS90d::data.pcrtd_aligned_offset_recalloc, VS90d::crtd__aligned_offset_recalloc, + NULL, NULL, NULL +}; + +static patchentry_t msvcr100Patch [] = { + scalar_new_dbg_name, &VS100::data.pcrtd__scalar_new_dbg, VS100::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS100::data.pcrtd__vector_new_dbg, VS100::crtd__vector_new_dbg, + "calloc", &VS100::data.pcrtd_calloc, VS100::crtd_calloc, + "malloc", &VS100::data.pcrtd_malloc, VS100::crtd_malloc, + "realloc", &VS100::data.pcrtd_realloc, VS100::crtd_realloc, + "_recalloc", &VS100::data.pcrtd_recalloc, VS100::crtd__recalloc, + "_strdup", &VS100::data.pcrtd__strdup, VS100::crtd__strdup, + "_wcsdup", &VS100::data.pcrtd__wcsdup, VS100::crtd__wcsdup, + scalar_new_name, &VS100::data.pcrtd_scalar_new, VS100::crtd_scalar_new, + vector_new_name, &VS100::data.pcrtd_vector_new, VS100::crtd_vector_new, + "_aligned_malloc", &VS100::data.pcrtd_aligned_malloc, VS100::crtd__aligned_malloc, + "_aligned_offset_malloc", &VS100::data.pcrtd_aligned_offset_malloc, VS100::crtd__aligned_offset_malloc, + "_aligned_realloc", &VS100::data.pcrtd_aligned_realloc, VS100::crtd__aligned_realloc, + "_aligned_offset_realloc", &VS100::data.pcrtd_aligned_offset_realloc, VS100::crtd__aligned_offset_realloc, + "_aligned_recalloc", &VS100::data.pcrtd_aligned_recalloc, VS100::crtd__aligned_recalloc, + "_aligned_offset_recalloc", &VS100::data.pcrtd_aligned_offset_recalloc, VS100::crtd__aligned_offset_recalloc, + NULL, NULL, NULL, +}; + +static patchentry_t msvcr100dPatch [] = { + "_calloc_dbg", &VS100d::data.pcrtd__calloc_dbg, VS100d::crtd__calloc_dbg, + "_malloc_dbg", &VS100d::data.pcrtd__malloc_dbg, VS100d::crtd__malloc_dbg, + "_realloc_dbg", &VS100d::data.pcrtd__realloc_dbg, VS100d::crtd__realloc_dbg, + "_recalloc_dbg", &VS100d::data.pcrtd__recalloc_dbg, VS100d::crtd__recalloc_dbg, + "_strdup_dbg", &VS100d::data.pcrtd__strdup_dbg, VS100d::crtd__strdup_dbg, + "_wcsdup_dbg", &VS100d::data.pcrtd__wcsdup_dbg, VS100d::crtd__wcsdup_dbg, + scalar_new_dbg_name, &VS100d::data.pcrtd__scalar_new_dbg, VS100d::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS100d::data.pcrtd__vector_new_dbg, VS100d::crtd__vector_new_dbg, + "calloc", &VS100d::data.pcrtd_calloc, VS100d::crtd_calloc, + "malloc", &VS100d::data.pcrtd_malloc, VS100d::crtd_malloc, + "realloc", &VS100d::data.pcrtd_realloc, VS100d::crtd_realloc, + "_recalloc", &VS100d::data.pcrtd_recalloc, VS100d::crtd__recalloc, + "_strdup", &VS100d::data.pcrtd__strdup, VS100d::crtd__strdup, + "_wcsdup", &VS100d::data.pcrtd__wcsdup, VS100d::crtd__wcsdup, + scalar_new_name, &VS100d::data.pcrtd_scalar_new, VS100d::crtd_scalar_new, + vector_new_name, &VS100d::data.pcrtd_vector_new, VS100d::crtd_vector_new, + "_aligned_malloc_dbg", &VS100d::data.pcrtd__aligned_malloc_dbg, VS100d::crtd__aligned_malloc_dbg, + "_aligned_offset_malloc_dbg", &VS100d::data.pcrtd__aligned_offset_malloc_dbg, VS100d::crtd__aligned_offset_malloc_dbg, + "_aligned_realloc_dbg", &VS100d::data.pcrtd__aligned_realloc_dbg, VS100d::crtd__aligned_realloc_dbg, + "_aligned_offset_realloc_dbg", &VS100d::data.pcrtd__aligned_offset_realloc_dbg, VS100d::crtd__aligned_offset_realloc_dbg, + "_aligned_recalloc_dbg", &VS100d::data.pcrtd__aligned_recalloc_dbg, VS100d::crtd__aligned_recalloc_dbg, + "_aligned_offset_recalloc_dbg", &VS100d::data.pcrtd__aligned_offset_recalloc_dbg, VS100d::crtd__aligned_offset_recalloc_dbg, + "_aligned_malloc", &VS100d::data.pcrtd_aligned_malloc, VS100d::crtd__aligned_malloc, + "_aligned_offset_malloc", &VS100d::data.pcrtd_aligned_offset_malloc, VS100d::crtd__aligned_offset_malloc, + "_aligned_realloc", &VS100d::data.pcrtd_aligned_realloc, VS100d::crtd__aligned_realloc, + "_aligned_offset_realloc", &VS100d::data.pcrtd_aligned_offset_realloc, VS100d::crtd__aligned_offset_realloc, + "_aligned_recalloc", &VS100d::data.pcrtd_aligned_recalloc, VS100d::crtd__aligned_recalloc, + "_aligned_offset_recalloc", &VS100d::data.pcrtd_aligned_offset_recalloc, VS100d::crtd__aligned_offset_recalloc, + NULL, NULL, NULL, +}; + +static patchentry_t msvcr110Patch [] = { + scalar_new_dbg_name, &VS110::data.pcrtd__scalar_new_dbg, VS110::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS110::data.pcrtd__vector_new_dbg, VS110::crtd__vector_new_dbg, + "calloc", &VS110::data.pcrtd_calloc, VS110::crtd_calloc, + "malloc", &VS110::data.pcrtd_malloc, VS110::crtd_malloc, + "realloc", &VS110::data.pcrtd_realloc, VS110::crtd_realloc, + "_recalloc", &VS110::data.pcrtd_recalloc, VS110::crtd__recalloc, + "_strdup", &VS110::data.pcrtd__strdup, VS110::crtd__strdup, + "_wcsdup", &VS110::data.pcrtd__wcsdup, VS110::crtd__wcsdup, + scalar_new_name, &VS110::data.pcrtd_scalar_new, VS110::crtd_scalar_new, + vector_new_name, &VS110::data.pcrtd_vector_new, VS110::crtd_vector_new, + "_aligned_malloc", &VS110::data.pcrtd_aligned_malloc, VS110::crtd__aligned_malloc, + "_aligned_offset_malloc", &VS110::data.pcrtd_aligned_offset_malloc, VS110::crtd__aligned_offset_malloc, + "_aligned_realloc", &VS110::data.pcrtd_aligned_realloc, VS110::crtd__aligned_realloc, + "_aligned_offset_realloc", &VS110::data.pcrtd_aligned_offset_realloc, VS110::crtd__aligned_offset_realloc, + "_aligned_recalloc", &VS110::data.pcrtd_aligned_recalloc, VS110::crtd__aligned_recalloc, + "_aligned_offset_recalloc", &VS110::data.pcrtd_aligned_offset_recalloc, VS110::crtd__aligned_offset_recalloc, + NULL, NULL, NULL, +}; + +static patchentry_t msvcr110dPatch [] = { + "_calloc_dbg", &VS110d::data.pcrtd__calloc_dbg, VS110d::crtd__calloc_dbg, + "_malloc_dbg", &VS110d::data.pcrtd__malloc_dbg, VS110d::crtd__malloc_dbg, + "_realloc_dbg", &VS110d::data.pcrtd__realloc_dbg, VS110d::crtd__realloc_dbg, + "_recalloc_dbg", &VS110d::data.pcrtd__recalloc_dbg, VS110d::crtd__recalloc_dbg, + "_strdup_dbg", &VS110d::data.pcrtd__strdup_dbg, VS110d::crtd__strdup_dbg, + "_wcsdup_dbg", &VS110d::data.pcrtd__wcsdup_dbg, VS110d::crtd__wcsdup_dbg, + scalar_new_dbg_name, &VS110d::data.pcrtd__scalar_new_dbg, VS110d::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS110d::data.pcrtd__vector_new_dbg, VS110d::crtd__vector_new_dbg, + "calloc", &VS110d::data.pcrtd_calloc, VS110d::crtd_calloc, + "malloc", &VS110d::data.pcrtd_malloc, VS110d::crtd_malloc, + "realloc", &VS110d::data.pcrtd_realloc, VS110d::crtd_realloc, + "_recalloc", &VS110d::data.pcrtd_recalloc, VS110d::crtd__recalloc, + "_strdup", &VS110d::data.pcrtd__strdup, VS110d::crtd__strdup, + "_wcsdup", &VS110d::data.pcrtd__wcsdup, VS110d::crtd__wcsdup, + scalar_new_name, &VS110d::data.pcrtd_scalar_new, VS110d::crtd_scalar_new, + vector_new_name, &VS110d::data.pcrtd_vector_new, VS110d::crtd_vector_new, + "_aligned_malloc_dbg", &VS110d::data.pcrtd__aligned_malloc_dbg, VS110d::crtd__aligned_malloc_dbg, + "_aligned_offset_malloc_dbg", &VS110d::data.pcrtd__aligned_offset_malloc_dbg, VS110d::crtd__aligned_offset_malloc_dbg, + "_aligned_realloc_dbg", &VS110d::data.pcrtd__aligned_realloc_dbg, VS110d::crtd__aligned_realloc_dbg, + "_aligned_offset_realloc_dbg", &VS110d::data.pcrtd__aligned_offset_realloc_dbg, VS110d::crtd__aligned_offset_realloc_dbg, + "_aligned_recalloc_dbg", &VS110d::data.pcrtd__aligned_recalloc_dbg, VS110d::crtd__aligned_recalloc_dbg, + "_aligned_offset_recalloc_dbg", &VS110d::data.pcrtd__aligned_offset_recalloc_dbg, VS110d::crtd__aligned_offset_recalloc_dbg, + "_aligned_malloc", &VS110d::data.pcrtd_aligned_malloc, VS110d::crtd__aligned_malloc, + "_aligned_offset_malloc", &VS110d::data.pcrtd_aligned_offset_malloc, VS110d::crtd__aligned_offset_malloc, + "_aligned_realloc", &VS110d::data.pcrtd_aligned_realloc, VS110d::crtd__aligned_realloc, + "_aligned_offset_realloc", &VS110d::data.pcrtd_aligned_offset_realloc, VS110d::crtd__aligned_offset_realloc, + "_aligned_recalloc", &VS110d::data.pcrtd_aligned_recalloc, VS110d::crtd__aligned_recalloc, + "_aligned_offset_recalloc", &VS110d::data.pcrtd_aligned_offset_recalloc, VS110d::crtd__aligned_offset_recalloc, + NULL, NULL, NULL, +}; + +static patchentry_t msvcr120Patch [] = { + scalar_new_dbg_name, &VS120::data.pcrtd__scalar_new_dbg, VS120::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS120::data.pcrtd__vector_new_dbg, VS120::crtd__vector_new_dbg, + "calloc", &VS120::data.pcrtd_calloc, VS120::crtd_calloc, + "malloc", &VS120::data.pcrtd_malloc, VS120::crtd_malloc, + "realloc", &VS120::data.pcrtd_realloc, VS120::crtd_realloc, + "_recalloc", &VS120::data.pcrtd_recalloc, VS120::crtd__recalloc, + "_strdup", &VS120::data.pcrtd__strdup, VS120::crtd__strdup, + "_wcsdup", &VS120::data.pcrtd__wcsdup, VS120::crtd__wcsdup, + scalar_new_name, &VS120::data.pcrtd_scalar_new, VS120::crtd_scalar_new, + vector_new_name, &VS120::data.pcrtd_vector_new, VS120::crtd_vector_new, + "_aligned_malloc", &VS120::data.pcrtd_aligned_malloc, VS120::crtd__aligned_malloc, + "_aligned_offset_malloc", &VS120::data.pcrtd_aligned_offset_malloc, VS120::crtd__aligned_offset_malloc, + "_aligned_realloc", &VS120::data.pcrtd_aligned_realloc, VS120::crtd__aligned_realloc, + "_aligned_offset_realloc", &VS120::data.pcrtd_aligned_offset_realloc, VS120::crtd__aligned_offset_realloc, + "_aligned_recalloc", &VS120::data.pcrtd_aligned_recalloc, VS120::crtd__aligned_recalloc, + "_aligned_offset_recalloc", &VS120::data.pcrtd_aligned_offset_recalloc, VS120::crtd__aligned_offset_recalloc, + NULL, NULL, NULL, +}; + +static patchentry_t msvcr120dPatch [] = { + "_calloc_dbg", &VS120d::data.pcrtd__calloc_dbg, VS120d::crtd__calloc_dbg, + "_malloc_dbg", &VS120d::data.pcrtd__malloc_dbg, VS120d::crtd__malloc_dbg, + "_realloc_dbg", &VS120d::data.pcrtd__realloc_dbg, VS120d::crtd__realloc_dbg, + "_recalloc_dbg", &VS120d::data.pcrtd__recalloc_dbg, VS120d::crtd__recalloc_dbg, + "_strdup_dbg", &VS120d::data.pcrtd__strdup_dbg, VS120d::crtd__strdup_dbg, + "_wcsdup_dbg", &VS120d::data.pcrtd__wcsdup_dbg, VS120d::crtd__wcsdup_dbg, + scalar_new_dbg_name, &VS120d::data.pcrtd__scalar_new_dbg, VS120d::crtd__scalar_new_dbg, + vector_new_dbg_name, &VS120d::data.pcrtd__vector_new_dbg, VS120d::crtd__vector_new_dbg, + "calloc", &VS120d::data.pcrtd_calloc, VS120d::crtd_calloc, + "malloc", &VS120d::data.pcrtd_malloc, VS120d::crtd_malloc, + "realloc", &VS120d::data.pcrtd_realloc, VS120d::crtd_realloc, + "_recalloc", &VS120d::data.pcrtd_recalloc, VS120d::crtd__recalloc, + "_strdup", &VS120d::data.pcrtd__strdup, VS120d::crtd__strdup, + "_wcsdup", &VS120d::data.pcrtd__wcsdup, VS120d::crtd__wcsdup, + scalar_new_name, &VS120d::data.pcrtd_scalar_new, VS120d::crtd_scalar_new, + vector_new_name, &VS120d::data.pcrtd_vector_new, VS120d::crtd_vector_new, + "_aligned_malloc_dbg", &VS120d::data.pcrtd__aligned_malloc_dbg, VS120d::crtd__aligned_malloc_dbg, + "_aligned_offset_malloc_dbg", &VS120d::data.pcrtd__aligned_offset_malloc_dbg, VS120d::crtd__aligned_offset_malloc_dbg, + "_aligned_realloc_dbg", &VS120d::data.pcrtd__aligned_realloc_dbg, VS120d::crtd__aligned_realloc_dbg, + "_aligned_offset_realloc_dbg", &VS120d::data.pcrtd__aligned_offset_realloc_dbg, VS120d::crtd__aligned_offset_realloc_dbg, + "_aligned_recalloc_dbg", &VS120d::data.pcrtd__aligned_recalloc_dbg, VS120d::crtd__aligned_recalloc_dbg, + "_aligned_offset_recalloc_dbg", &VS120d::data.pcrtd__aligned_offset_recalloc_dbg, VS120d::crtd__aligned_offset_recalloc_dbg, + "_aligned_malloc", &VS120d::data.pcrtd_aligned_malloc, VS120d::crtd__aligned_malloc, + "_aligned_offset_malloc", &VS120d::data.pcrtd_aligned_offset_malloc, VS120d::crtd__aligned_offset_malloc, + "_aligned_realloc", &VS120d::data.pcrtd_aligned_realloc, VS120d::crtd__aligned_realloc, + "_aligned_offset_realloc", &VS120d::data.pcrtd_aligned_offset_realloc, VS120d::crtd__aligned_offset_realloc, + "_aligned_recalloc", &VS120d::data.pcrtd_aligned_recalloc, VS120d::crtd__aligned_recalloc, + "_aligned_offset_recalloc", &VS120d::data.pcrtd_aligned_offset_recalloc, VS120d::crtd__aligned_offset_recalloc, + NULL, NULL, NULL, +}; + +static patchentry_t ucrtbasePatch[] = { + scalar_new_dbg_name, &UCRT::data.pcrtd__scalar_new_dbg, UCRT::crtd__scalar_new_dbg, + vector_new_dbg_name, &UCRT::data.pcrtd__vector_new_dbg, UCRT::crtd__vector_new_dbg, + "calloc", &UCRT::data.pcrtd_calloc, UCRT::crtd_calloc, + "malloc", &UCRT::data.pcrtd_malloc, UCRT::crtd_malloc, + "realloc", &UCRT::data.pcrtd_realloc, UCRT::crtd_realloc, + "_recalloc", &UCRT::data.pcrtd_recalloc, UCRT::crtd__recalloc, + "_strdup", &UCRT::data.pcrtd__strdup, UCRT::crtd__strdup, + "_wcsdup", &UCRT::data.pcrtd__wcsdup, UCRT::crtd__wcsdup, + scalar_new_name, &UCRT::data.pcrtd_scalar_new, UCRT::crtd_scalar_new, + vector_new_name, &UCRT::data.pcrtd_vector_new, UCRT::crtd_vector_new, + "_aligned_malloc", &UCRT::data.pcrtd_aligned_malloc, UCRT::crtd__aligned_malloc, + "_aligned_offset_malloc", &UCRT::data.pcrtd_aligned_offset_malloc, UCRT::crtd__aligned_offset_malloc, + "_aligned_realloc", &UCRT::data.pcrtd_aligned_realloc, UCRT::crtd__aligned_realloc, + "_aligned_offset_realloc", &UCRT::data.pcrtd_aligned_offset_realloc, UCRT::crtd__aligned_offset_realloc, + "_aligned_recalloc", &UCRT::data.pcrtd_aligned_recalloc, UCRT::crtd__aligned_recalloc, + "_aligned_offset_recalloc", &UCRT::data.pcrtd_aligned_offset_recalloc, UCRT::crtd__aligned_offset_recalloc, + NULL, NULL, NULL, +}; + +static patchentry_t ucrtbasedPatch[] = { + "_calloc_dbg", &UCRTd::data.pcrtd__calloc_dbg, UCRTd::crtd__calloc_dbg, + "_malloc_dbg", &UCRTd::data.pcrtd__malloc_dbg, UCRTd::crtd__malloc_dbg, + "_realloc_dbg", &UCRTd::data.pcrtd__realloc_dbg, UCRTd::crtd__realloc_dbg, + "_recalloc_dbg", &UCRTd::data.pcrtd__recalloc_dbg, UCRTd::crtd__recalloc_dbg, + "_strdup_dbg", &UCRTd::data.pcrtd__strdup_dbg, UCRTd::crtd__strdup_dbg, + "_wcsdup_dbg", &UCRTd::data.pcrtd__wcsdup_dbg, UCRTd::crtd__wcsdup_dbg, + scalar_new_dbg_name, &UCRTd::data.pcrtd__scalar_new_dbg, UCRTd::crtd__scalar_new_dbg, + vector_new_dbg_name, &UCRTd::data.pcrtd__vector_new_dbg, UCRTd::crtd__vector_new_dbg, + "calloc", &UCRTd::data.pcrtd_calloc, UCRTd::crtd_calloc, + "malloc", &UCRTd::data.pcrtd_malloc, UCRTd::crtd_malloc, + "realloc", &UCRTd::data.pcrtd_realloc, UCRTd::crtd_realloc, + "_recalloc", &UCRTd::data.pcrtd_recalloc, UCRTd::crtd__recalloc, + "_strdup", &UCRTd::data.pcrtd__strdup, UCRTd::crtd__strdup, + "_wcsdup", &UCRTd::data.pcrtd__wcsdup, UCRTd::crtd__wcsdup, + scalar_new_name, &UCRTd::data.pcrtd_scalar_new, UCRTd::crtd_scalar_new, + vector_new_name, &UCRTd::data.pcrtd_vector_new, UCRTd::crtd_vector_new, + "_aligned_malloc_dbg", &UCRTd::data.pcrtd__aligned_malloc_dbg, UCRTd::crtd__aligned_malloc_dbg, + "_aligned_offset_malloc_dbg", &UCRTd::data.pcrtd__aligned_offset_malloc_dbg, UCRTd::crtd__aligned_offset_malloc_dbg, + "_aligned_realloc_dbg", &UCRTd::data.pcrtd__aligned_realloc_dbg, UCRTd::crtd__aligned_realloc_dbg, + "_aligned_offset_realloc_dbg", &UCRTd::data.pcrtd__aligned_offset_realloc_dbg, UCRTd::crtd__aligned_offset_realloc_dbg, + "_aligned_recalloc_dbg", &UCRTd::data.pcrtd__aligned_recalloc_dbg, UCRTd::crtd__aligned_recalloc_dbg, + "_aligned_offset_recalloc_dbg", &UCRTd::data.pcrtd__aligned_offset_recalloc_dbg, UCRTd::crtd__aligned_offset_recalloc_dbg, + "_aligned_malloc", &UCRTd::data.pcrtd_aligned_malloc, UCRTd::crtd__aligned_malloc, + "_aligned_offset_malloc", &UCRTd::data.pcrtd_aligned_offset_malloc, UCRTd::crtd__aligned_offset_malloc, + "_aligned_realloc", &UCRTd::data.pcrtd_aligned_realloc, UCRTd::crtd__aligned_realloc, + "_aligned_offset_realloc", &UCRTd::data.pcrtd_aligned_offset_realloc, UCRTd::crtd__aligned_offset_realloc, + "_aligned_recalloc", &UCRTd::data.pcrtd_aligned_recalloc, UCRTd::crtd__aligned_recalloc, + "_aligned_offset_recalloc", &UCRTd::data.pcrtd_aligned_offset_recalloc, UCRTd::crtd__aligned_offset_recalloc, + NULL, NULL, NULL, +}; + +patchentry_t VisualLeakDetector::m_ntdllPatch [] = { + "RtlAllocateHeap", NULL, _RtlAllocateHeap, + "RtlFreeHeap", NULL, _RtlFreeHeap, + "RtlReAllocateHeap", NULL, _RtlReAllocateHeap, + NULL, NULL, NULL +}; + +patchentry_t VisualLeakDetector::m_ole32Patch [] = { + "CoGetMalloc", NULL, _CoGetMalloc, + "CoTaskMemAlloc", NULL, _CoTaskMemAlloc, + "CoTaskMemRealloc", NULL, _CoTaskMemRealloc, + NULL, NULL, NULL +}; + +moduleentry_t VisualLeakDetector::m_patchTable [] = { + // Win32 heap APIs. + "kernel32.dll", FALSE, 0x0, m_kernelbasePatch, // we patch this record on Win7 and higher + "kernel32.dll", FALSE, 0x0, m_kernel32Patch, + + // MFC new operators (exported by ordinal). + "mfc42.dll", TRUE, 0x0, mfc42Patch, + "mfc42d.dll", TRUE, 0x0, mfc42dPatch, + "mfc42u.dll", TRUE, 0x0, mfc42uPatch, + "mfc42ud.dll", TRUE, 0x0, mfc42udPatch, + "mfc70.dll", TRUE, 0x0, mfc70Patch, + "mfc70d.dll", TRUE, 0x0, mfc70dPatch, + "mfc70u.dll", TRUE, 0x0, mfc70uPatch, + "mfc70ud.dll", TRUE, 0x0, mfc70udPatch, + "mfc71.dll", TRUE, 0x0, mfc71Patch, + "mfc71d.dll", TRUE, 0x0, mfc71dPatch, + "mfc71u.dll", TRUE, 0x0, mfc71uPatch, + "mfc71ud.dll", TRUE, 0x0, mfc71udPatch, + "mfc80.dll", TRUE, 0x0, mfc80Patch, + "mfc80d.dll", TRUE, 0x0, mfc80dPatch, + "mfc80u.dll", TRUE, 0x0, mfc80uPatch, + "mfc80ud.dll", TRUE, 0x0, mfc80udPatch, + "mfc90.dll", TRUE, 0x0, mfc90Patch, + "mfc90d.dll", TRUE, 0x0, mfc90dPatch, + "mfc90u.dll", TRUE, 0x0, mfc90uPatch, + "mfc90ud.dll", TRUE, 0x0, mfc90udPatch, + "mfc100.dll", TRUE, 0x0, mfc100Patch, + "mfc100d.dll", TRUE, 0x0, mfc100dPatch, + "mfc100u.dll", TRUE, 0x0, mfc100uPatch, + "mfc100ud.dll", TRUE, 0x0, mfc100udPatch, + "mfc110.dll", TRUE, 0x0, mfc110Patch, + "mfc110d.dll", TRUE, 0x0, mfc110dPatch, + "mfc110u.dll", TRUE, 0x0, mfc110uPatch, + "mfc110ud.dll", TRUE, 0x0, mfc110udPatch, + "mfc120.dll", TRUE, 0x0, mfc120Patch, + "mfc120d.dll", TRUE, 0x0, mfc120dPatch, + "mfc120u.dll", TRUE, 0x0, mfc120uPatch, + "mfc120ud.dll", TRUE, 0x0, mfc120udPatch, + "mfc140.dll", TRUE, 0x0, mfc140Patch, + "mfc140d.dll", TRUE, 0x0, mfc140dPatch, + "mfc140u.dll", TRUE, 0x0, mfc140uPatch, + "mfc140ud.dll", TRUE, 0x0, mfc140udPatch, + + // CRT new operators and heap APIs. + "msvcrt.dll", FALSE, 0x0, msvcrtPatch, + "msvcrtd.dll", FALSE, 0x0, msvcrtdPatch, + "msvcr70.dll", FALSE, 0x0, msvcr70Patch, + "msvcr70d.dll", FALSE, 0x0, msvcr70dPatch, + "msvcr71.dll", FALSE, 0x0, msvcr71Patch, + "msvcr71d.dll", FALSE, 0x0, msvcr71dPatch, + "msvcr80.dll", FALSE, 0x0, msvcr80Patch, + "msvcr80d.dll", FALSE, 0x0, msvcr80dPatch, + "msvcr90.dll", FALSE, 0x0, msvcr90Patch, + "msvcr90d.dll", FALSE, 0x0, msvcr90dPatch, + "msvcr100.dll", FALSE, 0x0, msvcr100Patch, + "msvcr100d.dll",FALSE, 0x0, msvcr100dPatch, + "msvcr110.dll", FALSE, 0x0, msvcr110Patch, + "msvcr110d.dll",FALSE, 0x0, msvcr110dPatch, + "msvcr120.dll", FALSE, 0x0, msvcr120Patch, + "msvcr120d.dll",FALSE, 0x0, msvcr120dPatch, + "ucrtbase.dll", FALSE, 0x0, ucrtbasePatch, + "ucrtbased.dll",FALSE, 0x0, ucrtbasedPatch, + + // NT APIs. + "ntdll.dll", FALSE, 0x0, m_ntdllPatch, + + // COM heap APIs. + "ole32.dll", FALSE, 0x0, m_ole32Patch +}; diff --git a/src/loaderlock.h b/src/loaderlock.h new file mode 100644 index 00000000..5fdab5f4 --- /dev/null +++ b/src/loaderlock.h @@ -0,0 +1,57 @@ +#pragma once + +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#include "ntapi.h" + +// +// LdrLockLoaderLock Flags +// +#define LDR_LOCK_LOADER_LOCK_FLAG_DEFAULT 0x00000000 +#define LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS 0x00000001 +#define LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY 0x00000002 + +// +// LdrUnlockLoaderLock Flags +// +#define LDR_UNLOCK_LOADER_LOCK_FLAG_DEFAULT 0x00000000 +#define LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS 0x00000001 + +// +// LdrLockLoaderLock State +// +#define LDR_LOCK_LOADER_LOCK_STATE_INVALID 0 +#define LDR_LOCK_LOADER_LOCK_STATE_LOCK_ACQUIRED 1 +#define LDR_LOCK_LOADER_LOCK_STATE_LOCK_NOT_ACQUIRED 2 + +class LoaderLock +{ +public: + LoaderLock() : m_uCookie(NULL), m_hThreadId(NULL) { + ULONG uState = NULL; + NTSTATUS ntStatus = LdrLockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_DEFAULT, &uState, &m_uCookie); + if (ntStatus == STATUS_SUCCESS) { + m_hThreadId = GetCurrentThreadId(); + } + } + + ~LoaderLock() { + if (m_uCookie) { + NTSTATUS ntStatus = LdrUnlockLoaderLock(LDR_UNLOCK_LOADER_LOCK_FLAG_DEFAULT, m_uCookie); + if (ntStatus == STATUS_SUCCESS) { + m_hThreadId = NULL; + m_uCookie = NULL; + } + } + } + +private: + // Disallow certain operations + LoaderLock(const LoaderLock&); + LoaderLock& operator=(const LoaderLock&); + +private: + DWORD m_hThreadId; + ULONG_PTR m_uCookie; +}; diff --git a/map.h b/src/map.h similarity index 94% rename from map.h rename to src/map.h index 488eaec4..1c8f456d 100644 --- a/map.h +++ b/src/map.h @@ -1,357 +1,355 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - Lightweight STL-like Map Template -// Copyright (c) 2006 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef VLDBUILD -#error \ -"This header should only be included by Visual Leak Detector when building it from source. \ -Applications should never include this header." -#endif - -#include "tree.h" // Provides access to the Tree template class. - -//////////////////////////////////////////////////////////////////////////////// -// -// The Pair Template Class -// -// This is a lightweight STL-like pair template, for use with the lightweight -// Map class template. -// -// Note that while this is a STL-like class, it is not a full STL-compliant -// implementation of the STL pair utility class. It provides just the bare -// minimum functionality required by the Visual Leak Detector Map template -// class below. -// -template -class Pair { -public: - // Constructor - Pair () - { - first = Tf(); - second = Ts(); - } - - // Constructor with initializers. - Pair (const Tf &f, const Ts &s) - { - first = f; - second = s; - } - - // Less-than operator - Compares this Pair with another Pair to determine - // if this Pair is less than the other Pair. The Pair with the smallest - // "first" value is the lesser Pair. - // - // - other (IN): The other pair to compare against. - // - // Return Value: - // - // Returns true if this Pair is less than the other Pair. Otherwise - // returns false. - // - BOOL operator < (const Pair &other) const - { - return (first < other.first); - } - - // Public data. - Tf first; // The first value of the pair. - Ts second; // The second value of the pair. -}; - -//////////////////////////////////////////////////////////////////////////////// -// -// The Map Template Class -// -// This is a lightweidht STL-like map template. It makes use of the Tree class -// template to enable fast insert, find, and erase operations. -// -// Note that while this is a STL-like class, it is not a full STL-compliant -// implementation of the STL map container. It contains just the bare minimum -// functionality required by Visual Leak Detector. Because of its "lightweight" -// nature, this map class has a noticeable performance advantage over some -// other standard STL map implementations. -// -template -class Map { -public: - class Iterator { - public: - // Constructor - Iterator () - { - // Plainly constructed iterators don't reference anything. - m_node = NULL; - m_tree = NULL; - } - - // operator != - Inequality operator for Map Iterators. Two Map - // Iterators are considered equal if and only if they both reference - // the same key/value pair in the same Map. - // - // - other (IN): The other Map Iterator to compare against. - // - // Return Value: - // - // Returns true if the specified Map Iterator is not equal to this - // Map Iterator; otherwise, returns false. - // - BOOL operator != (const Iterator &other) const - { - return ((m_tree != other.m_tree) || (m_node != other.m_node)); - } - - // operator * - Dereference operator for Map Iterators. - // - // Note: The reference returned by this function is "const", so the - // value referenced by the Iterator may not be modified through the - // Iterator. This is a departure from STL iterator behavior. - // - // Also, dereferencing an Iterator which does not reference a valid - // value in the Map is undefined and will almost certainly cause a - // crash. - // - // Return Value: - // - // Returns a const reference to the key/value pair in the Map - // referenced by the Iterator. - // - const Pair& operator * () const - { - return m_node->key; - } - - // operator ++ - Prefix increment operator for Map Iterators. Causes the - // Iterator to reference the in-oder successor of the key/value pair - // currently referenced by the Iterator. If the Iterator is currently - // referencing the largest key/value pair in the Map, then the - // resulting Iterator will reference the Map's end (the NULL pair). - // - // Note: Incrementing an Iterator which does not reference a valid - // key/value pair in the Map is undefined and will almost certainly - // cause a crash. - // - // Return Value: - // - // Returns the Iterator after it has been incremented. - // - Iterator& operator ++ (int) - { - m_node = m_tree->next(m_node); - return *this; - } - - // operator ++ - Postfix increment operator for Map Iterators. Causes - // the Iterator to reference the in-order successor of the key/value - // pair currently referenced by the Iterator. If the Iterator is - // currently referencing the largest key/value pair in the Map, then - // the resulting Iterator will reference the Map's end (the NULL - // pair). - // - // Note: Incrementing an Iterator which does not reference a valid - // key/value pair in the Map is undefined and will almost certainly - // cause a crash. - // - // Return Value: - // - // Returns the Iterator before it has been incremented. - // - Iterator operator ++ () - { - typename Tree >::node_t *cur = m_node; - - m_node = m_tree->next(m_node); - return Iterator(m_tree, cur); - } - - // operator - - Subtraction operator for Map Iterators. Causes the - // the Iterator to reference a key/value pair that is an in-order - // predecessor of the currently refereced key/value pair. - // - // - num (IN): Number indicating the number of preceding key/value - // pairs to decrement the iterator. - // - // Return Value: - // - // Returns an Iterator referencing the key/value pair that precedes - // the original Iterator by "num" pairs. - // - Iterator operator - (SIZE_T num) const - { - SIZE_T count; - typename Tree >::node_t *cur = m_node; - - cur = m_tree->prev(m_node); - for (count = 0; count < num; count++) { - cur = m_tree->prev(m_node); - if (cur == NULL) { - return Iterator(m_tree, NULL); - } - } - return Iterator(m_tree, cur); - } - - // operator == - Equality operator for Map Iterators. Map Iterators are - // considered equal if and only if they both refernce the same - // key/value pair in the same Map. - // - // - other (IN): The other Map Iterator to compare against. - // - // Return Value: - // - // Returns true if the specified Map Iterator is equal to this Map - // Iterator; otherwise returns false. - // - BOOL operator == (const Iterator &other) const - { - return ((m_tree == other.m_tree) && (m_node == other.m_node)); - } - - private: - // Private constructor. Only the Map class itself may use this - // constructor. It is used for constructing Iterators which reference - // specific nodes in the internal tree's structure. - Iterator (const Tree > *tree, typename Tree >::node_t *node) - { - m_node = node; - m_tree = tree; - } - - typename Tree >::node_t *m_node; // Pointer to the node referenced by the Map Iterator. - const Tree > *m_tree; // Pointer to the tree containing the referenced node. - - // The Map class is a friend of Map Iterators. - friend class Map; - }; - - // begin - Obtains an Iterator referencing the beginning of the Map (i.e. - // the lowest key/value pair currently stored in the Map). - // - // Return Value: - // - // Returns an Iterator referencing the first key/value pair in the Map. - // If no key/value pairs are currenly stored in the map, returns the - // "NULL" Iterator. - // - Iterator begin () const - { - return Iterator(&m_tree, m_tree.begin()); - } - - // end - Obtains an Iterator referencing the end of the Map. The end of - // the map does not reference an actual key/value pair. Instead it - // represents a "null" key/value pair which signifies the end (i.e. just - // beyond largest key/value pair currently stored in the Map). Also - // known as the "NULL" Iterator. - // - // Return Value: - // - // Returns the "NULL" Iterator, signifying the end of the Map. - // - Iterator end () const - { - return Iterator(&m_tree, NULL); - } - - // erase - Erases a key/value pair from the map. - // - // - it (IN): Iterator referencing the key/value pair to be erased from - // the map. - // - // Return Value: - // - // None. - // - VOID erase (Iterator& it) - { - m_tree.erase(it.m_node); - } - - // erase - Erases a key/value pair from the map. - // - // - key (IN): The key corresponding to the key/value pair to be erased - // from the map. - // - // Return Value: - // - // None. - // - VOID erase (const Tk &key) - { - m_tree.erase(Pair(key, Tv())); - } - - // find - Finds a key/value pair in the map. - // - // - key (IN): The key corresponding to the key/value pair to be found. - // - // Return Value: - // - // Returns an Iterator referencing the found key/value pair. If no - // key/value pair with the specified key could be found, then the "NULL" - // Iterator is returned. - // - Iterator find (const Tk &key) const - { - return Iterator(&m_tree, m_tree.find(Pair(key, Tv()))); - } - - // insert - Inserts a key/value pair into the map. - // - // - key (IN): The key of the key/value pair to be inserted. - // - // - data (IN): The value of the key/value pair to be inserted. - // - // Return Value: - // - // Returns an Iterator referencing the resulting key/value pair after - // if has been inserted into the map. - // - Iterator insert (const Tk &key, const Tv &data) - { - return Iterator(&m_tree, m_tree.insert(Pair(key, data))); - } - - // reserve - Sets the reserve size of the map. The reserve size is the - // number of key/value pairs for which space should be pre-allocated - // to avoid frequent heap hits when inserting new key/value pairs into - // the map. - // - // - count (IN): The number of key/value pairs for which to reserve space - // in advance. - // - // Return Value: - // - // Returns the reserve size previously in use by the map. - // - size_t reserve (size_t count) - { - return m_tree.reserve(count); - } - -private: - // Private data - Tree > m_tree; // The key/value pairs are actually stored in a tree. -}; +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - Lightweight STL-like Map Template +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef VLDBUILD +#error \ +"This header should only be included by Visual Leak Detector when building it from source. \ +Applications should never include this header." +#endif + +#include "tree.h" // Provides access to the Tree template class. + +//////////////////////////////////////////////////////////////////////////////// +// +// The Pair Template Class +// +// This is a lightweight STL-like pair template, for use with the lightweight +// Map class template. +// +// Note that while this is a STL-like class, it is not a full STL-compliant +// implementation of the STL pair utility class. It provides just the bare +// minimum functionality required by the Visual Leak Detector Map template +// class below. +// +template +class Pair { +public: + // Constructor + Pair () + { + first = Tf(); + second = Ts(); + } + + // Constructor with initializers. + Pair (const Tf &f, const Ts &s) + { + first = f; + second = s; + } + + // Less-than operator - Compares this Pair with another Pair to determine + // if this Pair is less than the other Pair. The Pair with the smallest + // "first" value is the lesser Pair. + // + // - other (IN): The other pair to compare against. + // + // Return Value: + // + // Returns true if this Pair is less than the other Pair. Otherwise + // returns false. + // + BOOL operator < (const Pair &other) const + { + return (first < other.first); + } + + // Public data. + Tf first; // The first value of the pair. + Ts second; // The second value of the pair. +}; + +//////////////////////////////////////////////////////////////////////////////// +// +// The Map Template Class +// +// This is a lightweidht STL-like map template. It makes use of the Tree class +// template to enable fast insert, find, and erase operations. +// +// Note that while this is a STL-like class, it is not a full STL-compliant +// implementation of the STL map container. It contains just the bare minimum +// functionality required by Visual Leak Detector. Because of its "lightweight" +// nature, this map class has a noticeable performance advantage over some +// other standard STL map implementations. +// +template +class Map { +public: + class Iterator { + public: + // Constructor + Iterator () + { + // Plainly constructed iterators don't reference anything. + m_node = NULL; + m_tree = NULL; + } + + // operator != - Inequality operator for Map Iterators. Two Map + // Iterators are considered equal if and only if they both reference + // the same key/value pair in the same Map. + // + // - other (IN): The other Map Iterator to compare against. + // + // Return Value: + // + // Returns true if the specified Map Iterator is not equal to this + // Map Iterator; otherwise, returns false. + // + BOOL operator != (const Iterator &other) const + { + return ((m_tree != other.m_tree) || (m_node != other.m_node)); + } + + // operator * - Dereference operator for Map Iterators. + // + // Note: The reference returned by this function is "const", so the + // value referenced by the Iterator may not be modified through the + // Iterator. This is a departure from STL iterator behavior. + // + // Also, dereferencing an Iterator which does not reference a valid + // value in the Map is undefined and will almost certainly cause a + // crash. + // + // Return Value: + // + // Returns a const reference to the key/value pair in the Map + // referenced by the Iterator. + // + const Pair& operator * () const + { + return m_node->key; + } + + // operator ++ - Prefix increment operator for Map Iterators. Causes the + // Iterator to reference the in-oder successor of the key/value pair + // currently referenced by the Iterator. If the Iterator is currently + // referencing the largest key/value pair in the Map, then the + // resulting Iterator will reference the Map's end (the NULL pair). + // + // Note: Incrementing an Iterator which does not reference a valid + // key/value pair in the Map is undefined and will almost certainly + // cause a crash. + // + // Return Value: + // + // Returns the Iterator after it has been incremented. + // + Iterator& operator ++ (int) + { + m_node = m_tree->next(m_node); + return *this; + } + + // operator ++ - Postfix increment operator for Map Iterators. Causes + // the Iterator to reference the in-order successor of the key/value + // pair currently referenced by the Iterator. If the Iterator is + // currently referencing the largest key/value pair in the Map, then + // the resulting Iterator will reference the Map's end (the NULL + // pair). + // + // Note: Incrementing an Iterator which does not reference a valid + // key/value pair in the Map is undefined and will almost certainly + // cause a crash. + // + // Return Value: + // + // Returns the Iterator before it has been incremented. + // + Iterator operator ++ () + { + typename Tree >::node_t *cur = m_node; + + m_node = m_tree->next(m_node); + return Iterator(m_tree, cur); + } + + // operator - - Subtraction operator for Map Iterators. Causes the + // the Iterator to reference a key/value pair that is an in-order + // predecessor of the currently referenced key/value pair. + // + // - num (IN): Number indicating the number of preceding key/value + // pairs to decrement the iterator. + // + // Return Value: + // + // Returns an Iterator referencing the key/value pair that precedes + // the original Iterator by "num" pairs. + // + Iterator operator - (SIZE_T num) const + { + typename Tree >::node_t *cur = m_node; + + for (SIZE_T count = 0; count < num; count++) { + cur = m_tree->prev(cur); + if (cur == NULL) { + return Iterator(m_tree, NULL); + } + } + return Iterator(m_tree, cur); + } + + // operator == - Equality operator for Map Iterators. Map Iterators are + // considered equal if and only if they both reference the same + // key/value pair in the same Map. + // + // - other (IN): The other Map Iterator to compare against. + // + // Return Value: + // + // Returns true if the specified Map Iterator is equal to this Map + // Iterator; otherwise returns false. + // + BOOL operator == (const Iterator &other) const + { + return ((m_tree == other.m_tree) && (m_node == other.m_node)); + } + + private: + // Private constructor. Only the Map class itself may use this + // constructor. It is used for constructing Iterators which reference + // specific nodes in the internal tree's structure. + Iterator (const Tree > *tree, typename Tree >::node_t *node) + { + m_node = node; + m_tree = tree; + } + + typename Tree >::node_t *m_node; // Pointer to the node referenced by the Map Iterator. + const Tree > *m_tree; // Pointer to the tree containing the referenced node. + + // The Map class is a friend of Map Iterators. + friend class Map; + }; + + // begin - Obtains an Iterator referencing the beginning of the Map (i.e. + // the lowest key/value pair currently stored in the Map). + // + // Return Value: + // + // Returns an Iterator referencing the first key/value pair in the Map. + // If no key/value pairs are currenly stored in the map, returns the + // "NULL" Iterator. + // + Iterator begin () const + { + return Iterator(&m_tree, m_tree.begin()); + } + + // end - Obtains an Iterator referencing the end of the Map. The end of + // the map does not reference an actual key/value pair. Instead it + // represents a "null" key/value pair which signifies the end (i.e. just + // beyond largest key/value pair currently stored in the Map). Also + // known as the "NULL" Iterator. + // + // Return Value: + // + // Returns the "NULL" Iterator, signifying the end of the Map. + // + Iterator end () const + { + return Iterator(&m_tree, NULL); + } + + // erase - Erases a key/value pair from the map. + // + // - it (IN): Iterator referencing the key/value pair to be erased from + // the map. + // + // Return Value: + // + // None. + // + VOID erase (Iterator& it) + { + m_tree.erase(it.m_node); + } + + // erase - Erases a key/value pair from the map. + // + // - key (IN): The key corresponding to the key/value pair to be erased + // from the map. + // + // Return Value: + // + // None. + // + VOID erase (const Tk &key) + { + m_tree.erase(Pair(key, Tv())); + } + + // find - Finds a key/value pair in the map. + // + // - key (IN): The key corresponding to the key/value pair to be found. + // + // Return Value: + // + // Returns an Iterator referencing the found key/value pair. If no + // key/value pair with the specified key could be found, then the "NULL" + // Iterator is returned. + // + Iterator find (const Tk &key) const + { + return Iterator(&m_tree, m_tree.find(Pair(key, Tv()))); + } + + // insert - Inserts a key/value pair into the map. + // + // - key (IN): The key of the key/value pair to be inserted. + // + // - data (IN): The value of the key/value pair to be inserted. + // + // Return Value: + // + // Returns an Iterator referencing the resulting key/value pair after + // if has been inserted into the map. + // + Iterator insert (const Tk &key, const Tv &data) + { + return Iterator(&m_tree, m_tree.insert(Pair(key, data))); + } + + // reserve - Sets the reserve size of the map. The reserve size is the + // number of key/value pairs for which space should be pre-allocated + // to avoid frequent heap hits when inserting new key/value pairs into + // the map. + // + // - count (IN): The number of key/value pairs for which to reserve space + // in advance. + // + // Return Value: + // + // Returns the reserve size previously in use by the map. + // + size_t reserve (size_t count) + { + return m_tree.reserve(count); + } + +private: + // Private data + Tree > m_tree; // The key/value pairs are actually stored in a tree. +}; diff --git a/ntapi.cpp b/src/ntapi.cpp similarity index 82% rename from ntapi.cpp rename to src/ntapi.cpp index da287ea3..437dc65d 100644 --- a/ntapi.cpp +++ b/src/ntapi.cpp @@ -1,32 +1,40 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - Global NT API Function Pointers -// Copyright (c) 2006 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#define VLDBUILD -#include "ntapi.h" - -// Global function pointers for explicit dynamic linking with NT APIs that can't -// be load-time linked (there is no import library available for these). -LdrLoadDll_t LdrLoadDll; -RtlAllocateHeap_t RtlAllocateHeap; -RtlFreeHeap_t RtlFreeHeap; -RtlReAllocateHeap_t RtlReAllocateHeap; +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - Global NT API Function Pointers +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#define VLDBUILD +#include "ntapi.h" + +// Global function pointers for explicit dynamic linking with NT APIs that can't +// be load-time linked (there is no import library available for these). +LdrLoadDll_t LdrLoadDll; +LdrLoadDllWin8_t LdrLoadDllWin8; +RtlAllocateHeap_t RtlAllocateHeap; +RtlFreeHeap_t RtlFreeHeap; +RtlReAllocateHeap_t RtlReAllocateHeap; + +LdrGetDllHandle_t LdrGetDllHandle; +LdrGetProcedureAddress_t LdrGetProcedureAddress; +LdrUnloadDll_t LdrUnloadDll; +LdrLockLoaderLock_t LdrLockLoaderLock; +LdrUnlockLoaderLock_t LdrUnlockLoaderLock; \ No newline at end of file diff --git a/ntapi.h b/src/ntapi.h similarity index 67% rename from ntapi.h rename to src/ntapi.h index fef2b92a..38220171 100644 --- a/ntapi.h +++ b/src/ntapi.h @@ -1,57 +1,71 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - NT API Definitions -// Copyright (c) 2006-2009 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef VLDBUILD -#error \ -"This header should only be included by Visual Leak Detector when building it from source. \ -Applications should never include this header." -#endif - -#include - -// Return code type used by LdrLoadDll. -typedef LONG NTSTATUS; -#define STATUS_SUCCESS 0 - -// Unicode string structure used by NT APIs. -typedef struct unicodestring_s { - USHORT length; // Length of the string. - USHORT maxlength; // Length of the buffer. - PWSTR buffer; // The buffer containing the string. -} unicodestring_t; - -// Function pointer types for explicit dynamic linking with functions that can't -// be load-time linked (no import library is available for these). -typedef NTSTATUS (__stdcall *LdrLoadDll_t) (LPWSTR, PDWORD, unicodestring_t *, PHANDLE); -typedef LPVOID (__stdcall *RtlAllocateHeap_t) (HANDLE, DWORD, SIZE_T); -typedef BOOL (__stdcall *RtlFreeHeap_t) (HANDLE, DWORD, LPVOID); -typedef LPVOID (__stdcall *RtlReAllocateHeap_t) (HANDLE, DWORD, LPVOID, SIZE_T); - -// Provide forward declarations for the NT APIs for any source files that -// include this header. -extern LdrLoadDll_t LdrLoadDll; -extern RtlAllocateHeap_t RtlAllocateHeap; -extern RtlFreeHeap_t RtlFreeHeap; -extern RtlReAllocateHeap_t RtlReAllocateHeap; +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - NT API Definitions +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef VLDBUILD +#error \ +"This header should only be included by Visual Leak Detector when building it from source. \ +Applications should never include this header." +#endif + +#include + +// Return code type used by LdrLoadDll. +typedef __success(return >= 0) LONG NTSTATUS; +#define STATUS_SUCCESS 0 + +// Unicode string structure used by NT APIs. +struct unicodestring_t { + USHORT length; // Length of the string. + USHORT maxlength; // Length of the buffer. + PWSTR buffer; // The buffer containing the string. +}; + +// Function pointer types for explicit dynamic linking with functions that can't +// be load-time linked (no import library is available for these). +typedef NTSTATUS (__stdcall *LdrLoadDll_t) (LPWSTR, PULONG, unicodestring_t *, PHANDLE); +typedef NTSTATUS (__stdcall *LdrLoadDllWin8_t) (DWORD_PTR, PULONG, unicodestring_t *, PHANDLE); +typedef LPVOID (__stdcall *RtlAllocateHeap_t) (HANDLE, DWORD, SIZE_T); +typedef BYTE (__stdcall *RtlFreeHeap_t) (HANDLE, DWORD, LPVOID); +typedef LPVOID (__stdcall *RtlReAllocateHeap_t) (HANDLE, DWORD, LPVOID, SIZE_T); + +typedef NTSTATUS(NTAPI *LdrGetDllHandle_t) (PWSTR, PULONG, PUNICODE_STRING, PVOID *); +typedef NTSTATUS(NTAPI *LdrGetProcedureAddress_t)(PVOID, PANSI_STRING, ULONG, PVOID *); +typedef NTSTATUS(NTAPI *LdrUnloadDll_t)(PVOID); +typedef NTSTATUS(NTAPI *LdrLockLoaderLock_t)(ULONG, PULONG, PULONG_PTR); +typedef NTSTATUS(NTAPI *LdrUnlockLoaderLock_t)(ULONG, ULONG_PTR); + +// Provide forward declarations for the NT APIs for any source files that +// include this header. +extern LdrLoadDll_t LdrLoadDll; +extern LdrLoadDllWin8_t LdrLoadDllWin8; +extern RtlAllocateHeap_t RtlAllocateHeap; +extern RtlFreeHeap_t RtlFreeHeap; +extern RtlReAllocateHeap_t RtlReAllocateHeap; + +extern LdrGetDllHandle_t LdrGetDllHandle; +extern LdrGetProcedureAddress_t LdrGetProcedureAddress; +extern LdrUnloadDll_t LdrUnloadDll; +extern LdrLockLoaderLock_t LdrLockLoaderLock; +extern LdrUnlockLoaderLock_t LdrUnlockLoaderLock; diff --git a/resource.h b/src/resource.h old mode 100755 new mode 100644 similarity index 96% rename from resource.h rename to src/resource.h index c6b72e6e..c210abbb --- a/resource.h +++ b/src/resource.h @@ -1,14 +1,14 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by vld.rc - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by vld.rc + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/src/runalltests.bat b/src/runalltests.bat new file mode 100644 index 00000000..6528efdc --- /dev/null +++ b/src/runalltests.bat @@ -0,0 +1,15 @@ +@ECHO OFF +CLS +CMD /C "runtests Win32 Release-%1" +CMD /C "runtests Win32 Release_StaticCrt-%1" +CMD /C "runtests Win32 Debug-%1" +CMD /C "runtests Win32 Debug_StaticCrt-%1" +CMD /C "runtests Win32 Debug(Release)-%1" +CMD /C "runtests Win32 Debug(Release)_StaticCrt-%1" + +CMD /C "runtests x64 Release-%1" +CMD /C "runtests x64 Release_StaticCrt-%1" +CMD /C "runtests x64 Debug-%1" +CMD /C "runtests x64 Debug_StaticCrt-%1" +CMD /C "runtests x64 Debug(Release)-%1" +CMD /C "runtests x64 Debug(Release)_StaticCrt-%1" diff --git a/src/runtests.bat b/src/runtests.bat new file mode 100644 index 00000000..b4c4fbef --- /dev/null +++ b/src/runtests.bat @@ -0,0 +1,38 @@ +@ECHO OFF +SETLOCAL ENABLEDELAYEDEXPANSION + +SET tests_path=%~dp0\bin\%1\%~2 +IF NOT EXIST "!tests_path!\" GOTO nodir + +CD %~dp0\bin + +ECHO ------------------------------------------------------------------------------- +ECHO [ RUNNING ] %tests_path%\test_basics.exe +ECHO ------------------------------------------------------------------------------- +!tests_path!\test_basics.exe --gtest_output="xml:!tests_path!\test_basics.exe.xml" +ECHO ------------------------------------------------------------------------------- +ECHO [ RUNNING ] %tests_path%\dynamic_app.exe +ECHO ------------------------------------------------------------------------------- +!tests_path!\dynamic_app.exe --gtest_output="xml:!tests_path!\dynamic_app.exe.xml" +ECHO ------------------------------------------------------------------------------- +ECHO [ RUNNING ] %tests_path%\testsuite.exe +ECHO ------------------------------------------------------------------------------- +!tests_path!\testsuite.exe --gtest_output="xml:!tests_path!\testsuite.exe.xml" +ECHO ------------------------------------------------------------------------------- +ECHO [ RUNNING ] %tests_path%\corruption.exe +ECHO ------------------------------------------------------------------------------- +!tests_path!\corruption.exe --gtest_output="xml:!tests_path!\corruption.exe.xml" +ECHO ------------------------------------------------------------------------------- +ECHO [ RUNNING ] %tests_path%\vld_unload.exe +ECHO ------------------------------------------------------------------------------- +!tests_path!\vld_unload.exe --gtest_output="xml:!tests_path!\vld_unload.exe.xml" +ECHO ------------------------------------------------------------------------------- +ECHO [ RUNNING ] %tests_path%\vld_main_test.exe +ECHO ------------------------------------------------------------------------------- +!tests_path!\vld_main_test.exe --gtest_output="xml:!tests_path!\vld_main_test.exe.xml" +ECHO ------------------------------------------------------------------------------- +EXIT /b 0 + +:nodir +ECHO No test dir: "!tests_path!\" +EXIT /b 1 \ No newline at end of file diff --git a/set.h b/src/set.h similarity index 93% rename from set.h rename to src/set.h index 23829b2b..c3a03865 100644 --- a/set.h +++ b/src/set.h @@ -1,337 +1,335 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - Lightweight STL-like Set Template -// Copyright (c) 2006 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef VLDBUILD -#error \ -"This header should only be included by Visual Leak Detector when building it from source. \ -Applications should never include this header." -#endif - -#include "tree.h" // Provides access to the Tree template class. - -//////////////////////////////////////////////////////////////////////////////// -// -// The Set Template Class -// -// This is a lightweight STL-like set template. It makes use of the Tree class -// template to enable fast insert, find, and erase operations. -// -// Note that while this is a STL-like class, it is not a full STL-compliant -// implementation of the STL set container. It contains just the bare minimum -// functionality required by Visual Leak Detector. Because of its "lightweight" -// nature, this set class has a noticeable performance advantage over some -// other standard STL set implementations. -// -template -class Set { -public: - class Iterator { - public: - // Constructor - Iterator () - { - // Plainly constructed iterators don't reference anything. - m_node = NULL; - m_tree = NULL; - } - - // operator != - Inequality operator for Set Iterators. Two Set - // Iterators are considered equal if and only if they both reference - // the same key in the same Set. - // - // - other (IN): The other Set Iterator to compare against. - // - // Return Value: - // - // Returns true if the specified Set Iterator is not equal to this - // Set Iterator; otherwise, returns false. - // - BOOL operator != (const Iterator &other) const - { - return ((m_tree != other.m_tree) || (m_node != other.m_node)); - } - - // operator * - Dereference operator for Set Iterators. - // - // Note: The reference returned by this function is "const", so the - // value referenced by the Iterator may not be modified through the - // Iterator. This is a departure from STL iterator behavior. - // - // Also, dereferencing an Iterator which does not reference a valid - // value in the Set is undefined and will almost certainly cause a - // crash. - // - // Return Value: - // - // Returns a const reference to the key in the Map referenced by the - // Iterator. - // - const Tk& operator * () const - { - return m_node->key; - } - - // operator ++ - Prefix increment operator for Set Iterators. Causes the - // Iterator to reference the in-oder successor of the key currently - // referenced by the Iterator. If the Iterator is currently - // referencing the largest key in the Map, then the resulting Iterator - // will reference the Set's end (the NULL pair). - // - // Note: Incrementing an Iterator which does not reference a valid - // key in the Set is undefined and will almost certainly cause a - // crash. - // - // Return Value: - // - // Returns the Iterator after it has been incremented. - // - Iterator& operator ++ (int) - { - m_node = m_tree->next(m_node); - return *this; - } - - // operator ++ - Postfix increment operator for Map Iterators. Causes - // the Iterator to reference the in-order successor of the key/value - // pair currently referenced by the Iterator. If the Iterator is - // currently referencing the largest key/value pair in the Map, then - // the resulting Iterator will reference the Map's end (the NULL - // pair). - // - // Note: Incrementing an Iterator which does not reference a valid - // key/value pair in the Map is undefined and will almost certainly - // cause a crash. - // - // Return Value: - // - // Returns the Iterator before it has been incremented. - // - Iterator operator ++ () - { - typename Tree::node_t *cur = m_node; - - m_node = m_tree->next(m_node); - return Iterator(m_tree, cur); - } - - // operator - - Subtraction operator for Set Iterators. Causes the - // the Iterator to reference a key that is an in-order predecessor of - // the currently refereced key. - // - // - num (IN): Number indicating the number of preceding keys to - // decrement the iterator. - // - // Return Value: - // - // Returns an Iterator referencing the key that precedes the original - // Iterator by "num" keys. - // - Iterator operator - (SIZE_T num) const - { - SIZE_T count; - typename Tree::node_t *cur = m_node; - - cur = m_tree->prev(m_node); - for (count = 0; count < num; count++) { - cur = m_tree->prev(m_node); - if (cur == NULL) { - return Iterator(m_tree, NULL); - } - } - return Iterator(m_tree, cur); - } - - // operator == - Equality operator for Set Iterators. Set Iterators are - // considered equal if and only if they both refernce the same - // key in the same Set. - // - // - other (IN): The other Set Iterator to compare against. - // - // Return Value: - // - // Returns true if the specified Set Iterator is equal to this Set - // Iterator; otherwise returns false. - // - BOOL operator == (const Iterator &other) const - { - return ((m_tree == other.m_tree) && (m_node == other.m_node)); - } - - private: - // Private constructor. Only the Set class itself may use this - // constructor. It is used for constructing Iterators which reference - // specific nodes in the internal tree's structure. - Iterator (const Tree *tree, typename Tree::node_t *node) - { - m_node = node; - m_tree = tree; - } - - protected: - typename Tree::node_t *m_node; // Pointer to the node referenced by the Set Iterator. - const Tree *m_tree; // Pointer to the tree containing the referenced node. - - // The Set class is a friend of Set Iterators. - friend class Set; - }; - - // Muterator class - This class provides a mutable Iterator (the regular - // Iterators are const Iterators). By dereferencing a Muterator, you get - // a modifiable element. - // - // Caution: Modifing an element in a way that changes its sorting value - // will corrupt the Set container. Muterators should only be used when - // you are absolutely certain you will not be using it to make a - // modification that changes the sort order of the referenced element. - // - class Muterator : public Iterator - { - public: - // operator = - Assignment operator for Set Muterators. Can be used to - // copy a Muterator from an existing Iterator, such that the Muterator - // references the same element referenced by the Iterator. - Muterator& operator = (const Iterator& other) { - *(Iterator*)this = other; - return *this; - } - - // operator * - Dereference operator for Set Muterators. - // - // Note: Dereferencing a Muterator which does not reference a valid - // value in the Set is undefined and will almost certainly cause a - // crash. - // - // Return Value: - // - // Returns a reference to the key in the Map referenced by the - // Muterator. - // - Tk& operator * () - { - return m_node->key; - } - }; - - // begin - Obtains an Iterator referencing the beginning of the Set (i.e. - // the lowest key currently stored in the Set). - // - // Return Value: - // - // Returns an Iterator referencing the first key in the Set. If no keys - // are currenly stored in the Set, returns the "NULL" Iterator. - // - Iterator begin () const - { - return Iterator(&m_tree, m_tree.begin()); - } - - // end - Obtains an Iterator referencing the end of the Set. The end of - // the Set does not reference an actual key. Instead it represents a - // "null" key which signifies the end (i.e. just beyond largest key - // currently stored in the Set). Also known as the "NULL" Iterator. - // - // Return Value: - // - // Returns the "NULL" Iterator, signifying the end of the Set. - // - Iterator end () const - { - return Iterator(&m_tree, NULL); - } - - // erase - Erases a key from the Set. - // - // - it (IN): Iterator referencing the key to be erased from the Set. - // - // Return Value: - // - // None. - // - VOID erase (Iterator& it) - { - m_tree.erase(it.m_node); - } - - // erase - Erases a key from the Set. - // - // - key (IN): The key to be erased from the Set. - // - // Return Value: - // - // None. - // - VOID erase (const Tk &key) - { - m_tree.erase(key); - } - - // find - Finds a key in the Set. - // - // - key (IN): The key to be found. - // - // Return Value: - // - // Returns an Iterator referencing the found key. If the key could not - // be found, then the "NULL" Iterator is returned. - // - Iterator find (const Tk &key) const - { - return Iterator(&m_tree, m_tree.find(key)); - } - - // insert - Inserts a key into the Set. - // - // - key (IN): The key to be inserted. - // - // Return Value: - // - // Returns an Iterator referencing the key after it has been inserted - // into the Set. If an element with an identical key value already exists - // in the Set, then the NULL Iterator is returned. - // - Iterator insert (const Tk &key) - { - return Iterator(&m_tree, m_tree.insert(key)); - } - - // reserve - Sets the reserve size of the Set. The reserve size is the - // number of keys for which space should be pre-allocated to avoid - // frequent heap hits when inserting new keys into the Set. - // - // - count (IN): The number of keys for which to reserve space in advance. - // - // Return Value: - // - // Returns the reserve size previously in use by the Set. - // - size_t reserve (size_t count) - { - return m_tree.reserve(count); - } - -private: - // Private data - Tree m_tree; // The keys are actually stored in a tree. -}; +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - Lightweight STL-like Set Template +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef VLDBUILD +#error \ +"This header should only be included by Visual Leak Detector when building it from source. \ +Applications should never include this header." +#endif + +#include "tree.h" // Provides access to the Tree template class. + +//////////////////////////////////////////////////////////////////////////////// +// +// The Set Template Class +// +// This is a lightweight STL-like set template. It makes use of the Tree class +// template to enable fast insert, find, and erase operations. +// +// Note that while this is a STL-like class, it is not a full STL-compliant +// implementation of the STL set container. It contains just the bare minimum +// functionality required by Visual Leak Detector. Because of its "lightweight" +// nature, this set class has a noticeable performance advantage over some +// other standard STL set implementations. +// +template +class Set { +public: + class Iterator { + public: + // Constructor + Iterator () + { + // Plainly constructed iterators don't reference anything. + m_node = NULL; + m_tree = NULL; + } + + // operator != - Inequality operator for Set Iterators. Two Set + // Iterators are considered equal if and only if they both reference + // the same key in the same Set. + // + // - other (IN): The other Set Iterator to compare against. + // + // Return Value: + // + // Returns true if the specified Set Iterator is not equal to this + // Set Iterator; otherwise, returns false. + // + BOOL operator != (const Iterator &other) const + { + return ((m_tree != other.m_tree) || (m_node != other.m_node)); + } + + // operator * - Dereference operator for Set Iterators. + // + // Note: The reference returned by this function is "const", so the + // value referenced by the Iterator may not be modified through the + // Iterator. This is a departure from STL iterator behavior. + // + // Also, dereferencing an Iterator which does not reference a valid + // value in the Set is undefined and will almost certainly cause a + // crash. + // + // Return Value: + // + // Returns a const reference to the key in the Map referenced by the + // Iterator. + // + const Tk& operator * () const + { + return m_node->key; + } + + // operator ++ - Prefix increment operator for Set Iterators. Causes the + // Iterator to reference the in-oder successor of the key currently + // referenced by the Iterator. If the Iterator is currently + // referencing the largest key in the Map, then the resulting Iterator + // will reference the Set's end (the NULL pair). + // + // Note: Incrementing an Iterator which does not reference a valid + // key in the Set is undefined and will almost certainly cause a + // crash. + // + // Return Value: + // + // Returns the Iterator after it has been incremented. + // + Iterator& operator ++ (int) + { + m_node = m_tree->next(m_node); + return *this; + } + + // operator ++ - Postfix increment operator for Map Iterators. Causes + // the Iterator to reference the in-order successor of the key/value + // pair currently referenced by the Iterator. If the Iterator is + // currently referencing the largest key/value pair in the Map, then + // the resulting Iterator will reference the Map's end (the NULL + // pair). + // + // Note: Incrementing an Iterator which does not reference a valid + // key/value pair in the Map is undefined and will almost certainly + // cause a crash. + // + // Return Value: + // + // Returns the Iterator before it has been incremented. + // + Iterator operator ++ () + { + typename Tree::node_t *cur = m_node; + + m_node = m_tree->next(m_node); + return Iterator(m_tree, cur); + } + + // operator - - Subtraction operator for Set Iterators. Causes the + // the Iterator to reference a key that is an in-order predecessor of + // the currently referenced key. + // + // - num (IN): Number indicating the number of preceding keys to + // decrement the iterator. + // + // Return Value: + // + // Returns an Iterator referencing the key that precedes the original + // Iterator by "num" keys. + // + Iterator operator - (SIZE_T num) const + { + typename Tree::node_t *cur = m_node; + + for (SIZE_T count = 0; count < num; count++) { + cur = m_tree->prev(cur); + if (cur == NULL) { + return Iterator(m_tree, NULL); + } + } + return Iterator(m_tree, cur); + } + + // operator == - Equality operator for Set Iterators. Set Iterators are + // considered equal if and only if they both refernce the same + // key in the same Set. + // + // - other (IN): The other Set Iterator to compare against. + // + // Return Value: + // + // Returns true if the specified Set Iterator is equal to this Set + // Iterator; otherwise returns false. + // + BOOL operator == (const Iterator &other) const + { + return ((m_tree == other.m_tree) && (m_node == other.m_node)); + } + + private: + // Private constructor. Only the Set class itself may use this + // constructor. It is used for constructing Iterators which reference + // specific nodes in the internal tree's structure. + Iterator (const Tree *tree, typename Tree::node_t *node) + { + m_node = node; + m_tree = tree; + } + + protected: + typename Tree::node_t *m_node; // Pointer to the node referenced by the Set Iterator. + const Tree *m_tree; // Pointer to the tree containing the referenced node. + + // The Set class is a friend of Set Iterators. + friend class Set; + }; + + // Muterator class - This class provides a mutable Iterator (the regular + // Iterators are const Iterators). By dereferencing a Muterator, you get + // a modifiable element. + // + // Caution: Modifying an element in a way that changes its sorting value + // will corrupt the Set container. Muterators should only be used when + // you are absolutely certain you will not be using it to make a + // modification that changes the sort order of the referenced element. + // + class Muterator : public Iterator + { + public: + // operator = - Assignment operator for Set Muterators. Can be used to + // copy a Muterator from an existing Iterator, such that the Muterator + // references the same element referenced by the Iterator. + Muterator& operator = (const Iterator& other) { + *(Iterator*)this = other; + return *this; + } + + // operator * - Dereference operator for Set Muterators. + // + // Note: Dereferencing a Muterator which does not reference a valid + // value in the Set is undefined and will almost certainly cause a + // crash. + // + // Return Value: + // + // Returns a reference to the key in the Map referenced by the + // Muterator. + // + Tk& operator * () + { + return m_node->key; + } + }; + + // begin - Obtains an Iterator referencing the beginning of the Set (i.e. + // the lowest key currently stored in the Set). + // + // Return Value: + // + // Returns an Iterator referencing the first key in the Set. If no keys + // are currently stored in the Set, returns the "NULL" Iterator. + // + Iterator begin () const + { + return Iterator(&m_tree, m_tree.begin()); + } + + // end - Obtains an Iterator referencing the end of the Set. The end of + // the Set does not reference an actual key. Instead it represents a + // "null" key which signifies the end (i.e. just beyond largest key + // currently stored in the Set). Also known as the "NULL" Iterator. + // + // Return Value: + // + // Returns the "NULL" Iterator, signifying the end of the Set. + // + Iterator end () const + { + return Iterator(&m_tree, NULL); + } + + // erase - Erases a key from the Set. + // + // - it (IN): Iterator referencing the key to be erased from the Set. + // + // Return Value: + // + // None. + // + VOID erase (Iterator& it) + { + m_tree.erase(it.m_node); + } + + // erase - Erases a key from the Set. + // + // - key (IN): The key to be erased from the Set. + // + // Return Value: + // + // None. + // + VOID erase (const Tk &key) + { + m_tree.erase(key); + } + + // find - Finds a key in the Set. + // + // - key (IN): The key to be found. + // + // Return Value: + // + // Returns an Iterator referencing the found key. If the key could not + // be found, then the "NULL" Iterator is returned. + // + Iterator find (const Tk &key) const + { + return Iterator(&m_tree, m_tree.find(key)); + } + + // insert - Inserts a key into the Set. + // + // - key (IN): The key to be inserted. + // + // Return Value: + // + // Returns an Iterator referencing the key after it has been inserted + // into the Set. If an element with an identical key value already exists + // in the Set, then the NULL Iterator is returned. + // + Iterator insert (const Tk &key) + { + return Iterator(&m_tree, m_tree.insert(key)); + } + + // reserve - Sets the reserve size of the Set. The reserve size is the + // number of keys for which space should be pre-allocated to avoid + // frequent heap hits when inserting new keys into the Set. + // + // - count (IN): The number of keys for which to reserve space in advance. + // + // Return Value: + // + // Returns the reserve size previously in use by the Set. + // + size_t reserve (size_t count) + { + return m_tree.reserve(count); + } + +private: + // Private data + Tree m_tree; // The keys are actually stored in a tree. +}; diff --git a/src/stdafx.cpp b/src/stdafx.cpp new file mode 100644 index 00000000..cea1ca98 --- /dev/null +++ b/src/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// vld.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/src/stdafx.h b/src/stdafx.h new file mode 100644 index 00000000..a968c068 --- /dev/null +++ b/src/stdafx.h @@ -0,0 +1,14 @@ +#pragma once + +#include +#include +#include +#include +#if _WIN32_WINNT < 0x0600 // Windows XP or earlier, no GetProcessIdOfThread() +#include +#endif +#ifndef __out_xcount +#define __out_xcount(x) // Workaround for the specstrings.h bug in the Platform SDK. +#endif +#define DBGHELP_TRANSLATE_TCHAR +#include "dbghelp.h" // Provides portable executable (PE) image access functions. diff --git a/src/tests/Common.props b/src/tests/Common.props new file mode 100644 index 00000000..51d0be5c --- /dev/null +++ b/src/tests/Common.props @@ -0,0 +1,38 @@ + + + + + d + + + + x86 + x64 + + Debug + Debug + Release + Release + Release + Release + v140 + + + <_ProjectFileVersion>10.0.40219.1 + $(SolutionDir)src\bin\$(Platform)\$(Configuration)-v$(PlatformToolsetVersion)\ + $(SolutionDir)src\obj\$(Platform)\$(Configuration)-v$(PlatformToolsetVersion)\$(ProjectName)\ + + + + call ..\copydlls.bat $(Platform)\$(VldConfiguration)-$(VldToolset) $(NumericPlatform) "$(Outdir)" + Copying over Visual Leak Detector Dependencies + + + $(SolutionDir)\src\;$(SolutionDir)\lib\gtest\include;%(AdditionalIncludeDirectories) + _VARIADIC_MAX=10;%(PreprocessorDefinitions) + + + $(ProjectDir)..\..\bin\$(Platform)\$(VldConfiguration)-$(VldToolset);%(AdditionalLibraryDirectories) + + + \ No newline at end of file diff --git a/src/tests/basics/Allocs.cpp b/src/tests/basics/Allocs.cpp new file mode 100644 index 00000000..81b2df80 --- /dev/null +++ b/src/tests/basics/Allocs.cpp @@ -0,0 +1,482 @@ +#include "stdafx.h" +#include "Allocs.h" + +#include // for placement new +#include +#include +#include +#include +#include +#include + +#include + +// Name of the debug C Runtime Library DLL on this system +#ifdef _DEBUG +#if _MSC_VER == 1400 // VS 2005 +#ifdef _DLL +#define CRTDLLNAME _T("msvcr80d.dll") +#else +#define CRTDLLNAME _T("msvcrt.dll") +#endif +#elif _MSC_VER == 1500 // VS 2008 +#ifdef _DLL +#define CRTDLLNAME _T("msvcr90d.dll") +#else +#define CRTDLLNAME _T("msvcrt.dll") +#endif +#elif _MSC_VER == 1600 // VS 2010 +#define CRTDLLNAME _T("msvcr100d.dll") +#elif _MSC_VER == 1700 // VS 2012 +#define CRTDLLNAME _T("msvcr110d.dll") +#elif _MSC_VER == 1800 // VS 2013 +#define CRTDLLNAME _T("msvcr120d.dll") +#elif _MSC_VER == 1900 // VS 2015 +#define CRTDLLNAME _T("ucrtbased.dll") +#else +#error Unsupported compiler +#endif +#else +#if _MSC_VER == 1400 // VS 2005 +#ifdef _DLL +#define CRTDLLNAME _T("msvcr80.dll") +#else +#define CRTDLLNAME _T("msvcrt.dll") +#endif +#elif _MSC_VER == 1500 // VS 2008 +#ifdef _DLL +#define CRTDLLNAME _T("msvcr90.dll") +#else +#define CRTDLLNAME _T("msvcrt.dll") +#endif +#elif _MSC_VER == 1600 // VS 2010 +#define CRTDLLNAME _T("msvcr100.dll") +#elif _MSC_VER == 1700 // VS 2012 +#define CRTDLLNAME _T("msvcr110.dll") +#elif _MSC_VER == 1800 // VS 2013 +#define CRTDLLNAME _T("msvcr120.dll") +#elif _MSC_VER == 1900 // VS 2015 +#define CRTDLLNAME _T("ucrtbase.dll") +#else +#error Unsupported compiler +#endif +#endif + +// Vld shouldn't report this leak because we enable Vld after executing DllMain +class MemoryLeak { +public: + MemoryLeak() { l = malloc(7); memset(l, 0x30 + ((int)7 / 10), 7); } + ~MemoryLeak() { free(l); } +private: + void* l; +}; + +static MemoryLeak ml; + +typedef void* (__cdecl *free_t) (void* mem); +typedef void* (__cdecl *malloc_t) (size_t size); +typedef void (*allocFunc_t) (bool bFree); + +static const int recursion = 3; + +::testing::AssertionResult AssertCompareCallStacks(const char* actual_expr, + const char* expected_expr, + const wchar_t* actual, + const char* expected) +{ + using namespace ::testing::internal; + bool succeded = true; + std::wistringstream actualStream(actual != NULL ? actual : L""); + std::istringstream expectedStream(expected != NULL ? expected : ""); + std::ostringstream resultStream; + std::string expectedLine; + while (std::getline(expectedStream, expectedLine)) + { + std::wstring wactualLine; + if (!std::getline(actualStream, wactualLine)) + { + return ::testing::AssertionFailure() + << resultStream.str() << actual_expr << " contain less lines than " << expected_expr << ""; + } + std::string actualLine(wactualLine.begin(), wactualLine.end()); + std::transform(actualLine.begin(), actualLine.end(), actualLine.begin(), ::tolower); + if (!RE::FullMatch(actualLine, RE(expectedLine))) + { + if (succeded) + { + succeded = false; + resultStream + << actual_expr << " and " << expected_expr << " lines are not match\n"; + } + resultStream + << "line:\n" << actualLine << "\n and \n" << expectedLine << "\n"; + } + } + return succeded ? ::testing::AssertionSuccess() : (::testing::AssertionSuccess() << resultStream.str()); +} + +#ifdef _WIN64 +static const TCHAR* sVld_dll = _T("vld_x64.dll"); +#else +static const TCHAR* sVld_dll = _T("vld_x86.dll"); +#endif + +typedef const wchar_t*(*VldGetCallstack_func)(void* alloc, BOOL showInternalFrames); +static VldGetCallstack_func VldInternalGetAllocationCallstack = NULL; + +void GetVldFunctions() +{ + if (VldInternalGetAllocationCallstack == NULL) + { + HMODULE vld_module = GetModuleHandle(sVld_dll); + assert(vld_module); + typedef int(*VLDAPI_func)(); + if (vld_module != NULL) + { + VldInternalGetAllocationCallstack = (VldGetCallstack_func)GetProcAddress(vld_module, + "VldInternalGetAllocationCallstack"); + assert(VldInternalGetAllocationCallstack); + } + } +} + +__declspec(noinline) void allocMalloc(bool bFree) +{ + GetVldFunctions(); + int* leaked_memory = (int*)malloc(78); + const wchar_t* callstack = VldInternalGetAllocationCallstack(leaked_memory, false); + if (callstack != NULL) + { + const char* expectedCallstack = +#ifdef _DLL +//#ifdef _DEBUG +// "\\s+\\S+.cpp \\(\\d+\\): \\w+\\.dll!malloc\\(\\)\n" +//#else + "\\s+\\w+\\.dll!malloc\\(\\)\n" +//#endif +#else + "\\s+ntdll\\.dll!rtlallocateheap\\(\\)\n" +#ifdef _DEBUG + "\\s+\\S+\\\\heap\\\\malloc\\.cpp \\(\\d+\\): \\w+\\.\\w+!malloc\\(\\) \\+ 0x\\S+ bytes\n" +#else + "\\s+\\S+\\\\heap\\\\malloc_base\\.cpp \\(\\d+\\): \\w+\\.\\w+!_malloc_base\\(\\)\n" +#endif +#endif + "\\s+\\S+\\\\allocs\\.cpp \\(\\d+\\): \\w+\\.\\w+!allocmalloc\\(\\).*\n" + "\\s+\\S+\\\\allocs\\.cpp \\(\\d+\\): \\w+\\.\\w+!allocator<0>::alloc\\(\\) \\+ 0x\\S+ bytes"; + EXPECT_PRED_FORMAT2(AssertCompareCallStacks, callstack, expectedCallstack); + } + int* leaked_memory_dbg = (int*)_malloc_dbg(80, _NORMAL_BLOCK, __FILE__, __LINE__); + callstack = VldInternalGetAllocationCallstack(leaked_memory_dbg, false); + if (callstack != NULL) + { + const char* expectedCallstack = +#ifdef _DLL +#ifdef _DEBUG + "\\s+\\w+\\.dll!_?malloc_dbg\\(\\)\n" +// "\\s+\\S+.cpp \\(\\d+\\): \\w+\\.dll!_?malloc_dbg\\(\\)\n" +#else + "\\s+\\w+\\.dll!malloc\\(\\)\n" +#endif +#else + "\\s+ntdll\\.dll!rtlallocateheap\\(\\)\n" +#ifdef _DEBUG + "\\s+\\S+\\\\heap\\\\debug_heap\\.cpp \\(\\d+\\): \\w+\\.\\w+!_malloc_dbg\\(\\) \\+ 0x\\S+ bytes\n" +#else + "\\s+\\S+\\\\heap\\\\malloc_base\\.cpp \\(\\d+\\): \\w+\\.\\w+!_malloc_base\\(\\)\n" +#endif +#endif + "\\s+\\S+\\\\allocs\\.cpp \\(\\d+\\): \\w+\\.\\w+!allocmalloc\\(\\).*\n" + "\\s+\\S+\\\\allocs\\.cpp \\(\\d+\\): \\w+\\.\\w+!allocator<0>::alloc\\(\\) \\+ 0x\\S+ bytes"; + EXPECT_PRED_FORMAT2(AssertCompareCallStacks, callstack, expectedCallstack); + } + if (bFree) + { + free(leaked_memory); + _free_dbg(leaked_memory_dbg, _NORMAL_BLOCK); + } +} + +void allocNew(bool bFree) +{ + int* leaked_memory = (int*)malloc(78); + int* leaked_memory_dbg = (int*)_malloc_dbg(80, _NORMAL_BLOCK, __FILE__, __LINE__); + if (bFree) + { + free(leaked_memory); + _free_dbg(leaked_memory_dbg, _NORMAL_BLOCK); + } +} + +void allocNewArray(bool bFree) +{ + int* leaked_memory = new int[3]; + int* leaked_memory_dbg = new (_NORMAL_BLOCK, __FILE__, __LINE__) int[4]; + + // placement new operator + int temp[3]; + void* place = temp; + float* placed_mem = new (place) float[3]; // doesn't work. Nothing gets patched by vld + if (bFree) + { + delete[] leaked_memory; + delete[] leaked_memory_dbg; + } +} + +void allocCalloc(bool bFree) +{ + int* leaked_memory = (int*)calloc(47, sizeof(int)); + int* leaked_memory_dbg = (int*)_calloc_dbg(39, sizeof(int), _NORMAL_BLOCK, __FILE__, __LINE__); + if (bFree) + { + free(leaked_memory); + _free_dbg(leaked_memory_dbg, _NORMAL_BLOCK); + } +} + +void allocRealloc(bool bFree) +{ + int* temp = (int*)malloc(17); + int* old_leaked_memory = (int*)realloc(temp, 23); + int* leaked_memory = (int*)_recalloc(old_leaked_memory, 1, 31); + int* old_leaked_memory_dbg = (int*)malloc(9); + int* leaked_memory_dbg = (int*)_realloc_dbg(old_leaked_memory_dbg, 21, _NORMAL_BLOCK, __FILE__, __LINE__); + if (bFree) + { + free(leaked_memory); + _free_dbg(leaked_memory_dbg, _NORMAL_BLOCK); + } +} + +void allocCoTaskMem(bool bFree) +{ + void* leaked = CoTaskMemAlloc(7); + if (bFree) + { + CoTaskMemFree(leaked); + } + void* leaked2 = CoTaskMemAlloc(7); + void* realloced = CoTaskMemRealloc(leaked2, 29); + if (bFree) + { + CoTaskMemFree(realloced); + } +} + +void allocAlignedMalloc(bool bFree) +{ + void* leaked = _aligned_offset_malloc(64, 16, 1); + int* leaked_memory = (int*)_aligned_malloc(64, 16); + int* leaked_memory_dbg = (int*)_aligned_malloc_dbg(32, 16, __FILE__, __LINE__); + if (bFree) + { + _aligned_free(leaked); + _aligned_free(leaked_memory); + _aligned_free_dbg(leaked_memory_dbg); + } +} + +void allocAlignedRealloc(bool bFree) +{ + void* leaked = _aligned_offset_malloc(64, 16, 1); + int* leaked_memory = (int*)_aligned_malloc(64, 16); + int* leaked_memory_dbg = (int*)_aligned_malloc_dbg(32, 16, __FILE__, __LINE__); + leaked = (int*)_aligned_offset_realloc(leaked, 48, 16, 2); + leaked_memory = (int*)_aligned_realloc(leaked_memory, 128, 16); + leaked_memory_dbg = (int*)_aligned_realloc_dbg(leaked_memory_dbg, 48, 16, __FILE__, __LINE__); + leaked = (int*)_aligned_offset_recalloc(leaked, 1, 52, 16, 2); + leaked_memory = (int*)_aligned_recalloc(leaked_memory, 1, 132, 16); + leaked_memory_dbg = (int*)_aligned_recalloc_dbg(leaked_memory_dbg, 1, 64, 16, __FILE__, __LINE__); + if (bFree) + { + _aligned_free(leaked); + _aligned_free(leaked_memory); + _aligned_free_dbg(leaked_memory_dbg); + } +} + +void allocStrdup(bool bFree) +{ + int* leaked_memory = (int*)_strdup("_strdup() leaks!"); + int* leaked_memory_dbg = (int*)_strdup_dbg("_strdup_dbg() leaks!", _NORMAL_BLOCK, __FILE__, __LINE__); + void* leaked_wmemory = (int*)_wcsdup(L"_wcsdup() leaks!"); + void* leaked_wmemory_dbg = (int*)_wcsdup_dbg(L"_wcsdup_dbg() leaks!", _NORMAL_BLOCK, __FILE__, __LINE__); + if (bFree) + { + free(leaked_memory); + _free_dbg(leaked_memory_dbg, _NORMAL_BLOCK); + free(leaked_wmemory); + _free_dbg(leaked_wmemory_dbg, _NORMAL_BLOCK); + } +} + +void allocHeapAlloc(bool bFree) +{ + HANDLE heap = HeapCreate(0x0, 0, 0); + int* leaked_memory = (int*)HeapAlloc(heap, 0x0, 15); + if (bFree) + { + HeapFree(heap, 0, leaked_memory); + HeapDestroy(heap); + } +} + +void allocIMalloc(bool bFree) +{ + IMalloc *imalloc = NULL; + HRESULT hr = CoGetMalloc(1, &imalloc); + assert(SUCCEEDED(hr)); + int* leaked_memory = static_cast(imalloc->Alloc(34)); + if (bFree) + { + imalloc->Free(leaked_memory); + } +} + +void allocGetProcMalloc(bool bFree) +{ + malloc_t pmalloc = NULL; + free_t pfree = NULL; + HMODULE crt = LoadLibrary(CRTDLLNAME); + assert(crt != NULL); + pmalloc = reinterpret_cast(GetProcAddress(crt, "malloc")); + assert(pmalloc != NULL); + int* leaked_memory = static_cast(pmalloc(64)); + if (bFree) + { + pfree = reinterpret_cast(GetProcAddress(crt, "free")); + pfree(leaked_memory); + FreeLibrary(crt); + } +} + +#pragma optimize( "", off ) + +template +struct allocator; + +template<> +struct allocator<0> { + +__declspec(noinline) static void alloc(allocFunc_t func, bool bFree) +{ + func(bFree); +} + +}; + +template +struct allocator { + +__declspec(noinline) static void alloc(allocFunc_t func, bool bFree) +{ + allocator::alloc(func, bFree); +} + +}; + +#pragma optimize( "", on ) + +__declspec(noinline) void alloc(allocFunc_t func, bool bFree) +{ + allocator::alloc(func, bFree); +} + +const int repeats = 1; + +void LeakMemoryMalloc(int repeat, bool bFree) +{ + for (int i = 0; i < repeat; i++) + { + alloc(allocMalloc, bFree); + } +} + +void LeakMemoryNew(int repeat, bool bFree) +{ + for (int i = 0; i < repeat; i++) + { + alloc(allocNew, bFree); + } +} + +void LeakMemoryNewArray(int repeat, bool bFree) +{ + for (int i = 0; i < repeat; i++) + { + alloc(allocNewArray, bFree); + } +} + +void LeakMemoryCalloc(int repeat, bool bFree) +{ + for (int i = 0; i < repeat; i++) + { + alloc(allocCalloc, bFree); + } +} + +void LeakMemoryRealloc(int repeat, bool bFree) +{ + for (int i = 0; i < repeat; i++) + { + alloc(allocRealloc, bFree); + } +} + +void LeakMemoryCoTaskMem(int repeat, bool bFree) +{ + for (int i = 0; i < repeat; i++) + { + alloc(allocCoTaskMem, bFree); + } +} + +void LeakMemoryAlignedMalloc(int repeat, bool bFree) +{ + for (int i = 0; i < repeat; i++) + { + alloc(allocAlignedMalloc, bFree); + } +} + +void LeakMemoryAlignedRealloc(int repeat, bool bFree) +{ + for (int i = 0; i < repeat; i++) + { + alloc(allocAlignedRealloc, bFree); + } +} + +void LeakMemoryStrdup(int repeat, bool bFree) +{ + for (int i = 0; i < repeat; i++) + { + alloc(allocStrdup, bFree); + } +} + +void LeakMemoryHeapAlloc(int repeat, bool bFree) +{ + for (int i = 0; i < repeat; i++) + { + alloc(allocHeapAlloc, bFree); + } +} + +void LeakMemoryIMalloc(int repeat, bool bFree) +{ + for (int i = 0; i < repeat; i++) + { + alloc(allocIMalloc, bFree); + } +} + +void LeakMemoryGetProcMalloc(int repeat, bool bFree) +{ + for (int i = 0; i < repeat; i++) + { + alloc(allocGetProcMalloc, bFree); + } +} diff --git a/src/tests/basics/Allocs.h b/src/tests/basics/Allocs.h new file mode 100644 index 00000000..90991749 --- /dev/null +++ b/src/tests/basics/Allocs.h @@ -0,0 +1,16 @@ +#pragma once + +extern void LeakMemoryMalloc(int repeat, bool bFree = false); +extern void LeakMemoryNew(int repeat, bool bFree = false); +extern void LeakMemoryNewArray(int repeat, bool bFree = false); +extern void LeakMemoryCalloc(int repeat, bool bFree = false); +extern void LeakMemoryRealloc(int repeat, bool bFree = false); +extern void LeakMemoryCoTaskMem(int repeat, bool bFree = false); +extern void LeakMemoryAlignedMalloc(int repeat, bool bFree = false); +extern void LeakMemoryAlignedRealloc(int repeat, bool bFree = false); +extern void LeakMemoryStrdup(int repeat, bool bFree = false); +extern void LeakMemoryHeapAlloc(int repeat, bool bFree = false); +extern void LeakMemoryIMalloc(int repeat, bool bFree = false); +extern void LeakMemoryGetProcMalloc(int repeat, bool bFree = false); + +extern const int repeats; diff --git a/src/tests/basics/basics.cpp b/src/tests/basics/basics.cpp new file mode 100644 index 00000000..ce92100f --- /dev/null +++ b/src/tests/basics/basics.cpp @@ -0,0 +1,152 @@ +// basics.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" +#include "vld.h" +#include "Allocs.h" + +#include + +class TestBasics : public ::testing::TestWithParam +{ + virtual void SetUp() + { + VLDMarkAllLeaksAsReported(); + } + virtual void TearDown() + { + // Check that callstack resolved without unresolved functions (required symbols for all dll's) + //EXPECT_EQ(0, VLDResolveCallstacks()); + } +}; + +TEST_P(TestBasics, Malloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryMalloc(repeats, GetParam()); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + int correctLeaks = GetParam() ? 0 : repeats * 2; + ASSERT_EQ(correctLeaks, leaks); +} + +TEST_P(TestBasics, New) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryNew(repeats, GetParam()); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + int correctLeaks = GetParam() ? 0 : repeats * 2; + ASSERT_EQ(correctLeaks, leaks); +} + +TEST_P(TestBasics, NewArray) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryNewArray(repeats, GetParam()); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + int correctLeaks = GetParam() ? 0 : repeats * 2; + ASSERT_EQ(correctLeaks, leaks); +} + +TEST_P(TestBasics, Calloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryCalloc(repeats, GetParam()); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + int correctLeaks = GetParam() ? 0 : repeats * 2; + ASSERT_EQ(correctLeaks, leaks); +} + +TEST_P(TestBasics, Realloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryRealloc(repeats, GetParam()); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + int correctLeaks = GetParam() ? 0 : repeats * 2; + ASSERT_EQ(correctLeaks, leaks); +} + +TEST_P(TestBasics, CoTaskMem) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryCoTaskMem(repeats, GetParam()); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + int correctLeaks = GetParam() ? 0 : repeats * 2; + ASSERT_EQ(correctLeaks, leaks); +} + +TEST_P(TestBasics, AlignedMalloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryAlignedMalloc(repeats, GetParam()); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + int correctLeaks = GetParam() ? 0 : repeats * 3; + ASSERT_EQ(correctLeaks, leaks); +} + +TEST_P(TestBasics, AlignedRealloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryAlignedRealloc(repeats, GetParam()); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + int correctLeaks = GetParam() ? 0 : repeats * 3; + ASSERT_EQ(correctLeaks, leaks); +} + +TEST_P(TestBasics, Strdup) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryStrdup(repeats, GetParam()); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + int correctLeaks = GetParam() ? 0 : repeats * 4; + ASSERT_EQ(correctLeaks, leaks); +} + +TEST_P(TestBasics, HeapAlloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryHeapAlloc(repeats, GetParam()); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + int correctLeaks = GetParam() ? 0 : repeats * 1; + ASSERT_EQ(correctLeaks, leaks); +} + +TEST_P(TestBasics, IMalloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryIMalloc(repeats, GetParam()); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + int correctLeaks = GetParam() ? 0 : repeats * 1; + ASSERT_EQ(correctLeaks, leaks); +} + +TEST_P(TestBasics, GetProcMalloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryGetProcMalloc(repeats, GetParam()); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + int correctLeaks = GetParam() ? 0 : repeats * 1; + ASSERT_EQ(correctLeaks, leaks); +} + +INSTANTIATE_TEST_CASE_P(FreeVal, + TestBasics, + ::testing::Bool()); + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + int res = RUN_ALL_TESTS(); + VLDMarkAllLeaksAsReported(); + return res; +} diff --git a/src/tests/basics/basics.vcxproj b/src/tests/basics/basics.vcxproj new file mode 100644 index 00000000..888387df --- /dev/null +++ b/src/tests/basics/basics.vcxproj @@ -0,0 +1,345 @@ + + + + + Debug(Release)_StaticCrt + Win32 + + + Debug(Release)_StaticCrt + x64 + + + Debug(Release) + Win32 + + + Debug(Release) + x64 + + + Debug_StaticCrt + Win32 + + + Debug_StaticCrt + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_StaticCrt + Win32 + + + Release_StaticCrt + x64 + + + Release + Win32 + + + Release + x64 + + + + {0943354A-41E0-4215-878A-8D0FE758052C} + Win32Proj + test_basics + test_basics + 8.1 + + + + Application + Unicode + v140_xp + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + true + + + false + true + + + false + true + + + false + true + + + + + + + + + + + false + + + false + + + false + + + false + + + false + + + false + + + false + + + false + + + false + + + false + + + false + + + false + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + ProgramDatabase + + + Console + true + + + + + Use + Level3 + Disabled + STATIC_CRT;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + ProgramDatabase + MultiThreadedDebug + + + Console + true + + + + + Use + Level3 + Disabled + ProgramDatabase + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + + + + + Use + Level3 + Disabled + STATIC_CRT;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + ProgramDatabase + MultiThreadedDebug + + + Console + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + ProgramDatabase + + + Console + true + + + + + Use + Level3 + Disabled + STATIC_CRT;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + ProgramDatabase + MultiThreadedDebug + + + Console + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + ProgramDatabase + + + Console + true + + + + + Use + Level3 + Disabled + STATIC_CRT;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + ProgramDatabase + MultiThreadedDebug + + + Console + true + + + + + Level3 + Use + MaxSpeed + true + true + VLD_FORCE_ENABLE;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + STATIC_CRT;VLD_FORCE_ENABLE;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + + + Console + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + VLD_FORCE_ENABLE;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + STATIC_CRT;VLD_FORCE_ENABLE;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + + + Console + true + true + true + + + + + + + + + + + + + Create + + + + + {c8f6c172-56f2-4e76-b5fa-c3b423b31be7} + + + + + + \ No newline at end of file diff --git a/src/tests/basics/basics.vcxproj.filters b/src/tests/basics/basics.vcxproj.filters new file mode 100644 index 00000000..92eab5f7 --- /dev/null +++ b/src/tests/basics/basics.vcxproj.filters @@ -0,0 +1,42 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/src/tests/basics/basics_disabled.cpp b/src/tests/basics/basics_disabled.cpp new file mode 100644 index 00000000..a5b094be --- /dev/null +++ b/src/tests/basics/basics_disabled.cpp @@ -0,0 +1,129 @@ +// basics.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" +#include "vld.h" +#include "Allocs.h" + +#include + +class TestBasicsDisabled : public ::testing::Test +{ + virtual void SetUp() + { + VLDDisable(); + } + + virtual void TearDown() + { + VLDEnable(); + } +}; + +TEST_F(TestBasicsDisabled, Malloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryMalloc(repeats, false); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + ASSERT_EQ(0, leaks); +} + +TEST_F(TestBasicsDisabled, New) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryNew(repeats, false); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + ASSERT_EQ(0, leaks); +} + +TEST_F(TestBasicsDisabled, NewArray) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryNewArray(repeats, false); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + ASSERT_EQ(0, leaks); +} + +TEST_F(TestBasicsDisabled, Calloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryCalloc(repeats, false); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + ASSERT_EQ(0, leaks); +} + +TEST_F(TestBasicsDisabled, Realloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryRealloc(repeats, false); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + ASSERT_EQ(0, leaks); +} + +TEST_F(TestBasicsDisabled, CoTaskMem) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryCoTaskMem(repeats, false); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + ASSERT_EQ(0, leaks); +} + +TEST_F(TestBasicsDisabled, AlignedMalloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryAlignedMalloc(repeats, false); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + ASSERT_EQ(0, leaks); +} + +TEST_F(TestBasicsDisabled, AlignedRealloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryAlignedRealloc(repeats, false); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + ASSERT_EQ(0, leaks); +} + +TEST_F(TestBasicsDisabled, Strdup) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryStrdup(repeats, false); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + ASSERT_EQ(0, leaks); +} + +TEST_F(TestBasicsDisabled, HeapAlloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryHeapAlloc(repeats, false); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + ASSERT_EQ(0, leaks); +} + +TEST_F(TestBasicsDisabled, GetProcMalloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryGetProcMalloc(repeats, false); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + ASSERT_EQ(0, leaks); +} + +TEST_F(TestBasicsDisabled, IMalloc) +{ + int prev = static_cast(VLDGetLeaksCount()); + LeakMemoryIMalloc(repeats, false); + int total = static_cast(VLDGetLeaksCount()); + int leaks = total - prev; + ASSERT_EQ(0, leaks); +} diff --git a/src/tests/basics/stdafx.cpp b/src/tests/basics/stdafx.cpp new file mode 100644 index 00000000..27f0ee01 --- /dev/null +++ b/src/tests/basics/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// basics.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/src/tests/basics/stdafx.h b/src/tests/basics/stdafx.h new file mode 100644 index 00000000..b005a839 --- /dev/null +++ b/src/tests/basics/stdafx.h @@ -0,0 +1,15 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#include +#include + + + +// TODO: reference additional headers your program requires here diff --git a/src/tests/basics/targetver.h b/src/tests/basics/targetver.h new file mode 100644 index 00000000..87c0086d --- /dev/null +++ b/src/tests/basics/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/console/README.txt b/src/tests/console/README.md similarity index 81% rename from console/README.txt rename to src/tests/console/README.md index 7b75ae74..c898bd82 100644 --- a/console/README.txt +++ b/src/tests/console/README.md @@ -1,36 +1,37 @@ -Visual Leak Detector Example Console Application (Version 1.0.1) - - Example Program Using Visual Leak Detector in a Console Application - - -About The Example Program: --------------------------- -This is an example Visual C++ 6.0 console application project that -implements the Visual Leak Detector. - -The project actually contains two separate programs. A C program and a -C++ program. The C program is in main.c while the C++ program is in -main.cpp. You can select which one you want to build by selecting the -corresponding project configuration as the active configuration. The purpose -behind including both C and C++ versions is to demonstrate Visual Leak -Detector's compatibility with C's malloc and free as well as C++'s new and -delete. - -To build the example project, simply open the project file and start a build. - -After the project is built, running the program will display a simple -"Hello World!" message. But a small amount of memory (containing the -"Hello World!" string) will be leaked. If you run the program under the -Visual C++ debugger, you should see a memory leak report in the debug -output window after the program exits. The report will include detailed -stack traces of the calls that allocated the leaked memory blocks. - -Double-clicking on a source file/line number in the stack trace will take you to -that file and line in the editor. This allows you to quickly see where in the -program the memory was allocated and how it got there. - - -Documentation: --------------- - -See the README.html file for the complete Visual Leak Detector documentation. +Visual Leak Detector Example Console Application +================================================ + +Example Program Using Visual Leak Detector in a Console Application + + +About The Example Program: +-------------------------- +This is an example Visual C++ 6.0 console application project that +implements the Visual Leak Detector. + +The project actually contains two separate programs. A C program and a +C++ program. The C program is in main.c while the C++ program is in +main.cpp. You can select which one you want to build by selecting the +corresponding project configuration as the active configuration. The purpose +behind including both C and C++ versions is to demonstrate Visual Leak +Detector's compatibility with C's malloc and free as well as C++'s new and +delete. + +To build the example project, simply open the project file and start a build. + +After the project is built, running the program will display a simple +"Hello World!" message. But a small amount of memory (containing the +"Hello World!" string) will be leaked. If you run the program under the +Visual C++ debugger, you should see a memory leak report in the debug +output window after the program exits. The report will include detailed +stack traces of the calls that allocated the leaked memory blocks. + +Double-clicking on a source file/line number in the stack trace will take you to +that file and line in the editor. This allows you to quickly see where in the +program the memory was allocated and how it got there. + + +Documentation: +-------------- + +See the [http://vld.codeplex.com/documentation](http://vld.codeplex.com/documentation) for the complete Visual Leak Detector documentation. diff --git a/console/main.c b/src/tests/console/main.c similarity index 95% rename from console/main.c rename to src/tests/console/main.c index 69e54295..ad902764 100644 --- a/console/main.c +++ b/src/tests/console/main.c @@ -1,24 +1,24 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// A simple C example program for testing the Visual Leak Detector. -// -//////////////////////////////////////////////////////////////////////////////// - -#include -#include -#include - -// Include Visual Leak Detector -#include - -int main (int argc, char *argv []) -{ - char *s = (char*)malloc(14); - - strncpy(s, "Hello World!\n", 14); - printf(s); - - //free(s); - - return 0; -} +//////////////////////////////////////////////////////////////////////////////// +// +// A simple C example program for testing the Visual Leak Detector. +// +//////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include + +// Include Visual Leak Detector +#include + +int main (int argc, char *argv []) +{ + char *s = (char*)malloc(14); + + strncpy(s, "Hello World!\n", 14); + printf(s); + + //free(s); + + return 0; +} diff --git a/console/main.cpp b/src/tests/console/main.cpp similarity index 95% rename from console/main.cpp rename to src/tests/console/main.cpp index ac08c1e2..479898dc 100644 --- a/console/main.cpp +++ b/src/tests/console/main.cpp @@ -1,24 +1,24 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// A simple C++ example program for testing the Visual Leak Detector. -// -//////////////////////////////////////////////////////////////////////////////// - -#include -#include - -// Include Visual Leak Detector -#include - -using namespace std; - -int main (int argc, char *argv []) -{ - string *s = new string("Hello World!\n"); - - cout << *s; - - //delete s; - - return 0; -} +//////////////////////////////////////////////////////////////////////////////// +// +// A simple C++ example program for testing the Visual Leak Detector. +// +//////////////////////////////////////////////////////////////////////////////// + +#include +#include + +// Include Visual Leak Detector +#include + +using namespace std; + +int main (int argc, char *argv []) +{ + string *s = new string("Hello World!\n"); + + cout << *s; + + //delete s; + + return 0; +} diff --git a/console/vldconsole.sln b/src/tests/console/vldconsole.sln old mode 100755 new mode 100644 similarity index 70% rename from console/vldconsole.sln rename to src/tests/console/vldconsole.sln index 8ec9344a..d0146f23 --- a/console/vldconsole.sln +++ b/src/tests/console/vldconsole.sln @@ -1,20 +1,26 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vldconsole", "vldconsole.vcproj", "{23F66B23-5893-429F-BA3E-5F61EB3ED2A2}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - C Debug|Win32 = C Debug|Win32 - CPP Debug|Win32 = CPP Debug|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.C Debug|Win32.ActiveCfg = C Debug|Win32 - {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.C Debug|Win32.Build.0 = C Debug|Win32 - {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.CPP Debug|Win32.ActiveCfg = CPP Debug|Win32 - {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.CPP Debug|Win32.Build.0 = CPP Debug|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vldconsole", "vldconsole.vcproj", "{23F66B23-5893-429F-BA3E-5F61EB3ED2A2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + C Debug|Win32 = C Debug|Win32 + C Debug|x64 = C Debug|x64 + CPP Debug|Win32 = CPP Debug|Win32 + CPP Debug|x64 = CPP Debug|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.C Debug|Win32.ActiveCfg = C Debug|Win32 + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.C Debug|Win32.Build.0 = C Debug|Win32 + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.C Debug|x64.ActiveCfg = C Debug|x64 + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.C Debug|x64.Build.0 = C Debug|x64 + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.CPP Debug|Win32.ActiveCfg = CPP Debug|Win32 + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.CPP Debug|Win32.Build.0 = CPP Debug|Win32 + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.CPP Debug|x64.ActiveCfg = CPP Debug|x64 + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.CPP Debug|x64.Build.0 = CPP Debug|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/src/tests/console/vldconsole.vcxproj b/src/tests/console/vldconsole.vcxproj new file mode 100644 index 00000000..9ff05621 --- /dev/null +++ b/src/tests/console/vldconsole.vcxproj @@ -0,0 +1,290 @@ + + + + + C Debug + Win32 + + + C Debug + x64 + + + CPP Debug + Win32 + + + CPP Debug + x64 + + + + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2} + 8.1 + + + + Application + false + NotSet + v140_xp + + + Application + false + NotSet + v140_xp + + + Application + false + NotSet + v140_xp + + + Application + false + NotSet + v140_xp + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + ..\$(PlatformName)\Debug\ + ..\$(PlatformName)\Debug\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + true + true + ..\$(PlatformName)\Debug\ + ..\$(PlatformName)\Debug\ + $(PlatformName)\$(Configuration)\ + $(PlatformName)\$(Configuration)\ + true + true + AllRules.ruleset + AllRules.ruleset + + + + + AllRules.ruleset + AllRules.ruleset + + + + + + + + .\CPP Debug/vldconsole.tlb + + + + + Disabled + ..\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebug + .\CPP Debug/vldconsole.pch + .\CPP Debug/ + .\CPP Debug/ + .\CPP Debug/ + Level3 + true + EditAndContinue + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)\vldconsole.exe + true + ..\Win32\Debug;%(AdditionalLibraryDirectories) + true + .\CPP Debug/vldconsole.pdb + Console + false + + + MachineX86 + + + true + .\CPP Debug/vldconsole.bsc + + + + + .\CPP Debug/vldconsole.tlb + + + + + Disabled + ..\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebug + .\CPP Debug/vldconsole.pch + .\CPP Debug/ + .\CPP Debug/ + .\CPP Debug/ + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)\vldconsole.exe + true + ..\x64\Debug;%(AdditionalLibraryDirectories) + true + .\CPP Debug/vldconsole.pdb + Console + false + + + + + true + .\CPP Debug/vldconsole.bsc + + + + + .\C Debug/vldconsole.tlb + + + + + Disabled + ..\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebug + .\C Debug/vldconsole.pch + .\C Debug/ + .\C Debug/ + .\C Debug/ + Level3 + true + EditAndContinue + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)\vldconsole.exe + true + ..\Win32\Debug;%(AdditionalLibraryDirectories) + true + .\C Debug/vldconsole.pdb + Console + false + + + MachineX86 + + + true + .\C Debug/vldconsole.bsc + + + + + .\C Debug/vldconsole.tlb + + + + + Disabled + ..\;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebug + .\C Debug/vldconsole.pch + .\C Debug/ + .\C Debug/ + .\C Debug/ + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + + + $(OutDir)\vldconsole.exe + true + ..\x64\Debug;%(AdditionalLibraryDirectories) + true + .\C Debug/vldconsole.pdb + Console + false + + + + + true + .\C Debug/vldconsole.bsc + + + + + %(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + true + true + %(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + + + true + true + %(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) + %(PreprocessorDefinitions) + %(PreprocessorDefinitions) + + + + + + \ No newline at end of file diff --git a/src/tests/console/vldconsole.vcxproj.filters b/src/tests/console/vldconsole.vcxproj.filters new file mode 100644 index 00000000..a0d4a226 --- /dev/null +++ b/src/tests/console/vldconsole.vcxproj.filters @@ -0,0 +1,25 @@ + + + + + {cfef00a9-107f-44fb-b4e4-95d6324cce2c} + cpp;c;cxx;rc;def;r;odl;idl;hpj;bat + + + {6dc46008-9659-4679-95d2-cc106ba6ca2f} + h;hpp;hxx;hm;inl + + + {6568e0a7-4b52-49eb-a41c-1e38930cab1f} + ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/src/tests/console/vldconsole_vs10.sln b/src/tests/console/vldconsole_vs10.sln new file mode 100644 index 00000000..a28acb42 --- /dev/null +++ b/src/tests/console/vldconsole_vs10.sln @@ -0,0 +1,26 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vldconsole", "vldconsole.vcxproj", "{23F66B23-5893-429F-BA3E-5F61EB3ED2A2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + C Debug|Win32 = C Debug|Win32 + C Debug|x64 = C Debug|x64 + CPP Debug|Win32 = CPP Debug|Win32 + CPP Debug|x64 = CPP Debug|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.C Debug|Win32.ActiveCfg = C Debug|Win32 + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.C Debug|Win32.Build.0 = C Debug|Win32 + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.C Debug|x64.ActiveCfg = C Debug|x64 + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.C Debug|x64.Build.0 = C Debug|x64 + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.CPP Debug|Win32.ActiveCfg = CPP Debug|Win32 + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.CPP Debug|Win32.Build.0 = CPP Debug|Win32 + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.CPP Debug|x64.ActiveCfg = CPP Debug|x64 + {23F66B23-5893-429F-BA3E-5F61EB3ED2A2}.CPP Debug|x64.Build.0 = CPP Debug|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/src/tests/copydlls.bat b/src/tests/copydlls.bat new file mode 100644 index 00000000..c84b0f27 --- /dev/null +++ b/src/tests/copydlls.bat @@ -0,0 +1,6 @@ +REM Copying over Visual Leak Detector Dependencies +xcopy "%~dp0\..\..\vld.ini" "%~dp0\..\bin\" /y /d +copy "%~dp0\..\bin\%1\vld_%2.dll" "%~3\vld_%2.dll" /y +copy "%~dp0\..\bin\%1\vld_%2.pdb" "%~3\vld_%2.pdb" /y +copy "%~dp0\..\..\setup\dbghelp\%2\dbghelp.dll" "%~3\dbghelp.dll" /y +copy "%~dp0\..\..\setup\dbghelp\%2\Microsoft.DTfW.DHL.manifest" "%~3\Microsoft.DTfW.DHL.manifest" /y \ No newline at end of file diff --git a/src/tests/corruption/Tests.cpp b/src/tests/corruption/Tests.cpp new file mode 100644 index 00000000..d43a4d81 --- /dev/null +++ b/src/tests/corruption/Tests.cpp @@ -0,0 +1,52 @@ +#include "StdAfx.h" +#include "Tests.h" +#include "stdlib.h" +#define WIN32_LEAN_AND_MEAN +#include + +void TestAllocationMismatch_malloc_delete() +{ + int* pint = (int*)malloc(56); + // use the wrong function to deallocate + delete pint; +} + +void TestAllocationMismatch_malloc_deleteVec() +{ + int* pint = (int*)malloc(56); + // use the wrong function to deallocate + delete [] pint; +} + +void TestAllocationMismatch_new_free() +{ + int* pint = new int(45); // scalar new + // use the wrong function to deallocate + free(pint); +} + +void TestAllocationMismatch_newVec_free() +{ + int* pint = new int[3]; // vector new + // use the wrong function to deallocate + free(pint); +} + +void TestHeapMismatch() +{ + HANDLE test_heap = HeapCreate(HEAP_GENERATE_EXCEPTIONS | HEAP_CREATE_ENABLE_EXECUTE, + 0, // initialize reserved size; + 0); // maximum size can grow + HeapSetInformation(test_heap, HeapEnableTerminationOnCorruption, NULL, 0); + HANDLE default_heap = GetProcessHeap(); + HeapSetInformation(default_heap, HeapEnableTerminationOnCorruption, NULL, 0); + // Have to initialize vld with something, so it doesn't dismiss + // the default heap as having no memory allocs in it. + void* aptr = HeapAlloc(default_heap, 0, 42); + // Allocate it in the new heap + void* vptr = HeapAlloc(test_heap, 0, 56); + // Free this using the WRONG heap! + HeapFree( default_heap, 0, vptr); + + HeapDestroy(test_heap); +} diff --git a/src/tests/corruption/Tests.h b/src/tests/corruption/Tests.h new file mode 100644 index 00000000..13a70c7f --- /dev/null +++ b/src/tests/corruption/Tests.h @@ -0,0 +1,8 @@ +#pragma once + +void TestAllocationMismatch_malloc_delete(); +void TestAllocationMismatch_malloc_deleteVec(); +void TestAllocationMismatch_new_free(); +void TestAllocationMismatch_newVec_free(); + +void TestHeapMismatch(); diff --git a/src/tests/corruption/corruption.cpp b/src/tests/corruption/corruption.cpp new file mode 100644 index 00000000..d882ad70 --- /dev/null +++ b/src/tests/corruption/corruption.cpp @@ -0,0 +1,71 @@ +// corruption.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" +#include "Tests.h" +// This hooks vld into this app +#include "vld.h" + +#include + +enum CorruptionType +{ + eAllocMismatch, + eHeapMismatch, + eCount +}; + +int __cdecl ReportHook(int /*reportHook*/, wchar_t *message, int* /*returnValue*/) +{ + fwprintf(stderr, L"%s", message); + return 1; +} + +bool IgnoreExitCode(int exit_status) +{ + UNREFERENCED_PARAMETER(exit_status); + return true; +} + +void TestCorruption( CorruptionType check ) +{ + // Mark all previous memory leaks as reported which are not part of the current test. + VLDMarkAllLeaksAsReported(); + + if (check == eAllocMismatch) + { + TestAllocationMismatch_malloc_delete(); + TestAllocationMismatch_malloc_deleteVec(); + TestAllocationMismatch_new_free(); + TestAllocationMismatch_newVec_free(); + } + else if (check == eHeapMismatch) + { + TestHeapMismatch(); + } +} + +TEST(Corruption, AllocMismatch) +{ + TestCorruption(eAllocMismatch); +} + +TEST(CorruptionDeathTest, HeapMismatch) +{ + EXPECT_EXIT({ + VLDSetReportHook(VLD_RPTHOOK_INSTALL, ReportHook); + TestCorruption(eHeapMismatch); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, ReportHook); + }, IgnoreExitCode, "CRITICAL ERROR!: VLD reports that memory was allocated in one heap and freed in another."); +} + +int main(int argc, char **argv) { + UINT vld_options = VLDGetOptions(); + vld_options |= VLD_OPT_VALIDATE_HEAPFREE; + VLDSetOptions(vld_options, 15, 25); + + ::testing::InitGoogleTest(&argc, argv); + int res = RUN_ALL_TESTS(); + VLDMarkAllLeaksAsReported(); + return res; +} diff --git a/src/tests/corruption/corruption.vcxproj b/src/tests/corruption/corruption.vcxproj new file mode 100644 index 00000000..3f810734 --- /dev/null +++ b/src/tests/corruption/corruption.vcxproj @@ -0,0 +1,318 @@ + + + + + Debug(Release)_StaticCrt + Win32 + + + Debug(Release)_StaticCrt + x64 + + + Debug(Release) + Win32 + + + Debug(Release) + x64 + + + Debug_StaticCrt + Win32 + + + Debug_StaticCrt + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_StaticCrt + Win32 + + + Release_StaticCrt + x64 + + + Release + Win32 + + + Release + x64 + + + + {87911ED6-84BC-4526-9654-A4FF4E0EDF52} + Win32Proj + corruption + 8.1 + corruption + + + + Application + Unicode + v140_xp + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + true + + + false + true + + + false + true + + + false + true + + + + + + + + + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + + + false + + + false + + + false + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Console + true + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Console + true + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Console + true + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Console + true + + + + + Level3 + true + true + VLD_FORCE_ENABLE;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + true + true + + + + + Level3 + true + true + VLD_FORCE_ENABLE;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + + + Console + true + true + true + + + + + Level3 + true + true + VLD_FORCE_ENABLE;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + true + true + + + + + Level3 + true + true + VLD_FORCE_ENABLE;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + + + Console + true + true + true + + + + + + + + + + + + + + + {c8f6c172-56f2-4e76-b5fa-c3b423b31be7} + + + + + + \ No newline at end of file diff --git a/src/tests/corruption/corruption.vcxproj.filters b/src/tests/corruption/corruption.vcxproj.filters new file mode 100644 index 00000000..9194b4d8 --- /dev/null +++ b/src/tests/corruption/corruption.vcxproj.filters @@ -0,0 +1,39 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/src/tests/corruption/stdafx.cpp b/src/tests/corruption/stdafx.cpp new file mode 100644 index 00000000..397f6346 --- /dev/null +++ b/src/tests/corruption/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// corruption.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/src/tests/corruption/stdafx.h b/src/tests/corruption/stdafx.h new file mode 100644 index 00000000..661cb268 --- /dev/null +++ b/src/tests/corruption/stdafx.h @@ -0,0 +1,16 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#include +#include +#include + + + +// TODO: reference additional headers your program requires here diff --git a/src/tests/corruption/targetver.h b/src/tests/corruption/targetver.h new file mode 100644 index 00000000..87c0086d --- /dev/null +++ b/src/tests/corruption/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/src/tests/dynamic_app/LoadTests.cpp b/src/tests/dynamic_app/LoadTests.cpp new file mode 100644 index 00000000..c6dca567 --- /dev/null +++ b/src/tests/dynamic_app/LoadTests.cpp @@ -0,0 +1,114 @@ +#include "stdafx.h" +#include "LoadTests.h" +// Hook in Visual Leak Detector to this application +#include "../../vld.h" +#include + +#ifdef _WIN64 + static const TCHAR* sVld_dll = _T("vld_x64.dll"); +#else + static const TCHAR* sVld_dll = _T("vld_x86.dll"); +#endif + +void CallVLDExportedMethod(const CHAR* function) +{ + HMODULE vld_module = GetModuleHandle(sVld_dll); + assert(vld_module); + typedef int (*VLDAPI_func)(); + if (vld_module != NULL) + { + VLDAPI_func func = (VLDAPI_func)GetProcAddress(vld_module, function); + assert(func); + if (func) + { + int result = func(); + UNREFERENCED_PARAMETER(result); + } + } +} + +void CallDynamicMethods(HMODULE module, const CHAR* function) +{ + typedef void (__cdecl *DYNAPI_FNC)(); + if (module != NULL) + { + DYNAPI_FNC func = (DYNAPI_FNC)GetProcAddress(module, function ); + //GetFormattedMessage(GetLastError()); + assert(func); + if (func) + { + func(); + } + } +} + +HMODULE LoadDynamicTests() +{ + HMODULE hdyn = LoadLibrary(_T("dynamic.dll")); + if (hdyn) + { + VLDEnableModule(hdyn); + } + return hdyn; +} + +void RunLoaderTests(HMODULE hdyn, bool resolve) +{ + if (!hdyn) + return; + VLDEnableModule(hdyn); + + // Should leak 18 memory allocations in total + // These requires ansi, not Unicode strings + CallDynamicMethods(hdyn, "SimpleLeak_Malloc"); // leaks 6 + CallDynamicMethods(hdyn, "SimpleLeak_New"); // leaks 6 + CallDynamicMethods(hdyn, "SimpleLeak_New_Array"); // leaks 6 + + if (resolve) + { + CallVLDExportedMethod("VLDResolveCallstacks"); // This requires ansi, not Unicode strings + } +} + +void CallLibraryMethods( HMODULE hmfcLib, LPCSTR function ) +{ + HMODULE dynamic_module = hmfcLib; + assert(dynamic_module); + typedef void (__cdecl *DYNAPI_FNC)(); + if (dynamic_module != NULL) + { + DYNAPI_FNC func = (DYNAPI_FNC)GetProcAddress(dynamic_module, function ); + //GetFormattedMessage(GetLastError()); + assert(func); + if (func) + { + func(); + } + } +} + +HMODULE LoadMFCTests() +{ + HMODULE hmfcLib = LoadLibrary(_T("test_mfc.dll")); + if (hmfcLib) + { + VLDEnableModule(hmfcLib); + } + return hmfcLib; +} + +void RunMFCLoaderTests(HMODULE hmfcLib, bool resolve) +{ + if (!hmfcLib) + return; + // Should leak 11 memory allocations in total + // This requires ansi, not Unicode strings + CallLibraryMethods(hmfcLib, "MFC_LeakSimple"); // Leaks 4 x 2 = 8 + CallLibraryMethods(hmfcLib, "MFC_LeakArray"); // leaks 3 + + if (resolve) + { + CallVLDExportedMethod("VLDResolveCallstacks"); // This requires ansi, not Unicode strings + } +} + diff --git a/src/tests/dynamic_app/LoadTests.h b/src/tests/dynamic_app/LoadTests.h new file mode 100644 index 00000000..61956f23 --- /dev/null +++ b/src/tests/dynamic_app/LoadTests.h @@ -0,0 +1,6 @@ +#pragma once + +HMODULE LoadDynamicTests(); +void RunLoaderTests(HMODULE hdyn, bool resolve); +HMODULE LoadMFCTests(); +void RunMFCLoaderTests(HMODULE hmfcLib, bool resolve); diff --git a/src/tests/dynamic_app/ThreadTest.cpp b/src/tests/dynamic_app/ThreadTest.cpp new file mode 100644 index 00000000..3f65cceb --- /dev/null +++ b/src/tests/dynamic_app/ThreadTest.cpp @@ -0,0 +1,124 @@ +#include "stdafx.h" +#include "ThreadTests.h" +#include "LoadTests.h" +#include + +struct ThreadData +{ + bool resolve; + bool mfc; +}; + +void RunPSApiLoaderTests() +{ + HMODULE hModule = ::LoadLibrary(_T("psapi.dll")); + + if (NULL != hModule) + { + ::FreeLibrary(hModule); + } +} + +void Call_LoaderLocks(const ThreadData& threadData) +{ + RunPSApiLoaderTests(); // will not crash + HMODULE hlib; + if (threadData.mfc) + { + hlib = LoadMFCTests(); + RunMFCLoaderTests(hlib, threadData.resolve); // Leaks 11 allocs + } + else + { + hlib = LoadDynamicTests(); + RunLoaderTests(hlib, threadData.resolve); // Leaks 18 allocs + } +#ifndef STATIC_CRT + FreeLibrary(hlib); +#else + UNREFERENCED_PARAMETER(hlib); +#endif + + HMODULE this_app = NULL; + WCHAR path_name[MAX_PATH] = {0}; + // This also acquires the loader lock + GetModuleFileName(this_app, path_name, MAX_PATH); +} + +void Call_Three(const ThreadData& threadData) +{ + Call_LoaderLocks(threadData); +} + +void Call_Two(const ThreadData& threadData) +{ + Call_Three(threadData); +} + +void Call_One(const ThreadData& threadData) +{ + Call_Two(threadData); +} + +unsigned __stdcall Dynamic_Thread_Procedure(LPVOID foo) +{ + ThreadData& threadData = *(ThreadData*)(foo); + Call_One(threadData); + return 0; +} + +void RunLoaderLockTests(bool resolve, bool mfc) +{ + HANDLE threads[NUMTHREADS] = {0}; + unsigned thread_id = NULL; + ThreadData threadData; + threadData.resolve = resolve; + threadData.mfc = mfc; + + for (UINT i = 0; i < NUMTHREADS; ++i) + { + threads[i] = (HANDLE)_beginthreadex(NULL, // security attribute + 0, // stack size + Dynamic_Thread_Procedure, // start function + &threadData, // thread parameters + 0, // creation flags + &thread_id); // thread id + } + + BOOL wait_for_all = TRUE; + DWORD result = WaitForMultipleObjects(NUMTHREADS, threads, wait_for_all, INFINITE); + switch (result) + { + case WAIT_OBJECT_0: + _tprintf(_T("All threads finished correctly.\n")); + break; + case WAIT_ABANDONED_0: + _tprintf(_T("Abandoned mutex.\n")); + break; + case WAIT_TIMEOUT: + _tprintf(_T("All threads timed out\n")); + break; + case WAIT_FAILED: + { + _tprintf(_T("Function call to Wait failed with unknown error\n")); + TCHAR lpMsgBuf[MAX_PATH] = {0}; + FormatMessage( + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + lpMsgBuf, + MAX_PATH, + NULL ); + + _tprintf(_T("%s"), lpMsgBuf); + } + + break; + default: + _tprintf(_T("Some other return value\n")); + break; + } + +} diff --git a/src/tests/dynamic_app/ThreadTests.h b/src/tests/dynamic_app/ThreadTests.h new file mode 100644 index 00000000..5f3a5472 --- /dev/null +++ b/src/tests/dynamic_app/ThreadTests.h @@ -0,0 +1,5 @@ +#pragma once + +static const int NUMTHREADS = 64; + +void RunLoaderLockTests(bool, bool); diff --git a/src/tests/dynamic_app/dynamic_app.cpp b/src/tests/dynamic_app/dynamic_app.cpp new file mode 100644 index 00000000..887dbdb7 --- /dev/null +++ b/src/tests/dynamic_app/dynamic_app.cpp @@ -0,0 +1,145 @@ +// dynamic_app.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" +#include "LoadTests.h" +#include "ThreadTests.h" +#include "vld.h" + +#include + +// Leaks 6 memory allocations +void LeakDuplicateLeaks() +{ + // For testing aggregation + for (int i = 0; i < 3; ++i) + { + int* tmp = new int(0x63); + tmp; + } + for (int i = 0; i < 3; ++i) + { + int* tmp = new int(0x63); + tmp; + } + // Should report 6 memory leaks +} + +class DynamicLoader : public ::testing::TestWithParam { + virtual void SetUp() + { + VLDMarkAllLeaksAsReported(); + } + virtual void TearDown() + { + // Check that callstack resolved without unresolved functions (required symbols for all dll's) + //EXPECT_EQ(0, VLDResolveCallstacks()); + } +}; + + +TEST_P(DynamicLoader, LoaderTests) +{ + HMODULE hdynLib = LoadDynamicTests(); + ASSERT_NE(0u, reinterpret_cast(hdynLib)); +#ifdef STATIC_CRT // Toolset <= v100 use own heap + VLDMarkAllLeaksAsReported(); + RunLoaderTests(hdynLib, GetParam()); // leaks 18 + int leaks = static_cast(VLDGetLeaksCount()); + FreeLibrary(hdynLib); +#else + //VLDMarkAllLeaksAsReported(); + RunLoaderTests(hdynLib, GetParam()); // leaks 18 + FreeLibrary(hdynLib); + int leaks = static_cast(VLDGetLeaksCount()); +#endif + if (18 != leaks) VLDReportLeaks(); + ASSERT_EQ(18, leaks); +} + +TEST_P(DynamicLoader, MultithreadLoadingTests) +{ + // Creates NUMTHREADS threads that each leaks 18 allocations + DWORD start = GetTickCount(); + RunLoaderLockTests(GetParam(), false); + DWORD duration = GetTickCount() - start; + _tprintf(_T("Thread Test took: %u ms\n"), duration); + start = GetTickCount(); + int leaks = (int)VLDGetLeaksCount(); + duration = GetTickCount() - start; + _tprintf(_T("VLDGetLeaksCount took: %u ms\n"), duration); + int correctLeaks = NUMTHREADS * 18; + if (correctLeaks != leaks) VLDReportLeaks(); +#ifdef STATIC_CRT // One leak from dll static allocation + HMODULE hlib = LoadDynamicTests(); + for (int i = 0; i < NUMTHREADS + 1; i++) + FreeLibrary(hlib); +#endif + ASSERT_EQ(correctLeaks, leaks); +} + +TEST_P(DynamicLoader, MfcLoaderTests) +{ + HMODULE hmfcLib = LoadMFCTests(); + ASSERT_NE(0u, reinterpret_cast(hmfcLib)); +#ifdef STATIC_CRT // Toolset <= v100 use own heap + VLDMarkAllLeaksAsReported(); + RunMFCLoaderTests(hmfcLib, GetParam()); // leaks 11 + int leaks = (int)VLDGetLeaksCount(); + FreeLibrary(hmfcLib); +#else + //VLDMarkAllLeaksAsReported(); + RunMFCLoaderTests(hmfcLib, GetParam()); // leaks 11 + FreeLibrary(hmfcLib); + int leaks = (int)VLDGetLeaksCount(); +#endif + if (11 != leaks) VLDReportLeaks(); + ASSERT_EQ(11, leaks); +} + +TEST_P(DynamicLoader, MfcMultithreadLoadingTests) +{ + // Creates NUMTHREADS threads that each leaks 11 allocations + DWORD start = GetTickCount(); + RunLoaderLockTests(GetParam(), true); + DWORD duration = GetTickCount() - start; + _tprintf(_T("Thread Test took: %u ms\n"), duration); + start = GetTickCount(); + int leaks = (int)VLDGetLeaksCount(); + duration = GetTickCount() - start; + _tprintf(_T("VLDGetLeaksCount took: %u ms\n"), duration); + if (NUMTHREADS * 11 != leaks) VLDReportLeaks(); +#ifdef STATIC_CRT // One leak from dll static allocation + HMODULE hlib = LoadMFCTests(); + for (int i = 0; i < NUMTHREADS + 1; i++) + FreeLibrary(hlib); +#endif + ASSERT_EQ(NUMTHREADS * 11, leaks); +} + +INSTANTIATE_TEST_CASE_P(ResolveVal, + DynamicLoader, + ::testing::Bool()); + +TEST(Dynamic, DuplicateLeaks) +{ + VLDMarkAllLeaksAsReported(); + LeakDuplicateLeaks(); // leaks 6 + int leaks = (int)VLDGetLeaksCount(); + ASSERT_EQ(6, leaks); +} + +int __cdecl ReportHook(int /*reportHook*/, wchar_t *message, int* /*returnValue*/) +{ + OutputDebugString(message); + return 0; +} + +int main(int argc, char **argv) { + VLDSetReportHook(VLD_RPTHOOK_INSTALL, ReportHook); + ::testing::InitGoogleTest(&argc, argv); + int res = RUN_ALL_TESTS(); + VLDMarkAllLeaksAsReported(); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, ReportHook); + return res; +} diff --git a/src/tests/dynamic_app/dynamic_app.vcxproj b/src/tests/dynamic_app/dynamic_app.vcxproj new file mode 100644 index 00000000..427c0ac5 --- /dev/null +++ b/src/tests/dynamic_app/dynamic_app.vcxproj @@ -0,0 +1,328 @@ + + + + + Debug(Release)_StaticCrt + Win32 + + + Debug(Release)_StaticCrt + x64 + + + Debug(Release) + Win32 + + + Debug(Release) + x64 + + + Debug_StaticCrt + Win32 + + + Debug_StaticCrt + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_StaticCrt + Win32 + + + Release_StaticCrt + x64 + + + Release + Win32 + + + Release + x64 + + + + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA} + Win32Proj + dynamic_app + 8.1 + dynamic_app + + + + Application + Unicode + v140_xp + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + true + + + false + true + + + false + true + + + false + true + + + + + + + + + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + + + false + + + false + + + false + + + + Level4 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + + + + + Level4 + Disabled + STATIC_CRT;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Console + true + + + + + Level4 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + + + + + Level4 + Disabled + STATIC_CRT;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Console + true + + + + + Level4 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + + + + + Level4 + Disabled + STATIC_CRT;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Console + true + + + + + Level4 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + + + + + Level4 + Disabled + STATIC_CRT;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Console + true + + + + + Level4 + MaxSpeed + true + true + VLD_FORCE_ENABLE;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + true + true + + + + + Level4 + MaxSpeed + true + true + STATIC_CRT;VLD_FORCE_ENABLE;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + + + Console + true + true + true + + + + + Level4 + true + VLD_FORCE_ENABLE;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + true + true + + + + + Level4 + true + STATIC_CRT;VLD_FORCE_ENABLE;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreaded + + + Console + true + true + true + + + + + + + + + + + + + + + + + {c8f6c172-56f2-4e76-b5fa-c3b423b31be7} + + + {3aea2aaf-3e9b-466f-b361-560b95ad88b4} + false + false + false + false + false + + + + + + \ No newline at end of file diff --git a/src/tests/dynamic_app/dynamic_app.vcxproj.filters b/src/tests/dynamic_app/dynamic_app.vcxproj.filters new file mode 100644 index 00000000..72fba51d --- /dev/null +++ b/src/tests/dynamic_app/dynamic_app.vcxproj.filters @@ -0,0 +1,45 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/src/tests/dynamic_app/stdafx.cpp b/src/tests/dynamic_app/stdafx.cpp new file mode 100644 index 00000000..a53726f5 --- /dev/null +++ b/src/tests/dynamic_app/stdafx.cpp @@ -0,0 +1,26 @@ +// stdafx.cpp : source file that includes just the standard includes +// dynamic_app.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// Formats a message string using the specified message and variable +// list of arguments. +void GetFormattedMessage(DWORD last_error) +{ + // Retrieve the system error message for the last-error code + WCHAR lpMsgBuf[MAX_PATH] = {0}; + + FormatMessage( + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + last_error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + lpMsgBuf, + MAX_PATH, + NULL ); + + // Display the error message. + wprintf(_T("%s\n"), lpMsgBuf); +} diff --git a/src/tests/dynamic_app/stdafx.h b/src/tests/dynamic_app/stdafx.h new file mode 100644 index 00000000..33cd6e46 --- /dev/null +++ b/src/tests/dynamic_app/stdafx.h @@ -0,0 +1,15 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#include +#include +#include + + +void GetFormattedMessage(DWORD last_error); diff --git a/src/tests/dynamic_app/targetver.h b/src/tests/dynamic_app/targetver.h new file mode 100644 index 00000000..87c0086d --- /dev/null +++ b/src/tests/dynamic_app/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/src/tests/dynamic_dll/dllmain.cpp b/src/tests/dynamic_dll/dllmain.cpp new file mode 100644 index 00000000..5ebd4cc1 --- /dev/null +++ b/src/tests/dynamic_dll/dllmain.cpp @@ -0,0 +1,18 @@ +// dllmain.cpp : Defines the entry point for the DLL application. +#include "stdafx.h" + +BOOL APIENTRY DllMain( HMODULE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; +} diff --git a/src/tests/dynamic_dll/dynamic.cpp b/src/tests/dynamic_dll/dynamic.cpp new file mode 100644 index 00000000..1aa234be --- /dev/null +++ b/src/tests/dynamic_dll/dynamic.cpp @@ -0,0 +1,36 @@ +// dynamic.cpp : Defines the exported functions for the DLL application. +// + +#include "stdafx.h" +#include "dynamic.h" +#include "../basics/Allocs.h" + +extern "C" { +// This is an example of an exported variable +DYNAMIC_API int ndynamic = 0; + +// This is an example of an exported function. + +void SimpleLeak_Malloc(void) +{ + LeakMemoryMalloc(3); // leaks 6 +} + +void SimpleLeak_New(void) +{ + LeakMemoryNew(3); // leaks 6 +} + +void SimpleLeak_New_Array(void) +{ + LeakMemoryNewArray(3); // leaks 6 +} + +// This is the constructor of a class that has been exported. +// see dynamic.h for the class definition +Cdynamic::Cdynamic() +{ + return; +} + +} \ No newline at end of file diff --git a/src/tests/dynamic_dll/dynamic.h b/src/tests/dynamic_dll/dynamic.h new file mode 100644 index 00000000..5de4861b --- /dev/null +++ b/src/tests/dynamic_dll/dynamic.h @@ -0,0 +1,31 @@ +// The following ifdef block is the standard way of creating macros which make exporting +// from a DLL simpler. All files within this DLL are compiled with the DYNAMIC_EXPORTS +// symbol defined on the command line. This symbol should not be defined on any project +// that uses this DLL. This way any other project whose source files include this file see +// DYNAMIC_API functions as being imported from a DLL, whereas this DLL sees symbols +// defined with this macro as being exported. +#ifdef DYNAMIC_EXPORTS +#define DYNAMIC_API __declspec(dllexport) +#else +#define DYNAMIC_API __declspec(dllimport) +#endif + +extern "C" { +// This class is exported from the dynamic.dll +class DYNAMIC_API Cdynamic { +public: + Cdynamic(void); + // TODO: add your methods here. +}; + +extern DYNAMIC_API int ndynamic; + +// Leaks 2*3=6 allocations +DYNAMIC_API void SimpleLeak_Malloc(void); +// Leaks 2*3=6 allocations +DYNAMIC_API void SimpleLeak_New(void); +// Leaks 2*3=6 allocations +DYNAMIC_API void SimpleLeak_New_Array(void); + +} + diff --git a/src/tests/dynamic_dll/dynamic.vcxproj b/src/tests/dynamic_dll/dynamic.vcxproj new file mode 100644 index 00000000..295bf9e4 --- /dev/null +++ b/src/tests/dynamic_dll/dynamic.vcxproj @@ -0,0 +1,338 @@ + + + + + Debug(Release)_StaticCrt + Win32 + + + Debug(Release)_StaticCrt + x64 + + + Debug(Release) + Win32 + + + Debug(Release) + x64 + + + Debug_StaticCrt + Win32 + + + Debug_StaticCrt + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_StaticCrt + Win32 + + + Release_StaticCrt + x64 + + + Release + Win32 + + + Release + x64 + + + + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4} + Win32Proj + dynamic + dynamic + 8.1 + + + + DynamicLibrary + Unicode + v140_xp + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + true + + + false + true + + + false + true + + + false + true + + + + + + + + + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + + + false + + + false + + + false + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;DYNAMIC_EXPORTS;%(PreprocessorDefinitions) + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;DYNAMIC_EXPORTS;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;DYNAMIC_EXPORTS;%(PreprocessorDefinitions) + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;DYNAMIC_EXPORTS;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;DYNAMIC_EXPORTS;%(PreprocessorDefinitions) + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;DYNAMIC_EXPORTS;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;DYNAMIC_EXPORTS;%(PreprocessorDefinitions) + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;DYNAMIC_EXPORTS;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Windows + true + + + + + Level3 + Use + MaxSpeed + true + true + VLD_FORCE_ENABLE;WIN32;NDEBUG;_WINDOWS;_USRDLL;DYNAMIC_EXPORTS;%(PreprocessorDefinitions) + + + Windows + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + VLD_FORCE_ENABLE;WIN32;NDEBUG;_WINDOWS;_USRDLL;DYNAMIC_EXPORTS;%(PreprocessorDefinitions) + MultiThreaded + + + Windows + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + VLD_FORCE_ENABLE;WIN32;NDEBUG;_WINDOWS;_USRDLL;DYNAMIC_EXPORTS;%(PreprocessorDefinitions) + + + Windows + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + VLD_FORCE_ENABLE;WIN32;NDEBUG;_WINDOWS;_USRDLL;DYNAMIC_EXPORTS;%(PreprocessorDefinitions) + MultiThreaded + + + Windows + true + true + true + + + + + + + + + + + + + + Create + + + + + {c8f6c172-56f2-4e76-b5fa-c3b423b31be7} + + + + + + \ No newline at end of file diff --git a/src/tests/dynamic_dll/dynamic.vcxproj.filters b/src/tests/dynamic_dll/dynamic.vcxproj.filters new file mode 100644 index 00000000..52e065e3 --- /dev/null +++ b/src/tests/dynamic_dll/dynamic.vcxproj.filters @@ -0,0 +1,45 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/src/tests/dynamic_dll/stdafx.cpp b/src/tests/dynamic_dll/stdafx.cpp new file mode 100644 index 00000000..98804d63 --- /dev/null +++ b/src/tests/dynamic_dll/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// dynamic.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/src/tests/dynamic_dll/stdafx.h b/src/tests/dynamic_dll/stdafx.h new file mode 100644 index 00000000..f3a07375 --- /dev/null +++ b/src/tests/dynamic_dll/stdafx.h @@ -0,0 +1,16 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +// Windows Header Files: +#include + + + +// TODO: reference additional headers your program requires here diff --git a/src/tests/dynamic_dll/targetver.h b/src/tests/dynamic_dll/targetver.h new file mode 100644 index 00000000..87c0086d --- /dev/null +++ b/src/tests/dynamic_dll/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/src/tests/mfc/StdAfx.cpp b/src/tests/mfc/StdAfx.cpp new file mode 100644 index 00000000..52f38aae --- /dev/null +++ b/src/tests/mfc/StdAfx.cpp @@ -0,0 +1,8 @@ +// source file that includes just the standard includes +// vldmfc.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + + + diff --git a/src/tests/mfc/StdAfx.h b/src/tests/mfc/StdAfx.h new file mode 100644 index 00000000..921e06b8 --- /dev/null +++ b/src/tests/mfc/StdAfx.h @@ -0,0 +1,30 @@ +// include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#if !defined(AFX_STDAFX_H__9884638E_0AE1_42F8_BFF0_840BD090BD42__INCLUDED_) +#define AFX_STDAFX_H__9884638E_0AE1_42F8_BFF0_840BD090BD42__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers + +// Include Visual Leak Detector +#include + +#include // MFC core and standard components +#include // MFC extensions +#include // MFC support for Internet Explorer 4 Common Controls +#ifndef _AFX_NO_AFXCMN_SUPPORT +#include // MFC support for Windows Common Controls +#endif // _AFX_NO_AFXCMN_SUPPORT + + + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_STDAFX_H__9884638E_0AE1_42F8_BFF0_840BD090BD42__INCLUDED_) diff --git a/src/tests/mfc/res/vldmfc.ico b/src/tests/mfc/res/vldmfc.ico new file mode 100644 index 00000000..d56fbcdf Binary files /dev/null and b/src/tests/mfc/res/vldmfc.ico differ diff --git a/src/tests/mfc/res/vldmfc.rc2 b/src/tests/mfc/res/vldmfc.rc2 new file mode 100644 index 00000000..99777388 --- /dev/null +++ b/src/tests/mfc/res/vldmfc.rc2 @@ -0,0 +1,13 @@ +// +// VLDMFC.RC2 - resources Microsoft Visual C++ does not edit directly +// + +#ifdef APSTUDIO_INVOKED + #error this file is not editable by Microsoft Visual C++ +#endif //APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// Add manually edited resources here... + +///////////////////////////////////////////////////////////////////////////// diff --git a/mfc/resource.h b/src/tests/mfc/resource.h similarity index 96% rename from mfc/resource.h rename to src/tests/mfc/resource.h index 23db3670..016c8c5d 100644 --- a/mfc/resource.h +++ b/src/tests/mfc/resource.h @@ -1,21 +1,21 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by vldmfc.rc -// -#define IDM_ABOUTBOX 0x0010 -#define IDD_ABOUTBOX 100 -#define IDS_ABOUTBOX 101 -#define IDD_VLDMFC_DIALOG 102 -#define IDR_MAINFRAME 128 -#define IDC_CHECK_LEAK 1002 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 129 -#define _APS_NEXT_COMMAND_VALUE 32771 -#define _APS_NEXT_CONTROL_VALUE 1003 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by vldmfc.rc +// +#define IDM_ABOUTBOX 0x0010 +#define IDD_ABOUTBOX 100 +#define IDS_ABOUTBOX 101 +#define IDD_VLDMFC_DIALOG 102 +#define IDR_MAINFRAME 128 +#define IDC_CHECK_LEAK 1002 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 129 +#define _APS_NEXT_COMMAND_VALUE 32771 +#define _APS_NEXT_CONTROL_VALUE 1003 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/mfc/vldmfc.cpp b/src/tests/mfc/vldmfc.cpp similarity index 81% rename from mfc/vldmfc.cpp rename to src/tests/mfc/vldmfc.cpp index 8d015beb..9b3f8e58 100644 --- a/mfc/vldmfc.cpp +++ b/src/tests/mfc/vldmfc.cpp @@ -1,71 +1,68 @@ -#include "stdafx.h" -#include "vldmfc.h" -#include "vldmfcdlg.h" - -// Include Visual Leak Detector -#include - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CMFCExampleApp - -BEGIN_MESSAGE_MAP(CMFCExampleApp, CWinApp) - //{{AFX_MSG_MAP(CMFCExampleApp) - // NOTE - the ClassWizard will add and remove mapping macros here. - // DO NOT EDIT what you see in these blocks of generated code! - //}}AFX_MSG - ON_COMMAND(ID_HELP, CWinApp::OnHelp) -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CMFCExampleApp construction - -CMFCExampleApp::CMFCExampleApp() -{ - // TODO: add construction code here, - // Place all significant initialization in InitInstance -} - -///////////////////////////////////////////////////////////////////////////// -// The one and only CMFCExampleApp object - -CMFCExampleApp theApp; - -///////////////////////////////////////////////////////////////////////////// -// CMFCExampleApp initialization - -BOOL CMFCExampleApp::InitInstance() -{ - // Standard initialization - // If you are not using these features and wish to reduce the size - // of your final executable, you should remove from the following - // the specific initialization routines you do not need. - - CMFCExampleDlg dlg; - m_pMainWnd = &dlg; - int nResponse = dlg.DoModal(); - if (nResponse == IDOK) - { - // TODO: Place code here to handle when the dialog is - // dismissed with OK - CString *s = new CString("Hello World!\n"); - - if (!dlg.m_bLeak) { - delete s; - } - } - else if (nResponse == IDCANCEL) - { - // TODO: Place code here to handle when the dialog is - // dismissed with Cancel - } - - // Since the dialog has been closed, return FALSE so that we exit the - // application, rather than start the application's message pump. - return FALSE; -} +#include "stdafx.h" +#include "vldmfc.h" +#include "vldmfcdlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CMFCExampleApp + +BEGIN_MESSAGE_MAP(CMFCExampleApp, CWinApp) + //{{AFX_MSG_MAP(CMFCExampleApp) + // NOTE - the ClassWizard will add and remove mapping macros here. + // DO NOT EDIT what you see in these blocks of generated code! + //}}AFX_MSG + ON_COMMAND(ID_HELP, CWinApp::OnHelp) +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CMFCExampleApp construction + +CMFCExampleApp::CMFCExampleApp() +{ + // TODO: add construction code here, + // Place all significant initialization in InitInstance +} + +///////////////////////////////////////////////////////////////////////////// +// The one and only CMFCExampleApp object + +CMFCExampleApp theApp; + +///////////////////////////////////////////////////////////////////////////// +// CMFCExampleApp initialization + +BOOL CMFCExampleApp::InitInstance() +{ + // Standard initialization + // If you are not using these features and wish to reduce the size + // of your final executable, you should remove from the following + // the specific initialization routines you do not need. + + CMFCExampleDlg dlg; + m_pMainWnd = &dlg; + INT_PTR nResponse = dlg.DoModal(); + if (nResponse == IDOK) + { + // TODO: Place code here to handle when the dialog is + // dismissed with OK + CString *s = new CString("Hello World!\n"); + + if (!dlg.m_bLeak) { + delete s; + } + } + else if (nResponse == IDCANCEL) + { + // TODO: Place code here to handle when the dialog is + // dismissed with Cancel + } + + // Since the dialog has been closed, return FALSE so that we exit the + // application, rather than start the application's message pump. + return FALSE; +} diff --git a/src/tests/mfc/vldmfc.h b/src/tests/mfc/vldmfc.h new file mode 100644 index 00000000..9edfd2aa --- /dev/null +++ b/src/tests/mfc/vldmfc.h @@ -0,0 +1,46 @@ +#if !defined(AFX_VLDMFC_H__9B6C7B98_B322_4E4F_9969_823D500649E9__INCLUDED_) +#define AFX_VLDMFC_H__9B6C7B98_B322_4E4F_9969_823D500649E9__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#ifndef __AFXWIN_H__ + #error include 'stdafx.h' before including this file for PCH +#endif + +#include "resource.h" // main symbols + +///////////////////////////////////////////////////////////////////////////// +// CMFCExampleApp: +// See vldmfc.cpp for the implementation of this class +// + +class CMFCExampleApp : public CWinApp +{ +public: + CMFCExampleApp(); + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CMFCExampleApp) + public: + virtual BOOL InitInstance(); + //}}AFX_VIRTUAL + +// Implementation + + //{{AFX_MSG(CMFCExampleApp) + // NOTE - the ClassWizard will add and remove member functions here. + // DO NOT EDIT what you see in these blocks of generated code ! + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + + +///////////////////////////////////////////////////////////////////////////// + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_VLDMFC_H__9B6C7B98_B322_4E4F_9969_823D500649E9__INCLUDED_) diff --git a/mfc/vldmfc.rc b/src/tests/mfc/vldmfc.rc similarity index 96% rename from mfc/vldmfc.rc rename to src/tests/mfc/vldmfc.rc index 1ba4fb2e..53223679 100644 --- a/mfc/vldmfc.rc +++ b/src/tests/mfc/vldmfc.rc @@ -1,210 +1,210 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "#define _AFX_NO_SPLITTER_RESOURCES\r\n" - "#define _AFX_NO_OLE_RESOURCES\r\n" - "#define _AFX_NO_TRACKER_RESOURCES\r\n" - "#define _AFX_NO_PROPERTY_RESOURCES\r\n" - "\r\n" - "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" - "#ifdef _WIN32\r\n" - "LANGUAGE 9, 1\r\n" - "#pragma code_page(1252)\r\n" - "#endif //_WIN32\r\n" - "#include ""res\\vldmfc.rc2"" // non-Microsoft Visual C++ edited resources\r\n" - "#include ""afxres.rc"" // Standard components\r\n" - "#endif\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDR_MAINFRAME ICON DISCARDABLE "res\\vldmfc.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_ABOUTBOX DIALOG DISCARDABLE 0, 0, 235, 55 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "About Visual Leak Detector MFC Example" -FONT 8, "MS Sans Serif" -BEGIN - ICON IDR_MAINFRAME,IDC_STATIC,11,17,20,20 - LTEXT "Visual Leak Detector MFC Example Version 1.0.1", - IDC_STATIC,40,14,156,8,SS_NOPREFIX - LTEXT "Copyright (C) 2005 Dan Moulding",IDC_STATIC,40,31,119,8 - DEFPUSHBUTTON "OK",IDOK,178,34,50,14,WS_GROUP -END - -IDD_VLDMFC_DIALOG DIALOGEX 0, 0, 181, 43 -STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU -EXSTYLE WS_EX_APPWINDOW -CAPTION "Visual Leak Detector MFC Example" -FONT 8, "MS Sans Serif", 0, 0, 0x1 -BEGIN - DEFPUSHBUTTON "OK",IDOK,112,7,50,14 - PUSHBUTTON "Cancel",IDCANCEL,112,23,50,14 - CONTROL "Leak Some Memory",IDC_CHECK_LEAK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,19,16,79,10 -END - - -#ifndef _MAC -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,1,1 - PRODUCTVERSION 1,0,1,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "Comments", "This software is copyright (c) 2005 Dan Moulding and is distributed under the terms of the GNU Lesser Public License\0" - VALUE "CompanyName", "\0" - VALUE "FileDescription", "Visual Leak Detector MFC Example\0" - VALUE "FileVersion", "1, 0, 1, 1\0" - VALUE "InternalName", "vldmfc\0" - VALUE "LegalCopyright", "Copyright (C) 2005\0" - VALUE "LegalTrademarks", "\0" - VALUE "OriginalFilename", "vldmfc.exe\0" - VALUE "PrivateBuild", "\0" - VALUE "ProductName", "Visual Leak Detector MFC Example\0" - VALUE "ProductVersion", "1, 0, 1, 1\0" - VALUE "SpecialBuild", "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // !_MAC - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_ABOUTBOX, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 228 - TOPMARGIN, 7 - BOTTOMMARGIN, 48 - END - - IDD_VLDMFC_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 174 - TOPMARGIN, 7 - BOTTOMMARGIN, 36 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - IDS_ABOUTBOX "&About Visual Leak Detector MFC Example..." -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// -#define _AFX_NO_SPLITTER_RESOURCES -#define _AFX_NO_OLE_RESOURCES -#define _AFX_NO_TRACKER_RESOURCES -#define _AFX_NO_PROPERTY_RESOURCES - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE 9, 1 -#pragma code_page(1252) -#endif //_WIN32 -#include "res\vldmfc.rc2" // non-Microsoft Visual C++ edited resources -#include "afxres.rc" // Standard components -#endif - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - +//Microsoft Developer Studio generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "#define _AFX_NO_SPLITTER_RESOURCES\r\n" + "#define _AFX_NO_OLE_RESOURCES\r\n" + "#define _AFX_NO_TRACKER_RESOURCES\r\n" + "#define _AFX_NO_PROPERTY_RESOURCES\r\n" + "\r\n" + "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" + "#ifdef _WIN32\r\n" + "LANGUAGE 9, 1\r\n" + "#pragma code_page(1252)\r\n" + "#endif //_WIN32\r\n" + "#include ""res\\vldmfc.rc2"" // non-Microsoft Visual C++ edited resources\r\n" + "#include ""afxres.rc"" // Standard components\r\n" + "#endif\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDR_MAINFRAME ICON DISCARDABLE "res\\vldmfc.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_ABOUTBOX DIALOG DISCARDABLE 0, 0, 235, 55 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "About Visual Leak Detector MFC Example" +FONT 8, "MS Sans Serif" +BEGIN + ICON IDR_MAINFRAME,IDC_STATIC,11,17,20,20 + LTEXT "Visual Leak Detector MFC Example Version 1.0.1", + IDC_STATIC,40,14,156,8,SS_NOPREFIX + LTEXT "Copyright (C) 2005 Dan Moulding",IDC_STATIC,40,31,119,8 + DEFPUSHBUTTON "OK",IDOK,178,34,50,14,WS_GROUP +END + +IDD_VLDMFC_DIALOG DIALOGEX 0, 0, 181, 43 +STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU +EXSTYLE WS_EX_APPWINDOW +CAPTION "Visual Leak Detector MFC Example" +FONT 8, "MS Sans Serif", 0, 0, 0x1 +BEGIN + DEFPUSHBUTTON "OK",IDOK,112,7,50,14 + PUSHBUTTON "Cancel",IDCANCEL,112,23,50,14 + CONTROL "Leak Some Memory",IDC_CHECK_LEAK,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,19,16,79,10 +END + + +#ifndef _MAC +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,1,1 + PRODUCTVERSION 1,0,1,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "Comments", "This software is copyright (c) 2005 Dan Moulding and is distributed under the terms of the GNU Lesser Public License\0" + VALUE "CompanyName", "\0" + VALUE "FileDescription", "Visual Leak Detector MFC Example\0" + VALUE "FileVersion", "1, 0, 1, 1\0" + VALUE "InternalName", "vldmfc\0" + VALUE "LegalCopyright", "Copyright (C) 2005\0" + VALUE "LegalTrademarks", "\0" + VALUE "OriginalFilename", "vldmfc.exe\0" + VALUE "PrivateBuild", "\0" + VALUE "ProductName", "Visual Leak Detector MFC Example\0" + VALUE "ProductVersion", "1, 0, 1, 1\0" + VALUE "SpecialBuild", "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +#endif // !_MAC + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO DISCARDABLE +BEGIN + IDD_ABOUTBOX, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 228 + TOPMARGIN, 7 + BOTTOMMARGIN, 48 + END + + IDD_VLDMFC_DIALOG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 174 + TOPMARGIN, 7 + BOTTOMMARGIN, 36 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE DISCARDABLE +BEGIN + IDS_ABOUTBOX "&About Visual Leak Detector MFC Example..." +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#define _AFX_NO_SPLITTER_RESOURCES +#define _AFX_NO_OLE_RESOURCES +#define _AFX_NO_TRACKER_RESOURCES +#define _AFX_NO_PROPERTY_RESOURCES + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE 9, 1 +#pragma code_page(1252) +#endif //_WIN32 +#include "res\vldmfc.rc2" // non-Microsoft Visual C++ edited resources +#include "afxres.rc" // Standard components +#endif + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/mfc/vldmfc.sln b/src/tests/mfc/vldmfc.sln old mode 100755 new mode 100644 similarity index 71% rename from mfc/vldmfc.sln rename to src/tests/mfc/vldmfc.sln index f3db54d3..1ddbd0da --- a/mfc/vldmfc.sln +++ b/src/tests/mfc/vldmfc.sln @@ -1,20 +1,26 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vldmfc", "vldmfc.vcproj", "{A231973E-072A-428E-982E-5363ADD1CDE2}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.ActiveCfg = Debug|Win32 - {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.Build.0 = Debug|Win32 - {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|Win32.ActiveCfg = Release|Win32 - {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|Win32.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vldmfc", "vldmfc.vcproj", "{A231973E-072A-428E-982E-5363ADD1CDE2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.ActiveCfg = Debug|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.Build.0 = Debug|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|x64.ActiveCfg = Debug|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|x64.Build.0 = Debug|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|Win32.ActiveCfg = Release|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|Win32.Build.0 = Release|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|x64.ActiveCfg = Release|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/src/tests/mfc/vldmfc.vcxproj b/src/tests/mfc/vldmfc.vcxproj new file mode 100644 index 00000000..9d2ddad3 --- /dev/null +++ b/src/tests/mfc/vldmfc.vcxproj @@ -0,0 +1,293 @@ + + + + + Debug_StaticCrt + Win32 + + + Debug_StaticCrt + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_StaticCrt + Win32 + + + Release_StaticCrt + x64 + + + Release + Win32 + + + Release + x64 + + + + {A231973E-072A-428E-982E-5363ADD1CDE2} + MFCProj + 8.1 + vldmfc + vldmfc + + + + Application + Unicode + v140_xp + + + Dynamic + + + Static + + + Dynamic + + + Static + + + Dynamic + + + Static + + + Dynamic + + + Static + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + false + false + false + false + true + true + true + true + NativeRecommendedRules.ruleset + NativeRecommendedRules.ruleset + NativeRecommendedRules.ruleset + NativeRecommendedRules.ruleset + + + + + + + + + NativeRecommendedRules.ruleset + NativeRecommendedRules.ruleset + NativeRecommendedRules.ruleset + NativeRecommendedRules.ruleset + + + + + + + + + + + + MaxSpeed + OnlyExplicitInline + VLD_FORCE_ENABLE;WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + MultiThreadedDLL + true + Level3 + Use + + + NDEBUG;%(PreprocessorDefinitions) + + + Windows + false + true + + + + + MaxSpeed + OnlyExplicitInline + VLD_FORCE_ENABLE;WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + MultiThreaded + true + Level3 + Use + + + NDEBUG;%(PreprocessorDefinitions) + + + Windows + false + true + + + + + MaxSpeed + OnlyExplicitInline + VLD_FORCE_ENABLE;WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + MultiThreadedDLL + true + Level3 + Use + + + NDEBUG;%(PreprocessorDefinitions) + + + Windows + false + true + + + + + MaxSpeed + OnlyExplicitInline + VLD_FORCE_ENABLE;WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + MultiThreaded + true + Level3 + Use + + + NDEBUG;%(PreprocessorDefinitions) + + + Windows + false + true + + + + + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + Use + Level3 + + + _DEBUG;%(PreprocessorDefinitions) + + + true + Windows + false + + + + + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebug + Use + Level3 + + + _DEBUG;%(PreprocessorDefinitions) + + + true + Windows + false + + + + + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + Use + Level3 + + + _DEBUG;%(PreprocessorDefinitions) + + + true + Windows + false + + + + + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebug + Use + Level3 + + + _DEBUG;%(PreprocessorDefinitions) + + + true + Windows + false + + + + + Create + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/tests/mfc/vldmfc.vcxproj.filters b/src/tests/mfc/vldmfc.vcxproj.filters new file mode 100644 index 00000000..2aeb011e --- /dev/null +++ b/src/tests/mfc/vldmfc.vcxproj.filters @@ -0,0 +1,55 @@ + + + + + {34f1f2ae-d745-4d33-82c0-d281bca28a63} + cpp;c;cxx;rc;def;r;odl;idl;hpj;bat + + + {716aeea6-27e4-47d9-9d4e-4a9d35551f9c} + h;hpp;hxx;hm;inl + + + {468ee78d-f409-4040-95ff-fd2928868302} + ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + Source Files + + + Source Files + + + Source Files + + + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Resource Files + + + Resource Files + + + \ No newline at end of file diff --git a/src/tests/mfc/vldmfc_vs10.sln b/src/tests/mfc/vldmfc_vs10.sln new file mode 100644 index 00000000..c5000baf --- /dev/null +++ b/src/tests/mfc/vldmfc_vs10.sln @@ -0,0 +1,26 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vldmfc", "vldmfc.vcxproj", "{A231973E-072A-428E-982E-5363ADD1CDE2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.ActiveCfg = Debug|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.Build.0 = Debug|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|x64.ActiveCfg = Debug|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|x64.Build.0 = Debug|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|Win32.ActiveCfg = Release|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|Win32.Build.0 = Release|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|x64.ActiveCfg = Release|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/mfc/vldmfcdlg.cpp b/src/tests/mfc/vldmfcdlg.cpp similarity index 92% rename from mfc/vldmfcdlg.cpp rename to src/tests/mfc/vldmfcdlg.cpp index 30677908..d2cfd03f 100644 --- a/mfc/vldmfcdlg.cpp +++ b/src/tests/mfc/vldmfcdlg.cpp @@ -1,169 +1,169 @@ -#include "stdafx.h" -#include "vldmfc.h" -#include "vldmfcdlg.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CAboutDlg dialog used for App About - -class CAboutDlg : public CDialog -{ -public: - CAboutDlg(); - - // Dialog Data - //{{AFX_DATA(CAboutDlg) - enum { IDD = IDD_ABOUTBOX }; - //}}AFX_DATA - - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CAboutDlg) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - - // Implementation -protected: - //{{AFX_MSG(CAboutDlg) - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) -{ - //{{AFX_DATA_INIT(CAboutDlg) - //}}AFX_DATA_INIT -} - -void CAboutDlg::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CAboutDlg) - //}}AFX_DATA_MAP -} - -BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) - //{{AFX_MSG_MAP(CAboutDlg) - // No message handlers - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CMFCExampleDlg dialog - -CMFCExampleDlg::CMFCExampleDlg(CWnd* pParent /*=NULL*/) - : CDialog(CMFCExampleDlg::IDD, pParent) -{ - //{{AFX_DATA_INIT(CMFCExampleDlg) - m_bLeak = FALSE; - //}}AFX_DATA_INIT - // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 - m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); -} - -void CMFCExampleDlg::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CMFCExampleDlg) - DDX_Check(pDX, IDC_CHECK_LEAK, m_bLeak); - //}}AFX_DATA_MAP -} - -BEGIN_MESSAGE_MAP(CMFCExampleDlg, CDialog) - //{{AFX_MSG_MAP(CMFCExampleDlg) - ON_WM_SYSCOMMAND() - ON_WM_PAINT() - ON_WM_QUERYDRAGICON() - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CMFCExampleDlg message handlers - -BOOL CMFCExampleDlg::OnInitDialog() -{ - CDialog::OnInitDialog(); - - // Add "About..." menu item to system menu. - - // IDM_ABOUTBOX must be in the system command range. - ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); - ASSERT(IDM_ABOUTBOX < 0xF000); - - CMenu* pSysMenu = GetSystemMenu(FALSE); - if (pSysMenu != NULL) - { - CString strAboutMenu; - strAboutMenu.LoadString(IDS_ABOUTBOX); - if (!strAboutMenu.IsEmpty()) - { - pSysMenu->AppendMenu(MF_SEPARATOR); - pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); - } - } - - // Set the icon for this dialog. The framework does this automatically - // when the application's main window is not a dialog - SetIcon(m_hIcon, TRUE); // Set big icon - SetIcon(m_hIcon, FALSE); // Set small icon - - // TODO: Add extra initialization here - m_bLeak = TRUE; - UpdateData(FALSE); - - return TRUE; // return TRUE unless you set the focus to a control -} - -void CMFCExampleDlg::OnSysCommand(UINT nID, LPARAM lParam) -{ - if ((nID & 0xFFF0) == IDM_ABOUTBOX) - { - CAboutDlg dlgAbout; - dlgAbout.DoModal(); - } - else - { - CDialog::OnSysCommand(nID, lParam); - } -} - -// If you add a minimize button to your dialog, you will need the code below -// to draw the icon. For MFC applications using the document/view model, -// this is automatically done for you by the framework. - -void CMFCExampleDlg::OnPaint() -{ - if (IsIconic()) - { - CPaintDC dc(this); // device context for painting - - SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); - - // Center icon in client rectangle - int cxIcon = GetSystemMetrics(SM_CXICON); - int cyIcon = GetSystemMetrics(SM_CYICON); - CRect rect; - GetClientRect(&rect); - int x = (rect.Width() - cxIcon + 1) / 2; - int y = (rect.Height() - cyIcon + 1) / 2; - - // Draw the icon - dc.DrawIcon(x, y, m_hIcon); - } - else - { - CDialog::OnPaint(); - } -} - -// The system calls this to obtain the cursor to display while the user drags -// the minimized window. -HCURSOR CMFCExampleDlg::OnQueryDragIcon() -{ - return (HCURSOR) m_hIcon; -} +#include "stdafx.h" +#include "vldmfc.h" +#include "vldmfcdlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CAboutDlg dialog used for App About + +class CAboutDlg : public CDialog +{ +public: + CAboutDlg(); + + // Dialog Data + //{{AFX_DATA(CAboutDlg) + enum { IDD = IDD_ABOUTBOX }; + //}}AFX_DATA + + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CAboutDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + + // Implementation +protected: + //{{AFX_MSG(CAboutDlg) + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) +{ + //{{AFX_DATA_INIT(CAboutDlg) + //}}AFX_DATA_INIT +} + +void CAboutDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CAboutDlg) + //}}AFX_DATA_MAP +} + +BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) + //{{AFX_MSG_MAP(CAboutDlg) + // No message handlers + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CMFCExampleDlg dialog + +CMFCExampleDlg::CMFCExampleDlg(CWnd* pParent /*=NULL*/) + : CDialog(CMFCExampleDlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(CMFCExampleDlg) + m_bLeak = FALSE; + //}}AFX_DATA_INIT + // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 + m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); +} + +void CMFCExampleDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CMFCExampleDlg) + DDX_Check(pDX, IDC_CHECK_LEAK, m_bLeak); + //}}AFX_DATA_MAP +} + +BEGIN_MESSAGE_MAP(CMFCExampleDlg, CDialog) + //{{AFX_MSG_MAP(CMFCExampleDlg) + ON_WM_SYSCOMMAND() + ON_WM_PAINT() + ON_WM_QUERYDRAGICON() + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CMFCExampleDlg message handlers + +BOOL CMFCExampleDlg::OnInitDialog() +{ + CDialog::OnInitDialog(); + + // Add "About..." menu item to system menu. + + // IDM_ABOUTBOX must be in the system command range. + ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); + ASSERT(IDM_ABOUTBOX < 0xF000); + + CMenu* pSysMenu = GetSystemMenu(FALSE); + if (pSysMenu != NULL) + { + CString strAboutMenu; + strAboutMenu.LoadString(IDS_ABOUTBOX); + if (!strAboutMenu.IsEmpty()) + { + pSysMenu->AppendMenu(MF_SEPARATOR); + pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); + } + } + + // Set the icon for this dialog. The framework does this automatically + // when the application's main window is not a dialog + SetIcon(m_hIcon, TRUE); // Set big icon + SetIcon(m_hIcon, FALSE); // Set small icon + + // TODO: Add extra initialization here + m_bLeak = TRUE; + UpdateData(FALSE); + + return TRUE; // return TRUE unless you set the focus to a control +} + +void CMFCExampleDlg::OnSysCommand(UINT nID, LPARAM lParam) +{ + if ((nID & 0xFFF0) == IDM_ABOUTBOX) + { + CAboutDlg dlgAbout; + dlgAbout.DoModal(); + } + else + { + CDialog::OnSysCommand(nID, lParam); + } +} + +// If you add a minimize button to your dialog, you will need the code below +// to draw the icon. For MFC applications using the document/view model, +// this is automatically done for you by the framework. + +void CMFCExampleDlg::OnPaint() +{ + if (IsIconic()) + { + CPaintDC dc(this); // device context for painting + + SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); + + // Center icon in client rectangle + int cxIcon = GetSystemMetrics(SM_CXICON); + int cyIcon = GetSystemMetrics(SM_CYICON); + CRect rect; + GetClientRect(&rect); + int x = (rect.Width() - cxIcon + 1) / 2; + int y = (rect.Height() - cyIcon + 1) / 2; + + // Draw the icon + dc.DrawIcon(x, y, m_hIcon); + } + else + { + CDialog::OnPaint(); + } +} + +// The system calls this to obtain the cursor to display while the user drags +// the minimized window. +HCURSOR CMFCExampleDlg::OnQueryDragIcon() +{ + return (HCURSOR) m_hIcon; +} diff --git a/mfc/vldmfcdlg.h b/src/tests/mfc/vldmfcdlg.h similarity index 96% rename from mfc/vldmfcdlg.h rename to src/tests/mfc/vldmfcdlg.h index f0ac0e36..93cd2025 100644 --- a/mfc/vldmfcdlg.h +++ b/src/tests/mfc/vldmfcdlg.h @@ -1,46 +1,46 @@ -#if !defined(AFX_VLDMFCDLG_H__E5AE1FE6_8C7C_4A59_8DC1_2369B5C7B240__INCLUDED_) -#define AFX_VLDMFCDLG_H__E5AE1FE6_8C7C_4A59_8DC1_2369B5C7B240__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -///////////////////////////////////////////////////////////////////////////// -// CMFCExampleDlg dialog - -class CMFCExampleDlg : public CDialog -{ -// Construction -public: - CMFCExampleDlg(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CMFCExampleDlg) - enum { IDD = IDD_VLDMFC_DIALOG }; - BOOL m_bLeak; - //}}AFX_DATA - - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CMFCExampleDlg) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - HICON m_hIcon; - - // Generated message map functions - //{{AFX_MSG(CMFCExampleDlg) - virtual BOOL OnInitDialog(); - afx_msg void OnSysCommand(UINT nID, LPARAM lParam); - afx_msg void OnPaint(); - afx_msg HCURSOR OnQueryDragIcon(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_VLDMFCDLG_H__E5AE1FE6_8C7C_4A59_8DC1_2369B5C7B240__INCLUDED_) +#if !defined(AFX_VLDMFCDLG_H__E5AE1FE6_8C7C_4A59_8DC1_2369B5C7B240__INCLUDED_) +#define AFX_VLDMFCDLG_H__E5AE1FE6_8C7C_4A59_8DC1_2369B5C7B240__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +///////////////////////////////////////////////////////////////////////////// +// CMFCExampleDlg dialog + +class CMFCExampleDlg : public CDialog +{ +// Construction +public: + CMFCExampleDlg(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(CMFCExampleDlg) + enum { IDD = IDD_VLDMFC_DIALOG }; + BOOL m_bLeak; + //}}AFX_DATA + + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CMFCExampleDlg) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + HICON m_hIcon; + + // Generated message map functions + //{{AFX_MSG(CMFCExampleDlg) + virtual BOOL OnInitDialog(); + afx_msg void OnSysCommand(UINT nID, LPARAM lParam); + afx_msg void OnPaint(); + afx_msg HCURSOR OnQueryDragIcon(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_VLDMFCDLG_H__E5AE1FE6_8C7C_4A59_8DC1_2369B5C7B240__INCLUDED_) diff --git a/src/tests/mfc_dll/Resource.h b/src/tests/mfc_dll/Resource.h new file mode 100644 index 00000000..5906c537 --- /dev/null +++ b/src/tests/mfc_dll/Resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by mfc.rc +// + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS + +#define _APS_NEXT_RESOURCE_VALUE 1000 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 1000 +#define _APS_NEXT_COMMAND_VALUE 32771 +#endif +#endif diff --git a/src/tests/mfc_dll/mfc.cpp b/src/tests/mfc_dll/mfc.cpp new file mode 100644 index 00000000..d8dfaadd --- /dev/null +++ b/src/tests/mfc_dll/mfc.cpp @@ -0,0 +1,98 @@ +// mfc.cpp : Defines the initialization routines for the DLL. +// + +#include "stdafx.h" +#include "mfc.h" + +//#ifdef _DEBUG +//#define new DEBUG_NEW +//#endif + +// +//TODO: If this DLL is dynamically linked against the MFC DLLs, +// any functions exported from this DLL which call into +// MFC must have the AFX_MANAGE_STATE macro added at the +// very beginning of the function. +// +// For example: +// +// extern "C" BOOL PASCAL EXPORT ExportedFunction() +// { +// AFX_MANAGE_STATE(AfxGetStaticModuleState()); +// // normal function body here +// } +// +// It is very important that this macro appear in each +// function, prior to any calls into MFC. This means that +// it must appear as the first statement within the +// function, even before any object variable declarations +// as their constructors may generate calls into the MFC +// DLL. +// +// Please see MFC Technical Notes 33 and 58 for additional +// details. +// + +// CmfcApp + +BEGIN_MESSAGE_MAP(CmfcApp, CWinApp) +END_MESSAGE_MAP() + + +// CmfcApp construction + +CmfcApp::CmfcApp() +{ + // TODO: add construction code here, + // Place all significant initialization in InitInstance +} + + +// The one and only CmfcApp object + +CmfcApp theApp; + + +// CmfcApp initialization + +BOOL CmfcApp::InitInstance() +{ + CWinApp::InitInstance(); + + return TRUE; +} + +int CmfcApp::ExitInstance() +{ + // Without this, Dynamically unloading the MFC dll will crash +#ifdef _DEBUG // entire file + AfxEnableMemoryLeakDump(FALSE); +#endif + return 0; +} + +// Leaks 4 x 2 = 8 memory allocations (one by new operator and one by CString initialisation with string) +extern "C" void __declspec(dllexport) MFC_LeakSimple() +{ + AFX_MANAGE_STATE(AfxGetStaticModuleState()); + + // Attempt to allocate and leak some form of memory + CString* str_a = new CString(_T("I am a string in MFC")); + CString* str_b = new CString(_T("Another string in MFC")); + CString* str_c = DEBUG_NEW CString(_T("Another string in MFC")); + CString* str_d = new (_NORMAL_BLOCK, __FILE__, __LINE__) CString(_T("4 parameter new for mfc")); +} + +// Leaks 3 memory allocations, CString objects are initialised to empty state and do not allocate extra memory +extern "C" void __declspec(dllexport) MFC_LeakArray() +{ + AFX_MANAGE_STATE(AfxGetStaticModuleState()); + + // Attempt to allocate and leak an array of CStrings + CString* mystr = new CString[3]; + + CString* strArray = DEBUG_NEW CString[3]; + + CString* another = new (_NORMAL_BLOCK, __FILE__, __LINE__) CString[3]; +} + diff --git a/src/tests/mfc_dll/mfc.def b/src/tests/mfc_dll/mfc.def new file mode 100644 index 00000000..50ae4094 --- /dev/null +++ b/src/tests/mfc_dll/mfc.def @@ -0,0 +1,6 @@ +; mfc.def : Declares the module parameters for the DLL. + +LIBRARY + +EXPORTS + ; Explicit exports can go here diff --git a/src/tests/mfc_dll/mfc.h b/src/tests/mfc_dll/mfc.h new file mode 100644 index 00000000..7d05bc4b --- /dev/null +++ b/src/tests/mfc_dll/mfc.h @@ -0,0 +1,27 @@ +// mfc.h : main header file for the mfc DLL +// + +#pragma once + +#ifndef __AFXWIN_H__ + #error "include 'stdafx.h' before including this file for PCH" +#endif + +#include "resource.h" // main symbols + + +// CmfcApp +// See mfc.cpp for the implementation of this class +// + +class CmfcApp : public CWinApp +{ +public: + CmfcApp(); + +// Overrides +public: + virtual BOOL InitInstance(); + virtual int ExitInstance(); // return app exit code + DECLARE_MESSAGE_MAP() +}; diff --git a/src/tests/mfc_dll/mfc.rc b/src/tests/mfc_dll/mfc.rc new file mode 100644 index 00000000..cbc426ec Binary files /dev/null and b/src/tests/mfc_dll/mfc.rc differ diff --git a/src/tests/mfc_dll/mfc.vcxproj b/src/tests/mfc_dll/mfc.vcxproj new file mode 100644 index 00000000..7610e72d --- /dev/null +++ b/src/tests/mfc_dll/mfc.vcxproj @@ -0,0 +1,408 @@ + + + + + Debug(Release)_StaticCrt + Win32 + + + Debug(Release)_StaticCrt + x64 + + + Debug(Release) + Win32 + + + Debug(Release) + x64 + + + Debug_StaticCrt + Win32 + + + Debug_StaticCrt + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_StaticCrt + Win32 + + + Release_StaticCrt + x64 + + + Release + Win32 + + + Release + x64 + + + + {2178E5B2-1032-441F-A664-F3D8D1FD1913} + test_mfc + MFCDLLProj + test_mfc + 8.1 + + + + DynamicLibrary + Unicode + v140_xp + + + true + Dynamic + + + true + Static + + + true + Dynamic + + + true + Static + + + true + Dynamic + + + true + Static + + + true + Dynamic + + + true + Static + + + false + true + Dynamic + + + false + true + Static + + + false + true + Dynamic + + + false + true + Static + + + + + + + + + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + + + false + + + false + + + false + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + + + Windows + true + .\mfc.def + + + _DEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Windows + true + .\mfc.def + + + _DEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + + + Windows + true + .\mfc.def + + + _DEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + + + Windows + true + .\mfc.def + + + _DEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + + + Windows + true + .\mfc.def + + + _DEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Windows + true + .\mfc.def + + + _DEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + + + Windows + true + .\mfc.def + + + _DEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + + + Windows + true + .\mfc.def + + + _DEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;_WINDOWS;NDEBUG;_USRDLL;%(PreprocessorDefinitions) + + + Windows + true + true + true + .\mfc.def + + + NDEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;_WINDOWS;NDEBUG;_USRDLL;%(PreprocessorDefinitions) + MultiThreaded + + + Windows + true + true + true + .\mfc.def + + + NDEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;_WINDOWS;NDEBUG;_USRDLL;%(PreprocessorDefinitions) + + + Windows + true + true + true + .\mfc.def + + + NDEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;_WINDOWS;NDEBUG;_USRDLL;%(PreprocessorDefinitions) + MultiThreaded + + + Windows + true + true + true + .\mfc.def + + + NDEBUG;%(PreprocessorDefinitions) + $(IntDir);%(AdditionalIncludeDirectories) + + + + + + + + + + Create + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/tests/mfc_dll/mfc.vcxproj.filters b/src/tests/mfc_dll/mfc.vcxproj.filters new file mode 100644 index 00000000..656c5de1 --- /dev/null +++ b/src/tests/mfc_dll/mfc.vcxproj.filters @@ -0,0 +1,52 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Resource Files + + + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Resource Files + + + \ No newline at end of file diff --git a/src/tests/mfc_dll/res/mfc.rc2 b/src/tests/mfc_dll/res/mfc.rc2 new file mode 100644 index 00000000..ed6a2f98 Binary files /dev/null and b/src/tests/mfc_dll/res/mfc.rc2 differ diff --git a/src/tests/mfc_dll/stdafx.cpp b/src/tests/mfc_dll/stdafx.cpp new file mode 100644 index 00000000..0d3689f5 --- /dev/null +++ b/src/tests/mfc_dll/stdafx.cpp @@ -0,0 +1,7 @@ +// stdafx.cpp : source file that includes just the standard includes +// mfc.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + + diff --git a/src/tests/mfc_dll/stdafx.h b/src/tests/mfc_dll/stdafx.h new file mode 100644 index 00000000..d3d296b0 --- /dev/null +++ b/src/tests/mfc_dll/stdafx.h @@ -0,0 +1,39 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently + +#pragma once + +#ifndef VC_EXTRALEAN +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers +#endif + +#include "targetver.h" + +#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit + +#include // MFC core and standard components +#include // MFC extensions + +#ifndef _AFX_NO_OLE_SUPPORT +#include // MFC OLE classes +#include // MFC OLE dialog classes +#include // MFC Automation classes +#endif // _AFX_NO_OLE_SUPPORT + +#ifndef _AFX_NO_DB_SUPPORT +#include // MFC ODBC database classes +#endif // _AFX_NO_DB_SUPPORT + +#ifndef _AFX_NO_DAO_SUPPORT +#include // MFC DAO database classes +#endif // _AFX_NO_DAO_SUPPORT + +#ifndef _AFX_NO_OLE_SUPPORT +#include // MFC support for Internet Explorer 4 Common Controls +#endif +#ifndef _AFX_NO_AFXCMN_SUPPORT +#include // MFC support for Windows Common Controls +#endif // _AFX_NO_AFXCMN_SUPPORT + + diff --git a/src/tests/mfc_dll/targetver.h b/src/tests/mfc_dll/targetver.h new file mode 100644 index 00000000..87c0086d --- /dev/null +++ b/src/tests/mfc_dll/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/src/tests/suite/testsuite.cpp b/src/tests/suite/testsuite.cpp new file mode 100644 index 00000000..ede70168 --- /dev/null +++ b/src/tests/suite/testsuite.cpp @@ -0,0 +1,489 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - Test Suite +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +// +// Test suite for Visual Leak Detector +// +//////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include + +#include + +#include + +enum action_e { + a_calloc, + a_comalloc, + a_getprocmalloc, + a_heapalloc, + a_icomalloc, + a_ignored, + a_malloc, + a_new, + numactions +}; + +// Name of the debug C Runtime Library DLL on this system +#ifdef _DEBUG +#if _MSC_VER == 1400 // VS 2005 +#ifdef _DLL +#define CRTDLLNAME _T("msvcr80d.dll") +#else +#define CRTDLLNAME _T("msvcrt.dll") +#endif +#elif _MSC_VER == 1500 // VS 2008 +#ifdef _DLL +#define CRTDLLNAME _T("msvcr90d.dll") +#else +#define CRTDLLNAME _T("msvcrt.dll") +#endif +#elif _MSC_VER == 1600 // VS 2010 +#define CRTDLLNAME _T("msvcr100d.dll") +#elif _MSC_VER == 1700 // VS 2012 +#define CRTDLLNAME _T("msvcr110d.dll") +#elif _MSC_VER == 1800 // VS 2013 +#define CRTDLLNAME _T("msvcr120d.dll") +#elif _MSC_VER == 1900 // VS 2015 +#define CRTDLLNAME _T("ucrtbased.dll") +#else +#error Unsupported compiler +#endif +#else +#if _MSC_VER == 1400 // VS 2005 +#ifdef _DLL +#define CRTDLLNAME _T("msvcr80.dll") +#else +#define CRTDLLNAME _T("msvcrt.dll") +#endif +#elif _MSC_VER == 1500 // VS 2008 +#ifdef _DLL +#define CRTDLLNAME _T("msvcr90.dll") +#else +#define CRTDLLNAME _T("msvcrt.dll") +#endif +#elif _MSC_VER == 1600 // VS 2010 +#define CRTDLLNAME _T("msvcr100.dll") +#elif _MSC_VER == 1700 // VS 2012 +#define CRTDLLNAME _T("msvcr110.dll") +#elif _MSC_VER == 1800 // VS 2013 +#define CRTDLLNAME _T("msvcr120.dll") +#elif _MSC_VER == 1900 // VS 2015 +#define CRTDLLNAME _T("ucrtbase.dll") +#else +#error Unsupported compiler +#endif +#endif + +static int MAXALLOC = 0; // Maximum number of allocations of each type to perform, per thread +static int NUMTHREADS = 0; // Number of threads to run simultaneously +static int MAXBLOCKS = 0; // Total maximum number of allocations, per thread + +static const int MAXDEPTH = 32; // Maximum depth of the allocation call stack +static const int MAXSIZE = 64; // Maximum block size to allocate +static const int MINDEPTH = 0; // Minimum depth of the allocation call stack +static const int MINSIZE = 16; // Minimum block size to allocate +static const int NUMDUPLEAKS = 3; // Number of times to duplicate each leak +static const int ONCEINAWHILE = 10; // Free a random block approx. once every... + +struct blockholder_t { + PVOID block; + action_e action; + bool leak; +}; + +typedef void* (__cdecl *free_t) (void* mem); +typedef void* (__cdecl *malloc_t) (size_t size); + +struct threadcontext_t { + UINT index; + BOOL leaky; + DWORD seed; + unsigned threadid; +}; + +__declspec(thread) blockholder_t *blocks = NULL; +__declspec(thread) ULONG freeBlock = (ULONG)0; +__declspec(thread) ULONG counts [numactions] = { 0 }; +__declspec(thread) IMalloc *imalloc = NULL; +__declspec(thread) free_t pfree = NULL; +__declspec(thread) malloc_t pmalloc = NULL; +__declspec(thread) HANDLE threadheap; +__declspec(thread) ULONG total_allocs = 0; + +volatile LONG leaks_count = 0; + +ULONG random (ULONG max) +{ + FLOAT d; + FLOAT r; + ULONG v; + + r = ((FLOAT)rand()) / ((FLOAT)RAND_MAX); + r *= ((FLOAT)max); + d = r - ((ULONG)r); + if (d >= 0.5) { + v = ((ULONG)r) + 1; + } + else { + v = (ULONG)r; + } + + return v; +} + +VOID allocateblock (action_e action, SIZE_T size) +{ + HMODULE crt; + ULONG index; + ULONG index2; + LPCSTR name; + PVOID *pblock; + HRESULT status; + + // Find the first unused index. + index = freeBlock; + for (index2 = freeBlock + 1; index2 < MAXBLOCKS; index2++) { + if (blocks[index2].block == NULL) { + freeBlock = index2; + break; + } + } + blocks[index].action = action; + + // Now do the randomized allocation. + pblock = &blocks[index].block; + switch (action) { + case a_calloc: + name = "calloc"; + *pblock = calloc(1, size); + break; + + case a_comalloc: + name = "CoTaskMemAlloc"; + *pblock = CoTaskMemAlloc(size); + break; + + case a_getprocmalloc: + name = "GetProcAddress"; + if (pmalloc == NULL) { + crt = LoadLibrary(CRTDLLNAME); + assert(crt != NULL); + pmalloc = (malloc_t)GetProcAddress(crt, "malloc"); + assert(pmalloc != NULL); + } + *pblock = pmalloc(size); + break; + + case a_heapalloc: + name = "HeapAlloc"; + if (threadheap == NULL) { + threadheap = HeapCreate(0x0, 0, 0); + } + *pblock = HeapAlloc(threadheap, 0x0, size); + break; + + case a_icomalloc: + name = "IMalloc"; + if (imalloc == NULL) { + status = CoGetMalloc(1, &imalloc); + assert(status == S_OK); + } + *pblock = imalloc->Alloc(size); + break; + + case a_ignored: + name = "Ignored"; + VLDDisable(); + *pblock = malloc(size); + VLDRestore(); + break; + + case a_malloc: + name = "malloc"; + *pblock = malloc(size); + break; + + case a_new: + name = "new"; + *pblock = new BYTE [size]; + break; + + default: + assert(FALSE); + } + assert(*pblock != NULL); + counts[action]++; + total_allocs++; + + strncpy_s((char*)*pblock, size, name, _TRUNCATE); +} + +VOID freeblock (ULONG index) +{ + PVOID block; + HMODULE crt; + + block = blocks[index].block; + switch (blocks[index].action) { + case a_calloc: + free(block); + break; + + case a_comalloc: + CoTaskMemFree(block); + break; + + case a_getprocmalloc: + if (pfree == NULL) { + crt = GetModuleHandle(CRTDLLNAME); + assert(crt != NULL); + pfree = (free_t)GetProcAddress(crt, "free"); + assert(pfree != NULL); + } + pfree(block); + break; + + case a_heapalloc: + HeapFree(threadheap, 0x0, block); + break; + + case a_icomalloc: + imalloc->Free(block); + break; + + case a_ignored: + free(block); + break; + + case a_malloc: + free(block); + break; + + case a_new: + delete [] block; + break; + + default: + assert(FALSE); + } + blocks[index].block = NULL; + if (index < freeBlock) + freeBlock = index; + counts[blocks[index].action]--; + total_allocs--; +} + +VOID recursivelyallocate (UINT depth, action_e action, SIZE_T size) +{ + if (depth == 0) { + allocateblock(action, size); + } + else { + recursivelyallocate(depth - 1, action, size); + } +} + +unsigned __stdcall threadproc_test (LPVOID param) +{ + threadcontext_t* context = (threadcontext_t*)param; + assert(context); + + blocks = new blockholder_t[MAXBLOCKS]; + for (ULONG index = 0; index < MAXBLOCKS; index++) { + blocks[index].block = NULL; + blocks[index].leak = FALSE; + } + + srand(context->seed); + + BOOL allocate_more = TRUE; + while (allocate_more) { + // Select a random allocation action and a random size. + action_e action = (action_e)random(numactions - 1); + SIZE_T size = random(MAXSIZE); + if (size < MINSIZE) { + size = MINSIZE; + } + if (counts[action] == MAXALLOC) { + // We've done enough of this type of allocation. Select another. + continue; + } + + // Allocate a block, using recursion to build up a stack of random + // depth. + UINT depth = random(MAXDEPTH); + if (depth < MINDEPTH) { + depth = MINDEPTH; + } + recursivelyallocate(depth, action, size); + + // Every once in a while, free a random block. + if (random(ONCEINAWHILE) == ONCEINAWHILE) { + ULONG index = random(total_allocs); + if (blocks[index].block != NULL) { + freeblock(index); + } + } + + // See if we have allocated enough blocks using each type of action. + for (USHORT action_index = 0; action_index < numactions; action_index++) { + if (counts[action_index] < MAXALLOC) { + allocate_more = TRUE; + break; + } + allocate_more = FALSE; + } + } + + if (context->leaky) { + // This is the leaky thread. Randomly select one block to be leaked from + // each type of allocation action. + for (USHORT action_index = 0; action_index < numactions; action_index++) { + UINT leaks_selected = 0; + do { + ULONG index = random(MAXBLOCKS); + if (!blocks[index].leak && (blocks[index].block != NULL) && (blocks[index].action == (action_e)action_index)) { + blocks[index].leak = TRUE; + leaks_selected++; + if (blocks[index].action != a_ignored) + InterlockedIncrement(&leaks_count); + } + } while (leaks_selected < (1 + NUMDUPLEAKS)); + } + } + + // Free all blocks except for those marked as leaks. + for (ULONG index = 0; index < MAXBLOCKS; index++) { + if ((blocks[index].block != NULL) && (blocks[index].leak == FALSE)) { + freeblock(index); + } + } + + // Do a sanity check. + if (context->leaky) { + assert(total_allocs == (numactions * (1 + NUMDUPLEAKS))); + } + else { + assert(total_allocs == 0); + } + + delete[] blocks; + return 0; +} + +void RunTestSuite() +{ + if (!(VLDGetOptions() & VLD_OPT_SAFE_STACK_WALK)) + { + MAXALLOC = 1000; + NUMTHREADS = 63; + } + else + { + MAXALLOC = 10; + NUMTHREADS = 15; + } + _ASSERT(NUMTHREADS <= MAXIMUM_WAIT_OBJECTS); + MAXBLOCKS = (MAXALLOC * numactions); + + threadcontext_t* contexts = new threadcontext_t[NUMTHREADS]; + + // Select a random thread to be the leaker. + UINT leakythread = random(NUMTHREADS - 1); + HANDLE* threads = new HANDLE[NUMTHREADS]; + + for (UINT index = 0; index < NUMTHREADS; ++index) { + contexts[index].index = index; + if (index == leakythread) + contexts[index].leaky = TRUE; + else + contexts[index].leaky = FALSE; + contexts[index].seed = random(RAND_MAX); + HANDLE hthread = (HANDLE)_beginthreadex(NULL, 0, threadproc_test, &contexts[index], 0, &contexts[index].threadid); + threads[index] = hthread; + } + + // Wait for all threads to terminate. + BOOL wait_for_all = TRUE; + DWORD result = WaitForMultipleObjects(NUMTHREADS, threads, wait_for_all, INFINITE); + switch (result) + { + case WAIT_OBJECT_0: + _tprintf(_T("All threads finished correctly.\n")); + break; + case WAIT_ABANDONED_0: + _tprintf(_T("Abandoned mutex.\n")); + break; + case WAIT_TIMEOUT: + _tprintf(_T("All threads timed out\n")); + break; + case WAIT_FAILED: + { + _tprintf(_T("Function call to Wait failed with unknown error\n")); + TCHAR lpMsgBuf[MAX_PATH] = {0}; + FormatMessage( + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + lpMsgBuf, + MAX_PATH, + NULL ); + + _tprintf(_T("%s"), lpMsgBuf); + } + + break; + default: + _tprintf(_T("Some other return value\n")); + break; + } + delete[] contexts; + delete[] threads; +} + +TEST(TestSuit, MultiThread) +{ + leaks_count = 0; + + VLDMarkAllLeaksAsReported(); + RunTestSuite(); + int leaks = static_cast(VLDGetLeaksCount()); + if (leaks_count != leaks) + VLDReportLeaks(); + ASSERT_EQ(leaks_count, leaks); +} + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + int res = RUN_ALL_TESTS(); + VLDMarkAllLeaksAsReported(); + return res; +} diff --git a/src/tests/suite/testsuite.vcxproj b/src/tests/suite/testsuite.vcxproj new file mode 100644 index 00000000..96978851 --- /dev/null +++ b/src/tests/suite/testsuite.vcxproj @@ -0,0 +1,297 @@ + + + + + Debug(Release)_StaticCrt + Win32 + + + Debug(Release)_StaticCrt + x64 + + + Debug(Release) + Win32 + + + Debug(Release) + x64 + + + Debug_StaticCrt + Win32 + + + Debug_StaticCrt + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_StaticCrt + Win32 + + + Release_StaticCrt + x64 + + + Release + Win32 + + + Release + x64 + + + + {EE4A829C-5FD8-460B-8A90-B518B9BABB70} + testsuite + 8.1 + testsuite + + + + Application + NotSet + v140_xp + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + NativeRecommendedRules.ruleset + NativeRecommendedRules.ruleset + + + + + NativeRecommendedRules.ruleset + NativeRecommendedRules.ruleset + + + + + NativeRecommendedRules.ruleset + NativeRecommendedRules.ruleset + + + + + NativeRecommendedRules.ruleset + NativeRecommendedRules.ruleset + + + + + NativeRecommendedRules.ruleset + NativeRecommendedRules.ruleset + + + + + NativeRecommendedRules.ruleset + NativeRecommendedRules.ruleset + + + + + + + + Disabled + WIN32;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + false + false + + + true + Console + + + + + Disabled + WIN32;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebug + false + false + + + true + Console + + + + + Full + VLD_FORCE_ENABLE;NDEBUG;WIN32;%(PreprocessorDefinitions) + MultiThreadedDLL + true + true + + + true + true + true + Console + + + + + Full + VLD_FORCE_ENABLE;NDEBUG;WIN32;%(PreprocessorDefinitions) + MultiThreaded + true + true + + + true + true + true + Console + + + + + Disabled + WIN32;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + false + true + + + true + Console + + + + + Disabled + WIN32;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebug + false + true + + + true + Console + + + + + Disabled + WIN64;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + false + false + + + true + Console + + + + + Disabled + WIN64;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebug + false + false + + + true + Console + + + + + Full + VLD_FORCE_ENABLE;NDEBUG;WIN64;%(PreprocessorDefinitions) + MultiThreadedDLL + true + true + + + true + true + true + Console + + + + + Full + VLD_FORCE_ENABLE;NDEBUG;WIN64;%(PreprocessorDefinitions) + MultiThreaded + true + true + + + true + true + true + Console + + + + + Disabled + WIN64;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + false + true + + + true + true + Console + + + + + Disabled + WIN64;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebug + false + true + + + true + true + Console + + + + + + + + {c8f6c172-56f2-4e76-b5fa-c3b423b31be7} + + + + + + \ No newline at end of file diff --git a/src/tests/suite/testsuite.vcxproj.filters b/src/tests/suite/testsuite.vcxproj.filters new file mode 100644 index 00000000..31a8fddb --- /dev/null +++ b/src/tests/suite/testsuite.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav + + + + + Source Files + + + \ No newline at end of file diff --git a/src/tests/suite/testsuite.vcxproj.vspscc b/src/tests/suite/testsuite.vcxproj.vspscc new file mode 100644 index 00000000..b6d32892 --- /dev/null +++ b/src/tests/suite/testsuite.vcxproj.vspscc @@ -0,0 +1,10 @@ +"" +{ +"FILE_VERSION" = "9237" +"ENLISTMENT_CHOICE" = "NEVER" +"PROJECT_FILE_RELATIVE_PATH" = "" +"NUMBER_OF_EXCLUDED_FILES" = "0" +"ORIGINAL_PROJECT_FILE_PATH" = "" +"NUMBER_OF_NESTED_PROJECTS" = "0" +"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER" +} diff --git a/src/tests/vld_ComTest/ComTest.aps b/src/tests/vld_ComTest/ComTest.aps new file mode 100644 index 00000000..eeb1b0db Binary files /dev/null and b/src/tests/vld_ComTest/ComTest.aps differ diff --git a/src/tests/vld_ComTest/ComTest.cpp b/src/tests/vld_ComTest/ComTest.cpp new file mode 100644 index 00000000..47df2d73 --- /dev/null +++ b/src/tests/vld_ComTest/ComTest.cpp @@ -0,0 +1,81 @@ +#include "stdafx.h" +#include "resource.h" +#include "ComTest_i.h" +#include "dllmain.h" +#include "xdlldata.h" + + +STDAPI DllCanUnloadNow(void) +{ + #ifdef _MERGE_PROXYSTUB + HRESULT hr = PrxDllCanUnloadNow(); + if (hr != S_OK) + return hr; +#endif + AFX_MANAGE_STATE(AfxGetStaticModuleState()); + return (AfxDllCanUnloadNow()==S_OK && _AtlModule.GetLockCount()==0) ? S_OK : S_FALSE; +} + +STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) +{ + #ifdef _MERGE_PROXYSTUB + if (PrxDllGetClassObject(rclsid, riid, ppv) == S_OK) + return S_OK; +#endif + return _AtlModule.DllGetClassObject(rclsid, riid, ppv); +} + +STDAPI DllRegisterServer(void) +{ + //MessageBox(NULL, L"df", L"df", NULL); + HRESULT hr = _AtlModule.DllRegisterServer(); + #ifdef _MERGE_PROXYSTUB + if (FAILED(hr)) + return hr; + hr = PrxDllRegisterServer(); +#endif + return hr; +} + +STDAPI DllUnregisterServer(void) +{ + HRESULT hr = _AtlModule.DllUnregisterServer(); + #ifdef _MERGE_PROXYSTUB + if (FAILED(hr)) + return hr; + hr = PrxDllRegisterServer(); + if (FAILED(hr)) + return hr; + hr = PrxDllUnregisterServer(); +#endif + return hr; +} + +STDAPI DllInstall(BOOL bInstall, LPCWSTR pszCmdLine) +{ + HRESULT hr = E_FAIL; + static const wchar_t szUserSwitch[] = L"user"; + + if (pszCmdLine != NULL) + { + if (_wcsnicmp(pszCmdLine, szUserSwitch, _countof(szUserSwitch)) == 0) + { + ATL::AtlSetPerUserRegistration(true); + } + } + + if (bInstall) + { + hr = DllRegisterServer(); + if (FAILED(hr)) + { + DllUnregisterServer(); + } + } + else + { + hr = DllUnregisterServer(); + } + + return hr; +} diff --git a/src/tests/vld_ComTest/ComTest.def b/src/tests/vld_ComTest/ComTest.def new file mode 100644 index 00000000..ec0f033f --- /dev/null +++ b/src/tests/vld_ComTest/ComTest.def @@ -0,0 +1,8 @@ +LIBRARY + +EXPORTS + DllCanUnloadNow PRIVATE + DllGetClassObject PRIVATE + DllRegisterServer PRIVATE + DllUnregisterServer PRIVATE + DllInstall PRIVATE diff --git a/src/tests/vld_ComTest/ComTest.idl b/src/tests/vld_ComTest/ComTest.idl new file mode 100644 index 00000000..5952778f --- /dev/null +++ b/src/tests/vld_ComTest/ComTest.idl @@ -0,0 +1,27 @@ +import "oaidl.idl"; +import "ocidl.idl"; + +[ + object, + uuid(19823626-F6EA-472F-9AA3-1B2CA0693E53), + pointer_default(unique) +] +interface IMyMath : IUnknown{ + [] HRESULT Test(void); +}; +[ + uuid(68A502DA-EEB1-4B25-A0A4-3118922CBFE4), + version(1.0), +] +library ComTestLib +{ + importlib("stdole2.tlb"); + [ + uuid(B379BB26-80E6-4DCB-AD82-8F46BA81BBCF) + ] + coclass MyMath + { + [default] interface IMyMath; + }; +}; + diff --git a/src/tests/vld_ComTest/ComTest.rc b/src/tests/vld_ComTest/ComTest.rc new file mode 100644 index 00000000..31a00ea7 Binary files /dev/null and b/src/tests/vld_ComTest/ComTest.rc differ diff --git a/src/tests/vld_ComTest/ComTest.rgs b/src/tests/vld_ComTest/ComTest.rgs new file mode 100644 index 00000000..e7d37400 --- /dev/null +++ b/src/tests/vld_ComTest/ComTest.rgs @@ -0,0 +1,3 @@ +HKCR +{ +} diff --git a/src/tests/vld_ComTest/ComTest.sln b/src/tests/vld_ComTest/ComTest.sln new file mode 100644 index 00000000..1324742f --- /dev/null +++ b/src/tests/vld_ComTest/ComTest.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2013 +VisualStudioVersion = 12.0.31101.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ComTest", "ComTest.vcxproj", "{3719F504-3DF0-45F8-BC7A-4415804AC7C9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug|Win32.ActiveCfg = Debug|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug|Win32.Build.0 = Debug|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Release|Win32.ActiveCfg = Release|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/src/tests/vld_ComTest/ComTest_vs14.vcxproj b/src/tests/vld_ComTest/ComTest_vs14.vcxproj new file mode 100644 index 00000000..6145b07b --- /dev/null +++ b/src/tests/vld_ComTest/ComTest_vs14.vcxproj @@ -0,0 +1,565 @@ + + + + + Debug(Release)_StaticCrt + Win32 + + + Debug(Release)_StaticCrt + x64 + + + Debug(Release) + Win32 + + + Debug(Release) + x64 + + + Debug_StaticCrt + Win32 + + + Debug_StaticCrt + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_StaticCrt + Win32 + + + Release_StaticCrt + x64 + + + Release + Win32 + + + Release + x64 + + + + {3719F504-3DF0-45F8-BC7A-4415804AC7C9} + AtlProj + ComTest + ComTest + + + + DynamicLibrary + Unicode + v140_xp + + + true + Dynamic + + + true + Static + + + true + Dynamic + + + true + Static + + + true + Dynamic + + + true + Static + + + true + Dynamic + + + true + Static + + + false + Dynamic + + + false + Static + + + false + Dynamic + + + false + Static + + + + + + + + + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + + + false + + + false + + + false + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + + + false + Win32 + _DEBUG;%(PreprocessorDefinitions) + ComTest_i.h + ComTest_i.c + ComTest_p.c + true + $(IntDir)ComTest.tlb + true + + + 0x0804 + $(IntDir);%(AdditionalIncludeDirectories) + _DEBUG;%(PreprocessorDefinitions) + + + Windows + .\ComTest.def + true + true + true + + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + + + false + Win32 + _DEBUG;%(PreprocessorDefinitions) + ComTest_i.h + ComTest_i.c + ComTest_p.c + true + $(IntDir)ComTest.tlb + true + + + 0x0804 + $(IntDir);%(AdditionalIncludeDirectories) + _DEBUG;%(PreprocessorDefinitions) + + + Windows + .\ComTest.def + true + true + true + + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + + + false + Win32 + _DEBUG;%(PreprocessorDefinitions) + ComTest_i.h + ComTest_i.c + ComTest_p.c + true + $(IntDir)ComTest.tlb + true + + + 0x0804 + $(IntDir);%(AdditionalIncludeDirectories) + _DEBUG;%(PreprocessorDefinitions) + + + Windows + .\ComTest.def + true + true + true + + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + + + false + Win32 + _DEBUG;%(PreprocessorDefinitions) + ComTest_i.h + ComTest_i.c + ComTest_p.c + true + $(IntDir)ComTest.tlb + true + + + 0x0804 + $(IntDir);%(AdditionalIncludeDirectories) + _DEBUG;%(PreprocessorDefinitions) + + + Windows + .\ComTest.def + true + true + true + + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + + + false + _DEBUG;%(PreprocessorDefinitions) + ComTest_i.h + ComTest_i.c + ComTest_p.c + true + $(IntDir)ComTest.tlb + + + 0x0804 + $(IntDir);%(AdditionalIncludeDirectories) + _DEBUG;%(PreprocessorDefinitions) + + + Windows + .\ComTest.def + true + true + true + + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + + + false + _DEBUG;%(PreprocessorDefinitions) + ComTest_i.h + ComTest_i.c + ComTest_p.c + true + $(IntDir)ComTest.tlb + + + 0x0804 + $(IntDir);%(AdditionalIncludeDirectories) + _DEBUG;%(PreprocessorDefinitions) + + + Windows + .\ComTest.def + true + true + true + + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + + + false + _DEBUG;%(PreprocessorDefinitions) + ComTest_i.h + ComTest_i.c + ComTest_p.c + true + $(IntDir)ComTest.tlb + + + 0x0804 + $(IntDir);%(AdditionalIncludeDirectories) + _DEBUG;%(PreprocessorDefinitions) + + + Windows + .\ComTest.def + true + true + true + + + + + Use + Level3 + Disabled + WIN32;_WINDOWS;_DEBUG;_USRDLL;%(PreprocessorDefinitions) + + + false + _DEBUG;%(PreprocessorDefinitions) + ComTest_i.h + ComTest_i.c + ComTest_p.c + true + $(IntDir)ComTest.tlb + + + 0x0804 + $(IntDir);%(AdditionalIncludeDirectories) + _DEBUG;%(PreprocessorDefinitions) + + + Windows + .\ComTest.def + true + true + true + + + + + Use + Level3 + MaxSpeed + WIN32;_WINDOWS;NDEBUG;_USRDLL;%(PreprocessorDefinitions) + + + false + Win32 + NDEBUG;%(PreprocessorDefinitions) + ComTest_i.h + ComTest_i.c + ComTest_p.c + true + $(IntDir)ComTest.tlb + true + + + 0x0804 + $(IntDir);%(AdditionalIncludeDirectories) + NDEBUG;%(PreprocessorDefinitions) + + + Windows + .\ComTest.def + true + true + true + true + true + + + + + Use + Level3 + MaxSpeed + WIN32;_WINDOWS;NDEBUG;_USRDLL;%(PreprocessorDefinitions) + + + false + Win32 + NDEBUG;%(PreprocessorDefinitions) + ComTest_i.h + ComTest_i.c + ComTest_p.c + true + $(IntDir)ComTest.tlb + true + + + 0x0804 + $(IntDir);%(AdditionalIncludeDirectories) + NDEBUG;%(PreprocessorDefinitions) + + + Windows + .\ComTest.def + true + true + true + true + true + + + + + Use + Level3 + MaxSpeed + WIN32;_WINDOWS;NDEBUG;_USRDLL;%(PreprocessorDefinitions) + + + false + NDEBUG;%(PreprocessorDefinitions) + ComTest_i.h + ComTest_i.c + ComTest_p.c + true + $(IntDir)ComTest.tlb + + + 0x0804 + $(IntDir);%(AdditionalIncludeDirectories) + NDEBUG;%(PreprocessorDefinitions) + + + Windows + .\ComTest.def + true + true + true + true + true + + + + + Use + Level3 + MaxSpeed + WIN32;_WINDOWS;NDEBUG;_USRDLL;%(PreprocessorDefinitions) + + + false + NDEBUG;%(PreprocessorDefinitions) + ComTest_i.h + ComTest_i.c + ComTest_p.c + true + $(IntDir)ComTest.tlb + + + 0x0804 + $(IntDir);%(AdditionalIncludeDirectories) + NDEBUG;%(PreprocessorDefinitions) + + + Windows + .\ComTest.def + true + true + true + true + true + + + + + + NotUsing + + + + + Create + + + NotUsing + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/tests/vld_ComTest/ComTest_vs14.vcxproj.filters b/src/tests/vld_ComTest/ComTest_vs14.vcxproj.filters new file mode 100644 index 00000000..afccb08f --- /dev/null +++ b/src/tests/vld_ComTest/ComTest_vs14.vcxproj.filters @@ -0,0 +1,85 @@ + + + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {a27c1591-bff6-481d-8a73-f014c351a0f7} + False + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Source Files + + + Source Files + + + Generated Files + + + Source Files + + + Generated Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Generated Files + + + Header Files + + + + + Resource Files + + + + + Resource Files + + + Resource Files + + + Resource Files + + + + + Resource Files + + + \ No newline at end of file diff --git a/src/tests/vld_ComTest/MyMath.cpp b/src/tests/vld_ComTest/MyMath.cpp new file mode 100644 index 00000000..0aa55b2f --- /dev/null +++ b/src/tests/vld_ComTest/MyMath.cpp @@ -0,0 +1,11 @@ +#include "stdafx.h" +#include "MyMath.h" + +// CMyMath + +STDMETHODIMP CMyMath::Test(void) +{ + AFX_MANAGE_STATE(AfxGetStaticModuleState()); + + return S_OK; +} diff --git a/src/tests/vld_ComTest/MyMath.h b/src/tests/vld_ComTest/MyMath.h new file mode 100644 index 00000000..493ab7b4 --- /dev/null +++ b/src/tests/vld_ComTest/MyMath.h @@ -0,0 +1,41 @@ +#pragma once +#include "resource.h" + +#include "ComTest_i.h" + +using namespace ATL; + +// CMyMath + +class ATL_NO_VTABLE CMyMath : + public CComObjectRootEx, + public CComCoClass, + public IMyMath +{ +public: + CMyMath() + { + } + +DECLARE_REGISTRY_RESOURCEID(IDR_MYMATH) + +BEGIN_COM_MAP(CMyMath) + COM_INTERFACE_ENTRY(IMyMath) +END_COM_MAP() + + DECLARE_PROTECT_FINAL_CONSTRUCT() + + HRESULT FinalConstruct() + { + return S_OK; + } + + void FinalRelease() + { + } + +public: + STDMETHOD(Test)(void); +}; + +OBJECT_ENTRY_AUTO(__uuidof(MyMath), CMyMath) diff --git a/src/tests/vld_ComTest/MyMath.rgs b/src/tests/vld_ComTest/MyMath.rgs new file mode 100644 index 00000000..79a02165 --- /dev/null +++ b/src/tests/vld_ComTest/MyMath.rgs @@ -0,0 +1,15 @@ +HKCR +{ + NoRemove CLSID + { + ForceRemove {B379BB26-80E6-4DCB-AD82-8F46BA81BBCF} = s 'MyMath Class' + { + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + TypeLib = s '{68A502DA-EEB1-4B25-A0A4-3118922CBFE4}' + Version = s '1.0' + } + } +} diff --git a/src/tests/vld_ComTest/Resource.h b/src/tests/vld_ComTest/Resource.h new file mode 100644 index 00000000..86dc9607 --- /dev/null +++ b/src/tests/vld_ComTest/Resource.h @@ -0,0 +1,18 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by ComTest.rc +// +#define IDS_PROJNAME 100 +#define IDR_COMTEST 101 +#define IDR_MYMATH 106 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 201 +#define _APS_NEXT_COMMAND_VALUE 32768 +#define _APS_NEXT_CONTROL_VALUE 201 +#define _APS_NEXT_SYMED_VALUE 107 +#endif +#endif diff --git a/src/tests/vld_ComTest/dlldata.c b/src/tests/vld_ComTest/dlldata.c new file mode 100644 index 00000000..4638f411 --- /dev/null +++ b/src/tests/vld_ComTest/dlldata.c @@ -0,0 +1,37 @@ +/********************************************************* + DllData file -- generated by MIDL compiler + + DO NOT ALTER THIS FILE + + This file is regenerated by MIDL on every IDL file compile. + + To completely reconstruct this file, delete it and rerun MIDL + on all the IDL files in this DLL, specifying this file for the + /dlldata command line option + +*********************************************************/ + + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +EXTERN_PROXY_FILE( ComTest ) + + +PROXYFILE_LIST_START +/* Start of list */ + REFERENCE_PROXY_FILE( ComTest ), +/* End of list */ +PROXYFILE_LIST_END + + +DLLDATA_ROUTINES( aProxyFileList, GET_DLL_CLSID ) + +#ifdef __cplusplus +} /*extern "C" */ +#endif + +/* end of generated dlldata file */ diff --git a/src/tests/vld_ComTest/dllmain.cpp b/src/tests/vld_ComTest/dllmain.cpp new file mode 100644 index 00000000..ce5045a9 --- /dev/null +++ b/src/tests/vld_ComTest/dllmain.cpp @@ -0,0 +1,35 @@ +#include "stdafx.h" +#include "resource.h" +#include "ComTest_i.h" +#include "dllmain.h" +#include "xdlldata.h" + +CComTestModule _AtlModule; + +class CComTestApp : public CWinApp +{ +public: + virtual BOOL InitInstance(); + virtual int ExitInstance(); + + DECLARE_MESSAGE_MAP() +}; + +BEGIN_MESSAGE_MAP(CComTestApp, CWinApp) +END_MESSAGE_MAP() + +CComTestApp theApp; + +BOOL CComTestApp::InitInstance() +{ +#ifdef _MERGE_PROXYSTUB + if (!PrxDllMain(m_hInstance, DLL_PROCESS_ATTACH, NULL)) + return FALSE; +#endif + return CWinApp::InitInstance(); +} + +int CComTestApp::ExitInstance() +{ + return CWinApp::ExitInstance(); +} diff --git a/src/tests/vld_ComTest/dllmain.h b/src/tests/vld_ComTest/dllmain.h new file mode 100644 index 00000000..f2978954 --- /dev/null +++ b/src/tests/vld_ComTest/dllmain.h @@ -0,0 +1,8 @@ +class CComTestModule : public ATL::CAtlDllModuleT< CComTestModule > +{ +public : + DECLARE_LIBID(LIBID_ComTestLib) + DECLARE_REGISTRY_APPID_RESOURCEID(IDR_COMTEST, "{06DD8E8C-4587-41A0-8D5A-B3A87883B158}") +}; + +extern class CComTestModule _AtlModule; diff --git a/src/tests/vld_ComTest/stdafx.cpp b/src/tests/vld_ComTest/stdafx.cpp new file mode 100644 index 00000000..a27b824d --- /dev/null +++ b/src/tests/vld_ComTest/stdafx.cpp @@ -0,0 +1 @@ +#include "stdafx.h" diff --git a/src/tests/vld_ComTest/stdafx.h b/src/tests/vld_ComTest/stdafx.h new file mode 100644 index 00000000..979ad7bd --- /dev/null +++ b/src/tests/vld_ComTest/stdafx.h @@ -0,0 +1,39 @@ +#pragma once + +#ifndef STRICT +#define STRICT +#endif + +#include "targetver.h" + +//#define DISABLE_VLD +//#define OVERRIDE_DISABLE_VLD +#include + +#define _ATL_APARTMENT_THREADED + +#define _ATL_NO_AUTOMATIC_NAMESPACE + +#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _AFX_NO_OLE_SUPPORT +#include +#endif // _AFX_NO_OLE_SUPPORT + +#define ATL_NO_ASSERT_ON_DESTROY_NONEXISTENT_WINDOW + +#include "resource.h" +#include +#include +#include diff --git a/src/tests/vld_ComTest/targetver.h b/src/tests/vld_ComTest/targetver.h new file mode 100644 index 00000000..2b26ce28 --- /dev/null +++ b/src/tests/vld_ComTest/targetver.h @@ -0,0 +1,3 @@ +#pragma once + +#include diff --git a/src/tests/vld_ComTest/xdlldata.c b/src/tests/vld_ComTest/xdlldata.c new file mode 100644 index 00000000..c57bafcd Binary files /dev/null and b/src/tests/vld_ComTest/xdlldata.c differ diff --git a/src/tests/vld_ComTest/xdlldata.h b/src/tests/vld_ComTest/xdlldata.h new file mode 100644 index 00000000..89313c5c --- /dev/null +++ b/src/tests/vld_ComTest/xdlldata.h @@ -0,0 +1,15 @@ +#pragma once + +#ifdef _MERGE_PROXYSTUB + +extern "C" +{ +BOOL WINAPI PrxDllMain(HINSTANCE hInstance, DWORD dwReason, + LPVOID lpReserved); +STDAPI PrxDllCanUnloadNow(void); +STDAPI PrxDllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv); +STDAPI PrxDllRegisterServer(void); +STDAPI PrxDllUnregisterServer(void); +} + +#endif diff --git a/src/tests/vld_dll1/dllmain.cpp b/src/tests/vld_dll1/dllmain.cpp new file mode 100644 index 00000000..5a1ee8c1 --- /dev/null +++ b/src/tests/vld_dll1/dllmain.cpp @@ -0,0 +1,29 @@ +// dllmain.cpp : Defines the entry point for the DLL application. +#include "stdafx.h" +#include +#include + +BOOL APIENTRY DllMain(HMODULE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + switch (ul_reason_for_call) { + case DLL_PROCESS_ATTACH: { + void* leak = malloc(9); + break; + } + case DLL_THREAD_ATTACH: { + break; + } + case DLL_THREAD_DETACH: { + break; + } + case DLL_PROCESS_DETACH: { + //assert(1 == VLDGetThreadLeaksCount(GetCurrentThreadId())); + break; + } + } + return TRUE; +} + diff --git a/src/tests/vld_dll1/stdafx.cpp b/src/tests/vld_dll1/stdafx.cpp new file mode 100644 index 00000000..8cc80f5a --- /dev/null +++ b/src/tests/vld_dll1/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// vld_dll1.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/src/tests/vld_dll1/stdafx.h b/src/tests/vld_dll1/stdafx.h new file mode 100644 index 00000000..b9e5bc15 --- /dev/null +++ b/src/tests/vld_dll1/stdafx.h @@ -0,0 +1,19 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +// Windows Header Files: +#include + +#define VLD_FORCE_ENABLE +#include + + + +// TODO: reference additional headers your program requires here diff --git a/src/tests/vld_dll1/targetver.h b/src/tests/vld_dll1/targetver.h new file mode 100644 index 00000000..87c0086d --- /dev/null +++ b/src/tests/vld_dll1/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/src/tests/vld_dll1/vld_dll1_vs14.vcxproj b/src/tests/vld_dll1/vld_dll1_vs14.vcxproj new file mode 100644 index 00000000..c58ff22f --- /dev/null +++ b/src/tests/vld_dll1/vld_dll1_vs14.vcxproj @@ -0,0 +1,345 @@ + + + + + Debug(Release)_StaticCrt + Win32 + + + Debug(Release)_StaticCrt + x64 + + + Debug(Release) + Win32 + + + Debug(Release) + x64 + + + Debug_StaticCrt + Win32 + + + Debug_StaticCrt + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_StaticCrt + Win32 + + + Release_StaticCrt + x64 + + + Release + Win32 + + + Release + x64 + + + + {50C94B05-8C3E-49ED-B2B9-5715EB624D14} + Win32Proj + vld_dll1 + vld_dll1 + + + + DynamicLibrary + v140_xp + Unicode + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + true + + + false + true + + + false + true + + + false + true + + + + + + + + + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + + + false + + + false + + + false + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Windows + true + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + MultiThreaded + + + Windows + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + MultiThreaded + + + Windows + true + true + true + + + + + + + + + + Create + + + + + {0d30ffcb-45da-4d2b-8e3c-81bc145bf2de} + + + + + + \ No newline at end of file diff --git a/src/tests/vld_dll1/vld_dll1_vs14.vcxproj.filters b/src/tests/vld_dll1/vld_dll1_vs14.vcxproj.filters new file mode 100644 index 00000000..95c6df39 --- /dev/null +++ b/src/tests/vld_dll1/vld_dll1_vs14.vcxproj.filters @@ -0,0 +1,33 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/src/tests/vld_dll2/dllmain.cpp b/src/tests/vld_dll2/dllmain.cpp new file mode 100644 index 00000000..058cf3bc --- /dev/null +++ b/src/tests/vld_dll2/dllmain.cpp @@ -0,0 +1,29 @@ +// dllmain.cpp : Defines the entry point for the DLL application. +#include "stdafx.h" +#include +#include + +BOOL APIENTRY DllMain(HMODULE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + switch (ul_reason_for_call) { + case DLL_PROCESS_ATTACH: { + void* leak = malloc(15); + break; + } + case DLL_THREAD_ATTACH: { + break; + } + case DLL_THREAD_DETACH: { + break; + } + case DLL_PROCESS_DETACH: { + //assert(1 == VLDGetThreadLeaksCount(GetCurrentThreadId())); + break; + } + } + return TRUE; +} + diff --git a/src/tests/vld_dll2/stdafx.cpp b/src/tests/vld_dll2/stdafx.cpp new file mode 100644 index 00000000..8cc80f5a --- /dev/null +++ b/src/tests/vld_dll2/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// vld_dll1.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/src/tests/vld_dll2/stdafx.h b/src/tests/vld_dll2/stdafx.h new file mode 100644 index 00000000..b9e5bc15 --- /dev/null +++ b/src/tests/vld_dll2/stdafx.h @@ -0,0 +1,19 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +// Windows Header Files: +#include + +#define VLD_FORCE_ENABLE +#include + + + +// TODO: reference additional headers your program requires here diff --git a/src/tests/vld_dll2/targetver.h b/src/tests/vld_dll2/targetver.h new file mode 100644 index 00000000..87c0086d --- /dev/null +++ b/src/tests/vld_dll2/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/src/tests/vld_dll2/vld_dll2_vs14.vcxproj b/src/tests/vld_dll2/vld_dll2_vs14.vcxproj new file mode 100644 index 00000000..c23b1372 --- /dev/null +++ b/src/tests/vld_dll2/vld_dll2_vs14.vcxproj @@ -0,0 +1,345 @@ + + + + + Debug(Release)_StaticCrt + Win32 + + + Debug(Release)_StaticCrt + x64 + + + Debug(Release) + Win32 + + + Debug(Release) + x64 + + + Debug_StaticCrt + Win32 + + + Debug_StaticCrt + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_StaticCrt + Win32 + + + Release_StaticCrt + x64 + + + Release + Win32 + + + Release + x64 + + + + {33F98E06-F44C-4E22-9E16-4C20F8238A95} + Win32Proj + vld_dll2 + vld_dll2 + + + + DynamicLibrary + v140_xp + Unicode + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + true + + + false + true + + + false + true + + + false + true + + + + + + + + + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + + + false + + + false + + + false + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL2_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL2_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL2_EXPORTS;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL2_EXPORTS;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL2_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL2_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL2_EXPORTS;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Windows + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;VLD_DLL2_EXPORTS;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Windows + true + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + MultiThreaded + + + Windows + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + + + Windows + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;VLD_DLL1_EXPORTS;%(PreprocessorDefinitions) + true + MultiThreaded + + + Windows + true + true + true + + + + + + + + + + Create + + + + + {0d30ffcb-45da-4d2b-8e3c-81bc145bf2de} + + + + + + \ No newline at end of file diff --git a/src/tests/vld_dll2/vld_dll2_vs14.vcxproj.filters b/src/tests/vld_dll2/vld_dll2_vs14.vcxproj.filters new file mode 100644 index 00000000..95c6df39 --- /dev/null +++ b/src/tests/vld_dll2/vld_dll2_vs14.vcxproj.filters @@ -0,0 +1,33 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/src/tests/vld_main/stdafx.cpp b/src/tests/vld_main/stdafx.cpp new file mode 100644 index 00000000..d5a2f158 --- /dev/null +++ b/src/tests/vld_main/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// vld_main.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/src/tests/vld_main/stdafx.h b/src/tests/vld_main/stdafx.h new file mode 100644 index 00000000..b005a839 --- /dev/null +++ b/src/tests/vld_main/stdafx.h @@ -0,0 +1,15 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#include +#include + + + +// TODO: reference additional headers your program requires here diff --git a/src/tests/vld_main/targetver.h b/src/tests/vld_main/targetver.h new file mode 100644 index 00000000..87c0086d --- /dev/null +++ b/src/tests/vld_main/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/src/tests/vld_main/vld_main.cpp b/src/tests/vld_main/vld_main.cpp new file mode 100644 index 00000000..cd22b6c6 --- /dev/null +++ b/src/tests/vld_main/vld_main.cpp @@ -0,0 +1,74 @@ +// vld_main.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" +#include +#include +#include + +#define VLD_FORCE_ENABLE +#include + + +class MemoryLeak { +public: + MemoryLeak(size_t n) { l = malloc(n); memset(l, 0x30 + ((int)n / 10), n); } // 4,5 + ~MemoryLeak() { free(l); } +private: + void* l; +}; + +static void* s_m = malloc(10); // 1 +static char* s_n = new char[20]; // 2 + +static MemoryLeak* pml = new MemoryLeak(70); // 3: leaks a new pointer and malloc(70) +#if _MSC_VER > 1700 +static MemoryLeak ml{ 80 }; // *should* be freed and not report as a memory leak +#endif + +void* g_m = malloc(30); // 6 +char* g_n = new char[40]; // 7 + + +int Test() +{ + VLDSetOptions(VLD_OPT_TRACE_INTERNAL_FRAMES | VLD_OPT_SKIP_CRTSTARTUP_LEAKS, 256, 64); + + void* m = malloc(50); // 8 + char* n = new char[60]; // 9 + + memset(s_m, '1', 10); + memset(s_n, '2', 20); + memset(g_m, '3', 30); + memset(g_n, '4', 40); + memset(m, '5', 50); + memset(n, '6', 60); + + // std libary dynamically initializes the objects "cout" and "cerr", which + // produce false positive leaks in Release_StaticCrt because we doesn't have + // debug CRT allocation header. + std::cout << "Test: cout"; + //std::cerr << "Test: cerr"; + + // At this point VLDGetLeaksCount() and VLDReportLeaks() should report 9 leaks + // including a leak for ml which has not been freed yet. ml will be freed after + // _tmain exits but before VLDReportLeaks() is called internally by VLD and + // therefore correctly report 8 leaks. + int leaks = VLDGetLeaksCount(); + VLDReportLeaks(); // at this point should report 9 leaks; + return leaks; +} + +int _tmain(int argc, _TCHAR* argv[]) +{ + return Test(); +} + + +int WINAPI _tWinMain(__in HINSTANCE hInstance, + __in_opt HINSTANCE hPrevInstance, + __in LPWSTR lpCmdLine, + __in int nShowCmd) +{ + return Test(); +} \ No newline at end of file diff --git a/src/tests/vld_main/vld_main_vs14.vcxproj b/src/tests/vld_main/vld_main_vs14.vcxproj new file mode 100644 index 00000000..d1a3e39c --- /dev/null +++ b/src/tests/vld_main/vld_main_vs14.vcxproj @@ -0,0 +1,342 @@ + + + + + Debug(Release)_StaticCrt + Win32 + + + Debug(Release)_StaticCrt + x64 + + + Debug(Release) + Win32 + + + Debug(Release) + x64 + + + Debug_StaticCrt + Win32 + + + Debug_StaticCrt + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_StaticCrt + Win32 + + + Release_StaticCrt + x64 + + + Release + Win32 + + + Release + x64 + + + + {8C732490-DC1A-40C0-923F-1555B9141B80} + Win32Proj + vld_main + vld_main + + + + Application + v140_xp + Unicode + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + true + + + false + true + + + false + true + + + false + true + + + + + + + + + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + + + false + + + false + + + false + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebugDLL + + + Console + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Console + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Console + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebugDLL + + + Console + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Console + true + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Console + true + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreaded + + + Console + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreaded + + + Console + true + true + true + + + + + + + + + Create + + + + + + + \ No newline at end of file diff --git a/src/tests/vld_main/vld_main_vs14.vcxproj.filters b/src/tests/vld_main/vld_main_vs14.vcxproj.filters new file mode 100644 index 00000000..4644d1bb --- /dev/null +++ b/src/tests/vld_main/vld_main_vs14.vcxproj.filters @@ -0,0 +1,33 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/src/tests/vld_main_test/stdafx.cpp b/src/tests/vld_main_test/stdafx.cpp new file mode 100644 index 00000000..d5a2f158 --- /dev/null +++ b/src/tests/vld_main_test/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// vld_main.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/src/tests/vld_main_test/stdafx.h b/src/tests/vld_main_test/stdafx.h new file mode 100644 index 00000000..b005a839 --- /dev/null +++ b/src/tests/vld_main_test/stdafx.h @@ -0,0 +1,15 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#include +#include + + + +// TODO: reference additional headers your program requires here diff --git a/src/tests/vld_main_test/targetver.h b/src/tests/vld_main_test/targetver.h new file mode 100644 index 00000000..87c0086d --- /dev/null +++ b/src/tests/vld_main_test/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/src/tests/vld_main_test/vld_main_test.cpp b/src/tests/vld_main_test/vld_main_test.cpp new file mode 100644 index 00000000..95d1da18 --- /dev/null +++ b/src/tests/vld_main_test/vld_main_test.cpp @@ -0,0 +1,50 @@ +// vld_main.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" +#include +#include +#include + +std::wstring dir; + +TEST(TestWinMain, RunExe) +{ + PROCESS_INFORMATION processInformation = { 0 }; + STARTUPINFO startupInfo = { 0 }; + startupInfo.cb = sizeof(startupInfo); + + std::wstring exe = dir + _T("vld_main.exe"); + + // Create the process + BOOL result = CreateProcess(exe.c_str(), NULL, + NULL, NULL, FALSE, + NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, + NULL, NULL, &startupInfo, &processInformation); + EXPECT_NE(0, result); + + // Successfully created the process. Wait for it to finish. + EXPECT_EQ(WAIT_OBJECT_0, WaitForSingleObject(processInformation.hProcess, INFINITE)); + + // Get the exit code. + DWORD exitCode = 0; + result = GetExitCodeProcess(processInformation.hProcess, &exitCode); + EXPECT_NE(0, result); + + // Close the handles. + CloseHandle(processInformation.hProcess); + CloseHandle(processInformation.hThread); +#if _MSC_VER > 1700 + ASSERT_EQ(9, exitCode); +#else + ASSERT_EQ(8, exitCode); +#endif +} + +int _tmain(int argc, _TCHAR* argv[]) +{ + dir = argv[0]; + dir.resize(dir.find_last_of(_T("\\")) + 1); + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/src/tests/vld_main_test/vld_main_test_vs14.vcxproj b/src/tests/vld_main_test/vld_main_test_vs14.vcxproj new file mode 100644 index 00000000..16469d70 --- /dev/null +++ b/src/tests/vld_main_test/vld_main_test_vs14.vcxproj @@ -0,0 +1,422 @@ + + + + + Debug(Release)_StaticCrt + Win32 + + + Debug(Release)_StaticCrt + x64 + + + Debug(Release) + Win32 + + + Debug(Release) + x64 + + + Debug_StaticCrt + Win32 + + + Debug_StaticCrt + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_StaticCrt + Win32 + + + Release_StaticCrt + x64 + + + Release + Win32 + + + Release + x64 + + + + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E} + Win32Proj + vld_main_test + vld_main_test + + + + Application + v140_xp + Unicode + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + true + + + false + true + + + false + true + + + false + true + + + + + + + + + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + + + false + + + false + + + false + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + + + Console + true + + + + + + + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebugDLL + + + Console + true + + + + + + + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Console + true + + + + + + + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Console + true + + + + + + + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + + + Console + true + + + + + + + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebugDLL + + + Console + true + + + + + + + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Console + true + + + + + + + + + + + Use + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebug + + + Console + true + + + + + + + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreaded + + + Console + true + true + true + + + + + + + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + + + Level3 + Use + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + true + MultiThreaded + + + Console + true + true + true + + + + + + + + + + + + + + + Create + + + + + + {c8f6c172-56f2-4e76-b5fa-c3b423b31be7} + + + {8c732490-dc1a-40c0-923f-1555b9141b80} + + + + + + \ No newline at end of file diff --git a/src/tests/vld_main_test/vld_main_test_vs14.vcxproj.filters b/src/tests/vld_main_test/vld_main_test_vs14.vcxproj.filters new file mode 100644 index 00000000..9c309eb7 --- /dev/null +++ b/src/tests/vld_main_test/vld_main_test_vs14.vcxproj.filters @@ -0,0 +1,33 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/src/tests/vld_unload/stdafx.cpp b/src/tests/vld_unload/stdafx.cpp new file mode 100644 index 00000000..e1e5b477 --- /dev/null +++ b/src/tests/vld_unload/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// vld_test.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/src/tests/vld_unload/stdafx.h b/src/tests/vld_unload/stdafx.h new file mode 100644 index 00000000..b005a839 --- /dev/null +++ b/src/tests/vld_unload/stdafx.h @@ -0,0 +1,15 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#include +#include + + + +// TODO: reference additional headers your program requires here diff --git a/src/tests/vld_unload/targetver.h b/src/tests/vld_unload/targetver.h new file mode 100644 index 00000000..87c0086d --- /dev/null +++ b/src/tests/vld_unload/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/src/tests/vld_unload/vld_unload.cpp b/src/tests/vld_unload/vld_unload.cpp new file mode 100644 index 00000000..0bb99dac --- /dev/null +++ b/src/tests/vld_unload/vld_unload.cpp @@ -0,0 +1,145 @@ +// vld_unload.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" + +#include +#include +#include + +#include + +#ifdef _WIN64 +static const TCHAR* sVld_dll = _T("vld_x64.dll"); +#else +static const TCHAR* sVld_dll = _T("vld_x86.dll"); +#endif + +UINT VLDGetLeaksCount() +{ + HMODULE vld_module = GetModuleHandle(sVld_dll); + if (vld_module != NULL) { + typedef UINT(*VLDAPI_func)(); + VLDAPI_func func = (VLDAPI_func)GetProcAddress(vld_module, "VLDGetLeaksCount"); + assert(func); + if (func) { + return func(); + } + } + return -1; +} + +HMODULE GetModuleFromAddress(LPCVOID pAddress) +{ + HMODULE hModule = NULL; + MEMORY_BASIC_INFORMATION mbi; + if (VirtualQuery((LPCVOID)pAddress, &mbi, sizeof(MEMORY_BASIC_INFORMATION)) == sizeof(MEMORY_BASIC_INFORMATION)) { + // the allocation base is the beginning of a PE file + hModule = (HMODULE)mbi.AllocationBase; + } + return hModule; +} + + +TEST(TestUnloadDlls, Sequence1) +{ + ASSERT_EQ(NULL, GetModuleHandle(sVld_dll)); + HMODULE hModule1 = ::LoadLibrary(_T("vld_dll1.dll")); + int w = VLDGetLeaksCount(); // vld is loaded and counts 1 memory leak + EXPECT_EQ(1, w); + ::FreeLibrary(hModule1); // vld is unloaded here and reports the memory leak + int x = VLDGetLeaksCount(); // vld is unloaded and cannot count any memory leaks + EXPECT_EQ(-1, x); + + HMODULE hModule2 = ::LoadLibrary(_T("vld_dll2.dll")); + int y = VLDGetLeaksCount(); // vld is loaded and counts 1 memory leak + EXPECT_EQ(1, y); + ::FreeLibrary(hModule2); // vld is unloaded here and reports the memory leak + int z = VLDGetLeaksCount(); // vld is unloaded and cannot count any memory leaks + EXPECT_EQ(-1, z); +} + +TEST(TestUnloadDlls, Sequence2) +{ + ASSERT_EQ(NULL, GetModuleHandle(sVld_dll)); + HMODULE hModule3 = ::LoadLibrary(_T("vld_dll1.dll")); + int w = VLDGetLeaksCount(); // vld is loaded and counts 1 memory leak + EXPECT_EQ(1, w); + HMODULE hModule4 = ::LoadLibrary(_T("vld_dll2.dll")); + int x = VLDGetLeaksCount(); // vld is still loaded and counts 2 memory leaks + EXPECT_EQ(2, x); + ::FreeLibrary(hModule4); // vld is *not* unloaded here + int y = VLDGetLeaksCount(); +#if _MSC_VER <= 1600 && !defined(_DLL) // VS 2010 and bellow + // The reason for reporting 1 leak at this point is that the vld_dll1 module build with + + + + Debug(Release)_StaticCrt + Win32 + + + Debug(Release)_StaticCrt + x64 + + + Debug(Release) + Win32 + + + Debug(Release) + x64 + + + Debug_StaticCrt + Win32 + + + Debug_StaticCrt + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release_StaticCrt + Win32 + + + Release_StaticCrt + x64 + + + Release + Win32 + + + Release + x64 + + + + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814} + Win32Proj + vld_unload + vld_unload + + + + Application + v140_xp + Unicode + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + true + + + false + true + + + false + true + + + false + true + + + + + + + + + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + true + + + false + + + false + + + false + + + false + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + + + Console + true + + + + + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + + + Console + true + + + + + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Console + true + + + + + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Console + true + + + + + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + + + Console + true + + + + + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + + + Console + true + + + + + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Console + true + + + + + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + MultiThreadedDebug + + + Console + true + + + + + + + + + + + Level3 + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + + + Console + true + true + true + + + + + + + + + + + Level3 + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + MultiThreaded + + + Console + true + true + true + + + + + + + + + + + Level3 + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + + + Console + true + true + true + + + + + + + + + + + Level3 + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) + MultiThreaded + + + Console + true + true + true + + + + + + + + + + + + + + + + + + + {c8f6c172-56f2-4e76-b5fa-c3b423b31be7} + + + {50c94b05-8c3e-49ed-b2b9-5715eb624d14} + true + false + false + false + + + {33f98e06-f44c-4e22-9e16-4c20f8238a95} + true + false + false + false + + + + + + \ No newline at end of file diff --git a/src/tests/vld_unload/vld_unload_vs14.vcxproj.filters b/src/tests/vld_unload/vld_unload_vs14.vcxproj.filters new file mode 100644 index 00000000..43a60e40 --- /dev/null +++ b/src/tests/vld_unload/vld_unload_vs14.vcxproj.filters @@ -0,0 +1,33 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/tree.h b/src/tree.h similarity index 88% rename from tree.h rename to src/tree.h index 949990ea..94c44954 100644 --- a/tree.h +++ b/src/tree.h @@ -1,785 +1,756 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - Red-black Tree Template -// Copyright (c) 2005-2006 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef VLDBUILD -#error \ -"This header should only be included by Visual Leak Detector when building it from source. \ -Applications should never include this header." -#endif - -#include "vldheap.h" // Provides internal new and delete operators. - -#define TREE_DEFAULT_RESERVE 32 // By default, trees reserve enough space, in advance, for this many nodes. - -//////////////////////////////////////////////////////////////////////////////// -// -// The Tree Template Class -// -// This data structure is the internal data structure behind the lightweight -// STL-like container classes. This is a red-black tree which provides for -// fast insert, find, and erase operations. -// -// The binary tree nodes are overlaid on top of larger chunks of allocated -// memory (called chunks) which are arranged in a simple linked list. This -// allows the tree to grow (add nodes) dynamically without incurring a heap -// hit each time a new node is added. -// -// The Tree class provides member functions which make it easily adaptable to -// an STL-like interface so that it can be used as the backend for STL-like -// container classes. -// -template -class Tree -{ -public: - // This is a red-black tree. - enum color_e { - red, - black - }; - - // The node is the basic data structure which the tree is built from. - typedef struct node_s { - color_e color; // The node's color. - T key; // The node's value, by which nodes are sorted. - union { - struct node_s *left; // For nodes in the tree, the node's left child. - struct node_s *next; // For nodes in the free list, the next node on the free list. - }; - struct node_s *parent; // The node's parent. - struct node_s *right; // The node's right child. - } node_t; - - // Reserve capacity for the tree is allocated in large chunks with room for - // many nodes. - typedef struct chunk_s { - struct chunk_s *next; // Pointer to the next node in the chunk list. - node_t *nodes; // Pointer to an array (of variable size) where nodes are stored. - } chunk_t; - - // Constructor - Tree () - { - m_freelist = NULL; - InitializeCriticalSection(&m_lock); - m_nil.color = black; - m_nil.key = T(); - m_nil.left = &m_nil; - m_nil.parent = &m_nil; - m_nil.right = &m_nil; - m_reserve = TREE_DEFAULT_RESERVE; - m_root = &m_nil; - m_store = NULL; - m_storetail = NULL; - } - - // Copy constructor - The sole purpose of this constructor's existence is - // to ensure that trees are not being inadvertently copied. - Tree (const Tree& source) - { - assert(FALSE); // Do not make copies of trees! - } - - // Destructor - ~Tree () - { - chunk_t *cur; - chunk_t *temp; - - // Free all the chunks in the chunk list. - EnterCriticalSection(&m_lock); - cur = m_store; - while (cur != NULL) { - temp = cur; - cur = cur->next; - delete [] temp->nodes; - delete temp; - } - LeaveCriticalSection(&m_lock); - DeleteCriticalSection(&m_lock); - } - - // operator = - Assignment operator. For efficiency, we want to avoid ever - // making copies of Trees (only pointer passing or reference passing - // should be performed). The sole purpose of this assignment operator is - // to ensure that no copying is being done inadvertently. - // - Tree& operator = (const Tree &other) - { - // Don't make copies of Trees! - assert(FALSE); - return *this; - } - - // begin - Obtains a pointer to the first node (the node with the smallest - // key value) in the tree. - // - // Return Value: - // - // Returns a pointer to the first node in the tree. - // - typename Tree::node_t* begin () const - { - node_t *cur; - - EnterCriticalSection(&m_lock); - if (m_root == &m_nil) { - LeaveCriticalSection(&m_lock); - return NULL; - } - - cur = m_root; - while (cur->left != &m_nil) { - cur = cur->left; - } - LeaveCriticalSection(&m_lock); - - return cur; - } - - // erase - Erases the specified node from the tree. Note that this does - // not cause the key associated with the erased node to be freed. The - // caller is responsible for freeing any dynamically allocated memory - // associated with the key. - // - // - node (IN): Pointer to the node to erase from the tree. - // - // Return Value: - // - // None. - // - VOID erase (typename Tree::node_t *node) - { - node_t *child; - node_t *cur; - node_t *erasure; - node_t *sibling; - - EnterCriticalSection(&m_lock); - - if ((node->left == &m_nil) || (node->right == &m_nil)) { - // The node to be erased has less than two children. It can be directly - // removed from the tree. - erasure = node; - } - else { - // The node to be erased has two children. It can only be removed - // indirectly. The actual node will stay where it is, but it's contents - // will be replaced by it's in-order successor's contents. The successor - // node will then be erased. Find the successor. - erasure = node->right; - while (erasure->left != &m_nil) { - erasure = erasure->left; - } - } - - // Select the child node which will replace the node to be erased. - if (erasure->left != &m_nil) { - child = erasure->left; - } - else { - child = erasure->right; - } - - // Replace the node to be erased with the selected child. - child->parent = erasure->parent; - if (child->parent == &m_nil) { - // The root of the tree is being erased. The child becomes root. - m_root = child; - } - else { - if (erasure == erasure->parent->left) { - erasure->parent->left = child; - } - else { - erasure->parent->right = child; - } - } - - if (erasure != node) { - // The node being erased from the tree is the successor of the actual - // node to be erased. Replace the contents of the node to be erased - // with the successor's contents. - node->key = erasure->key; - } - - if (erasure->color == black) { - // The node being erased from the tree is black. Restructuring of the - // tree may be needed so that black-height is maintained. - cur = child; - while ((cur != m_root) && (cur->color == black)) { - if (cur == cur->parent->left) { - // Current node is a left child. - sibling = cur->parent->right; - if (sibling->color == red) { - // Sibling is red. Rotate sibling up and color it black. - sibling->color = black; - cur->parent->color = red; - _rotateleft(cur->parent); - sibling = cur->parent->right; - } - if ((sibling->left->color == black) && (sibling->right->color == black)) { - // Both of sibling's children are black. Color sibling red. - sibling->color = red; - cur = cur->parent; - } - else { - // At least one of sibling's children is red. - if (sibling->right->color == black) { - sibling->left->color = black; - sibling->color = red; - _rotateright(sibling); - sibling = cur->parent->right; - } - sibling->color = cur->parent->color; - cur->parent->color = black; - sibling->right->color = black; - _rotateleft(cur->parent); - cur = m_root; - } - } - else { - // Current node is a right child. - sibling = cur->parent->left; - if (sibling->color == red) { - // Sibling is red. Rotate sibling up and color it black. - sibling->color = black; - cur->parent->color = red; - _rotateright(cur->parent); - sibling = cur->parent->left; - } - if ((sibling->left->color == black) && (sibling->right->color == black)) { - // Both of sibling's children are black. Color sibling red. - sibling->color = red; - cur = cur->parent; - } - else { - // At least one of sibling's children is red. - if (sibling->left->color == black) { - sibling->right->color = black; - sibling->color = red; - _rotateleft(sibling); - sibling = cur->parent->left; - } - sibling->color = cur->parent->color; - cur->parent->color = black; - sibling->left->color = black; - _rotateright(cur->parent); - cur = m_root; - } - } - } - cur->color = black; - } - - // Put the erased node onto the free list. - erasure->next = m_freelist; - m_freelist = erasure; - - LeaveCriticalSection(&m_lock); - } - - // erase - Erases the specified key from the tree. Note that this does - // not cause the key associated with the erased node to be freed. The - // caller is responsible for freeing any dynamically allocated memory - // associated with the key. - // - // - key (IN): The key to erase from the tree. This value is treated as - // the key for sorting within the tree. It must therefore be of a type - // which supports the "<" operator. - // - // Return Value: - // - // None. - // - VOID erase (const T &key) - { - node_t *node; - - // Find the node to erase. - EnterCriticalSection(&m_lock); - node = m_root; - while (node != &m_nil) { - if (node->key < key) { - // Go right. - node = node->right; - } - else if (key < node->key) { - // Go left. - node = node->left; - } - else { - // Found it. - erase(node); - LeaveCriticalSection(&m_lock); - return; - } - } - LeaveCriticalSection(&m_lock); - - // 'key' is not in the tree. - return; - } - - // find - Obtains a pointer to the node corresponding to the specified key. - // - // - key (IN): The value to search for in the tree. This value is treated - // as the key for sorting within the tree. It must therefore be of a - // type which supports the "<" operator. - // - // Return Value: - // - // Returns a pointer to the node corresponding to the specified key. If - // the key is not in the tree, then "find" returns NULL. - // - typename Tree::node_t* find (const T &key) const - { - node_t *cur; - - EnterCriticalSection(&m_lock); - cur = m_root; - while (cur != &m_nil) { - if (cur->key < key) { - // Go right. - cur = cur->right; - } - else if (key < cur->key) { - // Go left. - cur = cur->left; - } - else { - // Found it. - LeaveCriticalSection(&m_lock); - return cur; - } - } - LeaveCriticalSection(&m_lock); - - // 'key' is not in the tree. - return NULL; - } - - // insert - Inserts a new key into the tree. - // - // - key (IN): The key to insert into the tree. This value is treated as - // the key for sorting within the tree. It must therefore be of a type - // which supports the "<" operator. - // - // Return Value: - // - // Returns a pointer to the node corresponding to the newly inserted - // key. If an attempt is made to insert a key which is already in the - // tree, then NULL is returned and the new key is not inserted. - // - typename Tree::node_t* insert (const T &key) - { - node_t *cur; - node_t *node; - node_t *parent; - node_t *uncle; - - EnterCriticalSection(&m_lock); - - // Find the location where the new node should be inserted.. - cur = m_root; - parent = &m_nil; - while (cur != &m_nil) { - parent = cur; - if (cur->key < key) { - // Go right. - cur = cur->right; - } - else if (key < cur->key) { - // Go left. - cur = cur->left; - } - else { - // Keys in the tree must be unique. - LeaveCriticalSection(&m_lock); - return NULL; - } - } - - // Obtain a new node from the free list. - if (m_freelist == NULL) { - // Allocate additional storage. - reserve(m_reserve); - } - node = m_freelist; - m_freelist = m_freelist->next; - - // Initialize the new node and insert it. - node->color = red; - node->key = key; - node->left = &m_nil; - node->parent = parent; - node->right = &m_nil; - if (parent == &m_nil) { - // The tree is empty. The new node becomes root. - m_root = node; - } - else { - if (parent->key < key) { - // New node is a right child. - parent->right = node; - } - else { - // New node is a left child. - parent->left = node; - } - } - - // Rebalance and/or adjust the tree, if necessary. - cur = node; - while (cur->parent->color == red) { - // Double-red violation. Rebalancing/adjustment needed. - if (cur->parent == cur->parent->parent->left) { - // Parent is the left child. Uncle is the right child. - uncle = cur->parent->parent->right; - if (uncle->color == red) { - // Uncle is red. Recolor. - cur->parent->parent->color = red; - cur->parent->color = black; - uncle->color = black; - cur = cur->parent->parent; - } - else { - // Uncle is black. Restructure. - if (cur == cur->parent->right) { - cur = cur->parent; - _rotateleft(cur); - } - cur->parent->color = black; - cur->parent->parent->color = red; - _rotateright(cur->parent->parent); - } - } - else { - // Parent is the right child. Uncle is the left child. - uncle = cur->parent->parent->left; - if (uncle->color == red) { - // Uncle is red. Recolor. - cur->parent->parent->color = red; - cur->parent->color = black; - uncle->color = black; - cur = cur->parent->parent; - } - else { - // Uncle is black. Restructure. - if (cur == cur->parent->left) { - cur = cur->parent; - _rotateright(cur); - } - cur->parent->color = black; - cur->parent->parent->color = red; - _rotateleft(cur->parent->parent); - } - } - } - - // The root node is always colored black. - m_root->color = black; - - LeaveCriticalSection(&m_lock); - - return node; - } - - // next - Obtains a pointer to the in-order successor of the specified - // node. - // - // - node (IN): Pointer to the node whose in-order successor to retrieve. - // - // Return Value: - // - // Returns a pointer to the node's in-order successor. If the specified - // node corresponds to the largest value in the tree, then the specified - // node has no successor and "next" will return NULL. - // - typename Tree::node_t* next (typename Tree::node_t *node) const - { - node_t* cur; - - if (node == NULL) { - return NULL; - } - - EnterCriticalSection(&m_lock); - if (node->right != &m_nil) { - // 'node' has a right child. Successor is the far left node in - // the right subtree. - cur = node->right; - while (cur->left != &m_nil) { - cur = cur->left; - } - LeaveCriticalSection(&m_lock); - return cur; - } - else if (node->parent != &m_nil) { - // 'node' has no right child, but does have a parent. - if (node == node->parent->left) { - // 'node' is a left child; node's parent is successor. - LeaveCriticalSection(&m_lock); - return node->parent; - } - else { - // 'node' is a right child. - cur = node; - // Go up the tree until we find a parent to the right. - while (cur->parent != &m_nil) { - if (cur == cur->parent->right) { - cur = cur->parent; - continue; - } - else { - LeaveCriticalSection(&m_lock); - return cur->parent; - } - } - - // There is no parent greater than 'node'. 'node' is the - // maximum node. - LeaveCriticalSection(&m_lock); - return NULL; - } - } - else { - // 'node' is root and root is the maximum node. - LeaveCriticalSection(&m_lock); - return NULL; - } - } - - // prev - Obtains a pointer to the in-order predecessor of the specified - // node. - // - // - node (IN): Pointer to the node whose in-order predecessor to retrieve. - // - // Return Value: - // - // Returns a pointer to the node's in-order predecessor. If the specified - // node corresponds to the smallest value in the tree, then the specified - // node has no predecessor and "prev" will return NULL. - // - typename Tree::node_t* prev (typename Tree::node_t *node) const - { - node_t* cur; - - if (node == NULL) { - return NULL; - } - - EnterCriticalSection(&m_lock); - if (node->left != &m_nil) { - // 'node' has left child. Predecessor is the far right node in the - // left subtree. - cur = node->left; - while (cur->right != &m_nil) { - cur = cur->right; - } - LeaveCriticalSection(&m_lock); - return cur; - } - else if (node->parent != & m_nil) { - // 'node' has no left child, but does have a parent. - if (node == node->parent->right) { - // 'node' is a right child; node's parent is predecessor. - LeaveCriticalSection(&m_lock); - return node->parent; - } - else { - // 'node is a left child. - cur = node; - // Go up the tree until we find a parent to the left. - while (cur->parent != &m_nil) { - if (cur == cur->parent->left) { - cur = cur->parent; - continue; - } - else { - LeaveCriticalSection(&m_lock); - return cur->parent; - } - } - - // There is no parent less than 'node'. 'node' is the minimum - // node. - LeaveCriticalSection(&m_lock); - return NULL; - } - } - else { - // 'node' is root and root is the minimum node. - LeaveCriticalSection(&m_lock); - return NULL; - } - } - - // reserve - Reserves storage for a number of nodes in advance and/or sets - // the number of nodes for which the tree will automatically reserve - // storage when the tree needs to "grow" to accomodate new values being - // inserted into the tree. If this function is not called to set the - // reserve size to a specific value, then a pre-determined default value - // will be used. If this function is called when the tree currently has - // no reserve storage, then in addition to setting the tree's reserve - // value, it will also cause the tree to immediately reserve the - // specified amount of storage. - // - // - count (IN): The number of individual nodes' worth of storage to - // reserve. - // - // Return Value: - // - // Returns the previously defined reserve value. - // - UINT32 reserve (UINT32 count) - { - chunk_t *chunk; - UINT32 index; - UINT32 oldreserve = m_reserve; - - if (count != m_reserve) { - if (count < 1) { - // Minimum reserve size is 1. - m_reserve = 1; - } - else { - m_reserve = count; - } - } - - EnterCriticalSection(&m_lock); - if (m_freelist == NULL) { - // Allocate additional storage. - // Link a new chunk into the chunk list. - chunk = new Tree::chunk_t; - chunk->nodes = new Tree::node_s [m_reserve]; - chunk->next = NULL; - if (m_store == NULL) { - m_store = chunk; - } - else { - m_storetail->next = chunk; - } - m_storetail = chunk; - - // Link the individual nodes together to form a new free list. - for (index = 0; index < m_reserve - 1; index++) { - chunk->nodes[index].next = &chunk->nodes[index + 1]; - } - chunk->nodes[index].next = NULL; - m_freelist = chunk->nodes; - } - LeaveCriticalSection(&m_lock); - - return oldreserve; - } - -private: - // _rotateleft: Rotates a pair of nodes counter-clockwise so that the parent - // node becomes the left child and the right child becomes the parent. - // - // - parent (IN): Pointer to the parent to rotate about. - // - // Return Value: - // - // None. - // - VOID _rotateleft (typename Tree::node_t *parent) - { - node_t *child = parent->right; - - // Reassign the child's left subtree to the parent. - parent->right = child->left; - if (child->left != &m_nil) { - child->left->parent = parent; - } - - // Reassign the child/parent relationship. - child->parent = parent->parent; - if (parent->parent == &m_nil) { - // The child becomes the new root node. - m_root = child; - } - else { - // Point the grandparent at the child. - if (parent == parent->parent->left) { - parent->parent->left = child; - } - else { - parent->parent->right = child; - } - } - child->left = parent; - parent->parent = child; - } - - // _rotateright - Rotates a pair of nodes clockwise so that the parent node - // becomes the right child and the left child becomes the parent. - // - // - parent (IN): Pointer to the parent to rotate about. - // - // Return Value: - // - // None. - // - VOID _rotateright (typename Tree::node_t *parent) - { - node_t *child = parent->left; - - // Reassign the child's right subtree to the parent. - parent->left = child->right; - if (child->right != &m_nil) { - child->right->parent = parent; - } - - // Reassign the child/parent relationship. - child->parent = parent->parent; - if (parent->parent == &m_nil) { - // The child becomes the new root node. - m_root = child; - } - else { - // Point the grandparent at the child. - if (parent == parent->parent->left) { - parent->parent->left = child; - } - else { - parent->parent->right = child; - } - } - child->right = parent; - parent->parent = child; - } - - // Private data members. - node_t *m_freelist; // Pointer to the list of free nodes (reserve storage). - mutable CRITICAL_SECTION m_lock; // Protects the tree's integrity against concurrent accesses. - node_t m_nil; // The tree's nil node. All leaf nodes point to this. - UINT32 m_reserve; // The size (in nodes) of the chunks of reserve storage. - node_t *m_root; // Pointer to the tree's root node. - chunk_t *m_store; // Pointer to the start of the chunk list. - chunk_t *m_storetail; // Pointer to the end of the chunk list. -}; +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - Red-black Tree Template +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef VLDBUILD +#error \ +"This header should only be included by Visual Leak Detector when building it from source. \ +Applications should never include this header." +#endif + +#include "vldheap.h" // Provides internal new and delete operators. +#include "criticalsection.h" + +#define TREE_DEFAULT_RESERVE 32 // By default, trees reserve enough space, in advance, for this many nodes. + +//////////////////////////////////////////////////////////////////////////////// +// +// The Tree Template Class +// +// This data structure is the internal data structure behind the lightweight +// STL-like container classes. This is a red-black tree which provides for +// fast insert, find, and erase operations. +// +// The binary tree nodes are overlaid on top of larger chunks of allocated +// memory (called chunks) which are arranged in a simple linked list. This +// allows the tree to grow (add nodes) dynamically without incurring a heap +// hit each time a new node is added. +// +// The Tree class provides member functions which make it easily adaptable to +// an STL-like interface so that it can be used as the backend for STL-like +// container classes. +// +template +class Tree +{ +public: + // This is a red-black tree. + enum color_e { + red, + black + }; + + // The node is the basic data structure which the tree is built from. + struct node_t { + color_e color; // The node's color. + T key; // The node's value, by which nodes are sorted. + union { + struct node_t *left; // For nodes in the tree, the node's left child. + struct node_t *next; // For nodes in the free list, the next node on the free list. + }; + struct node_t *parent; // The node's parent. + struct node_t *right; // The node's right child. + }; + + // Reserve capacity for the tree is allocated in large chunks with room for + // many nodes. + struct chunk_t { + struct chunk_t *next; // Pointer to the next node in the chunk list. + node_t *nodes; // Pointer to an array (of variable size) where nodes are stored. + }; + + // Constructor + Tree () + { + m_freelist = NULL; + m_lock.Initialize(); + m_nil.color = black; + m_nil.key = T(); + m_nil.left = &m_nil; + m_nil.parent = &m_nil; + m_nil.right = &m_nil; + m_reserve = TREE_DEFAULT_RESERVE; + m_root = &m_nil; + m_store = NULL; + m_storetail = NULL; + } + + // Copy constructor - The sole purpose of this constructor's existence is + // to ensure that trees are not being inadvertently copied. + Tree (const Tree& source) + { + assert(FALSE); // Do not make copies of trees! + } + + // Destructor + ~Tree () + { + chunk_t *cur; + chunk_t *temp; + + // Free all the chunks in the chunk list. + m_lock.Enter(); + cur = m_store; + while (cur != NULL) { + temp = cur; + cur = cur->next; + delete [] temp->nodes; + delete temp; + } + m_lock.Leave(); + + m_lock.Delete(); + } + + // operator = - Assignment operator. For efficiency, we want to avoid ever + // making copies of Trees (only pointer passing or reference passing + // should be performed). The sole purpose of this assignment operator is + // to ensure that no copying is being done inadvertently. + // + Tree& operator = (const Tree &other) + { + // Don't make copies of Trees! + assert(FALSE); + return *this; + } + + // begin - Obtains a pointer to the first node (the node with the smallest + // key value) in the tree. + // + // Return Value: + // + // Returns a pointer to the first node in the tree. + // + typename Tree::node_t* begin () const + { + node_t *cur; + + CriticalSectionLocker<> cs(m_lock); + if (m_root == &m_nil) { + return NULL; + } + + cur = m_root; + while (cur->left != &m_nil) { + cur = cur->left; + } + + return cur; + } + + // erase - Erases the specified node from the tree. Note that this does + // not cause the key associated with the erased node to be freed. The + // caller is responsible for freeing any dynamically allocated memory + // associated with the key. + // + // - node (IN): Pointer to the node to erase from the tree. + // + // Return Value: + // + // None. + // + VOID erase (typename Tree::node_t *node) + { + node_t *child; + node_t *cur; + node_t *erasure; + node_t *sibling; + + CriticalSectionLocker<> cs(m_lock); + + if ((node->left == &m_nil) || (node->right == &m_nil)) { + // The node to be erased has less than two children. It can be directly + // removed from the tree. + erasure = node; + } + else { + // The node to be erased has two children. It can only be removed + // indirectly. The actual node will stay where it is, but it's contents + // will be replaced by it's in-order successor's contents. The successor + // node will then be erased. Find the successor. + erasure = node->right; + while (erasure->left != &m_nil) { + erasure = erasure->left; + } + } + + // Select the child node which will replace the node to be erased. + if (erasure->left != &m_nil) { + child = erasure->left; + } + else { + child = erasure->right; + } + + // Replace the node to be erased with the selected child. + child->parent = erasure->parent; + if (child->parent == &m_nil) { + // The root of the tree is being erased. The child becomes root. + m_root = child; + } + else { + if (erasure == erasure->parent->left) { + erasure->parent->left = child; + } + else { + erasure->parent->right = child; + } + } + + if (erasure != node) { + // The node being erased from the tree is the successor of the actual + // node to be erased. Replace the contents of the node to be erased + // with the successor's contents. + node->key = erasure->key; + } + + if (erasure->color == black) { + // The node being erased from the tree is black. Restructuring of the + // tree may be needed so that black-height is maintained. + cur = child; + while ((cur != m_root) && (cur->color == black)) { + if (cur == cur->parent->left) { + // Current node is a left child. + sibling = cur->parent->right; + if (sibling->color == red) { + // Sibling is red. Rotate sibling up and color it black. + sibling->color = black; + cur->parent->color = red; + _rotateleft(cur->parent); + sibling = cur->parent->right; + } + if ((sibling->left->color == black) && (sibling->right->color == black)) { + // Both of sibling's children are black. Color sibling red. + sibling->color = red; + cur = cur->parent; + } + else { + // At least one of sibling's children is red. + if (sibling->right->color == black) { + sibling->left->color = black; + sibling->color = red; + _rotateright(sibling); + sibling = cur->parent->right; + } + sibling->color = cur->parent->color; + cur->parent->color = black; + sibling->right->color = black; + _rotateleft(cur->parent); + cur = m_root; + } + } + else { + // Current node is a right child. + sibling = cur->parent->left; + if (sibling->color == red) { + // Sibling is red. Rotate sibling up and color it black. + sibling->color = black; + cur->parent->color = red; + _rotateright(cur->parent); + sibling = cur->parent->left; + } + if ((sibling->left->color == black) && (sibling->right->color == black)) { + // Both of sibling's children are black. Color sibling red. + sibling->color = red; + cur = cur->parent; + } + else { + // At least one of sibling's children is red. + if (sibling->left->color == black) { + sibling->right->color = black; + sibling->color = red; + _rotateleft(sibling); + sibling = cur->parent->left; + } + sibling->color = cur->parent->color; + cur->parent->color = black; + sibling->left->color = black; + _rotateright(cur->parent); + cur = m_root; + } + } + } + cur->color = black; + } + + // Put the erased node onto the free list. + erasure->next = m_freelist; + m_freelist = erasure; + } + + // erase - Erases the specified key from the tree. Note that this does + // not cause the key associated with the erased node to be freed. The + // caller is responsible for freeing any dynamically allocated memory + // associated with the key. + // + // - key (IN): The key to erase from the tree. This value is treated as + // the key for sorting within the tree. It must therefore be of a type + // which supports the "<" operator. + // + // Return Value: + // + // None. + // + VOID erase (const T &key) + { + node_t *node; + + // Find the node to erase. + CriticalSectionLocker<> cs(m_lock); + node = m_root; + while (node != &m_nil) { + if (node->key < key) { + // Go right. + node = node->right; + } + else if (key < node->key) { + // Go left. + node = node->left; + } + else { + // Found it. + erase(node); + return; + } + } + + // 'key' is not in the tree. + } + + // find - Obtains a pointer to the node corresponding to the specified key. + // + // - key (IN): The value to search for in the tree. This value is treated + // as the key for sorting within the tree. It must therefore be of a + // type which supports the "<" operator. + // + // Return Value: + // + // Returns a pointer to the node corresponding to the specified key. If + // the key is not in the tree, then "find" returns NULL. + // + typename Tree::node_t* find (const T &key) const + { + node_t *cur; + + CriticalSectionLocker<> cs(m_lock); + cur = m_root; + while (cur != &m_nil) { + if (cur->key < key) { + // Go right. + cur = cur->right; + } + else if (key < cur->key) { + // Go left. + cur = cur->left; + } + else { + // Found it. + return cur; + } + } + + // 'key' is not in the tree. + return NULL; + } + + // insert - Inserts a new key into the tree. + // + // - key (IN): The key to insert into the tree. This value is treated as + // the key for sorting within the tree. It must therefore be of a type + // which supports the "<" operator. + // + // Return Value: + // + // Returns a pointer to the node corresponding to the newly inserted + // key. If an attempt is made to insert a key which is already in the + // tree, then NULL is returned and the new key is not inserted. + // + typename Tree::node_t* insert (const T &key) + { + CriticalSectionLocker<> cs(m_lock); + + // Find the location where the new node should be inserted.. + node_t *cur = m_root; + node_t *parent = &m_nil; + while (cur != &m_nil) { + parent = cur; + if (cur->key < key) { + // Go right. + cur = cur->right; + } + else if (key < cur->key) { + // Go left. + cur = cur->left; + } + else { + // Keys in the tree must be unique. + return NULL; + } + } + + // Obtain a new node from the free list. + if (m_freelist == NULL) { + // Allocate additional storage. + reserve(m_reserve); + } + node_t *node = m_freelist; + m_freelist = m_freelist->next; + + // Initialize the new node and insert it. + node->color = red; + node->key = key; + node->left = &m_nil; + node->parent = parent; + node->right = &m_nil; + if (parent == &m_nil) { + // The tree is empty. The new node becomes root. + m_root = node; + } + else { + if (parent->key < key) { + // New node is a right child. + parent->right = node; + } + else { + // New node is a left child. + parent->left = node; + } + } + + // Rebalance and/or adjust the tree, if necessary. + cur = node; + node_t *uncle; + while (cur->parent->color == red) { + // Double-red violation. Rebalancing/adjustment needed. + if (cur->parent == cur->parent->parent->left) { + // Parent is the left child. Uncle is the right child. + uncle = cur->parent->parent->right; + if (uncle->color == red) { + // Uncle is red. Recolor. + cur->parent->parent->color = red; + cur->parent->color = black; + uncle->color = black; + cur = cur->parent->parent; + } + else { + // Uncle is black. Restructure. + if (cur == cur->parent->right) { + cur = cur->parent; + _rotateleft(cur); + } + cur->parent->color = black; + cur->parent->parent->color = red; + _rotateright(cur->parent->parent); + } + } + else { + // Parent is the right child. Uncle is the left child. + uncle = cur->parent->parent->left; + if (uncle->color == red) { + // Uncle is red. Recolor. + cur->parent->parent->color = red; + cur->parent->color = black; + uncle->color = black; + cur = cur->parent->parent; + } + else { + // Uncle is black. Restructure. + if (cur == cur->parent->left) { + cur = cur->parent; + _rotateright(cur); + } + cur->parent->color = black; + cur->parent->parent->color = red; + _rotateleft(cur->parent->parent); + } + } + } + + // The root node is always colored black. + m_root->color = black; + return node; + } + + // next - Obtains a pointer to the in-order successor of the specified + // node. + // + // - node (IN): Pointer to the node whose in-order successor to retrieve. + // + // Return Value: + // + // Returns a pointer to the node's in-order successor. If the specified + // node corresponds to the largest value in the tree, then the specified + // node has no successor and "next" will return NULL. + // + typename Tree::node_t* next (typename Tree::node_t *node) const + { + if (node == NULL) + return NULL; + + CriticalSectionLocker<> cs(m_lock); + node_t* cur; + if (node->right != &m_nil) { + // 'node' has a right child. Successor is the far left node in + // the right subtree. + cur = node->right; + while (cur->left != &m_nil) { + cur = cur->left; + } + return cur; + } + else if (node->parent != &m_nil) { + // 'node' has no right child, but does have a parent. + if (node == node->parent->left) { + // 'node' is a left child; node's parent is successor. + return node->parent; + } + else { + // 'node' is a right child. + cur = node; + // Go up the tree until we find a parent to the right. + while (cur->parent != &m_nil) { + if (cur == cur->parent->right) { + cur = cur->parent; + continue; + } + else { + return cur->parent; + } + } + + // There is no parent greater than 'node'. 'node' is the + // maximum node. + return NULL; + } + } + else { + // 'node' is root and root is the maximum node. + return NULL; + } + } + + // prev - Obtains a pointer to the in-order predecessor of the specified + // node. + // + // - node (IN): Pointer to the node whose in-order predecessor to retrieve. + // + // Return Value: + // + // Returns a pointer to the node's in-order predecessor. If the specified + // node corresponds to the smallest value in the tree, then the specified + // node has no predecessor and "prev" will return NULL. + // + typename Tree::node_t* prev (typename Tree::node_t *node) const + { + if (node == NULL) { + return NULL; + } + + CriticalSectionLocker<> cs(m_lock); + node_t* cur; + if (node->left != &m_nil) { + // 'node' has left child. Predecessor is the far right node in the + // left subtree. + cur = node->left; + while (cur->right != &m_nil) { + cur = cur->right; + } + return cur; + } + else if (node->parent != & m_nil) { + // 'node' has no left child, but does have a parent. + if (node == node->parent->right) { + // 'node' is a right child; node's parent is predecessor. + return node->parent; + } + else { + // 'node is a left child. + cur = node; + // Go up the tree until we find a parent to the left. + while (cur->parent != &m_nil) { + if (cur == cur->parent->left) { + cur = cur->parent; + continue; + } + else { + return cur->parent; + } + } + + // There is no parent less than 'node'. 'node' is the minimum + // node. + return NULL; + } + } + else { + // 'node' is root and root is the minimum node. + return NULL; + } + } + + // reserve - Reserves storage for a number of nodes in advance and/or sets + // the number of nodes for which the tree will automatically reserve + // storage when the tree needs to "grow" to accomodate new values being + // inserted into the tree. If this function is not called to set the + // reserve size to a specific value, then a pre-determined default value + // will be used. If this function is called when the tree currently has + // no reserve storage, then in addition to setting the tree's reserve + // value, it will also cause the tree to immediately reserve the + // specified amount of storage. + // + // - count (IN): The number of individual nodes' worth of storage to + // reserve. + // + // Return Value: + // + // Returns the previously defined reserve value. + // + size_t reserve (size_t count) + { + chunk_t *chunk; + size_t index; + size_t oldreserve = m_reserve; + + if (count != m_reserve) { + if (count < 1) { + // Minimum reserve size is 1. + m_reserve = 1; + } + else { + m_reserve = count; + } + } + + CriticalSectionLocker<> cs(m_lock); + if (m_freelist == NULL) { + // Allocate additional storage. + // Link a new chunk into the chunk list. + chunk = new Tree::chunk_t; + chunk->nodes = new Tree::node_t [m_reserve]; + chunk->next = NULL; + if (m_store == NULL) { + m_store = chunk; + } + else { + m_storetail->next = chunk; + } + m_storetail = chunk; + + // Link the individual nodes together to form a new free list. + for (index = 0; index < m_reserve - 1; index++) { + chunk->nodes[index].next = &chunk->nodes[index + 1]; + } + chunk->nodes[index].next = NULL; + m_freelist = chunk->nodes; + } + + return oldreserve; + } + +private: + // _rotateleft: Rotates a pair of nodes counter-clockwise so that the parent + // node becomes the left child and the right child becomes the parent. + // + // - parent (IN): Pointer to the parent to rotate about. + // + // Return Value: + // + // None. + // + VOID _rotateleft (typename Tree::node_t *parent) + { + node_t *child = parent->right; + + // Reassign the child's left subtree to the parent. + parent->right = child->left; + if (child->left != &m_nil) { + child->left->parent = parent; + } + + // Reassign the child/parent relationship. + child->parent = parent->parent; + if (parent->parent == &m_nil) { + // The child becomes the new root node. + m_root = child; + } + else { + // Point the grandparent at the child. + if (parent == parent->parent->left) { + parent->parent->left = child; + } + else { + parent->parent->right = child; + } + } + child->left = parent; + parent->parent = child; + } + + // _rotateright - Rotates a pair of nodes clockwise so that the parent node + // becomes the right child and the left child becomes the parent. + // + // - parent (IN): Pointer to the parent to rotate about. + // + // Return Value: + // + // None. + // + VOID _rotateright (typename Tree::node_t *parent) + { + node_t *child = parent->left; + + // Reassign the child's right subtree to the parent. + parent->left = child->right; + if (child->right != &m_nil) { + child->right->parent = parent; + } + + // Reassign the child/parent relationship. + child->parent = parent->parent; + if (parent->parent == &m_nil) { + // The child becomes the new root node. + m_root = child; + } + else { + // Point the grandparent at the child. + if (parent == parent->parent->left) { + parent->parent->left = child; + } + else { + parent->parent->right = child; + } + } + child->right = parent; + parent->parent = child; + } + + // Private data members. + node_t *m_freelist; // Pointer to the list of free nodes (reserve storage). + mutable CriticalSection m_lock; // Protects the tree's integrity against concurrent accesses. + node_t m_nil; // The tree's nil node. All leaf nodes point to this. + size_t m_reserve; // The size (in nodes) of the chunks of reserve storage. + node_t *m_root; // Pointer to the tree's root node. + chunk_t *m_store; // Pointer to the start of the chunk list. + chunk_t *m_storetail; // Pointer to the end of the chunk list. +}; diff --git a/src/utility.cpp b/src/utility.cpp new file mode 100644 index 00000000..e3c32fe4 --- /dev/null +++ b/src/utility.cpp @@ -0,0 +1,1267 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - Various Utility Functions +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#define VLDBUILD // Declares that we are building Visual Leak Detector. +#include "utility.h" // Provides various utility functions and macros. +#include "vldheap.h" // Provides internal new and delete operators. +#include "vldint.h" +#include +#include + +//#define PRINTHOOKINFO + +// Imported Global Variables +extern ReportHookSet* g_pReportHooks; +extern VisualLeakDetector g_vld; +extern ImageDirectoryEntries g_Ide; + +// Global variables. +static BOOL s_reportDelay = FALSE; // If TRUE, we sleep for a bit after calling OutputDebugString to give the debugger time to catch up. +static FILE *s_reportFile = NULL; // Pointer to the file, if any, to send the memory leak report to. +static BOOL s_reportToDebugger = TRUE; // If TRUE, a copy of the memory leak report will be sent to the debugger for display. +static BOOL s_reportToStdOut = TRUE; // If TRUE, a copy of the memory leak report will be sent to standard output. +static encoding_e s_reportEncoding = ascii; // Output encoding of the memory leak report. + +#define IS_ORDINAL(name) (((UINT_PTR)name & 0xFFFF) == ((UINT_PTR)name)) + +// DumpMemoryA - Dumps a nicely formatted rendition of a region of memory. +// Includes both the hex value of each byte and its ASCII equivalent (if +// printable). +// +// - address (IN): Pointer to the beginning of the memory region to dump. +// +// - size (IN): The size, in bytes, of the region to dump. +// +// Return Value: +// +// None. +// +VOID DumpMemoryA (LPCVOID address, SIZE_T size) +{ + // Each line of output is 16 bytes. + SIZE_T dumpLen; + if ((size % 16) == 0) { + // No padding needed. + dumpLen = size; + } + else { + // We'll need to pad the last line out to 16 bytes. + dumpLen = size + (16 - (size % 16)); + } + + // For each byte of data, get both the ASCII equivalent (if it is a + // printable character) and the hex representation. + SIZE_T bytesDone = 0; + WCHAR hexDump [HEXDUMPLINELENGTH] = {0}; + WCHAR ascDump [18] = {0}; + WCHAR formatBuf [BYTEFORMATBUFFERLENGTH]; + for (SIZE_T byteIndex = 0; byteIndex < dumpLen; byteIndex++) { + SIZE_T wordIndex = byteIndex % 16; + SIZE_T hexIndex = 3 * (wordIndex + (wordIndex / 4)); // 3 characters per byte, plus a 3-character space after every 4 bytes. + SIZE_T ascIndex = wordIndex + wordIndex / 8; // 1 character per byte, plus a 1-character space after every 8 bytes. + if (byteIndex < size) { + BYTE byte = ((PBYTE)address)[byteIndex]; + _snwprintf_s(formatBuf, BYTEFORMATBUFFERLENGTH, _TRUNCATE, L"%.2X ", byte); + formatBuf[3] = '\0'; + wcsncpy_s(hexDump + hexIndex, HEXDUMPLINELENGTH - hexIndex, formatBuf, 4); + if (isgraph(byte)) { + ascDump[ascIndex] = (WCHAR)byte; + } + else { + ascDump[ascIndex] = L'.'; + } + } + else { + // Add padding to fill out the last line to 16 bytes. + wcsncpy_s(hexDump + hexIndex, HEXDUMPLINELENGTH - hexIndex, L" ", 4); + ascDump[ascIndex] = L'.'; + } + bytesDone++; + if ((bytesDone % 16) == 0) { + // Print one line of data for every 16 bytes. Include the + // ASCII dump and the hex dump side-by-side. + Report(L" %s %s\n", hexDump, ascDump); + } + else { + if ((bytesDone % 8) == 0) { + // Add a spacer in the ASCII dump after every 8 bytes. + ascDump[ascIndex + 1] = L' '; + } + if ((bytesDone % 4) == 0) { + // Add a spacer in the hex dump after every 4 bytes. + wcsncpy_s(hexDump + hexIndex + 3, HEXDUMPLINELENGTH - hexIndex - 3, L" ", 4); + } + } + } +} + +// DumpMemoryW - Dumps a nicely formatted rendition of a region of memory. +// Includes both the hex value of each byte and its Unicode equivalent. +// +// - address (IN): Pointer to the beginning of the memory region to dump. +// +// - size (IN): The size, in bytes, of the region to dump. +// +// Return Value: +// +// None. +// +VOID DumpMemoryW (LPCVOID address, SIZE_T size) +{ + // Each line of output is 16 bytes. + SIZE_T dumpLen; + if ((size % 16) == 0) { + // No padding needed. + dumpLen = size; + } + else { + // We'll need to pad the last line out to 16 bytes. + dumpLen = size + (16 - (size % 16)); + } + + // For each word of data, get both the Unicode equivalent and the hex + // representation. + WCHAR formatBuf [BYTEFORMATBUFFERLENGTH]; + WCHAR hexDump [HEXDUMPLINELENGTH] = {0}; + WCHAR unidump [18] = {0}; + SIZE_T bytesDone = 0; + for (SIZE_T byteIndex = 0; byteIndex < dumpLen; byteIndex++) { + SIZE_T hexIndex = 3 * ((byteIndex % 16) + ((byteIndex % 16) / 4)); // 3 characters per byte, plus a 3-character space after every 4 bytes. + SIZE_T uniIndex = ((byteIndex / 2) % 8) + ((byteIndex / 2) % 8) / 8; // 1 character every other byte, plus a 1-character space after every 8 bytes. + if (byteIndex < size) { + BYTE byte = ((PBYTE)address)[byteIndex]; + _snwprintf_s(formatBuf, BYTEFORMATBUFFERLENGTH, _TRUNCATE, L"%.2X ", byte); + formatBuf[BYTEFORMATBUFFERLENGTH - 1] = '\0'; + wcsncpy_s(hexDump + hexIndex, HEXDUMPLINELENGTH - hexIndex, formatBuf, 4); + if (((byteIndex % 2) == 0) && ((byteIndex + 1) < dumpLen)) { + // On every even byte, print one character. + WORD word = ((PWORD)address)[byteIndex / 2]; + if ((word == 0x0000) || (word == 0x0020)) { + unidump[uniIndex] = L'.'; + } + else { + unidump[uniIndex] = word; + } + } + } + else { + // Add padding to fill out the last line to 16 bytes. + wcsncpy_s(hexDump + hexIndex, HEXDUMPLINELENGTH - hexIndex, L" ", 4); + unidump[uniIndex] = L'.'; + } + bytesDone++; + if ((bytesDone % 16) == 0) { + // Print one line of data for every 16 bytes. Include the + // ASCII dump and the hex dump side-by-side. + Report(L" %s %s\n", hexDump, unidump); + } + else { + if ((bytesDone % 8) == 0) { + // Add a spacer in the ASCII dump after every 8 bytes. + unidump[uniIndex + 1] = L' '; + } + if ((bytesDone % 4) == 0) { + // Add a spacer in the hex dump after every 4 bytes. + wcsncpy_s(hexDump + hexIndex + 3, HEXDUMPLINELENGTH - hexIndex - 3, L" ", 4); + } + } + } +} + +// FilterFunction - Used in structured exception handling +DWORD FilterFunction(long) +{ + return EXCEPTION_CONTINUE_SEARCH; +} + +// FindOriginalImportDescriptor - Determines if the specified module imports the named import +// from the named exporting module. +// +// - importmodule (IN): Handle (base address) of the module to be searched to +// see if it imports the specified import. +// +// - exportmodulename (IN): ANSI string containing the name of the module that +// exports the import to be searched for. +// +// Return Value: +// +// Returns pointer to descriptor. +// +IMAGE_IMPORT_DESCRIPTOR* FindOriginalImportDescriptor (HMODULE importmodule, LPCSTR exportmodulename) +{ + IMAGE_IMPORT_DESCRIPTOR* idte = NULL; + IMAGE_SECTION_HEADER* section = NULL; + ULONG size = 0; + + // Locate the importing module's Import Directory Table (IDT) entry for the + // exporting module. The importing module actually can have several IATs -- + // one for each export module that it imports something from. The IDT entry + // gives us the offset of the IAT for the module we are interested in. + { + idte = (IMAGE_IMPORT_DESCRIPTOR*)g_Ide.ImageDirectoryEntryToDataEx((PVOID)GetCallingModule((UINT_PTR)importmodule), TRUE, + IMAGE_DIRECTORY_ENTRY_IMPORT, &size, §ion); + } + + if (idte == NULL) { + // This module has no IDT (i.e. it imports nothing). + return NULL; + } + while (idte->OriginalFirstThunk != 0x0) { + PCHAR name = (PCHAR)R2VA(importmodule, idte->Name); + if (_stricmp(name, exportmodulename) == 0) { + // Found the IDT entry for the exporting module. + break; + } + idte++; + } + if (idte->OriginalFirstThunk == 0x0) { + // The importing module does not import anything from the exporting + // module. + return NULL; + } + return idte; +} + +// FindImport - Determines if the specified module imports the named import +// from the named exporting module. +// +// - importmodule (IN): Handle (base address) of the module to be searched to +// see if it imports the specified import. +// +// - exportmodule (IN): Handle (base address) of the module that exports the +// import to be searched for. +// +// - exportmodulename (IN): ANSI string containing the name of the module that +// exports the import to be searched for. +// +// - importname (IN): ANSI string containing the name of the import to search +// for. May be an integer cast to a string if the import is exported by +// ordinal. +// +// Return Value: +// +// Returns TRUE if the module imports to the specified import. Otherwise +// returns FALSE. +// +BOOL FindImport (HMODULE importmodule, HMODULE exportmodule, LPCSTR exportmodulename, LPCSTR importname) +{ + IMAGE_IMPORT_DESCRIPTOR *idte; + IMAGE_THUNK_DATA *iate; + FARPROC import; + + DbgTrace(L"dbghelp32.dll %i: FindImport - ImageDirectoryEntryToDataEx\n", GetCurrentThreadId()); + idte = FindOriginalImportDescriptor(importmodule, exportmodulename); + if (idte == NULL) + return FALSE; + + // Get the *real* address of the import. If we find this address in the IAT, + // then we've found that the module does import the named import. + import = GetProcAddress(exportmodule, importname); + + // Perhaps the named export module does not actually export the named import? + //assert(import != NULL); - on my Windows 7 x64, VS 9 SP1, Win x32 project assertion failure will cause new DLL loading, and then infinite loop of calls to findimport() and stack overflow. Maybe it's caused by antivirus, nevertheless this solution fixes infinite loop + if ( import == NULL ) // - instead of assert + { + OutputDebugStringW(__FUNCTIONW__ L"(" __FILEW__ L") : import == NULL\n" ); + if ( ::IsDebuggerPresent() ) + __debugbreak(); + + return FALSE; + } + + // Locate the import's IAT entry. + iate = (IMAGE_THUNK_DATA*)R2VA(importmodule, idte->FirstThunk); + while (iate->u1.Function != 0x0) { + if (iate->u1.Function == (DWORD_PTR)import) { + // Found the IAT entry. The module imports the named import. + return TRUE; + } + iate++; + } + + // The module does not import the named import. + return FALSE; +} + +// FindPatch - Determines if the specified module has been patched to use the +// specified replacement. +// +// - importmodule (IN): Handle (base address) of the module to be searched to +// see if it imports the specified replacement export. +// +// - exportmodulename (IN): ANSI string containing the name of the module that +// normally exports that import that would have been patched to use the +// replacement export. +// +// - replacement (IN): Address of the replacement, or destination, function or +// variable to search for. +// +// Return Value: +// +// Returns TRUE if the module has been patched to use the specified +// replacement export. +// +BOOL FindPatch (HMODULE importmodule, moduleentry_t *module) +{ + IMAGE_IMPORT_DESCRIPTOR *idte; + + idte = FindOriginalImportDescriptor(importmodule, module->exportModuleName); + if (idte == NULL) + return FALSE; + + int i = 0; + patchentry_t *entry = module->patchTable; + while(entry->importName) + { + LPCVOID replacement = entry->replacement; + + IMAGE_THUNK_DATA *iate; + + // Locate the replacement's IAT entry. + iate = (IMAGE_THUNK_DATA*)R2VA(importmodule, idte->FirstThunk); + while (iate->u1.Function != 0x0) { + if (iate->u1.Function == (DWORD_PTR)replacement) { + // Found the IAT entry for the replacement. This patch has been + // installed. + return TRUE; + } + iate++; + } + entry++; i++; + } + + // The module does not import the replacement. The patch has not been + // installed. + return FALSE; +} + +// InsertReportDelay - Sets the report function to sleep for a bit after each +// call to OutputDebugString, in order to allow the debugger to catch up. +// +// Return Value: +// +// None. +// +VOID InsertReportDelay () +{ + s_reportDelay = TRUE; +} + +// ConvertModulePathToAscii - Convert module path to ascii encoding. +void ConvertModulePathToAscii( LPCWSTR modulename, LPSTR * modulenamea ) +{ + size_t length = ::WideCharToMultiByte(CP_ACP, 0, modulename, -1, 0, 0, 0, 0); + *modulenamea = new CHAR [length]; + + // wcstombs_s requires locale to be already set up correctly, but it might not be correct on vld init step. So use WideCharToMultiByte instead + CHAR defaultChar = '?'; + BOOL defaultCharUsed = FALSE; + + int count = ::WideCharToMultiByte(CP_ACP, 0/*flags*/, modulename, (int)-1, *modulenamea, (int)length, &defaultChar, &defaultCharUsed); + assert(count != 0); + if ( defaultCharUsed ) + { + ::OutputDebugStringW(__FILEW__ L": " __FUNCTIONW__ L" - defaultChar was used while conversion from \""); + ::OutputDebugStringW(modulename); + ::OutputDebugStringW(L"\" to ANSI \""); + ::OutputDebugStringA(*modulenamea); + ::OutputDebugStringW(L"\". Result can be wrong.\n"); + } +} + +// IsModulePatched - Checks to see if any of the imports listed in the specified +// patch table have been patched into the specified importmodule. +// +// - importmodule (IN): Handle (base address) of the module to be queried to +// determine if it has been patched. +// +// - patchtable (IN): An array of patchentry_t structures specifying all of the +// import patches to search for. +// +// - tablesize (IN): Size, in entries, of the specified patch table. +// +// Return Value: +// +// Returns TRUE if at least one of the patches listed in the patch table is +// installed in the importmodule. Otherwise returns FALSE. +// +BOOL IsModulePatched (HMODULE importmodule, moduleentry_t patchtable [], UINT tablesize) +{ + // Loop through the import patch table, individually checking each patch + // entry to see if it is installed in the import module. If any patch entry + // is installed in the import module, then the module has been patched. + BOOL found = FALSE; + for (UINT index = 0; index < tablesize; index++) { + moduleentry_t *entry = &patchtable[index]; + found = FindPatch(importmodule, entry); + if (found) { + // Found one of the listed patches installed in the import module. + return TRUE; + } + } + + // No patches listed in the patch table were found in the import module. + return FALSE; +} + +LPVOID FindRealCode(LPVOID pCode) +{ + LPVOID result = pCode; + if (pCode != NULL) + { + if (*(WORD *)pCode == 0x25ff) // JMP r/m32 + { +#ifdef _WIN64 + LONG offset = *((LONG *)((ULONG_PTR)pCode + 2)); + // RIP relative addressing + PBYTE pNextInst = (PBYTE)((ULONG_PTR)pCode + 6); + pCode = *(LPVOID*)(pNextInst + offset); + return pCode; +#else + DWORD addr = *((DWORD *)((ULONG_PTR)pCode + 2)); + pCode = *(LPVOID*)(addr); + return FindRealCode(pCode); +#endif + } + if (*(BYTE *)pCode == 0xE9) // JMP rel32 + { + // Relative next instruction + PBYTE pNextInst = (PBYTE)((ULONG_PTR)pCode + 5); + LONG offset = *((LONG *)((ULONG_PTR)pCode + 1)); + pCode = (LPVOID*)(pNextInst + offset); + return FindRealCode(pCode); + } + } + return result; +} + +// PatchImport - Patches all future calls to an imported function, or references +// to an imported variable, through to a replacement function or variable. +// Patching is done by replacing the import's address in the specified target +// module's Import Address Table (IAT) with the address of the replacement +// function or variable. +// +// - importmodule (IN): Handle (base address) of the target module for which +// calls or references to the import should be patched. +// +// - exportmodule (IN): Handle (base address) of the module that exports the +// the function or variable to be patched. +// +// - exportmodulename (IN): ANSI string containing the name of the module that +// exports the function or variable to be patched. +// +// - importname (IN): ANSI string containing the name of the imported function +// or variable to be patched. May be an integer cast to a string if the +// import is exported by ordinal. +// +// - replacement (IN): Address of the function or variable to which future +// calls or references should be patched through to. This function or +// variable can be thought of as effectively replacing the original import +// from the point of view of the module specified by "importmodule". +// +// Return Value: +// +// Returns TRUE if the patch was installed into the import module. If the +// import module does not import the specified export, so nothing changed, +// then FALSE will be returned. +// +BOOL PatchImport (HMODULE importmodule, moduleentry_t *patchModule) +{ + HMODULE exportmodule = (HMODULE)patchModule->moduleBase; + if (exportmodule == NULL) + return FALSE; + + IMAGE_IMPORT_DESCRIPTOR *idte = NULL; + IMAGE_SECTION_HEADER *section = NULL; + ULONG size = 0; + + // Locate the importing module's Import Directory Table (IDT) entry for the + // exporting module. The importing module actually can have several IATs -- + // one for each export module that it imports something from. The IDT entry + // gives us the offset of the IAT for the module we are interested in. + { + idte = (IMAGE_IMPORT_DESCRIPTOR*)g_Ide.ImageDirectoryEntryToDataEx((PVOID)GetCallingModule((UINT_PTR)importmodule), TRUE, + IMAGE_DIRECTORY_ENTRY_IMPORT, &size, §ion); + } + + if (idte == NULL) { + // This module has no IDT (i.e. it imports nothing). + return FALSE; + } +#ifdef PRINTHOOKINFO + bool dllNamePrinted = false; + CHAR cwBuffer[2048] = { 0 }; + LPSTR pszBuffer = cwBuffer; + DWORD dwMaxChars = _countof(cwBuffer); + DWORD dwLength = ::GetModuleFileNameA(importmodule, pszBuffer, dwMaxChars); +#endif + + int result = 0; + while (idte->FirstThunk != 0x0) { + PCHAR importdllname = (PCHAR)R2VA(importmodule, idte->Name); + UNREFERENCED_PARAMETER(importdllname); + + patchentry_t *patchEntry = patchModule->patchTable; + int i = 0; + while(patchEntry->importName) + { + LPCSTR importname = patchEntry->importName; + LPCVOID replacement = patchEntry->replacement; + + // Get the *real* address of the import. If we find this address in the IAT, + // then we've found the entry that needs to be patched. + LPVOID import = VisualLeakDetector::_RGetProcAddress(exportmodule, importname); + if ( !import) + import = GetProcAddress(exportmodule, importname); + import = FindRealCode(import); + + if (import == NULL) // Perhaps the named export module does not actually export the named import? + { + patchEntry++; i++; + continue; + } + + // Locate the import's IAT entry. + IMAGE_THUNK_DATA *thunk = (IMAGE_THUNK_DATA*)R2VA(importmodule, idte->FirstThunk); + IMAGE_THUNK_DATA *origThunk = (IMAGE_THUNK_DATA*)R2VA(importmodule, idte->OriginalFirstThunk); + for (; origThunk->u1.Function != NULL; + origThunk++, thunk++) + { + LPVOID func = FindRealCode((LPVOID)thunk->u1.Function); + if (((DWORD_PTR)func == (DWORD_PTR)import)) + { + // Found the IAT entry. Overwrite the address stored in the IAT + // entry with the address of the replacement. Note that the IAT + // entry may be write-protected, so we must first ensure that it is + // writable. + if (import != replacement) + { + if (patchEntry->original != NULL) + *patchEntry->original = func; + + DWORD protect; + if (VirtualProtect(&thunk->u1.Function, sizeof(thunk->u1.Function), PAGE_EXECUTE_READWRITE, &protect)) { + thunk->u1.Function = (DWORD_PTR)replacement; + if (VirtualProtect(&thunk->u1.Function, sizeof(thunk->u1.Function), protect, &protect)) { +#ifdef PRINTHOOKINFO + if (!IS_ORDINAL(importname)) { + DbgReport(L"Hook dll \"%S\" import %S!%S()\n", + strrchr(pszBuffer, '\\') + 1, patchModule->exportModuleName, importname); + } else { + DbgReport(L"Hook dll \"%S\" import %S!%zu()\n", + strrchr(pszBuffer, '\\') + 1, patchModule->exportModuleName, importname); + } +#endif + } + } + } + // The patch has been installed in the import module. + result++; + break; + } +#ifdef PRINTHOOKINFO + PIMAGE_IMPORT_BY_NAME funcEntry = (PIMAGE_IMPORT_BY_NAME) + R2VA(importmodule, origThunk->u1.AddressOfData); + if (stricmp(importdllname, patchModule->exportModuleName) == 0) + { + if (!(origThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG) && !IS_ORDINAL(importname) && + strcmp(reinterpret_cast(funcEntry->Name), importname) == 0) + { + if (!dllNamePrinted) + { + dllNamePrinted = true; + DbgReport(L"Hook dll \"%S\":\n", + strrchr(pszBuffer, '\\') + 1); + } + DbgReport(L"Import found %S(\"%S\") for dll \"%S\".\n", + importname, patchModule->exportModuleName, importdllname); + break; + } + if ((origThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG) && IS_ORDINAL(importname) && + (IMAGE_ORDINAL(origThunk->u1.Ordinal) == (UINT_PTR)importname)) + { + if (!dllNamePrinted) + { + dllNamePrinted = true; + DbgReport(L"Hook dll \"%S\":\n", + strrchr(pszBuffer, '\\') + 1); + } + DbgReport(L"Import found %zu(\"%S\") for dll \"%S\".\n", + importname, patchModule->exportModuleName, importdllname); + break; + } + } +#endif + } + patchEntry++; i++; + } + + idte++; + } + + // The import's IAT entry was not found. The importing module does not + // import the specified import. + return result > 0; +} + +// PatchModule - Patches all imports listed in the supplied patch table, and +// which are imported by the specified module, through to their respective +// replacement functions. +// +// Note: If the specified module does not import any of the functions listed +// in the patch table, then nothing is changed for the specified module. +// +// - importmodule (IN): Handle (base address) of the target module which is to +// have its imports patched. +// +// - patchtable (IN): An array of patchentry_t structures specifying all of the +// imports to patch for the specified module. +// +// - tablesize (IN): Size, in entries, of the specified patch table. +// +// Return Value: +// +// Returns TRUE if at least one of the patches listed in the patch table was +// installed in the importmodule. Otherwise returns FALSE. +// +BOOL PatchModule (HMODULE importmodule, moduleentry_t patchtable [], UINT tablesize) +{ + moduleentry_t *entry; + UINT index; + BOOL patched = FALSE; + +#ifdef PRINTHOOKINFO + CHAR cwBuffer[2048] = { 0 }; + LPSTR pszBuffer = cwBuffer; + DWORD dwMaxChars = _countof(cwBuffer); + DWORD dwLength = ::GetModuleFileNameA(importmodule, pszBuffer, dwMaxChars); +#endif + + // Loop through the import patch table, individually patching each import + // listed in the table. + DbgTrace(L"dbghelp32.dll %i: PatchModule - ImageDirectoryEntryToDataEx\n", GetCurrentThreadId()); + for (index = 0; index < tablesize; index++) { + entry = &patchtable[index]; + if (PatchImport(importmodule, entry)) { + patched = TRUE; + } + } + + return patched; +} + +int CallReportHook(int reportType, LPWSTR message, int* hook_retval) +{ + if (g_pReportHooks == NULL) + return 0; + for (ReportHookSet::Iterator it = g_pReportHooks->begin(); it != g_pReportHooks->end(); ++it) + { + int result = (*it)(reportType, message, hook_retval); + if (result) // handled + return result; + } + return 0; +} + +// Print - Sends a message to the debugger for display +// and/or to a file. +// +// Note: A message longer than MAXREPORTLENGTH characters will be truncated +// to MAXREPORTLENGTH. +// +// - ... (IN): Arguments to be formatted using the specified format string. +// +// Return Value: +// +// None. +// +VOID Print (LPWSTR messagew) +{ + if (NULL == messagew) + return; + + int hook_retval=0; + if (!CallReportHook(0, messagew, &hook_retval)) + { + if (s_reportEncoding == unicode) { + if (s_reportFile != NULL) { + // Send the report to the previously specified file. + fwrite(messagew, sizeof(WCHAR), wcslen(messagew), s_reportFile); + } + + if ( s_reportToStdOut ) + fputws(messagew, stdout); + } + else { + const size_t MAXMESSAGELENGTH = 5119; + size_t count = 0; + CHAR messagea [MAXMESSAGELENGTH + 1]; + if (wcstombs_s(&count, messagea, MAXMESSAGELENGTH + 1, messagew, _TRUNCATE) != 0) { + // Failed to convert the Unicode message to ASCII. + assert(FALSE); + return; + } + messagea[MAXMESSAGELENGTH] = '\0'; + + if (s_reportFile != NULL) { + // Send the report to the previously specified file. + fwrite(messagea, sizeof(CHAR), strlen(messagea), s_reportFile); + } + + if ( s_reportToStdOut ) + fputs(messagea, stdout); + } + + if (s_reportToDebugger) + OutputDebugStringW(messagew); + } + else if (hook_retval == 1) + __debugbreak(); + + if (s_reportToDebugger && (s_reportDelay)) { + Sleep(10); // Workaround the Visual Studio 6 bug where debug strings are sometimes lost if they're sent too fast. + } +} + +// Report - Sends a printf-style formatted message to the debugger for display +// and/or to a file. +// +// Note: A message longer than MAXREPORTLENGTH characters will be truncated +// to MAXREPORTLENGTH. +// +// - format (IN): Specifies a printf-compliant format string containing the +// message to be sent to the debugger. +// +// - ... (IN): Arguments to be formatted using the specified format string. +// +// Return Value: +// +// None. +// +VOID Report (LPCWSTR format, ...) +{ + va_list args; + WCHAR messagew [MAXREPORTLENGTH + 1]; + + va_start(args, format); + int result = _vsnwprintf_s(messagew, MAXREPORTLENGTH + 1, _TRUNCATE, format, args); + va_end(args); + messagew[MAXREPORTLENGTH] = L'\0'; + + if (result >= 0) + Print(messagew); +} + +// RestoreImport - Restores the IAT entry for an import previously patched via +// a call to "PatchImport" to the original address of the import. +// +// - importmodule (IN): Handle (base address) of the target module for which +// calls or references to the import should be restored. +// +// - exportmodule (IN): Handle (base address) of the module that exports the +// function or variable to be patched. +// +// - exportmodulename (IN): ANSI string containing the name of the module that +// exports the function or variable to be patched. +// +// - importname (IN): ANSI string containing the name of the imported function +// or variable to be restored. May be an integer cast to a string if the +// import is exported by ordinal. +// +// - replacement (IN): Address of the function or variable which the import was +// previously patched through to via a call to "PatchImport". +// +// Return Value: +// +// None. +// +VOID RestoreImport (HMODULE importmodule, moduleentry_t* module) +{ + HMODULE exportmodule = (HMODULE)module->moduleBase; + LPCSTR exportmodulename = module->exportModuleName; + UNREFERENCED_PARAMETER(exportmodulename); + if (exportmodule == NULL) + return; + + IMAGE_IMPORT_DESCRIPTOR *idte = NULL; + IMAGE_SECTION_HEADER *section = NULL; + ULONG size = 0; + + // Locate the importing module's Import Directory Table (IDT) entry for the + // exporting module. The importing module actually can have several IATs -- + // one for each export module that it imports something from. The IDT entry + // gives us the offset of the IAT for the module we are interested in. + { + idte = (IMAGE_IMPORT_DESCRIPTOR*)g_Ide.ImageDirectoryEntryToDataEx((PVOID)GetCallingModule((UINT_PTR)importmodule), TRUE, + IMAGE_DIRECTORY_ENTRY_IMPORT, &size, §ion); + } + + if (idte == NULL) { + // This module has no IDT (i.e. it imports nothing). + return; + } + +#ifdef PRINTHOOKINFO + bool dllNamePrinted = false; + CHAR cwBuffer[2048] = { 0 }; + LPSTR pszBuffer = cwBuffer; + DWORD dwMaxChars = _countof(cwBuffer); + DWORD dwLength = ::GetModuleFileNameA(importmodule, pszBuffer, dwMaxChars); +#endif + + int result = 0; + while (idte->OriginalFirstThunk != 0x0) + { + PCHAR name = (PCHAR)R2VA(importmodule, idte->Name); + UNREFERENCED_PARAMETER(name); + + int i = 0; + patchentry_t *entry = module->patchTable; + while(entry->importName) + { + LPCSTR importname = entry->importName; + LPCVOID replacement = entry->replacement; + UNREFERENCED_PARAMETER(importname); + + // Get the *real* address of the import. + //LPCVOID original = entry->original; + LPCVOID original = g_vld._RGetProcAddress(exportmodule, importname); + if (original == NULL) // Perhaps the named export module does not actually export the named import? + { + entry++; i++; + continue; + } + + // Locate the import's original IAT entry (it currently has the replacement + // address in it). + IMAGE_THUNK_DATA* iate = (IMAGE_THUNK_DATA*)R2VA(importmodule, idte->FirstThunk); + while (iate->u1.Function != 0x0) + { + if (iate->u1.Function != (DWORD_PTR)replacement) + { + iate++; + continue; + } + + if (iate->u1.Function != (DWORD_PTR)original) + { + // Found the IAT entry. Overwrite the address stored in the IAT + // entry with the import's real address. Note that the IAT entry may + // be write-protected, so we must first ensure that it is writable. + DWORD protect; + if (VirtualProtect(&iate->u1.Function, sizeof(iate->u1.Function), PAGE_EXECUTE_READWRITE, &protect)) { + iate->u1.Function = (DWORD_PTR)original; + if (VirtualProtect(&iate->u1.Function, sizeof(iate->u1.Function), protect, &protect)) { +#ifdef PRINTHOOKINFO + if (!IS_ORDINAL(importname)) { + DbgReport(L"UnHook dll \"%S\" import %S!%S()\n", + strrchr(pszBuffer, '\\') + 1, module->exportModuleName, importname); + } else { + DbgReport(L"UnHook dll \"%S\" import %S!%zu()\n", + strrchr(pszBuffer, '\\') + 1, module->exportModuleName, importname); + } +#endif + } + } + } + result++; + iate++; + } + entry++; i++; + } + idte++; + } +} + +// RestoreModule - Restores all imports listed in the supplied patch table, and +// which are imported by the specified module, to their original functions. +// +// Note: If the specified module does not import any of the functions listed +// in the patch table, then nothing is changed for the specified module. +// +// - importmodule (IN): Handle (base address) of the target module which is to +// have its imports restored. +// +// - patchtable (IN): Array of patchentry_t structures specifying all of the +// imports to restore for the specified module. +// +// - tablesize (IN): Size, in entries, of the specified patch table. +// +// Return Value: +// +// None. +// +VOID RestoreModule (HMODULE importmodule, moduleentry_t patchtable [], UINT tablesize) +{ + moduleentry_t *entry; + UINT index; + + // Loop through the import patch table, individually restoring each import + // listed in the table. + DbgTrace(L"dbghelp32.dll %i: RestoreModule - ImageDirectoryEntryToDataEx\n", GetCurrentThreadId()); + for (index = 0; index < tablesize; index++) { + entry = &patchtable[index]; + RestoreImport(importmodule, entry); + } +} + +// SetReportEncoding - Sets the output encoding of report messages to either +// ASCII (the default) or Unicode. +// +// - encoding (IN): Specifies either "ascii" or "unicode". +// +// Return Value: +// +// None. +// +VOID SetReportEncoding (encoding_e encoding) +{ + switch (encoding) { + case ascii: + case unicode: + s_reportEncoding = encoding; + break; + + default: + assert(FALSE); + } +} + +// SetReportFile - Sets a destination file to which all report messages should +// be sent. If this function is not called to set a destination file, then +// report messages will be sent to the debugger instead of to a file. +// +// - file (IN): Pointer to an open file, to which future report messages should +// be sent. +// +// - copydebugger (IN): If true, in addition to sending report messages to +// the specified file, a copy of each message will also be sent to the +// debugger. +// +// Return Value: +// +// None. +// +VOID SetReportFile (FILE *file, BOOL copydebugger, BOOL tostdout) +{ + s_reportFile = file; + s_reportToDebugger = copydebugger; + s_reportToStdOut = tostdout; +} + +// AppendString - Appends the specified source string to the specified destination +// string. Allocates additional space so that the destination string "grows" +// as new strings are appended to it. This is accomplished by deleting the +// destination string after the new longer string is gets the copied contents +// of the destination and additional text. This function is fairly infrequently +// used so efficiency is not a major concern. +// +// - dest (IN): Address of the destination string. Receives the resulting +// combined string after the append operation. +// +// - source (IN): Source string to be appended to the destination string. +// +// Return Value: +// +// The new concatenated string. +// +LPWSTR AppendString (LPWSTR dest, LPCWSTR source) +{ + if ((source == NULL) || (source[0] == '\0')) + { + return dest; + } + SIZE_T length = wcslen(dest) + wcslen(source); + LPWSTR new_str = new WCHAR [length + 1]; + wcsncpy_s(new_str, length + 1, dest, _TRUNCATE); + wcsncat_s(new_str, length + 1, source, _TRUNCATE); + delete [] dest; + return new_str; +} + +// StrToBool - Converts string values (e.g. "yes", "no", "on", "off") to boolean +// values. +// +// - s (IN): String value to convert. +// +// Return Value: +// +// Returns TRUE if the string is recognized as a "true" string. Otherwise +// returns FALSE. +// +BOOL StrToBool (LPCWSTR s) { + WCHAR *end; + + if ((_wcsicmp(s, L"true") == 0) || + (_wcsicmp(s, L"yes") == 0) || + (_wcsicmp(s, L"on") == 0) || + (wcstol(s, &end, 10) == 1)) { + return TRUE; + } + else { + return FALSE; + } +} + +// _GetProcessIdOfThread - Returns the ID of the process owns the thread. +// +// - thread (IN): The handle to the thread. +// +// Return Value: +// +// Returns the ID of the process that owns the thread. Otherwise returns 0. +// +DWORD _GetProcessIdOfThread (HANDLE thread) +{ + typedef struct _CLIENT_ID { + HANDLE UniqueProcess; + HANDLE UniqueThread; + } CLIENT_ID, *PCLIENT_ID; + + typedef LONG NTSTATUS; + typedef LONG KPRIORITY; + + typedef struct _THREAD_BASIC_INFORMATION { + NTSTATUS ExitStatus; + PVOID TebBaseAddress; + CLIENT_ID ClientId; + KAFFINITY AffinityMask; + KPRIORITY Priority; + KPRIORITY BasePriority; + } THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION; + + const static THREADINFOCLASS ThreadBasicInformation = (THREADINFOCLASS)0; + + typedef NTSTATUS (WINAPI *PNtQueryInformationThread) (HANDLE thread, + THREADINFOCLASS infoclass, PVOID buffer, ULONG buffersize, + PULONG used); + + static PNtQueryInformationThread NtQueryInformationThread = NULL; + + THREAD_BASIC_INFORMATION tbi; + NTSTATUS status; + if (NtQueryInformationThread == NULL) { + HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); + if (ntdll) + { + NtQueryInformationThread = (PNtQueryInformationThread)GetProcAddress(ntdll, "NtQueryInformationThread"); + } + + if (NtQueryInformationThread == NULL) { + return 0; + } + } + + status = NtQueryInformationThread(thread, ThreadBasicInformation, &tbi, sizeof(tbi), NULL); + if(status < 0) { + // Shall we go through all the trouble of setting last error? + return 0; + } + + return (DWORD)tbi.ClientId.UniqueProcess; +} + +static const DWORD crctab[256] = { + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, + 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, + 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, + 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, + 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, + 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, + 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, + 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, + 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, + 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, + 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, + 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, + 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, + 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, + 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, + 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, + 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, + 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, + 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, + 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, + 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, + 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, + 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, + 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, + 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, + 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, + 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, + 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, + 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, + 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, + 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, + 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, + 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, + 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, + 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, + 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d, +}; + +DWORD CalculateCRC32(UINT_PTR p, UINT startValue) +{ + register DWORD hash = startValue; + hash = (hash >> 8) ^ crctab[(hash & 0xff) ^ ((p >> 0) & 0xff)]; + hash = (hash >> 8) ^ crctab[(hash & 0xff) ^ ((p >> 8) & 0xff)]; + hash = (hash >> 8) ^ crctab[(hash & 0xff) ^ ((p >> 16) & 0xff)]; + hash = (hash >> 8) ^ crctab[(hash & 0xff) ^ ((p >> 24) & 0xff)]; +#ifdef WIN64 + hash = (hash >> 8) ^ crctab[(hash & 0xff) ^ ((p >> 32) & 0xff)]; + hash = (hash >> 8) ^ crctab[(hash & 0xff) ^ ((p >> 40) & 0xff)]; + hash = (hash >> 8) ^ crctab[(hash & 0xff) ^ ((p >> 48) & 0xff)]; + hash = (hash >> 8) ^ crctab[(hash & 0xff) ^ ((p >> 56) & 0xff)]; +#endif + return hash; +} + +// Formats a message string using the specified message and variable +// list of arguments. +void GetFormattedMessage(DWORD last_error) +{ + // Retrieve the system error message for the last-error code + WCHAR lpMsgBuf[MAX_PATH] = {0}; + + FormatMessage( + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + last_error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + lpMsgBuf, + MAX_PATH, + NULL ); + + // Display the error message. + Report(L"%s", lpMsgBuf); +} + +// GetCallingModule - Return calling module by address. +// +// Return Value: +// +// Module handle. +// +HMODULE GetCallingModule( UINT_PTR pCaller ) +{ + HMODULE hModule = NULL; + MEMORY_BASIC_INFORMATION mbi; + if ( VirtualQuery((LPCVOID)pCaller, &mbi, sizeof(MEMORY_BASIC_INFORMATION)) == sizeof(MEMORY_BASIC_INFORMATION) ) + { + // the allocation base is the beginning of a PE file + hModule = (HMODULE) mbi.AllocationBase; + } + return hModule; +} + +// LoadBoolOption - Loads specified option from environment variables or from specified ini file, +// if env var is unavailable and converts string values (e.g. "yes", "no", "on", "off") to boolean values. +// +// - optionname (IN): Option to load. +// +// - defaultvalue (IN): Default value if optionname in unavailable. +// +// - inipath (IN): Path to configuration ini file. +// +// Return Value: +// +// Returns TRUE if the string is recognized as a "true" string. Otherwise +// returns FALSE. +// +BOOL LoadBoolOption(LPCWSTR optionname, LPCWSTR defaultvalue, LPCWSTR inipath) +{ + const UINT buffersize = 64; + WCHAR buffer[buffersize] = { 0 }; + + WCHAR envirinmentoptionname[buffersize] = L"Vld"; + wcscat_s(envirinmentoptionname, buffersize, optionname); + + if (!GetEnvironmentVariable(envirinmentoptionname, buffer, buffersize)) { + GetPrivateProfileString(L"Options", optionname, defaultvalue, buffer, buffersize, inipath); + } + + return StrToBool(buffer); +} + +// LoadIntOption - Loads specified option from environment variables or from specified ini file, +// if env var is unavailable. +// +// - optionname (IN): Option to load +// +// - defaultvalue (IN): Default value if optionname in unavailable. +// +// - inipath (IN): Path to configuration ini file. +// +// Return Value: +// +// Returns integer representation of optionname's value. +// +UINT LoadIntOption(LPCWSTR optionname, UINT defaultvalue, LPCWSTR inipath) +{ + const UINT buffersize = 64; + WCHAR buffer[buffersize] = { 0 }; + + WCHAR envirinmentoptionname[buffersize] = L"Vld"; + wcscat_s(envirinmentoptionname, buffersize, optionname); + + if (!GetEnvironmentVariable(envirinmentoptionname, buffer, buffersize)) { + return GetPrivateProfileInt(L"Options", optionname, defaultvalue, inipath); + } + + return _tstoi(buffer); +} + +// LoadStringOption - Loads specified option from environment variables or from specified ini file, +// if env var is unavailable. +// +// - optionname (IN): Option to load. +// +// - outputbuffer (OUT): A buffer to store the string. +// +// - buffersize (IN): Size of a buffer in characters. +// +// - inipath (IN): Path to configuration ini file. +// +// Return Value: +// +// None. +// +VOID LoadStringOption(LPCWSTR optionname, LPWSTR outputbuffer, UINT buffersize, LPCWSTR inipath) +{ + const UINT namebuffersize = 64; + WCHAR envirinmentoptionname[namebuffersize] = L"Vld"; + wcscat_s(envirinmentoptionname, namebuffersize, optionname); + + if (!GetEnvironmentVariable(envirinmentoptionname, outputbuffer, buffersize)) { + GetPrivateProfileString(L"Options", optionname, L"", outputbuffer, buffersize, inipath); + } +} \ No newline at end of file diff --git a/src/utility.h b/src/utility.h new file mode 100644 index 00000000..25b7b64c --- /dev/null +++ b/src/utility.h @@ -0,0 +1,166 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - Various Utility Definitions +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef VLDBUILD +#error \ +"This header should only be included by Visual Leak Detector when building it from source. \ +Applications should never include this header." +#endif + +#include +#include +#include + +#ifdef _WIN64 +#define ADDRESSFORMAT L"0x%.16X" // Format string for 64-bit addresses +#define ADDRESSCPPFORMAT L"0x{:016X}" // Format string for 64-bit addresses +#else +#define ADDRESSFORMAT L"0x%.8X" // Format string for 32-bit addresses +#define ADDRESSCPPFORMAT L"0x{:08X}" // Format string for 32-bit addresses +#endif // _WIN64 +#define BOM 0xFEFF // Unicode byte-order mark. +#define MAXREPORTLENGTH 511 // Maximum length, in characters, of "report" messages. + +// Architecture-specific definitions for x86 and x64 +#if defined(_M_IX86) +#define X86X64ARCHITECTURE IMAGE_FILE_MACHINE_I386 +#define BPREG Ebp +#define IPREG Eip +#define SPREG Esp +#elif defined(_M_X64) +#define X86X64ARCHITECTURE IMAGE_FILE_MACHINE_AMD64 +#define BPREG Rbp +#define IPREG Rip +#define SPREG Rsp +#endif // _M_IX86 + +struct context_t +{ + UINT_PTR fp; + UINT_PTR func; +#if defined(_M_IX86) + DWORD Ebp; + DWORD Esp; + DWORD Eip; +#elif defined(_M_X64) + DWORD64 Rbp; + DWORD64 Rsp; + DWORD64 Rip; +#endif // _M_IX86 +}; + +// Capture current context +#if defined(_M_IX86) +#define CAPTURE_CONTEXT() \ + context_t context_; \ + {CONTEXT _ctx; \ + RtlCaptureContext(&_ctx); \ + context_.Ebp = _ctx.Ebp; context_.Esp = _ctx.Esp; context_.Eip = _ctx.Eip; \ + context_.fp = (UINT_PTR)_ReturnAddress();} +#define GET_RETURN_ADDRESS(context) (context.fp) +#elif defined(_M_X64) +#define CAPTURE_CONTEXT() \ + context_t context_; \ + {CONTEXT _ctx; \ + RtlCaptureContext(&_ctx); \ + context_.Rbp = _ctx.Rbp; context_.Rsp = _ctx.Rsp; context_.Rip = _ctx.Rip; \ + context_.fp = (UINT_PTR)_ReturnAddress();} +#define GET_RETURN_ADDRESS(context) (context.fp) +#else +// If you want to retarget Visual Leak Detector to another processor +// architecture then you'll need to provide an architecture-specific macro to +// obtain the frame pointer (or other address) which can be used to obtain the +// return address and stack pointer of the calling frame. +#error "Visual Leak Detector is not supported on this architecture." +#endif // _M_IX86 || _M_X64 + +// Miscellaneous definitions +#define R2VA(moduleBase, rva) (((PBYTE)moduleBase) + rva) // Relative Virtual Address to Virtual Address conversion. +#define BYTEFORMATBUFFERLENGTH 4 +#define HEXDUMPLINELENGTH 58 + +// Reports can be encoded as either ASCII or Unicode (UTF-16). +enum encoding_e { + ascii, + unicode +}; + +// This structure allows us to build a table of APIs which should be patched +// through to replacement functions provided by VLD. +struct patchentry_t +{ + LPCSTR importName; // The name (or ordinal) of the imported API being patched. + LPVOID* original; // Pointer to the original function. + LPCVOID replacement; // Pointer to the function to which the imported API should be patched through to. +}; + +struct moduleentry_t +{ + LPCSTR exportModuleName; // The name of the module exporting the patched API. + BOOL reportLeaks; // Patch module to report leaks from it + UINT_PTR moduleBase; // The base address of the exporting module (filled in at runtime when the modules are loaded). + patchentry_t* patchTable; +}; + +// Utility functions. See function definitions for details. +VOID DumpMemoryA (LPCVOID address, SIZE_T length); +VOID DumpMemoryW (LPCVOID address, SIZE_T length); +BOOL FindImport (HMODULE importmodule, HMODULE exportmodule, LPCSTR exportmodulename, LPCSTR importname); +BOOL FindPatch (HMODULE importmodule, LPCSTR exportmodulename, LPCVOID replacement); +VOID InsertReportDelay (); +BOOL IsModulePatched (HMODULE importmodule, moduleentry_t patchtable [], UINT tablesize); +BOOL PatchImport (HMODULE importmodule, moduleentry_t *module); +BOOL PatchModule (HMODULE importmodule, moduleentry_t patchtable [], UINT tablesize); +VOID Print (LPWSTR message); +VOID Report (LPCWSTR format, ...); +#ifndef NDEBUG +#define DbgPrint(x) Print(x) +#define DbgReport(...) Report(__VA_ARGS__) +#define DbgTrace(...) +#else +#define DbgPrint(x) +#define DbgReport(...) +#define DbgTrace(...) +#endif +VOID RestoreImport (HMODULE importmodule, moduleentry_t* module); +VOID RestoreModule (HMODULE importmodule, moduleentry_t patchtable [], UINT tablesize); +VOID SetReportEncoding (encoding_e encoding); +VOID SetReportFile (FILE *file, BOOL copydebugger, BOOL copytostdout); +LPWSTR AppendString (LPWSTR dest, LPCWSTR source); +BOOL StrToBool (LPCWSTR s); +#if _WIN32_WINNT < 0x0600 // Windows XP or earlier, no GetProcessIdOfThread() +DWORD _GetProcessIdOfThread (HANDLE thread); +#define GetProcessIdOfThread _GetProcessIdOfThread +#endif +void ConvertModulePathToAscii( LPCWSTR modulename, LPSTR * modulenamea ); +DWORD CalculateCRC32(UINT_PTR p, UINT startValue = 0xD202EF8D); +// Formats a message string using the specified message and variable +// list of arguments. +void GetFormattedMessage(DWORD last_error); +HMODULE GetCallingModule(UINT_PTR pCaller); +DWORD FilterFunction(long); +BOOL LoadBoolOption(LPCWSTR optionname, LPCWSTR defaultvalue, LPCWSTR inipath); +UINT LoadIntOption(LPCWSTR optionname, UINT defaultvalue, LPCWSTR inipath); +VOID LoadStringOption(LPCWSTR optionname, LPWSTR outputbuffer, UINT buffersize, LPCWSTR inipath); \ No newline at end of file diff --git a/src/vld.cpp b/src/vld.cpp new file mode 100644 index 00000000..d19295ff --- /dev/null +++ b/src/vld.cpp @@ -0,0 +1,2996 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - VisualLeakDetector Class Implementation +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" + +#pragma comment(lib, "dbghelp.lib") + +#include + +#define VLDBUILD // Declares that we are building Visual Leak Detector. +#include "callstack.h" // Provides a class for handling call stacks. +#include "crtmfcpatch.h" // Provides CRT and MFC patch functions. +#include "map.h" // Provides a lightweight STL-like map template. +#include "ntapi.h" // Provides access to NT APIs. +#include "set.h" // Provides a lightweight STL-like set template. +#include "utility.h" // Provides various utility functions. +#include "vldint.h" // Provides access to the Visual Leak Detector internals. +#include "loaderlock.h" +#include "tchar.h" + +#define BLOCK_MAP_RESERVE 64 // This should strike a balance between memory use and a desire to minimize heap hits. +#define HEAP_MAP_RESERVE 2 // Usually there won't be more than a few heaps in the process, so this should be small. +#define MODULE_SET_RESERVE 16 // There are likely to be several modules loaded in the process. + +// Imported global variables. +extern vldblockheader_t *g_vldBlockList; +extern HANDLE g_vldHeap; +extern CriticalSection g_vldHeapLock; + +// Global variables. +HANDLE g_currentProcess; // Pseudo-handle for the current process. +HANDLE g_currentThread; // Pseudo-handle for the current thread. +HANDLE g_processHeap; // Handle to the process's heap (COM allocations come from here). +CriticalSection g_heapMapLock; // Serializes access to the heap and block maps. +ReportHookSet* g_pReportHooks; +DbgHelp g_DbgHelp; +ImageDirectoryEntries g_Ide; +LoadedModules g_LoadedModules; + +// The one and only VisualLeakDetector object instance. +__declspec(dllexport) VisualLeakDetector g_vld; + +// Patch only this entries in Kernel32.dll and KernelBase.dll +patchentry_t ldrLoadDllPatch [] = { + "LdrLoadDll", NULL, VisualLeakDetector::_LdrLoadDll, + "LdrGetDllHandle", NULL, VisualLeakDetector::_LdrGetDllHandle, + "LdrGetProcedureAddress", NULL, VisualLeakDetector::_LdrGetProcedureAddress, + "LdrLockLoaderLock", NULL, VisualLeakDetector::_LdrLockLoaderLock, + "LdrUnlockLoaderLock", NULL, VisualLeakDetector::_LdrUnlockLoaderLock, + NULL, NULL, NULL +}; +moduleentry_t ntdllPatch [] = { + "ntdll.dll", FALSE, NULL, ldrLoadDllPatch, +}; + +///////////////////////////////////////////////////////// + +// We provide our own DllEntryPoint in order to capture the ReturnAddress of the function calling our DllEntryPoint. +// Then we patch this function namely ntdll.dll!LdrpCallInitRoutine or any equivalent NT loader function by calling +// our LdrpCallInitRoutine where we RefreshModules before calling the EntryPoint in order to hook all functions required +// to properly capture all _CRT_INIT memory allocations which include internal CRT startup memory allocations and all +// global and static initializers. +// +// In getLeaksCount(), reportLeaks() and resolveStacks(), we take extra measures to identify and exclude debug and release +// internal CRT allocations from reporting as real memory leaks. +// +// Global and static initializers *might* be reported as memory leaks based on the order being unintialised by _CRT_INIT. + +typedef BOOLEAN(NTAPI *PDLL_INIT_ROUTINE)(IN PVOID DllHandle, IN ULONG Reason, IN PCONTEXT Context OPTIONAL); +BOOLEAN WINAPI LdrpCallInitRoutine(IN PVOID BaseAddress, IN ULONG Reason, IN PVOID Context, IN PDLL_INIT_ROUTINE EntryPoint) +{ + LoaderLock ll; + + if (Reason == DLL_PROCESS_ATTACH) { + g_vld.RefreshModules(); + } + + return EntryPoint(BaseAddress, Reason, (PCONTEXT)Context); +} + +PBYTE NtDllFindDetourAddress(const PBYTE pAddress, SIZE_T dwSize) +{ + MEMORY_BASIC_INFORMATION meminfo = { 0 }; + if (VirtualQuery(pAddress, &meminfo, sizeof(meminfo))) { + // Find spare bytes at the end of the memory region that are unused + // so we can jump to this address and set up the detour. + PBYTE end = (PBYTE)meminfo.BaseAddress + meminfo.RegionSize; + PBYTE begin = end; + + while (((SIZE_T)(end - begin) < dwSize) && (begin != pAddress)) { + if (*(--begin) != 0x00) + end = begin; + } + if (begin != pAddress) + return begin; + } + return NULL; +} + +PBYTE NtDllFindParamAddress(const PBYTE pAddress) +{ + PBYTE ptr = pAddress; + // Test previous 32 bytes to find the begining address we need to patch + // for 32bit find => push [ebp][14h] => parameters are pushed to stack + // for 64bit find => mov r8,... => parameters are moved to registers r8, edx, rcx + while (pAddress - --ptr < 0x20) { +#ifdef _WIN64 + if (((ptr[0] & 0x4D) >= 0x4C) && (ptr[1] == 0x8B) && ((ptr[2] & 0xC7) == ptr[2])) { +#else + if ((ptr[0] == 0xFF) && (ptr[1] == 0x75) && (ptr[2] == 0x14)) { +#endif + return ptr; + } + } + return NULL; + } + +PBYTE NtDllFindCallAddress(const PBYTE pAddress) +{ + PBYTE ptr = pAddress; + // Test previous 32 bytes to find the begining address we need to patch + // for 32bit find => call [ebp][08h] + // for 64bit find => call + while (pAddress - --ptr < 0x20) { +#ifdef _WIN64 + if ((ptr[0] == 0xFF) && ((ptr[1] & 0xD7) == ptr[1])) { + if ((*(ptr - 1) & 0x41) == *(ptr - 1)) { + --ptr; + } +#else + if ((ptr[0] == 0xFF) && (ptr[1] == 0x55) && (ptr[2] == 0x08)) { +#endif + return ptr; + } + } + return NULL; + } + +typedef struct _NTDLL_LDR_PATCH { + PBYTE pPatchAddress; + SIZE_T nPatchSize; + BYTE pBackup[0x20]; + PBYTE pDetourAddress; + SIZE_T nDetourSize; + BOOL bState; +} NTDLL_LDR_PATCH, *PNTDLL_LDR_PATCH; + +NTDLL_LDR_PATCH patch; + + +BOOL NtDllPatch(const PBYTE pReturnAddress, NTDLL_LDR_PATCH &NtDllPatch) +{ + if (NtDllPatch.bState == FALSE) { +#ifdef _WIN64 + BYTE ptr[] = { '?', 0x8B, '?' }; // mov r9, r.. + BYTE mov[] = { 0x48, 0xB8, '?', '?', '?', '?', '?', '?', '?', '?' }; // mov rax, 0x0000000000000000 + BYTE call[] = { 0xFF, 0xD0 }; // call rax +#else + BYTE ptr[] = { 0xFF, 0x75, 0x08 }; // push [ebp][08h] + BYTE mov[] = { 0x90, 0xB8, '?', '?', '?', '?' }; // mov eax, 0x00000000 + BYTE call[] = { 0xFF, 0xD0 }; // call eax +#endif + BYTE jmp[] = { 0xE9, '?', '?', '?', '?' }; // jmp 0x00000000 + + NtDllPatch.pPatchAddress = NtDllFindParamAddress(pReturnAddress); + PBYTE pCallAddress = NtDllFindCallAddress(pReturnAddress); + NtDllPatch.nPatchSize = pReturnAddress - NtDllPatch.pPatchAddress; + SIZE_T nParamSize = pCallAddress - NtDllPatch.pPatchAddress; + + NtDllPatch.nDetourSize = _countof(ptr) + nParamSize + _countof(mov) + _countof(jmp); + NtDllPatch.pDetourAddress = NtDllFindDetourAddress(pReturnAddress, NtDllPatch.nDetourSize); + + if (NtDllPatch.pPatchAddress && NtDllPatch.pDetourAddress && ((_countof(jmp) + _countof(call)) <= NtDllPatch.nPatchSize)) { + memcpy(NtDllPatch.pBackup, NtDllPatch.pPatchAddress, NtDllPatch.nPatchSize); + + DWORD dwProtect = 0; + if (VirtualProtect(NtDllPatch.pDetourAddress, NtDllPatch.nDetourSize, PAGE_EXECUTE_READWRITE, &dwProtect)) { + memset(NtDllPatch.pDetourAddress, 0x90, NtDllPatch.nDetourSize); +#ifdef _WIN64 + // Copy original param instructions + memcpy(NtDllPatch.pDetourAddress, NtDllPatch.pPatchAddress, nParamSize); + + BYTE reg = 0x00; + + LPBYTE icall = NtDllPatch.pPatchAddress + nParamSize - (3 /*instruction size*/ + sizeof(DWORD)); + if ((*(LPDWORD)icall & 0x000D8B4C) == 0x000D8B4C) { + // From Windows 10 (1607) calls to the EntryPoint are dispatched through + // __guard_dispatch_icall_fptr. In such case correct the relative address. + DWORD fptr = *(LPDWORD)(icall + 3) + (3 /*instruction size*/ + sizeof(DWORD)) - (DWORD)(NtDllPatch.pDetourAddress - NtDllPatch.pPatchAddress); + memcpy(NtDllPatch.pDetourAddress + nParamSize - sizeof(DWORD), &fptr, sizeof(DWORD)); + + // Additionally in such case the EntryPoint is held in another register + // that was moved to rax. In such case identify the correct register + // holding the EntryPoint + reg = ((*(icall - 3) & 0xF1) == 0x41 ? 0x08 : 0x00) + (*(icall - 1) & 0x07); + } else { + reg = ((pCallAddress[0] & 0xF1) == 0x41 ? 0x08 : 0x00) + (pCallAddress[pReturnAddress - pCallAddress - 1] & 0x07); + } + + // Copy the register that holds the EntryPoint to r9 + ptr[0] = 0x4C + ((reg & 0x08) ? 0x01 : 0x00); + ptr[2] = 0xC8 + (reg & 0x07); + memcpy(&NtDllPatch.pDetourAddress[nParamSize], &ptr, _countof(ptr)); +#else + // Push EntryPoint as last parameter + memcpy(&NtDllPatch.pDetourAddress[0], &ptr, _countof(ptr)); + // Copy original param instructions + memcpy(&NtDllPatch.pDetourAddress[_countof(ptr)], NtDllPatch.pPatchAddress, nParamSize); +#endif + // Move LdrpCallInitRoutine to eax/rax + *(PSIZE_T)(&mov[2]) = (SIZE_T)LdrpCallInitRoutine; + memcpy(&NtDllPatch.pDetourAddress[_countof(ptr) + nParamSize], &mov, _countof(mov)); + + // Jump to original function + *(DWORD*)(&jmp[1]) = (DWORD)(pReturnAddress - _countof(call) - (NtDllPatch.pDetourAddress + NtDllPatch.nDetourSize)); + memcpy(&NtDllPatch.pDetourAddress[_countof(ptr) + nParamSize + _countof(mov)], &jmp, _countof(jmp)); + + VirtualProtect(NtDllPatch.pDetourAddress, NtDllPatch.nDetourSize, dwProtect, &dwProtect); + + if (VirtualProtect(NtDllPatch.pPatchAddress, NtDllPatch.nPatchSize, PAGE_EXECUTE_READWRITE, &dwProtect)) { + memset(NtDllPatch.pPatchAddress, 0x90, NtDllPatch.nPatchSize); + + // Jump to detour address + *(DWORD*)(&jmp[1]) = (DWORD)(NtDllPatch.pDetourAddress - (pReturnAddress - _countof(call))); + memcpy(pReturnAddress - _countof(call) - _countof(jmp), &jmp, _countof(jmp)); + + // Call LdrpCallInitRoutine from eax/rax + memcpy(pReturnAddress - _countof(call), &call, _countof(call)); + + VirtualProtect(NtDllPatch.pPatchAddress, NtDllPatch.nPatchSize, dwProtect, &dwProtect); + + NtDllPatch.bState = TRUE; + } + } + } + } + return NtDllPatch.bState; +} + + +BOOL NtDllRestore(NTDLL_LDR_PATCH &NtDllPatch) +{ + // Restore patched bytes + BOOL bResult = FALSE; + if (NtDllPatch.bState && NtDllPatch.nPatchSize && &NtDllPatch.pBackup[0]) { + DWORD dwProtect = 0; + if (VirtualProtect(NtDllPatch.pPatchAddress, NtDllPatch.nPatchSize, PAGE_EXECUTE_READWRITE, &dwProtect)) { + memcpy(NtDllPatch.pPatchAddress, NtDllPatch.pBackup, NtDllPatch.nPatchSize); + VirtualProtect(NtDllPatch.pPatchAddress, NtDllPatch.nPatchSize, dwProtect, &dwProtect); + + if (VirtualProtect(NtDllPatch.pDetourAddress, NtDllPatch.nDetourSize, PAGE_EXECUTE_READWRITE, &dwProtect)) { + memset(NtDllPatch.pDetourAddress, 0x00, NtDllPatch.nDetourSize); + VirtualProtect(NtDllPatch.pDetourAddress, NtDllPatch.nDetourSize, dwProtect, &dwProtect); + bResult = TRUE; + } + } + } + return bResult; +} + +#define _DECL_DLLMAIN // for _CRT_INIT +#include // for _CRT_INIT +#pragma comment(linker, "/entry:DllEntryPoint") + +__declspec(noinline) +BOOL WINAPI DllEntryPoint(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved) +{ + // Patch/Restore ntdll address that calls the dll entry point + if (fdwReason == DLL_PROCESS_ATTACH) { + NtDllPatch((PBYTE)_ReturnAddress(), patch); + } + + if (fdwReason == DLL_PROCESS_ATTACH || fdwReason == DLL_THREAD_ATTACH) + if (!_CRT_INIT(hinstDLL, fdwReason, lpReserved)) + return(FALSE); + + if (fdwReason == DLL_PROCESS_DETACH || fdwReason == DLL_THREAD_DETACH) + if (!_CRT_INIT(hinstDLL, fdwReason, lpReserved)) + return(FALSE); + + if (fdwReason == DLL_PROCESS_DETACH) { + NtDllRestore(patch); + } + return(TRUE); +} + +///////////////////////////////////////////////////////// + +bool IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor) +{ + OSVERSIONINFOEXW osvi = { sizeof(osvi), 0, 0, 0, 0,{ 0 }, 0, 0 }; + DWORDLONG const dwlConditionMask = VerSetConditionMask( + VerSetConditionMask( + VerSetConditionMask( + 0, VER_MAJORVERSION, VER_GREATER_EQUAL), + VER_MINORVERSION, VER_GREATER_EQUAL), + VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); + + osvi.dwMajorVersion = wMajorVersion; + osvi.dwMinorVersion = wMinorVersion; + osvi.wServicePackMajor = wServicePackMajor; + + return !!VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask); +} + +bool IsWindows7OrGreater() +{ + return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7), 0); +} + +#define _WIN32_WINNT_WIN8 0x0602 +bool IsWindows8OrGreater() +{ + return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN8), LOBYTE(_WIN32_WINNT_WIN8), 0); +} + +// Constructor - Initializes private data, loads configuration options, and +// attaches Visual Leak Detector to all other modules loaded into the current +// process. +// +VisualLeakDetector::VisualLeakDetector () +{ + _set_error_mode(_OUT_TO_STDERR); + + // Initialize configuration options and related private data. + _wcsnset_s(m_forcedModuleList, MAXMODULELISTLENGTH, '\0', _TRUNCATE); + m_maxDataDump = 0xffffffff; + m_maxTraceFrames = 0xffffffff; + m_options = 0x0; + m_reportFile = NULL; + wcsncpy_s(m_reportFilePath, MAX_PATH, VLD_DEFAULT_REPORT_FILE_NAME, _TRUNCATE); + m_status = 0x0; + + HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); + if (ntdll) + { + if (!IsWindows8OrGreater()) + { + LdrLoadDll = (LdrLoadDll_t)GetProcAddress(ntdll, "LdrLoadDll"); + } else + { + LdrLoadDllWin8 = (LdrLoadDllWin8_t)GetProcAddress(ntdll, "LdrLoadDll"); + ldrLoadDllPatch[0].replacement = _LdrLoadDllWin8; + } + RtlAllocateHeap = (RtlAllocateHeap_t)GetProcAddress(ntdll, "RtlAllocateHeap"); + RtlFreeHeap = (RtlFreeHeap_t)GetProcAddress(ntdll, "RtlFreeHeap"); + RtlReAllocateHeap = (RtlReAllocateHeap_t)GetProcAddress(ntdll, "RtlReAllocateHeap"); + + LdrGetDllHandle = (LdrGetDllHandle_t)GetProcAddress(ntdll, "LdrGetDllHandle"); + LdrGetProcedureAddress = (LdrGetProcedureAddress_t)GetProcAddress(ntdll, "LdrGetProcedureAddress"); + LdrUnloadDll = (LdrUnloadDll_t)GetProcAddress(ntdll, "LdrUnloadDll"); + LdrLockLoaderLock = (LdrLockLoaderLock_t)GetProcAddress(ntdll, "LdrLockLoaderLock"); + LdrUnlockLoaderLock = (LdrUnlockLoaderLock_t)GetProcAddress(ntdll, "LdrUnlockLoaderLock"); + } + + // Load configuration options. + configure(); + if (m_options & VLD_OPT_VLDOFF) { + Report(L"Visual Leak Detector is turned off.\n"); + return; + } + + HMODULE kernel32 = GetModuleHandleW(L"kernel32.dll"); + HMODULE kernelBase = GetModuleHandleW(L"KernelBase.dll"); + + if (!IsWindows7OrGreater()) // kernel32.dll + { + if (kernel32) + m_GetProcAddress = (GetProcAddress_t) GetProcAddress(kernel32, "GetProcAddress"); + } + else + { + if (kernelBase) + { + m_GetProcAddress = (GetProcAddress_t)GetProcAddress(kernelBase, "GetProcAddress"); + m_GetProcAddressForCaller = (GetProcAddressForCaller_t)GetProcAddress(kernelBase, "GetProcAddressForCaller"); + } + assert(m_patchTable[0].patchTable == m_kernelbasePatch); + m_patchTable[0].exportModuleName = "kernelbase.dll"; + } + + // Initialize global variables. + g_currentProcess = GetCurrentProcess(); + g_currentThread = GetCurrentThread(); + g_processHeap = GetProcessHeap(); + + LoaderLock ll; + + g_heapMapLock.Initialize(); + g_vldHeap = HeapCreate(0x0, 0, 0); + g_vldHeapLock.Initialize(); + g_pReportHooks = new ReportHookSet; + + // Initialize remaining private data. + m_heapMap = new HeapMap; + m_heapMap->reserve(HEAP_MAP_RESERVE); + m_iMalloc = NULL; + m_requestCurr = 1; + m_totalAlloc = 0; + m_curAlloc = 0; + m_maxAlloc = 0; + m_loadedModules = new ModuleSet(); + m_optionsLock.Initialize(); + m_modulesLock.Initialize(); + m_selfTestFile = __FILE__; + m_selfTestLine = 0; + m_tlsIndex = TlsAlloc(); + m_tlsLock.Initialize(); + m_tlsMap = new TlsMap; + + if (m_options & VLD_OPT_SELF_TEST) { + // Self-test mode has been enabled. Intentionally leak a small amount of + // memory so that memory leak self-checking can be verified. + if (m_options & VLD_OPT_UNICODE_REPORT) { + wcsncpy_s(new WCHAR [wcslen(SELFTESTTEXTW) + 1], wcslen(SELFTESTTEXTW) + 1, SELFTESTTEXTW, _TRUNCATE); + m_selfTestLine = __LINE__ - 1; + } + else { + strncpy_s(new CHAR [strlen(SELFTESTTEXTA) + 1], strlen(SELFTESTTEXTA) + 1, SELFTESTTEXTA, _TRUNCATE); + m_selfTestLine = __LINE__ - 1; + } + } + if (m_options & VLD_OPT_START_DISABLED) { + // Memory leak detection will initially be disabled. + m_status |= VLD_STATUS_NEVER_ENABLED; + } + if (m_options & VLD_OPT_REPORT_TO_FILE) { + setupReporting(); + } + if (m_options & VLD_OPT_SLOW_DEBUGGER_DUMP) { + // Insert a slight delay between messages sent to the debugger for + // output. (For working around a bug in VC6 where data sent to the + // debugger gets lost if it's sent too fast). + InsertReportDelay(); + } + + // This is highly unlikely to happen, but just in case, check to be sure + // we got a valid TLS index. + if (m_tlsIndex == TLS_OUT_OF_INDEXES) { + Report(L"ERROR: Visual Leak Detector could not be installed because thread local" + L" storage could not be allocated."); + return; + } + + // Initialize the symbol handler. We use it for obtaining source file/line + // number information and function names for the memory leak report. + LPWSTR symbolpath = buildSymbolSearchPath(); +#ifdef NOISY_DBGHELP_DIAGOSTICS + // From MSDN docs about SYMOPT_DEBUG: + /* To view all attempts to load symbols, call SymSetOptions with SYMOPT_DEBUG. + This causes DbgHelp to call the OutputDebugString function with detailed + information on symbol searches, such as the directories it is searching and and error messages. + In other words, this will really pollute the debug output window with extra messages. + To enable this debug output to be displayed to the console without changing your source code, + set the DBGHELP_DBGOUT environment variable to a non-NULL value before calling the SymInitialize function. + To log the information to a file, set the DBGHELP_LOG environment variable to the name of the log file to be used. + */ + g_DbgHelp.SymSetOptions(SYMOPT_DEBUG | SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES); +#else + g_DbgHelp.SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES); +#endif + DbgTrace(L"dbghelp32.dll %i: SymInitializeW\n", GetCurrentThreadId()); + if (!g_DbgHelp.SymInitializeW(g_currentProcess, symbolpath, FALSE)) { + Report(L"WARNING: Visual Leak Detector: The symbol handler failed to initialize (error=%lu).\n" + L" File and function names will probably not be available in call stacks.\n", GetLastError()); + } + delete [] symbolpath; + + ntdllPatch[0].moduleBase = (UINT_PTR)ntdll; + PatchImport(kernel32, ntdllPatch); + if (kernelBase != NULL) + PatchImport(kernelBase, ntdllPatch); + + // Attach Visual Leak Detector to every module loaded in the process. + ModuleSet* newmodules = new ModuleSet(); + newmodules->reserve(MODULE_SET_RESERVE); + DbgTrace(L"dbghelp32.dll %i: EnumerateLoadedModulesW64\n", GetCurrentThreadId()); + g_LoadedModules.EnumerateLoadedModulesW64(g_currentProcess, addLoadedModule, newmodules); + attachToLoadedModules(newmodules); + ModuleSet* oldmodules = m_loadedModules; + m_loadedModules = newmodules; + delete oldmodules; + m_status |= VLD_STATUS_INSTALLED; + + m_dbghlpBase = GetModuleHandleW(L"dbghelp.dll"); + if (m_dbghlpBase) + ChangeModuleState(m_dbghlpBase, false); + + Report(L"Visual Leak Detector Version " VLDVERSION L" installed.\n"); + if (m_status & VLD_STATUS_FORCE_REPORT_TO_FILE) { + // The report is being forced to a file. Let the human know why. + Report(L"NOTE: Visual Leak Detector: Unicode-encoded reporting has been enabled, but the\n" + L" debugger is the only selected report destination. The debugger cannot display\n" + L" Unicode characters, so the report will also be sent to a file. If no file has\n" + L" been specified, the default file name is \"" VLD_DEFAULT_REPORT_FILE_NAME L"\".\n"); + } + reportConfig(); +} + +bool VisualLeakDetector::waitForAllVLDThreads() +{ + bool threadsactive = false; + DWORD dwCurProcessID = GetCurrentProcessId(); + int waitcount = 0; + + // See if any threads that have ever entered VLD's code are still active. + CriticalSectionLocker<> cs(m_tlsLock); + for (TlsMap::Iterator tlsit = m_tlsMap->begin(); tlsit != m_tlsMap->end(); ++tlsit) { + if ((*tlsit).second->threadId == GetCurrentThreadId()) { + // Don't wait for the current thread to exit. + continue; + } + + HANDLE thread = OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, (*tlsit).second->threadId); + if (thread == NULL) { + // Couldn't query this thread. We'll assume that it exited. + continue; // XXX should we check GetLastError()? + } + if (GetProcessIdOfThread(thread) != dwCurProcessID) { + //The thread ID has been recycled. + CloseHandle(thread); + continue; + } + if (WaitForSingleObject(thread, 10000) == WAIT_TIMEOUT) { // 10 seconds + // There is still at least one other thread running. The CRT + // will stomp it dead when it cleans up, which is not a + // graceful way for a thread to go down. Warn about this, + // and wait until the thread has exited so that we know it + // can't still be off running somewhere in VLD's code. + // + // Since we've been waiting a while, let the human know we are + // still here and alive. + waitcount++; + threadsactive = true; + if (waitcount >= 9) // 90 sec. + { + CloseHandle(thread); + return threadsactive; + } + Report(L"Visual Leak Detector: Waiting for threads to terminate...\n"); + } + CloseHandle(thread); + } + return threadsactive; +} + +void VisualLeakDetector::checkInternalMemoryLeaks() +{ + const char* leakfile = NULL; + size_t count; + WCHAR leakfilew [MAX_PATH]; + int leakline = 0; + + // Do a memory leak self-check. + SIZE_T internalleaks = 0; + vldblockheader_t *header = g_vldBlockList; + while (header) { + // Doh! VLD still has an internally allocated block! + // This won't ever actually happen, right guys?... guys? + internalleaks++; + leakfile = header->file; + leakline = header->line; + mbstowcs_s(&count, leakfilew, MAX_PATH, leakfile, _TRUNCATE); + Report(L"ERROR: Visual Leak Detector: Detected a memory leak internal to Visual Leak Detector!!\n"); + Report(L"---------- Block %Iu at " ADDRESSFORMAT L": %Iu bytes ----------\n", header->serialNumber, VLDBLOCKDATA(header), header->size); + Report(L" Call Stack:\n"); + Report(L" %s (%d): Full call stack not available.\n", leakfilew, leakline); + if (m_maxDataDump != 0) { + Report(L" Data:\n"); + if (m_options & VLD_OPT_UNICODE_REPORT) { + DumpMemoryW(VLDBLOCKDATA(header), (m_maxDataDump < header->size) ? m_maxDataDump : header->size); + } + else { + DumpMemoryA(VLDBLOCKDATA(header), (m_maxDataDump < header->size) ? m_maxDataDump : header->size); + } + } + Report(L"\n"); + header = header->next; + } + if (m_options & VLD_OPT_SELF_TEST) { + if ((internalleaks == 1) && (strcmp(leakfile, m_selfTestFile) == 0) && (leakline == m_selfTestLine)) { + Report(L"Visual Leak Detector passed the memory leak self-test.\n"); + } + else { + Report(L"ERROR: Visual Leak Detector: Failed the memory leak self-test.\n"); + } + } +} + +// Destructor - Detaches Visual Leak Detector from all modules loaded in the +// process, frees internally allocated resources, and generates the memory +// leak report. +// +VisualLeakDetector::~VisualLeakDetector () +{ + LoaderLock ll; + + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return; + } + + if (m_status & VLD_STATUS_INSTALLED) { + // Detach Visual Leak Detector from all previously attached modules. + DbgTrace(L"dbghelp32.dll %i: EnumerateLoadedModulesW64\n", GetCurrentThreadId()); + g_LoadedModules.EnumerateLoadedModulesW64(g_currentProcess, detachFromModule, NULL); + + HMODULE kernel32 = GetModuleHandleW(L"kernel32.dll"); + HMODULE kernelBase = GetModuleHandleW(L"KernelBase.dll"); + RestoreImport(kernel32, ntdllPatch); + if (kernelBase != NULL) + RestoreImport(kernelBase, ntdllPatch); + + BOOL threadsactive = waitForAllVLDThreads(); + + if (m_status & VLD_STATUS_NEVER_ENABLED) { + // Visual Leak Detector started with leak detection disabled and + // it was never enabled at runtime. A lot of good that does. + Report(L"WARNING: Visual Leak Detector: Memory leak detection was never enabled.\n"); + } + else { + // Generate a memory leak report for each heap in the process. + SIZE_T leaks_count = ReportLeaks(); + + // Show a summary. + if (leaks_count == 0) { + Report(L"No memory leaks detected.\n"); + } + else { + Report(L"Visual Leak Detector detected %Iu memory leak", leaks_count); + Report((leaks_count > 1) ? L"s (%Iu bytes).\n" : L" (%Iu bytes).\n", m_curAlloc); + Report(L"Largest number used: %Iu bytes.\n", m_maxAlloc); + Report(L"Total allocations: %Iu bytes.\n", m_totalAlloc); + } + } + + // Free resources used by the symbol handler. + DbgTrace(L"dbghelp32.dll %i: SymCleanup\n", GetCurrentThreadId()); + if (!g_DbgHelp.SymCleanup(g_currentProcess)) { + Report(L"WARNING: Visual Leak Detector: The symbol handler failed to deallocate resources (error=%lu).\n", + GetLastError()); + } + + { + // Free internally allocated resources used by the heapmap and blockmap. + CriticalSectionLocker<> cs(g_heapMapLock); + for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { + BlockMap *blockmap = &(*heapit).second->blockMap; + for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { + delete (*blockit).second; + } + delete blockmap; + } + delete m_heapMap; + } + delete m_loadedModules; + + { + // Free internally allocated resources used for thread local storage. + CriticalSectionLocker<> cs(m_tlsLock); + for (TlsMap::Iterator tlsit = m_tlsMap->begin(); tlsit != m_tlsMap->end(); ++tlsit) { + delete (*tlsit).second; + } + delete m_tlsMap; + } + if (threadsactive) { + Report(L"WARNING: Visual Leak Detector: Some threads appear to have not terminated normally.\n" + L" This could cause inaccurate leak detection results, including false positives.\n"); + } + Report(L"Visual Leak Detector is now exiting.\n"); + + delete g_pReportHooks; + g_pReportHooks = NULL; + + checkInternalMemoryLeaks(); + } + else { + // VLD failed to load properly. + delete m_heapMap; + delete m_tlsMap; + delete g_pReportHooks; + g_pReportHooks = NULL; + } + HeapDestroy(g_vldHeap); + + m_optionsLock.Delete(); + m_modulesLock.Delete(); + m_tlsLock.Delete(); + g_heapMapLock.Delete(); + g_vldHeapLock.Delete(); + + if (m_tlsIndex != TLS_OUT_OF_INDEXES) { + TlsFree(m_tlsIndex); + } + + if (m_reportFile != NULL) { + fclose(m_reportFile); + } + + // Decrement the library reference count. + FreeLibrary(m_vldBase); +} + + +//////////////////////////////////////////////////////////////////////////////// +// +// Private Leak Detection Functions +// +//////////////////////////////////////////////////////////////////////////////// + +UINT32 VisualLeakDetector::getModuleState(ModuleSet::Iterator& it, UINT32& moduleFlags) +{ + const moduleinfo_t& moduleinfo = *it; + DWORD64 modulebase = (DWORD64) moduleinfo.addrLow; + moduleFlags = 0; + + if (!GetCallingModule((UINT_PTR)modulebase)) // module unloaded + return 0; + + { + CriticalSectionLocker<> cs(m_modulesLock); + ModuleSet* oldmodules = m_loadedModules; + ModuleSet::Iterator oldit = oldmodules->find(moduleinfo); + if (oldit != oldmodules->end()) // We've seen this "new" module loaded in the process before. + moduleFlags = (*oldit).flags; + else // This is new loaded module + return 1; + } + + if (IsModulePatched((HMODULE) modulebase, m_patchTable, _countof(m_patchTable))) + { + // This module is already attached. Just update the module's + // flags, nothing more. + ModuleSet::Muterator updateit; + updateit = it; + (*updateit).flags = moduleFlags; + return 2; + } + + // This module may have been attached before and has been + // detached. We'll need to try reattaching to it in case it + // was unloaded and then subsequently reloaded. + return 3; +} + +// dbghelp32.dll should be updated in setup folder if you update dbghelp.h +static char dbghelp32_assert[sizeof(IMAGEHLP_MODULE64) == 3256 ? 1 : -1]; + +// attachtoloadedmodules - Attaches VLD to all modules contained in the provided +// ModuleSet. Not all modules are in the ModuleSet will actually be included +// in leak detection. Only modules that import the global VisualLeakDetector +// class object, or those that are otherwise explicitly included in leak +// detection, will be checked for memory leaks. +// +// When VLD attaches to a module, it means that any of the imports listed in +// the import patch table which are imported by the module, will be redirected +// to VLD's designated replacements. +// +// - newmodules (IN): Pointer to a ModuleSet containing information about any +// loaded modules that need to be attached. +// +// Return Value: +// +// None. +// +VOID VisualLeakDetector::attachToLoadedModules (ModuleSet *newmodules) +{ + LoaderLock ll; + CriticalSectionLocker locker(g_DbgHelp); + + // Iterate through the supplied set, until all modules have been attached. + for (ModuleSet::Iterator newit = newmodules->begin(); newit != newmodules->end(); ++newit) + { + UINT32 moduleFlags = 0x0; + UINT32 state = getModuleState(newit, moduleFlags); + + if (state == 0 || state == 2) + continue; + + DWORD64 modulebase = (DWORD64) (*newit).addrLow; + LPCWSTR modulename = (*newit).name.c_str(); + LPCWSTR modulepath = (*newit).path.c_str(); + DWORD modulesize = (DWORD)((*newit).addrHigh - (*newit).addrLow) + 1; + + if ((state == 3) && (moduleFlags & VLD_MODULE_SYMBOLSLOADED)) { + // Discard the previously loaded symbols, so we can refresh them. + DbgTrace(L"dbghelp32.dll %i: SymUnloadModule64\n", GetCurrentThreadId()); + if (g_DbgHelp.SymUnloadModule64(g_currentProcess, modulebase, locker) == false) { + Report(L"WARNING: Visual Leak Detector: Failed to unload the symbols for %s. Function names and line" + L" numbers shown in the memory leak report for %s may be inaccurate.\n", modulename, modulename); + } + } + + // Try to load the module's symbols. This ensures that we have loaded + // the symbols for every module that has ever been loaded into the + // process, guaranteeing the symbols' availability when generating the + // leak report. + IMAGEHLP_MODULE64 moduleimageinfo; + moduleimageinfo.SizeOfStruct = sizeof(IMAGEHLP_MODULE64); + BOOL SymbolsLoaded = g_DbgHelp.SymGetModuleInfoW64(g_currentProcess, modulebase, &moduleimageinfo, locker); + + if (!SymbolsLoaded || moduleimageinfo.BaseOfImage != modulebase) + { + DbgTrace(L"dbghelp32.dll %i: SymLoadModuleEx\n", GetCurrentThreadId()); + DWORD64 module = g_DbgHelp.SymLoadModuleExW(g_currentProcess, NULL, modulepath, NULL, modulebase, modulesize, NULL, 0, locker); + if (module == modulebase) + { + DbgTrace(L"dbghelp32.dll %i: SymGetModuleInfoW64\n", GetCurrentThreadId()); + SymbolsLoaded = g_DbgHelp.SymGetModuleInfoW64(g_currentProcess, modulebase, &moduleimageinfo, locker); + } + } + if (SymbolsLoaded) + moduleFlags |= VLD_MODULE_SYMBOLSLOADED; + + if (_wcsicmp(TEXT(VLDDLL), modulename) == 0) { + // What happens when a module goes through it's own portal? Bad things. + // Like infinite recursion. And ugly bald men wearing dresses. VLD + // should not, therefore, attach to itself. + continue; + } + + // increase reference count to module + HMODULE modulelocal = NULL; + if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR) modulebase, &modulelocal)) + continue; + + if (!FindImport(modulelocal, m_vldBase, VLDDLL, "?g_vld@@3VVisualLeakDetector@@A")) + { + // mfc dll's shouldn't be excluded, to have matched number of leaks + // from the statically linked MFC and dynamically + bool patchKnownModule = false; + LPSTR modulenamea; + ConvertModulePathToAscii(modulename, &modulenamea); + + for (UINT index = 0; index < _countof(m_patchTable); index++) { + moduleentry_t *entry = &m_patchTable[index]; + if (_stricmp(entry->exportModuleName, modulenamea) == 0) { + if (entry->reportLeaks != 0) + patchKnownModule = true; + break; + } + } + delete[] modulenamea; + + if (!patchKnownModule) + { + // This module does not import VLD. This means that none of the module's + // sources #included vld.h. + if ((m_options & VLD_OPT_MODULE_LIST_INCLUDE) != 0) + { + if (wcsstr(m_forcedModuleList, modulename) == NULL) { + // Exclude this module from leak detection. + moduleFlags |= VLD_MODULE_EXCLUDED; + } + } + else + { + if (wcsstr(m_forcedModuleList, modulename) != NULL) { + // Exclude this module from leak detection. + moduleFlags |= VLD_MODULE_EXCLUDED; + } + } + } + } + if ((moduleFlags & VLD_MODULE_EXCLUDED) == 0 && + !(moduleFlags & VLD_MODULE_SYMBOLSLOADED) || (moduleimageinfo.SymType == SymExport)) { + // This module is going to be included in leak detection, but complete + // symbols for this module couldn't be loaded. This means that any stack + // traces through this module may lack information, like line numbers + // and function names. + Report(L"WARNING: Visual Leak Detector: A module, %s, included in memory leak detection\n" + L" does not have any debugging symbols available, or they could not be located.\n" + L" Function names and/or line numbers for this module may not be available.\n", modulename); + } + + // Update the module's flags in the "new modules" set. + ModuleSet::Muterator updateit; + updateit = newit; + (*updateit).flags = moduleFlags; + + // Attach to the module. + PatchModule(modulelocal, m_patchTable, _countof(m_patchTable)); + + FreeLibrary(modulelocal); + } +} + +// buildsymbolsearchpath - Builds the symbol search path for the symbol handler. +// This helps the symbol handler find the symbols for the application being +// debugged. +// +// Return Value: +// +// Returns a string containing the search path. The caller is responsible for +// freeing the string. +// +LPWSTR VisualLeakDetector::buildSymbolSearchPath () +{ + // Oddly, the symbol handler ignores the link to the PDB embedded in the + // executable image. So, we'll manually add the location of the executable + // to the search path since that is often where the PDB will be located. + WCHAR directory [_MAX_DIR] = {0}; + WCHAR drive [_MAX_DRIVE] = {0}; + LPWSTR path = new WCHAR [MAX_PATH * 4]; + path[0] = L'\0'; + + HMODULE module = GetModuleHandleW(NULL); + GetModuleFileName(module, path, MAX_PATH); + _wsplitpath_s(path, drive, _MAX_DRIVE, directory, _MAX_DIR, NULL, 0, NULL, 0); + wcsncpy_s(path, MAX_PATH, drive, _TRUNCATE); + path = AppendString(path, directory); + path = AppendString(path, L";"); + + // When the symbol handler is given a custom symbol search path, it will no + // longer search the default directories (working directory, _NT_SYMBOL_PATH, + // etc...). But we'd like it to still search those directories, so we'll add + // them to our custom search path. + + // Append the working directory. + path = AppendString(path, L".\\;"); + + // Append %_NT_SYMBOL_PATH%. + DWORD envlen = GetEnvironmentVariable(L"_NT_SYMBOL_PATH", NULL, 0); + if (envlen != 0) { + LPWSTR env = new WCHAR [envlen]; + if (GetEnvironmentVariable(L"_NT_SYMBOL_PATH", env, envlen) != 0) { + path = AppendString(path, env); + path = AppendString(path, L";"); + } + delete [] env; + } + + // Append %_NT_ALT_SYMBOL_PATH%. + envlen = GetEnvironmentVariable(L"_NT_ALT_SYMBOL_PATH", NULL, 0); + if (envlen != 0) { + LPWSTR env = new WCHAR [envlen]; + if (GetEnvironmentVariable(L"_NT_ALT_SYMBOL_PATH", env, envlen) != 0) { + path = AppendString(path, env); + path = AppendString(path, L";"); + } + delete [] env; + } + + // Append %_NT_ALTERNATE_SYMBOL_PATH%. + envlen = GetEnvironmentVariable(L"_NT_ALTERNATE_SYMBOL_PATH", NULL, 0); + if (envlen != 0) { + LPWSTR env = new WCHAR [envlen]; + if (GetEnvironmentVariable(L"_NT_ALTERNATE_SYMBOL_PATH", env, envlen) != 0) { + path = AppendString(path, env); + path = AppendString(path, L";"); + } + delete [] env; + } + +#if _MSC_VER > 1900 +#error Not supported VS +#endif + // Append Visual Studio 2015/2013/2012/2010/2008 symbols cache directory. + for (UINT n = 9; n <= 14; ++n) { + WCHAR debuggerpath[MAX_PATH] = { 0 }; + swprintf(debuggerpath, _countof(debuggerpath), L"Software\\Microsoft\\VisualStudio\\%u.0\\Debugger", n); + HKEY debuggerkey; + WCHAR symbolCacheDir[MAX_PATH] = { 0 }; + LSTATUS regstatus = RegOpenKeyExW(HKEY_CURRENT_USER, debuggerpath, 0, KEY_QUERY_VALUE, &debuggerkey); + + if (regstatus == ERROR_SUCCESS) { + DWORD valuetype; + DWORD dirLength = MAX_PATH * sizeof(WCHAR); + regstatus = RegQueryValueExW(debuggerkey, L"SymbolCacheDir", NULL, &valuetype, (LPBYTE)&symbolCacheDir, &dirLength); + if (regstatus == ERROR_SUCCESS && valuetype == REG_SZ && symbolCacheDir[0] != NULL && !wcsstr(path, symbolCacheDir)) { + path = AppendString(path, symbolCacheDir); + path = AppendString(path, L"\\MicrosoftPublicSymbols;"); + path = AppendString(path, symbolCacheDir); + path = AppendString(path, L";"); + } + RegCloseKey(debuggerkey); + } + } + + // Remove any quotes from the path. The symbol handler doesn't like them. + SIZE_T pos = 0; + SIZE_T length = wcslen(path); + while (pos < length) { + if (path[pos] == L'\"') { + for (SIZE_T index = pos; index < length; index++) { + path[index] = path[index + 1]; + } + } + pos++; + } + + return path; +} + +// GetIniFilePath - Obtains vld.ini file path. +// +// Return Value: +// +// Returns true if an actual vld.ini file was found +// Otherwise, returns false. +// +BOOL VisualLeakDetector::GetIniFilePath(LPTSTR lpPath, SIZE_T cchPath) +{ + TCHAR path[MAX_PATH] = {0}; + struct _stat s; + DWORD written = 0; + + // Get the location of the vld.ini file from current directory path. + if (0 < (written = GetCurrentDirectory(MAX_PATH, path))) { + _tcsncpy_s(&path[written], MAX_PATH - written, TEXT("\\vld.ini"), _TRUNCATE); + if (_tstat(path, &s) == 0) { + _tcsncpy_s(lpPath, cchPath, path, _TRUNCATE); + return TRUE; + } + } + + // Get the location of the vld.ini file from VLDDLL file path. + HMODULE hModule = GetCallingModule((UINT_PTR)this); + if (0 < (written = GetModuleFileName(hModule, path, MAX_PATH))) { + LPTSTR p = _tcsrchr(path, TEXT('\\')); + written = (DWORD)(p - path); + if (p && 0 == _tcsncpy_s(p, MAX_PATH - written, TEXT("\\vld.ini"), _TRUNCATE)) { + if (_tstat(path, &s) == 0) { + _tcsncpy_s(lpPath, cchPath, path, _TRUNCATE); + return TRUE; + } + } + } + + // Get the location of the vld.ini file from executable file path. + if (0 < (written = GetModuleFileName(NULL, path, MAX_PATH))) { + LPTSTR p = _tcsrchr(path, TEXT('\\')); + written = (DWORD)(p - path); + if (p && 0 == _tcsncpy_s(p, MAX_PATH - written, TEXT("\\vld.ini"), _TRUNCATE)) { + if (_tstat(path, &s) == 0) { + _tcsncpy_s(lpPath, cchPath, path, _TRUNCATE); + return TRUE; + } + } + } + + HKEY productkey = 0; + DWORD length = 0; + DWORD valuetype = 0; + + // Get the location of the vld.ini file from the registry. + LONG regstatus = RegOpenKeyEx(HKEY_CURRENT_USER, VLDREGKEYPRODUCT, 0, KEY_QUERY_VALUE, &productkey); + if (regstatus == ERROR_SUCCESS) { + length = MAX_PATH * sizeof(TCHAR); + regstatus = RegQueryValueEx(productkey, TEXT("IniFile"), NULL, &valuetype, (LPBYTE)&path, &length); + RegCloseKey(productkey); + if (regstatus == ERROR_SUCCESS && (_tstat(path, &s) == 0)) { + _tcsncpy_s(lpPath, cchPath, path, _TRUNCATE); + return TRUE; + } + } + + // Get the location of the vld.ini file from the registry. + regstatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, VLDREGKEYPRODUCT, 0, KEY_QUERY_VALUE, &productkey); + if (regstatus == ERROR_SUCCESS) { + length = MAX_PATH * sizeof(TCHAR); + regstatus = RegQueryValueEx(productkey, TEXT("IniFile"), NULL, &valuetype, (LPBYTE)&path, &length); + RegCloseKey(productkey); + if (regstatus == ERROR_SUCCESS && (_tstat(path, &s) == 0)) { + _tcsncpy_s(lpPath, cchPath, path, _TRUNCATE); + return TRUE; + } + } + + _tcsncpy_s(lpPath, cchPath, TEXT("vld.ini"), _TRUNCATE); + return FALSE; +} + +// configure - Configures VLD using values read from the vld.ini file. +// +// Return Value: +// +// None. +// +VOID VisualLeakDetector::configure () +{ + TCHAR inipath [MAX_PATH] = {0}; + BOOL found = GetIniFilePath(inipath, _countof(inipath)); + + Report(L"Visual Leak Detector read settings from: %s\n", found ? inipath : L"(default settings)"); + + // Read the boolean options. + const UINT buffersize = 64; + WCHAR buffer[buffersize] = { 0 }; + + if (!GetEnvironmentVariable(L"VLD", buffer, buffersize)) { + GetPrivateProfileString(L"Options", L"VLD", L"on", buffer, buffersize, inipath); + } + + if (StrToBool(buffer) == FALSE) { + m_options |= VLD_OPT_VLDOFF; + return; + } + + if (LoadBoolOption(L"AggregateDuplicates", L"", inipath)) { + m_options |= VLD_OPT_AGGREGATE_DUPLICATES; + } + + if (LoadBoolOption(L"SelfTest", L"", inipath)) { + m_options |= VLD_OPT_SELF_TEST; + } + + if (LoadBoolOption(L"SlowDebuggerDump", L"", inipath)) { + m_options |= VLD_OPT_SLOW_DEBUGGER_DUMP; + } + + if (LoadBoolOption(L"StartDisabled", L"", inipath)) { + m_options |= VLD_OPT_START_DISABLED; + } + + if (LoadBoolOption(L"TraceInternalFrames", L"", inipath)) { + m_options |= VLD_OPT_TRACE_INTERNAL_FRAMES; + } + + if (LoadBoolOption(L"SkipHeapFreeLeaks", L"", inipath)) { + m_options |= VLD_OPT_SKIP_HEAPFREE_LEAKS; + } + + if (LoadBoolOption(L"SkipCrtStartupLeaks", L"yes", inipath)) { + m_options |= VLD_OPT_SKIP_CRTSTARTUP_LEAKS; + } + + // Read the integer configuration options. + m_maxDataDump = LoadIntOption(L"MaxDataDump", VLD_DEFAULT_MAX_DATA_DUMP, inipath); + m_maxTraceFrames = LoadIntOption(L"MaxTraceFrames", VLD_DEFAULT_MAX_TRACE_FRAMES, inipath); + if (m_maxTraceFrames < 1) { + m_maxTraceFrames = VLD_DEFAULT_MAX_TRACE_FRAMES; + } + + // Read the force-include module list. + LoadStringOption(L"ForceIncludeModules", m_forcedModuleList, MAXMODULELISTLENGTH, inipath); + _wcslwr_s(m_forcedModuleList, MAXMODULELISTLENGTH); + if (wcscmp(m_forcedModuleList, L"*") == 0) + m_forcedModuleList[0] = '\0'; + else + m_options |= VLD_OPT_MODULE_LIST_INCLUDE; + + // Read the report destination (debugger, file, or both). + WCHAR filename [MAX_PATH] = {0}; + LoadStringOption(L"ReportFile", filename, MAX_PATH, inipath); + if (filename[0] == '\0') { + wcsncpy_s(filename, MAX_PATH, VLD_DEFAULT_REPORT_FILE_NAME, _TRUNCATE); + } + WCHAR* path = _wfullpath(m_reportFilePath, filename, MAX_PATH); + assert(path); + + LoadStringOption(L"ReportTo", buffer, buffersize, inipath); + if (_wcsicmp(buffer, L"both") == 0) { + m_options |= (VLD_OPT_REPORT_TO_DEBUGGER | VLD_OPT_REPORT_TO_FILE); + } + else if (_wcsicmp(buffer, L"file") == 0) { + m_options |= VLD_OPT_REPORT_TO_FILE; + } + else if (_wcsicmp(buffer, L"stdout") == 0) { + m_options |= VLD_OPT_REPORT_TO_STDOUT; + } + else { + m_options |= VLD_OPT_REPORT_TO_DEBUGGER; + } + + // Read the report file encoding (ascii or unicode). + LoadStringOption(L"ReportEncoding", buffer, buffersize, inipath); + if (_wcsicmp(buffer, L"unicode") == 0) { + m_options |= VLD_OPT_UNICODE_REPORT; + } + if ((m_options & VLD_OPT_UNICODE_REPORT) && !(m_options & VLD_OPT_REPORT_TO_FILE)) { + // If Unicode report encoding is enabled, then the report needs to be + // sent to a file because the debugger will not display Unicode + // characters, it will display question marks in their place instead. + m_options |= VLD_OPT_REPORT_TO_FILE; + m_status |= VLD_STATUS_FORCE_REPORT_TO_FILE; + } + + // Read the stack walking method. + LoadStringOption(L"StackWalkMethod", buffer, buffersize, inipath); + if (_wcsicmp(buffer, L"safe") == 0) { + m_options |= VLD_OPT_SAFE_STACK_WALK; + } + + if (LoadBoolOption(L"ValidateHeapAllocs", L"", inipath)) { + m_options |= VLD_OPT_VALIDATE_HEAPFREE; + } +} + +// enabled - Determines if memory leak detection is enabled for the current +// thread. +// +// Return Value: +// +// Returns true if Visual Leak Detector is enabled for the current thread. +// Otherwise, returns false. +// +BOOL VisualLeakDetector::enabled () +{ + if (!(m_status & VLD_STATUS_INSTALLED)) { + // Memory leak detection is not yet enabled because VLD is still + // initializing. + return FALSE; + } + + tls_t* tls = getTls(); + if (!(tls->flags & VLD_TLS_DISABLED) && !(tls->flags & VLD_TLS_ENABLED)) { + // The enabled/disabled state for the current thread has not been + // initialized yet. Use the default state. + if (m_options & VLD_OPT_START_DISABLED) { + tls->flags |= VLD_TLS_DISABLED; + } + else { + tls->flags |= VLD_TLS_ENABLED; + } + } + + return ((tls->flags & VLD_TLS_ENABLED) != 0); +} + +// eraseduplicates - Erases, from the block maps, blocks that appear to be +// duplicate leaks of an already identified leak. +// +// - element (IN): BlockMap Iterator referencing the block of which to search +// for duplicates. +// +// Return Value: +// +// Returns the number of duplicate blocks erased from the block map. +// +SIZE_T VisualLeakDetector::eraseDuplicates (const BlockMap::Iterator &element, Set &aggregatedLeaks) +{ + blockinfo_t *elementinfo = (*element).second; + + if (elementinfo->callStack == NULL) + return 0; + + SIZE_T erased = 0; + // Iterate through all block maps, looking for blocks with the same size + // and callstack as the specified element. + CriticalSectionLocker<> cs(g_heapMapLock); + for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { + BlockMap *blockmap = &(*heapit).second->blockMap; + for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { + if (blockit == element) { + // Don't delete the element of which we are searching for + // duplicates. + continue; + } + blockinfo_t *info = (*blockit).second; + if (info->callStack == NULL) + continue; + Set::Iterator it = aggregatedLeaks.find(info); + if (it != aggregatedLeaks.end()) + continue; + if ((info->size == elementinfo->size) && (*(info->callStack) == *(elementinfo->callStack))) { + // Found a duplicate. Mark it. + aggregatedLeaks.insert(info); + erased++; + } + } + } + + return erased; +} + +// gettls - Obtains the thread local storage structure for the calling thread. +// +// Return Value: +// +// Returns a pointer to the thread local storage structure. (This function +// always succeeds). +// +tls_t* VisualLeakDetector::getTls () +{ + // Get the pointer to this thread's thread local storage structure. + tls_t* tls = (tls_t*)TlsGetValue(m_tlsIndex); + assert(GetLastError() == ERROR_SUCCESS); + + if (tls == NULL) { + DWORD threadId = GetCurrentThreadId(); + + CriticalSectionLocker<> cs(m_tlsLock); + TlsMap::Iterator it = m_tlsMap->find(threadId); + if (it == m_tlsMap->end()) { + // This thread's thread local storage structure has not been allocated. + tls = new tls_t; + + // Add this thread's TLS to the TlsSet. + m_tlsMap->insert(threadId, tls); + } else { + // Already had a thread with this ID + tls = (*it).second; + } + + ZeroMemory(&tls->context, sizeof(tls->context)); + tls->flags = 0x0; + tls->oldFlags = 0x0; + tls->threadId = threadId; + tls->blockWithoutGuard = NULL; + TlsSetValue(m_tlsIndex, tls); + } + + return tls; +} + +// mapblock - Tracks memory allocations. Information about allocated blocks is +// collected and then the block is mapped to this information. +// +// - heap (IN): Handle to the heap from which the block has been allocated. +// +// - mem (IN): Pointer to the memory block being allocated. +// +// - size (IN): Size, in bytes, of the memory block being allocated. +// +// - addrOfRetAddr (IN): Address of return address at the time this allocation +// first entered VLD's code. This is used from determining the starting +// point for the stack trace. +// +// - crtalloc (IN): Should be set to TRUE if this allocation is a CRT memory +// block. Otherwise should be FALSE. +// +// Return Value: +// +// None. +// +VOID VisualLeakDetector::mapBlock (HANDLE heap, LPCVOID mem, SIZE_T size, bool debugcrtalloc, bool ucrt, DWORD threadId, blockinfo_t* &pblockInfo) +{ + CriticalSectionLocker<> cs(g_heapMapLock); + + // Record the block's information. + blockinfo_t* blockinfo = new blockinfo_t(); + blockinfo->callStack = NULL; + pblockInfo = blockinfo; + blockinfo->threadId = threadId; + blockinfo->serialNumber = m_requestCurr++; + blockinfo->size = size; + blockinfo->reported = false; + blockinfo->debugCrtAlloc = debugcrtalloc; + blockinfo->ucrt = ucrt; + + if (SIZE_MAX - m_totalAlloc > size) + m_totalAlloc += size; + else + m_totalAlloc = SIZE_MAX; + m_curAlloc += size; + + if (m_curAlloc > m_maxAlloc) + m_maxAlloc = m_curAlloc; + + // Insert the block's information into the block map. + HeapMap::Iterator heapit = m_heapMap->find(heap); + if (heapit == m_heapMap->end()) { + // We haven't mapped this heap to a block map yet. Do it now. + mapHeap(heap); + heapit = m_heapMap->find(heap); + assert(heapit != m_heapMap->end()); + } + BlockMap* blockmap = &(*heapit).second->blockMap; + BlockMap::Iterator blockit = blockmap->insert(mem, blockinfo); + if (blockit == blockmap->end()) { + // A block with this address has already been allocated. The + // previously allocated block must have been freed (probably by some + // mechanism unknown to VLD), or the heap wouldn't have allocated it + // again. Replace the previously allocated info with the new info. + blockit = blockmap->find(mem); + blockinfo_t* info = (*blockit).second; + m_curAlloc -= info->size; + Report(L"VLD: New allocation at already allocated address: 0x%p with size: %u and new size: %u\n", mem, info->size, size); + delete info; + blockmap->erase(blockit); + blockmap->insert(mem, blockinfo); + } +} + +// mapheap - Tracks heap creation. Creates a block map for tracking individual +// allocations from the newly created heap and then maps the heap to this +// block map. +// +// - heap (IN): Handle to the newly created heap. +// +// Return Value: +// +// None. +// +VOID VisualLeakDetector::mapHeap (HANDLE heap) +{ + CriticalSectionLocker<> cs(g_heapMapLock); + + // Create a new block map for this heap and insert it into the heap map. + heapinfo_t* heapinfo = new heapinfo_t; + heapinfo->blockMap.reserve(BLOCK_MAP_RESERVE); + heapinfo->flags = 0x0; + + HeapMap::Iterator heapit = m_heapMap->insert(heap, heapinfo); + if (heapit == m_heapMap->end()) { + // Somehow this heap has been created twice without being destroyed, + // or at least it was destroyed without VLD's knowledge. Unmap the heap + // from the existing heapinfo, and remap it to the new one. + Report(L"WARNING: Visual Leak Detector detected a duplicate heap (" ADDRESSFORMAT L").\n", heap); + heapit = m_heapMap->find(heap); + unmapHeap((*heapit).first); + m_heapMap->insert(heap, heapinfo); + } +} + +// unmapblock - Tracks memory blocks that are freed. Unmaps the specified block +// from the block's information, relinquishing internally allocated resources. +// +// - heap (IN): Handle to the heap to which this block is being freed. +// +// - mem (IN): Pointer to the memory block being freed. +// +// Return Value: +// +// None. +// +VOID VisualLeakDetector::unmapBlock (HANDLE heap, LPCVOID mem, const context_t &context) +{ + if (NULL == mem) + return; + + // Find this heap's block map. + CriticalSectionLocker<> cs(g_heapMapLock); + HeapMap::Iterator heapit = m_heapMap->find(heap); + if (heapit == m_heapMap->end()) { + // We don't have a block map for this heap. We must not have monitored + // this allocation (probably happened before VLD was initialized). + return; + } + + // Find this block in the block map. + BlockMap *blockmap = &(*heapit).second->blockMap; + BlockMap::Iterator blockit = blockmap->find(mem); + if (blockit == blockmap->end()) + { + // This memory block is not in the block map. We must not have monitored this + // allocation (probably happened before VLD was initialized). + + // This can also result from allocating on one heap, and freeing on another heap. + // This is an especially bad way to corrupt the application. + // Now we have to search through every heap and every single block in each to make + // sure that this is indeed the case. + if (m_options & VLD_OPT_VALIDATE_HEAPFREE) + { + HANDLE other_heap = NULL; + blockinfo_t* alloc_block = findAllocedBlock(mem, other_heap); // other_heap is an out parameter + bool diff = other_heap != heap; // Check indeed if the other heap is different + if (alloc_block && alloc_block->callStack && diff) + { + Report(L"CRITICAL ERROR!: VLD reports that memory was allocated in one heap and freed in another.\nThis will result in a corrupted heap.\nAllocation Call stack.\n"); + Report(L"---------- Block %Iu at " ADDRESSFORMAT L": %Iu bytes ----------\n", alloc_block->serialNumber, mem, alloc_block->size); + Report(L" TID: %u\n", alloc_block->threadId); + Report(L" Call Stack:\n"); + alloc_block->callStack->dump(m_options & VLD_OPT_TRACE_INTERNAL_FRAMES); + + // Now we need a way to print the current callstack at this point: + CallStack* stack_here = CallStack::Create(); + stack_here->getStackTrace(m_maxTraceFrames, context); + Report(L"Deallocation Call stack.\n"); + Report(L"---------- Block %Iu at " ADDRESSFORMAT L": %Iu bytes ----------\n", alloc_block->serialNumber, mem, alloc_block->size); + Report(L" Call Stack:\n"); + stack_here->dump(FALSE); + // Now it should be safe to delete our temporary callstack + delete stack_here; + stack_here = NULL; + if (IsDebuggerPresent()) + DebugBreak(); + } + } + return; + } + + // Free the blockinfo_t structure and erase it from the block map. + blockinfo_t *info = (*blockit).second; + m_curAlloc -= info->size; + delete info; + blockmap->erase(blockit); +} + +// unmapheap - Tracks heap destruction. Unmaps the specified heap from its block +// map. The block map is cleared and deleted, relinquishing internally +// allocated resources. +// +// - heap (IN): Handle to the heap which is being destroyed. +// +// Return Value: +// +// None. +// +VOID VisualLeakDetector::unmapHeap (HANDLE heap) +{ + // Find this heap's block map. + CriticalSectionLocker<> cs(g_heapMapLock); + HeapMap::Iterator heapit = m_heapMap->find(heap); + if (heapit == m_heapMap->end()) { + // This heap hasn't been mapped. We must not have monitored this heap's + // creation (probably happened before VLD was initialized). + return; + } + + // Free all of the blockinfo_t structures stored in the block map. + heapinfo_t *heapinfo = (*heapit).second; + BlockMap *blockmap = &heapinfo->blockMap; + for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { + m_curAlloc -= (*blockit).second->size; + delete (*blockit).second; + } + delete heapinfo; + + // Remove this heap's block map from the heap map. + m_heapMap->erase(heapit); +} + +// remapblock - Tracks reallocations. Unmaps a block from its previously +// collected information and remaps it to updated information. +// +// Note: If the block itself remains at the same address, then the block's +// information can simply be updated rather than having to actually erase and +// reinsert the block. +// +// - heap (IN): Handle to the heap from which the memory is being reallocated. +// +// - mem (IN): Pointer to the memory block being reallocated. +// +// - newmem (IN): Pointer to the memory block being returned to the caller +// that requested the reallocation. This pointer may or may not be the same +// as the original memory block (as pointed to by "mem"). +// +// - size (IN): Size, in bytes, of the new memory block. +// +// - framepointer (IN): The frame pointer at which this reallocation entered +// VLD's code. Used for determining the starting point of the stack trace. +// +// - crtalloc (IN): Should be set to TRUE if this reallocation is for a CRT +// memory block. Otherwise should be set to FALSE. +// +// Return Value: +// +// None. +// +VOID VisualLeakDetector::remapBlock (HANDLE heap, LPCVOID mem, LPCVOID newmem, SIZE_T size, + bool debugcrtalloc, bool ucrt, DWORD threadId, blockinfo_t* &pblockInfo, const context_t &context) +{ + CriticalSectionLocker<> cs(g_heapMapLock); + + if (newmem != mem) { + // The block was not reallocated in-place. Instead the old block was + // freed and a new block allocated to satisfy the new size. + unmapBlock(heap, mem, context); + mapBlock(heap, newmem, size, debugcrtalloc, ucrt, threadId, pblockInfo); + return; + } + + // The block was reallocated in-place. Find the existing blockinfo_t + // entry in the block map and update it with the new callstack and size. + HeapMap::Iterator heapit = m_heapMap->find(heap); + if (heapit == m_heapMap->end()) { + // We haven't mapped this heap to a block map yet. Obviously the + // block has also not been mapped to a blockinfo_t entry yet either, + // so treat this reallocation as a brand-new allocation (this will + // also map the heap to a new block map). + mapBlock(heap, newmem, size, debugcrtalloc, ucrt, threadId, pblockInfo); + return; + } + + // Find the block's blockinfo_t structure so that we can update it. + BlockMap *blockmap = &(*heapit).second->blockMap; + BlockMap::Iterator blockit = blockmap->find(mem); + if (blockit == blockmap->end()) { + // The block hasn't been mapped to a blockinfo_t entry yet. + // Treat this reallocation as a new allocation. + mapBlock(heap, newmem, size, debugcrtalloc, ucrt, threadId, pblockInfo); + return; + } + + // Found the blockinfo_t entry for this block. Update it with + // a new callstack and new size. + blockinfo_t* info = (*blockit).second; + if (info->callStack) + { + info->callStack.reset(); + } + + if (m_totalAlloc < SIZE_MAX) + { + m_totalAlloc -= info->size; + if (SIZE_MAX - m_totalAlloc > size) + m_totalAlloc += size; + else + m_totalAlloc = SIZE_MAX; + } + + m_curAlloc -= info->size; + m_curAlloc += size; + + if (m_curAlloc > m_maxAlloc) + m_maxAlloc = m_curAlloc; + + info->threadId = threadId; + // Update the block's size. + info->size = size; + pblockInfo = info; +} + +// reportconfig - Generates a brief report summarizing Visual Leak Detector's +// configuration, as loaded from the vld.ini file. +// +// Return Value: +// +// None. +// +VOID VisualLeakDetector::reportConfig () +{ + if (m_options & VLD_OPT_AGGREGATE_DUPLICATES) { + Report(L" Aggregating duplicate leaks.\n"); + } + if (m_forcedModuleList[0] != '\0') { + Report(L" Forcing %s of these modules in leak detection: %s\n", + (m_options & VLD_OPT_MODULE_LIST_INCLUDE) ? L"inclusion" : L"exclusion", m_forcedModuleList); + } + if (m_maxDataDump != VLD_DEFAULT_MAX_DATA_DUMP) { + if (m_maxDataDump == 0) { + Report(L" Suppressing data dumps.\n"); + } + else { + Report(L" Limiting data dumps to %Iu bytes.\n", m_maxDataDump); + } + } + if (m_maxTraceFrames != VLD_DEFAULT_MAX_TRACE_FRAMES) { + Report(L" Limiting stack traces to %u frames.\n", m_maxTraceFrames); + } + if (m_options & VLD_OPT_UNICODE_REPORT) { + Report(L" Generating a Unicode (UTF-16) encoded report.\n"); + } + if (m_options & VLD_OPT_REPORT_TO_FILE) { + if (m_options & VLD_OPT_REPORT_TO_DEBUGGER) { + Report(L" Outputting the report to the debugger and to %s\n", m_reportFilePath); + } + else { + Report(L" Outputting the report to %s\n", m_reportFilePath); + } + } + if (m_options & VLD_OPT_SLOW_DEBUGGER_DUMP) { + Report(L" Outputting the report to the debugger at a slower rate.\n"); + } + if (m_options & VLD_OPT_SAFE_STACK_WALK) { + Report(L" Using the \"safe\" (but slow) stack walking method.\n"); + } + if (m_options & VLD_OPT_SELF_TEST) { + Report(L" Performing a memory leak self-test.\n"); + } + if (m_options & VLD_OPT_START_DISABLED) { + Report(L" Starting with memory leak detection disabled.\n"); + } + if (m_options & VLD_OPT_TRACE_INTERNAL_FRAMES) { + Report(L" Including heap and VLD internal frames in stack traces.\n"); + } +} + +bool VisualLeakDetector::isDebugCrtAlloc( LPCVOID block, blockinfo_t* info ) +{ + // Autodetection allocations from statically linked CRT + if (!info->debugCrtAlloc) { + crtdbgblockheader_t* crtheader = (crtdbgblockheader_t*)block; + SIZE_T nSize = sizeof(crtdbgblockheader_t) + crtheader->size + GAPSIZE; + int nValid = _CrtIsValidPointer(block, (unsigned int)info->size, TRUE); + if (_BLOCK_TYPE_IS_VALID(crtheader->use) && nValid && (nSize == info->size)) { + info->debugCrtAlloc = true; + info->ucrt = false; + } + } + + if (!info->debugCrtAlloc) { + crtdbgblockheaderucrt_t* crtheader = (crtdbgblockheaderucrt_t*)block; + SIZE_T nSize = sizeof(crtdbgblockheaderucrt_t) + crtheader->size + GAPSIZE; + int nValid = _CrtIsValidPointer(block, (unsigned int)info->size, TRUE); + if (_BLOCK_TYPE_IS_VALID(crtheader->use) && nValid && (nSize == info->size)) { + info->debugCrtAlloc = true; + info->ucrt = true; + } + } + + return info->debugCrtAlloc; +} + +// getleakscount - Calculate number of memory leaks. +// +// - heap (IN): Handle to the heap for which to generate a memory leak +// report. +// +// Return Value: +// +// None. +// +SIZE_T VisualLeakDetector::getLeaksCount (heapinfo_t* heapinfo, DWORD threadId) +{ + BlockMap* blockmap = &heapinfo->blockMap; + SIZE_T memoryleaks = 0; + + for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) + { + // Found a block which is still in the BlockMap. We've identified a + // potential memory leak. + LPCVOID block = (*blockit).first; + blockinfo_t* info = (*blockit).second; + if (info->reported) + continue; + + if (threadId != ((DWORD)-1) && info->threadId != threadId) + continue; + + if (isDebugCrtAlloc(block, info)) { + // This block is allocated to a CRT heap, so the block has a CRT + // memory block header pretended to it. + int blockUse = getCrtBlockUse(block, info->ucrt); + // Leaks identified as CRT_USE_IGNORE should not be ignored here otherwise + // DynamicLoader/Thread test will randomly fail with less leaks being reported. + if (CRT_USE_TYPE(blockUse) == CRT_USE_FREE || + CRT_USE_TYPE(blockUse) == CRT_USE_INTERNAL) { + // This block is marked as being used internally by the CRT. + // The CRT will free the block after VLD is destroyed. + continue; + } + } + + if (m_options & VLD_OPT_SKIP_CRTSTARTUP_LEAKS) { + // Check for crt startup allocations + if (info->callStack && info->callStack->isCrtStartupAlloc()) { + info->reported = true; + continue; + } + } + + memoryleaks ++; + } + + return memoryleaks; +} + +// reportleaks - Generates a memory leak report for the specified heap. +// +// - heap (IN): Handle to the heap for which to generate a memory leak +// report. +// +// Return Value: +// +// None. +// +SIZE_T VisualLeakDetector::reportHeapLeaks (HANDLE heap) +{ + assert(heap != NULL); + + // Find the heap's information (blockmap, etc). + CriticalSectionLocker<> cs(g_heapMapLock); + HeapMap::Iterator heapit = m_heapMap->find(heap); + if (heapit == m_heapMap->end()) { + // Nothing is allocated from this heap. No leaks. + return 0; + } + + Set aggregatedLeaks; + heapinfo_t* heapinfo = (*heapit).second; + // Generate a memory leak report for heap. + bool firstLeak = true; + SIZE_T leaks_count = reportLeaks(heapinfo, firstLeak, aggregatedLeaks); + + // Show a summary. + if (leaks_count != 0) { + Report(L"Visual Leak Detector detected %Iu memory leak%s in heap " ADDRESSFORMAT L"\n", + leaks_count, (leaks_count > 1) ? L"s" : L"", heap); + } + return leaks_count; +} + +int VisualLeakDetector::getCrtBlockUse(LPCVOID block, bool ucrt) +{ + if (!ucrt) + { + crtdbgblockheader_t* crtheader = (crtdbgblockheader_t*)block; + return crtheader->use; + } + else + { + crtdbgblockheaderucrt_t* crtheader = (crtdbgblockheaderucrt_t*)block; + return crtheader->use; + } +} + +size_t VisualLeakDetector::getCrtBlockSize(LPCVOID block, bool ucrt) +{ + if (!ucrt) + { + crtdbgblockheader_t* crtheader = (crtdbgblockheader_t*)block; + return crtheader->size; + } + else + { + crtdbgblockheaderucrt_t* crtheader = (crtdbgblockheaderucrt_t*)block; + return crtheader->size; + } +} + +SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, Set &aggregatedLeaks, DWORD threadId) +{ + BlockMap* blockmap = &heapinfo->blockMap; + SIZE_T leaksFound = 0; + + for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) + { + // Found a block which is still in the BlockMap. We've identified a + // potential memory leak. + LPCVOID block = (*blockit).first; + blockinfo_t* info = (*blockit).second; + if (info->reported) + continue; + + if (threadId != ((DWORD)-1) && info->threadId != threadId) + continue; + + Set::Iterator it = aggregatedLeaks.find(info); + if (it != aggregatedLeaks.end()) + continue; + + LPCVOID address = block; + SIZE_T size = info->size; + + if (isDebugCrtAlloc( block, info )) { + // This block is allocated to a CRT heap, so the block has a CRT + // memory block header pretended to it. + int blockUse = getCrtBlockUse( block, info->ucrt ); + // Leaks identified as CRT_USE_IGNORE should not be ignored here otherwise + // DynamicLoader/Thread test will randomly fail with less leaks being reported. + if (CRT_USE_TYPE(blockUse) == CRT_USE_FREE || + CRT_USE_TYPE(blockUse) == CRT_USE_INTERNAL) + { + // This block is marked as being used internally by the CRT. + // The CRT will free the block after VLD is destroyed. + continue; + } + + // The CRT header is more or less transparent to the user, so + // the information about the contained block will probably be + // more useful to the user. Accordingly, that's the information + // we'll include in the report. + address = CRTDBGBLOCKDATA(block); + size = getCrtBlockSize(block, info->ucrt); + } + + if (m_options & VLD_OPT_SKIP_CRTSTARTUP_LEAKS) { + // Check for crt startup allocations + if (info->callStack && info->callStack->isCrtStartupAlloc()) { + info->reported = true; + continue; + } + } + + // It looks like a real memory leak. + if (firstLeak) { // A confusing way to only display this message once + Report(L"WARNING: Visual Leak Detector detected memory leaks!\n"); + firstLeak = false; + } + SIZE_T blockLeaksCount = 1; + Report(L"---------- Block %Iu at " ADDRESSFORMAT L": %Iu bytes ----------\n", info->serialNumber, address, size); +#ifdef _DEBUG + if (info->debugCrtAlloc) + { + crtdbgblockheader_t* crtheader = (crtdbgblockheader_t*)block; + Report(L" CRT Alloc ID: %Iu\n", crtheader->request); + assert(size == getCrtBlockSize(block, info->ucrt)); + } +#endif + assert(info->callStack); + if (m_options & VLD_OPT_AGGREGATE_DUPLICATES) { + // Aggregate all other leaks which are duplicates of this one + // under this same heading, to cut down on clutter. + SIZE_T erased = eraseDuplicates(blockit, aggregatedLeaks); + + // add only the number that were erased, since the 'one left over' + // is already recorded as a leak + blockLeaksCount += erased; + } + + DWORD callstackCRC = 0; + if (info->callStack) + callstackCRC = CalculateCRC32(info->size, info->callStack->getHashValue()); + Report(L" Leak Hash: 0x%08X, Count: %Iu, Total %Iu bytes\n", callstackCRC, blockLeaksCount, size * blockLeaksCount); + leaksFound += blockLeaksCount; + + // Dump the call stack. + if (blockLeaksCount == 1) + Report(L" Call Stack (TID %u):\n", info->threadId); + else + Report(L" Call Stack:\n"); + if (info->callStack) + info->callStack->dump(m_options & VLD_OPT_TRACE_INTERNAL_FRAMES); + + // Dump the data in the user data section of the memory block. + if (m_maxDataDump != 0) { + Report(L" Data:\n"); + if (m_options & VLD_OPT_UNICODE_REPORT) { + DumpMemoryW(address, (m_maxDataDump < size) ? m_maxDataDump : size); + } + else { + DumpMemoryA(address, (m_maxDataDump < size) ? m_maxDataDump : size); + } + } + Report(L"\n\n"); + } + + return leaksFound; +} + +VOID VisualLeakDetector::markAllLeaksAsReported (heapinfo_t* heapinfo, DWORD threadId) +{ + BlockMap* blockmap = &heapinfo->blockMap; + + for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) + { + blockinfo_t* info = (*blockit).second; + if (threadId == ((DWORD)-1) || info->threadId == threadId) + info->reported = true; + } +} + +// FindAllocedBlock - Find if a particular memory allocation is tracked inside of VLD. +// This is a really good example of how to iterate through the data structures +// that represent heaps and their associated memory blocks. +// Pre Condition: Be VERY sure that this is only called within a block that already has +// acquired a critical section for m_maplock. +// +// mem - The particular memory address to search for. +// +// Return Value: +// If mem is found, it will return the blockinfo_t pointer, otherwise NULL +// +blockinfo_t* VisualLeakDetector::findAllocedBlock(LPCVOID mem, __out HANDLE& heap) +{ + heap = NULL; + blockinfo_t* result = NULL; + // Iterate through all heaps + CriticalSectionLocker<> cs(g_heapMapLock); + for (HeapMap::Iterator it = m_heapMap->begin(); + it != m_heapMap->end(); + ++it) + { + HANDLE heap_handle = (*it).first; + (heap_handle); // unused + heapinfo_t* heapPtr = (*it).second; + + // Iterate through all memory blocks in each heap + BlockMap& p_block_map = heapPtr->blockMap; + for (BlockMap::Iterator iter = p_block_map.begin(); + iter != p_block_map.end(); + ++iter) + { + if ((*iter).first == mem) + { + // Found the block. + blockinfo_t* alloc_block = (*iter).second; + heap = heap_handle; + result = alloc_block; + break; + } + } + + if (result) + { + break; + } + } + + return result; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// Static Leak Detection Functions (Callbacks) +// +//////////////////////////////////////////////////////////////////////////////// + +// addloadedmodule - Callback function for EnumerateLoadedModules64. This +// function records information about every module loaded in the process, +// each time adding the module's information to the provided ModuleSet (the +// "context" parameter). +// +// When EnumerateLoadedModules64 has finished calling this function for each +// loaded module, then the resulting ModuleSet can be used at any time to get +// information about any modules loaded into the process. +// +// - modulepath (IN): The fully qualified path from where the module was +// loaded. +// +// - modulebase (IN): The base address at which the module has been loaded. +// +// - modulesize (IN): The size, in bytes, of the loaded module. +// +// - context (IN): Pointer to the ModuleSet to which information about each +// module is to be added. +// +// Return Value: +// +// Always returns TRUE, which tells EnumerateLoadedModules64 to continue +// enumerating. +// +BOOL VisualLeakDetector::addLoadedModule (PCWSTR modulepath, DWORD64 modulebase, ULONG modulesize, PVOID context) +{ + vldstring modulepathw(modulepath); + + // Extract just the filename and extension from the module path. + WCHAR filename [_MAX_FNAME]; + WCHAR extension [_MAX_EXT]; + _wsplitpath_s(modulepathw.c_str(), NULL, 0, NULL, 0, filename, _MAX_FNAME, extension, _MAX_EXT); + + vldstring modulename(filename); + modulename.append(extension); + _wcslwr_s(&modulename[0], modulename.size() + 1); + + if (_wcsicmp(modulename.c_str(), TEXT(VLDDLL)) == 0) { + // Record Visual Leak Detector's own base address. + g_vld.m_vldBase = (HMODULE)modulebase; + } + else { + LPSTR modulenamea; + ConvertModulePathToAscii(modulename.c_str(), &modulenamea); + + // See if this is a module listed in the patch table. If it is, update + // the corresponding patch table entries' module base address. + UINT tablesize = _countof(m_patchTable); + for (UINT index = 0; index < tablesize; index++) { + moduleentry_t *entry = &m_patchTable[index]; + if (_stricmp(entry->exportModuleName, modulenamea) == 0) { + entry->moduleBase = (UINT_PTR)modulebase; + } + } + + delete [] modulenamea; + } + + // Record the module's information and store it in the set. + moduleinfo_t moduleinfo; + moduleinfo.addrLow = (UINT_PTR)modulebase; + moduleinfo.addrHigh = (UINT_PTR)(modulebase + modulesize) - 1; + moduleinfo.flags = 0x0; + moduleinfo.name = modulename; + moduleinfo.path = modulepathw; + + ModuleSet* newmodules = (ModuleSet*)context; + newmodules->insert(moduleinfo); + + return TRUE; +} + +// detachfrommodule - Callback function for EnumerateLoadedModules64 that +// detaches Visual Leak Detector from the specified module. If the specified +// module has not previously been attached to, then calling this function will +// not actually result in any changes. +// +// - modulepath (IN): String containing the name, which may include a path, of +// the module to detach from (ignored). +// +// - modulebase (IN): Base address of the module. +// +// - modulesize (IN): Total size of the module (ignored). +// +// - context (IN): User-supplied context (ignored). +// +// Return Value: +// +// Always returns TRUE. +// +BOOL VisualLeakDetector::detachFromModule (PCWSTR /*modulepath*/, DWORD64 modulebase, ULONG /*modulesize*/, + PVOID /*context*/) +{ + UINT tablesize = _countof(m_patchTable); + + RestoreModule((HMODULE)modulebase, m_patchTable, tablesize); + + return TRUE; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// Win32 IAT Replacement Functions +// +//////////////////////////////////////////////////////////////////////////////// + +// _GetProcAddress - Calls to GetProcAddress are patched through to this +// function. If the requested function is a function that has been patched +// through to one of VLD's handlers, then the address of VLD's handler +// function is returned instead of the real address. Otherwise, this +// function is just a wrapper around the real GetProcAddress. +// +// - module (IN): Handle (base address) of the module from which to retrieve +// the address of an exported function. +// +// - procname (IN): ANSI string containing the name of the exported function +// whose address is to be retrieved. +// +// Return Value: +// +// Returns a pointer to the requested function, or VLD's replacement for +// the function, if there is a replacement function. +// +FARPROC VisualLeakDetector::_GetProcAddress (HMODULE module, LPCSTR procname) +{ + FARPROC original = g_vld._RGetProcAddress(module, procname); + if (original) { + // See if there is an entry in the patch table that matches the requested + // function. + UINT tablesize = _countof(g_vld.m_patchTable); + for (UINT index = 0; index < tablesize; index++) { + moduleentry_t *entry = &g_vld.m_patchTable[index]; + if ((entry->moduleBase == 0x0) || ((HMODULE)entry->moduleBase != module)) { + // This patch table entry is for a different module. + continue; + } + + patchentry_t *patchentry = entry->patchTable; + while (patchentry->importName) { + // This patch table entry is for the specified module. If the requested + // imports name matches the entry's import name (or ordinal), then + // return the address of the replacement instead of the address of the + // actual import. + if (HIWORD(patchentry->importName) == 0) { + // Import name is a function ordinal value. + if ((UINT_PTR)patchentry->importName == (UINT_PTR)procname) { + if (patchentry->original != NULL) + *patchentry->original = original; + return (FARPROC)patchentry->replacement; + } + } else { + // Import name is a function name value. + if (strcmp(patchentry->importName, procname) == 0) { + if (patchentry->original != NULL) + *patchentry->original = original; + return (FARPROC)patchentry->replacement; + } + } + patchentry++; + } + } + } + // The requested function is not a patched function. Just return the real + // address of the requested function. + return original; +} + +FARPROC VisualLeakDetector::_RGetProcAddress(HMODULE module, LPCSTR procname) +{ + return m_GetProcAddress(module, procname); +} + +// _GetProcAddress - Calls to GetProcAddress are patched through to this +// function. If the requested function is a function that has been patched +// through to one of VLD's handlers, then the address of VLD's handler +// function is returned instead of the real address. Otherwise, this +// function is just a wrapper around the real GetProcAddress. +// +// - module (IN): Handle (base address) of the module from which to retrieve +// the address of an exported function. +// +// - procname (IN): ANSI string containing the name of the exported function +// whose address is to be retrieved. +// +// - caller (IN) +// +// Return Value: +// +// Returns a pointer to the requested function, or VLD's replacement for +// the function, if there is a replacement function. +// +FARPROC VisualLeakDetector::_GetProcAddressForCaller(HMODULE module, LPCSTR procname, LPVOID caller) +{ + FARPROC original = g_vld._RGetProcAddressForCaller(module, procname, caller); + if (original) { + // See if there is an entry in the patch table that matches the requested + // function. + UINT tablesize = _countof(g_vld.m_patchTable); + for (UINT index = 0; index < tablesize; index++) { + moduleentry_t *entry = &g_vld.m_patchTable[index]; + if ((entry->moduleBase == 0x0) || ((HMODULE)entry->moduleBase != module)) { + // This patch table entry is for a different module. + continue; + } + + patchentry_t *patchentry = entry->patchTable; + while (patchentry->importName) { + // This patch table entry is for the specified module. If the requested + // imports name matches the entry's import name (or ordinal), then + // return the address of the replacement instead of the address of the + // actual import. + if (HIWORD(patchentry->importName) == 0) { + // Import name is a function ordinal value. + if ((UINT_PTR)patchentry->importName == (UINT_PTR)procname) { + if (patchentry->original != NULL) + *patchentry->original = original; + return (FARPROC)patchentry->replacement; + } + } else { + // Import name is a function name value. + if (strcmp(patchentry->importName, procname) == 0) { + if (patchentry->original != NULL) + *patchentry->original = original; + return (FARPROC)patchentry->replacement; + } + } + patchentry++; + } + } + } + + // The requested function is not a patched function. Just return the real + // address of the requested function. + return original; +} + +FARPROC VisualLeakDetector::_RGetProcAddressForCaller(HMODULE module, LPCSTR procname, LPVOID caller) +{ + return m_GetProcAddressForCaller(module, procname, caller); +} + +// _LdrLoadDll - Calls to LdrLoadDll are patched through to this function. This +// function invokes the real LdrLoadDll and then re-attaches VLD to all +// modules loaded in the process after loading of the new DLL is complete. +// All modules must be re-enumerated because the explicit load of the +// specified module may result in the implicit load of one or more additional +// modules which are dependencies of the specified module. +// +// - searchpath (IN): The path to use for searching for the specified module to +// be loaded. +// +// - flags (IN): Pointer to action flags. +// +// - modulename (IN): Pointer to a unicodestring_t structure specifying the +// name of the module to be loaded. +// +// - modulehandle (OUT): Address of a HANDLE to receive the newly loaded +// module's handle. +// +// Return Value: +// +// Returns the value returned by LdrLoadDll. +// +NTSTATUS VisualLeakDetector::_LdrLoadDll (LPWSTR searchpath, PULONG flags, unicodestring_t *modulename, + PHANDLE modulehandle) +{ + // Load the DLL + NTSTATUS status = LdrLoadDll(searchpath, flags, modulename, modulehandle); + return status; +} + +NTSTATUS VisualLeakDetector::_LdrLoadDllWin8 (DWORD_PTR reserved, PULONG flags, unicodestring_t *modulename, + PHANDLE modulehandle) +{ + // Load the DLL + NTSTATUS status = LdrLoadDllWin8(reserved, flags, modulename, modulehandle); + return status; +} + +NTSTATUS VisualLeakDetector::_LdrGetDllHandle(IN PWSTR DllPath OPTIONAL, IN PULONG DllCharacteristics OPTIONAL, IN PUNICODE_STRING DllName, OUT PVOID *DllHandle OPTIONAL) +{ + LoaderLock ll; + + NTSTATUS status = LdrGetDllHandle(DllPath, DllCharacteristics, DllName, DllHandle); + return status; +} +NTSTATUS VisualLeakDetector::_LdrGetProcedureAddress(IN PVOID BaseAddress, IN PANSI_STRING Name, IN ULONG Ordinal, OUT PVOID * ProcedureAddress) +{ + LoaderLock ll; + + NTSTATUS status = LdrGetProcedureAddress(BaseAddress, Name, Ordinal, ProcedureAddress); + return status; +} + +NTSTATUS VisualLeakDetector::_LdrLockLoaderLock(IN ULONG Flags, OUT PULONG Disposition OPTIONAL, OUT PULONG_PTR Cookie OPTIONAL) +{ + return LdrLockLoaderLock(Flags, Disposition, Cookie); +} + +NTSTATUS VisualLeakDetector::_LdrUnlockLoaderLock(IN ULONG Flags, IN ULONG_PTR Cookie OPTIONAL) +{ + return LdrUnlockLoaderLock(Flags, Cookie); +} + +NTSTATUS VisualLeakDetector::_LdrUnloadDll(IN PVOID BaseAddress) +{ + return LdrUnloadDll(BaseAddress); +} + +VOID VisualLeakDetector::RefreshModules() +{ + LoaderLock ll; + + if (m_options & VLD_OPT_VLDOFF) + return; + + ModuleSet* newmodules = new ModuleSet(); + newmodules->reserve(MODULE_SET_RESERVE); + { + // Duplicate code here in this method. Consider refactoring out to another method. + // Create a new set of all loaded modules, including any newly loaded + // modules. + DbgTrace(L"dbghelp32.dll %i: EnumerateLoadedModulesW64\n", GetCurrentThreadId()); + g_LoadedModules.EnumerateLoadedModulesW64(g_currentProcess, addLoadedModule, newmodules); + + // Attach to all modules included in the set. + attachToLoadedModules(newmodules); + } + + // Start using the new set of loaded modules. + CriticalSectionLocker<> cs(m_modulesLock); + ModuleSet* oldmodules = m_loadedModules; + m_loadedModules = newmodules; + + // Free resources used by the old module list. + delete oldmodules; +} + +// Find the information for the module that initiated this reallocation. +bool VisualLeakDetector::isModuleExcluded(UINT_PTR address) +{ + moduleinfo_t moduleinfo; + ModuleSet::Iterator moduleit; + moduleinfo.addrLow = address; + moduleinfo.addrHigh = address + 1024; + moduleinfo.flags = 0; + + CriticalSectionLocker<> cs(g_vld.m_modulesLock); + moduleit = g_vld.m_loadedModules->find(moduleinfo); + if (moduleit != g_vld.m_loadedModules->end()) + return (*moduleit).flags & VLD_MODULE_EXCLUDED ? true : false; + return false; +} + +SIZE_T VisualLeakDetector::GetLeaksCount() +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return 0; + } + + SIZE_T leaksCount = 0; + // Generate a memory leak report for each heap in the process. + CriticalSectionLocker<> cs(g_heapMapLock); + for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { + HANDLE heap = (*heapit).first; + UNREFERENCED_PARAMETER(heap); + heapinfo_t* heapinfo = (*heapit).second; + leaksCount += getLeaksCount(heapinfo); + } + return leaksCount; +} + +SIZE_T VisualLeakDetector::GetThreadLeaksCount(DWORD threadId) +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return 0; + } + + SIZE_T leaksCount = 0; + // Generate a memory leak report for each heap in the process. + CriticalSectionLocker<> cs(g_heapMapLock); + for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { + HANDLE heap = (*heapit).first; + UNREFERENCED_PARAMETER(heap); + heapinfo_t* heapinfo = (*heapit).second; + leaksCount += getLeaksCount(heapinfo, threadId); + } + return leaksCount; +} + +SIZE_T VisualLeakDetector::ReportLeaks( ) +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return 0; + } + + // Generate a memory leak report for each heap in the process. + SIZE_T leaksCount = 0; + CriticalSectionLocker<> cs(g_heapMapLock); + bool firstLeak = true; + Set aggregatedLeaks; + for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { + HANDLE heap = (*heapit).first; + UNREFERENCED_PARAMETER(heap); + heapinfo_t* heapinfo = (*heapit).second; + leaksCount += reportLeaks(heapinfo, firstLeak, aggregatedLeaks); + } + return leaksCount; +} + +SIZE_T VisualLeakDetector::ReportThreadLeaks( DWORD threadId ) +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return 0; + } + + // Generate a memory leak report for each heap in the process. + SIZE_T leaksCount = 0; + CriticalSectionLocker<> cs(g_heapMapLock); + bool firstLeak = true; + Set aggregatedLeaks; + for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { + HANDLE heap = (*heapit).first; + UNREFERENCED_PARAMETER(heap); + heapinfo_t* heapinfo = (*heapit).second; + leaksCount += reportLeaks(heapinfo, firstLeak, aggregatedLeaks, threadId); + } + return leaksCount; +} + +VOID VisualLeakDetector::MarkAllLeaksAsReported( ) +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return; + } + + // Generate a memory leak report for each heap in the process. + CriticalSectionLocker<> cs(g_heapMapLock); + for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { + HANDLE heap = (*heapit).first; + UNREFERENCED_PARAMETER(heap); + heapinfo_t* heapinfo = (*heapit).second; + markAllLeaksAsReported(heapinfo); + } +} + +VOID VisualLeakDetector::MarkThreadLeaksAsReported( DWORD threadId ) +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return; + } + + // Generate a memory leak report for each heap in the process. + CriticalSectionLocker<> cs(g_heapMapLock); + for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { + HANDLE heap = (*heapit).first; + UNREFERENCED_PARAMETER(heap); + heapinfo_t* heapinfo = (*heapit).second; + markAllLeaksAsReported(heapinfo, threadId); + } +} + +void VisualLeakDetector::ChangeModuleState(HMODULE module, bool on) +{ + ModuleSet::Iterator moduleit; + + CriticalSectionLocker<> cs(m_modulesLock); + moduleit = m_loadedModules->begin(); + while( moduleit != m_loadedModules->end() ) + { + if ( (*moduleit).addrLow == (UINT_PTR)module) + { + moduleinfo_t *mod = (moduleinfo_t *)&(*moduleit); + if ( on ) + mod->flags &= ~VLD_MODULE_EXCLUDED; + else + mod->flags |= VLD_MODULE_EXCLUDED; + + break; + } + ++moduleit; + } +} + +void VisualLeakDetector::EnableModule(HMODULE module) +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return; + } + + ChangeModuleState(module,true); +} + +void VisualLeakDetector::DisableModule(HMODULE module) +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return; + } + + ChangeModuleState(module,false); +} + +void VisualLeakDetector::DisableLeakDetection () +{ + tls_t *tls; + + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return; + } + + // Disable memory leak detection for the current thread. There are two flags + // because if neither flag is set, it means that we are in the default or + // "starting" state, which could be either enabled or disabled depending on + // the configuration. + tls = getTls(); + tls->oldFlags = tls->flags; + tls->flags &= ~VLD_TLS_ENABLED; + tls->flags |= VLD_TLS_DISABLED; +} + +void VisualLeakDetector::EnableLeakDetection () +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return; + } + + tls_t *tls; + + // Enable memory leak detection for the current thread. + tls = getTls(); + tls->oldFlags = tls->flags; + tls->flags &= ~VLD_TLS_DISABLED; + tls->flags |= VLD_TLS_ENABLED; + m_status &= ~VLD_STATUS_NEVER_ENABLED; +} + +void VisualLeakDetector::RestoreLeakDetectionState () +{ + tls_t *tls; + + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return; + } + + // Restore state memory leak detection for the current thread. + tls = getTls(); + tls->flags &= ~(VLD_TLS_DISABLED | VLD_TLS_ENABLED); + tls->flags |= tls->oldFlags & (VLD_TLS_DISABLED | VLD_TLS_ENABLED); +} + +void VisualLeakDetector::GlobalDisableLeakDetection () +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return; + } + + CriticalSectionLocker<> cs(m_optionsLock); + m_options |= VLD_OPT_START_DISABLED; + + // Disable memory leak detection for all threads. + CriticalSectionLocker<> cstls(m_tlsLock); + TlsMap::Iterator tlsit; + for (tlsit = m_tlsMap->begin(); tlsit != m_tlsMap->end(); ++tlsit) { + (*tlsit).second->oldFlags = (*tlsit).second->flags; + (*tlsit).second->flags &= ~VLD_TLS_ENABLED; + (*tlsit).second->flags |= VLD_TLS_DISABLED; + } +} + +void VisualLeakDetector::GlobalEnableLeakDetection () +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return; + } + + CriticalSectionLocker<> cs(m_optionsLock); + m_options &= ~VLD_OPT_START_DISABLED; + m_status &= ~VLD_STATUS_NEVER_ENABLED; + + // Enable memory leak detection for all threads. + CriticalSectionLocker<> cstls(m_tlsLock); + TlsMap::Iterator tlsit; + for (tlsit = m_tlsMap->begin(); tlsit != m_tlsMap->end(); ++tlsit) { + (*tlsit).second->oldFlags = (*tlsit).second->flags; + (*tlsit).second->flags &= ~VLD_TLS_DISABLED; + (*tlsit).second->flags |= VLD_TLS_ENABLED; + } +} + +CONST UINT32 OptionsMask = VLD_OPT_AGGREGATE_DUPLICATES | VLD_OPT_MODULE_LIST_INCLUDE | + VLD_OPT_SAFE_STACK_WALK | VLD_OPT_SLOW_DEBUGGER_DUMP | VLD_OPT_START_DISABLED | + VLD_OPT_TRACE_INTERNAL_FRAMES | VLD_OPT_SKIP_HEAPFREE_LEAKS | VLD_OPT_VALIDATE_HEAPFREE | + VLD_OPT_SKIP_CRTSTARTUP_LEAKS; + +UINT32 VisualLeakDetector::GetOptions() +{ + CriticalSectionLocker<> cs(m_optionsLock); + return m_options & OptionsMask; +} + +void VisualLeakDetector::SetOptions(UINT32 option_mask, SIZE_T maxDataDump, UINT32 maxTraceFrames) +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return; + } + + CriticalSectionLocker<> cs(m_optionsLock); + m_options &= ~OptionsMask; // clear used bits + m_options |= option_mask & OptionsMask; + + m_maxDataDump = maxDataDump; + m_maxTraceFrames = maxTraceFrames; + if (m_maxTraceFrames < 1) { + m_maxTraceFrames = VLD_DEFAULT_MAX_TRACE_FRAMES; + } + + m_options |= option_mask & VLD_OPT_START_DISABLED; + if (m_options & VLD_OPT_START_DISABLED) + GlobalDisableLeakDetection(); +} + +void VisualLeakDetector::SetModulesList(CONST WCHAR *modules, BOOL includeModules) +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return; + } + + CriticalSectionLocker<> cs(m_optionsLock); + wcsncpy_s(m_forcedModuleList, MAXMODULELISTLENGTH, modules, _TRUNCATE); + _wcslwr_s(m_forcedModuleList, MAXMODULELISTLENGTH); + if (includeModules) + m_options |= VLD_OPT_MODULE_LIST_INCLUDE; + else + m_options &= ~VLD_OPT_MODULE_LIST_INCLUDE; +} + +bool VisualLeakDetector::GetModulesList(WCHAR *modules, UINT size) +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + modules[0] = '\0'; + return true; + } + + CriticalSectionLocker<> cs(m_optionsLock); + wcsncpy_s(modules, size, m_forcedModuleList, _TRUNCATE); + return (m_options & VLD_OPT_MODULE_LIST_INCLUDE) > 0; +} + +void VisualLeakDetector::GetReportFilename(WCHAR *filename) +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + m_reportFilePath[0] = '\0'; + return; + } + + CriticalSectionLocker<> cs(m_optionsLock); + wcsncpy_s(filename, MAX_PATH, m_reportFilePath, _TRUNCATE); +} + +void VisualLeakDetector::SetReportOptions(UINT32 option_mask, CONST WCHAR *filename) +{ + if (m_options & VLD_OPT_VLDOFF) { + // VLD has been turned off. + return; + } + + CriticalSectionLocker<> cs(m_optionsLock); + m_options &= ~(VLD_OPT_REPORT_TO_DEBUGGER | VLD_OPT_REPORT_TO_FILE | + VLD_OPT_REPORT_TO_STDOUT | VLD_OPT_UNICODE_REPORT); // clear used bits + + m_options |= option_mask & VLD_OPT_REPORT_TO_DEBUGGER; + if ( (option_mask & VLD_OPT_REPORT_TO_FILE) && ( filename != NULL )) + { + wcsncpy_s(m_reportFilePath, MAX_PATH, filename, _TRUNCATE); + m_options |= option_mask & VLD_OPT_REPORT_TO_FILE; + } + m_options |= option_mask & VLD_OPT_REPORT_TO_STDOUT; + m_options |= option_mask & VLD_OPT_UNICODE_REPORT; + + if ((m_options & VLD_OPT_UNICODE_REPORT) && !(m_options & VLD_OPT_REPORT_TO_FILE)) { + // If Unicode report encoding is enabled, then the report needs to be + // sent to a file because the debugger will not display Unicode + // characters, it will display question marks in their place instead. + m_options |= VLD_OPT_REPORT_TO_FILE; + m_status |= VLD_STATUS_FORCE_REPORT_TO_FILE; + } + + if (m_options & VLD_OPT_REPORT_TO_FILE) { + setupReporting(); + } + else if ( m_reportFile ) { //Close the previous report file if needed. + fclose(m_reportFile); + m_reportFile = NULL; + } +} + +int VisualLeakDetector::SetReportHook(int mode, VLD_REPORT_HOOK pfnNewHook) +{ + if (m_options & VLD_OPT_VLDOFF || pfnNewHook == NULL) { + // VLD has been turned off. + return -1; + } + CriticalSectionLocker<> cs(m_optionsLock); + if (mode == VLD_RPTHOOK_INSTALL) + { + ReportHookSet::Iterator it = g_pReportHooks->insert(pfnNewHook); + return (it != g_pReportHooks->end()) ? 0 : -1; + } + else if (mode == VLD_RPTHOOK_REMOVE) + { + g_pReportHooks->erase(pfnNewHook); + return 0; + } + return -1; +} + +void VisualLeakDetector::setupReporting() +{ + WCHAR bom = BOM; // Unicode byte-order mark. + + //Close the previous report file if needed. + if (m_reportFile) { + fclose(m_reportFile); + m_reportFile = NULL; + } + + // Reporting to file enabled. + if (m_options & VLD_OPT_UNICODE_REPORT) { + // Unicode data encoding has been enabled. Write the byte-order + // mark before anything else gets written to the file. Open the + // file for binary writing. + if (_wfopen_s(&m_reportFile, m_reportFilePath, L"wb") == EINVAL) { + // Couldn't open the file. + m_reportFile = NULL; + } + else if (m_reportFile) { + fwrite(&bom, sizeof(WCHAR), 1, m_reportFile); + SetReportEncoding(unicode); + } + } + else { + // Open the file in text mode for ASCII output. + if (_wfopen_s(&m_reportFile, m_reportFilePath, L"w") == EINVAL) { + // Couldn't open the file. + m_reportFile = NULL; + } + else if (m_reportFile) { + SetReportEncoding(ascii); + } + } + if (m_reportFile == NULL) { + Report(L"WARNING: Visual Leak Detector: Couldn't open report file for writing: %s\n" + L" The report will be sent to the debugger instead.\n", m_reportFilePath); + } + else { + // Set the "report" function to write to the file. + SetReportFile(m_reportFile, m_options & VLD_OPT_REPORT_TO_DEBUGGER, m_options & VLD_OPT_REPORT_TO_STDOUT); + } +} + +blockinfo_t* VisualLeakDetector::getAllocationBlockInfo(void* alloc) +{ + // should be called under g_heapMapLock + for (HeapMap::Iterator heapiter = m_heapMap->begin(); heapiter != m_heapMap->end(); ++heapiter) + { + HANDLE heap = (*heapiter).first; + UNREFERENCED_PARAMETER(heap); + heapinfo_t* heapinfo = (*heapiter).second; + BlockMap& blockmap = heapinfo->blockMap; + + for (BlockMap::Iterator blockit = blockmap.begin(); blockit != blockmap.end(); ++blockit) { + // Found a block which is still in the BlockMap. We've identified a + // potential memory leak. + LPCVOID block = (*blockit).first; + blockinfo_t* info = (*blockit).second; + if (block == alloc) + return info; + + if (isDebugCrtAlloc(block, info)) { + // The CRT header is more or less transparent to the user, so + // the information about the contained block will probably be + // more useful to the user. Accordingly, that's the information + // we'll include in the report. + if (CRTDBGBLOCKDATA(block) == alloc) + return info; + } + } + } + return NULL; +} + +const wchar_t* VisualLeakDetector::GetAllocationResolveResults(void* alloc, BOOL showInternalFrames) +{ + LoaderLock ll; + + if (m_options & VLD_OPT_VLDOFF) + return NULL; + + CriticalSectionLocker<> cs(g_heapMapLock); + blockinfo_t* info = getAllocationBlockInfo(alloc); + if (info != NULL) + { + int unresolvedFunctionsCount = info->callStack->resolve(showInternalFrames); + _ASSERT(unresolvedFunctionsCount == 0); + return info->callStack->getResolvedCallstack(showInternalFrames); + } + return NULL; +} + +int VisualLeakDetector::resolveStacks(heapinfo_t* heapinfo) +{ + int unresolvedFunctionsCount = 0; + BlockMap& blockmap = heapinfo->blockMap; + + for (BlockMap::Iterator blockit = blockmap.begin(); blockit != blockmap.end(); ++blockit) { + // Found a block which is still in the BlockMap. We've identified a + // potential memory leak. + const void* block = (*blockit).first; + blockinfo_t* info = (*blockit).second; + assert(info); + if (info == NULL) + { + continue; + } + + if (info->reported) { + continue; + } + + // The actual memory address + const void* address = block; + assert(address != NULL); + + if (isDebugCrtAlloc(block, info)) { + // This block is allocated to a CRT heap, so the block has a CRT + // memory block header prepended to it. + crtdbgblockheader_t* crtheader = (crtdbgblockheader_t*)block; + if (!crtheader) + continue; + + // Leaks identified as CRT_USE_IGNORE should not be ignored here otherwise + // DynamicLoader/Thread test will randomly fail with less leaks being reported. + if (CRT_USE_TYPE(crtheader->use) == CRT_USE_FREE || + CRT_USE_TYPE(crtheader->use) == CRT_USE_INTERNAL) + { + // This block is marked as being used internally by the CRT. + // The CRT will free the block after VLD is destroyed. + continue; + } + } + + // Dump the call stack. + if (info->callStack) + { + unresolvedFunctionsCount += info->callStack->resolve(m_options & VLD_OPT_TRACE_INTERNAL_FRAMES); + if ((m_options & VLD_OPT_SKIP_CRTSTARTUP_LEAKS) && info->callStack->isCrtStartupAlloc()) { + info->reported = true; + continue; + } + } + } + return unresolvedFunctionsCount; +} + +int VisualLeakDetector::ResolveCallstacks() +{ + LoaderLock ll; + + if (m_options & VLD_OPT_VLDOFF) + return 0; + + int unresolvedFunctionsCount = 0; + // Generate the Callstacks early + CriticalSectionLocker<> cs(g_heapMapLock); + for (HeapMap::Iterator heapiter = m_heapMap->begin(); heapiter != m_heapMap->end(); ++heapiter) + { + HANDLE heap = (*heapiter).first; + UNREFERENCED_PARAMETER(heap); + heapinfo_t* heapinfo = (*heapiter).second; + unresolvedFunctionsCount += resolveStacks(heapinfo); + } + return unresolvedFunctionsCount; +} + +CaptureContext::CaptureContext(void* func, context_t& context, BOOL debug, BOOL ucrt) : m_context(context) { + context.func = reinterpret_cast(func); + m_tls = g_vld.getTls(); + + if (debug) { + m_tls->flags |= VLD_TLS_DEBUGCRTALLOC; + } + + if (ucrt) { + m_tls->flags |= VLD_TLS_UCRT; + } + + m_bFirst = (GET_RETURN_ADDRESS(m_tls->context) == NULL); + if (m_bFirst) { + // This is the first call to enter VLD for the current allocation. + // Record the current frame pointer. + m_tls->context = m_context; + } +} + +CaptureContext::~CaptureContext() { + if (!m_bFirst) + return; + + if ((m_tls->blockWithoutGuard) && (!IsExcludedModule())) { + blockinfo_t* pblockInfo = NULL; + if (m_tls->newBlockWithoutGuard == NULL) { + g_vld.mapBlock(m_tls->heap, + m_tls->blockWithoutGuard, + m_tls->size, + (m_tls->flags & VLD_TLS_DEBUGCRTALLOC) != 0, + (m_tls->flags & VLD_TLS_UCRT) != 0, + m_tls->threadId, + pblockInfo); + } + else { + g_vld.remapBlock(m_tls->heap, + m_tls->blockWithoutGuard, + m_tls->newBlockWithoutGuard, + m_tls->size, + (m_tls->flags & VLD_TLS_DEBUGCRTALLOC) != 0, + (m_tls->flags & VLD_TLS_UCRT) != 0, + m_tls->threadId, + pblockInfo, m_tls->context); + } + + CallStack* callstack = CallStack::Create(); + callstack->getStackTrace(g_vld.m_maxTraceFrames, m_tls->context); + pblockInfo->callStack.reset(callstack); + } + + // Reset thread local flags and variables for the next allocation. + Reset(); +} + +void CaptureContext::Set(HANDLE heap, LPVOID mem, LPVOID newmem, SIZE_T size) { + m_tls->heap = heap; + m_tls->blockWithoutGuard = mem; + m_tls->newBlockWithoutGuard = newmem; + m_tls->size = size; + + if ((m_tls->blockWithoutGuard) && (g_vld.m_options & VLD_OPT_TRACE_INTERNAL_FRAMES)) { + // If VLD_OPT_TRACE_INTERNAL_FRAMES is specified then we capture the frame pointer upto the function that actually + // performs the allocation to the heap being: HeapAlloc, HeapReAlloc, RtlAllocateHeap, RtlReAllocateHeap. + m_tls->context = m_context; + } +} + +void CaptureContext::Reset() { + m_tls->context.func = NULL; + m_tls->context.fp = NULL; +#if defined(_M_IX86) + m_tls->context.Ebp = m_tls->context.Esp = m_tls->context.Eip = NULL; +#elif defined(_M_X64) + m_tls->context.Rbp = m_tls->context.Rsp = m_tls->context.Rip = NULL; +#endif + m_tls->flags &= ~(VLD_TLS_DEBUGCRTALLOC | VLD_TLS_UCRT); + Set(NULL, NULL, NULL, NULL); +} + +BOOL CaptureContext::IsExcludedModule() { + HMODULE hModule = GetCallingModule(m_context.fp); + if (hModule == g_vld.m_dbghlpBase) + return TRUE; + + UINT tablesize = _countof(g_vld.m_patchTable); + for (UINT index = 0; index < tablesize; index++) { + if (((HMODULE)g_vld.m_patchTable[index].moduleBase == hModule)) { + return !g_vld.m_patchTable[index].reportLeaks; + } + } + + return g_vld.isModuleExcluded((UINT_PTR)hModule); +} \ No newline at end of file diff --git a/vld.dll.dependency.manifest b/src/vld.dll.dependency.x64.manifest similarity index 82% rename from vld.dll.dependency.manifest rename to src/vld.dll.dependency.x64.manifest index 0d609fe2..bc9fe1d2 100644 --- a/vld.dll.dependency.manifest +++ b/src/vld.dll.dependency.x64.manifest @@ -1,8 +1,8 @@ - - - - - - - - + + + + + + + + diff --git a/src/vld.dll.dependency.x86.manifest b/src/vld.dll.dependency.x86.manifest new file mode 100644 index 00000000..cad71ffa --- /dev/null +++ b/src/vld.dll.dependency.x86.manifest @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/src/vld.h b/src/vld.h new file mode 100644 index 00000000..b591ff3e --- /dev/null +++ b/src/vld.h @@ -0,0 +1,350 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - Import Library Header +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "vld_def.h" + +typedef int VLD_BOOL; +typedef unsigned int VLD_UINT; +typedef size_t VLD_SIZET; +typedef void* VLD_HMODULE; + +#if defined _DEBUG || defined VLD_FORCE_ENABLE + +#ifdef __AFXWIN_H__ +#error[VLD COMPILE ERROR] '#include ' should appear before '#include ' in file stdafx.h +#endif + +#pragma comment(lib, "vld.lib") + +// Force a symbolic reference to the global VisualLeakDetector class object from +// the DLL. This ensures that the DLL is loaded and linked with the program, +// even if no code otherwise imports any of the DLL's exports. +#pragma comment(linker, "/include:__imp_?g_vld@@3VVisualLeakDetector@@A") + +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector APIs +// + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +// VLDDisable - Disables Visual Leak Detector's memory leak detection at +// runtime. If memory leak detection is already disabled, then calling this +// function has no effect. +// +// Note: In multithreaded programs, this function operates on a per-thread +// basis. In other words, if you call this function from one thread, then +// memory leak detection is only disabled for that thread. If memory leak +// detection is enabled for other threads, then it will remain enabled for +// those other threads. It was designed to work this way to insulate you, +// the programmer, from having to ensure thread synchronization when calling +// VLDEnable() and VLDDisable(). Without this, calling these two functions +// unsynchronized could result in unpredictable and unintended behavior. +// But this also means that if you want to disable memory leak detection +// process-wide, then you need to call this function from every thread in +// the process. +// +// Return Value: +// +// None. +// +__declspec(dllimport) void VLDDisable (); + +// VLDEnable - Enables Visual Leak Detector's memory leak detection at runtime. +// If memory leak detection is already enabled, which it is by default, then +// calling this function has no effect. +// +// Note: In multithreaded programs, this function operates on a per-thread +// basis. In other words, if you call this function from one thread, then +// memory leak detection is only enabled for that thread. If memory leak +// detection is disabled for other threads, then it will remain disabled for +// those other threads. It was designed to work this way to insulate you, +// the programmer, from having to ensure thread synchronization when calling +// VLDEnable() and VLDDisable(). Without this, calling these two functions +// unsynchronized could result in unpredictable and unintended behavior. +// But this also means that if you want to enable memory leak detection +// process-wide, then you need to call this function from every thread in +// the process. +// +// Return Value: +// +// None. +// +__declspec(dllimport) void VLDEnable (); + +// VLDRestore - Restore Visual Leak Detector's previous state. +// +// Return Value: +// +// None. +// +__declspec(dllimport) void VLDRestore (); + +// VLDGlobalDisable - Disables Visual Leak Detector's memory leak detection at +// runtime in all threads. If memory leak detection is already disabled, +// then calling this function has no effect. +// +// Return Value: +// +// None. +// +__declspec(dllimport) void VLDGlobalDisable (); + +// VLDGlobalEnable - Enables Visual Leak Detector's memory leak detection +// at runtime in all threads. If memory leak detection is already enabled, +// which it is by default, then calling this function has no effect. +// +// Return Value: +// +// None. +// +__declspec(dllimport) void VLDGlobalEnable (); + +// VLDReportLeaks - Report leaks up to the execution point. +// +// Return Value: +// +// None. +// +__declspec(dllimport) VLD_UINT VLDReportLeaks (); + +// VLDReportThreadLeaks - Report thread leaks up to the execution point. +// +// threadId: thread Id. +// +// Return Value: +// +// None. +// +__declspec(dllimport) VLD_UINT VLDReportThreadLeaks (VLD_UINT threadId); + +// VLDGetLeaksCount - Return memory leaks count to the execution point. +// +// Return Value: +// +// None. +// +__declspec(dllimport) VLD_UINT VLDGetLeaksCount (); + +// VLDGetThreadLeaksCount - Return thread memory leaks count to the execution point. +// +// threadId: thread Id. +// +// Return Value: +// +// None. +// +__declspec(dllimport) VLD_UINT VLDGetThreadLeaksCount (VLD_UINT threadId); + +// VLDMarkAllLeaksAsReported - Mark all leaks as reported. +// +// Return Value: +// +// None. +// +__declspec(dllimport) void VLDMarkAllLeaksAsReported (); + +// VLDMarkThreadLeaksAsReported - Mark thread leaks as reported. +// +// threadId: thread Id. +// +// Return Value: +// +// None. +// +__declspec(dllimport) void VLDMarkThreadLeaksAsReported (VLD_UINT threadId); + + +// VLDRefreshModules - Look for recently loaded DLLs and patch them if necessary. +// +// Return Value: +// +// None. +// +__declspec(dllimport) void VLDRefreshModules(); + + +// VLDEnableModule - Enable Memory leak checking on the specified module. +// +// module: module handle. +// +// Return Value: +// +// None. +// + +__declspec(dllimport) void VLDEnableModule(VLD_HMODULE module); + + +// VLDDisableModule - Disable Memory leak checking on the specified module. +// +// module: module handle. +// +// Return Value: +// +// None. +// +__declspec(dllimport) void VLDDisableModule(VLD_HMODULE module); + +// VLDGetOptions - Return all current options. +// +// Return Value: +// +// Mask of current options. +// +__declspec(dllimport) VLD_UINT VLDGetOptions(); + +// VLDGetReportFilename - Return current report filename. +// +// filename: current report filename (max characters - MAX_PATH). +// +// Return Value: +// +// None. +// +__declspec(dllimport) void VLDGetReportFilename(wchar_t *filename); + +// VLDSetOptions - Update the report options via function call rather than INI file. +// +// option_mask: Only the following flags are checked +// VLD_OPT_AGGREGATE_DUPLICATES +// VLD_OPT_MODULE_LIST_INCLUDE +// VLD_OPT_SAFE_STACK_WALK +// VLD_OPT_SLOW_DEBUGGER_DUMP +// VLD_OPT_TRACE_INTERNAL_FRAMES +// VLD_OPT_START_DISABLED +// VLD_OPT_SKIP_HEAPFREE_LEAKS +// VLD_OPT_VALIDATE_HEAPFREE +// +// maxDataDump: maximum number of user-data bytes to dump for each leaked block. +// +// maxTraceFrames: maximum number of frames per stack trace for each leaked block. +// +// Return Value: +// +// None. +// +__declspec(dllimport) void VLDSetOptions(VLD_UINT option_mask, VLD_SIZET maxDataDump, VLD_UINT maxTraceFrames); + +// VLDSetModulesList - Set list of modules included/excluded in leak detection +// depending on parameter "includeModules". +// +// modules: list of modules to be forcefully included/excluded in leak detection. +// +// includeModules: include or exclude that modules. +// +// Return Value: +// +// None. +// +__declspec(dllimport) void VLDSetModulesList(const wchar_t *modules, VLD_BOOL includeModules); + +// VLDGetModulesList - Return current list of included/excluded modules +// depending on flag VLD_OPT_TRACE_INTERNAL_FRAMES. +// +// modules: destination string for list of included/excluded modules (maximum length 512 characters). +// +// size: maximum string size. +// +// Return Value: +// +// VLD_BOOL: TRUE if include modules, otherwise FALSE. +// +__declspec(dllimport) VLD_BOOL VLDGetModulesList(wchar_t *modules, VLD_UINT size); + +// VLDSetReportOptions - Update the report options via function call rather than INI file. +// +// Only the following flags are checked +// VLD_OPT_REPORT_TO_DEBUGGER +// VLD_OPT_REPORT_TO_FILE +// VLD_OPT_REPORT_TO_STDOUT +// VLD_OPT_UNICODE_REPORT +// +// filename is optional and can be NULL. +// +// Return Value: +// +// None. +// +__declspec(dllimport) void VLDSetReportOptions(VLD_UINT option_mask, const wchar_t *filename); + +// VLDSetReportHook - Installs or uninstalls a client-defined reporting function by hooking it +// into the C run-time debug reporting process (debug version only). +// +// mode: The action to take: VLD_RPTHOOK_INSTALL or VLD_RPTHOOK_REMOVE. +// +// pfnNewHook: Report hook to install or remove. +// +// Return Value: +// +// int: 0 if success. +// +__declspec(dllimport) int VLDSetReportHook(int mode, VLD_REPORT_HOOK pfnNewHook); + +// VLDResolveCallstacks - Performs symbol resolution for all saved extent CallStack's that have +// been tracked by Visual Leak Detector. This function is necessary for applications that +// dynamically load and unload modules, and through which memory leaks might be included. +// If this is NOT called, stack traces may have stack frames with no symbol information. This +// happens because the symbol API's cannot look up symbols for a binary / module that has been unloaded +// from the process. +// +// Return Value: +// +// int: 0 if successfully resolved all callstacks. +// +__declspec(dllexport) int VLDResolveCallstacks(); + +#ifdef __cplusplus +} +#endif // __cplusplus + +#else // !_DEBUG + +#define VLDEnable() +#define VLDDisable() +#define VLDRestore() +#define VLDGlobalDisable() +#define VLDGlobalEnable() +#define VLDReportLeaks() (0) +#define VLDReportThreadLeaks() (0) +#define VLDGetLeaksCount() (0) +#define VLDGetThreadLeaksCount() (0) +#define VLDMarkAllLeaksAsReported() +#define VLDMarkThreadLeaksAsReported(a) +#define VLDRefreshModules() +#define VLDEnableModule(a) +#define VLDDisableModule(b) +#define VLDGetOptions() (0) +#define VLDGetReportFilename(a) +#define VLDSetOptions(a, b, c) +#define VLDSetReportHook(a, b) +#define VLDSetModulesList(a) +#define VLDGetModulesList(a, b) (FALSE) +#define VLDSetReportOptions(a, b) +#define VLDResolveCallstacks() (0) + +#endif // _DEBUG diff --git a/src/vld.natvis b/src/vld.natvis new file mode 100644 index 00000000..bca5474f --- /dev/null +++ b/src/vld.natvis @@ -0,0 +1,94 @@ + + + + + {first}, {second,na} + ({first}, {second,na}) + + first + second + + + + + {m_tree} + + m_tree + + + + + {{ reserve={m_reserve} }}} + + + + + + *cur + cur = cur->left + + + + + + + {key} + + key + + + + + {m_node} + + m_node + + + + + {{ size={m_size} }}} + + m_size + m_capacity + + + + + m_size + + i = 0 + + (void*)chunk->frames[i] + i++ + + chunk = chunk->next + + + + + + + + {buffer,[length/2]su} + buffer,[length/2]su + + length + maxlength + + length/2 + buffer + + + + + + + + this + next + *this,! + + + + + diff --git a/vld.rc b/src/vld.rc old mode 100755 new mode 100644 similarity index 80% rename from vld.rc rename to src/vld.rc index 187fbff6..f6cacc51 --- a/vld.rc +++ b/src/vld.rc @@ -1,101 +1,106 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,9,8,0 - PRODUCTVERSION 1,9,8,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x3L -#else - FILEFLAGS 0x2L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "FileDescription", "Visual Leak Detector DLL" - VALUE "FileVersion", "1, 9, 8, 0" - VALUE "InternalName", "vld" - VALUE "LegalCopyright", "Copyright (C) 2009" - VALUE "OriginalFilename", "vld.dll" - VALUE "ProductName", "Visual Leak Detector" - VALUE "ProductVersion", "1, 9, 8, 0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" +#include "version.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include \r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_NUMBER + PRODUCTVERSION VERSION_NUMBER + FILEFLAGSMASK 0x17L +#ifdef _DEBUG + FILEFLAGS 0x3L +#else + FILEFLAGS 0x2L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "FileDescription", "Visual Leak Detector DLL" + VALUE "FileVersion", VERSION_STRING + VALUE "InternalName", "vld" + VALUE "LegalCopyright", VERSION_COPYRIGHT +#ifndef WIN64 + VALUE "OriginalFilename", "vld_x86.dll" +#else + VALUE "OriginalFilename", "vld_x64.dll" +#endif + VALUE "ProductName", "Visual Leak Detector" + VALUE "ProductVersion", VERSION_STRING + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/src/vld.vcxproj b/src/vld.vcxproj new file mode 100644 index 00000000..37727b1b --- /dev/null +++ b/src/vld.vcxproj @@ -0,0 +1,217 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} + vld + Unicode + DynamicLibrary + true + x86 + x64 + 8.1 + vld + + + + + v140_xp + + + + + <_ProjectFileVersion>10.0.30128.1 + $(ProjectDir)bin\$(Platform)\$(Configuration)-v$(PlatformToolsetVersion)\ + $(ProjectDir)obj\$(Platform)\$(Configuration)-v$(PlatformToolsetVersion)\$(ProjectName)\ + NativeRecommendedRules.ruleset + $(ProjectName)_$(NumericPlatform) + false + + + false + + + false + + + false + NativeRecommendedRules.ruleset + + + false + NativeRecommendedRules.ruleset + + + + $(SolutionDir)\lib\;$(SolutionDir)\lib\dbghelp\include;$(SolutionDir)\setup;%(AdditionalIncludeDirectories) + Use + + + true + 0x03200000 + false + $(SolutionDir)\lib\dbghelp\lib\$(PlatformName);%(AdditionalLibraryDirectories) + + + copy "$(OutDir)$(TargetName).lib" "$(OutDir)vld.lib" /y + + + $(SolutionDir)\setup + + + + + Disabled + _DEBUG;_USRDLL;WIN32;_WIN32_WINNT=0x0502;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebug + Level4 + false + false + 4201;4229;4091;4302;4311;4312;4127 + + + psapi.lib;%(AdditionalDependencies) + Windows + + + vld.dll.dependency.x86.manifest + + + + + Disabled + _DEBUG;_USRDLL;WIN64;_WIN32_WINNT=0x0502;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebug + Level4 + false + 4201;4229;4091;4302;4311;4312;4127 + false + + + psapi.lib;%(AdditionalDependencies) + Windows + + + vld.dll.dependency.x64.manifest + + + _UNICODE;UNICODE;WIN64;%(PreprocessorDefinitions) + + + + + Full + Speed + true + NDEBUG;_USRDLL;WIN32;_WIN32_WINNT=0x0502;%(PreprocessorDefinitions) + true + MultiThreaded + false + Fast + false + 4201;4229;4091;4302;4311;4312;4127 + false + + + true + true + Windows + + + vld.dll.dependency.x86.manifest + + + + + Full + Speed + true + NDEBUG;_USRDLL;WIN64;_WIN32_WINNT=0x0502;%(PreprocessorDefinitions) + true + MultiThreaded + false + Fast + false + false + 4201;4229;4091;4302;4311;4312;4127 + false + + + true + true + true + Windows + + + vld.dll.dependency.x64.manifest + + + _UNICODE;UNICODE;WIN64;%(PreprocessorDefinitions) + + + + + + + + Create + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {4adfd279-56c6-4b1d-ba9e-b815e81c1b17} + + + + + + \ No newline at end of file diff --git a/src/vld.vcxproj.filters b/src/vld.vcxproj.filters new file mode 100644 index 00000000..dc0a38b3 --- /dev/null +++ b/src/vld.vcxproj.filters @@ -0,0 +1,107 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Resource Files + + + + + + \ No newline at end of file diff --git a/src/vld_def.h b/src/vld_def.h new file mode 100644 index 00000000..265de49c --- /dev/null +++ b/src/vld_def.h @@ -0,0 +1,49 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - Import Library Header +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef _WCHAR_T_DEFINED +# include +#endif + +#define VLD_OPT_AGGREGATE_DUPLICATES 0x0001 // If set, aggregate duplicate leaks in the leak report. +#define VLD_OPT_MODULE_LIST_INCLUDE 0x0002 // If set, modules in the module list are included, all others are excluded. +#define VLD_OPT_REPORT_TO_DEBUGGER 0x0004 // If set, the memory leak report is sent to the debugger. +#define VLD_OPT_REPORT_TO_FILE 0x0008 // If set, the memory leak report is sent to a file. +#define VLD_OPT_SAFE_STACK_WALK 0x0010 // If set, the stack is walked using the "safe" method (StackWalk64). +#define VLD_OPT_SELF_TEST 0x0020 // If set, perform a self-test to verify memory leak self-checking. +#define VLD_OPT_SLOW_DEBUGGER_DUMP 0x0040 // If set, inserts a slight delay between sending output to the debugger. +#define VLD_OPT_START_DISABLED 0x0080 // If set, memory leak detection will initially disabled. +#define VLD_OPT_TRACE_INTERNAL_FRAMES 0x0100 // If set, include useless frames (e.g. internal to VLD) in call stacks. +#define VLD_OPT_UNICODE_REPORT 0x0200 // If set, the leak report will be encoded UTF-16 instead of ASCII. +#define VLD_OPT_VLDOFF 0x0400 // If set, VLD will be completely deactivated. It will not attach to any modules. +#define VLD_OPT_REPORT_TO_STDOUT 0x0800 // If set, the memory leak report is sent to stdout. +#define VLD_OPT_SKIP_HEAPFREE_LEAKS 0x1000 // If set, VLD skip HeapFree memory leaks. +#define VLD_OPT_VALIDATE_HEAPFREE 0x2000 // If set, VLD verifies and reports heap consistency for HeapFree calls. +#define VLD_OPT_SKIP_CRTSTARTUP_LEAKS 0x4000 // If set, VLD skip crt srtartup memory leaks. + +#define VLD_RPTHOOK_INSTALL 0 +#define VLD_RPTHOOK_REMOVE 1 + +typedef int (__cdecl * VLD_REPORT_HOOK)(int reportType, wchar_t *message, int *returnValue); diff --git a/src/vld_hooks.cpp b/src/vld_hooks.cpp new file mode 100644 index 00000000..314e99c7 --- /dev/null +++ b/src/vld_hooks.cpp @@ -0,0 +1,611 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - VisualLeakDetector Class Implementation +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" + +#pragma comment(lib, "dbghelp.lib") + +#include + +#define VLDBUILD // Declares that we are building Visual Leak Detector. +#include "callstack.h" // Provides a class for handling call stacks. +#include "crtmfcpatch.h" // Provides CRT and MFC patch functions. +#include "map.h" // Provides a lightweight STL-like map template. +#include "ntapi.h" // Provides access to NT APIs. +#include "set.h" // Provides a lightweight STL-like set template. +#include "utility.h" // Provides various utility functions. +#include "vldheap.h" // Provides internal new and delete operators. +#include "vldint.h" // Provides access to the Visual Leak Detector internals. +#include "loaderlock.h" + +extern HANDLE g_currentProcess; +extern CriticalSection g_heapMapLock; +extern DbgHelp g_DbgHelp; + +//////////////////////////////////////////////////////////////////////////////// +// +// Debug CRT and MFC IAT Replacement Functions +// +// The addresses of these functions are not actually directly patched into the +// import address tables, but these functions do get indirectly called by the +// patch functions that are placed in the import address tables. +// +//////////////////////////////////////////////////////////////////////////////// + +// GetProcessHeap - Calls to GetProcessHeap are patched through to this function. This +// function is just a wrapper around the real GetProcessHeap. +// +// Return Value: +// +// Returns the value returned by GetProcessHeap. +// +HANDLE VisualLeakDetector::_GetProcessHeap() +{ + PRINT_HOOKED_FUNCTION(); + // Get the process heap. + HANDLE heap = m_GetProcessHeap(); + + CriticalSectionLocker<> cs(g_heapMapLock); + HeapMap::Iterator heapit = g_vld.m_heapMap->find(heap); + if (heapit == g_vld.m_heapMap->end()) + { + g_vld.mapHeap(heap); + heapit = g_vld.m_heapMap->find(heap); + } + + return heap; +} + +// _HeapCreate - Calls to HeapCreate are patched through to this function. This +// function is just a wrapper around the real HeapCreate that calls VLD's heap +// creation tracking function after the heap has been created. +// +// - options (IN): Heap options. +// +// - initsize (IN): Initial size of the heap. +// +// - maxsize (IN): Maximum size of the heap. +// +// Return Value: +// +// Returns the value returned by HeapCreate. +// +HANDLE VisualLeakDetector::_HeapCreate (DWORD options, SIZE_T initsize, SIZE_T maxsize) +{ + PRINT_HOOKED_FUNCTION(); + // Create the heap. + HANDLE heap = m_HeapCreate(options, initsize, maxsize); + + CriticalSectionLocker<> cs(g_heapMapLock); + + // Map the created heap handle to a new block map. + g_vld.mapHeap(heap); + + HeapMap::Iterator heapit = g_vld.m_heapMap->find(heap); + assert(heapit != g_vld.m_heapMap->end()); + + return heap; +} + +// _HeapDestroy - Calls to HeapDestroy are patched through to this function. +// This function is just a wrapper around the real HeapDestroy that calls +// VLD's heap destruction tracking function after the heap has been destroyed. +// +// - heap (IN): Handle to the heap to be destroyed. +// +// Return Value: +// +// Returns the valued returned by HeapDestroy. +// +BOOL VisualLeakDetector::_HeapDestroy (HANDLE heap) +{ + PRINT_HOOKED_FUNCTION(); + // After this heap is destroyed, the heap's address space will be unmapped + // from the process's address space. So, we'd better generate a leak report + // for this heap now, while we can still read from the memory blocks + // allocated to it. + if (!(g_vld.m_options & VLD_OPT_SKIP_HEAPFREE_LEAKS)) + g_vld.reportHeapLeaks(heap); + + g_vld.unmapHeap(heap); + + return HeapDestroy(heap); +} + +// _RtlAllocateHeap - Calls to RtlAllocateHeap are patched through to this +// function. This function invokes the real RtlAllocateHeap and then calls +// VLD's allocation tracking function. Pretty much all memory allocations +// will eventually result in a call to RtlAllocateHeap, so this is where we +// finally map the allocated block. +// +// - heap (IN): Handle to the heap from which to allocate memory. +// +// - flags (IN): Heap allocation control flags. +// +// - size (IN): Size, in bytes, of the block to allocate. +// +// Return Value: +// +// Returns the return value from RtlAllocateHeap. +// +LPVOID VisualLeakDetector::_RtlAllocateHeap (HANDLE heap, DWORD flags, SIZE_T size) +{ + PRINT_HOOKED_FUNCTION2(); + // Allocate the block. + LPVOID block = RtlAllocateHeap(heap, flags, size); + + if ((block == NULL) || !g_vld.enabled()) + return block; + + if (!g_DbgHelp.IsLockedByCurrentThread()) { // skip dbghelp.dll calls + CAPTURE_CONTEXT(); + CaptureContext cc(RtlAllocateHeap, context_); + cc.Set(heap, block, NULL, size); + } + + return block; +} + +// HeapAlloc (kernel32.dll) call RtlAllocateHeap (ntdll.dll) +LPVOID VisualLeakDetector::_HeapAlloc (HANDLE heap, DWORD flags, SIZE_T size) +{ + PRINT_HOOKED_FUNCTION2(); + // Allocate the block. + LPVOID block = HeapAlloc(heap, flags, size); + + if ((block == NULL) || !g_vld.enabled()) + return block; + + if (!g_DbgHelp.IsLockedByCurrentThread()) { // skip dbghelp.dll calls + CAPTURE_CONTEXT(); + CaptureContext cc(HeapAlloc, context_); + cc.Set(heap, block, NULL, size); + } + + return block; +} + +// _RtlFreeHeap - Calls to RtlFreeHeap are patched through to this function. +// This function calls VLD's free tracking function and then invokes the real +// RtlFreeHeap. Pretty much all memory frees will eventually result in a call +// to RtlFreeHeap, so this is where we finally unmap the freed block. +// +// - heap (IN): Handle to the heap to which the block being freed belongs. +// +// - flags (IN): Heap control flags. +// +// - mem (IN): Pointer to the memory block being freed. +// +// Return Value: +// +// Returns the value returned by RtlFreeHeap. +// +BYTE VisualLeakDetector::_RtlFreeHeap (HANDLE heap, DWORD flags, LPVOID mem) +{ + PRINT_HOOKED_FUNCTION2(); + BYTE status; + + if (!g_DbgHelp.IsLockedByCurrentThread()) // skip dbghelp.dll calls + { + // Record the current frame pointer. + CAPTURE_CONTEXT(); + context_.func = reinterpret_cast(RtlFreeHeap); + + // Unmap the block from the specified heap. + g_vld.unmapBlock(heap, mem, context_); + } + + status = RtlFreeHeap(heap, flags, mem); + + return status; +} + +// HeapFree (kernel32.dll) call RtlFreeHeap (ntdll.dll) +BOOL VisualLeakDetector::_HeapFree (HANDLE heap, DWORD flags, LPVOID mem) +{ + PRINT_HOOKED_FUNCTION2(); + BOOL status; + + if (!g_DbgHelp.IsLockedByCurrentThread()) // skip dbghelp.dll calls + { + // Record the current frame pointer. + CAPTURE_CONTEXT(); + context_.func = reinterpret_cast(m_HeapFree); + + // Unmap the block from the specified heap. + g_vld.unmapBlock(heap, mem, context_); + } + + status = m_HeapFree(heap, flags, mem); + + return status; +} + +// _RtlReAllocateHeap - Calls to RtlReAllocateHeap are patched through to this +// function. This function invokes the real RtlReAllocateHeap and then calls +// VLD's reallocation tracking function. All arguments passed to this function +// are passed on to the real RtlReAllocateHeap without modification. Pretty +// much all memory re-allocations will eventually result in a call to +// RtlReAllocateHeap, so this is where we finally remap the reallocated block. +// +// - heap (IN): Handle to the heap to reallocate memory from. +// +// - flags (IN): Heap control flags. +// +// - mem (IN): Pointer to the currently allocated block which is to be +// reallocated. +// +// - size (IN): Size, in bytes, of the block to reallocate. +// +// Return Value: +// +// Returns the value returned by RtlReAllocateHeap. +// +LPVOID VisualLeakDetector::_RtlReAllocateHeap (HANDLE heap, DWORD flags, LPVOID mem, SIZE_T size) +{ + PRINT_HOOKED_FUNCTION(); + + // Reallocate the block. + LPVOID newmem = RtlReAllocateHeap(heap, flags, mem, size); + if ((newmem == NULL) || !g_vld.enabled()) + return newmem; + + if (!g_DbgHelp.IsLockedByCurrentThread()) { // skip dbghelp.dll calls + CAPTURE_CONTEXT(); + CaptureContext cc(RtlReAllocateHeap, context_); + cc.Set(heap, mem, newmem, size); + } + + return newmem; +} + +// for kernel32.dll +LPVOID VisualLeakDetector::_HeapReAlloc (HANDLE heap, DWORD flags, LPVOID mem, SIZE_T size) +{ + PRINT_HOOKED_FUNCTION(); + + // Reallocate the block. + LPVOID newmem = HeapReAlloc(heap, flags, mem, size); + if ((newmem == NULL) || !g_vld.enabled()) + return newmem; + + if (!g_DbgHelp.IsLockedByCurrentThread()) { // skip dbghelp.dll calls + CAPTURE_CONTEXT(); + CaptureContext cc(HeapReAlloc, context_); + cc.Set(heap, mem, newmem, size); + } + + return newmem; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// COM IAT Replacement Functions +// +//////////////////////////////////////////////////////////////////////////////// + +// _CoGetMalloc - Calls to CoGetMalloc are patched through to this function. +// This function returns a pointer to Visual Leak Detector's implementation +// of the IMalloc interface, instead of returning a pointer to the system +// implementation. This allows VLD's implementation of the IMalloc interface +// (which is basically a thin wrapper around the system implementation) to be +// invoked in place of the system implementation. +// +// - context (IN): Reserved; value must be 1. +// +// - imalloc (IN): Address of a pointer to receive the address of VLD's +// implementation of the IMalloc interface. +// +// Return Value: +// +// Always returns S_OK. +// +HRESULT VisualLeakDetector::_CoGetMalloc (DWORD context, LPMALLOC *imalloc) +{ + PRINT_HOOKED_FUNCTION(); + static CoGetMalloc_t pCoGetMalloc = NULL; + + HRESULT hr = S_OK; + + HMODULE ole32; + + *imalloc = (LPMALLOC)&g_vld; + + if (pCoGetMalloc == NULL) { + // This is the first call to this function. Link to the real + // CoGetMalloc and get a pointer to the system implementation of the + // IMalloc interface. + ole32 = GetModuleHandleW(L"ole32.dll"); + pCoGetMalloc = (CoGetMalloc_t)g_vld._RGetProcAddress(ole32, "CoGetMalloc"); + hr = pCoGetMalloc(context, &g_vld.m_iMalloc); + + // Increment the library reference count to defer unloading the library, + // since a call to CoGetMalloc returns the global pointer to the VisualLeakDetector object. + HMODULE module = NULL; + GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)g_vld.m_vldBase, &module); + } + else + { + // wait for different thread initialization + int c = 0; + while(g_vld.m_iMalloc == NULL && c < 10) + { + Sleep(1); + c++; + } + if (g_vld.m_iMalloc == NULL) + hr = E_INVALIDARG; + } + + if (SUCCEEDED(hr)) { + g_vld.AddRef(); + } + return hr; +} + +// _CoTaskMemAlloc - Calls to CoTaskMemAlloc are patched through to this +// function. This function is just a wrapper around the real CoTaskMemAlloc +// that sets appropriate flags to be consulted when the memory is actually +// allocated by RtlAllocateHeap. +// +// - size (IN): Size of the memory block to allocate. +// +// Return Value: +// +// Returns the value returned from CoTaskMemAlloc. +// +LPVOID VisualLeakDetector::_CoTaskMemAlloc (SIZE_T size) +{ + PRINT_HOOKED_FUNCTION(); + static CoTaskMemAlloc_t pCoTaskMemAlloc = NULL; + + if (pCoTaskMemAlloc == NULL) { + // This is the first call to this function. Link to the real + // CoTaskMemAlloc. + HMODULE ole32 = GetModuleHandleW(L"ole32.dll"); + pCoTaskMemAlloc = (CoTaskMemAlloc_t)g_vld._RGetProcAddress(ole32, "CoTaskMemAlloc"); + } + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pCoTaskMemAlloc, context_); + + // Do the allocation. The block will be mapped by _RtlAllocateHeap. + return pCoTaskMemAlloc(size); +} + +// _CoTaskMemRealloc - Calls to CoTaskMemRealloc are patched through to this +// function. This function is just a wrapper around the real CoTaskMemRealloc +// that sets appropriate flags to be consulted when the memory is actually +// allocated by RtlAllocateHeap. +// +// - mem (IN): Pointer to the memory block to reallocate. +// +// - size (IN): Size, in bytes, of the block to reallocate. +// +// Return Value: +// +// Returns the value returned from CoTaskMemRealloc. +// +LPVOID VisualLeakDetector::_CoTaskMemRealloc (LPVOID mem, SIZE_T size) +{ + PRINT_HOOKED_FUNCTION(); + static CoTaskMemRealloc_t pCoTaskMemRealloc = NULL; + + if (pCoTaskMemRealloc == NULL) { + // This is the first call to this function. Link to the real + // CoTaskMemRealloc. + HMODULE ole32 = GetModuleHandleW(L"ole32.dll"); + pCoTaskMemRealloc = (CoTaskMemRealloc_t)g_vld._RGetProcAddress(ole32, "CoTaskMemRealloc"); + } + + CAPTURE_CONTEXT(); + CaptureContext cc((void*)pCoTaskMemRealloc, context_); + + // Do the allocation. The block will be mapped by _RtlReAllocateHeap. + return pCoTaskMemRealloc(mem, size); +} + +//////////////////////////////////////////////////////////////////////////////// +// +// Public COM IMalloc Implementation Functions +// +//////////////////////////////////////////////////////////////////////////////// + +// AddRef - Calls to IMalloc::AddRef end up here. This function is just a +// wrapper around the real IMalloc::AddRef implementation. +// +// Return Value: +// +// Returns the value returned by the system implementation of +// IMalloc::AddRef. +// +ULONG VisualLeakDetector::AddRef () +{ + PRINT_HOOKED_FUNCTION(); + assert(m_iMalloc != NULL); + if (m_iMalloc) { + // Increment the library reference count to defer unloading the library, + // since this function increments the reference count of the IMalloc interface. + HMODULE module = NULL; + GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)m_vldBase, &module); + return m_iMalloc->AddRef(); + } + return 0; +} + +// Alloc - Calls to IMalloc::Alloc end up here. This function is just a wrapper +// around the real IMalloc::Alloc implementation that sets appropriate flags +// to be consulted when the memory is actually allocated by RtlAllocateHeap. +// +// - size (IN): The size of the memory block to allocate. +// +// Return Value: +// +// Returns the value returned by the system's IMalloc::Alloc implementation. +// +LPVOID VisualLeakDetector::Alloc (_In_ SIZE_T size) +{ + PRINT_HOOKED_FUNCTION(); + UINT_PTR* cVtablePtr = (UINT_PTR*)((UINT_PTR*)m_iMalloc)[0]; + UINT_PTR iMallocAlloc = cVtablePtr[3]; + CAPTURE_CONTEXT(); + CaptureContext cc((void*)iMallocAlloc, context_); + + // Do the allocation. The block will be mapped by _RtlAllocateHeap. + assert(m_iMalloc != NULL); + return (m_iMalloc) ? m_iMalloc->Alloc(size) : NULL; +} + +// DidAlloc - Calls to IMalloc::DidAlloc will end up here. This function is just +// a wrapper around the system implementation of IMalloc::DidAlloc. +// +// - mem (IN): Pointer to a memory block to inquire about. +// +// Return Value: +// +// Returns the value returned by the system implementation of +// IMalloc::DidAlloc. +// +INT VisualLeakDetector::DidAlloc (_In_opt_ LPVOID mem) +{ + PRINT_HOOKED_FUNCTION(); + assert(m_iMalloc != NULL); + return (m_iMalloc) ? m_iMalloc->DidAlloc(mem) : 0; +} + +// Free - Calls to IMalloc::Free will end up here. This function is just a +// wrapper around the real IMalloc::Free implementation. +// +// - mem (IN): Pointer to the memory block to be freed. +// +// Return Value: +// +// None. +// +VOID VisualLeakDetector::Free (_In_opt_ LPVOID mem) +{ + PRINT_HOOKED_FUNCTION(); + assert(m_iMalloc != NULL); + if (m_iMalloc) m_iMalloc->Free(mem); +} + +// GetSize - Calls to IMalloc::GetSize will end up here. This function is just a +// wrapper around the real IMalloc::GetSize implementation. +// +// - mem (IN): Pointer to the memory block to inquire about. +// +// Return Value: +// +// Returns the value returned by the system implementation of +// IMalloc::GetSize. +// +SIZE_T VisualLeakDetector::GetSize (_In_opt_ LPVOID mem) +{ + PRINT_HOOKED_FUNCTION(); + assert(m_iMalloc != NULL); + return (m_iMalloc) ? m_iMalloc->GetSize(mem) : 0; +} + +// HeapMinimize - Calls to IMalloc::HeapMinimize will end up here. This function +// is just a wrapper around the real IMalloc::HeapMinimize implementation. +// +// Return Value: +// +// None. +// +VOID VisualLeakDetector::HeapMinimize () +{ + PRINT_HOOKED_FUNCTION(); + assert(m_iMalloc != NULL); + if (m_iMalloc) m_iMalloc->HeapMinimize(); +} + +// QueryInterface - Calls to IMalloc::QueryInterface will end up here. This +// function is just a wrapper around the real IMalloc::QueryInterface +// implementation. +// +// - iid (IN): COM interface ID to query about. +// +// - object (IN): Address of a pointer to receive the requested interface +// pointer. +// +// Return Value: +// +// Returns the value returned by the system implementation of +// IMalloc::QueryInterface. +// +HRESULT VisualLeakDetector::QueryInterface (REFIID iid, LPVOID *object) +{ + PRINT_HOOKED_FUNCTION(); + assert(m_iMalloc != NULL); + return (m_iMalloc) ? m_iMalloc->QueryInterface(iid, object) : E_UNEXPECTED; +} + +// Realloc - Calls to IMalloc::Realloc will end up here. This function is just a +// wrapper around the real IMalloc::Realloc implementation that sets +// appropriate flags to be consulted when the memory is actually allocated by +// RtlAllocateHeap. +// +// - mem (IN): Pointer to the memory block to reallocate. +// +// - size (IN): Size, in bytes, of the memory block to reallocate. +// +// Return Value: +// +// Returns the value returned by the system implementation of +// IMalloc::Realloc. +// +LPVOID VisualLeakDetector::Realloc (_In_opt_ LPVOID mem, _In_ SIZE_T size) +{ + PRINT_HOOKED_FUNCTION(); + UINT_PTR* cVtablePtr = (UINT_PTR*)((UINT_PTR*)m_iMalloc)[0]; + UINT_PTR iMallocRealloc = cVtablePtr[4]; + CAPTURE_CONTEXT(); + CaptureContext cc((void*)iMallocRealloc, context_); + + // Do the allocation. The block will be mapped by _RtlReAllocateHeap. + assert(m_iMalloc != NULL); + return (m_iMalloc) ? m_iMalloc->Realloc(mem, size) : NULL; +} + +// Release - Calls to IMalloc::Release will end up here. This function is just +// a wrapper around the real IMalloc::Release implementation. +// +// Return Value: +// +// Returns the value returned by the system implementation of +// IMalloc::Release. +// +ULONG VisualLeakDetector::Release () +{ + PRINT_HOOKED_FUNCTION(); + assert(m_iMalloc != NULL); + ULONG nCount = 0; + if (m_iMalloc) { + nCount = m_iMalloc->Release(); + + // Decrement the library reference count. + FreeLibrary(m_vldBase); + } + return nCount; +} diff --git a/src/vldallocator.h b/src/vldallocator.h new file mode 100644 index 00000000..50434ae0 --- /dev/null +++ b/src/vldallocator.h @@ -0,0 +1,60 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - Internal C++ Heap Management Definitions +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once +#include +#include "vldheap.h" // Provides internal new and delete operators. + +#pragma push_macro("new") +#undef new +template +class vldallocator: public std::allocator +{ +public: + typedef size_t size_type; + typedef T* pointer; + typedef const T* const_pointer; + + template + struct rebind + { + typedef vldallocator<_Tp1> other; + }; + + pointer allocate(size_type n, const void * /*hint*/ = 0) + { + return (pointer)::operator new(sizeof(T)*n, __FILE__, __LINE__); + } + + void deallocate(pointer p, size_type /*n*/) + { + return ::operator delete(p); + } + + vldallocator() throw() : std::allocator() { } + vldallocator(const vldallocator &a) throw() : std::allocator(a) { } + template + vldallocator(const vldallocator &a) throw() : std::allocator(a) { } + ~vldallocator() throw() { } +}; +#pragma pop_macro("new") diff --git a/src/vldapi.cpp b/src/vldapi.cpp new file mode 100644 index 00000000..15396556 --- /dev/null +++ b/src/vldapi.cpp @@ -0,0 +1,156 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - Exported APIs +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" + +#define VLDBUILD // Declares that we are building Visual Leak Detector. +#include "vldint.h" // Provides access to the Visual Leak Detector internals. +#include "vldheap.h" // Provides internal new and delete operators. + +// Imported global variables. +extern VisualLeakDetector g_vld; + +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector APIs - see vldapi.h for each function's details. +// + +extern "C" { + +__declspec(dllexport) void VLDDisable () +{ + g_vld.DisableLeakDetection(); +} + +__declspec(dllexport) void VLDEnable () +{ + g_vld.EnableLeakDetection(); +} + +__declspec(dllexport) void VLDRestore () +{ + g_vld.RestoreLeakDetectionState(); +} + +__declspec(dllexport) void VLDGlobalDisable () +{ + g_vld.GlobalDisableLeakDetection(); +} + +__declspec(dllexport) void VLDGlobalEnable () +{ + g_vld.GlobalEnableLeakDetection(); +} + +__declspec(dllexport) UINT VLDReportLeaks () +{ + return (UINT)g_vld.ReportLeaks(); +} + +__declspec(dllexport) UINT VLDReportThreadLeaks (UINT threadId) +{ + return (UINT)g_vld.ReportThreadLeaks(threadId); +} + +__declspec(dllexport) UINT VLDGetLeaksCount () +{ + return (UINT)g_vld.GetLeaksCount(); +} + +__declspec(dllexport) UINT VLDGetThreadLeaksCount (UINT threadId) +{ + return (UINT)g_vld.GetThreadLeaksCount(threadId); +} + +__declspec(dllexport) void VLDMarkAllLeaksAsReported () +{ + g_vld.MarkAllLeaksAsReported(); +} + +__declspec(dllexport) void VLDMarkThreadLeaksAsReported (UINT threadId) +{ + g_vld.MarkThreadLeaksAsReported(threadId); +} + +__declspec(dllexport) void VLDRefreshModules() +{ + g_vld.RefreshModules(); +} + +__declspec(dllexport) void VLDEnableModule(HMODULE module) +{ + g_vld.EnableModule(module); +} + +__declspec(dllexport) void VLDDisableModule(HMODULE module) +{ + g_vld.DisableModule(module); +} + +__declspec(dllexport) UINT VLDGetOptions() +{ + return g_vld.GetOptions(); +} + +__declspec(dllexport) void VLDGetReportFilename(WCHAR *filename) +{ + g_vld.GetReportFilename(filename); +} + +__declspec(dllexport) void VLDSetOptions(UINT option_mask, SIZE_T maxDataDump, UINT maxTraceFrames) +{ + g_vld.SetOptions(option_mask, maxDataDump, maxTraceFrames); +} + +__declspec(dllexport) int VLDSetReportHook(int mode, VLD_REPORT_HOOK pfnNewHook) +{ + return g_vld.SetReportHook(mode, pfnNewHook); +} + +__declspec(dllexport) void VLDSetModulesList(CONST WCHAR *modules, BOOL includeModules) +{ + g_vld.SetModulesList(modules, includeModules); +} + +__declspec(dllexport) BOOL VLDGetModulesList(WCHAR *modules, UINT size) +{ + return g_vld.GetModulesList(modules, size); +} + +__declspec(dllexport) void VLDSetReportOptions(UINT option_mask, CONST WCHAR *filename) +{ + g_vld.SetReportOptions(option_mask,filename); +} + +__declspec(dllexport) int VLDResolveCallstacks() +{ + return g_vld.ResolveCallstacks(); +} + +/// Internal function for tests. Not safe to use because Vld own returned string +__declspec(dllexport) const wchar_t* VldInternalGetAllocationCallstack(void* alloc, BOOL showInternalFrames) +{ + return g_vld.GetAllocationResolveResults(alloc, showInternalFrames); +} + +} diff --git a/vldheap.cpp b/src/vldheap.cpp similarity index 84% rename from vldheap.cpp rename to src/vldheap.cpp index 50f807b7..249e91f1 100644 --- a/vldheap.cpp +++ b/src/vldheap.cpp @@ -1,212 +1,215 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - Internal C++ Heap Management -// Copyright (c) 2006 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#include -#define VLDBUILD // Declares that we are building Visual Leak Detector. -#include "ntapi.h" // Provides access to NT APIs. -#include "vldheap.h" // Provides access to VLD's internal heap data structures. -#undef new // Do not map "new" to VLD's new operator in this file - -// Global variables. -vldblockheader_t *vldblocklist = NULL; // List of internally allocated blocks on VLD's private heap. -HANDLE vldheap; // VLD's private heap. -CRITICAL_SECTION vldheaplock; // Serializes access to VLD's private heap. - -// Local helper functions. -static inline void vlddelete (void *block); -static inline void* vldnew (size_t size, const char *file, int line); - -// scalar delete operator - Delete operator used to free internally used memory -// back to VLD's private heap. -// -// - block (IN): Pointer to the scalar memory block to free. -// -// Return Value: -// -// None. -// -void operator delete (void *block) -{ - vlddelete(block); -} - -// vector delete operator - Delete operator used to free internally used memory -// back to VLD's private heap. -// -// - block (IN): Pointer to the vector memory block to free. -// -// Return Value: -// -// None. -// -void operator delete [] (void *block) -{ - vlddelete(block); -} - -// scalar delete operator - Delete operator used to free memory partially -// allocated by new in the event that the corresponding new operator throws -// an exception. -// -// Note: This version of the delete operator should never be called directly. -// The compiler automatically generates calls to this function as needed. -// -void operator delete (void *block, const char *, int) -{ - vlddelete(block); -} - -// vector delete operator - Delete operator used to free memory partially -// allocated by new in the event that the corresponding new operator throws -// an exception. -// -// Note: This version of the delete operator should never be called directly. -// The compiler automatically generates calls to this function as needed. -// -void operator delete [] (void *block, const char *, int) -{ - vlddelete(block); -} - -// scalar new operator - New operator used to allocate a scalar memory block -// from VLD's private heap. -// -// - size (IN): Size of the memory block to be allocated. -// -// - file (IN): The name of the file from which this function is being -// called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// If the allocation succeeds, a pointer to the allocated memory block is -// returned. If the allocation fails, NULL is returned. -// -void* operator new (size_t size, const char *file, int line) -{ - return vldnew(size, file, line); -} - -// vector new operator - New operator used to allocate a vector memory block -// from VLD's private heap. -// -// - size (IN): Size of the memory block to be allocated. -// -// - file (IN): The name of the file from which this function is being -// called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// If the allocation succeeds, a pointer to the allocated memory block is -// returned. If the allocation fails, NULL is returned. -// -void* operator new [] (size_t size, const char *file, int line) -{ - return vldnew(size, file, line); -} - -// vlddelete - Local helper function that actually frees memory back to VLD's -// private heap. -// -// - block (IN): Pointer to a memory block being freed. -// -// Return Value: -// -// None. -// -void vlddelete (void *block) -{ - BOOL freed; - vldblockheader_t *header = VLDBLOCKHEADER((LPVOID)block); - - // Unlink the block from the block list. - EnterCriticalSection(&vldheaplock); - if (header->prev) { - header->prev->next = header->next; - } - else { - vldblocklist = header->next; - } - - if (header->next) { - header->next->prev = header->prev; - } - LeaveCriticalSection(&vldheaplock); - - // Free the block. - freed = RtlFreeHeap(vldheap, 0x0, header); - assert(freed != FALSE); -} - -// vldnew - Local helper function that actually allocates memory from VLD's -// private heap. Prepends a header, which is used for bookeeping information -// that allows VLD to detect and report internal memory leaks, to the returned -// block, but the header is transparent to the caller because the returned -// pointer points to the useable section of memory requested by the caller, it -// does not point to the block header. -// -// - size (IN): Size of the memory block to be allocated. -// -// - file (IN): Name of the file that called the new operator. -// -// - line (IN): Line, in the above file, at which the new operator was called. -// -// Return Value: -// -// If the memory allocation succeeds, a pointer to the allocated memory -// block is returned. If the allocation fails, NULL is returned. -// -void* vldnew (size_t size, const char *file, int line) -{ - vldblockheader_t *header = (vldblockheader_t*)RtlAllocateHeap(vldheap, 0x0, size + sizeof(vldblockheader_t)); - static SIZE_T serialnumber = 0; - - if (header == NULL) { - // Out of memory. - return NULL; - } - - // Fill in the block's header information. - header->file = file; - header->line = line; - header->serialnumber = serialnumber++; - header->size = size; - - // Link the block into the block list. - EnterCriticalSection(&vldheaplock); - header->next = vldblocklist; - if (header->next != NULL) { - header->next->prev = header; - } - header->prev = NULL; - vldblocklist = header; - LeaveCriticalSection(&vldheaplock); - - // Return a pointer to the beginning of the data section of the block. - return (void*)VLDBLOCKDATA(header); -} +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - Internal C++ Heap Management +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" + +#define VLDBUILD // Declares that we are building Visual Leak Detector. +#include "ntapi.h" // Provides access to NT APIs. +#include "vldheap.h" // Provides access to VLD's internal heap data structures. +#include "criticalsection.h" +#undef new // Do not map "new" to VLD's new operator in this file + +// Global variables. +vldblockheader_t *g_vldBlockList = NULL; // List of internally allocated blocks on VLD's private heap. +HANDLE g_vldHeap; // VLD's private heap. +CriticalSection g_vldHeapLock; // Serializes access to VLD's private heap. + +// Local helper functions. +static inline void* vldnew (size_t size, const char *file, int line); +static inline void vlddelete (void *block); + +// scalar new operator - New operator used to allocate a scalar memory block +// from VLD's private heap. +// +// - size (IN): Size of the memory block to be allocated. +// +// - file (IN): The name of the file from which this function is being +// called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// If the allocation succeeds, a pointer to the allocated memory block is +// returned. If the allocation fails, NULL is returned. +// +void* operator new (size_t size, const char *file, int line) +{ + return vldnew(size, file, line); +} + +// vector new operator - New operator used to allocate a vector memory block +// from VLD's private heap. +// +// - size (IN): Size of the memory block to be allocated. +// +// - file (IN): The name of the file from which this function is being +// called. +// +// - line (IN): The line number, in the above file, at which this function is +// being called. +// +// Return Value: +// +// If the allocation succeeds, a pointer to the allocated memory block is +// returned. If the allocation fails, NULL is returned. +// +void* operator new [] (size_t size, const char *file, int line) +{ + return vldnew(size, file, line); +} + +// scalar delete operator - Delete operator used to free internally used memory +// back to VLD's private heap. +// +// - block (IN): Pointer to the scalar memory block to free. +// +// Return Value: +// +// None. +// +void operator delete (void *block) +{ + vlddelete(block); +} + +// vector delete operator - Delete operator used to free internally used memory +// back to VLD's private heap. +// +// - block (IN): Pointer to the vector memory block to free. +// +// Return Value: +// +// None. +// +void operator delete [] (void *block) +{ + vlddelete(block); +} + +// scalar delete operator - Delete operator used to free memory partially +// allocated by new in the event that the corresponding new operator throws +// an exception. +// +// Note: This version of the delete operator should never be called directly. +// The compiler automatically generates calls to this function as needed. +// +void operator delete (void *block, const char *, int) +{ + vlddelete(block); +} + +// vector delete operator - Delete operator used to free memory partially +// allocated by new in the event that the corresponding new operator throws +// an exception. +// +// Note: This version of the delete operator should never be called directly. +// The compiler automatically generates calls to this function as needed. +// +void operator delete [] (void *block, const char *, int) +{ + vlddelete(block); +} + +// vldnew - Local helper function that actually allocates memory from VLD's +// private heap. Prepends a header, which is used for bookkeeping information +// that allows VLD to detect and report internal memory leaks, to the returned +// block, but the header is transparent to the caller because the returned +// pointer points to the usable section of memory requested by the caller, it +// does not point to the block header. +// +// - size (IN): Size of the memory block to be allocated. +// +// - file (IN): Name of the file that called the new operator. +// +// - line (IN): Line, in the above file, at which the new operator was called. +// +// Return Value: +// +// If the memory allocation succeeds, a pointer to the allocated memory +// block is returned. If the allocation fails, NULL is returned. +// +void* vldnew (size_t size, const char *file, int line) +{ + vldblockheader_t *header = (vldblockheader_t*)RtlAllocateHeap(g_vldHeap, 0x0, size + sizeof(vldblockheader_t)); + static SIZE_T serialnumber = 0; + + if (header == NULL) { + // Out of memory. + return NULL; + } + + // Fill in the block's header information. + header->file = file; + header->line = line; + header->serialNumber = serialnumber++; + header->size = size; + + // Link the block into the block list. + CriticalSectionLocker<> cs(g_vldHeapLock); + header->next = g_vldBlockList; + if (header->next != NULL) { + header->next->prev = header; + } + header->prev = NULL; + g_vldBlockList = header; + + // Return a pointer to the beginning of the data section of the block. + return (void*)VLDBLOCKDATA(header); +} + +// vlddelete - Local helper function that actually frees memory back to VLD's +// private heap. +// +// - block (IN): Pointer to a memory block being freed. +// +// Return Value: +// +// None. +// +void vlddelete (void *block) +{ + if (block == NULL) + return; + + BOOL freed; + vldblockheader_t *header = VLDBLOCKHEADER((LPVOID)block); + + // Unlink the block from the block list. + CriticalSectionLocker<> cs(g_vldHeapLock); + if (header->prev) { + header->prev->next = header->next; + } + else { + g_vldBlockList = header->next; + } + + if (header->next) { + header->next->prev = header->prev; + } + + // Free the block. + freed = RtlFreeHeap(g_vldHeap, 0x0, header); + assert(freed); +} diff --git a/vldheap.h b/src/vldheap.h similarity index 69% rename from vldheap.h rename to src/vldheap.h index 8d83fdf0..34469d6c 100644 --- a/vldheap.h +++ b/src/vldheap.h @@ -1,94 +1,117 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - Internal C++ Heap Management Definitions -// Copyright (c) 2006 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef VLDBUILD -#error \ -"This header should only be included by Visual Leak Detector when building it from source. \ -Applications should never include this header." -#endif - -#include - -#define GAPSIZE 4 - -// Memory block header structure used internally by the debug CRT. All blocks -// allocated by the CRT are allocated from the CRT heap and, in debug mode, they -// have this header prepended to them (there's also a trailer appended at the -// end, but we're not interested in that). -typedef struct crtdbgblockheader_s -{ - struct crtblockheader_s *next; // Pointer to the next block in the list of blocks allocated from the CRT heap. - struct crtblockheader_s *prev; // Pointer to the previous block in the list of blocks allocated from the CRT heap. - char *file; // Source file where this block was allocated. - int line; // Line of code, within the above file, where this block was allocated. -#ifdef _WIN64 - int use; // This block's "use type": see below. - size_t size; // Size of the data portion of the block. -#else - size_t size; // Size of the data portion of the block. - int use; // This block's "use type": -#endif // _WIN64 -#define CRT_USE_FREE 0 // This block has been freed. -#define CRT_USE_NORMAL 1 // This is a normal (user) block. -#define CRT_USE_INTERNAL 2 // This block is used internally by the CRT. -#define CRT_USE_IGNORE 3 // This block is a specially tagged block that is ignored during some debug error checking. -#define CRT_USE_CLIENT 4 // This block is a specially tagged block with special use defined by the user application. - long request; // This block's "request" number. Basically a serial number. - unsigned char gap [GAPSIZE]; // No-man's land buffer zone, for buffer overrun/underrun checking. -} crtdbgblockheader_t; - -// Macro to strip off any sub-type information stored in a block's "use type". -#define CRT_USE_TYPE(use) (use & 0xFFFF) - -// Memory block header structure used internally by VLD. All internally -// allocated blocks are allocated from VLD's private heap and have this header -// prepended to them. -typedef struct vldblockheader_s -{ - struct vldblockheader_s *next; // Pointer to the next block in the list of internally allocated blocks. - struct vldblockheader_s *prev; // Pointer to the preceding block in the list of internally allocated blocks. - const char *file; // Name of the file where this block was allocated. - int line; // Line number within the above file where this block was allocated. - size_t size; // The size of this memory block, not including this header. - SIZE_T serialnumber; // Each block is assigned a unique serial number, starting from zero. -} vldblockheader_t; - -// Data-to-Header and Header-to-Data conversion -#define CRTDBGBLOCKHEADER(d) (crtdbgblockheader_t*)(((PBYTE)d) - sizeof(crtdbgblockheader_t)) -#define CRTDBGBLOCKDATA(h) (LPVOID)(((PBYTE)h) + sizeof(crtdbgblockheader_t)) -#define VLDBLOCKHEADER(d) (vldblockheader_t*)(((PBYTE)d) - sizeof(vldblockheader_t)) -#define VLDBLOCKDATA(h) (LPVOID)(((PBYTE)h) + sizeof(vldblockheader_t)) - -// new and delete operators for allocating from VLD's private heap. -void operator delete (void *block); -void operator delete [] (void *block); -void operator delete (void *block, const char *file, int line); -void operator delete [] (void *block, const char *file, int line); -void* operator new (size_t size, const char *file, int line); -void* operator new [] (size_t size, const char *file, int line); - -// All calls to the new operator from within VLD are mapped to the version of -// new that allocates from VLD's private heap. -#define new new(__FILE__, __LINE__) +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - Internal C++ Heap Management Definitions +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef VLDBUILD +#error \ +"This header should only be included by Visual Leak Detector when building it from source. \ +Applications should never include this header." +#endif + +#include + +#define GAPSIZE 4 + +// Memory block header structure used internally by the debug CRT. All blocks +// allocated by the CRT are allocated from the CRT heap and, in debug mode, they +// have this header pretended to them (there's also a trailer appended at the +// end, but we're not interested in that). +struct crtdbgblockheader_t +{ + struct crtdbgblockheader_t *next; // Pointer to the next block in the list of blocks allocated from the CRT heap. + struct crtdbgblockheader_t *prev; // Pointer to the previous block in the list of blocks allocated from the CRT heap. + char const *file; // Source file where this block was allocated. + int line; // Line of code, within the above file, where this block was allocated. +#ifdef _WIN64 + int use; // This block's "use type": see below. + size_t size; // Size of the data portion of the block. +#else + size_t size; // Size of the data portion of the block. + int use; // This block's "use type": +#endif // _WIN64 +#define CRT_USE_FREE 0 // This block has been freed. +#define CRT_USE_NORMAL 1 // This is a normal (user) block. +#define CRT_USE_INTERNAL 2 // This block is used internally by the CRT. +#define CRT_USE_IGNORE 3 // This block is a specially tagged block that is ignored during some debug error checking. +#define CRT_USE_CLIENT 4 // This block is a specially tagged block with special use defined by the user application. + long request; // This block's "request" number. Basically a serial number. + unsigned char gap [GAPSIZE]; // No-man's land buffer zone, for buffer overrun/underrun checking. +}; + +typedef char checkDebugHeapBlockAlignment[ + (sizeof(crtdbgblockheader_t) % MEMORY_ALLOCATION_ALIGNMENT == 0) ? 1 : -1]; + +// Same for UCRT. +struct crtdbgblockheaderucrt_t +{ + struct crtdbgblockheaderucrt_t *next; // Pointer to the next block in the list of blocks allocated from the CRT heap. + struct crtdbgblockheaderucrt_t *prev; // Pointer to the previous block in the list of blocks allocated from the CRT heap. + char const *file; // Source file where this block was allocated. + int line; // Line of code, within the above file, where this block was allocated. + int use; // This block's "use type": see below. + size_t size; // Size of the data portion of the block. + long request; // This block's "request" number. Basically a serial number. + unsigned char gap[GAPSIZE]; // No-man's land buffer zone, for buffer overrun/underrun checking. +}; + +typedef char checkDebugUcrtHeapBlockAlignment[ + (sizeof(crtdbgblockheaderucrt_t) % MEMORY_ALLOCATION_ALIGNMENT == 0) ? 1 : -1]; + +typedef char checkDebugHeapBlockSize[ + (sizeof(crtdbgblockheader_t) == sizeof(crtdbgblockheaderucrt_t)) ? 1 : -1]; + +// Macro to strip off any sub-type information stored in a block's "use type". +#define CRT_USE_TYPE(use) (use & 0xFFFF) +#define _BLOCK_TYPE_IS_VALID(use) (_BLOCK_TYPE(use) == _CLIENT_BLOCK || (use) == _NORMAL_BLOCK || _BLOCK_TYPE(use) == _CRT_BLOCK || (use) == _IGNORE_BLOCK) + +// Memory block header structure used internally by VLD. All internally +// allocated blocks are allocated from VLD's private heap and have this header +// pretended to them. +struct vldblockheader_t +{ + struct vldblockheader_t *next; // Pointer to the next block in the list of internally allocated blocks. + struct vldblockheader_t *prev; // Pointer to the preceding block in the list of internally allocated blocks. + const char *file; // Name of the file where this block was allocated. + int line; // Line number within the above file where this block was allocated. + size_t size; // The size of this memory block, not including this header. + size_t serialNumber; // Each block is assigned a unique serial number, starting from zero. +}; + +// Data-to-Header and Header-to-Data conversion +#define VLDBLOCKHEADER(d) (vldblockheader_t*)(((PBYTE)d) - sizeof(vldblockheader_t)) +#define VLDBLOCKDATA(h) (LPVOID)(((PBYTE)h) + sizeof(vldblockheader_t)) +#define CRTDBGBLOCKHEADER(d) (crtdbgblockheader_t*)(((PBYTE)d) - sizeof(crtdbgblockheader_t)) +#define CRTDBGBLOCKDATA(h) (LPVOID)(((PBYTE)h) + sizeof(crtdbgblockheader_t)) + +// new and delete operators for allocating from VLD's private heap. +void operator delete (void *block); +void operator delete [] (void *block); +void operator delete (void *block, const char *file, int line); +void operator delete [] (void *block, const char *file, int line); +void* operator new (size_t size, const char *file, int line); +void* operator new [] (size_t size, const char *file, int line); + +// All calls to the new operator from within VLD are mapped to the version of +// new that allocates from VLD's private heap. +#define new new(__FILE__, __LINE__) diff --git a/src/vldint.h b/src/vldint.h new file mode 100644 index 00000000..05cec209 --- /dev/null +++ b/src/vldint.h @@ -0,0 +1,411 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Visual Leak Detector - VisualLeakDetector Class Definition +// Copyright (c) 2005-2014 VLD Team +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +// +// See COPYING.txt for the full terms of the GNU Lesser General Public License. +// +//////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef VLDBUILD +#error \ + "This header should only be included by Visual Leak Detector when building it from source. \ + Applications should never include this header." +#endif + +#include +#pragma push_macro("new") +#undef new +#include +#include +#pragma pop_macro("new") +#include +#include "vld_def.h" +#include "version.h" +#include "callstack.h" // Provides a custom class for handling call stacks. +#include "map.h" // Provides a custom STL-like map template. +#include "ntapi.h" // Provides access to NT APIs. +#include "set.h" // Provides a custom STL-like set template. +#include "utility.h" // Provides miscellaneous utility functions. +#include "vldallocator.h" // Provides internal allocator. + +#define MAXMODULELISTLENGTH 512 // Maximum module list length, in characters. +#define SELFTESTTEXTA "Memory Leak Self-Test" +#define SELFTESTTEXTW L"Memory Leak Self-Test" +#define VLDREGKEYPRODUCT L"Software\\Visual Leak Detector" +#ifndef WIN64 +#define VLDDLL "vld_x86.dll" +#else +#define VLDDLL "vld_x64.dll" +#endif + +// The Visual Leak Detector APIs. +extern "C" __declspec(dllexport) void VLDDisable (); +extern "C" __declspec(dllexport) void VLDEnable (); +extern "C" __declspec(dllexport) void VLDRestore (); + +// Function pointer types for explicit dynamic linking with functions listed in +// the import patch table. +typedef HANDLE(__stdcall *GetProcessHeap_t) (); +typedef HANDLE(__stdcall *HeapCreate_t) (DWORD, SIZE_T, SIZE_T); +typedef BOOL(__stdcall *HeapFree_t) (HANDLE, DWORD, LPVOID); +typedef FARPROC(__stdcall *GetProcAddress_t) (HMODULE, LPCSTR); +typedef FARPROC(__stdcall *GetProcAddressForCaller_t) (HMODULE, LPCSTR, LPVOID); + +typedef void* (__cdecl *_calloc_dbg_t) (size_t, size_t, int, const char*, int); +typedef void* (__cdecl *_malloc_dbg_t) (size_t, int, const char *, int); +typedef void* (__cdecl *_realloc_dbg_t) (void *, size_t, int, const char *, int); +typedef void* (__cdecl *_recalloc_dbg_t) (void *, size_t, size_t, int, const char *, int); +typedef void* (__cdecl *calloc_t) (size_t, size_t); +typedef HRESULT (__stdcall *CoGetMalloc_t) (DWORD, LPMALLOC *); +typedef LPVOID (__stdcall *CoTaskMemAlloc_t) (SIZE_T); +typedef LPVOID (__stdcall *CoTaskMemRealloc_t) (LPVOID, SIZE_T); +typedef void* (__cdecl *malloc_t) (size_t); +typedef void* (__cdecl *new_t) (size_t); +typedef void* (__cdecl *new_dbg_crt_t) (size_t, int, const char *, int); +typedef void* (__cdecl *new_dbg_mfc_t) (size_t, const char *, int); +typedef void* (__cdecl *realloc_t) (void *, size_t); +typedef void* (__cdecl *_recalloc_t) (void *, size_t, size_t); +typedef char* (__cdecl *_strdup_t) (const char*); +typedef char* (__cdecl *_strdup_dbg_t) (const char*, int, const char* ,int); +typedef wchar_t* (__cdecl *_wcsdup_t) (const wchar_t*); +typedef wchar_t* (__cdecl *_wcsdup_dbg_t) (const wchar_t*, int, const char* ,int); +typedef void* (__cdecl *_aligned_malloc_t) (size_t, size_t); +typedef void* (__cdecl *_aligned_offset_malloc_t) (size_t, size_t, size_t); +typedef void* (__cdecl *_aligned_realloc_t) (void *, size_t, size_t); +typedef void* (__cdecl *_aligned_offset_realloc_t) (void *, size_t, size_t, size_t); +typedef void* (__cdecl *_aligned_recalloc_t) (void *, size_t, size_t, size_t); +typedef void* (__cdecl *_aligned_offset_recalloc_t) (void *, size_t, size_t, size_t, size_t); +typedef void* (__cdecl *_aligned_malloc_dbg_t) (size_t, size_t, int, const char *, int); +typedef void* (__cdecl *_aligned_offset_malloc_dbg_t) (size_t, size_t, size_t, int, const char *, int); +typedef void* (__cdecl *_aligned_realloc_dbg_t) (void *, size_t, size_t, int, const char *, int); +typedef void* (__cdecl *_aligned_offset_realloc_dbg_t) (void *, size_t, size_t, size_t, int, const char *, int); +typedef void* (__cdecl *_aligned_recalloc_dbg_t) (void *, size_t, size_t, size_t, int, const char *, int); +typedef void* (__cdecl *_aligned_offset_recalloc_dbg_t) (void *, size_t, size_t, size_t, size_t, int, const char *, int); + +// Data is collected for every block allocated from any heap in the process. +// The data is stored in this structure and these structures are stored in +// a BlockMap which maps each of these structures to its corresponding memory +// block. +struct blockinfo_t { + std::unique_ptr callStack; + DWORD threadId; + SIZE_T serialNumber; + SIZE_T size; + bool reported; + bool debugCrtAlloc; + bool ucrt; +}; + +// BlockMaps map memory blocks (via their addresses) to blockinfo_t structures. +typedef Map BlockMap; + +// Information about each heap in the process is kept in this map. Primarily +// this is used for mapping heaps to all of the blocks allocated from those +// heaps. +struct heapinfo_t { + BlockMap blockMap; // Map of all blocks allocated from this heap. + UINT32 flags; // Heap status flags +}; + +// HeapMaps map heaps (via their handles) to BlockMaps. +typedef Map HeapMap; +typedef std::basic_string, vldallocator > vldstring; + +// This structure stores information, primarily the virtual address range, about +// a given module and can be used with the Set template because it supports the +// '<' operator (sorts by virtual address range). +struct moduleinfo_t { + BOOL operator < (const struct moduleinfo_t& other) const + { + if (addrHigh < other.addrLow) { + return TRUE; + } + else { + return FALSE; + } + } + + SIZE_T addrLow; // Lowest address within the module's virtual address space (i.e. base address). + SIZE_T addrHigh; // Highest address within the module's virtual address space (i.e. base + size). + UINT32 flags; // Module flags: +#define VLD_MODULE_EXCLUDED 0x1 // If set, this module is excluded from leak detection. +#define VLD_MODULE_SYMBOLSLOADED 0x2 // If set, this module's debug symbols have been loaded. + vldstring name; // The module's name (e.g. "kernel32.dll"). + vldstring path; // The fully qualified path from where the module was loaded. +}; + +// ModuleSets store information about modules loaded in the process. +typedef Set ModuleSet; + +typedef Set ReportHookSet; + +// Thread local storage structure. Every thread in the process gets its own copy +// of this structure. Thread specific information, such as the current leak +// detection status (enabled or disabled) and the address that initiated the +// current allocation is stored here. +struct tls_t { + context_t context; // Address of return address at the first call that entered VLD's code for the current allocation. + UINT32 flags; // Thread-local status flags: +#define VLD_TLS_DEBUGCRTALLOC 0x1 // If set, the current allocation is a CRT allocation. +#define VLD_TLS_DISABLED 0x2 // If set, memory leak detection is disabled for the current thread. +#define VLD_TLS_ENABLED 0x4 // If set, memory leak detection is enabled for the current thread. +#define VLD_TLS_UCRT 0x8 // If set, the current allocation is a UCRT allocation. + UINT32 oldFlags; // Thread-local status old flags + DWORD threadId; // Thread ID of the thread that owns this TLS structure. + HANDLE heap; + LPVOID blockWithoutGuard; // Store pointer to block. + LPVOID newBlockWithoutGuard; + SIZE_T size; +}; + +// Allocation state: +// 1. Allocation function set tls->context and tls->blockWithoutGuard = NULL +// 2. HeapAlloc set tls->heap, tls->blockWithoutGuard, tls->newBlockWithoutGuard and tls->size +// 3. Allocation function reset tls data, map block and capture callstack to tls->blockWithoutGuard + +// The TlsSet allows VLD to keep track of all thread local storage structures +// allocated in the process. +typedef Map TlsMap; + +class CaptureContext { +public: + CaptureContext(void* func, context_t& context, BOOL debug = FALSE, BOOL ucrt = FALSE); + ~CaptureContext(); + __forceinline void Set(HANDLE heap, LPVOID mem, LPVOID newmem, SIZE_T size); +private: + // Disallow certain operations + CaptureContext(); + CaptureContext(const CaptureContext&); + CaptureContext& operator=(const CaptureContext&); +private: + BOOL IsExcludedModule(); + void Reset(); +private: + tls_t *m_tls; + BOOL m_bFirst; + const context_t& m_context; +}; + +class CallStack; + +//////////////////////////////////////////////////////////////////////////////// +// +// The VisualLeakDetector Class +// +// One global instance of this class is instantiated. Upon construction it +// patches the import address table (IAT) of every other module loaded in the +// process (see the "patchimport" utility function) to allow key Windows heap +// APIs to be patched through to, or redirected to, functions provided by VLD. +// Patching the IATs in this manner allows VLD to be made aware of all +// relevant heap activity, making it possible for VLD to detect and trace +// memory leaks. +// +// The one global instance of this class is constructed within the context of +// the process' main thread during process initialization and is destroyed in +// the same context during process termination. +// +// When the VisualLeakDetector object is destroyed, it consults its internal +// data structures, looking for any memory that has not been freed. A memory +// leak report is then generated, indicating any memory leaks that may have +// been identified. +// +// This class is derived from IMalloc so that it can provide an implementation +// of the IMalloc COM interface in order to support detection of COM-based +// memory leaks. However, this implementation of IMalloc is actually just a +// thin wrapper around the system's implementation of IMalloc. +// +class VisualLeakDetector : public IMalloc +{ + friend class CallStack; + friend class CaptureContext; +public: + VisualLeakDetector(); + ~VisualLeakDetector(); + + //////////////////////////////////////////////////////////////////////////////// + // Public IMalloc methods - for support of COM-based memory leak detection. + //////////////////////////////////////////////////////////////////////////////// + ULONG __stdcall AddRef (); + LPVOID __stdcall Alloc (_In_ SIZE_T size); + INT __stdcall DidAlloc (_In_opt_ LPVOID mem); + VOID __stdcall Free (_In_opt_ LPVOID mem); + SIZE_T __stdcall GetSize (_In_opt_ LPVOID mem); + VOID __stdcall HeapMinimize (); + HRESULT __stdcall QueryInterface (REFIID iid, LPVOID *object); + LPVOID __stdcall Realloc (_In_opt_ LPVOID mem, _In_ SIZE_T size); + ULONG __stdcall Release (); + + void DisableLeakDetection (); + void EnableLeakDetection (); + void RestoreLeakDetectionState (); + void GlobalDisableLeakDetection (); + void GlobalEnableLeakDetection (); + + VOID RefreshModules(); + SIZE_T GetLeaksCount(); + SIZE_T GetThreadLeaksCount(DWORD threadId); + SIZE_T ReportLeaks(); + SIZE_T ReportThreadLeaks(DWORD threadId); + VOID MarkAllLeaksAsReported(); + VOID MarkThreadLeaksAsReported(DWORD threadId); + VOID EnableModule(HMODULE module); + VOID DisableModule(HMODULE module); + UINT32 GetOptions(); + VOID GetReportFilename(WCHAR *filename); + VOID SetOptions(UINT32 option_mask, SIZE_T maxDataDump, UINT32 maxTraceFrames); + VOID SetReportOptions(UINT32 option_mask, CONST WCHAR *filename); + int SetReportHook(int mode, VLD_REPORT_HOOK pfnNewHook); + VOID SetModulesList(CONST WCHAR *modules, BOOL includeModules); + bool GetModulesList(WCHAR *modules, UINT size); + int ResolveCallstacks(); + const wchar_t* GetAllocationResolveResults(void* alloc, BOOL showInternalFrames); + + static NTSTATUS __stdcall _LdrLoadDll (LPWSTR searchpath, PULONG flags, unicodestring_t *modulename, + PHANDLE modulehandle); + static NTSTATUS __stdcall _LdrLoadDllWin8 (DWORD_PTR reserved, PULONG flags, unicodestring_t *modulename, + PHANDLE modulehandle); + static FARPROC __stdcall _RGetProcAddress(HMODULE module, LPCSTR procname); + static FARPROC __stdcall _RGetProcAddressForCaller(HMODULE module, LPCSTR procname, LPVOID caller); + + static NTSTATUS NTAPI _LdrGetDllHandle(IN PWSTR DllPath OPTIONAL, IN PULONG DllCharacteristics OPTIONAL, IN PUNICODE_STRING DllName, OUT PVOID *DllHandle OPTIONAL); + static NTSTATUS NTAPI _LdrGetProcedureAddress(IN PVOID BaseAddress, IN PANSI_STRING Name, IN ULONG Ordinal, OUT PVOID * ProcedureAddress); + static NTSTATUS NTAPI _LdrUnloadDll(IN PVOID BaseAddress); + static NTSTATUS NTAPI _LdrLockLoaderLock(IN ULONG Flags, OUT PULONG Disposition OPTIONAL, OUT PULONG_PTR Cookie OPTIONAL); + static NTSTATUS NTAPI _LdrUnlockLoaderLock(IN ULONG Flags, IN ULONG_PTR Cookie OPTIONAL); + +private: + //////////////////////////////////////////////////////////////////////////////// + // Private leak detection functions - see each function definition for details. + //////////////////////////////////////////////////////////////////////////////// + VOID attachToLoadedModules (ModuleSet *newmodules); + UINT32 getModuleState(ModuleSet::Iterator& it, UINT32 &moduleFlags); + LPWSTR buildSymbolSearchPath(); + BOOL GetIniFilePath(LPTSTR lpPath, SIZE_T cchPath); + VOID configure (); + BOOL enabled (); + SIZE_T eraseDuplicates (const BlockMap::Iterator &element, Set &aggregatedLeak); + tls_t* getTls (); + VOID mapBlock (HANDLE heap, LPCVOID mem, SIZE_T size, bool crtalloc, bool ucrt, DWORD threadId, blockinfo_t* &pblockInfo); + VOID mapHeap (HANDLE heap); + VOID remapBlock (HANDLE heap, LPCVOID mem, LPCVOID newmem, SIZE_T size, + bool crtalloc, bool ucrt, DWORD threadId, blockinfo_t* &pblockInfo, const context_t &context); + VOID reportConfig (); + static bool isDebugCrtAlloc(LPCVOID block, blockinfo_t* info); + SIZE_T reportHeapLeaks (HANDLE heap); + static int getCrtBlockUse (LPCVOID block, bool ucrt); + static size_t getCrtBlockSize(LPCVOID block, bool ucrt); + SIZE_T getLeaksCount (heapinfo_t* heapinfo, DWORD threadId = (DWORD)-1); + SIZE_T reportLeaks(heapinfo_t* heapinfo, bool &firstLeak, Set &aggregatedLeaks, DWORD threadId = (DWORD)-1); + VOID markAllLeaksAsReported (heapinfo_t* heapinfo, DWORD threadId = (DWORD)-1); + VOID unmapBlock (HANDLE heap, LPCVOID mem, const context_t &context); + VOID unmapHeap (HANDLE heap); + int resolveStacks(heapinfo_t* heapinfo); + + // Static functions (callbacks) + static BOOL __stdcall addLoadedModule (PCWSTR modulepath, DWORD64 modulebase, ULONG modulesize, PVOID context); + static BOOL __stdcall detachFromModule (PCWSTR modulepath, DWORD64 modulebase, ULONG modulesize, PVOID context); + + // Utils + static bool isModuleExcluded (UINT_PTR returnaddress); + blockinfo_t* findAllocedBlock(LPCVOID, __out HANDLE& heap); + blockinfo_t* getAllocationBlockInfo(void* alloc); + void setupReporting(); + void checkInternalMemoryLeaks(); + bool waitForAllVLDThreads(); + + //////////////////////////////////////////////////////////////////////////////// + // IAT replacement functions - see each function definition for details. + // + // Because there are so many virtually identical CRT and MFC replacement + // functions, they are excluded from the class to reduce the amount of noise + // within this class's code. See crtmfcpatch.cpp for those functions. + //////////////////////////////////////////////////////////////////////////////// + // Win32 IAT replacement functions + static FARPROC __stdcall _GetProcAddress(HMODULE module, LPCSTR procname); + static FARPROC __stdcall _GetProcAddressForCaller(HMODULE module, LPCSTR procname, LPVOID caller); + + static HANDLE __stdcall _GetProcessHeap(); + + static HANDLE __stdcall _HeapCreate (DWORD options, SIZE_T initsize, SIZE_T maxsize); + static BOOL __stdcall _HeapDestroy (HANDLE heap); + static LPVOID __stdcall _HeapAlloc (HANDLE heap, DWORD flags, SIZE_T size); + static BOOL __stdcall _HeapFree (HANDLE heap, DWORD flags, LPVOID mem); + static LPVOID __stdcall _HeapReAlloc (HANDLE heap, DWORD flags, LPVOID mem, SIZE_T size); + + static LPVOID __stdcall _RtlAllocateHeap (HANDLE heap, DWORD flags, SIZE_T size); + static BYTE __stdcall _RtlFreeHeap (HANDLE heap, DWORD flags, LPVOID mem); + static LPVOID __stdcall _RtlReAllocateHeap (HANDLE heap, DWORD flags, LPVOID mem, SIZE_T size); + + // COM IAT replacement functions + static HRESULT __stdcall _CoGetMalloc (DWORD context, LPMALLOC *imalloc); + static LPVOID __stdcall _CoTaskMemAlloc (SIZE_T size); + static LPVOID __stdcall _CoTaskMemRealloc (LPVOID mem, SIZE_T size); + + //////////////////////////////////////////////////////////////////////////////// + // Private data + //////////////////////////////////////////////////////////////////////////////// + WCHAR m_forcedModuleList [MAXMODULELISTLENGTH]; // List of modules to be forcefully included in leak detection. + HeapMap *m_heapMap; // Map of all active heaps in the process. + IMalloc *m_iMalloc; // Pointer to the system implementation of IMalloc. + + SIZE_T m_requestCurr; // Current request number. + SIZE_T m_totalAlloc; // Grand total - sum of all allocations. + SIZE_T m_curAlloc; // Total amount currently allocated. + SIZE_T m_maxAlloc; // Largest ever allocated at once. + ModuleSet *m_loadedModules; // Contains information about all modules loaded in the process. + SIZE_T m_maxDataDump; // Maximum number of user-data bytes to dump for each leaked block. + UINT32 m_maxTraceFrames; // Maximum number of frames per stack trace for each leaked block. + CriticalSection m_modulesLock; // Protects accesses to the "loaded modules" ModuleSet. + CriticalSection m_optionsLock; // Serializes access to the heap and block maps. + UINT32 m_options; // Configuration options. + + static patchentry_t m_kernelbasePatch []; + static patchentry_t m_kernel32Patch []; + static patchentry_t m_ntdllPatch []; + static patchentry_t m_ole32Patch []; + static moduleentry_t m_patchTable [58]; // Table of imports patched for attaching VLD to other modules. + FILE *m_reportFile; // File where the memory leak report may be sent to. + WCHAR m_reportFilePath [MAX_PATH]; // Full path and name of file to send memory leak report to. + const char *m_selfTestFile; // Filename where the memory leak self-test block is leaked. + int m_selfTestLine; // Line number where the memory leak self-test block is leaked. + UINT32 m_status; // Status flags: +#define VLD_STATUS_DBGHELPLINKED 0x1 // If set, the explicit dynamic link to the Debug Help Library succeeded. +#define VLD_STATUS_INSTALLED 0x2 // If set, VLD was successfully installed. +#define VLD_STATUS_NEVER_ENABLED 0x4 // If set, VLD started disabled, and has not yet been manually enabled. +#define VLD_STATUS_FORCE_REPORT_TO_FILE 0x8 // If set, the leak report is being forced to a file. + DWORD m_tlsIndex; // Thread-local storage index. + CriticalSection m_tlsLock; // Protects accesses to the Set of TLS structures. + TlsMap *m_tlsMap; // Set of all thread-local storage structures for the process. + HMODULE m_vldBase; // Visual Leak Detector's own module handle (base address). + HMODULE m_dbghlpBase; + + VOID __stdcall ChangeModuleState(HMODULE module, bool on); + static GetProcAddress_t m_GetProcAddress; + static GetProcAddressForCaller_t m_GetProcAddressForCaller; + static GetProcessHeap_t m_GetProcessHeap; + static HeapCreate_t m_HeapCreate; + static HeapFree_t m_HeapFree; +}; + + +// Configuration option default values +#define VLD_DEFAULT_MAX_DATA_DUMP 256 +#define VLD_DEFAULT_MAX_TRACE_FRAMES 64 +#define VLD_DEFAULT_REPORT_FILE_NAME L".\\memory_leak_report.txt" diff --git a/testsuite/testsuite.cpp b/testsuite/testsuite.cpp deleted file mode 100644 index 0f0d2553..00000000 --- a/testsuite/testsuite.cpp +++ /dev/null @@ -1,377 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - Test Suite -// Copyright (c) 2009 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -//////////////////////////////////////////////////////////////////////////////// -// -// Test suite for Visual Leak Detector -// -//////////////////////////////////////////////////////////////////////////////// - -#include -#include -#include - -#include - -enum action_e { - a_calloc, - a_comalloc, - a_getprocmalloc, - a_heapalloc, - a_icomalloc, - a_ignored, - a_malloc, - a_new, - numactions -}; - -#define CRTDLLNAME "msvcr90d.dll" // Name of the debug C Runtime Library DLL on this system -#define MAXALLOC 1000 // Maximum number of allocations of each type to perform, per thread -#define MAXBLOCKS (MAXALLOC * numactions) // Total maximum number of allocations, per thread -#define MAXDEPTH 32 // Maximum depth of the allocation call stack -#define MAXSIZE 64 // Maximum block size to allocate -#define MINDEPTH 0 // Minimum depth of the allocation call stack -#define MINSIZE 16 // Minimum block size to allocate -#define NUMDUPLEAKS 0 // Number of times to duplicate each leak -#define NUMTHREADS 72 // Number of threads to run simultaneously -#define ONCEINAWHILE 10 // Free a random block approx. once every... - -typedef struct blockholder_s { - action_e action; - PVOID block; - BOOL leak; -} blockholder_t; - -typedef void* (__cdecl *free_t) (void* mem); -typedef void* (__cdecl *malloc_t) (size_t size); - -typedef struct threadcontext_s { - UINT index; - BOOL leaky; - DWORD seed; - BOOL terminated; - DWORD threadid; -} threadcontext_t; - -__declspec(thread) blockholder_t blocks [MAXBLOCKS]; -__declspec(thread) ULONG counts [numactions] = { 0 }; -__declspec(thread) IMalloc *imalloc = NULL; -__declspec(thread) free_t pfree = NULL; -__declspec(thread) malloc_t pmalloc = NULL; -__declspec(thread) HANDLE threadheap; -__declspec(thread) ULONG total_allocs = 0; - -ULONG random (ULONG max) -{ - FLOAT d; - FLOAT r; - ULONG v; - - r = ((FLOAT)rand()) / ((FLOAT)RAND_MAX); - r *= ((FLOAT)max); - d = r - ((ULONG)r); - if (d >= 0.5) { - v = ((ULONG)r) + 1; - } - else { - v = (ULONG)r; - } - - return v; -} - -VOID allocateblock (action_e action, SIZE_T size) -{ - HMODULE crt; - ULONG index; - LPCSTR name; - PVOID *pblock; - HRESULT status; - - // Find the first unused index. - for (index = 0; index < MAXBLOCKS; index++) { - if (blocks[index].block == NULL) { - break; - } - } - blocks[index].action = action; - - // Now do the randomized allocation. - pblock = &blocks[index].block; - switch (action) { - case a_calloc: - name = "calloc"; - *pblock = calloc(1, size); - break; - - case a_comalloc: - name = "CoTaskMemAlloc"; - *pblock = CoTaskMemAlloc(size); - break; - - case a_getprocmalloc: - name = "GetProcAddress"; - if (pmalloc == NULL) { - crt = LoadLibrary(CRTDLLNAME); - assert(crt != NULL); - pmalloc = (malloc_t)GetProcAddress(crt, "malloc"); - assert(pmalloc != NULL); - } - *pblock = pmalloc(size); - break; - - case a_heapalloc: - name = "HeapAlloc"; - if (threadheap == NULL) { - threadheap = HeapCreate(0x0, 0, 0); - } - *pblock = HeapAlloc(threadheap, 0x0, size); - break; - - case a_icomalloc: - name = "IMalloc"; - if (imalloc == NULL) { - status = CoGetMalloc(1, &imalloc); - assert(status == S_OK); - } - *pblock = imalloc->Alloc(size); - break; - - case a_ignored: - name = "Ignored"; - VLDDisable(); - *pblock = malloc(size); - VLDEnable(); - break; - - case a_malloc: - name = "malloc"; - *pblock = malloc(size); - break; - - case a_new: - name = "new"; - *pblock = new BYTE [size]; - break; - - default: - assert(FALSE); - } - counts[action]++; - total_allocs++; - - strncpy_s((char*)*pblock, size, name, _TRUNCATE); -} - -VOID freeblock (ULONG index) -{ - PVOID block; - HMODULE crt; - - block = blocks[index].block; - switch (blocks[index].action) { - case a_calloc: - free(block); - break; - - case a_comalloc: - CoTaskMemFree(block); - break; - - case a_getprocmalloc: - if (pfree == NULL) { - crt = GetModuleHandle(CRTDLLNAME); - assert(crt != NULL); - pfree = (free_t)GetProcAddress(crt, "free"); - assert(pfree != NULL); - } - pfree(block); - break; - - case a_heapalloc: - HeapFree(threadheap, 0x0, block); - break; - - case a_icomalloc: - imalloc->Free(block); - break; - - case a_ignored: - free(block); - break; - - case a_malloc: - free(block); - break; - - case a_new: - delete [] block; - break; - - default: - assert(FALSE); - } - blocks[index].block = NULL; - counts[blocks[index].action]--; - total_allocs--; -} - -VOID recursivelyallocate (UINT depth, action_e action, SIZE_T size) -{ - if (depth == 0) { - allocateblock(action, size); - } - else { - recursivelyallocate(depth - 1, action, size); - } -} - -DWORD __stdcall runtestsuite (LPVOID param) -{ - action_e action; - USHORT action_index; - BOOL allocate_more = TRUE; - threadcontext_t *context = (threadcontext_t*)param; - UINT depth; - ULONG index; - UINT leaks_selected; - SIZE_T size; - - srand(context->seed); - - for (index = 0; index < MAXBLOCKS; index++) { - blocks[index].block = NULL; - blocks[index].leak = FALSE; - } - - while (allocate_more == TRUE) { - // Select a random allocation action and a random size. - action = (action_e)random(numactions - 1); - size = random(MAXSIZE); - if (size < MINSIZE) { - size = MINSIZE; - } - if (counts[action] == MAXALLOC) { - // We've done enough of this type of allocation. Select another. - continue; - } - - // Allocate a block, using recursion to build up a stack of random - // depth. - depth = random(MAXDEPTH); - if (depth < MINDEPTH) { - depth = MINDEPTH; - } - recursivelyallocate(depth, action, size); - - // Every once in a while, free a random block. - if (random(ONCEINAWHILE) == ONCEINAWHILE) { - index = random(total_allocs); - if (blocks[index].block != NULL) { - freeblock(index); - } - } - - // See if we have allocated enough blocks using each type of action. - for (action_index = 0; action_index < numactions; action_index++) { - if (counts[action_index] < MAXALLOC) { - allocate_more = TRUE; - break; - } - allocate_more = FALSE; - } - } - - if (context->leaky == TRUE) { - // This is the leaky thread. Randomly select one block to be leaked from - // each type of allocation action. - for (action_index = 0; action_index < numactions; action_index++) { - leaks_selected = 0; - do { - index = random(MAXBLOCKS); - if ((blocks[index].block != NULL) && (blocks[index].action == (action_e)action_index)) { - blocks[index].leak = TRUE; - leaks_selected++; - } - } while (leaks_selected < (1 + NUMDUPLEAKS)); - } - } - - // Free all blocks except for those marked as leaks. - for (index = 0; index < MAXBLOCKS; index++) { - if ((blocks[index].block != NULL) && (blocks[index].leak == FALSE)) { - freeblock(index); - } - } - - // Do a sanity check. - if (context->leaky == TRUE) { - assert(total_allocs == (numactions * (1 + NUMDUPLEAKS))); - } - else { - assert(total_allocs == 0); - } - - context->terminated = TRUE; - return 0; -} - -int main (int argc, char *argv []) -{ - threadcontext_t contexts [NUMTHREADS]; - DWORD end; - UINT index; -#define MESSAGESIZE 512 - char message [512]; - DWORD start; - UINT leakythread; - - start = GetTickCount(); - srand(start); - - // Select a random thread to be the leaker. - leakythread = random(NUMTHREADS - 1); - - for (index = 0; index < NUMTHREADS; ++index) { - contexts[index].index = index; - if (index == leakythread) { - contexts[index].leaky = TRUE; - } - contexts[index].seed = random(RAND_MAX); - contexts[index].terminated = FALSE; - CreateThread(NULL, 0, runtestsuite, &contexts[index], 0, &contexts[index].threadid); - } - - // Wait for all threads to terminate. - for (index = 0; index < NUMTHREADS; ++index) { - while (contexts[index].terminated == FALSE) { - Sleep(10); - } - } - - end = GetTickCount(); - _snprintf_s(message, 512, _TRUNCATE, "Elapsed Time = %ums\n", end - start); - OutputDebugString(message); - - return 0; -} diff --git a/testsuite/testsuite.vcproj b/testsuite/testsuite.vcproj deleted file mode 100644 index b56e9957..00000000 --- a/testsuite/testsuite.vcproj +++ /dev/null @@ -1,258 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/utility.cpp b/utility.cpp deleted file mode 100644 index 561d8bd5..00000000 --- a/utility.cpp +++ /dev/null @@ -1,840 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - Various Utility Functions -// Copyright (c) 2005-2009 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#if _WIN32_WINNT < 0x0600 // Windows XP or earlier, no GetProcessIdOfThread() -#include -#endif -#ifndef __out_xcount -#define __out_xcount(x) // Workaround for the specstrings.h bug in the Platform SDK. -#endif -#define DBGHELP_TRANSLATE_TCHAR -#include // Provides portable executable (PE) image access functions. -#define VLDBUILD // Declares that we are building Visual Leak Detector. -#include "utility.h" // Provides various utility functions and macros. -#include "vldheap.h" // Provides internal new and delete operators. - -// Imported Global Variables -extern CRITICAL_SECTION imagelock; - -// Global variables. -static BOOL reportdelay = FALSE; // If TRUE, we sleep for a bit after calling OutputDebugString to give the debugger time to catch up. -static FILE *reportfile = NULL; // Pointer to the file, if any, to send the memory leak report to. -static BOOL reporttodebugger = TRUE; // If TRUE, a copy of the memory leak report will be sent to the debugger for display. -static encoding_e reportencoding = ascii; // Output encoding of the memory leak report. - -// dumpmemorya - Dumps a nicely formatted rendition of a region of memory. -// Includes both the hex value of each byte and its ASCII equivalent (if -// printable). -// -// - address (IN): Pointer to the beginning of the memory region to dump. -// -// - size (IN): The size, in bytes, of the region to dump. -// -// Return Value: -// -// None. -// -VOID dumpmemorya (LPCVOID address, SIZE_T size) -{ - WCHAR ascdump [18] = {0}; - SIZE_T ascindex; - BYTE byte; - SIZE_T byteindex; - SIZE_T bytesdone; - SIZE_T dumplen; - WCHAR formatbuf [BYTEFORMATBUFFERLENGTH]; - WCHAR hexdump [HEXDUMPLINELENGTH] = {0}; - SIZE_T hexindex; - - // Each line of output is 16 bytes. - if ((size % 16) == 0) { - // No padding needed. - dumplen = size; - } - else { - // We'll need to pad the last line out to 16 bytes. - dumplen = size + (16 - (size % 16)); - } - - // For each byte of data, get both the ASCII equivalent (if it is a - // printable character) and the hex representation. - bytesdone = 0; - for (byteindex = 0; byteindex < dumplen; byteindex++) { - hexindex = 3 * ((byteindex % 16) + ((byteindex % 16) / 4)); // 3 characters per byte, plus a 3-character space after every 4 bytes. - ascindex = (byteindex % 16) + (byteindex % 16) / 8; // 1 character per byte, plus a 1-character space after every 8 bytes. - if (byteindex < size) { - byte = ((PBYTE)address)[byteindex]; - _snwprintf_s(formatbuf, BYTEFORMATBUFFERLENGTH, _TRUNCATE, L"%.2X ", byte); - formatbuf[3] = '\0'; - wcsncpy_s(hexdump + hexindex, HEXDUMPLINELENGTH - hexindex, formatbuf, 4); - if (isgraph(byte)) { - ascdump[ascindex] = (WCHAR)byte; - } - else { - ascdump[ascindex] = L'.'; - } - } - else { - // Add padding to fill out the last line to 16 bytes. - wcsncpy_s(hexdump + hexindex, HEXDUMPLINELENGTH - hexindex, L" ", 4); - ascdump[ascindex] = L'.'; - } - bytesdone++; - if ((bytesdone % 16) == 0) { - // Print one line of data for every 16 bytes. Include the - // ASCII dump and the hex dump side-by-side. - report(L" %s %s\n", hexdump, ascdump); - } - else { - if ((bytesdone % 8) == 0) { - // Add a spacer in the ASCII dump after every 8 bytes. - ascdump[ascindex + 1] = L' '; - } - if ((bytesdone % 4) == 0) { - // Add a spacer in the hex dump after every 4 bytes. - wcsncpy_s(hexdump + hexindex + 3, HEXDUMPLINELENGTH - hexindex - 3, L" ", 4); - } - } - } -} - -// dumpmemoryw - Dumps a nicely formatted rendition of a region of memory. -// Includes both the hex value of each byte and its Unicode equivalent. -// -// - address (IN): Pointer to the beginning of the memory region to dump. -// -// - size (IN): The size, in bytes, of the region to dump. -// -// Return Value: -// -// None. -// -VOID dumpmemoryw (LPCVOID address, SIZE_T size) -{ - BYTE byte; - SIZE_T byteindex; - SIZE_T bytesdone; - SIZE_T dumplen; - WCHAR formatbuf [BYTEFORMATBUFFERLENGTH]; - WCHAR hexdump [HEXDUMPLINELENGTH] = {0}; - SIZE_T hexindex; - WORD word; - WCHAR unidump [18] = {0}; - SIZE_T uniindex; - - // Each line of output is 16 bytes. - if ((size % 16) == 0) { - // No padding needed. - dumplen = size; - } - else { - // We'll need to pad the last line out to 16 bytes. - dumplen = size + (16 - (size % 16)); - } - - // For each word of data, get both the Unicode equivalent and the hex - // representation. - bytesdone = 0; - for (byteindex = 0; byteindex < dumplen; byteindex++) { - hexindex = 3 * ((byteindex % 16) + ((byteindex % 16) / 4)); // 3 characters per byte, plus a 3-character space after every 4 bytes. - uniindex = ((byteindex / 2) % 8) + ((byteindex / 2) % 8) / 8; // 1 character every other byte, plus a 1-character space after every 8 bytes. - if (byteindex < size) { - byte = ((PBYTE)address)[byteindex]; - _snwprintf_s(formatbuf, BYTEFORMATBUFFERLENGTH, _TRUNCATE, L"%.2X ", byte); - formatbuf[BYTEFORMATBUFFERLENGTH - 1] = '\0'; - wcsncpy_s(hexdump + hexindex, HEXDUMPLINELENGTH - hexindex, formatbuf, 4); - if (((byteindex % 2) == 0) && ((byteindex + 1) < dumplen)) { - // On every even byte, print one character. - word = ((PWORD)address)[byteindex / 2]; - if ((word == 0x0000) || (word == 0x0020)) { - unidump[uniindex] = L'.'; - } - else { - unidump[uniindex] = word; - } - } - } - else { - // Add padding to fill out the last line to 16 bytes. - wcsncpy_s(hexdump + hexindex, HEXDUMPLINELENGTH - hexindex, L" ", 4); - unidump[uniindex] = L'.'; - } - bytesdone++; - if ((bytesdone % 16) == 0) { - // Print one line of data for every 16 bytes. Include the - // ASCII dump and the hex dump side-by-side. - report(L" %s %s\n", hexdump, unidump); - } - else { - if ((bytesdone % 8) == 0) { - // Add a spacer in the ASCII dump after every 8 bytes. - unidump[uniindex + 1] = L' '; - } - if ((bytesdone % 4) == 0) { - // Add a spacer in the hex dump after every 4 bytes. - wcsncpy_s(hexdump + hexindex + 3, HEXDUMPLINELENGTH - hexindex - 3, L" ", 4); - } - } - } -} - -// findimport - Determines if the specified module imports the named import -// from the named exporting module. -// -// - importmodule (IN): Handle (base address) of the module to be searched to -// see if it imports the specified import. -// -// - exportmodule (IN): Handle (base address) of the module that exports the -// import to be searched for. -// -// - exportmodulename (IN): ANSI string containing the name of the module that -// exports the import to be searched for. -// -// - importname (IN): ANSI string containing the name of the import to search -// for. May be an integer cast to a string if the import is exported by -// ordinal. -// -// Return Value: -// -// Returns TRUE if the module imports to the specified import. Otherwise -// returns FALSE. -// -BOOL findimport (HMODULE importmodule, HMODULE exportmodule, LPCSTR exportmodulename, LPCSTR importname) -{ - IMAGE_THUNK_DATA *iate; - IMAGE_IMPORT_DESCRIPTOR *idte; - FARPROC import; - IMAGE_SECTION_HEADER *section; - ULONG size; - - // Locate the importing module's Import Directory Table (IDT) entry for the - // exporting module. The importing module actually can have several IATs -- - // one for each export module that it imports something from. The IDT entry - // gives us the offset of the IAT for the module we are interested in. - EnterCriticalSection(&imagelock); - idte = (IMAGE_IMPORT_DESCRIPTOR*)ImageDirectoryEntryToDataEx((PVOID)importmodule, TRUE, - IMAGE_DIRECTORY_ENTRY_IMPORT, &size, §ion); - LeaveCriticalSection(&imagelock); - if (idte == NULL) { - // This module has no IDT (i.e. it imports nothing). - return FALSE; - } - while (idte->OriginalFirstThunk != 0x0) { - if (_stricmp((PCHAR)R2VA(importmodule, idte->Name), exportmodulename) == 0) { - // Found the IDT entry for the exporting module. - break; - } - idte++; - } - if (idte->OriginalFirstThunk == 0x0) { - // The importing module does not import anything from the exporting - // module. - return FALSE; - } - - // Get the *real* address of the import. If we find this address in the IAT, - // then we've found that the module does import the named import. - import = GetProcAddress(exportmodule, importname); - assert(import != NULL); // Perhaps the named export module does not actually export the named import? - - // Locate the import's IAT entry. - iate = (IMAGE_THUNK_DATA*)R2VA(importmodule, idte->FirstThunk); - while (iate->u1.Function != 0x0) { - if (iate->u1.Function == (DWORD_PTR)import) { - // Found the IAT entry. The module imports the named import. - return TRUE; - } - iate++; - } - - // The module does not import the named import. - return FALSE; -} - -// findpatch - Determines if the specified module has been patched to use the -// specified replacement. -// -// - importmodule (IN): Handle (base address) of the module to be searched to -// see if it imports the specified replacement export. -// -// - exportmodulename (IN): ANSI string containing the name of the module that -// normally exports that import that would have been patched to use the -// replacement export. -// -// - replacement (IN): Address of the replacement, or destination, function or -// variable to search for. -// -// Return Value: -// -// Returns TRUE if the module has been patched to use the specified -// replacement export. -// -BOOL findpatch (HMODULE importmodule, LPCSTR exportmodulename, LPCVOID replacement) -{ - IMAGE_THUNK_DATA *iate; - IMAGE_IMPORT_DESCRIPTOR *idte; - IMAGE_SECTION_HEADER *section; - ULONG size; - - // Locate the importing module's Import Directory Table (IDT) entry for the - // exporting module. The importing module actually can have several IATs -- - // one for each export module that it imports something from. The IDT entry - // gives us the offset of the IAT for the module we are interested in. - EnterCriticalSection(&imagelock); - idte = (IMAGE_IMPORT_DESCRIPTOR*)ImageDirectoryEntryToDataEx((PVOID)importmodule, TRUE, - IMAGE_DIRECTORY_ENTRY_IMPORT, &size, §ion); - LeaveCriticalSection(&imagelock); - if (idte == NULL) { - // This module has no IDT (i.e. it imports nothing). - return FALSE; - } - while (idte->OriginalFirstThunk != 0x0) { - if (_stricmp((PCHAR)R2VA(importmodule, idte->Name), exportmodulename) == 0) { - // Found the IDT entry for the exporting module. - break; - } - idte++; - } - if (idte->OriginalFirstThunk == 0x0) { - // The importing module does not import anything from the exporting - // module. - return FALSE; - } - - // Locate the replacement's IAT entry. - iate = (IMAGE_THUNK_DATA*)R2VA(importmodule, idte->FirstThunk); - while (iate->u1.Function != 0x0) { - if (iate->u1.Function == (DWORD_PTR)replacement) { - // Found the IAT entry for the replacement. This patch has been - // installed. - return TRUE; - } - iate++; - } - - // The module does not import the replacement. The patch has not been - // installed. - return FALSE; -} - -// insertreportdelay - Sets the report function to sleep for a bit after each -// call to OutputDebugString, in order to allow the debugger to catch up. -// -// Return Value: -// -// None. -// -VOID insertreportdelay () -{ - reportdelay = TRUE; -} - -// moduleispatched - Checks to see if any of the imports listed in the specified -// patch table have been patched into the specified importmodule. -// -// - importmodule (IN): Handle (base address) of the module to be queried to -// determine if it has been patched. -// -// - patchtable (IN): An array of patchentry_t structures specifying all of the -// import patches to search for. -// -// - tablesize (IN): Size, in entries, of the specified patch table. -// -// Return Value: -// -// Returns TRUE if at least one of the patches listed in the patch table is -// installed in the importmodule. Otherwise returns FALSE. -// -BOOL moduleispatched (HMODULE importmodule, patchentry_t patchtable [], UINT tablesize) -{ - patchentry_t *entry; - BOOL found = FALSE; - UINT index; - - // Loop through the import patch table, individually checking each patch - // entry to see if it is installed in the import module. If any patch entry - // is installed in the import module, then the module has been patched. - for (index = 0; index < tablesize; index++) { - entry = &patchtable[index]; - found = findpatch(importmodule, entry->exportmodulename, entry->replacement); - if (found == TRUE) { - // Found one of the listed patches installed in the import module. - return TRUE; - } - } - - // No patches listed in the patch table were found in the import module. - return FALSE; -} - -// patchimport - Patches all future calls to an imported function, or references -// to an imported variable, through to a replacement function or variable. -// Patching is done by replacing the import's address in the specified target -// module's Import Address Table (IAT) with the address of the replacement -// function or variable. -// -// - importmodule (IN): Handle (base address) of the target module for which -// calls or references to the import should be patched. -// -// - exportmodule (IN): Handle (base address) of the module that exports the -// the function or variable to be patched. -// -// - exportmodulename (IN): ANSI string containing the name of the module that -// exports the function or variable to be patched. -// -// - importname (IN): ANSI string containing the name of the imported function -// or variable to be patched. May be an integer cast to a string if the -// import is exported by ordinal. -// -// - replacement (IN): Address of the function or variable to which future -// calls or references should be patched through to. This function or -// variable can be thought of as effectively replacing the original import -// from the point of view of the module specified by "importmodule". -// -// Return Value: -// -// Returns TRUE if the patch was installed into the import module. If the -// import module does not import the specified export, so nothing changed, -// then FALSE will be returned. -// -BOOL patchimport (HMODULE importmodule, HMODULE exportmodule, LPCSTR exportmodulename, LPCSTR importname, - LPCVOID replacement) -{ - IMAGE_THUNK_DATA *iate; - IMAGE_IMPORT_DESCRIPTOR *idte; - FARPROC import; - DWORD protect; - IMAGE_SECTION_HEADER *section; - ULONG size; - - // Locate the importing module's Import Directory Table (IDT) entry for the - // exporting module. The importing module actually can have several IATs -- - // one for each export module that it imports something from. The IDT entry - // gives us the offset of the IAT for the module we are interested in. - EnterCriticalSection(&imagelock); - idte = (IMAGE_IMPORT_DESCRIPTOR*)ImageDirectoryEntryToDataEx((PVOID)importmodule, TRUE, - IMAGE_DIRECTORY_ENTRY_IMPORT, &size, §ion); - LeaveCriticalSection(&imagelock); - if (idte == NULL) { - // This module has no IDT (i.e. it imports nothing). - return FALSE; - } - while (idte->OriginalFirstThunk != 0x0) { - if (_stricmp((PCHAR)R2VA(importmodule, idte->Name), exportmodulename) == 0) { - // Found the IDT entry for the exporting module. - break; - } - idte++; - } - if (idte->OriginalFirstThunk == 0x0) { - // The importing module does not import anything from the exporting - // module. - return FALSE; - } - - // Get the *real* address of the import. If we find this address in the IAT, - // then we've found the entry that needs to be patched. - import = GetProcAddress(exportmodule, importname); - assert(import != NULL); // Perhaps the named export module does not actually export the named import? - - // Locate the import's IAT entry. - iate = (IMAGE_THUNK_DATA*)R2VA(importmodule, idte->FirstThunk); - while (iate->u1.Function != 0x0) { - if (iate->u1.Function == (DWORD_PTR)import) { - // Found the IAT entry. Overwrite the address stored in the IAT - // entry with the address of the replacement. Note that the IAT - // entry may be write-protected, so we must first ensure that it is - // writable. - VirtualProtect(&iate->u1.Function, sizeof(iate->u1.Function), PAGE_READWRITE, &protect); - iate->u1.Function = (DWORD_PTR)replacement; - VirtualProtect(&iate->u1.Function, sizeof(iate->u1.Function), protect, &protect); - - // The patch has been installed in the import module. - return TRUE; - } - iate++; - } - - // The import's IAT entry was not found. The importing module does not - // import the specified import. - return FALSE; -} - -// patchmodule - Patches all imports listed in the supplied patch table, and -// which are imported by the specified module, through to their respective -// replacement functions. -// -// Note: If the specified module does not import any of the functions listed -// in the patch table, then nothing is changed for the specified module. -// -// - importmodule (IN): Handle (base address) of the target module which is to -// have its imports patched. -// -// - patchtable (IN): An array of patchentry_t structures specifying all of the -// imports to patch for the specified module. -// -// - tablesize (IN): Size, in entries, of the specified patch table. -// -// Return Value: -// -// Returns TRUE if at least one of the patches listed in the patch table was -// installed in the importmodule. Otherwise returns FALSE. -// -BOOL patchmodule (HMODULE importmodule, patchentry_t patchtable [], UINT tablesize) -{ - patchentry_t *entry; - UINT index; - BOOL patched = FALSE; - - // Loop through the import patch table, individually patching each import - // listed in the table. - for (index = 0; index < tablesize; index++) { - entry = &patchtable[index]; - if (patchimport(importmodule, (HMODULE)entry->modulebase, entry->exportmodulename, entry->importname, - entry->replacement) == TRUE) { - patched = TRUE; - } - } - - return patched; -} - -// report - Sends a printf-style formatted message to the debugger for display -// and/or to a file. -// -// Note: A message longer than MAXREPORTLENGTH characters will be truncated -// to MAXREPORTLENGTH. -// -// - format (IN): Specifies a printf-compliant format string containing the -// message to be sent to the debugger. -// -// - ... (IN): Arguments to be formatted using the specified format string. -// -// Return Value: -// -// None. -// -VOID report (LPCWSTR format, ...) -{ - va_list args; - size_t count; - CHAR messagea [MAXREPORTLENGTH + 1]; - WCHAR messagew [MAXREPORTLENGTH + 1]; - - va_start(args, format); - _vsnwprintf_s(messagew, MAXREPORTLENGTH + 1, _TRUNCATE, format, args); - va_end(args); - messagew[MAXREPORTLENGTH] = L'\0'; - - if (reportencoding == unicode) { - if (reportfile != NULL) { - // Send the report to the previously specified file. - fwrite(messagew, sizeof(WCHAR), wcslen(messagew), reportfile); - } - if (reporttodebugger) { - OutputDebugStringW(messagew); - } - } - else { - if (wcstombs_s(&count, messagea, MAXREPORTLENGTH + 1, messagew, _TRUNCATE) == -1) { - // Failed to convert the Unicode message to ASCII. - assert(FALSE); - return; - } - messagea[MAXREPORTLENGTH] = '\0'; - if (reportfile != NULL) { - // Send the report to the previously specified file. - fwrite(messagea, sizeof(CHAR), strlen(messagea), reportfile); - } - if (reporttodebugger) { - OutputDebugStringA(messagea); - } - } - - if (reporttodebugger && (reportdelay == TRUE)) { - Sleep(10); // Workaround the Visual Studio 6 bug where debug strings are sometimes lost if they're sent too fast. - } -} - -// restoreimport - Restores the IAT entry for an import previously patched via -// a call to "patchimport" to the original address of the import. -// -// - importmodule (IN): Handle (base address) of the target module for which -// calls or references to the import should be restored. -// -// - exportmodule (IN): Handle (base address) of the module that exports the -// function or variable to be patched. -// -// - exportmodulename (IN): ANSI string containing the name of the module that -// exports the function or variable to be patched. -// -// - importname (IN): ANSI string containing the name of the imported function -// or variable to be restored. May be an integer cast to a string if the -// import is exported by ordinal. -// -// - replacement (IN): Address of the function or variable which the import was -// previously patched through to via a call to "patchimport". -// -// Return Value: -// -// None. -// -VOID restoreimport (HMODULE importmodule, HMODULE exportmodule, LPCSTR exportmodulename, LPCSTR importname, - LPCVOID replacement) -{ - IMAGE_THUNK_DATA *iate; - IMAGE_IMPORT_DESCRIPTOR *idte; - FARPROC import; - DWORD protect; - IMAGE_SECTION_HEADER *section; - ULONG size; - - // Locate the importing module's Import Directory Table (IDT) entry for the - // exporting module. The importing module actually can have several IATs -- - // one for each export module that it imports something from. The IDT entry - // gives us the offset of the IAT for the module we are interested in. - EnterCriticalSection(&imagelock); - idte = (IMAGE_IMPORT_DESCRIPTOR*)ImageDirectoryEntryToDataEx((PVOID)importmodule, TRUE, - IMAGE_DIRECTORY_ENTRY_IMPORT, &size, §ion); - LeaveCriticalSection(&imagelock); - if (idte == NULL) { - // This module has no IDT (i.e. it imports nothing). - return; - } - while (idte->OriginalFirstThunk != 0x0) { - if (_stricmp((PCHAR)R2VA(importmodule, idte->Name), exportmodulename) == 0) { - // Found the IDT entry for the exporting module. - break; - } - idte++; - } - if (idte->OriginalFirstThunk == 0x0) { - // The importing module does not import anything from the exporting - // module. - return; - } - - // Get the *real* address of the import. - import = GetProcAddress(exportmodule, importname); - assert(import != NULL); // Perhaps the named export module does not actually export the named import? - - // Locate the import's original IAT entry (it currently has the replacement - // address in it). - iate = (IMAGE_THUNK_DATA*)R2VA(importmodule, idte->FirstThunk); - while (iate->u1.Function != 0x0) { - if (iate->u1.Function == (DWORD_PTR)replacement) { - // Found the IAT entry. Overwrite the address stored in the IAT - // entry with the import's real address. Note that the IAT entry may - // be write-protected, so we must first ensure that it is writable. - VirtualProtect(&iate->u1.Function, sizeof(iate->u1.Function), PAGE_READWRITE, &protect); - iate->u1.Function = (DWORD_PTR)import; - VirtualProtect(&iate->u1.Function, sizeof(iate->u1.Function), protect, &protect); - break; - } - iate++; - } -} - -// restoremodule - Restores all imports listed in the supplied patch table, and -// which are imported by the specified module, to their original functions. -// -// Note: If the specified module does not import any of the functions listed -// in the patch table, then nothing is changed for the specified module. -// -// - importmodule (IN): Handle (base address) of the target module which is to -// have its imports restored. -// -// - patchtable (IN): Array of patchentry_t structures specifying all of the -// imports to restore for the specified module. -// -// - tablesize (IN): Size, in entries, of the specified patch table. -// -// Return Value: -// -// None. -// -VOID restoremodule (HMODULE importmodule, patchentry_t patchtable [], UINT tablesize) -{ - patchentry_t *entry; - UINT index; - - // Loop through the import patch table, individually restoring each import - // listed in the table. - for (index = 0; index < tablesize; index++) { - entry = &patchtable[index]; - restoreimport(importmodule, (HMODULE)entry->modulebase, entry->exportmodulename, entry->importname, - entry->replacement); - } -} - -// setreportencoding - Sets the output encoding of report messages to either -// ASCII (the default) or Unicode. -// -// - encoding (IN): Specifies either "ascii" or "unicode". -// -// Return Value: -// -// None. -// -VOID setreportencoding (encoding_e encoding) -{ - switch (encoding) { - case ascii: - case unicode: - reportencoding = encoding; - break; - - default: - assert(FALSE); - } -} - -// setreportfile - Sets a destination file to which all report messages should -// be sent. If this function is not called to set a destination file, then -// report messages will be sent to the debugger instead of to a file. -// -// - file (IN): Pointer to an open file, to which future report messages should -// be sent. -// -// - copydebugger (IN): If true, in addition to sending report messages to -// the specified file, a copy of each message will also be sent to the -// debugger. -// -// Return Value: -// -// None. -// -VOID setreportfile (FILE *file, BOOL copydebugger) -{ - reportfile = file; - reporttodebugger = copydebugger; -} - -// strapp - Appends the specified source string to the specified destination -// string. Allocates additional space so that the destination string "grows" -// as new strings are appended to it. This function is fairly infrequently -// used so efficiency is not a major concern. -// -// - dest (IN/OUT): Address of the destination string. Receives the resulting -// combined string after the append operation. -// -// - source (IN): Source string to be appended to the destination string. -// -// Return Value: -// -// None. -// -VOID strapp (LPWSTR *dest, LPCWSTR source) -{ - SIZE_T length; - LPWSTR temp; - - temp = *dest; - length = wcslen(*dest) + wcslen(source); - *dest = new WCHAR [length + 1]; - wcsncpy_s(*dest, length + 1, temp, _TRUNCATE); - wcsncat_s(*dest, length + 1, source, _TRUNCATE); - delete [] temp; -} - -// strtobool - Converts string values (e.g. "yes", "no", "on", "off") to boolean -// values. -// -// - s (IN): String value to convert. -// -// Return Value: -// -// Returns TRUE if the string is recognized as a "true" string. Otherwise -// returns FALSE. -// -BOOL strtobool (LPCWSTR s) { - WCHAR *end; - - if ((_wcsicmp(s, L"true") == 0) || - (_wcsicmp(s, L"yes") == 0) || - (_wcsicmp(s, L"on") == 0) || - (wcstol(s, &end, 10) == 1)) { - return TRUE; - } - else { - return FALSE; - } -} - -// _GetProcessIdOfThread - Returns the ID of the process owns the thread. -// -// - thread (IN): The handle to the thread. -// -// Return Value: -// -// Returns the ID of the process that owns the thread. Otherwise returns 0. -// -DWORD _GetProcessIdOfThread (HANDLE thread) -{ - typedef struct _CLIENT_ID { - HANDLE UniqueProcess; - HANDLE UniqueThread; - } CLIENT_ID, *PCLIENT_ID; - - typedef LONG NTSTATUS; - typedef LONG KPRIORITY; - - typedef struct _THREAD_BASIC_INFORMATION { - NTSTATUS ExitStatus; - PVOID TebBaseAddress; - CLIENT_ID ClientId; - KAFFINITY AffinityMask; - KPRIORITY Priority; - KPRIORITY BasePriority; - } THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION; - - const static THREADINFOCLASS ThreadBasicInformation = (THREADINFOCLASS)0; - - typedef NTSTATUS (WINAPI *PNtQueryInformationThread) (HANDLE thread, - THREADINFOCLASS infoclass, PVOID buffer, ULONG buffersize, - PULONG used); - - static PNtQueryInformationThread NtQueryInformationThread = NULL; - - THREAD_BASIC_INFORMATION tbi; - NTSTATUS status; - HMODULE ntdll; - if (NtQueryInformationThread == NULL) { - ntdll = GetModuleHandle(L"ntdll.dll"); - NtQueryInformationThread = (PNtQueryInformationThread)GetProcAddress(ntdll, "NtQueryInformationThread"); - if (NtQueryInformationThread == NULL) { - return 0; - } - } - - status = NtQueryInformationThread(thread, ThreadBasicInformation, &tbi, sizeof(tbi), NULL); - if(status < 0) { - // Shall we go through all the trouble of setting last error? - return 0; - } - - return (DWORD)tbi.ClientId.UniqueProcess; -} diff --git a/utility.h b/utility.h deleted file mode 100644 index dd106004..00000000 --- a/utility.h +++ /dev/null @@ -1,112 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - Various Utility Definitions -// Copyright (c) 2005-2006 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef VLDBUILD -#error \ -"This header should only be included by Visual Leak Detector when building it from source. \ -Applications should never include this header." -#endif - -#include -#include - -#ifdef _WIN64 -#define ADDRESSFORMAT L"0x%.16X" // Format string for 64-bit addresses -#else -#define ADDRESSFORMAT L"0x%.8X" // Format string for 32-bit addresses -#endif // _WIN64 -#define BOM 0xFEFF // Unicode byte-order mark. -#define MAXREPORTLENGTH 511 // Maximum length, in characters, of "report" messages. - -// Architecture-specific definitions for x86 and x64 -#if defined(_M_IX86) -#define SIZEOFPTR 4 -#define X86X64ARCHITECTURE IMAGE_FILE_MACHINE_I386 -#define AXREG Eax -#define BPREG Ebp -#define IPREG Eip -#define SPREG Esp -#elif defined(_M_X64) -#define SIZEOFPTR 8 -#define X86X64ARCHITECTURE IMAGE_FILE_MACHINE_AMD64 -#define AXREG Rax -#define BPREG Rbp -#define IPREG Rip -#define SPREG Rsp -#endif // _M_IX86 - -#if defined(_M_IX86) || defined (_M_X64) -#define FRAMEPOINTER(fp) __asm {mov fp, BPREG} // Copies the current frame pointer to the supplied variable. -#else -// If you want to retarget Visual Leak Detector to another processor -// architecture then you'll need to provide an architecture-specific macro to -// obtain the frame pointer (or other address) which can be used to obtain the -// return address and stack pointer of the calling frame. -#error "Visual Leak Detector is not supported on this architecture." -#endif // _M_IX86 || _M_X64 - -// Miscellaneous definitions -#define R2VA(modulebase, rva) (((PBYTE)modulebase) + rva) // Relative Virtual Address to Virtual Address conversion. -#define BYTEFORMATBUFFERLENGTH 4 -#define HEXDUMPLINELENGTH 58 - -// Reports can be encoded as either ASCII or Unicode (UTF-16). -enum encoding_e { - ascii, - unicode -}; - -// This structure allows us to build a table of APIs which should be patched -// through to replacement functions provided by VLD. -typedef struct patchentry_s -{ - LPCSTR exportmodulename; // The name of the module exporting the patched API. - LPCSTR importname; // The name (or ordinal) of the imported API being patched. - SIZE_T modulebase; // The base address of the exporting module (filled in at runtime when the modules are loaded). - LPCVOID replacement; // Pointer to the function to which the imported API should be patched through to. -} patchentry_t; - -// Utility functions. See function definitions for details. -VOID dumpmemorya (LPCVOID address, SIZE_T length); -VOID dumpmemoryw (LPCVOID address, SIZE_T length); -BOOL findimport (HMODULE importmodule, HMODULE exportmodule, LPCSTR exportmodulename, LPCSTR importname); -BOOL findpatch (HMODULE importmodule, LPCSTR exportmodulename, LPCVOID replacement); -VOID insertreportdelay (); -BOOL moduleispatched (HMODULE importmodule, patchentry_t patchtable [], UINT tablesize); -BOOL patchimport (HMODULE importmodule, HMODULE exportmodule, LPCSTR exportmodulename, LPCSTR importname, - LPCVOID replacement); -BOOL patchmodule (HMODULE importmodule, patchentry_t patchtable [], UINT tablesize); -VOID report (LPCWSTR format, ...); -VOID restoreimport (HMODULE importmodule, HMODULE exportmodule, LPCSTR exportmodulename, LPCSTR importname, - LPCVOID replacement); -VOID restoremodule (HMODULE importmodule, patchentry_t patchtable [], UINT tablesize); -VOID setreportencoding (encoding_e encoding); -VOID setreportfile (FILE *file, BOOL copydebugger); -VOID strapp (LPWSTR *dest, LPCWSTR source); -BOOL strtobool (LPCWSTR s); -#if _WIN32_WINNT < 0x0600 // Windows XP or earlier, no GetProcessIdOfThread() -DWORD _GetProcessIdOfThread (HANDLE thread); -#define GetProcessIdOfThread _GetProcessIdOfThread -#endif \ No newline at end of file diff --git a/vld.cpp b/vld.cpp deleted file mode 100644 index d797d2e2..00000000 --- a/vld.cpp +++ /dev/null @@ -1,2726 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - VisualLeakDetector Class Implementation -// Copyright (c) 2005-2009 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#pragma comment(lib, "dbghelp.lib") - -#include -#include -#include -#include -#include -#ifndef __out_xcount -#define __out_xcount(x) // Workaround for the specstrings.h bug in the Platform SDK. -#endif -#define DBGHELP_TRANSLATE_TCHAR -#include // Provides symbol handling services. -#define VLDBUILD // Declares that we are building Visual Leak Detector. -#include "callstack.h" // Provides a class for handling call stacks. -#include "crtmfcpatch.h" // Provides CRT and MFC patch functions. -#include "map.h" // Provides a lightweight STL-like map template. -#include "ntapi.h" // Provides access to NT APIs. -#include "set.h" // Provides a lightweight STL-like set template. -#include "utility.h" // Provides various utility functions. -#include "vldheap.h" // Provides internal new and delete operators. -#include "vldint.h" // Provides access to the Visual Leak Detector internals. - -#define BLOCKMAPRESERVE 64 // This should strike a balance between memory use and a desire to minimize heap hits. -#define HEAPMAPRESERVE 2 // Usually there won't be more than a few heaps in the process, so this should be small. -#define MAXSYMBOLNAMELENGTH 256 // Maximum symbol name length that we will allow. Longer names will be truncated. -#define MODULESETRESERVE 16 // There are likely to be several modules loaded in the process. - -// Imported global variables. -extern vldblockheader_t *vldblocklist; -extern HANDLE vldheap; -extern CRITICAL_SECTION vldheaplock; - -// Global variables. -HANDLE currentprocess; // Pseudo-handle for the current process. -HANDLE currentthread; // Pseudo-handle for the current thread. -CRITICAL_SECTION imagelock; // Serializes calls to the Debug Help Library PE image access APIs. -HANDLE processheap; // Handle to the process's heap (COM allocations come from here). -CRITICAL_SECTION stackwalklock; // Serializes calls to StackWalk64 from the Debug Help Library. -CRITICAL_SECTION symbollock; // Serializes calls to the Debug Help Library symbols handling APIs. - -// The one and only VisualLeakDetector object instance. -__declspec(dllexport) VisualLeakDetector vld; - -// Global function pointers for explicit dynamic linking with functions listed -// in the import patch table. Using explicit dynamic linking minimizes VLD's -// footprint by loading only modules that are actually used. These pointers will -// be linked to the real functions the first time they are used. - -// The import patch table: lists the heap-related API imports that VLD patches -// through to replacement functions provided by VLD. Having this table simply -// makes it more convenient to add additional IAT patches. -patchentry_t VisualLeakDetector::m_patchtable [] = { - // Win32 heap APIs. - "kernel32.dll", "GetProcAddress", 0x0, _GetProcAddress, // Not heap related, but can be used to obtain pointers to heap functions. - "kernel32.dll", "HeapAlloc", 0x0, _RtlAllocateHeap, - "kernel32.dll", "HeapCreate", 0x0, _HeapCreate, - "kernel32.dll", "HeapDestroy", 0x0, _HeapDestroy, - "kernel32.dll", "HeapFree", 0x0, _RtlFreeHeap, - "kernel32.dll", "HeapReAlloc", 0x0, _RtlReAllocateHeap, - - // MFC new operators (exported by ordinal). - // XXX why are the vector new operators missing for mfc42d.dll? - "mfc42d.dll", (LPCSTR)711, 0x0, VS60::mfcd_scalar_new, - "mfc42d.dll", (LPCSTR)712, 0x0, VS60::mfcd__scalar_new_dbg_4p, - "mfc42d.dll", (LPCSTR)714, 0x0, VS60::mfcd__scalar_new_dbg_3p, - "mfc42ud.dll", (LPCSTR)711, 0x0, VS60::mfcud_scalar_new, - "mfc42ud.dll", (LPCSTR)712, 0x0, VS60::mfcud__scalar_new_dbg_4p, - "mfc42ud.dll", (LPCSTR)714, 0x0, VS60::mfcud__scalar_new_dbg_3p, - "mfc70d.dll", (LPCSTR)257, 0x0, VS70::mfcd_vector_new, - "mfc70d.dll", (LPCSTR)258, 0x0, VS70::mfcd__vector_new_dbg_4p, - "mfc70d.dll", (LPCSTR)259, 0x0, VS70::mfcd__vector_new_dbg_3p, - "mfc70d.dll", (LPCSTR)832, 0x0, VS70::mfcd_scalar_new, - "mfc70d.dll", (LPCSTR)833, 0x0, VS70::mfcd__scalar_new_dbg_4p, - "mfc70d.dll", (LPCSTR)834, 0x0, VS70::mfcd__scalar_new_dbg_3p, - "mfc70ud.dll", (LPCSTR)258, 0x0, VS70::mfcud_vector_new, - "mfc70ud.dll", (LPCSTR)259, 0x0, VS70::mfcud__vector_new_dbg_4p, - "mfc70ud.dll", (LPCSTR)260, 0x0, VS70::mfcud__vector_new_dbg_3p, - "mfc70ud.dll", (LPCSTR)833, 0x0, VS70::mfcud_scalar_new, - "mfc70ud.dll", (LPCSTR)834, 0x0, VS70::mfcud__scalar_new_dbg_4p, - "mfc70ud.dll", (LPCSTR)835, 0x0, VS70::mfcud__scalar_new_dbg_3p, - "mfc71d.dll", (LPCSTR)267, 0x0, VS71::mfcd_vector_new, - "mfc71d.dll", (LPCSTR)268, 0x0, VS71::mfcd__vector_new_dbg_4p, - "mfc71d.dll", (LPCSTR)269, 0x0, VS71::mfcd__vector_new_dbg_3p, - "mfc71d.dll", (LPCSTR)893, 0x0, VS71::mfcd_scalar_new, - "mfc71d.dll", (LPCSTR)894, 0x0, VS71::mfcd__scalar_new_dbg_4p, - "mfc71d.dll", (LPCSTR)895, 0x0, VS71::mfcd__scalar_new_dbg_3p, - "mfc71ud.dll", (LPCSTR)267, 0x0, VS71::mfcud_vector_new, - "mfc71ud.dll", (LPCSTR)268, 0x0, VS71::mfcud__vector_new_dbg_4p, - "mfc71ud.dll", (LPCSTR)269, 0x0, VS71::mfcud__vector_new_dbg_3p, - "mfc71ud.dll", (LPCSTR)893, 0x0, VS71::mfcud_scalar_new, - "mfc71ud.dll", (LPCSTR)894, 0x0, VS71::mfcud__scalar_new_dbg_4p, - "mfc71ud.dll", (LPCSTR)895, 0x0, VS71::mfcud__scalar_new_dbg_3p, - "mfc80d.dll", (LPCSTR)267, 0x0, VS80::mfcd_vector_new, - "mfc80d.dll", (LPCSTR)268, 0x0, VS80::mfcd__vector_new_dbg_4p, - "mfc80d.dll", (LPCSTR)269, 0x0, VS80::mfcd__vector_new_dbg_3p, - "mfc80d.dll", (LPCSTR)893, 0x0, VS80::mfcd_scalar_new, - "mfc80d.dll", (LPCSTR)894, 0x0, VS80::mfcd__scalar_new_dbg_4p, - "mfc80d.dll", (LPCSTR)895, 0x0, VS80::mfcd__scalar_new_dbg_3p, - "mfc80ud.dll", (LPCSTR)267, 0x0, VS80::mfcud_vector_new, - "mfc80ud.dll", (LPCSTR)268, 0x0, VS80::mfcud__vector_new_dbg_4p, - "mfc80ud.dll", (LPCSTR)269, 0x0, VS80::mfcud__vector_new_dbg_3p, - "mfc80ud.dll", (LPCSTR)893, 0x0, VS80::mfcud_scalar_new, - "mfc80ud.dll", (LPCSTR)894, 0x0, VS80::mfcud__scalar_new_dbg_4p, - "mfc80ud.dll", (LPCSTR)895, 0x0, VS80::mfcud__scalar_new_dbg_3p, - "mfc90d.dll", (LPCSTR)267, 0x0, VS90::mfcd_vector_new, - "mfc90d.dll", (LPCSTR)268, 0x0, VS90::mfcd__vector_new_dbg_4p, - "mfc90d.dll", (LPCSTR)269, 0x0, VS90::mfcd__vector_new_dbg_3p, - "mfc90d.dll", (LPCSTR)931, 0x0, VS90::mfcd_scalar_new, - "mfc90d.dll", (LPCSTR)932, 0x0, VS90::mfcd__scalar_new_dbg_4p, - "mfc90d.dll", (LPCSTR)933, 0x0, VS90::mfcd__scalar_new_dbg_3p, - "mfc90ud.dll", (LPCSTR)267, 0x0, VS90::mfcud_vector_new, - "mfc90ud.dll", (LPCSTR)268, 0x0, VS90::mfcud__vector_new_dbg_4p, - "mfc90ud.dll", (LPCSTR)269, 0x0, VS90::mfcud__vector_new_dbg_3p, - "mfc90ud.dll", (LPCSTR)935, 0x0, VS90::mfcud_scalar_new, - "mfc90ud.dll", (LPCSTR)936, 0x0, VS90::mfcud__scalar_new_dbg_4p, - "mfc90ud.dll", (LPCSTR)937, 0x0, VS90::mfcud__scalar_new_dbg_3p, - - // CRT new operators and heap APIs. - "msvcrtd.dll", "_calloc_dbg", 0x0, VS60::crtd__calloc_dbg, - "msvcrtd.dll", "_malloc_dbg", 0x0, VS60::crtd__malloc_dbg, - "msvcrtd.dll", "_realloc_dbg", 0x0, VS60::crtd__realloc_dbg, - "msvcrtd.dll", "??2@YAPAXIHPBDH@Z", 0x0, VS60::crtd__scalar_new_dbg, -// "msvcrtd.dll", "??_U@YAPAXIHPBDH@Z", 0x0, VS60::crtd__vector_new_dbg, - "msvcrtd.dll", "calloc", 0x0, VS60::crtd_calloc, - "msvcrtd.dll", "malloc", 0x0, VS60::crtd_malloc, - "msvcrtd.dll", "realloc", 0x0, VS60::crtd_realloc, - "msvcrtd.dll", "??2@YAPAXI@Z", 0x0, VS60::crtd_scalar_new, -// "msvcrtd.dll", "??_U@YAPAXI@Z", 0x0, VS60::crtd_vector_new, - "msvcr70d.dll", "_calloc_dbg", 0x0, VS70::crtd__calloc_dbg, - "msvcr70d.dll", "_malloc_dbg", 0x0, VS70::crtd__malloc_dbg, - "msvcr70d.dll", "_realloc_dbg", 0x0, VS70::crtd__realloc_dbg, - "msvcr70d.dll", "??2@YAPAXIHPBDH@Z", 0x0, VS70::crtd__scalar_new_dbg, - "msvcr70d.dll", "??_U@YAPAXIHPBDH@Z", 0x0, VS70::crtd__vector_new_dbg, - "msvcr70d.dll", "calloc", 0x0, VS70::crtd_calloc, - "msvcr70d.dll", "malloc", 0x0, VS70::crtd_malloc, - "msvcr70d.dll", "realloc", 0x0, VS70::crtd_realloc, - "msvcr70d.dll", "??2@YAPAXI@Z", 0x0, VS70::crtd_scalar_new, - "msvcr70d.dll", "??_U@YAPAXI@Z", 0x0, VS70::crtd_vector_new, - "msvcr71d.dll", "_calloc_dbg", 0x0, VS71::crtd__calloc_dbg, - "msvcr71d.dll", "_malloc_dbg", 0x0, VS71::crtd__malloc_dbg, - "msvcr71d.dll", "_realloc_dbg", 0x0, VS71::crtd__realloc_dbg, - "msvcr71d.dll", "??2@YAPAXIHPBDH@Z", 0x0, VS71::crtd__scalar_new_dbg, - "msvcr71d.dll", "??_U@YAPAXIHPBDH@Z", 0x0, VS71::crtd__vector_new_dbg, - "msvcr71d.dll", "calloc", 0x0, VS71::crtd_calloc, - "msvcr71d.dll", "malloc", 0x0, VS71::crtd_malloc, - "msvcr71d.dll", "realloc", 0x0, VS71::crtd_realloc, - "msvcr71d.dll", "??2@YAPAXI@Z", 0x0, VS71::crtd_scalar_new, - "msvcr71d.dll", "??_U@YAPAXI@Z", 0x0, VS71::crtd_vector_new, - "msvcr80d.dll", "_calloc_dbg", 0x0, VS80::crtd__calloc_dbg, - "msvcr80d.dll", "_malloc_dbg", 0x0, VS80::crtd__malloc_dbg, - "msvcr80d.dll", "_realloc_dbg", 0x0, VS80::crtd__realloc_dbg, - "msvcr80d.dll", "??2@YAPAXIHPBDH@Z", 0x0, VS80::crtd__scalar_new_dbg, - "msvcr80d.dll", "??_U@YAPAXIHPBDH@Z", 0x0, VS80::crtd__vector_new_dbg, - "msvcr80d.dll", "calloc", 0x0, VS80::crtd_calloc, - "msvcr80d.dll", "malloc", 0x0, VS80::crtd_malloc, - "msvcr80d.dll", "realloc", 0x0, VS80::crtd_realloc, - "msvcr80d.dll", "??2@YAPAXI@Z", 0x0, VS80::crtd_scalar_new, - "msvcr80d.dll", "??_U@YAPAXI@Z", 0x0, VS80::crtd_vector_new, - "msvcr90d.dll", "_calloc_dbg", 0x0, VS90::crtd__calloc_dbg, - "msvcr90d.dll", "_malloc_dbg", 0x0, VS90::crtd__malloc_dbg, - "msvcr90d.dll", "_realloc_dbg", 0x0, VS90::crtd__realloc_dbg, - "msvcr90d.dll", "??2@YAPAXIHPBDH@Z", 0x0, VS90::crtd__scalar_new_dbg, - "msvcr90d.dll", "??_U@YAPAXIHPBDH@Z", 0x0, VS90::crtd__vector_new_dbg, - "msvcr90d.dll", "calloc", 0x0, VS90::crtd_calloc, - "msvcr90d.dll", "malloc", 0x0, VS90::crtd_malloc, - "msvcr90d.dll", "realloc", 0x0, VS90::crtd_realloc, - "msvcr90d.dll", "??2@YAPAXI@Z", 0x0, VS90::crtd_scalar_new, - "msvcr90d.dll", "??_U@YAPAXI@Z", 0x0, VS90::crtd_vector_new, - - // NT APIs. - "ntdll.dll", "RtlAllocateHeap", 0x0, _RtlAllocateHeap, - "ntdll.dll", "RtlFreeHeap", 0x0, _RtlFreeHeap, - "ntdll.dll", "RtlReAllocateHeap", 0x0, _RtlReAllocateHeap, - - // COM heap APIs. - "ole32.dll", "CoGetMalloc", 0x0, _CoGetMalloc, - "ole32.dll", "CoTaskMemAlloc", 0x0, _CoTaskMemAlloc, - "ole32.dll", "CoTaskMemRealloc", 0x0, _CoTaskMemRealloc -}; - -// Constructor - Initializes private data, loads configuration options, and -// attaches Visual Leak Detector to all other modules loaded into the current -// process. -// -VisualLeakDetector::VisualLeakDetector () -{ - WCHAR bom = BOM; // Unicode byte-order mark. - HMODULE kernel32; - ModuleSet *newmodules; - HMODULE ntdll; - LPWSTR symbolpath; - - // Initialize configuration options and related private data. - _wcsnset_s(m_forcedmodulelist, MAXMODULELISTLENGTH, '\0', _TRUNCATE); - m_maxdatadump = 0xffffffff; - m_maxtraceframes = 0xffffffff; - m_options = 0x0; - m_reportfile = NULL; - wcsncpy_s(m_reportfilepath, MAX_PATH, VLD_DEFAULT_REPORT_FILE_NAME, _TRUNCATE); - m_status = 0x0; - - // Load configuration options. - configure(); - if (m_options & VLD_OPT_VLDOFF) { - report(L"Visual Leak Detector is turned off.\n"); - return; - } - - kernel32 = GetModuleHandle(L"kernel32.dll"); - ntdll = GetModuleHandle(L"ntdll.dll"); - - // Initialize global variables. - currentprocess = GetCurrentProcess(); - currentthread = GetCurrentThread(); - InitializeCriticalSection(&imagelock); - LdrLoadDll = (LdrLoadDll_t)GetProcAddress(ntdll, "LdrLoadDll"); - processheap = GetProcessHeap(); - RtlAllocateHeap = (RtlAllocateHeap_t)GetProcAddress(ntdll, "RtlAllocateHeap"); - RtlFreeHeap = (RtlFreeHeap_t)GetProcAddress(ntdll, "RtlFreeHeap"); - RtlReAllocateHeap = (RtlReAllocateHeap_t)GetProcAddress(ntdll, "RtlReAllocateHeap"); - InitializeCriticalSection(&stackwalklock); - InitializeCriticalSection(&symbollock); - vldheap = HeapCreate(0x0, 0, 0); - InitializeCriticalSection(&vldheaplock); - - // Initialize remaining private data. - m_heapmap = new HeapMap; - m_heapmap->reserve(HEAPMAPRESERVE); - m_imalloc = NULL; - m_leaksfound = 0; - m_loadedmodules = NULL; - InitializeCriticalSection(&m_loaderlock); - InitializeCriticalSection(&m_maplock); - InitializeCriticalSection(&m_moduleslock); - m_selftestfile = __FILE__; - m_selftestline = 0; - m_tlsindex = TlsAlloc(); - InitializeCriticalSection(&m_tlslock); - m_tlsset = new TlsSet; - - if (m_options & VLD_OPT_SELF_TEST) { - // Self-test mode has been enabled. Intentionally leak a small amount of - // memory so that memory leak self-checking can be verified. - if (m_options & VLD_OPT_UNICODE_REPORT) { - wcsncpy_s(new WCHAR [wcslen(SELFTESTTEXTW) + 1], wcslen(SELFTESTTEXTW) + 1, SELFTESTTEXTW, _TRUNCATE); - m_selftestline = __LINE__ - 1; - } - else { - strncpy_s(new CHAR [strlen(SELFTESTTEXTA) + 1], strlen(SELFTESTTEXTA) + 1, SELFTESTTEXTA, _TRUNCATE); - m_selftestline = __LINE__ - 1; - } - } - if (m_options & VLD_OPT_START_DISABLED) { - // Memory leak detection will initially be disabled. - m_status |= VLD_STATUS_NEVER_ENABLED; - } - if (m_options & VLD_OPT_REPORT_TO_FILE) { - // Reporting to file enabled. - if (m_options & VLD_OPT_UNICODE_REPORT) { - // Unicode data encoding has been enabled. Write the byte-order - // mark before anything else gets written to the file. Open the - // file for binary writing. - if (_wfopen_s(&m_reportfile, m_reportfilepath, L"wb") == EINVAL) { - // Couldn't open the file. - m_reportfile = NULL; - } - else { - fwrite(&bom, sizeof(WCHAR), 1, m_reportfile); - setreportencoding(unicode); - } - } - else { - // Open the file in text mode for ASCII output. - if (_wfopen_s(&m_reportfile, m_reportfilepath, L"w") == EINVAL) { - // Couldn't open the file. - m_reportfile = NULL; - } - else { - setreportencoding(ascii); - } - } - if (m_reportfile == NULL) { - report(L"WARNING: Visual Leak Detector: Couldn't open report file for writing: %s\n" - L" The report will be sent to the debugger instead.\n", m_reportfilepath); - } - else { - // Set the "report" function to write to the file. - setreportfile(m_reportfile, m_options & VLD_OPT_REPORT_TO_DEBUGGER); - } - } - if (m_options & VLD_OPT_SLOW_DEBUGGER_DUMP) { - // Insert a slight delay between messages sent to the debugger for - // output. (For working around a bug in VC6 where data sent to the - // debugger gets lost if it's sent too fast). - insertreportdelay(); - } - - // This is highly unlikely to happen, but just in case, check to be sure - // we got a valid TLS index. - if (m_tlsindex == TLS_OUT_OF_INDEXES) { - report(L"ERROR: Visual Leak Detector could not be installed because thread local" - L" storage could not be allocated."); - return; - } - - // Initialize the symbol handler. We use it for obtaining source file/line - // number information and function names for the memory leak report. - symbolpath = buildsymbolsearchpath(); - SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME); - if (!SymInitializeW(currentprocess, symbolpath, FALSE)) { - report(L"WARNING: Visual Leak Detector: The symbol handler failed to initialize (error=%lu).\n" - L" File and function names will probably not be available in call stacks.\n", GetLastError()); - } - delete [] symbolpath; - - // Patch into kernel32.dll's calls to LdrLoadDll so that VLD can - // dynamically attach to new modules loaded during runtime. - patchimport(kernel32, ntdll, "ntdll.dll", "LdrLoadDll", _LdrLoadDll); - - // Attach Visual Leak Detector to every module loaded in the process. - newmodules = new ModuleSet; - newmodules->reserve(MODULESETRESERVE); - EnumerateLoadedModulesW64(currentprocess, addloadedmodule, newmodules); - attachtoloadedmodules(newmodules); - m_loadedmodules = newmodules; - m_status |= VLD_STATUS_INSTALLED; - - report(L"Visual Leak Detector Version " VLDVERSION L" installed.\n"); - if (m_status & VLD_STATUS_FORCE_REPORT_TO_FILE) { - // The report is being forced to a file. Let the human know why. - report(L"NOTE: Visual Leak Detector: Unicode-encoded reporting has been enabled, but the\n" - L" debugger is the only selected report destination. The debugger cannot display\n" - L" Unicode characters, so the report will also be sent to a file. If no file has\n" - L" been specified, the default file name is \"" VLD_DEFAULT_REPORT_FILE_NAME L"\".\n"); - - } - reportconfig(); -} - -// Destructor - Detaches Visual Leak Detector from all modules loaded in the -// process, frees internally allocated resources, and generates the memory -// leak report. -// -VisualLeakDetector::~VisualLeakDetector () -{ - BlockMap::Iterator blockit; - BlockMap *blockmap; - size_t count; - vldblockheader_t *header; - HANDLE heap; - HeapMap::Iterator heapit; - SIZE_T internalleaks = 0; - const char *leakfile = NULL; - WCHAR leakfilew [MAX_PATH]; - int leakline = 0; - ModuleSet::Iterator moduleit; - HANDLE thread; - BOOL threadsactive= FALSE; - TlsSet::Iterator tlsit; - DWORD dwCurProcessID; - - if (m_options & VLD_OPT_VLDOFF) { - // VLD has been turned off. - return; - } - - if (m_status & VLD_STATUS_INSTALLED) { - // Detach Visual Leak Detector from all previously attached modules. - EnumerateLoadedModulesW64(currentprocess, detachfrommodule, NULL); - - dwCurProcessID = GetCurrentProcessId(); - - // See if any threads that have ever entered VLD's code are still active. - EnterCriticalSection(&m_tlslock); - for (tlsit = m_tlsset->begin(); tlsit != m_tlsset->end(); ++tlsit) { - if ((*tlsit)->threadid == GetCurrentThreadId()) { - // Don't wait for the current thread to exit. - continue; - } - - thread = OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, (*tlsit)->threadid); - if (thread == NULL) { - // Couldn't query this thread. We'll assume that it exited. - continue; // XXX should we check GetLastError()? - } - if (GetProcessIdOfThread(thread) != dwCurProcessID) { - //The thread ID has been recycled. - CloseHandle(thread); - continue; - } - while (WaitForSingleObject(thread, 10000) == WAIT_TIMEOUT) { // 10 seconds - // There is still at least one other thread running. The CRT - // will stomp it dead when it cleans up, which is not a - // graceful way for a thread to go down. Warn about this, - // and wait until the thread has exited so that we know it - // can't still be off running somewhere in VLD's code. - // - // Since we've been waiting a while, let the human know we are - // still here and alive. - threadsactive = TRUE; - report(L"Visual Leak Detector: Waiting for threads to terminate...\n"); - } - CloseHandle(thread); - } - LeaveCriticalSection(&m_tlslock); - - if (m_status & VLD_STATUS_NEVER_ENABLED) { - // Visual Leak Detector started with leak detection disabled and - // it was never enabled at runtime. A lot of good that does. - report(L"WARNING: Visual Leak Detector: Memory leak detection was never enabled.\n"); - } - else { - // Generate a memory leak report for each heap in the process. - for (heapit = m_heapmap->begin(); heapit != m_heapmap->end(); ++heapit) { - heap = (*heapit).first; - reportleaks(heap); - } - - // Show a summary. - if (m_leaksfound == 0) { - report(L"No memory leaks detected.\n"); - } - else { - report(L"Visual Leak Detector detected %lu memory leak", m_leaksfound); - report((m_leaksfound > 1) ? L"s.\n" : L".\n"); - } - } - - // Free resources used by the symbol handler. - if (!SymCleanup(currentprocess)) { - report(L"WARNING: Visual Leak Detector: The symbol handler failed to deallocate resources (error=%lu).\n", - GetLastError()); - } - - // Free internally allocated resources used by the heapmap and blockmap. - for (heapit = m_heapmap->begin(); heapit != m_heapmap->end(); ++heapit) { - blockmap = &(*heapit).second->blockmap; - for (blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { - delete (*blockit).second->callstack; - delete (*blockit).second; - } - delete blockmap; - } - delete m_heapmap; - - // Free internally allocated resources used by the loaded module set. - for (moduleit = m_loadedmodules->begin(); moduleit != m_loadedmodules->end(); ++moduleit) { - delete (*moduleit).name; - delete (*moduleit).path; - } - delete m_loadedmodules; - - // Free internally allocated resources used for thread local storage. - for (tlsit = m_tlsset->begin(); tlsit != m_tlsset->end(); ++tlsit) { - delete *tlsit; - } - delete m_tlsset; - - // Do a memory leak self-check. - header = vldblocklist; - while (header) { - // Doh! VLD still has an internally allocated block! - // This won't ever actually happen, right guys?... guys? - internalleaks++; - leakfile = header->file; - leakline = header->line; - mbstowcs_s(&count, leakfilew, MAX_PATH, leakfile, _TRUNCATE); - report(L"ERROR: Visual Leak Detector: Detected a memory leak internal to Visual Leak Detector!!\n"); - report(L"---------- Block %ld at " ADDRESSFORMAT L": %u bytes ----------\n", header->serialnumber, - VLDBLOCKDATA(header), header->size); - report(L" Call Stack:\n"); - report(L" %s (%d): Full call stack not available.\n", leakfilew, leakline); - if (m_maxdatadump != 0) { - report(L" Data:\n"); - if (m_options & VLD_OPT_UNICODE_REPORT) { - dumpmemoryw(VLDBLOCKDATA(header), (m_maxdatadump < header->size) ? m_maxdatadump : header->size); - } - else { - dumpmemorya(VLDBLOCKDATA(header), (m_maxdatadump < header->size) ? m_maxdatadump : header->size); - } - } - report(L"\n"); - header = header->next; - } - if (m_options & VLD_OPT_SELF_TEST) { - if ((internalleaks == 1) && (strcmp(leakfile, m_selftestfile) == 0) && (leakline == m_selftestline)) { - report(L"Visual Leak Detector passed the memory leak self-test.\n"); - } - else { - report(L"ERROR: Visual Leak Detector: Failed the memory leak self-test.\n"); - } - } - - if (threadsactive == TRUE) { - report(L"WARNING: Visual Leak Detector: Some threads appear to have not terminated normally.\n" - L" This could cause inaccurate leak detection results, including false positives.\n"); - } - report(L"Visual Leak Detector is now exiting.\n"); - } - else { - // VLD failed to load properly. - delete m_heapmap; - delete m_tlsset; - } - HeapDestroy(vldheap); - - DeleteCriticalSection(&imagelock); - DeleteCriticalSection(&m_loaderlock); - DeleteCriticalSection(&m_maplock); - DeleteCriticalSection(&m_moduleslock); - DeleteCriticalSection(&stackwalklock); - DeleteCriticalSection(&symbollock); - DeleteCriticalSection(&vldheaplock); - - if (m_tlsindex != TLS_OUT_OF_INDEXES) { - TlsFree(m_tlsindex); - } - - if (m_reportfile != NULL) { - fclose(m_reportfile); - } -} - - -//////////////////////////////////////////////////////////////////////////////// -// -// Private Leak Detection Functions -// -//////////////////////////////////////////////////////////////////////////////// - -// attachtoloadedmodules - Attaches VLD to all modules contained in the provided -// ModuleSet. Not all modules are in the ModuleSet will actually be included -// in leak detection. Only modules that import the global VisualLeakDetector -// class object, or those that are otherwise explicitly included in leak -// detection, will be checked for memory leaks. -// -// When VLD attaches to a module, it means that any of the imports listed in -// the import patch table which are imported by the module, will be redirected -// to VLD's designated replacements. -// -// - newmodules (IN): Pointer to a ModuleSet containing information about any -// loaded modules that need to be attached. -// -// Return Value: -// -// None. -// -VOID VisualLeakDetector::attachtoloadedmodules (ModuleSet *newmodules) -{ - size_t count; - DWORD64 modulebase; - UINT32 moduleflags; - IMAGEHLP_MODULE64 moduleimageinfo; - LPCSTR modulename; -#define MAXMODULENAME (_MAX_FNAME + _MAX_EXT) - WCHAR modulenamew [MAXMODULENAME]; - LPCSTR modulepath; - DWORD modulesize; - ModuleSet::Iterator newit; - ModuleSet::Iterator oldit; - ModuleSet *oldmodules; - BOOL refresh; - UINT tablesize = sizeof(m_patchtable) / sizeof(patchentry_t); - ModuleSet::Muterator updateit; - - // Iterate through the supplied set, until all modules have been attached. - for (newit = newmodules->begin(); newit != newmodules->end(); ++newit) { - modulebase = (DWORD64)(*newit).addrlow; - moduleflags = 0x0; - modulename = (*newit).name; - modulepath = (*newit).path; - modulesize = (DWORD)((*newit).addrhigh - (*newit).addrlow) + 1; - - refresh = FALSE; - EnterCriticalSection(&m_moduleslock); - oldmodules = m_loadedmodules; - if (oldmodules != NULL) { - // This is not the first time we have been called to attach to the - // currently loaded modules. - oldit = oldmodules->find(*newit); - if (oldit != oldmodules->end()) { - // We've seen this "new" module loaded in the process before. - moduleflags = (*oldit).flags; - LeaveCriticalSection(&m_moduleslock); - if (moduleispatched((HMODULE)modulebase, m_patchtable, tablesize)) { - // This module is already attached. Just update the module's - // flags, nothing more. - updateit = newit; - (*updateit).flags = moduleflags; - continue; - } - else { - // This module may have been attached before and has been - // detached. We'll need to try reattaching to it in case it - // was unloaded and then subsequently reloaded. - refresh = TRUE; - } - } - else { - LeaveCriticalSection(&m_moduleslock); - } - } - else { - LeaveCriticalSection(&m_moduleslock); - } - - EnterCriticalSection(&symbollock); - if ((refresh == TRUE) && (moduleflags & VLD_MODULE_SYMBOLSLOADED)) { - // Discard the previously loaded symbols, so we can refresh them. - if (SymUnloadModule64(currentprocess, modulebase) == FALSE) { - report(L"WARNING: Visual Leak Detector: Failed to unload the symbols for %s. Function names and line" - L" numbers shown in the memory leak report for %s may be inaccurate.", modulename, modulename); - } - } - - // Try to load the module's symbols. This ensures that we have loaded - // the symbols for every module that has ever been loaded into the - // process, guaranteeing the symbols' availability when generating the - // leak report. - moduleimageinfo.SizeOfStruct = sizeof(IMAGEHLP_MODULE64); - if ((SymGetModuleInfoW64(currentprocess, (DWORD64)modulebase, &moduleimageinfo) == TRUE) || - ((SymLoadModule64(currentprocess, NULL, modulepath, NULL, modulebase, modulesize) == modulebase) && - (SymGetModuleInfoW64(currentprocess, modulebase, &moduleimageinfo) == TRUE))) { - moduleflags |= VLD_MODULE_SYMBOLSLOADED; - } - LeaveCriticalSection(&symbollock); - - if (_stricmp("vld.dll", modulename) == 0) { - // What happens when a module goes through it's own portal? Bad things. - // Like infinite recursion. And ugly bald men wearing dresses. VLD - // should not, therefore, attach to itself. - continue; - } - - mbstowcs_s(&count, modulenamew, MAXMODULENAME, modulename, _TRUNCATE); - if ((findimport((HMODULE)modulebase, m_vldbase, "vld.dll", "?vld@@3VVisualLeakDetector@@A") == FALSE) && - (wcsstr(vld.m_forcedmodulelist, modulenamew) == NULL)) { - // This module does not import VLD. This means that none of the module's - // sources #included vld.h. Exclude this module from leak detection. - moduleflags |= VLD_MODULE_EXCLUDED; - } - else if (!(moduleflags & VLD_MODULE_SYMBOLSLOADED) || (moduleimageinfo.SymType == SymExport)) { - // This module is going to be included in leak detection, but complete - // symbols for this module couldn't be loaded. This means that any stack - // traces through this module may lack information, like line numbers - // and function names. - report(L"WARNING: Visual Leak Detector: A module, %s, included in memory leak detection\n" - L" does not have any debugging symbols available, or they could not be located.\n" - L" Function names and/or line numbers for this module may not be available.\n", modulename); - } - - // Update the module's flags in the "new modules" set. - updateit = newit; - (*updateit).flags = moduleflags; - - // Attach to the module. - patchmodule((HMODULE)modulebase, m_patchtable, tablesize); - } -} - -// buildsymbolsearchpath - Builds the symbol search path for the symbol handler. -// This helps the symbol handler find the symbols for the application being -// debugged. -// -// Return Value: -// -// Returns a string containing the search path. The caller is responsible for -// freeing the string. -// -LPWSTR VisualLeakDetector::buildsymbolsearchpath () -{ - WCHAR directory [_MAX_DIR]; - WCHAR drive [_MAX_DRIVE]; - LPWSTR env; - DWORD envlen; - SIZE_T index; - SIZE_T length; - HMODULE module; - LPWSTR path = new WCHAR [MAX_PATH]; - SIZE_T pos = 0; - WCHAR system [MAX_PATH]; - WCHAR windows [MAX_PATH]; - - // Oddly, the symbol handler ignores the link to the PDB embedded in the - // executable image. So, we'll manually add the location of the executable - // to the search path since that is often where the PDB will be located. - path[0] = L'\0'; - module = GetModuleHandle(NULL); - GetModuleFileName(module, path, MAX_PATH); - _wsplitpath_s(path, drive, _MAX_DRIVE, directory, _MAX_DIR, NULL, 0, NULL, 0); - wcsncpy_s(path, MAX_PATH, drive, _TRUNCATE); - strapp(&path, directory); - - // When the symbol handler is given a custom symbol search path, it will no - // longer search the default directories (working directory, system root, - // etc). But we'd like it to still search those directories, so we'll add - // them to our custom search path. - // - // Append the working directory. - strapp(&path, L";.\\"); - - // Append the Windows directory. - if (GetWindowsDirectory(windows, MAX_PATH) != 0) { - strapp(&path, L";"); - strapp(&path, windows); - } - - // Append the system directory. - if (GetSystemDirectory(system, MAX_PATH) != 0) { - strapp(&path, L";"); - strapp(&path, system); - } - - // Append %_NT_SYMBOL_PATH%. - envlen = GetEnvironmentVariable(L"_NT_SYMBOL_PATH", NULL, 0); - if (envlen != 0) { - env = new WCHAR [envlen]; - if (GetEnvironmentVariable(L"_NT_SYMBOL_PATH", env, envlen) != 0) { - strapp(&path, L";"); - strapp(&path, env); - } - delete [] env; - } - - // Append %_NT_ALT_SYMBOL_PATH%. - envlen = GetEnvironmentVariable(L"_NT_ALT_SYMBOL_PATH", NULL, 0); - if (envlen != 0) { - env = new WCHAR [envlen]; - if (GetEnvironmentVariable(L"_NT_ALT_SYMBOL_PATH", env, envlen) != 0) { - strapp(&path, L";"); - strapp(&path, env); - } - delete [] env; - } - - // Remove any quotes from the path. The symbol handler doesn't like them. - pos = 0; - length = wcslen(path); - while (pos < length) { - if (path[pos] == L'\"') { - for (index = pos; index < length; index++) { - path[index] = path[index + 1]; - } - } - pos++; - } - - return path; -} - -// configure - Configures VLD using values read from the vld.ini file. -// -// Return Value: -// -// None. -// -VOID VisualLeakDetector::configure () -{ -#define BSIZE 64 - WCHAR buffer [BSIZE]; - WCHAR filename [MAX_PATH]; - WCHAR inipath [MAX_PATH]; - BOOL keyopen = FALSE; - DWORD length; - HKEY productkey; - LONG regstatus; - struct _stat s; - DWORD valuetype; - - if (_wstat(L".\\vld.ini", &s) == 0) { - // Found a copy of vld.ini in the working directory. Use it. - wcsncpy_s(inipath, MAX_PATH, L".\\vld.ini", _TRUNCATE); - } - else { - // Get the location of the vld.ini file from the registry. - regstatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, VLDREGKEYPRODUCT, 0, KEY_QUERY_VALUE, &productkey); - if (regstatus == ERROR_SUCCESS) { - keyopen = TRUE; - regstatus = RegQueryValueEx(productkey, L"IniFile", NULL, &valuetype, (LPBYTE)&inipath, &length); - } - if (keyopen) { - RegCloseKey(productkey); - } - if ((regstatus != ERROR_SUCCESS) || (_wstat(inipath, &s) != 0)) { - // The location of vld.ini could not be read from the registry. As a - // last resort, look in the Windows directory. - wcsncpy_s(inipath, MAX_PATH, L"vld.ini", _TRUNCATE); - } - } - - // Read the boolean options. - GetPrivateProfileString(L"Options", L"VLD", L"on", buffer, BSIZE, inipath); - if (strtobool(buffer) == FALSE) { - m_options |= VLD_OPT_VLDOFF; - return; - } - - GetPrivateProfileString(L"Options", L"AggregateDuplicates", L"", buffer, BSIZE, inipath); - if (strtobool(buffer) == TRUE) { - m_options |= VLD_OPT_AGGREGATE_DUPLICATES; - } - - GetPrivateProfileString(L"Options", L"SelfTest", L"", buffer, BSIZE, inipath); - if (strtobool(buffer) == TRUE) { - m_options |= VLD_OPT_SELF_TEST; - } - - GetPrivateProfileString(L"Options", L"SlowDebuggerDump", L"", buffer, BSIZE, inipath); - if (strtobool(buffer) == TRUE) { - m_options |= VLD_OPT_SLOW_DEBUGGER_DUMP; - } - - GetPrivateProfileString(L"Options", L"StartDisabled", L"", buffer, BSIZE, inipath); - if (strtobool(buffer) == TRUE) { - m_options |= VLD_OPT_START_DISABLED; - } - - GetPrivateProfileString(L"Options", L"TraceInternalFrames", L"", buffer, BSIZE, inipath); - if (strtobool(buffer) == TRUE) { - m_options |= VLD_OPT_TRACE_INTERNAL_FRAMES; - } - - // Read the integer configuration options. - m_maxdatadump = GetPrivateProfileInt(L"Options", L"MaxDataDump", VLD_DEFAULT_MAX_DATA_DUMP, inipath); - m_maxtraceframes = GetPrivateProfileInt(L"Options", L"MaxTraceFrames", VLD_DEFAULT_MAX_TRACE_FRAMES, inipath); - if (m_maxtraceframes < 1) { - m_maxtraceframes = VLD_DEFAULT_MAX_TRACE_FRAMES; - } - - // Read the force-include module list. - GetPrivateProfileString(L"Options", L"ForceIncludeModules", L"", m_forcedmodulelist, MAXMODULELISTLENGTH, inipath); - _wcslwr_s(m_forcedmodulelist, MAXMODULELISTLENGTH); - - // Read the report destination (debugger, file, or both). - GetPrivateProfileString(L"Options", L"ReportFile", L"", filename, MAX_PATH, inipath); - if (wcslen(filename) == 0) { - wcsncpy_s(filename, MAX_PATH, VLD_DEFAULT_REPORT_FILE_NAME, _TRUNCATE); - } - _wfullpath(m_reportfilepath, filename, MAX_PATH); - GetPrivateProfileString(L"Options", L"ReportTo", L"", buffer, BSIZE, inipath); - if (_wcsicmp(buffer, L"both") == 0) { - m_options |= (VLD_OPT_REPORT_TO_DEBUGGER | VLD_OPT_REPORT_TO_FILE); - } - else if (_wcsicmp(buffer, L"file") == 0) { - m_options |= VLD_OPT_REPORT_TO_FILE; - } - else { - m_options |= VLD_OPT_REPORT_TO_DEBUGGER; - } - - // Read the report file encoding (ascii or unicode). - GetPrivateProfileString(L"Options", L"ReportEncoding", L"", buffer, BSIZE, inipath); - if (_wcsicmp(buffer, L"unicode") == 0) { - m_options |= VLD_OPT_UNICODE_REPORT; - } - if ((m_options & VLD_OPT_UNICODE_REPORT) && !(m_options & VLD_OPT_REPORT_TO_FILE)) { - // If Unicode report encoding is enabled, then the report needs to be - // sent to a file because the debugger will not display Unicode - // characters, it will display question marks in their place instead. - m_options |= VLD_OPT_REPORT_TO_FILE; - m_status |= VLD_STATUS_FORCE_REPORT_TO_FILE; - } - - // Read the stack walking method. - GetPrivateProfileString(L"Options", L"StackWalkMethod", L"", buffer, BSIZE, inipath); - if (_wcsicmp(buffer, L"safe") == 0) { - m_options |= VLD_OPT_SAFE_STACK_WALK; - } -} - -// enabled - Determines if memory leak detection is enabled for the current -// thread. -// -// Return Value: -// -// Returns true if Visual Leak Detector is enabled for the current thread. -// Otherwise, returns false. -// -BOOL VisualLeakDetector::enabled () -{ - tls_t *tls = vld.gettls(); - - if (!(m_status & VLD_STATUS_INSTALLED)) { - // Memory leak detection is not yet enabled because VLD is still - // initializing. - return FALSE; - } - - if (!(tls->flags & VLD_TLS_DISABLED) && !(tls->flags & VLD_TLS_ENABLED)) { - // The enabled/disabled state for the current thread has not been - // initialized yet. Use the default state. - if (m_options & VLD_OPT_START_DISABLED) { - tls->flags |= VLD_TLS_DISABLED; - } - else { - tls->flags |= VLD_TLS_ENABLED; - } - } - - return ((tls->flags & VLD_TLS_ENABLED) != 0); -} - -// eraseduplicates - Erases, from the block maps, blocks that appear to be -// duplicate leaks of an already identified leak. -// -// - element (IN): BlockMap Iterator referencing the block of which to search -// for duplicates. -// -// Return Value: -// -// Returns the number of duplicate blocks erased from the block map. -// -SIZE_T VisualLeakDetector::eraseduplicates (const BlockMap::Iterator &element) -{ - BlockMap::Iterator blockit; - BlockMap *blockmap; - blockinfo_t *elementinfo; - SIZE_T erased = 0; - HeapMap::Iterator heapit; - blockinfo_t *info; - BlockMap::Iterator previt; - - elementinfo = (*element).second; - - // Iteratate through all block maps, looking for blocks with the same size - // and callstack as the specified element. - for (heapit = m_heapmap->begin(); heapit != m_heapmap->end(); ++heapit) { - blockmap = &(*heapit).second->blockmap; - for (blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { - if (blockit == element) { - // Don't delete the element of which we are searching for - // duplicates. - continue; - } - info = (*blockit).second; - if ((info->size == elementinfo->size) && (*(info->callstack) == *(elementinfo->callstack))) { - // Found a duplicate. Erase it. - delete info->callstack; - delete info; - previt = blockit - 1; - blockmap->erase(blockit); - blockit = previt; - erased++; - } - } - } - - return erased; -} - -// gettls - Obtains the thread local storage structure for the calling thread. -// -// Return Value: -// -// Returns a pointer to the thread local storage structure. (This function -// always succeeds). -// -tls_t* VisualLeakDetector::gettls () -{ - tls_t *tls; - - // Get the pointer to this thread's thread local storage structure. - tls = (tls_t*)TlsGetValue(m_tlsindex); - assert(GetLastError() == ERROR_SUCCESS); - - if (tls == NULL) { - // This thread's thread local storage structure has not been allocated. - tls = new tls_t; - TlsSetValue(m_tlsindex, tls); - tls->addrfp = 0x0; - tls->flags = 0x0; - tls->threadid = GetCurrentThreadId(); - - // Add this thread's TLS to the TlsSet. - EnterCriticalSection(&m_tlslock); - m_tlsset->insert(tls); - LeaveCriticalSection(&m_tlslock); - } - - return tls; -} - -// mapblock - Tracks memory allocations. Information about allocated blocks is -// collected and then the block is mapped to this information. -// -// - heap (IN): Handle to the heap from which the block has been allocated. -// -// - mem (IN): Pointer to the memory block being allocated. -// -// - size (IN): Size, in bytes, of the memory block being allocated. -// -// - framepointer (IN): Framepointer at the time this allocation first entered -// VLD's code. This is used from determining the starting point for the -// stack trace. -// -// - crtalloc (IN): Should be set to TRUE if this allocation is a CRT memory -// block. Otherwise should be FALSE. -// -// Return Value: -// -// None. -// -VOID VisualLeakDetector::mapblock (HANDLE heap, LPCVOID mem, SIZE_T size, SIZE_T framepointer, BOOL crtalloc) -{ - blockinfo_t *blockinfo; - BlockMap::Iterator blockit; - BlockMap *blockmap; - HeapMap::Iterator heapit; - static SIZE_T serialnumber = 0; - - // Record the block's information. - blockinfo = new blockinfo_t; - if (m_options & VLD_OPT_SAFE_STACK_WALK) { - blockinfo->callstack = new SafeCallStack; - } - else { - blockinfo->callstack = new FastCallStack; - } - if (m_options & VLD_OPT_TRACE_INTERNAL_FRAMES) { - // Passing NULL for the frame pointer argument will force the stack - // trace to begin at the current frame. - blockinfo->callstack->getstacktrace(m_maxtraceframes, NULL); - } - else { - // Start the stack trace at the call that first entered VLD's code. - blockinfo->callstack->getstacktrace(m_maxtraceframes, (SIZE_T*)framepointer); - } - blockinfo->serialnumber = serialnumber++; - blockinfo->size = size; - - // Insert the block's information into the block map. - EnterCriticalSection(&m_maplock); - heapit = m_heapmap->find(heap); - if (heapit == m_heapmap->end()) { - // We haven't mapped this heap to a block map yet. Do it now. - mapheap(heap); - heapit = m_heapmap->find(heap); - assert(heapit != m_heapmap->end()); - } - if (crtalloc == TRUE) { - // The heap that this block was allocated from is a CRT heap. - (*heapit).second->flags |= VLD_HEAP_CRT; - } - blockmap = &(*heapit).second->blockmap; - blockit = blockmap->insert(mem, blockinfo); - if (blockit == blockmap->end()) { - // A block with this address has already been allocated. The - // previously allocated block must have been freed (probably by some - // mechanism unknown to VLD), or the heap wouldn't have allocated it - // again. Replace the previously allocated info with the new info. - blockit = blockmap->find(mem); - delete (*blockit).second->callstack; - delete (*blockit).second; - blockmap->erase(blockit); - blockmap->insert(mem, blockinfo); - } - LeaveCriticalSection(&m_maplock); -} - -// mapheap - Tracks heap creation. Creates a block map for tracking individual -// allocations from the newly created heap and then maps the heap to this -// block map. -// -// - heap (IN): Handle to the newly created heap. -// -// Return Value: -// -// None. -// -VOID VisualLeakDetector::mapheap (HANDLE heap) -{ - heapinfo_t *heapinfo; - HeapMap::Iterator heapit; - - // Create a new block map for this heap and insert it into the heap map. - heapinfo = new heapinfo_t; - heapinfo->blockmap.reserve(BLOCKMAPRESERVE); - heapinfo->flags = 0x0; - EnterCriticalSection(&m_maplock); - heapit = m_heapmap->insert(heap, heapinfo); - if (heapit == m_heapmap->end()) { - // Somehow this heap has been created twice without being destroyed, - // or at least it was destroyed without VLD's knowledge. Unmap the heap - // from the existing heapinfo, and remap it to the new one. - report(L"WARNING: Visual Leak Detector detected a duplicate heap (" ADDRESSFORMAT L").\n", heap); - heapit = m_heapmap->find(heap); - unmapheap((*heapit).first); - m_heapmap->insert(heap, heapinfo); - } - LeaveCriticalSection(&m_maplock); -} - -// remapblock - Tracks reallocations. Unmaps a block from its previously -// collected information and remaps it to updated information. -// -// Note: If the block itself remains at the same address, then the block's -// information can simply be updated rather than having to actually erase and -// reinsert the block. -// -// - heap (IN): Handle to the heap from which the memory is being reallocated. -// -// - mem (IN): Pointer to the memory block being reallocated. -// -// - newmem (IN): Pointer to the memory block being returned to the caller -// that requested the reallocation. This pointer may or may not be the same -// as the original memory block (as pointed to by "mem"). -// -// - size (IN): Size, in bytes, of the new memory block. -// -// - framepointer (IN): The frame pointer at which this reallocation entered -// VLD's code. Used for determining the starting point of the stack trace. -// -// - crtalloc (IN): Should be set to TRUE if this reallocation is for a CRT -// memory block. Otherwise should be set to FALSE. -// -// Return Value: -// -// None. -// -VOID VisualLeakDetector::remapblock (HANDLE heap, LPCVOID mem, LPCVOID newmem, SIZE_T size, SIZE_T framepointer, - BOOL crtalloc) -{ - BlockMap::Iterator blockit; - BlockMap *blockmap; - HeapMap::Iterator heapit; - blockinfo_t *info; - - if (newmem != mem) { - // The block was not reallocated in-place. Instead the old block was - // freed and a new block allocated to satisfy the new size. - unmapblock(heap, mem); - mapblock(heap, newmem, size, framepointer, crtalloc); - return; - } - - // The block was reallocated in-place. Find the existing blockinfo_t - // entry in the block map and update it with the new callstack and size. - EnterCriticalSection(&m_maplock); - heapit = m_heapmap->find(heap); - if (heapit == m_heapmap->end()) { - // We haven't mapped this heap to a block map yet. Obviously the - // block has also not been mapped to a blockinfo_t entry yet either, - // so treat this reallocation as a brand-new allocation (this will - // also map the heap to a new block map). - mapblock(heap, newmem, size, framepointer, crtalloc); - LeaveCriticalSection(&m_maplock); - return; - } - - // Find the block's blockinfo_t structure so that we can update it. - blockmap = &(*heapit).second->blockmap; - blockit = blockmap->find(mem); - if (blockit == blockmap->end()) { - // The block hasn't been mapped to a blockinfo_t entry yet. - // Treat this reallocation as a new allocation. - mapblock(heap, newmem, size, framepointer, crtalloc); - LeaveCriticalSection(&m_maplock); - return; - } - - // Found the blockinfo_t entry for this block. Update it with - // a new callstack and new size. - info = (*blockit).second; - info->callstack->clear(); - if (crtalloc) { - // The heap that this block was allocated from is a CRT heap. - (*heapit).second->flags |= VLD_HEAP_CRT; - } - LeaveCriticalSection(&m_maplock); - - // Update the block's callstack and size. - if (m_options & VLD_OPT_TRACE_INTERNAL_FRAMES) { - // Passing NULL for the frame pointer argument will force - // the stack trace to begin at the current frame. - info->callstack->getstacktrace(m_maxtraceframes, NULL); - } - else { - // Start the stack trace at the call that first entered - // VLD's code. - info->callstack->getstacktrace(m_maxtraceframes, (SIZE_T*)framepointer); - } - info->size = size; -} - -// reportconfig - Generates a brief report summarizing Visual Leak Detector's -// configuration, as loaded from the vld.ini file. -// -// Return Value: -// -// None. -// -VOID VisualLeakDetector::reportconfig () -{ - if (m_options & VLD_OPT_AGGREGATE_DUPLICATES) { - report(L" Aggregating duplicate leaks.\n"); - } - if (wcslen(m_forcedmodulelist) != 0) { - report(L" Forcing inclusion of these modules in leak detection: %s\n", m_forcedmodulelist); - } - if (m_maxdatadump != VLD_DEFAULT_MAX_DATA_DUMP) { - if (m_maxdatadump == 0) { - report(L" Suppressing data dumps.\n"); - } - else { - report(L" Limiting data dumps to %lu bytes.\n", m_maxdatadump); - } - } - if (m_maxtraceframes != VLD_DEFAULT_MAX_TRACE_FRAMES) { - report(L" Limiting stack traces to %u frames.\n", m_maxtraceframes); - } - if (m_options & VLD_OPT_UNICODE_REPORT) { - report(L" Generating a Unicode (UTF-16) encoded report.\n"); - } - if (m_options & VLD_OPT_REPORT_TO_FILE) { - if (m_options & VLD_OPT_REPORT_TO_DEBUGGER) { - report(L" Outputting the report to the debugger and to %s\n", m_reportfilepath); - } - else { - report(L" Outputting the report to %s\n", m_reportfilepath); - } - } - if (m_options & VLD_OPT_SLOW_DEBUGGER_DUMP) { - report(L" Outputting the report to the debugger at a slower rate.\n"); - } - if (m_options & VLD_OPT_SAFE_STACK_WALK) { - report(L" Using the \"safe\" (but slow) stack walking method.\n"); - } - if (m_options & VLD_OPT_SELF_TEST) { - report(L" Perfoming a memory leak self-test.\n"); - } - if (m_options & VLD_OPT_START_DISABLED) { - report(L" Starting with memory leak detection disabled.\n"); - } - if (m_options & VLD_OPT_TRACE_INTERNAL_FRAMES) { - report(L" Including heap and VLD internal frames in stack traces.\n"); - } -} - -// reportleaks - Generates a memory leak report for the specified heap. -// -// - heap (IN): Handle to the heap for which to generate a memory leak -// report. -// -// Return Value: -// -// None. -// -VOID VisualLeakDetector::reportleaks (HANDLE heap) -{ - LPCVOID address; - LPCVOID block; - BlockMap::Iterator blockit; - BlockMap *blockmap; - crtdbgblockheader_t *crtheader; - SIZE_T duplicates; - heapinfo_t *heapinfo; - HeapMap::Iterator heapit; - blockinfo_t *info; - SIZE_T size; - - // Find the heap's information (blockmap, etc). - EnterCriticalSection(&m_maplock); - heapit = m_heapmap->find(heap); - if (heapit == m_heapmap->end()) { - // Nothing is allocated from this heap. No leaks. - LeaveCriticalSection(&m_maplock); - return; - } - - heapinfo = (*heapit).second; - blockmap = &heapinfo->blockmap; - for (blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { - // Found a block which is still in the BlockMap. We've identified a - // potential memory leak. - block = (*blockit).first; - info = (*blockit).second; - address = block; - size = info->size; - if (heapinfo->flags & VLD_HEAP_CRT) { - // This block is allocated to a CRT heap, so the block has a CRT - // memory block header prepended to it. - crtheader = (crtdbgblockheader_t*)block; - if (CRT_USE_TYPE(crtheader->use) == CRT_USE_INTERNAL) { - // This block is marked as being used internally by the CRT. - // The CRT will free the block after VLD is destroyed. - continue; - } - // The CRT header is more or less transparent to the user, so - // the information about the contained block will probably be - // more useful to the user. Accordingly, that's the information - // we'll include in the report. - address = CRTDBGBLOCKDATA(block); - size = crtheader->size; - } - // It looks like a real memory leak. - if (m_leaksfound == 0) { - report(L"WARNING: Visual Leak Detector detected memory leaks!\n"); - } - m_leaksfound++; - report(L"---------- Block %ld at " ADDRESSFORMAT L": %u bytes ----------\n", info->serialnumber, address, size); - if (m_options & VLD_OPT_AGGREGATE_DUPLICATES) { - // Aggregate all other leaks which are duplicates of this one - // under this same heading, to cut down on clutter. - duplicates = eraseduplicates(blockit); - if (duplicates) { - report(L"A total of %lu leaks match this size and call stack. Showing only the first one.\n", - duplicates + 1); - m_leaksfound += duplicates; - } - } - // Dump the call stack. - report(L" Call Stack:\n"); - info->callstack->dump(m_options & VLD_OPT_TRACE_INTERNAL_FRAMES); - // Dump the data in the user data section of the memory block. - if (m_maxdatadump != 0) { - report(L" Data:\n"); - if (m_options & VLD_OPT_UNICODE_REPORT) { - dumpmemoryw(address, (m_maxdatadump < size) ? m_maxdatadump : size); - } - else { - dumpmemorya(address, (m_maxdatadump < size) ? m_maxdatadump : size); - } - } - report(L"\n"); - } - - LeaveCriticalSection(&m_maplock); -} - -// unmapblock - Tracks memory blocks that are freed. Unmaps the specified block -// from the block's information, relinquishing internally allocated resources. -// -// - heap (IN): Handle to the heap to which this block is being freed. -// -// - mem (IN): Pointer to the memory block being freed. -// -// Return Value: -// -// None. -// -VOID VisualLeakDetector::unmapblock (HANDLE heap, LPCVOID mem) -{ - BlockMap::Iterator blockit; - BlockMap *blockmap; - HeapMap::Iterator heapit; - blockinfo_t *info; - - // Find this heap's block map. - EnterCriticalSection(&m_maplock); - heapit = m_heapmap->find(heap); - if (heapit == m_heapmap->end()) { - // We don't have a block map for this heap. We must not have monitored - // this allocation (probably happened before VLD was initialized). - LeaveCriticalSection(&m_maplock); - return; - } - - // Find this block in the block map. - blockmap = &(*heapit).second->blockmap; - blockit = blockmap->find(mem); - if (blockit == blockmap->end()) { - // This block is not in the block map. We must not have monitored this - // allocation (probably happened before VLD was initialized). - LeaveCriticalSection(&m_maplock); - return; - } - - // Free the blockinfo_t structure and erase it from the block map. - info = (*blockit).second; - delete info->callstack; - delete info; - blockmap->erase(blockit); - LeaveCriticalSection(&m_maplock); -} - -// unmapheap - Tracks heap destruction. Unmaps the specified heap from its block -// map. The block map is cleared and deleted, relinquishing internally -// allocated resources. -// -// - heap (IN): Handle to the heap which is being destroyed. -// -// Return Value: -// -// None. -// -VOID VisualLeakDetector::unmapheap (HANDLE heap) -{ - BlockMap::Iterator blockit; - BlockMap *blockmap; - heapinfo_t *heapinfo; - HeapMap::Iterator heapit; - - // Find this heap's block map. - EnterCriticalSection(&m_maplock); - heapit = m_heapmap->find(heap); - if (heapit == m_heapmap->end()) { - // This heap hasn't been mapped. We must not have monitored this heap's - // creation (probably happened before VLD was initialized). - LeaveCriticalSection(&m_maplock); - return; - } - - // Free all of the blockinfo_t structures stored in the block map. - heapinfo = (*heapit).second; - blockmap = &heapinfo->blockmap; - for (blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { - delete (*blockit).second->callstack; - delete (*blockit).second; - } - delete heapinfo; - - // Remove this heap's block map from the heap map. - m_heapmap->erase(heapit); - LeaveCriticalSection(&m_maplock); -} - - -//////////////////////////////////////////////////////////////////////////////// -// -// Static Leak Detection Functions (Callbacks) -// -//////////////////////////////////////////////////////////////////////////////// - -// addloadedmodule - Callback function for EnumerateLoadedModules64. This -// function records information about every module loaded in the process, -// each time adding the module's information to the provided ModuleSet (the -// "context" parameter). -// -// When EnumerateLoadedModules64 has finished calling this function for each -// loaded module, then the resulting ModuleSet can be used at any time to get -// information about any modules loaded into the process. -// -// - modulepath (IN): The fully qualified path from where the module was -// loaded. -// -// - modulebase (IN): The base address at which the module has been loaded. -// -// - modulesize (IN): The size, in bytes, of the loaded module. -// -// - context (IN): Pointer to the ModuleSet to which information about each -// module is to be added. -// -// Return Value: -// -// Always returns TRUE, which tells EnumerateLoadedModules64 to continue -// enumerating. -// -BOOL VisualLeakDetector::addloadedmodule (PCWSTR modulepath, DWORD64 modulebase, ULONG modulesize, PVOID context) -{ - size_t count; - patchentry_t *entry; - CHAR extension [_MAX_EXT]; - CHAR filename [_MAX_FNAME]; - UINT index; - moduleinfo_t moduleinfo; - LPSTR modulenamea; - LPSTR modulepatha; - ModuleSet* newmodules = (ModuleSet*)context; - SIZE_T size; - UINT tablesize = sizeof(m_patchtable) / sizeof(patchentry_t); - - // Convert the module path to ASCII. - size = wcslen(modulepath) + 1; - modulepatha = new CHAR [size]; - wcstombs_s(&count, modulepatha, size, modulepath, _TRUNCATE); - - // Extract just the filename and extension from the module path. - _splitpath_s(modulepatha, NULL, 0, NULL, 0, filename, _MAX_FNAME, extension, _MAX_EXT); - size = strlen(filename) + strlen(extension) + 1; - modulenamea = new CHAR [size]; - strncpy_s(modulenamea, size, filename, _TRUNCATE); - strncat_s(modulenamea, size, extension, _TRUNCATE); - _strlwr_s(modulenamea, size); - - if (_stricmp(modulenamea, "vld.dll") == 0) { - // Record Visual Leak Detector's own base address. - vld.m_vldbase = (HMODULE)modulebase; - } - else { - // See if this is a module listed in the patch table. If it is, update - // the corresponding patch table entries' module base address. - for (index = 0; index < tablesize; index++) { - entry = &m_patchtable[index]; - if (_stricmp(entry->exportmodulename, modulenamea) == 0) { - entry->modulebase = (SIZE_T)modulebase; - } - } - } - - // Record the module's information and store it in the set. - moduleinfo.addrlow = (SIZE_T)modulebase; - moduleinfo.addrhigh = (SIZE_T)(modulebase + modulesize) - 1; - moduleinfo.flags = 0x0; - moduleinfo.name = modulenamea; - moduleinfo.path = modulepatha; - newmodules->insert(moduleinfo); - - return TRUE; -} - -// detachfrommodule - Callback function for EnumerateLoadedModules64 that -// detaches Visual Leak Detector from the specified module. If the specified -// module has not previously been attached to, then calling this function will -// not actually result in any changes. -// -// - modulepath (IN): String containing the name, which may include a path, of -// the module to detach from (ignored). -// -// - modulebase (IN): Base address of the module. -// -// - modulesize (IN): Total size of the module (ignored). -// -// - context (IN): User-supplied context (ignored). -// -// Return Value: -// -// Always returns TRUE. -// -BOOL VisualLeakDetector::detachfrommodule (PCWSTR /*modulepath*/, DWORD64 modulebase, ULONG /*modulesize*/, - PVOID /*context*/) -{ - UINT tablesize = sizeof(m_patchtable) / sizeof(patchentry_t); - - restoremodule((HMODULE)modulebase, m_patchtable, tablesize); - - return TRUE; -} - - -//////////////////////////////////////////////////////////////////////////////// -// -// Standard CRT and MFC IAT Replacement Functions -// -// The addresses of these functions are not actually directly patched into the -// import address tables, but these functions do get indirectly called by the -// patch functions that are placed in the import address tables. -// -//////////////////////////////////////////////////////////////////////////////// - -// _calloc - This function is just a wrapper around the real calloc that sets -// appropriate flags to be consulted when the memory is actually allocated by -// RtlAllocateHeap. -// -// - pcalloc (IN): Pointer to the particular calloc implementation to call. -// -// - fp (IN): Frame pointer from the call that initiated this allocation. -// -// - num (IN): The number of blocks, of size 'size', to be allocated. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// Return Value: -// -// Returns the value returned from the specified calloc. -// -void* VisualLeakDetector::_calloc (calloc_t pcalloc, - SIZE_T fp, - size_t num, - size_t size) -{ - void *block; - tls_t *tls = vld.gettls(); - - // malloc is a CRT function and allocates from the CRT heap. - tls->flags |= VLD_TLS_CRTALLOC; - - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - tls->addrfp = fp; - } - - // Do the allocation. The block will be mapped by _RtlAllocateHeap. - block = pcalloc(num, size); - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -// _malloc - This function is just a wrapper around the real malloc that sets -// appropriate flags to be consulted when the memory is actually allocated by -// RtlAllocateHeap. -// -// - pmalloc (IN): Pointer to the particular malloc implementation to call. -// -// - fp (IN): Frame pointer from the call that initiated this allocation. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// Return Value: -// -// Returns the value returned from the specified malloc. -// -void *VisualLeakDetector::_malloc (malloc_t pmalloc, SIZE_T fp, size_t size) -{ - void *block; - tls_t *tls = vld.gettls(); - - // malloc is a CRT function and allocates from the CRT heap. - tls->flags |= VLD_TLS_CRTALLOC; - - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - tls->addrfp = fp; - } - - // Do the allocation. The block will be mapped by _RtlAllocateHeap. - block = pmalloc(size); - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -// _new - This function is just a wrapper around the real CRT and MFC new -// operators that sets appropriate flags to be consulted when the memory is -// actually allocated by RtlAllocateHeap. -// -// - pnew (IN): Pointer to the particular new implementation to call. -// -// - fp (IN): Frame pointer from the call that initiated this allocation. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// Return Value: -// -// Returns the value returned by the specified CRT new operator. -// -void* VisualLeakDetector::_new (new_t pnew, SIZE_T fp, size_t size) -{ - void *block; - tls_t *tls = vld.gettls(); - - // The new operator is a CRT function and allocates from the CRT heap. - tls->flags |= VLD_TLS_CRTALLOC; - - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - tls->addrfp = fp; - } - - // Do the allocation. The block will be mapped by _RtlAllocateHeap. - block = pnew(size); - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -// _realloc - This function is just a wrapper around the real realloc that sets -// appropriate flags to be consulted when the memory is actually allocated by -// RtlAllocateHeap. -// -// - prealloc (IN): Pointer to the particular realloc implementation to call. -// -// - fp (IN): Frame pointer from the call that initiated this allocation. -// -// - mem (IN): Pointer to the memory block to reallocate. -// -// - size (IN): Size of the memory block to reallocate. -// -// Return Value: -// -// Returns the value returned from the specified realloc. -// -void* VisualLeakDetector::_realloc (realloc_t prealloc, - SIZE_T fp, - void *mem, - size_t size) -{ - void *block; - tls_t *tls = vld.gettls(); - - // realloc is a CRT function and allocates from the CRT heap. - tls->flags |= VLD_TLS_CRTALLOC; - - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - tls->addrfp = fp; - } - - // Do the allocation. The block will be mapped by _RtlReAllocateHeap. - block = prealloc(mem, size); - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -//////////////////////////////////////////////////////////////////////////////// -// -// Debug CRT and MFC IAT Replacement Functions -// -// The addresses of these functions are not actually directly patched into the -// import address tables, but these functions do get indirectly called by the -// patch functions that are placed in the import address tables. -// -//////////////////////////////////////////////////////////////////////////////// - -// __calloc_dbg - This function is just a wrapper around the real _calloc_dbg -// that sets appropriate flags to be consulted when the memory is actually -// allocated by RtlAllocateHeap. -// -// - p_calloc_dbg: Pointer to the particular _calloc_dbg implementation to -// call. -// -// - fp (IN): Frame pointer from the call that initiated this allocation. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - type (IN): The CRT "use type" of the block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the specified _calloc_dbg. -// -void* VisualLeakDetector::__calloc_dbg (_calloc_dbg_t p_calloc_dbg, - SIZE_T fp, - size_t num, - size_t size, - int type, - char const *file, - int line) -{ - void *block; - tls_t *tls = vld.gettls(); - - // _malloc_dbg is a CRT function and allocates from the CRT heap. - tls->flags |= VLD_TLS_CRTALLOC; - - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - tls->addrfp = fp; - } - - // Do the allocation. The block will be mapped by _RtlAllocateHeap. - block = p_calloc_dbg(num, size, type, file, line); - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -// __malloc_dbg - This function is just a wrapper around the real _malloc_dbg -// that sets appropriate flags to be consulted when the memory is actually -// allocated by RtlAllocateHeap. -// -// - p_malloc_dbg (IN): Pointer to the particular _malloc_dbg implementation to -// call. -// -// - fp (IN): Frame pointer from the call that initiated this allocation. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - type (IN): The CRT "use type" of the block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the specified _malloc_dbg. -// -void* VisualLeakDetector::__malloc_dbg (_malloc_dbg_t p_malloc_dbg, - SIZE_T fp, - size_t size, - int type, - char const *file, - int line) -{ - void *block; - tls_t *tls = vld.gettls(); - - // _malloc_dbg is a CRT function and allocates from the CRT heap. - tls->flags |= VLD_TLS_CRTALLOC; - - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - tls->addrfp = fp; - } - - // Do the allocation. The block will be mapped by _RtlAllocateHeap. - block = p_malloc_dbg(size, type, file, line); - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -// new_dbg_crt - This function is just a wrapper around the real CRT debug new -// operators that sets appropriate flags to be consulted when the memory is -// actually allocated by RtlAllocateHeap. -// -// - pnew_dbg_crt (IN): Pointer to the particular CRT new operator -// implementation to call. -// -// - fp (IN): Frame pointer from the call that initiated this allocation. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - type (IN): The CRT "use type" of the block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the specified CRT debug new operator. -// -void* VisualLeakDetector::new_dbg_crt (new_dbg_crt_t pnew_dbg_crt, - SIZE_T fp, - size_t size, - int type, - char const *file, - int line) -{ - void *block; - tls_t *tls = vld.gettls(); - - // The debug new operator is a CRT function and allocates from the CRT heap. - tls->flags |= VLD_TLS_CRTALLOC; - - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - tls->addrfp = fp; - } - - // Do the allocation. The block will be mapped by _RtlAllocateHeap. - block = pnew_dbg_crt(size, type, file, line); - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -// new_dbg_mfc - This function is just a wrapper around the real MFC debug new -// operators that sets appropriate flags to be consulted when the memory is -// actually allocated by RtlAllocateHeap. -// -// - pnew_dbg (IN): Pointer to the particular CRT new operator -// implementation to call. -// -// - fp (IN): Frame pointer from the call that initiated this allocation. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - type (IN): The CRT "use type" of the block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the specified CRT debug new operator. -// -void* VisualLeakDetector::new_dbg_mfc (new_dbg_crt_t pnew_dbg, - SIZE_T fp, - size_t size, - int type, - char const *file, - int line) -{ - void *block; - tls_t *tls = vld.gettls(); - - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - tls->addrfp = fp; - } - - // Do the allocation. The block will be mapped by _RtlAllocateHeap. - block = pnew_dbg(size, type, file, line); - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -// new_dbg_mfc - This function is just a wrapper around the real MFC debug new -// operators that sets appropriate flags to be consulted when the memory is -// actually allocated by RtlAllocateHeap. -// -// - pnew_dbg_mfc (IN): Pointer to the particular MFC new operator -// implementation to call. -// -// - fp (IN): Frame pointer of the call that initiated this allocation. -// -// - size (IN): The size, in bytes, of the memory block to be allocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the specified MFC debug new operator. -// -void* VisualLeakDetector::new_dbg_mfc (new_dbg_mfc_t pnew_dbg_mfc, - SIZE_T fp, - size_t size, - char const *file, - int line) -{ - void *block; - tls_t *tls = vld.gettls(); - - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - tls->addrfp = fp; - } - - // Do the allocation. The block will be mapped by _RtlAllocateHeap. - block = pnew_dbg_mfc(size, file, line); - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -// __realloc_debug - This function is just a wrapper around the real -// _realloc_dbg that sets appropriate flags to be consulted when the memory is -// actually allocated by RtlAllocateHeap. -// -// - p_realloc_dbg (IN): Pointer to the particular __realloc_dbg implementation -// to call. -// -// - fp (IN): Frame pointer from the call that initiated this allocation. -// -// - mem (IN): Pointer to the memory block to be reallocated. -// -// - size (IN): The size of the memory block to reallocate. -// -// - type (IN): The CRT "use type" of the block to be reallocated. -// -// - file (IN): The name of the file from which this function is being called. -// -// - line (IN): The line number, in the above file, at which this function is -// being called. -// -// Return Value: -// -// Returns the value returned by the specified _realloc_dbg. -// -void* VisualLeakDetector::__realloc_dbg (_realloc_dbg_t p_realloc_dbg, - SIZE_T fp, - void *mem, - size_t size, - int type, - char const *file, - int line) -{ - void *block; - tls_t *tls = vld.gettls(); - - // _realloc_dbg is a CRT function and allocates from the CRT heap. - tls->flags |= VLD_TLS_CRTALLOC; - - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - tls->addrfp = fp; - } - - // Do the allocation. The block will be mapped by _RtlReAllocateHeap. - block = p_realloc_dbg(mem, size, type, file, line); - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -//////////////////////////////////////////////////////////////////////////////// -// -// Win32 IAT Replacement Functions -// -//////////////////////////////////////////////////////////////////////////////// - -// _GetProcAddress - Calls to GetProcAddress are patched through to this -// function. If the requested function is a function that has been patched -// through to one of VLD's handlers, then the address of VLD's handler -// function is returned instead of the real address. Otherwise, this -// function is just a wrapper around the real GetProcAddress. -// -// - module (IN): Handle (base address) of the module from which to retrieve -// the address of an exported function. -// -// - procname (IN): ANSI string containing the name of the exported function -// whose address is to be retrieved. -// -// Return Value: -// -// Returns a pointer to the requested function, or VLD's replacement for -// the function, if there is a replacement function. -// -FARPROC VisualLeakDetector::_GetProcAddress (HMODULE module, LPCSTR procname) -{ - patchentry_t *entry; - UINT index; - UINT tablesize = sizeof(vld.m_patchtable) / sizeof(patchentry_t); - - // See if there is an entry in the patch table that matches the requested - // function. - for (index = 0; index < tablesize; index++) { - entry = &vld.m_patchtable[index]; - if ((entry->modulebase == 0x0) || ((HMODULE)entry->modulebase != module)) { - // This patch table entry is for a different module. - continue; - } - - // This patch table entry is for the specified module. If the requested - // import's name matches the entry's import name (or ordinal), then - // return the address of the replacement instead of the address of the - // actual import. - if ((SIZE_T)entry->importname < (SIZE_T)vld.m_vldbase) { - // This entry's import name is not a valid pointer to data in - // vld.dll. It must be an ordinal value. - if ((UINT)entry->importname == (UINT)procname) { - return (FARPROC)entry->replacement; - } - } - else { - if (strcmp(entry->importname, procname) == 0) { - return (FARPROC)entry->replacement; - } - } - } - - // The requested function is not a patched function. Just return the real - // address of the requested function. - return GetProcAddress(module, procname); -} - -// _HeapCreate - Calls to HeapCreate are patched through to this function. This -// function is just a wrapper around the real HeapCreate that calls VLD's heap -// creation tracking function after the heap has been created. -// -// - options (IN): Heap options. -// -// - initsize (IN): Initial size of the heap. -// -// - maxsize (IN): Maximum size of the heap. -// -// Return Value: -// -// Returns the value returned by HeapCreate. -// -HANDLE VisualLeakDetector::_HeapCreate (DWORD options, SIZE_T initsize, SIZE_T maxsize) -{ - DWORD64 displacement; - SIZE_T fp; - SYMBOL_INFO *functioninfo; - HANDLE heap; - HeapMap::Iterator heapit; - SIZE_T ra; - BYTE symbolbuffer [sizeof(SYMBOL_INFO) + (MAXSYMBOLNAMELENGTH * sizeof(WCHAR)) - 1] = { 0 }; - BOOL symfound; - - // Get the return address within the calling function. - FRAMEPOINTER(fp); - ra = *((SIZE_T*)fp + 1); - - // Create the heap. - heap = HeapCreate(options, initsize, maxsize); - - // Map the created heap handle to a new block map. - vld.mapheap(heap); - - // Try to get the name of the function containing the return address. - functioninfo = (SYMBOL_INFO*)&symbolbuffer; - functioninfo->SizeOfStruct = sizeof(SYMBOL_INFO); - functioninfo->MaxNameLen = MAXSYMBOLNAMELENGTH; - EnterCriticalSection(&symbollock); - symfound = SymFromAddrW(currentprocess, ra, &displacement, functioninfo); - LeaveCriticalSection(&symbollock); - if (symfound == TRUE) { - if (wcscmp(L"_heap_init", functioninfo->Name) == 0) { - // HeapCreate was called by _heap_init. This is a static CRT heap. - EnterCriticalSection(&vld.m_maplock); - heapit = vld.m_heapmap->find(heap); - assert(heapit != vld.m_heapmap->end()); - (*heapit).second->flags |= VLD_HEAP_CRT; - LeaveCriticalSection(&vld.m_maplock); - } - } - - return heap; -} - -// _HeapDestroy - Calls to HeapDestroy are patched through to this function. -// This function is just a wrapper around the real HeapDestroy that calls -// VLD's heap destruction tracking function after the heap has been destroyed. -// -// - heap (IN): Handle to the heap to be destroyed. -// -// Return Value: -// -// Returns the valued returned by HeapDestroy. -// -BOOL VisualLeakDetector::_HeapDestroy (HANDLE heap) -{ - // After this heap is destroyed, the heap's address space will be unmapped - // from the process's address space. So, we'd better generate a leak report - // for this heap now, while we can still read from the memory blocks - // allocated to it. - vld.reportleaks(heap); - - vld.unmapheap(heap); - - return HeapDestroy(heap); -} - -// _LdrLoadDll - Calls to LdrLoadDll are patched through to this function. This -// function invokes the real LdrLoadDll and then re-attaches VLD to all -// modules loaded in the process after loading of the new DLL is complete. -// All modules must be re-enumerated because the explicit load of the -// specified module may result in the implicit load of one or more additional -// modules which are dependencies of the specified module. -// -// - searchpath (IN): The path to use for searching for the specified module to -// be loaded. -// -// - flags (IN): Pointer to action flags. -// -// - modulename (IN): Pointer to a unicodestring_t structure specifying the -// name of the module to be loaded. -// -// - modulehandle (OUT): Address of a HANDLE to receive the newly loaded -// module's handle. -// -// Return Value: -// -// Returns the value returned by LdrLoadDll. -// -NTSTATUS VisualLeakDetector::_LdrLoadDll (LPWSTR searchpath, PDWORD flags, unicodestring_t *modulename, - PHANDLE modulehandle) -{ - ModuleSet::Iterator moduleit; - ModuleSet *newmodules; - ModuleSet *oldmodules; - NTSTATUS status; - - EnterCriticalSection(&vld.m_loaderlock); - - // Load the DLL. - status = LdrLoadDll(searchpath, flags, modulename, modulehandle); - - if (STATUS_SUCCESS == status) { - // Create a new set of all loaded modules, including any newly loaded - // modules. - newmodules = new ModuleSet; - newmodules->reserve(MODULESETRESERVE); - EnumerateLoadedModulesW64(currentprocess, addloadedmodule, newmodules); - - // Attach to all modules included in the set. - vld.attachtoloadedmodules(newmodules); - - // Start using the new set of loaded modules. - EnterCriticalSection(&vld.m_moduleslock); - oldmodules = vld.m_loadedmodules; - vld.m_loadedmodules = newmodules; - LeaveCriticalSection(&vld.m_moduleslock); - - // Free resources used by the old module list. - for (moduleit = oldmodules->begin(); moduleit != oldmodules->end(); ++moduleit) { - delete (*moduleit).name; - delete (*moduleit).path; - } - delete oldmodules; - } - - LeaveCriticalSection(&vld.m_loaderlock); - - return status; -} - -// _RtlAllocateHeap - Calls to RtlAllocateHeap are patched through to this -// function. This function invokes the real RtlAllocateHeap and then calls -// VLD's allocation tracking function. Pretty much all memory allocations -// will eventually result in a call to RtlAllocateHeap, so this is where we -// finally map the allocated block. -// -// - heap (IN): Handle to the heap from which to allocate memory. -// -// - flags (IN): Heap allocation control flags. -// -// - size (IN): Size, in bytes, of the block to allocate. -// -// Return Value: -// -// Returns the return value from RtlAllocateHeap. -// -LPVOID VisualLeakDetector::_RtlAllocateHeap (HANDLE heap, DWORD flags, SIZE_T size) -{ - BOOL crtalloc; - BOOL excluded = FALSE; - SIZE_T fp; - LPVOID block; - moduleinfo_t moduleinfo; - ModuleSet::Iterator moduleit; - SIZE_T returnaddress; - tls_t *tls = vld.gettls(); - - // Allocate the block. - block = RtlAllocateHeap(heap, flags, size); - if ((block != NULL) && vld.enabled()) { - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - FRAMEPOINTER(fp); - } - else { - fp = tls->addrfp; - } - crtalloc = (tls->flags & VLD_TLS_CRTALLOC) ? TRUE : FALSE; - - // Reset thread local flags and variables, in case any libraries called - // into while mapping the block allocate some memory. - tls->addrfp = 0x0; - tls->flags &=~VLD_TLS_CRTALLOC; - - // Find the information for the module that initiated this allocation. - returnaddress = *((SIZE_T*)fp + 1); - moduleinfo.addrhigh = returnaddress; - moduleinfo.addrlow = returnaddress; - EnterCriticalSection(&vld.m_moduleslock); - moduleit = vld.m_loadedmodules->find(moduleinfo); - if (moduleit != vld.m_loadedmodules->end()) { - excluded = (*moduleit).flags & VLD_MODULE_EXCLUDED ? TRUE : FALSE; - } - LeaveCriticalSection(&vld.m_moduleslock); - if (!excluded) { - // The module that initiated this allocation is included in leak - // detection. Map this block to the specified heap. - vld.mapblock(heap, block, size, fp, crtalloc); - } - } - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -// _RtlFreeHeap - Calls to RtlFreeHeap are patched through to this function. -// This function calls VLD's free tracking function and then invokes the real -// RtlFreeHeap. Pretty much all memory frees will eventually result in a call -// to RtlFreeHeap, so this is where we finally unmap the freed block. -// -// - heap (IN): Handle to the heap to which the block being freed belongs. -// -// - flags (IN): Heap control flags. -// -// - mem (IN): Pointer to the memory block being freed. -// -// Return Value: -// -// Returns the value returned by RtlFreeHeap. -// -BOOL VisualLeakDetector::_RtlFreeHeap (HANDLE heap, DWORD flags, LPVOID mem) -{ - BOOL status; - - // Unmap the block from the specified heap. - vld.unmapblock(heap, mem); - - status = RtlFreeHeap(heap, flags, mem); - - return status; -} - -// _RtlReAllocateHeap - Calls to RtlReAllocateHeap are patched through to this -// function. This function invokes the real RtlReAllocateHeap and then calls -// VLD's reallocation tracking function. All arguments passed to this function -// are passed on to the real RtlReAllocateHeap without modification. Pretty -// much all memory re-allocations will eventually result in a call to -// RtlReAllocateHeap, so this is where we finally remap the reallocated block. -// -// - heap (IN): Handle to the heap to reallocate memory from. -// -// - flags (IN): Heap control flags. -// -// - mem (IN): Pointer to the currently allocated block which is to be -// reallocated. -// -// - size (IN): Size, in bytes, of the block to reallocate. -// -// Return Value: -// -// Returns the value returned by RtlReAllocateHeap. -// -LPVOID VisualLeakDetector::_RtlReAllocateHeap (HANDLE heap, DWORD flags, LPVOID mem, SIZE_T size) -{ - BOOL crtalloc; - BOOL excluded = FALSE; - SIZE_T fp; - moduleinfo_t moduleinfo; - ModuleSet::Iterator moduleit; - LPVOID newmem; - SIZE_T returnaddress; - tls_t *tls = vld.gettls(); - - // Reallocate the block. - newmem = RtlReAllocateHeap(heap, flags, mem, size); - - if (newmem != NULL) { - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - FRAMEPOINTER(fp); - } - else { - fp = tls->addrfp; - } - crtalloc = (tls->flags & VLD_TLS_CRTALLOC) ? TRUE : FALSE; - - // Reset thread local flags and variables, in case any libraries called - // into while remapping the block allocate some memory. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - // Find the information for the module that initiated this reallocation. - returnaddress = *((SIZE_T*)fp + 1); - moduleinfo.addrhigh = returnaddress; - moduleinfo.addrlow = returnaddress; - EnterCriticalSection(&vld.m_moduleslock); - moduleit = vld.m_loadedmodules->find(moduleinfo); - if (moduleit != vld.m_loadedmodules->end()) { - excluded = (*moduleit).flags & VLD_MODULE_EXCLUDED ? TRUE : FALSE; - } - LeaveCriticalSection(&vld.m_moduleslock); - if (!excluded) { - // The module that initiated this allocation is included in leak - // detection. Remap the block. - vld.remapblock(heap, mem, newmem, size, fp, crtalloc); - } - } - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return newmem; -} - -//////////////////////////////////////////////////////////////////////////////// -// -// COM IAT Replacement Functions -// -//////////////////////////////////////////////////////////////////////////////// - -// _CoGetMalloc - Calls to CoGetMalloc are patched through to this function. -// This function returns a pointer to Visual Leak Detector's implementation -// of the IMalloc interface, instead of returning a pointer to the system -// implementation. This allows VLD's implementation of the IMalloc interface -// (which is basically a thin wrapper around the system implementation) to be -// invoked in place of the system implementation. -// -// - context (IN): Reserved; value must be 1. -// -// - imalloc (IN): Address of a pointer to receive the address of VLD's -// implementation of the IMalloc interface. -// -// Return Value: -// -// Always returns S_OK. -// -HRESULT VisualLeakDetector::_CoGetMalloc (DWORD context, LPMALLOC *imalloc) -{ - static CoGetMalloc_t pCoGetMalloc = NULL; - - HMODULE ole32; - - *imalloc = (LPMALLOC)&vld; - - if (pCoGetMalloc == NULL) { - // This is the first call to this function. Link to the real - // CoGetMalloc and get a pointer to the system implementation of the - // IMalloc interface. - ole32 = GetModuleHandle(L"ole32.dll"); - pCoGetMalloc = (CoGetMalloc_t)GetProcAddress(ole32, "CoGetMalloc"); - pCoGetMalloc(context, &vld.m_imalloc); - } - - return S_OK; -} - -// _CoTaskMemAlloc - Calls to CoTaskMemAlloc are patched through to this -// function. This function is just a wrapper around the real CoTaskMemAlloc -// that sets appropriate flags to be consulted when the memory is actually -// allocated by RtlAllocateHeap. -// -// - size (IN): Size of the memory block to allocate. -// -// Return Value: -// -// Returns the value returned from CoTaskMemAlloc. -// -LPVOID VisualLeakDetector::_CoTaskMemAlloc (ULONG size) -{ - static CoTaskMemAlloc_t pCoTaskMemAlloc = NULL; - - LPVOID block; - SIZE_T fp; - HMODULE ole32; - tls_t *tls = vld.gettls(); - - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - FRAMEPOINTER(fp); - tls->addrfp = fp; - } - - if (pCoTaskMemAlloc == NULL) { - // This is the first call to this function. Link to the real - // CoTaskMemAlloc. - ole32 = GetModuleHandle(L"ole32.dll"); - pCoTaskMemAlloc = (CoTaskMemAlloc_t)GetProcAddress(ole32, "CoTaskMemAlloc"); - } - - // Do the allocation. The block will be mapped by _RtlAllocateHeap. - block = pCoTaskMemAlloc(size); - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -// _CoTaskMemRealloc - Calls to CoTaskMemRealloc are patched through to this -// function. This function is just a wrapper around the real CoTaskMemRealloc -// that sets appropriate flags to be consulted when the memory is actually -// allocated by RtlAllocateHeap. -// -// - mem (IN): Pointer to the memory block to reallocate. -// -// - size (IN): Size, in bytes, of the block to reallocate. -// -// Return Value: -// -// Returns the value returned from CoTaskMemRealloc. -// -LPVOID VisualLeakDetector::_CoTaskMemRealloc (LPVOID mem, ULONG size) -{ - static CoTaskMemRealloc_t pCoTaskMemRealloc = NULL; - - LPVOID block; - SIZE_T fp; - HMODULE ole32; - tls_t *tls = vld.gettls(); - - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - FRAMEPOINTER(fp); - tls->addrfp = fp; - } - - if (pCoTaskMemRealloc == NULL) { - // This is the first call to this function. Link to the real - // CoTaskMemRealloc. - ole32 = GetModuleHandle(L"ole32.dll"); - pCoTaskMemRealloc = (CoTaskMemRealloc_t)GetProcAddress(ole32, "CoTaskMemRealloc"); - } - - // Do the allocation. The block will be mapped by _RtlReAllocateHeap. - block = pCoTaskMemRealloc(mem, size); - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -//////////////////////////////////////////////////////////////////////////////// -// -// Public COM IMalloc Implementation Functions -// -//////////////////////////////////////////////////////////////////////////////// - -// AddRef - Calls to IMalloc::AddRef end up here. This function is just a -// wrapper around the real IMalloc::AddRef implementation. -// -// Return Value: -// -// Returns the value returned by the system implementation of -// IMalloc::AddRef. -// -ULONG VisualLeakDetector::AddRef () -{ - assert(m_imalloc != NULL); - return m_imalloc->AddRef(); -} - -// Alloc - Calls to IMalloc::Alloc end up here. This function is just a wrapper -// around the real IMalloc::Alloc implementation that sets appropriate flags -// to be consulted when the memory is actually allocated by RtlAllocateHeap. -// -// - size (IN): The size of the memory block to allocate. -// -// Return Value: -// -// Returns the value returned by the system's IMalloc::Alloc implementation. -// -LPVOID VisualLeakDetector::Alloc (ULONG size) -{ - LPVOID block; - SIZE_T fp; - tls_t *tls = vld.gettls(); - - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - FRAMEPOINTER(fp); - tls->addrfp = fp; - } - - // Do the allocation. The block will be mapped by _RtlAllocateHeap. - assert(m_imalloc != NULL); - block = m_imalloc->Alloc(size); - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -// DidAlloc - Calls to IMalloc::DidAlloc will end up here. This function is just -// a wrapper around the system implementation of IMalloc::DidAlloc. -// -// - mem (IN): Pointer to a memory block to inquire about. -// -// Return Value: -// -// Returns the value returned by the system implementation of -// IMalloc::DidAlloc. -// -INT VisualLeakDetector::DidAlloc (LPVOID mem) -{ - assert(m_imalloc != NULL); - return m_imalloc->DidAlloc(mem); -} - -// Free - Calls to IMalloc::Free will end up here. This function is just a -// wrapper around the real IMalloc::Free implementation. -// -// - mem (IN): Pointer to the memory block to be freed. -// -// Return Value: -// -// None. -// -VOID VisualLeakDetector::Free (LPVOID mem) -{ - assert(m_imalloc != NULL); - m_imalloc->Free(mem); -} - -// GetSize - Calls to IMalloc::GetSize will end up here. This function is just a -// wrapper around the real IMalloc::GetSize implementation. -// -// - mem (IN): Pointer to the memory block to inquire about. -// -// Return Value: -// -// Returns the value returned by the system implementation of -// IMalloc::GetSize. -// -ULONG VisualLeakDetector::GetSize (LPVOID mem) -{ - assert(m_imalloc != NULL); - return m_imalloc->GetSize(mem); -} - -// HeapMinimize - Calls to IMalloc::HeapMinimize will end up here. This function -// is just a wrapper around the real IMalloc::HeapMinimize implementation. -// -// Return Value: -// -// None. -// -VOID VisualLeakDetector::HeapMinimize () -{ - assert(m_imalloc != NULL); - m_imalloc->HeapMinimize(); -} - -// QueryInterface - Calls to IMalloc::QueryInterface will end up here. This -// function is just a wrapper around the real IMalloc::QueryInterface -// implementation. -// -// - iid (IN): COM interface ID to query about. -// -// - object (IN): Address of a pointer to receive the requested interface -// pointer. -// -// Return Value: -// -// Returns the value returned by the system implementation of -// IMalloc::QueryInterface. -// -HRESULT VisualLeakDetector::QueryInterface (REFIID iid, LPVOID *object) -{ - assert(m_imalloc != NULL); - return m_imalloc->QueryInterface(iid, object); -} - -// Realloc - Calls to IMalloc::Realloc will end up here. This function is just a -// wrapper around the real IMalloc::Realloc implementation that sets -// appropriate flags to be consulted when the memory is actually allocated by -// RtlAllocateHeap. -// -// - mem (IN): Pointer to the memory block to reallocate. -// -// - size (IN): Size, in bytes, of the memory block to reallocate. -// -// Return Value: -// -// Returns the value returned by the system implementation of -// IMalloc::Realloc. -// -LPVOID VisualLeakDetector::Realloc (LPVOID mem, ULONG size) -{ - LPVOID block; - SIZE_T fp; - tls_t *tls = vld.gettls(); - - if (tls->addrfp == 0x0) { - // This is the first call to enter VLD for the current allocation. - // Record the current frame pointer. - FRAMEPOINTER(fp); - tls->addrfp = fp; - } - - // Do the allocation. The block will be mapped by _RtlReAllocateHeap. - assert(m_imalloc != NULL); - block = m_imalloc->Realloc(mem, size); - - // Reset thread local flags and variables for the next allocation. - tls->addrfp = 0x0; - tls->flags &= ~VLD_TLS_CRTALLOC; - - return block; -} - -// Release - Calls to IMalloc::Release will end up here. This function is just -// a wrapper around the real IMalloc::Release implementation. -// -// Return Value: -// -// Returns the value returned by the system implementation of -// IMalloc::Release. -// -ULONG VisualLeakDetector::Release () -{ - assert(m_imalloc != NULL); - return m_imalloc->Release(); -} diff --git a/vld.h b/vld.h deleted file mode 100644 index 234c87f3..00000000 --- a/vld.h +++ /dev/null @@ -1,97 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - Import Library Header -// Copyright (c) 2006 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifdef _DEBUG - -#pragma comment(lib, "vld.lib") - -// Force a symbolic reference to the global VisualLeakDetector class object from -// the DLL. This enusres that the DLL is loaded and linked with the program, -// even if no code otherwise imports any of the DLL's exports. -#pragma comment(linker, "/include:__imp_?vld@@3VVisualLeakDetector@@A") - -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector APIs -// - -#ifdef __cplusplus -extern "C" { -#endif // __cplusplus - -// VLDDisable - Disables Visual Leak Detector's memory leak detection at -// runtime. If memory leak detection is already disabled, then calling this -// function has no effect. -// -// Note: In multithreaded programs, this function operates on a per-thread -// basis. In other words, if you call this function from one thread, then -// memory leak detection is only disabled for that thread. If memory leak -// detection is enabled for other threads, then it will remain enabled for -// those other threads. It was designed to work this way to insulate you, -// the programmer, from having to ensure thread synchronization when calling -// VLDEnable() and VLDDisable(). Without this, calling these two functions -// unsychronized could result in unpredictable and unintended behavior. -// But this also means that if you want to disable memory leak detection -// process-wide, then you need to call this function from every thread in -// the process. -// -// Return Value: -// -// None. -// -__declspec(dllimport) void VLDDisable (); - -// VLDEnable - Enables Visual Leak Detector's memory leak detection at runtime. -// If memory leak detection is already enabled, which it is by default, then -// calling this function has no effect. -// -// Note: In multithreaded programs, this function operates on a per-thread -// basis. In other words, if you call this function from one thread, then -// memory leak detection is only enabled for that thread. If memory leak -// detection is disabled for other threads, then it will remain disabled for -// those other threads. It was designed to work this way to insulate you, -// the programmer, from having to ensure thread synchronization when calling -// VLDEnable() and VLDDisable(). Without this, calling these two functions -// unsychronized could result in unpredictable and unintended behavior. -// But this also means that if you want to enable memory leak detection -// process-wide, then you need to call this function from every thread in -// the process. -// -// Return Value: -// -// None. -// -__declspec(dllimport) void VLDEnable (); - -#ifdef __cplusplus -} -#endif // __cplusplus - -#else // !_DEBUG - -#define VLDEnable() -#define VLDDisable() - -#endif // _DEBUG diff --git a/vld.ini b/vld.ini index 44cd4413..fa501129 100644 --- a/vld.ini +++ b/vld.ini @@ -1,155 +1,171 @@ -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; -;; Visual Leak Detector - Initialization/Configuration File -;; Copyright (c) 2006 Dan Moulding -;; -;; This library is free software; you can redistribute it and/or -;; modify it under the terms of the GNU Lesser General Public -;; License as published by the Free Software Foundation; either -;; version 2.1 of the License, or (at your option) any later version. -;; -;; This library is distributed in the hope that it will be useful, -;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -;; Lesser General Public License for more details. -;; -;; You should have received a copy of the GNU Lesser General Public -;; License along with this library; if not, write to the Free Software -;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -;; -;; See COPYING.txt for the full terms of the GNU Lesser General Public License. -;; -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -; Any options left blank or not present will revert to their default values. -[Options] - -; The main on/off switch. If off, Visual Leak Detector will be completely -; disabled. It will do nothing but print a message to the debugger indicating -; that it has been turned off. -; -; Valid Values: on, off -; Default: on -; -VLD = on - -; If yes, duplicate leaks (those that are identical) are not shown individually. -; Only the first such leak is shown, along with a number indicating the total -; number of duplicate leaks. -; -; Valid Values: yes, no -; Default: no -; -AggregateDuplicates = no - -; Lists any additional modules to be included in memory leak detection. This can -; be useful for checking for memory leaks in debug builds of 3rd party modules -; which can not be easily rebuilt with '#include "vld.h"'. This option should be -; used only if absolutely necessary and only if you really know what you are -; doing. -; -; CAUTION: Avoid listing any modules that link with the release CRT libraries. -; Only modules that link with the debug CRT libraries should be listed here. -; Doing otherwise might result in false memory leak reports or even crashes. -; -; Valid Values: Any list containing module names (i.e. names of EXEs or DLLs). -; Default: None. -; -ForceIncludeModules = - -; Maximum number of data bytes to display for each leaked block. If zero, then -; the data dump is completely suppressed and only call stacks are shown. -; Limiting this to a low number can be useful if any of the leaked blocks are -; very large and cause unnecessary clutter in the memory leak report. -; -; Value Values: 0 - 4294967295 -; Default: 256 -; -MaxDataDump = - -; Maximum number of call stack frames to trace back during leak detection. -; Limiting this to a low number can reduce the CPU utilization overhead imposed -; by memory leak detection, especially when using the slower "safe" stack -; walking method (see StackWalkMethod below). -; -; Valid Values: 1 - 4294967295 -; Default: 64 -; -MaxTraceFrames = - -; Sets the type of encoding to use for the generated memory leak report. This -; option is really only useful in conjuction with sending the report to a file. -; Sending a Unicode encoded report to the debugger is not useful because the -; debugger cannot display Unicode characters. Using Unicode encoding might be -; useful if the data contained in leaked blocks is likely to consist of Unicode -; text. -; -; Valid Values: ascii, unicode -; Default: ascii -; -ReportEncoding = ascii - -; Sets the report file destination, if reporting to file is enabled. A relative -; path may be specified and is considered relative to the process' working -; directory. -; -; Valid Values: Any valid path and filename. -; Default: .\memory_leak_report.txt -; -ReportFile = - -; Sets the report destination to either a file, the debugger, or both. If -; reporting to file is enabled, the report is sent to the file specified by the -; ReportFile option. -; -; Valid Values: debugger, file, both -; Default: debugger -; -ReportTo = debugger - -; Turns on or off a self-test mode which is used to verify that VLD is able to -; detect memory leaks in itself. Intended to be used for debugging VLD itself, -; not for debugging other programs. -; -; Valid Values: on, off -; Default: off -; -SelfTest = off - -; Selects the method to be used for walking the stack to obtain stack traces for -; allocated memory blocks. The "fast" method may not always be able to -; successfully trace completely through all call stacks. In such cases, the -; "safe" method may prove to more reliably obtain the full stack trace. The -; disadvantage is that the "safe" method is significantly slower than the "fast" -; method and will probably result in very noticeable performance degradation of -; the program being debugged. -; -; Valid Values: fast, safe -; Default: fast -; -StackWalkMethod = fast - -; Determines whether memory leak detection should be initially enabled for all -; threads, or whether it should be initially disabled for all threads. If set -; to "yes", then any threads requiring memory leak detection to be enabled will -; need to call VLDEnable at some point to enable leak detection for those -; threads. -; -; Valid Values: yes, no -; Default: no -; -StartDisabled = no - -; Determines whether or not all frames, including frames internal to the heap, -; are traced. There will always be a number of frames internal to Visual Leak -; Detector and C/C++ or Win32 heap APIs that aren't generally useful for -; determining the cause of a leak. Normally these frames are skipped during the -; stack trace, which somewhat reduces the time spent tracing and amount of data -; collected and stored in memory. Including all frames in the stack trace, all -; the way down into VLD's own code can, however, be useful for debugging VLD -; itself. -; -; Valid Values: yes, no -; Default: no -; -TraceInternalFrames = no +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Visual Leak Detector - Initialization/Configuration File +;; Copyright (c) 2005-2017 VLD Team +;; +;; This library is free software; you can redistribute it and/or +;; modify it under the terms of the GNU Lesser General Public +;; License as published by the Free Software Foundation; either +;; version 2.1 of the License, or (at your option) any later version. +;; +;; This library is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +;; Lesser General Public License for more details. +;; +;; You should have received a copy of the GNU Lesser General Public +;; License along with this library; if not, write to the Free Software +;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +;; +;; See COPYING.txt for the full terms of the GNU Lesser General Public License. +;; +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +; Any options left blank or not present will revert to their default values. +[Options] + +; The main on/off switch. If off, Visual Leak Detector will be completely +; disabled. It will do nothing but print a message to the debugger indicating +; that it has been turned off. +; +; Valid Values: on, off +; Default: on +; +VLD = on + +; If yes, duplicate leaks (those that are identical) are not shown individually. +; Only the first such leak is shown, along with a number indicating the total +; number of duplicate leaks. +; +; Valid Values: yes, no +; Default: no +; +AggregateDuplicates = no + +; Lists any additional modules to be included in memory leak detection. This can +; be useful for checking for memory leaks in debug builds of 3rd party modules +; which can not be easily rebuilt with '#include "vld.h"'. This option should be +; used only if absolutely necessary and only if you really know what you are +; doing. +; +; CAUTION: Avoid listing any modules that link with the release CRT libraries. +; Only modules that link with the debug CRT libraries should be listed here. +; Doing otherwise might result in false memory leak reports or even crashes. +; +; Valid Values: Any list containing module names (i.e. names of EXEs or DLLs) +; Default: None. +; +ForceIncludeModules = + +; Maximum number of data bytes to display for each leaked block. If zero, then +; the data dump is completely suppressed and only call stacks are shown. +; Limiting this to a low number can be useful if any of the leaked blocks are +; very large and cause unnecessary clutter in the memory leak report. +; +; Value Values: 0 - 4294967295 +; Default: 256 +; +MaxDataDump = + +; Maximum number of call stack frames to trace back during leak detection. +; Limiting this to a low number can reduce the CPU utilization overhead imposed +; by memory leak detection, especially when using the slower "safe" stack +; walking method (see StackWalkMethod below). +; +; Valid Values: 1 - 4294967295 +; Default: 64 +; +MaxTraceFrames = + +; Sets the type of encoding to use for the generated memory leak report. This +; option is really only useful in conjuction with sending the report to a file. +; Sending a Unicode encoded report to the debugger is not useful because the +; debugger cannot display Unicode characters. Using Unicode encoding might be +; useful if the data contained in leaked blocks is likely to consist of Unicode +; text. +; +; Valid Values: ascii, unicode +; Default: ascii +; +ReportEncoding = ascii + +; Sets the report file destination, if reporting to file is enabled. A relative +; path may be specified and is considered relative to the process' working +; directory. +; +; Valid Values: Any valid path and filename. +; Default: .\memory_leak_report.txt +; +ReportFile = + +; Sets the report destination to either a file, the debugger, or both. If +; reporting to file is enabled, the report is sent to the file specified by the +; ReportFile option. +; +; Valid Values: debugger, file, both +; Default: debugger +; +ReportTo = debugger + +; Turns on or off a self-test mode which is used to verify that VLD is able to +; detect memory leaks in itself. Intended to be used for debugging VLD itself, +; not for debugging other programs. +; +; Valid Values: on, off +; Default: off +; +SelfTest = off + +; Selects the method to be used for walking the stack to obtain stack traces for +; allocated memory blocks. The "fast" method may not always be able to +; successfully trace completely through all call stacks. In such cases, the +; "safe" method may prove to more reliably obtain the full stack trace. The +; disadvantage is that the "safe" method is significantly slower than the "fast" +; method and will probably result in very noticeable performance degradation of +; the program being debugged. +; +; Valid Values: fast, safe +; Default: fast +; +StackWalkMethod = fast + +; Determines whether memory leak detection should be initially enabled for all +; threads, or whether it should be initially disabled for all threads. If set +; to "yes", then any threads requiring memory leak detection to be enabled will +; need to call VLDEnable at some point to enable leak detection for those +; threads. +; +; Valid Values: yes, no +; Default: no +; +StartDisabled = no + +; Determines whether or not all frames, including frames internal to the heap, +; are traced. There will always be a number of frames internal to Visual Leak +; Detector and C/C++ or Win32 heap APIs that aren't generally useful for +; determining the cause of a leak. Normally these frames are skipped during the +; stack trace, which somewhat reduces the time spent tracing and amount of data +; collected and stored in memory. Including all frames in the stack trace, all +; the way down into VLD's own code can, however, be useful for debugging VLD +; itself. +; +; Valid Values: yes, no +; Default: no +; +TraceInternalFrames = no + +; Determines whether or not report memory leaks when missing HeapFree calls. +; +; Valid Values: yes, no +; Default: no +; +SkipHeapFreeLeaks = no + +; Determines whether or not report memory leaks generated from crt startup code. +; These are not actual memory leaks as they are freed by crt after the VLD object +; has been destroyed. +; +; Valid Values: yes, no +; Default: yes +; +SkipCrtStartupLeaks = yes diff --git a/vld.sln b/vld.sln deleted file mode 100644 index 23f0e475..00000000 --- a/vld.sln +++ /dev/null @@ -1,29 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vld", "vld.vcproj", "{0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testsuite", "testsuite\testsuite.vcproj", "{EE4A829C-5FD8-460B-8A90-B518B9BABB70}" - ProjectSection(ProjectDependencies) = postProject - {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} = {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug|Win32.ActiveCfg = Debug|Win32 - {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug|Win32.Build.0 = Debug|Win32 - {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release|Win32.ActiveCfg = Release|Win32 - {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release|Win32.Build.0 = Release|Win32 - {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug|Win32.ActiveCfg = Debug|Win32 - {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug|Win32.Build.0 = Debug|Win32 - {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release|Win32.ActiveCfg = Debug(Release)|Win32 - {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release|Win32.Build.0 = Debug(Release)|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/vld.vcproj b/vld.vcproj deleted file mode 100644 index 0d1b30cb..00000000 --- a/vld.vcproj +++ /dev/null @@ -1,262 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vld_vs14.sln b/vld_vs14.sln new file mode 100644 index 00000000..cbd2e466 --- /dev/null +++ b/vld_vs14.sln @@ -0,0 +1,498 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.24720.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vld", "src\vld.vcxproj", "{0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_basics", "src\tests\basics\basics.vcxproj", "{0943354A-41E0-4215-878A-8D0FE758052C}" + ProjectSection(ProjectDependencies) = postProject + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} = {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testsuite", "src\tests\suite\testsuite.vcxproj", "{EE4A829C-5FD8-460B-8A90-B518B9BABB70}" + ProjectSection(ProjectDependencies) = postProject + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} = {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dynamic", "src\tests\dynamic_dll\dynamic.vcxproj", "{3AEA2AAF-3E9B-466F-B361-560B95AD88B4}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dynamic_app", "src\tests\dynamic_app\dynamic_app.vcxproj", "{5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}" + ProjectSection(ProjectDependencies) = postProject + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4} = {3AEA2AAF-3E9B-466F-B361-560B95AD88B4} + {2178E5B2-1032-441F-A664-F3D8D1FD1913} = {2178E5B2-1032-441F-A664-F3D8D1FD1913} + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} = {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_mfc", "src\tests\mfc_dll\mfc.vcxproj", "{2178E5B2-1032-441F-A664-F3D8D1FD1913}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vldmfc", "src\tests\mfc\vldmfc.vcxproj", "{A231973E-072A-428E-982E-5363ADD1CDE2}" + ProjectSection(ProjectDependencies) = postProject + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} = {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "corruption", "src\tests\corruption\corruption.vcxproj", "{87911ED6-84BC-4526-9654-A4FF4E0EDF52}" + ProjectSection(ProjectDependencies) = postProject + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} = {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Dlls", "Dlls", "{281D5ACB-9ED2-496B-B19E-A75F4D4DA111}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libgtest", "lib\gtest\msvc\gtest.vcxproj", "{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libs", "Libs", "{9FD1911C-3FAB-48DE-BE31-9F2C7B1EB58C}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libformat", "lib\cppformat\format.vcxproj", "{4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vld_main", "src\tests\vld_main\vld_main_vs14.vcxproj", "{8C732490-DC1A-40C0-923F-1555B9141B80}" + ProjectSection(ProjectDependencies) = postProject + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} = {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vld_unload", "src\tests\vld_unload\vld_unload_vs14.vcxproj", "{A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}" + ProjectSection(ProjectDependencies) = postProject + {50C94B05-8C3E-49ED-B2B9-5715EB624D14} = {50C94B05-8C3E-49ED-B2B9-5715EB624D14} + {33F98E06-F44C-4E22-9E16-4C20F8238A95} = {33F98E06-F44C-4E22-9E16-4C20F8238A95} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vld_dll1", "src\tests\vld_dll1\vld_dll1_vs14.vcxproj", "{50C94B05-8C3E-49ED-B2B9-5715EB624D14}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vld_dll2", "src\tests\vld_dll2\vld_dll2_vs14.vcxproj", "{33F98E06-F44C-4E22-9E16-4C20F8238A95}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ComTest", "src\tests\vld_ComTest\ComTest_vs14.vcxproj", "{3719F504-3DF0-45F8-BC7A-4415804AC7C9}" + ProjectSection(ProjectDependencies) = postProject + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} = {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vld_main_test", "src\tests\vld_main_test\vld_main_test_vs14.vcxproj", "{BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}" + ProjectSection(ProjectDependencies) = postProject + {8C732490-DC1A-40C0-923F-1555B9141B80} = {8C732490-DC1A-40C0-923F-1555B9141B80} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug_StaticCrt|Win32 = Debug_StaticCrt|Win32 + Debug_StaticCrt|x64 = Debug_StaticCrt|x64 + Debug_VldRelease_StaticCrt|Win32 = Debug_VldRelease_StaticCrt|Win32 + Debug_VldRelease_StaticCrt|x64 = Debug_VldRelease_StaticCrt|x64 + Debug_VldRelease|Win32 = Debug_VldRelease|Win32 + Debug_VldRelease|x64 = Debug_VldRelease|x64 + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release_StaticCrt|Win32 = Release_StaticCrt|Win32 + Release_StaticCrt|x64 = Release_StaticCrt|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_StaticCrt|Win32.ActiveCfg = Debug|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_StaticCrt|Win32.Build.0 = Debug|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_StaticCrt|x64.ActiveCfg = Debug|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_StaticCrt|x64.Build.0 = Debug|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Release|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease_StaticCrt|x64.Build.0 = Release|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease|Win32.ActiveCfg = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease|Win32.Build.0 = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease|x64.ActiveCfg = Release|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease|x64.Build.0 = Release|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug|Win32.ActiveCfg = Debug|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug|Win32.Build.0 = Debug|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug|x64.ActiveCfg = Debug|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug|x64.Build.0 = Debug|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release_StaticCrt|Win32.ActiveCfg = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release_StaticCrt|Win32.Build.0 = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release_StaticCrt|x64.ActiveCfg = Release|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release_StaticCrt|x64.Build.0 = Release|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release|Win32.ActiveCfg = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release|Win32.Build.0 = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release|x64.ActiveCfg = Release|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release|x64.Build.0 = Release|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug|Win32.ActiveCfg = Debug|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug|Win32.Build.0 = Debug|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug|x64.ActiveCfg = Debug|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug|x64.Build.0 = Debug|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release|Win32.ActiveCfg = Release|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release|Win32.Build.0 = Release|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release|x64.ActiveCfg = Release|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release|x64.Build.0 = Release|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_StaticCrt|x64.Deploy.0 = Debug_StaticCrt|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug|Win32.ActiveCfg = Debug|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug|Win32.Build.0 = Debug|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug|x64.ActiveCfg = Debug|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug|x64.Build.0 = Debug|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release|Win32.ActiveCfg = Release|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release|Win32.Build.0 = Release|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release|x64.ActiveCfg = Release|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release|x64.Build.0 = Release|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug|Win32.ActiveCfg = Debug|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug|Win32.Build.0 = Debug|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug|x64.ActiveCfg = Debug|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug|x64.Build.0 = Debug|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release|Win32.ActiveCfg = Release|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release|Win32.Build.0 = Release|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release|x64.ActiveCfg = Release|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release|x64.Build.0 = Release|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug|Win32.ActiveCfg = Debug|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug|Win32.Build.0 = Debug|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug|x64.ActiveCfg = Debug|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug|x64.Build.0 = Debug|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release|Win32.ActiveCfg = Release|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release|Win32.Build.0 = Release|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release|x64.ActiveCfg = Release|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release|x64.Build.0 = Release|x64 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug|Win32.ActiveCfg = Debug|Win32 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug|Win32.Build.0 = Debug|Win32 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug|x64.ActiveCfg = Debug|x64 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Debug|x64.Build.0 = Debug|x64 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Release|Win32.ActiveCfg = Release|Win32 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Release|Win32.Build.0 = Release|Win32 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Release|x64.ActiveCfg = Release|x64 + {2178E5B2-1032-441F-A664-F3D8D1FD1913}.Release|x64.Build.0 = Release|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug_VldRelease_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug_VldRelease|Win32.ActiveCfg = Release|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug_VldRelease|Win32.Build.0 = Release|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug_VldRelease|x64.ActiveCfg = Release|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug_VldRelease|x64.Build.0 = Release|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.ActiveCfg = Debug|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|Win32.Build.0 = Debug|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|x64.ActiveCfg = Debug|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Debug|x64.Build.0 = Debug|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|Win32.ActiveCfg = Release|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|Win32.Build.0 = Release|Win32 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|x64.ActiveCfg = Release|x64 + {A231973E-072A-428E-982E-5363ADD1CDE2}.Release|x64.Build.0 = Release|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug|Win32.ActiveCfg = Debug|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug|Win32.Build.0 = Debug|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug|x64.ActiveCfg = Debug|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug|x64.Build.0 = Debug|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release|Win32.ActiveCfg = Release|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release|Win32.Build.0 = Release|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release|x64.ActiveCfg = Release|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release|x64.Build.0 = Release|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease|Win32.ActiveCfg = Debug|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease|Win32.Build.0 = Debug|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease|x64.ActiveCfg = Debug|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease|x64.Build.0 = Debug|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|Win32.ActiveCfg = Debug|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|Win32.Build.0 = Debug|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|x64.ActiveCfg = Debug|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|x64.Build.0 = Debug|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|Win32.ActiveCfg = Release|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|Win32.Build.0 = Release|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|x64.ActiveCfg = Release|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|x64.Build.0 = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_StaticCrt|Win32.ActiveCfg = Debug|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_StaticCrt|Win32.Build.0 = Debug|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_StaticCrt|x64.ActiveCfg = Debug|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_StaticCrt|x64.Build.0 = Debug|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease_StaticCrt|x64.Build.0 = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease|Win32.ActiveCfg = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease|Win32.Build.0 = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease|x64.ActiveCfg = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease|x64.Build.0 = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug|Win32.ActiveCfg = Debug|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug|Win32.Build.0 = Debug|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug|x64.ActiveCfg = Debug|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug|x64.Build.0 = Debug|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release_StaticCrt|Win32.ActiveCfg = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release_StaticCrt|Win32.Build.0 = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release_StaticCrt|x64.ActiveCfg = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release_StaticCrt|x64.Build.0 = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release|Win32.ActiveCfg = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release|Win32.Build.0 = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release|x64.ActiveCfg = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release|x64.Build.0 = Release|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug|Win32.ActiveCfg = Debug|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug|Win32.Build.0 = Debug|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug|x64.ActiveCfg = Debug|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug|x64.Build.0 = Debug|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release|Win32.ActiveCfg = Release|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release|Win32.Build.0 = Release|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release|x64.ActiveCfg = Release|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release|x64.Build.0 = Release|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug|Win32.ActiveCfg = Debug|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug|Win32.Build.0 = Debug|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug|x64.ActiveCfg = Debug|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug|x64.Build.0 = Debug|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release|Win32.ActiveCfg = Release|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release|Win32.Build.0 = Release|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release|x64.ActiveCfg = Release|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release|x64.Build.0 = Release|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug|Win32.ActiveCfg = Debug|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug|Win32.Build.0 = Debug|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug|x64.ActiveCfg = Debug|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug|x64.Build.0 = Debug|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release|Win32.ActiveCfg = Release|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release|Win32.Build.0 = Release|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release|x64.ActiveCfg = Release|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release|x64.Build.0 = Release|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug|Win32.ActiveCfg = Debug|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug|Win32.Build.0 = Debug|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug|x64.ActiveCfg = Debug|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug|x64.Build.0 = Debug|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release|Win32.ActiveCfg = Release|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release|Win32.Build.0 = Release|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release|x64.ActiveCfg = Release|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release|x64.Build.0 = Release|x64 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug|Win32.ActiveCfg = Debug|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug|Win32.Build.0 = Debug|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug|x64.ActiveCfg = Debug|x64 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Debug|x64.Build.0 = Debug|x64 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Release|Win32.ActiveCfg = Release|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Release|Win32.Build.0 = Release|Win32 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Release|x64.ActiveCfg = Release|x64 + {3719F504-3DF0-45F8-BC7A-4415804AC7C9}.Release|x64.Build.0 = Release|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug|Win32.ActiveCfg = Debug|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug|Win32.Build.0 = Debug|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug|x64.ActiveCfg = Debug|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug|x64.Build.0 = Debug|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release|Win32.ActiveCfg = Release|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release|Win32.Build.0 = Release|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release|x64.ActiveCfg = Release|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {0943354A-41E0-4215-878A-8D0FE758052C} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {EE4A829C-5FD8-460B-8A90-B518B9BABB70} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4} = {281D5ACB-9ED2-496B-B19E-A75F4D4DA111} + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {2178E5B2-1032-441F-A664-F3D8D1FD1913} = {281D5ACB-9ED2-496B-B19E-A75F4D4DA111} + {A231973E-072A-428E-982E-5363ADD1CDE2} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {87911ED6-84BC-4526-9654-A4FF4E0EDF52} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {281D5ACB-9ED2-496B-B19E-A75F4D4DA111} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7} = {9FD1911C-3FAB-48DE-BE31-9F2C7B1EB58C} + {9FD1911C-3FAB-48DE-BE31-9F2C7B1EB58C} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17} = {9FD1911C-3FAB-48DE-BE31-9F2C7B1EB58C} + {8C732490-DC1A-40C0-923F-1555B9141B80} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {50C94B05-8C3E-49ED-B2B9-5715EB624D14} = {281D5ACB-9ED2-496B-B19E-A75F4D4DA111} + {33F98E06-F44C-4E22-9E16-4C20F8238A95} = {281D5ACB-9ED2-496B-B19E-A75F4D4DA111} + {3719F504-3DF0-45F8-BC7A-4415804AC7C9} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + EndGlobalSection +EndGlobal diff --git a/vld_vs14_wo_mfc.sln b/vld_vs14_wo_mfc.sln new file mode 100644 index 00000000..aae24504 --- /dev/null +++ b/vld_vs14_wo_mfc.sln @@ -0,0 +1,410 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.24720.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vld", "src\vld.vcxproj", "{0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_basics", "src\tests\basics\basics.vcxproj", "{0943354A-41E0-4215-878A-8D0FE758052C}" + ProjectSection(ProjectDependencies) = postProject + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} = {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testsuite", "src\tests\suite\testsuite.vcxproj", "{EE4A829C-5FD8-460B-8A90-B518B9BABB70}" + ProjectSection(ProjectDependencies) = postProject + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} = {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dynamic", "src\tests\dynamic_dll\dynamic.vcxproj", "{3AEA2AAF-3E9B-466F-B361-560B95AD88B4}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dynamic_app", "src\tests\dynamic_app\dynamic_app.vcxproj", "{5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}" + ProjectSection(ProjectDependencies) = postProject + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4} = {3AEA2AAF-3E9B-466F-B361-560B95AD88B4} + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} = {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "corruption", "src\tests\corruption\corruption.vcxproj", "{87911ED6-84BC-4526-9654-A4FF4E0EDF52}" + ProjectSection(ProjectDependencies) = postProject + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} = {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Dlls", "Dlls", "{281D5ACB-9ED2-496B-B19E-A75F4D4DA111}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libgtest", "lib\gtest\msvc\gtest.vcxproj", "{C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libs", "Libs", "{9FD1911C-3FAB-48DE-BE31-9F2C7B1EB58C}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libformat", "lib\cppformat\format.vcxproj", "{4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vld_main", "src\tests\vld_main\vld_main_vs14.vcxproj", "{8C732490-DC1A-40C0-923F-1555B9141B80}" + ProjectSection(ProjectDependencies) = postProject + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} = {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vld_unload", "src\tests\vld_unload\vld_unload_vs14.vcxproj", "{A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}" + ProjectSection(ProjectDependencies) = postProject + {50C94B05-8C3E-49ED-B2B9-5715EB624D14} = {50C94B05-8C3E-49ED-B2B9-5715EB624D14} + {33F98E06-F44C-4E22-9E16-4C20F8238A95} = {33F98E06-F44C-4E22-9E16-4C20F8238A95} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vld_dll1", "src\tests\vld_dll1\vld_dll1_vs14.vcxproj", "{50C94B05-8C3E-49ED-B2B9-5715EB624D14}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vld_dll2", "src\tests\vld_dll2\vld_dll2_vs14.vcxproj", "{33F98E06-F44C-4E22-9E16-4C20F8238A95}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "vld_main_test", "src\tests\vld_main_test\vld_main_test_vs14.vcxproj", "{BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}" + ProjectSection(ProjectDependencies) = postProject + {8C732490-DC1A-40C0-923F-1555B9141B80} = {8C732490-DC1A-40C0-923F-1555B9141B80} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug_StaticCrt|Win32 = Debug_StaticCrt|Win32 + Debug_StaticCrt|x64 = Debug_StaticCrt|x64 + Debug_VldRelease_StaticCrt|Win32 = Debug_VldRelease_StaticCrt|Win32 + Debug_VldRelease_StaticCrt|x64 = Debug_VldRelease_StaticCrt|x64 + Debug_VldRelease|Win32 = Debug_VldRelease|Win32 + Debug_VldRelease|x64 = Debug_VldRelease|x64 + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release_StaticCrt|Win32 = Release_StaticCrt|Win32 + Release_StaticCrt|x64 = Release_StaticCrt|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_StaticCrt|Win32.ActiveCfg = Debug|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_StaticCrt|Win32.Build.0 = Debug|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_StaticCrt|x64.ActiveCfg = Debug|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_StaticCrt|x64.Build.0 = Debug|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Release|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease_StaticCrt|x64.Build.0 = Release|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease|Win32.ActiveCfg = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease|Win32.Build.0 = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease|x64.ActiveCfg = Release|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug_VldRelease|x64.Build.0 = Release|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug|Win32.ActiveCfg = Debug|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug|Win32.Build.0 = Debug|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug|x64.ActiveCfg = Debug|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Debug|x64.Build.0 = Debug|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release_StaticCrt|Win32.ActiveCfg = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release_StaticCrt|Win32.Build.0 = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release_StaticCrt|x64.ActiveCfg = Release|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release_StaticCrt|x64.Build.0 = Release|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release|Win32.ActiveCfg = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release|Win32.Build.0 = Release|Win32 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release|x64.ActiveCfg = Release|x64 + {0D30FFCB-45DA-4D2B-8E3C-81BC145BF2DE}.Release|x64.Build.0 = Release|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug|Win32.ActiveCfg = Debug|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug|Win32.Build.0 = Debug|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug|x64.ActiveCfg = Debug|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Debug|x64.Build.0 = Debug|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release|Win32.ActiveCfg = Release|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release|Win32.Build.0 = Release|Win32 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release|x64.ActiveCfg = Release|x64 + {0943354A-41E0-4215-878A-8D0FE758052C}.Release|x64.Build.0 = Release|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_StaticCrt|x64.Deploy.0 = Debug_StaticCrt|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug|Win32.ActiveCfg = Debug|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug|Win32.Build.0 = Debug|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug|x64.ActiveCfg = Debug|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Debug|x64.Build.0 = Debug|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release|Win32.ActiveCfg = Release|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release|Win32.Build.0 = Release|Win32 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release|x64.ActiveCfg = Release|x64 + {EE4A829C-5FD8-460B-8A90-B518B9BABB70}.Release|x64.Build.0 = Release|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug|Win32.ActiveCfg = Debug|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug|Win32.Build.0 = Debug|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug|x64.ActiveCfg = Debug|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Debug|x64.Build.0 = Debug|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release|Win32.ActiveCfg = Release|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release|Win32.Build.0 = Release|Win32 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release|x64.ActiveCfg = Release|x64 + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4}.Release|x64.Build.0 = Release|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug|Win32.ActiveCfg = Debug|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug|Win32.Build.0 = Debug|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug|x64.ActiveCfg = Debug|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Debug|x64.Build.0 = Debug|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release|Win32.ActiveCfg = Release|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release|Win32.Build.0 = Release|Win32 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release|x64.ActiveCfg = Release|x64 + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA}.Release|x64.Build.0 = Release|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug|Win32.ActiveCfg = Debug|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug|Win32.Build.0 = Debug|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug|x64.ActiveCfg = Debug|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Debug|x64.Build.0 = Debug|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release|Win32.ActiveCfg = Release|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release|Win32.Build.0 = Release|Win32 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release|x64.ActiveCfg = Release|x64 + {87911ED6-84BC-4526-9654-A4FF4E0EDF52}.Release|x64.Build.0 = Release|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease|Win32.ActiveCfg = Debug|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease|Win32.Build.0 = Debug|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease|x64.ActiveCfg = Debug|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug_VldRelease|x64.Build.0 = Debug|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|Win32.ActiveCfg = Debug|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|Win32.Build.0 = Debug|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|x64.ActiveCfg = Debug|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Debug|x64.Build.0 = Debug|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|Win32.ActiveCfg = Release|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|Win32.Build.0 = Release|Win32 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|x64.ActiveCfg = Release|x64 + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7}.Release|x64.Build.0 = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_StaticCrt|Win32.ActiveCfg = Debug|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_StaticCrt|Win32.Build.0 = Debug|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_StaticCrt|x64.ActiveCfg = Debug|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_StaticCrt|x64.Build.0 = Debug|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease_StaticCrt|x64.Build.0 = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease|Win32.ActiveCfg = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease|Win32.Build.0 = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease|x64.ActiveCfg = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug_VldRelease|x64.Build.0 = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug|Win32.ActiveCfg = Debug|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug|Win32.Build.0 = Debug|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug|x64.ActiveCfg = Debug|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Debug|x64.Build.0 = Debug|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release_StaticCrt|Win32.ActiveCfg = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release_StaticCrt|Win32.Build.0 = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release_StaticCrt|x64.ActiveCfg = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release_StaticCrt|x64.Build.0 = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release|Win32.ActiveCfg = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release|Win32.Build.0 = Release|Win32 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release|x64.ActiveCfg = Release|x64 + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17}.Release|x64.Build.0 = Release|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug|Win32.ActiveCfg = Debug|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug|Win32.Build.0 = Debug|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug|x64.ActiveCfg = Debug|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Debug|x64.Build.0 = Debug|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release|Win32.ActiveCfg = Release|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release|Win32.Build.0 = Release|Win32 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release|x64.ActiveCfg = Release|x64 + {8C732490-DC1A-40C0-923F-1555B9141B80}.Release|x64.Build.0 = Release|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug|Win32.ActiveCfg = Debug|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug|Win32.Build.0 = Debug|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug|x64.ActiveCfg = Debug|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Debug|x64.Build.0 = Debug|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release|Win32.ActiveCfg = Release|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release|Win32.Build.0 = Release|Win32 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release|x64.ActiveCfg = Release|x64 + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814}.Release|x64.Build.0 = Release|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug|Win32.ActiveCfg = Debug|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug|Win32.Build.0 = Debug|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug|x64.ActiveCfg = Debug|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Debug|x64.Build.0 = Debug|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release|Win32.ActiveCfg = Release|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release|Win32.Build.0 = Release|Win32 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release|x64.ActiveCfg = Release|x64 + {50C94B05-8C3E-49ED-B2B9-5715EB624D14}.Release|x64.Build.0 = Release|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug|Win32.ActiveCfg = Debug|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug|Win32.Build.0 = Debug|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug|x64.ActiveCfg = Debug|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Debug|x64.Build.0 = Debug|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release|Win32.ActiveCfg = Release|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release|Win32.Build.0 = Release|Win32 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release|x64.ActiveCfg = Release|x64 + {33F98E06-F44C-4E22-9E16-4C20F8238A95}.Release|x64.Build.0 = Release|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_StaticCrt|Win32.ActiveCfg = Debug_StaticCrt|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_StaticCrt|Win32.Build.0 = Debug_StaticCrt|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_StaticCrt|x64.ActiveCfg = Debug_StaticCrt|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_StaticCrt|x64.Build.0 = Debug_StaticCrt|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease_StaticCrt|Win32.ActiveCfg = Debug(Release)_StaticCrt|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease_StaticCrt|Win32.Build.0 = Debug(Release)_StaticCrt|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease_StaticCrt|x64.ActiveCfg = Debug(Release)_StaticCrt|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease_StaticCrt|x64.Build.0 = Debug(Release)_StaticCrt|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease|Win32.ActiveCfg = Debug(Release)|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease|Win32.Build.0 = Debug(Release)|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease|x64.ActiveCfg = Debug(Release)|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug_VldRelease|x64.Build.0 = Debug(Release)|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug|Win32.ActiveCfg = Debug|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug|Win32.Build.0 = Debug|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug|x64.ActiveCfg = Debug|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Debug|x64.Build.0 = Debug|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release_StaticCrt|Win32.ActiveCfg = Release_StaticCrt|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release_StaticCrt|Win32.Build.0 = Release_StaticCrt|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release_StaticCrt|x64.ActiveCfg = Release_StaticCrt|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release_StaticCrt|x64.Build.0 = Release_StaticCrt|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release|Win32.ActiveCfg = Release|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release|Win32.Build.0 = Release|Win32 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release|x64.ActiveCfg = Release|x64 + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {0943354A-41E0-4215-878A-8D0FE758052C} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {EE4A829C-5FD8-460B-8A90-B518B9BABB70} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {3AEA2AAF-3E9B-466F-B361-560B95AD88B4} = {281D5ACB-9ED2-496B-B19E-A75F4D4DA111} + {5C25E1C8-00CB-4E0A-9BEC-952F0A6E5DCA} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {87911ED6-84BC-4526-9654-A4FF4E0EDF52} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {281D5ACB-9ED2-496B-B19E-A75F4D4DA111} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {C8F6C172-56F2-4E76-B5FA-C3B423B31BE7} = {9FD1911C-3FAB-48DE-BE31-9F2C7B1EB58C} + {9FD1911C-3FAB-48DE-BE31-9F2C7B1EB58C} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {4ADFD279-56C6-4B1D-BA9E-B815E81C1B17} = {9FD1911C-3FAB-48DE-BE31-9F2C7B1EB58C} + {8C732490-DC1A-40C0-923F-1555B9141B80} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {A8EEDB38-1E5A-4D6E-A3E0-F15EF1F2E814} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + {50C94B05-8C3E-49ED-B2B9-5715EB624D14} = {281D5ACB-9ED2-496B-B19E-A75F4D4DA111} + {33F98E06-F44C-4E22-9E16-4C20F8238A95} = {281D5ACB-9ED2-496B-B19E-A75F4D4DA111} + {BB99EDE9-D039-4169-B26B-6BFD93C6AF8E} = {9F9CFA3A-F154-4069-89E3-19BDC6BD3A7D} + EndGlobalSection +EndGlobal diff --git a/vldapi.cpp b/vldapi.cpp deleted file mode 100644 index 88d0a531..00000000 --- a/vldapi.cpp +++ /dev/null @@ -1,68 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - Exported APIs -// Copyright (c) 2005-2006 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#define VLDBUILD // Declares that we are building Visual Leak Detector. -#include "vldint.h" // Provides access to the Visual Leak Detector internals. -#include "vldheap.h" // Provides internal new and delete operators. - -// Imported global variables. -extern VisualLeakDetector vld; - -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector APIs - see vldapi.h for each function's details. -// - -extern "C" __declspec(dllexport) void VLDDisable () -{ - tls_t *tls; - - if (vld.m_options & VLD_OPT_VLDOFF) { - // VLD has been turned off. - return; - } - - // Disable memory leak detection for the current thread. There are two flags - // because if neither flag is set, it means that we are in the default or - // "starting" state, which could be either enabled or disabled depending on - // the configuration. - tls = vld.gettls(); - tls->flags &= ~VLD_TLS_ENABLED; - tls->flags |= VLD_TLS_DISABLED; -} - -extern "C" __declspec(dllexport) void VLDEnable () -{ - tls_t *tls; - - if (vld.m_options & VLD_OPT_VLDOFF) { - // VLD has been turned off. - return; - } - - // Enable memory leak detection for the current thread. - tls = vld.gettls(); - tls->flags &= ~VLD_TLS_DISABLED; - tls->flags |= VLD_TLS_ENABLED; - vld.m_status &= ~VLD_STATUS_NEVER_ENABLED; -} diff --git a/vldint.h b/vldint.h deleted file mode 100644 index 1646341c..00000000 --- a/vldint.h +++ /dev/null @@ -1,292 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Visual Leak Detector - VisualLeakDetector Class Definition -// Copyright (c) 2005-2009 Dan Moulding -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// -// See COPYING.txt for the full terms of the GNU Lesser General Public License. -// -//////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef VLDBUILD -#error \ -"This header should only be included by Visual Leak Detector when building it from source. \ -Applications should never include this header." -#endif - -#include -#include -#include "callstack.h" // Provides a custom class for handling call stacks. -#include "map.h" // Provides a custom STL-like map template. -#include "ntapi.h" // Provides access to NT APIs. -#include "set.h" // Provides a custom STL-like set template. -#include "utility.h" // Provides miscellaneous utility functions. - -#define MAXMODULELISTLENGTH 512 // Maximum module list length, in characters. -#define SELFTESTTEXTA "Memory Leak Self-Test" -#define SELFTESTTEXTW L"Memory Leak Self-Test" -#define VLDREGKEYPRODUCT L"Software\\Visual Leak Detector" -#define VLDVERSION L"1.9h" - -// The Visual Leak Detector APIs. -extern "C" __declspec(dllexport) void VLDDisable (); -extern "C" __declspec(dllexport) void VLDEnable (); - -// Function pointer types for explicit dynamic linking with functions listed in -// the import patch table. -typedef void* (__cdecl *_calloc_dbg_t) (size_t, size_t, int, const char*, int); -typedef void* (__cdecl *_malloc_dbg_t) (size_t, int, const char *, int); -typedef void* (__cdecl *_realloc_dbg_t) (void *, size_t, int, const char *, int); -typedef void* (__cdecl *calloc_t) (size_t, size_t); -typedef HRESULT (__stdcall *CoGetMalloc_t) (DWORD, LPMALLOC *); -typedef LPVOID (__stdcall *CoTaskMemAlloc_t) (ULONG); -typedef LPVOID (__stdcall *CoTaskMemRealloc_t) (LPVOID, ULONG); -typedef void* (__cdecl *malloc_t) (size_t); -typedef void* (__cdecl *new_t) (size_t); -typedef void* (__cdecl *new_dbg_crt_t) (size_t, int, const char *, int); -typedef void* (__cdecl *new_dbg_mfc_t) (size_t, const char *, int); -typedef void* (__cdecl *realloc_t) (void *, size_t); - -// Data is collected for every block allocated from any heap in the process. -// The data is stored in this structure and these structures are stored in -// a BlockMap which maps each of these structures to its corresponding memory -// block. -typedef struct blockinfo_s { - CallStack *callstack; - SIZE_T serialnumber; - SIZE_T size; -} blockinfo_t; - -// BlockMaps map memory blocks (via their addresses) to blockinfo_t structures. -typedef Map BlockMap; - -// Information about each heap in the process is kept in this map. Primarily -// this is used for mapping heaps to all of the blocks allocated from those -// heaps. -typedef struct heapinfo_s { - BlockMap blockmap; // Map of all blocks allocated from this heap. - UINT32 flags; // Heap status flags: -#define VLD_HEAP_CRT 0x1 // If set, this heap is a CRT heap (i.e. the CRT uses it for new/malloc). -} heapinfo_t; - -// HeapMaps map heaps (via their handles) to BlockMaps. -typedef Map HeapMap; - -// This structure stores information, primarily the virtual address range, about -// a given module and can be used with the Set template because it supports the -// '<' operator (sorts by virtual address range). -typedef struct moduleinfo_s { - BOOL operator < (const struct moduleinfo_s &other) const - { - if (addrhigh < other.addrlow) { - return TRUE; - } - else { - return FALSE; - } - } - - SIZE_T addrhigh; // Highest address within the module's virtual address space (i.e. base + size). - SIZE_T addrlow; // Lowest address within the module's virtual address space (i.e. base address). - UINT32 flags; // Module flags: -#define VLD_MODULE_EXCLUDED 0x1 // If set, this module is excluded from leak detection. -#define VLD_MODULE_SYMBOLSLOADED 0x2 // If set, this module's debug symbols have been loaded. - LPCSTR name; // The module's name (e.g. "kernel32.dll"). - LPCSTR path; // The fully qualified path from where the module was loaded. -} moduleinfo_t; - -// ModuleSets store information about modules loaded in the process. -typedef Set ModuleSet; - -// Thread local storage structure. Every thread in the process gets its own copy -// of this structure. Thread specific information, such as the current leak -// detection status (enabled or disabled) and the address that initiated the -// current allocation is stored here. -typedef struct tls_s { - SIZE_T addrfp; // Frame pointer at the first call that entered VLD's code for the current allocation. - UINT32 flags; // Thread-local status flags: -#define VLD_TLS_CRTALLOC 0x1 // If set, the current allocation is a CRT allocation. -#define VLD_TLS_DISABLED 0x2 // If set, memory leak detection is disabled for the current thread. -#define VLD_TLS_ENABLED 0x4 // If set, memory leak detection is enabled for the current thread. - DWORD threadid; // Thread ID of the thread that owns this TLS structure. -} tls_t; - -// The TlsSet allows VLD to keep track of all thread local storage structures -// allocated in the process. -typedef Set TlsSet; - -//////////////////////////////////////////////////////////////////////////////// -// -// The VisualLeakDetector Class -// -// One global instance of this class is instantiated. Upon construction it -// patches the import address table (IAT) of every other module loaded in the -// process (see the "patchimport" utility function) to allow key Windows heap -// APIs to be patched through to, or redirected to, functions provided by VLD. -// Patching the IATs in this manner allows VLD to be made aware of all -// relevant heap activity, making it possible for VLD to detect and trace -// memory leaks. -// -// The one global instance of this class is constructed within the context of -// the process' main thread during process initialization and is destroyed in -// the same context during process termination. -// -// When the VisualLeakDetector object is destroyed, it consults its internal -// datastructures, looking for any memory that has not been freed. A memory -// leak report is then generated, indicating any memory leaks that may have -// been identified. -// -// This class is derived from IMalloc so that it can provide an implementation -// of the IMalloc COM interface in order to support detection of COM-based -// memory leaks. However, this implementation of IMalloc is actually just a -// thin wrapper around the system's implementation of IMalloc. -// -class VisualLeakDetector : public IMalloc -{ -public: - VisualLeakDetector(); - ~VisualLeakDetector(); - -//////////////////////////////////////////////////////////////////////////////// -// Public CRT and MFC Common Handlers -// -// Many heap functions are indirectly rerouted to these handlers. One common -// function exists for each heap function with a given signature. These -// handlers are not direct IAT replacements, but are called by the individual -// IAT replacement functions. -//////////////////////////////////////////////////////////////////////////////// - // Standard CRT and MFC common handlers - void* _calloc (calloc_t pcalloc, SIZE_T fp, size_t num, size_t size); - void* _malloc (malloc_t pmalloc, SIZE_T fp, size_t size); - void* _new (new_t pnew, SIZE_T fp, size_t size); - void* _realloc (realloc_t prealloc, SIZE_T fp, void *mem, size_t size); - - // Debug CRT and MFC common handlers - void* __calloc_dbg (_calloc_dbg_t p_calloc_dbg, SIZE_T fp, size_t num, size_t size, int type, char const *file, int line); - void* __malloc_dbg (_malloc_dbg_t p_malloc_dbg, SIZE_T fp, size_t size, int type, char const *file, int line); - void* new_dbg_crt (new_dbg_crt_t pnew_dbg_crt, SIZE_T fp, size_t size, int type, char const *file, int line); - void* new_dbg_mfc (new_dbg_crt_t pnew_dbg, SIZE_T fp, size_t size, int type, char const *file, int line); - void* new_dbg_mfc (new_dbg_mfc_t pnew_dbg_mfc, SIZE_T fp, size_t size, char const *file, int line); - void* __realloc_dbg (_realloc_dbg_t p_realloc_dbg, SIZE_T fp, void *mem, size_t size, int type, char const *file, int line); - -//////////////////////////////////////////////////////////////////////////////// -// Public IMalloc methods - for support of COM-based memory leak detection. -//////////////////////////////////////////////////////////////////////////////// - ULONG __stdcall AddRef (); - LPVOID __stdcall Alloc (ULONG size); - INT __stdcall DidAlloc (LPVOID mem); - VOID __stdcall Free (LPVOID mem); - ULONG __stdcall GetSize (LPVOID mem); - VOID __stdcall HeapMinimize (); - HRESULT __stdcall QueryInterface (REFIID iid, LPVOID *object); - LPVOID __stdcall Realloc (LPVOID mem, ULONG size); - ULONG __stdcall Release (); - -private: -//////////////////////////////////////////////////////////////////////////////// -// Private leak detection functions - see each function definition for details. -//////////////////////////////////////////////////////////////////////////////// - VOID attachtoloadedmodules (ModuleSet *newmodules); - LPWSTR buildsymbolsearchpath (); - VOID configure (); - BOOL enabled (); - SIZE_T eraseduplicates (const BlockMap::Iterator &element); - tls_t* gettls (); - VOID mapblock (HANDLE heap, LPCVOID mem, SIZE_T size, SIZE_T framepointer, BOOL crtalloc); - VOID mapheap (HANDLE heap); - VOID remapblock (HANDLE heap, LPCVOID mem, LPCVOID newmem, SIZE_T size, SIZE_T framepointer, BOOL crtalloc); - VOID reportconfig (); - VOID reportleaks (HANDLE heap); - VOID unmapblock (HANDLE heap, LPCVOID mem); - VOID unmapheap (HANDLE heap); - - // Static functions (callbacks) - static BOOL __stdcall addloadedmodule (PCWSTR modulepath, DWORD64 modulebase, ULONG modulesize, PVOID context); - static BOOL __stdcall detachfrommodule (PCWSTR modulepath, DWORD64 modulebase, ULONG modulesize, PVOID context); - -//////////////////////////////////////////////////////////////////////////////// -// IAT replacement functions - see each function definition for details. -// -// Because there are so many virtually identical CRT and MFC replacement -// functions, they are excluded from the class to reduce the amount of noise -// within this class's code. See crtmfcpatch.cpp for those functions. -//////////////////////////////////////////////////////////////////////////////// - // Win32 IAT replacement functions - static FARPROC __stdcall _GetProcAddress (HMODULE module, LPCSTR procname); - static HANDLE __stdcall _HeapCreate (DWORD options, SIZE_T initsize, SIZE_T maxsize); - static BOOL __stdcall _HeapDestroy (HANDLE heap); - static NTSTATUS __stdcall _LdrLoadDll (LPWSTR searchpath, PDWORD flags, unicodestring_t *modulename, - PHANDLE modulehandle); - static LPVOID __stdcall _RtlAllocateHeap (HANDLE heap, DWORD flags, SIZE_T size); - static BOOL __stdcall _RtlFreeHeap (HANDLE heap, DWORD flags, LPVOID mem); - static LPVOID __stdcall _RtlReAllocateHeap (HANDLE heap, DWORD flags, LPVOID mem, SIZE_T size); - - // COM IAT replacement functions - static HRESULT __stdcall _CoGetMalloc (DWORD context, LPMALLOC *imalloc); - static LPVOID __stdcall _CoTaskMemAlloc (ULONG size); - static LPVOID __stdcall _CoTaskMemRealloc (LPVOID mem, ULONG size); - -//////////////////////////////////////////////////////////////////////////////// -// Private data -//////////////////////////////////////////////////////////////////////////////// - WCHAR m_forcedmodulelist [MAXMODULELISTLENGTH]; // List of modules to be forcefully included in leak detection. - HeapMap *m_heapmap; // Map of all active heaps in the process. - IMalloc *m_imalloc; // Pointer to the system implementation of IMalloc. - SIZE_T m_leaksfound; // Total number of leaks found. - ModuleSet *m_loadedmodules; // Contains information about all modules loaded in the process. - CRITICAL_SECTION m_loaderlock; // Serializes the attachment of newly loaded modules. - CRITICAL_SECTION m_maplock; // Serializes access to the heap and block maps. - SIZE_T m_maxdatadump; // Maximum number of user-data bytes to dump for each leaked block. - UINT32 m_maxtraceframes; // Maximum number of frames per stack trace for each leaked block. - CRITICAL_SECTION m_moduleslock; // Protects accesses to the "loaded modules" ModuleSet. - UINT32 m_options; // Configuration options: -#define VLD_OPT_AGGREGATE_DUPLICATES 0x1 // If set, aggregate duplicate leaks in the leak report. -#define VLD_OPT_MODULE_LIST_INCLUDE 0x2 // If set, modules in the module list are included, all others are excluded. -#define VLD_OPT_REPORT_TO_DEBUGGER 0x4 // If set, the memory leak report is sent to the debugger. -#define VLD_OPT_REPORT_TO_FILE 0x8 // If set, the memory leak report is sent to a file. -#define VLD_OPT_SAFE_STACK_WALK 0x10 // If set, the stack is walked using the "safe" method (StackWalk64). -#define VLD_OPT_SELF_TEST 0x20 // If set, peform a self-test to verify memory leak self-checking. -#define VLD_OPT_SLOW_DEBUGGER_DUMP 0x40 // If set, inserts a slight delay between sending output to the debugger. -#define VLD_OPT_START_DISABLED 0x80 // If set, memory leak detection will initially disabled. -#define VLD_OPT_TRACE_INTERNAL_FRAMES 0x100 // If set, include useless frames (e.g. internal to VLD) in call stacks. -#define VLD_OPT_UNICODE_REPORT 0x200 // If set, the leak report will be encoded UTF-16 instead of ASCII. -#define VLD_OPT_VLDOFF 0x400 // If set, VLD will be completely deactivated. It will not attach to any modules. - static patchentry_t m_patchtable []; // Table of imports patched for attaching VLD to other modules. - FILE *m_reportfile; // File where the memory leak report may be sent to. - WCHAR m_reportfilepath [MAX_PATH]; // Full path and name of file to send memory leak report to. - const char *m_selftestfile; // Filename where the memory leak self-test block is leaked. - int m_selftestline; // Line number where the memory leak self-test block is leaked. - UINT32 m_status; // Status flags: -#define VLD_STATUS_DBGHELPLINKED 0x1 // If set, the explicit dynamic link to the Debug Help Library succeeded. -#define VLD_STATUS_INSTALLED 0x2 // If set, VLD was successfully installed. -#define VLD_STATUS_NEVER_ENABLED 0x4 // If set, VLD started disabled, and has not yet been manually enabled. -#define VLD_STATUS_FORCE_REPORT_TO_FILE 0x8 // If set, the leak report is being forced to a file. - DWORD m_tlsindex; // Thread-local storage index. - CRITICAL_SECTION m_tlslock; // Protects accesses to the Set of TLS structures. - TlsSet *m_tlsset; // Set of all all thread-local storage structres for the process. - HMODULE m_vldbase; // Visual Leak Detector's own module handle (base address). - - // The Visual Leak Detector APIs are our friends. - friend __declspec(dllexport) void VLDDisable (); - friend __declspec(dllexport) void VLDEnable (); -}; - -// Configuration option default values -#define VLD_DEFAULT_MAX_DATA_DUMP 256 -#define VLD_DEFAULT_MAX_TRACE_FRAMES 64 -#define VLD_DEFAULT_REPORT_FILE_NAME L".\\memory_leak_report.txt"