OVR_DebugHelp.cpp 171 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241
  1. /************************************************************************************
  2. Filename : ExceptionHandler.cpp
  3. Content : Platform-independent exception handling interface
  4. Created : October 6, 2014
  5. Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
  6. Licensed under the Apache License, Version 2.0 (the "License");
  7. you may not use this file except in compliance with the License.
  8. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. ************************************************************************************/
  16. #include "OVR_DebugHelp.h"
  17. #include "OVR_Types.h"
  18. #include "OVR_UTF8Util.h"
  19. #include "OVR_Atomic.h"
  20. #include "OVR_SysFile.h"
  21. #include "Util/Util_SystemGUI.h"
  22. #include <stdlib.h>
  23. #include <time.h>
  24. #if defined(OVR_OS_WIN32) || defined(OVR_OS_WIN64)
  25. #pragma warning(push, 0)
  26. #include "OVR_Win32_IncludeWindows.h"
  27. #include <ShlObj.h>
  28. #include <WinNT.h>
  29. #include <DbgHelp.h>
  30. #include <WinVer.h>
  31. #include <share.h>
  32. #include <Psapi.h>
  33. #include <TlHelp32.h>
  34. #include <comutil.h>
  35. #include <Wbemcli.h>
  36. #include <Wbemidl.h>
  37. #include <ObjBase.h>
  38. #include <process.h>
  39. #pragma warning(pop)
  40. #pragma comment(lib, "Psapi.lib") // To consider: It may be a problem to statically link to these libraries if the application at runtime intends to dynamically
  41. #pragma comment(lib, "ole32.lib") // link to a different version of the same library, and we are statically linked into that application instead of being a DLL.
  42. #pragma comment(lib, "shell32.lib")
  43. #pragma comment(lib, "Version.lib")
  44. // NtQueryInformation and THREAD_BASIC_INFORMATION are undocumented but frequently needed for digging into thread information.
  45. typedef LONG (WINAPI *NtQueryInformationThreadFunc)(HANDLE, int, PVOID, ULONG, PULONG);
  46. struct THREAD_BASIC_INFORMATION
  47. {
  48. LONG ExitStatus;
  49. PVOID TebBaseAddress;
  50. PVOID UniqueProcessId;
  51. PVOID UniqueThreadId;
  52. PVOID Priority;
  53. PVOID BasePriority;
  54. };
  55. #ifndef UNW_FLAG_NHANDLER // Older Windows SDKs don't support this.
  56. #define UNW_FLAG_NHANDLER 0
  57. #endif
  58. #elif defined(OVR_OS_MAC)
  59. #include <unistd.h>
  60. #include <sys/sysctl.h>
  61. #include <sys/utsname.h>
  62. #include <sys/types.h>
  63. #include <sys/mman.h>
  64. #include <stdlib.h>
  65. #include <stdio.h>
  66. #include <pthread.h>
  67. #include <mach/mach.h>
  68. #include <mach/mach_error.h>
  69. #include <mach/thread_status.h>
  70. #include <mach/exception.h>
  71. #include <mach/task.h>
  72. #include <mach/thread_act.h>
  73. #include <mach-o/dyld.h>
  74. #include <mach-o/dyld_images.h>
  75. #include <libproc.h>
  76. #include <libgen.h>
  77. #include <execinfo.h>
  78. #include <cxxabi.h>
  79. #include "OVR_mach_exc_OSX.h"
  80. #if defined(__LP64__)
  81. typedef struct mach_header_64 MachHeader;
  82. typedef struct segment_command_64 SegmentCommand;
  83. typedef struct section_64 Section;
  84. #define kLCSegment LC_SEGMENT_64
  85. #else
  86. typedef struct mach_header MachHeader;
  87. typedef struct segment_command SegmentCommand;
  88. typedef struct section Section;
  89. #define kLCSegment LC_SEGMENT
  90. #endif
  91. extern "C" const struct dyld_all_image_infos* _dyld_get_all_image_infos(); // From libdyld.dylib
  92. #elif defined(OVR_OS_UNIX)
  93. #include <unistd.h>
  94. #include "sys/stat.h"
  95. #if defined(OVR_OS_ANDROID)
  96. #include <linux/sysctl.h>
  97. #else
  98. #include <sys/sysctl.h>
  99. #endif
  100. #include <sys/utsname.h>
  101. #include <sys/types.h>
  102. #include <sys/ptrace.h>
  103. #include <sys/wait.h>
  104. #include <sys/mman.h>
  105. #include <stdlib.h>
  106. #include <stdio.h>
  107. #include <pthread.h>
  108. #include <libgen.h>
  109. #if !defined(OVR_OS_ANDROID)
  110. #include <execinfo.h>
  111. #endif
  112. #include <cxxabi.h>
  113. //#include <libunwind.h> // Can't use this until we can ensure that we have an installed version of it.
  114. #endif
  115. #if !defined(MIN)
  116. #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
  117. #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
  118. #endif
  119. OVR_DISABLE_MSVC_WARNING(4351) // new behavior: elements of array will be default initialized
  120. OVR_DISABLE_MSVC_WARNING(4996) // This function or variable may be unsafe
  121. #if defined(OVR_OS_APPLE)
  122. static OVR::ExceptionHandler* sExceptionHandler = nullptr;
  123. const uint32_t sMachCancelMessageType = 0x0ca9ce11; // This is a made-up value of our own choice.
  124. extern "C"
  125. {
  126. kern_return_t catch_mach_exception_raise_OVR(mach_port_t /*exceptionPort*/, mach_port_t /*threadSysId*/,
  127. mach_port_t /*machTask*/, exception_type_t /*machExceptionType*/,
  128. mach_exception_data_t /*machExceptionData*/, mach_msg_type_number_t /*machExceptionDataCount*/)
  129. {
  130. return KERN_FAILURE;
  131. }
  132. kern_return_t catch_mach_exception_raise_state_OVR(mach_port_t /*exceptionPort*/, exception_type_t /*exceptionType*/,
  133. const mach_exception_data_t /*machExceptionData*/, mach_msg_type_number_t /*machExceptionDataCount*/,
  134. int* /*pMachExceptionFlavor*/, const thread_state_t /*threadStatePrev*/, mach_msg_type_number_t /*threaStatePrevCount*/,
  135. thread_state_t /*threadStateNew*/, mach_msg_type_number_t* /*pThreadStateNewCount*/)
  136. {
  137. return KERN_FAILURE;
  138. }
  139. kern_return_t catch_mach_exception_raise_state_identity_OVR(mach_port_t exceptionPort, mach_port_t threadSysId, mach_port_t machTask,
  140. exception_type_t exceptionType, mach_exception_data_type_t* pMachExceptionData,
  141. mach_msg_type_number_t machExceptionDataCount, int* pMachExceptionFlavor,
  142. thread_state_t threadStatePrev, mach_msg_type_number_t threadStatePrevCount,
  143. thread_state_t threadStateNew, mach_msg_type_number_t* pThreadStateNewCount)
  144. {
  145. return sExceptionHandler->HandleMachException(exceptionPort, threadSysId, machTask, exceptionType, pMachExceptionData,
  146. machExceptionDataCount, pMachExceptionFlavor, threadStatePrev, threadStatePrevCount,
  147. threadStateNew, pThreadStateNewCount);
  148. }
  149. void* MachHandlerThreadFunctionStatic(void* pExceptionHandlerVoid)
  150. {
  151. return static_cast<OVR::ExceptionHandler*>(pExceptionHandlerVoid)->MachHandlerThreadFunction();
  152. }
  153. } // extern "C"
  154. #endif
  155. namespace OVR {
  156. void GetInstructionPointer(void*& pInstruction)
  157. {
  158. #if defined(OVR_CC_MSVC)
  159. pInstruction = _ReturnAddress();
  160. #else // GCC, clang
  161. pInstruction = __builtin_return_address(0);
  162. #endif
  163. }
  164. // addressStrCapacity should be at least 2+16+1 = 19 characters.
  165. static size_t SprintfAddress(char* addressStr, size_t addressStrCapacity, const void* pAddress)
  166. {
  167. #if defined(OVR_CC_MSVC)
  168. #if (OVR_PTR_SIZE >= 8)
  169. return OVR_snprintf(addressStr, addressStrCapacity, "0x%016I64x", pAddress); // e.g. 0x0123456789abcdef
  170. #else
  171. return OVR_snprintf(addressStr, addressStrCapacity, "0x%08x", pAddress); // e.g. 0x89abcdef
  172. #endif
  173. #else
  174. #if (OVR_PTR_SIZE >= 8)
  175. return OVR_snprintf(addressStr, addressStrCapacity, "%016llx", pAddress); // e.g. 0x0123456789abcdef
  176. #else
  177. return OVR_snprintf(addressStr, addressStrCapacity, "%08x", pAddress); // e.g. 0x89abcdef
  178. #endif
  179. #endif
  180. }
  181. // threadHandleStrCapacity should be at least 2+16+1 = 19 characters.
  182. static size_t SprintfThreadHandle(char* threadHandleStr, size_t threadHandleStrCapacity, const ThreadHandle& threadHandle)
  183. {
  184. return SprintfAddress(threadHandleStr, threadHandleStrCapacity, threadHandle);
  185. }
  186. // threadSysIdStrCapacity should be at least 20+4+16+2 = 42 characters.
  187. static size_t SprintfThreadSysId(char* threadSysIdStr, size_t threadSysIdStrCapacity, const ThreadSysId& threadSysId)
  188. {
  189. #if defined(OVR_CC_MSVC) // Somebody could conceivably use VC++ with a different standard library that supports %ll. And VS2012+ also support %ll.
  190. return OVR_snprintf(threadSysIdStr, threadSysIdStrCapacity, "%I64u (0x%I64x)", (uint64_t)threadSysId, (uint64_t)threadSysId); // e.g. 5642 (0x160a)
  191. #else
  192. return OVR_snprintf(threadSysIdStr, threadSysIdStrCapacity, "%llu (0x%llx)", (uint64_t)threadSysId, (uint64_t)threadSysId);
  193. #endif
  194. }
  195. void GetThreadStackBounds(void*& pStackBase, void*& pStackLimit, ThreadHandle threadHandle)
  196. {
  197. #if defined(OVR_OS_WIN64) || defined(OVR_OS_WIN32)
  198. ThreadSysId threadSysIdCurrent = (ThreadSysId)GetCurrentThreadId();
  199. ThreadSysId threadSysId;
  200. NT_TIB* pTIB = nullptr;
  201. if(threadHandle == OVR_THREADHANDLE_INVALID)
  202. threadSysId = threadSysIdCurrent;
  203. else
  204. threadSysId = ConvertThreadHandleToThreadSysId(threadHandle);
  205. if(threadSysId == threadSysIdCurrent)
  206. {
  207. #if (OVR_PTR_SIZE == 4)
  208. // Need to use __asm__("movl %%fs:0x18, %0" : "=r" (pTIB) : : ); under gcc/clang.
  209. __asm {
  210. mov eax, fs:[18h]
  211. mov pTIB, eax
  212. }
  213. #else
  214. pTIB = (NT_TIB*)NtCurrentTeb();
  215. #endif
  216. }
  217. else
  218. {
  219. #if (OVR_PTR_SIZE == 4)
  220. // It turns out we don't need to suspend the thread when getting SegFs/SegGS, as that's
  221. // constant per thread and doesn't require the thread to be suspended.
  222. //SuspendThread((HANDLE)threadHandle);
  223. CONTEXT context;
  224. memset(&context, 0, sizeof(context));
  225. context.ContextFlags = CONTEXT_SEGMENTS;
  226. GetThreadContext((HANDLE)threadHandle, &context); // Requires THREAD_QUERY_INFORMATION privileges.
  227. LDT_ENTRY ldtEntry;
  228. if(GetThreadSelectorEntry(threadHandle, context.SegFs, &ldtEntry)) // Requires THREAD_QUERY_INFORMATION
  229. pTIB = (NT_TIB*)((ldtEntry.HighWord.Bits.BaseHi << 24 ) | (ldtEntry.HighWord.Bits.BaseMid << 16) | ldtEntry.BaseLow);
  230. //ResumeThread((HANDLE)threadHandle);
  231. #else
  232. // We cannot use GetThreadSelectorEntry or Wow64GetThreadSelectorEntry on Win64.
  233. // We need to read the SegGs qword at offset 0x30. We can't use pTIB = (NT_TIB*)__readgsqword(0x30) because that reads only the current setGs offset.
  234. // mov rax, qword ptr gs:[30h]
  235. // mov qword ptr [pTIB],rax
  236. // In the meantime we rely on the NtQueryInformationThread function.
  237. static NtQueryInformationThreadFunc spNtQueryInformationThread = nullptr;
  238. if(!spNtQueryInformationThread)
  239. {
  240. HMODULE hNTDLL = GetModuleHandleA("ntdll.dll");
  241. spNtQueryInformationThread = (NtQueryInformationThreadFunc)(uintptr_t)GetProcAddress(hNTDLL, "NtQueryInformationThread");
  242. }
  243. if(spNtQueryInformationThread)
  244. {
  245. THREAD_BASIC_INFORMATION tbi;
  246. memset(&tbi, 0, sizeof(tbi));
  247. LONG result = spNtQueryInformationThread(threadHandle, 0, &tbi, sizeof(tbi), nullptr); // Requires THREAD_QUERY_INFORMATION privileges
  248. if(result == 0)
  249. pTIB = (NT_TIB*)tbi.TebBaseAddress;
  250. }
  251. #endif
  252. }
  253. if(pTIB)
  254. {
  255. pStackBase = (void*)pTIB->StackBase;
  256. pStackLimit = (void*)pTIB->StackLimit;
  257. }
  258. else
  259. {
  260. pStackBase = nullptr;
  261. pStackLimit = nullptr;
  262. }
  263. #elif defined(OVR_OS_APPLE)
  264. if(!threadHandle)
  265. threadHandle = pthread_self();
  266. pStackBase = pthread_get_stackaddr_np((pthread_t)threadHandle);
  267. size_t stackSize = pthread_get_stacksize_np((pthread_t)threadHandle);
  268. pStackLimit = (void*)((size_t)pStackBase - stackSize);
  269. #elif defined(OVR_OS_UNIX)
  270. pStackBase = nullptr;
  271. pStackLimit = nullptr;
  272. pthread_attr_t threadAttr;
  273. pthread_attr_init(&threadAttr);
  274. #if defined(OVR_OS_LINUX)
  275. int result = pthread_getattr_np((pthread_t)threadHandle, &threadAttr);
  276. #else
  277. int result = pthread_attr_get_np((pthread_t)threadHandle, &threadAttr);
  278. #endif
  279. if(result == 0)
  280. {
  281. size_t stackSize = 0;
  282. result = pthread_attr_getstack(&threadAttr, &pStackLimit, &stackSize);
  283. if(result == 0)
  284. pStackBase = (void*)((uintptr_t)pStackLimit + stackSize); // We assume the stack grows downward.
  285. }
  286. #endif
  287. }
  288. bool KillCdeclFunction(void* pFunction, int32_t functionReturnValue, SavedFunction* pSavedFunction)
  289. {
  290. #if defined(OVR_OS_MS)
  291. // The same implementation works for both 32 bit x86 and 64 bit x64.
  292. DWORD dwOldProtect;
  293. const uint8_t size = ((functionReturnValue == 0) ? 3 : 6);
  294. if(VirtualProtect(pFunction, size, PAGE_EXECUTE_READWRITE, &dwOldProtect))
  295. {
  296. if(pSavedFunction) // If the user wants to save the implementation for later restoration...
  297. {
  298. pSavedFunction->Function = pFunction;
  299. pSavedFunction->Size = size;
  300. memcpy(pSavedFunction->Data, pFunction, pSavedFunction->Size);
  301. }
  302. if(functionReturnValue == 0)
  303. {
  304. const uint8_t instructionBytes[] = { 0x33, 0xc0, 0xc3 }; // xor eax, eax; ret
  305. memcpy(pFunction, instructionBytes, sizeof(instructionBytes));
  306. }
  307. else
  308. {
  309. uint8_t instructionBytes[] = { 0xb8, 0x00, 0x00, 0x00, 0x00, 0xc3 }; // mov eax, 0x00000000; ret
  310. memcpy(instructionBytes + 1, &functionReturnValue, sizeof(int32_t)); // mov eax, functionReturnValue; ret
  311. memcpy(pFunction, instructionBytes, sizeof(instructionBytes));
  312. }
  313. VirtualProtect(pFunction, size, dwOldProtect, &dwOldProtect);
  314. return true;
  315. }
  316. #else
  317. OVR_UNUSED3(pFunction, functionReturnValue, pSavedFunction);
  318. #endif
  319. return false;
  320. }
  321. bool KillCdeclFunction(void* pFunction, SavedFunction* pSavedFunction)
  322. {
  323. #if defined(OVR_OS_MS)
  324. // The same implementation works for both 32 bit x86 and 64 bit x64.
  325. DWORD dwOldProtect;
  326. const uint8_t size = 1;
  327. if(VirtualProtect(pFunction, size, PAGE_EXECUTE_READWRITE, &dwOldProtect))
  328. {
  329. if(pSavedFunction) // If the user wants to save the implementation for later restoration...
  330. {
  331. pSavedFunction->Function = pFunction;
  332. pSavedFunction->Size = size;
  333. memcpy(pSavedFunction->Data, pFunction, pSavedFunction->Size);
  334. }
  335. const uint8_t instructionBytes[] = { 0xc3 }; // asm ret
  336. memcpy(pFunction, instructionBytes, sizeof(instructionBytes));
  337. VirtualProtect(pFunction, size, dwOldProtect, &dwOldProtect);
  338. return true;
  339. }
  340. #else
  341. OVR_UNUSED2(pFunction, pSavedFunction);
  342. #endif
  343. return false;
  344. }
  345. bool RestoreCdeclFunction(SavedFunction* pSavedFunction)
  346. {
  347. if(pSavedFunction->Size)
  348. {
  349. #if defined(OVR_OS_MS)
  350. DWORD dwOldProtect;
  351. if(VirtualProtect(pSavedFunction->Function, pSavedFunction->Size, PAGE_EXECUTE_READWRITE, &dwOldProtect))
  352. {
  353. memcpy(pSavedFunction->Function, pSavedFunction->Data, pSavedFunction->Size);
  354. VirtualProtect(pSavedFunction->Function, pSavedFunction->Size, dwOldProtect, &dwOldProtect);
  355. return true;
  356. }
  357. #else
  358. OVR_UNUSED(pSavedFunction);
  359. #endif
  360. }
  361. return false;
  362. }
  363. bool OVRIsDebuggerPresent()
  364. {
  365. #if defined(OVR_OS_MS)
  366. return ::IsDebuggerPresent() != 0;
  367. #elif defined(OVR_OS_APPLE)
  368. int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  369. struct kinfo_proc info;
  370. size_t size = sizeof(info);
  371. info.kp_proc.p_flag = 0;
  372. sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0);
  373. return ((info.kp_proc.p_flag & P_TRACED) != 0);
  374. #elif defined(PT_TRACE_ME) && !defined(OVR_OS_ANDROID)
  375. return (ptrace(PT_TRACE_ME, 0, 1, 0) < 0);
  376. #elif (defined(OVR_OS_LINUX) || defined(OVR_OS_BSD)) && !defined(OVR_OS_ANDROID)
  377. // This works better than the PT_TRACE_ME approach, but causes the debugger to get
  378. // confused when executed under a debugger.
  379. // It also presents this problem:
  380. // http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html
  381. // When the application calls fork() from a signal handler and any of the
  382. // fork handlers registered by pthread_atfork() calls a function that is
  383. // not asynch-signal-safe, the behavior is undefined.
  384. // We may need to provide two pathways within this function, one of which
  385. // doesn't fork and instead uses PT_TRACE_ME.
  386. int pid = fork();
  387. int status;
  388. bool present = false;
  389. if (pid == -1) // If fork failed...
  390. {
  391. // perror("fork");
  392. }
  393. else if (pid == 0) // If we are the child process...
  394. {
  395. int ppid = getppid();
  396. #if defined(OVR_OS_LINUX)
  397. if (ptrace(PTRACE_ATTACH, ppid, nullptr, nullptr) == 0)
  398. #else
  399. if (ptrace(PT_ATTACH, ppid, nullptr, nullptr) == 0)
  400. #endif
  401. {
  402. waitpid(ppid, nullptr, 0);
  403. #if defined(OVR_OS_LINUX)
  404. ptrace(PTRACE_CONT, getppid(), nullptr, nullptr);
  405. ptrace(PTRACE_DETACH, getppid(), nullptr, nullptr);
  406. #else
  407. ptrace(PT_CONTINUE, getppid(), nullptr, nullptr);
  408. ptrace(PT_DETACH, getppid(), nullptr, nullptr);
  409. #endif
  410. }
  411. else
  412. {
  413. // ptrace failed so the debugger is present.
  414. present = true;
  415. }
  416. exit(present ? 1 : 0); // The WEXITSTATUS call below will read this exit value.
  417. }
  418. else // Else we are the original process.
  419. {
  420. waitpid(pid, &status, 0);
  421. present = WEXITSTATUS(status) ? true : false; // Read the exit value from the child's call to exit.
  422. }
  423. return present;
  424. #else
  425. return false;
  426. #endif
  427. }
  428. // Exits the process with the given exit code.
  429. void ExitProcess(intptr_t processReturnValue)
  430. {
  431. exit((int)processReturnValue);
  432. }
  433. // Note that we can't just return sizeof(void*) == 8, as we may have the case of a
  434. // 32 bit app running on a 64 bit operating system.
  435. static bool Is64BitOS()
  436. {
  437. #if (OVR_PTR_SIZE >= 8)
  438. return true;
  439. #elif defined(OVR_OS_WIN32) || defined(OVR_OS_WIN64)
  440. BOOL is64BitOS = FALSE;
  441. bool IsWow64ProcessPresent = (GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "IsWow64Process") != nullptr);
  442. return (IsWow64ProcessPresent && IsWow64Process(GetCurrentProcess(), &is64BitOS) && is64BitOS);
  443. #elif defined(OVR_OS_MAC) || defined(OVR_OS_UNIX)
  444. utsname utsName;
  445. memset(&utsName, 0, sizeof(utsName));
  446. return (uname(&utsName) == 0) && (strcmp(utsName.machine, "x86_64") == 0);
  447. #else
  448. return false;
  449. #endif
  450. }
  451. // The output will always be 0-terminated.
  452. // Returns the required strlen of the output.
  453. // Returns (size_t)-1 on failure.
  454. size_t SpawnShellCommand(const char* shellCommand, char* output, size_t outputCapacity)
  455. {
  456. #if defined(OVR_OS_UNIX) || defined(OVR_OS_APPLE)
  457. FILE* pFile = popen(shellCommand, "r");
  458. if(pFile)
  459. {
  460. size_t requiredLength = 0;
  461. char buffer[256];
  462. while(fgets(buffer, sizeof(buffer), pFile)) // fgets 0-terminates the buffer.
  463. {
  464. size_t length = OVR_strlen(buffer);
  465. requiredLength += length;
  466. if(outputCapacity)
  467. {
  468. OVR_strlcpy(output, buffer, outputCapacity);
  469. length = MIN(outputCapacity, length);
  470. }
  471. output += length;
  472. outputCapacity -= length;
  473. }
  474. pclose(pFile);
  475. return requiredLength;
  476. }
  477. #else
  478. // To do. Properly solving this on Windows requires a bit of code.
  479. OVR_UNUSED(shellCommand);
  480. OVR_UNUSED(output);
  481. OVR_UNUSED(outputCapacity);
  482. #endif
  483. return (size_t)-1;
  484. }
  485. // Retrieves the name of the given thread.
  486. // To do: Move this to OVR_Threads.h
  487. bool GetThreadName(OVR::ThreadHandle threadHandle, char* threadName, size_t threadNameCapacity)
  488. {
  489. #if (defined(OVR_OS_APPLE) || defined(OVR_OS_LINUX)) && !defined(OVR_OS_ANDROID)
  490. int result = pthread_getname_np((pthread_t)threadHandle, threadName, threadNameCapacity);
  491. if(result == 0)
  492. return true;
  493. #else
  494. // This is not currently possible on Windows, as only the debugger stores the thread name. We could potentially use a vectored
  495. // exception handler to catch all thread name exceptions (0x406d1388) and record them in a static list at runtime. To detect
  496. // thread exit we could use WMI Win32_ThreadStopTrace. Maintain a list of thread names between these two events.
  497. OVR_UNUSED(threadHandle);
  498. OVR_UNUSED(threadNameCapacity);
  499. #endif
  500. if(threadNameCapacity)
  501. threadName[0] = 0;
  502. return false;
  503. }
  504. OVR::ThreadSysId ConvertThreadHandleToThreadSysId(OVR::ThreadHandle threadHandle)
  505. {
  506. #if defined(OVR_OS_WIN64)
  507. return (OVR::ThreadSysId)::GetThreadId(threadHandle); // Requires THREAD_QUERY_INFORMATION privileges.
  508. #elif defined(OVR_OS_WIN32)
  509. typedef DWORD (WINAPI *GetThreadIdFunc)(HANDLE);
  510. static volatile bool sInitialized = false;
  511. static GetThreadIdFunc spGetThreadIdFunc = nullptr;
  512. static NtQueryInformationThreadFunc spNtQueryInformationThread = nullptr;
  513. if(!sInitialized)
  514. {
  515. HMODULE hKernel32 = GetModuleHandleA("kernel32.dll");
  516. if(hKernel32)
  517. spGetThreadIdFunc = (GetThreadIdFunc)(uintptr_t)GetProcAddress(hKernel32, "GetThreadId");
  518. if(!spGetThreadIdFunc)
  519. {
  520. HMODULE hNTDLL = GetModuleHandleA("ntdll.dll");
  521. if(hNTDLL)
  522. spNtQueryInformationThread = (NtQueryInformationThreadFunc)(uintptr_t)GetProcAddress(hNTDLL, "NtQueryInformationThread");
  523. }
  524. sInitialized = true;
  525. }
  526. if(spGetThreadIdFunc)
  527. return (OVR::ThreadSysId)spGetThreadIdFunc(threadHandle);
  528. if(spNtQueryInformationThread)
  529. {
  530. THREAD_BASIC_INFORMATION tbi;
  531. if(spNtQueryInformationThread(threadHandle, 0, &tbi, sizeof(tbi), nullptr) == 0)
  532. return (OVR::ThreadSysId)tbi.UniqueThreadId;
  533. }
  534. return OVR_THREADSYSID_INVALID;
  535. #elif defined(OVR_OS_APPLE)
  536. mach_port_t threadSysId = pthread_mach_thread_np((pthread_t)threadHandle); // OS 10.4 and later.
  537. return (ThreadSysId)threadSysId;
  538. #elif defined(OVR_OS_LINUX)
  539. // I believe we can usually (though not portably) intepret the pthread_t as a pointer to a struct whose first member is a lwp id.
  540. OVR_UNUSED(threadHandle);
  541. return OVR_THREADSYSID_INVALID;
  542. #else
  543. OVR_UNUSED(threadHandle);
  544. return OVR_THREADSYSID_INVALID;
  545. #endif
  546. }
  547. OVR::ThreadHandle ConvertThreadSysIdToThreadHandle(OVR::ThreadSysId threadSysId)
  548. {
  549. #if defined(OVR_OS_MS)
  550. // We currently request the given rights because that's what users of this function typically need it for. Ideally there would
  551. // be a way to specify the requested rights in order to avoid the problem if we need only a subset of them but can't get it.
  552. // The solution we use below to try opening with successively reduced rights will work for our uses here but isn't a good general solution to this.
  553. OVR::ThreadHandle threadHandle = ::OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, TRUE, (DWORD)threadSysId);
  554. if(threadHandle == OVR_THREADHANDLE_INVALID)
  555. {
  556. threadHandle = ::OpenThread(THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, TRUE, (DWORD)threadSysId);
  557. if(threadHandle == OVR_THREADHANDLE_INVALID)
  558. threadHandle = ::OpenThread(THREAD_QUERY_INFORMATION, TRUE, (DWORD)threadSysId);
  559. }
  560. return threadHandle;
  561. #elif defined(OVR_OS_MAC)
  562. return (ThreadHandle)pthread_from_mach_thread_np((mach_port_t)threadSysId);
  563. #else
  564. return (ThreadHandle)threadSysId;
  565. #endif
  566. }
  567. void FreeThreadHandle(OVR::ThreadHandle threadHandle)
  568. {
  569. #if defined(OVR_OS_MS)
  570. if(threadHandle != OVR_THREADHANDLE_INVALID)
  571. ::CloseHandle(threadHandle);
  572. #else
  573. OVR_UNUSED(threadHandle);
  574. #endif
  575. }
  576. OVR::ThreadSysId GetCurrentThreadSysId()
  577. {
  578. #if defined(OVR_OS_MS)
  579. return ::GetCurrentThreadId();
  580. #elif defined(OVR_OS_APPLE)
  581. return (ThreadSysId)mach_thread_self();
  582. #else
  583. return (ThreadSysId)pthread_self();
  584. #endif
  585. }
  586. static void GetCurrentProcessFilePath(char* appPath, size_t appPathCapacity)
  587. {
  588. appPath[0] = 0;
  589. #if defined(OVR_OS_MS)
  590. wchar_t pathW[OVR_MAX_PATH];
  591. GetModuleFileNameW(0, pathW, (DWORD)OVR_ARRAY_COUNT(pathW));
  592. size_t requiredUTF8Length = (size_t)OVR::UTF8Util::GetEncodeStringSize(pathW); // Returns required strlen.
  593. if(requiredUTF8Length < appPathCapacity)
  594. {
  595. OVR::UTF8Util::EncodeString(appPath, pathW, -1);
  596. }
  597. else
  598. {
  599. appPath[0] = 0;
  600. }
  601. #elif defined(OVR_OS_APPLE)
  602. struct BunderFolder
  603. {
  604. // Returns true if pStr ends with pFind, case insensitively.
  605. // To do: Move OVR_striend to OVRKernel/Std.h
  606. static bool OVR_striend(const char* pStr, const char* pFind, size_t strLength = (size_t)-1, size_t findLength = (size_t)-1)
  607. {
  608. if(strLength == (size_t)-1)
  609. strLength = OVR_strlen(pStr);
  610. if(findLength == (size_t)-1)
  611. findLength = OVR_strlen(pFind);
  612. if(strLength >= findLength)
  613. return (OVR_stricmp(pStr + strLength - findLength, pFind) == 0);
  614. return false;
  615. }
  616. static bool IsBundleFolder(const char* filePath)
  617. {
  618. // https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/AboutBundles/AboutBundles.html#//apple_ref/doc/uid/10000123i-CH100-SW1
  619. static const char* extensionArray[] = { ".app", ".bundle", ".framework", ".plugin", ".kext" };
  620. for(size_t i = 0; i < OVR_ARRAY_COUNT(extensionArray); i++)
  621. {
  622. if(OVR_striend(filePath, extensionArray[i]))
  623. return true;
  624. }
  625. return false;
  626. }
  627. };
  628. char appPathTemp[PATH_MAX];
  629. uint32_t appPathTempCapacity32 = PATH_MAX;
  630. size_t requiredStrlen = appPathCapacity;
  631. if(_NSGetExecutablePath(appPathTemp, &appPathTempCapacity32) == 0)
  632. {
  633. char appPathTempReal[PATH_MAX];
  634. if(realpath(appPathTemp, appPathTempReal)) // If the path is a symbolic link, this converts it to the real path.
  635. {
  636. // To consider: Enable reading the internal bundle executable path. An application on Mac may in
  637. // fact be within a file bundle, which is an private file system within a file. With Objective C
  638. // we could use: [[NSWorkspace sharedWorkspace] isFilePackageAtPath:fullPath];
  639. bool shouldReadTheBunderPath = false;
  640. if(shouldReadTheBunderPath)
  641. {
  642. // We recursively call dirname() until we find .app/.bundle/.plugin as a directory name.
  643. OVR_strlcpy(appPathTemp, appPathTempReal, OVR_ARRAY_COUNT(appPathTemp));
  644. bool found = BunderFolder::IsBundleFolder(appPathTemp);
  645. while(!found && OVR_strcmp(appPathTemp, ".") && OVR_strcmp(appPathTemp, "/"))
  646. {
  647. OVR_strlcpy(appPathTemp, dirname(appPathTemp), OVR_ARRAY_COUNT(appPathTemp));
  648. found = BunderFolder::IsBundleFolder(appPathTemp);
  649. }
  650. if(found) // If somewhere above we found a parent bundle container...
  651. requiredStrlen = OVR_strlcpy(appPath, appPathTemp, appPathCapacity);
  652. else
  653. requiredStrlen = OVR_strlcpy(appPath, appPathTempReal, appPathCapacity);
  654. }
  655. else
  656. {
  657. requiredStrlen = OVR_strlcpy(appPath, appPathTempReal, appPathCapacity);
  658. }
  659. }
  660. }
  661. if(requiredStrlen >= appPathCapacity)
  662. appPath[0] = '\0';
  663. #elif defined(OVR_OS_LINUX)
  664. ssize_t length = readlink("/proc/self/exe", appPath, appPathCapacity);
  665. if((length != -1) && ((size_t)length < (appPathCapacity - 1)))
  666. {
  667. appPath[length] = '\0';
  668. }
  669. #endif
  670. }
  671. static const char* GetFileNameFromPath(const char* filePath)
  672. {
  673. const char* lastPathSeparator = strrchr(filePath, '/');
  674. #if defined(OVR_OS_MS)
  675. // Microsoft APIs are inconsistent with respect to allowing / as a path separator.
  676. const char* candidate = strrchr(filePath, '\\');
  677. if(candidate > lastPathSeparator)
  678. {
  679. lastPathSeparator = candidate;
  680. }
  681. #endif
  682. if(lastPathSeparator)
  683. return lastPathSeparator + 1;
  684. return filePath;
  685. }
  686. static void FormatDateTime(char* buffer, size_t bufferCapacity, time_t timeValue, bool getDate, bool getTime, bool localDateTime, bool fileNameSafeCharacters = false)
  687. {
  688. char temp[128];
  689. const tm* pTime = localDateTime ? localtime(&timeValue) : gmtime(&timeValue);
  690. if(bufferCapacity)
  691. buffer[0] = 0;
  692. if(getDate)
  693. {
  694. const char* format = fileNameSafeCharacters ? "%Y-%m-%d" : "%Y/%m/%d";
  695. strftime(temp, OVR_ARRAY_COUNT(temp), format, pTime);
  696. OVR::OVR_strlcpy(buffer, temp, bufferCapacity);
  697. }
  698. if(getTime)
  699. {
  700. const char* format = fileNameSafeCharacters ? " %H.%M.%S" : " %H:%M:%S";
  701. strftime(temp, OVR_ARRAY_COUNT(temp), (getDate ? format : format + 1), pTime);
  702. OVR::OVR_strlcat(buffer, temp, bufferCapacity);
  703. }
  704. }
  705. static void GetOSVersionName(char* versionName, size_t versionNameCapacity)
  706. {
  707. #if defined(OVR_OS_MS)
  708. const char* name = "unknown";
  709. OSVERSIONINFOEXW vi;
  710. memset(&vi, 0, sizeof(vi));
  711. vi.dwOSVersionInfoSize = sizeof(vi);
  712. if(GetVersionExW((LPOSVERSIONINFOW)&vi))
  713. {
  714. if (vi.dwMajorVersion == 10)
  715. {
  716. if (vi.dwMinorVersion == 0)
  717. {
  718. if (vi.wProductType == VER_NT_WORKSTATION)
  719. name = "Windows 10";
  720. else
  721. name = "Windows Server 2016 Technical Preview";
  722. }
  723. else
  724. {
  725. // Unknown recent version.
  726. if (vi.wProductType == VER_NT_WORKSTATION)
  727. name = "Windows 10 Unknown";
  728. else
  729. name = "Windows Server 2016 Unknown";
  730. }
  731. }
  732. else if(vi.dwMajorVersion >= 7)
  733. {
  734. // Unknown recent version.
  735. }
  736. else if(vi.dwMajorVersion >= 6)
  737. {
  738. if(vi.dwMinorVersion >= 4)
  739. name = "Windows 10 Pre Released";
  740. else if(vi.dwMinorVersion >= 3)
  741. {
  742. if(vi.wProductType == VER_NT_WORKSTATION)
  743. name = "Windows 8.1";
  744. else
  745. name = "Windows Server 2012 R2";
  746. }
  747. else if(vi.dwMinorVersion >= 2)
  748. {
  749. if(vi.wProductType == VER_NT_WORKSTATION)
  750. name = "Windows 8";
  751. else
  752. name = "Windows Server 2012";
  753. }
  754. else if(vi.dwMinorVersion >= 1)
  755. {
  756. if(vi.wProductType == VER_NT_WORKSTATION)
  757. name = "Windows 7";
  758. else
  759. name = "Windows Server 2008 R2";
  760. }
  761. else
  762. {
  763. if(vi.wProductType == VER_NT_WORKSTATION)
  764. name = "Windows Vista";
  765. else
  766. name = "Windows Server 2008";
  767. }
  768. }
  769. else if(vi.dwMajorVersion >= 5)
  770. {
  771. if(vi.dwMinorVersion == 0)
  772. name = "Windows 2000";
  773. else if(vi.dwMinorVersion == 1)
  774. name = "Windows XP";
  775. else // vi.dwMinorVersion == 2
  776. {
  777. if(GetSystemMetrics(SM_SERVERR2) != 0)
  778. name = "Windows Server 2003 R2";
  779. else if(vi.wSuiteMask & VER_SUITE_WH_SERVER)
  780. name = "Windows Home Server";
  781. if(GetSystemMetrics(SM_SERVERR2) == 0)
  782. name = "Windows Server 2003";
  783. else
  784. name = "Windows XP Professional x64 Edition";
  785. }
  786. }
  787. else
  788. name = "Windows 98 or earlier";
  789. }
  790. OVR_strlcpy(versionName, name, versionNameCapacity);
  791. #elif defined(OVR_OS_UNIX) || defined(OVR_OS_APPLE)
  792. utsname utsName;
  793. memset(&utsName, 0, sizeof(utsName));
  794. if(uname(&utsName) == 0)
  795. OVR_snprintf(versionName, versionNameCapacity, "%s %s %s %s", utsName.sysname, utsName.release, utsName.version, utsName.machine);
  796. else
  797. OVR_snprintf(versionName, versionNameCapacity, "Unix");
  798. #endif
  799. }
  800. void CreateException(CreateExceptionType exceptionType)
  801. {
  802. char buffer[1024] = {};
  803. switch(exceptionType)
  804. {
  805. case kCETAccessViolation:
  806. {
  807. int* pNullPtr = reinterpret_cast<int*>((rand() / 2) / RAND_MAX);
  808. pNullPtr[0] = 0; // This line should generate an exception.
  809. sprintf(buffer, "%p", pNullPtr);
  810. break;
  811. }
  812. case kCETDivideByZero:
  813. {
  814. int smallValue = 1;
  815. int largeValue = (1000 * exceptionType);
  816. int divByZero = (smallValue / largeValue); // This line should generate a div/0 exception.
  817. sprintf(buffer, "%d", divByZero);
  818. break;
  819. }
  820. case kCETIllegalInstruction:
  821. {
  822. #if defined(OVR_CPU_X86) || (defined(OVR_CPU_X86_64) && !defined(OVR_CC_MSVC)) // (if x86) or (if x64 and any computer but VC++)...
  823. #if defined(OVR_CC_MSVC)
  824. __asm ud2
  825. #else // e.g. GCC
  826. asm volatile("ud2");
  827. #endif
  828. #elif defined(OVR_CPU_X86_64) && (defined(OVR_OS_MS) && defined(PAGE_EXECUTE_READWRITE))
  829. // VC++ for x64 doesn't support inline asm.
  830. void* pVoid = _AddressOfReturnAddress();
  831. void** ppVoid = reinterpret_cast<void**>(pVoid);
  832. void* pReturnAddress = *ppVoid;
  833. DWORD dwProtectPrev = 0;
  834. if(VirtualProtect(pReturnAddress, 2, PAGE_EXECUTE_READWRITE, &dwProtectPrev)) // If we can set the memory to be executable...
  835. {
  836. // Modify the code we return to.
  837. uint8_t asm_ud2[] = { 0x0f, 0x0b };
  838. memcpy(pReturnAddress, asm_ud2, sizeof(asm_ud2));
  839. VirtualProtect(pReturnAddress, 2, dwProtectPrev, &dwProtectPrev);
  840. }
  841. else
  842. {
  843. // To do: Fix this.
  844. }
  845. #else
  846. // To do: Fix this.
  847. #endif
  848. break;
  849. }
  850. case kCETStackCorruption:
  851. {
  852. size_t size = (sizeof(buffer) * 16) - (rand() % 16);
  853. char* pOutsizeStack = buffer - ((sizeof(buffer) * 16) + (rand() % 16));
  854. memset(buffer, 0, size);
  855. memset(pOutsizeStack, 0, size); // This line should generate an exception, or an exception will be generated upon return from this function.
  856. break;
  857. }
  858. case kCETStackOverflow:
  859. {
  860. CreateException(exceptionType); // Call ourselves recursively. This line should generate a div/0 exception.
  861. sprintf(buffer, "%d", exceptionType);
  862. break;
  863. }
  864. case kCETAlignment:
  865. {
  866. // Not all platforms generate alignment exceptions. Some internally handle it.
  867. void* pAligned = malloc(16);
  868. char* pMisaligned = (char*)pAligned + 1;
  869. uint64_t* pMisaligned64 = reinterpret_cast<uint64_t*>(pMisaligned);
  870. *pMisaligned64 = 0; // This line should generate an exception.
  871. free(pAligned);
  872. break;
  873. }
  874. case kCETFPU:
  875. // Platforms usually have FPU exceptions disabled. In order to test FPU exceptions we will need to at least
  876. // temporarily disable them before executing code here to generate such exceptions.
  877. // To do.
  878. break;
  879. case kCETTrap:
  880. // To do. This is hardware-specific.
  881. break;
  882. }
  883. }
  884. //-----------------------------------------------------------------------------
  885. // SymbolLookup
  886. #if defined(OVR_OS_MS)
  887. #if defined(OVR_CC_MSVC)
  888. // The Lock below is one that we want to keep around as long as possible, as there may be application code that
  889. // needs to do symbol lookups during process teardown after main has returned. The init_seg(lib) statement
  890. // below makes it so that this module's globals are initialized right after the C standard library has initialized,
  891. // and are destroyed right before the C standard library is destroyed (after after all other app globals are destroyed).
  892. #pragma warning(disable: 4073) // warning C4073: initializers put in library initialization area.
  893. #pragma warning(disable: 4075) // warning C4075: initializers put in unrecognized initialization area.
  894. #pragma init_seg(lib)
  895. #endif
  896. typedef BOOL (WINAPI * StackWalk64Type)(DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME64 StackFrame, PVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
  897. typedef PVOID (WINAPI * SymFunctionTableAccess64Type)(HANDLE hProcess, DWORD64 dwAddr);
  898. typedef DWORD64 (WINAPI * SymGetModuleBase64Type)(HANDLE hProcess, DWORD64 dwAddr);
  899. typedef DWORD (WINAPI * SymSetOptionsType)(DWORD SymOptions);
  900. typedef BOOL (WINAPI * SymInitializeWType)(HANDLE hProcess, PCWSTR UserSearchPath, BOOL fInvadeProcess);
  901. typedef BOOL (WINAPI * SymCleanupType)(HANDLE hProcess);
  902. typedef DWORD64 (WINAPI * SymLoadModule64Type)(HANDLE hProcess, HANDLE hFile, PCSTR ImageName, PCSTR ModuleName, DWORD64 BaseOfDll, DWORD SizeOfDll);
  903. typedef BOOL (WINAPI * SymFromAddrType)(HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement, PSYMBOL_INFO Symbol);
  904. typedef BOOL (WINAPI * SymGetLineFromAddr64Type)(HANDLE hProcess, DWORD64 qwAddr, PDWORD pdwDisplacement, PIMAGEHLP_LINE64 Line64);
  905. static StackWalk64Type pStackWalk64 = nullptr;
  906. static SymFunctionTableAccess64Type pSymFunctionTableAccess64 = nullptr;
  907. static SymGetModuleBase64Type pSymGetModuleBase64 = nullptr;
  908. static SymSetOptionsType pSymSetOptions = nullptr;
  909. static SymInitializeWType pSymInitializeW = nullptr;
  910. static SymCleanupType pSymCleanup = nullptr;
  911. static SymLoadModule64Type pSymLoadModule64 = nullptr;
  912. static SymFromAddrType pSymFromAddr = nullptr;
  913. static SymGetLineFromAddr64Type pSymGetLineFromAddr64 = nullptr;
  914. static int32_t sSymUsageCount = 0;
  915. static HMODULE sDbgHelp = nullptr;
  916. static OVR::Lock sDbgHelpLock;
  917. bool SymbolLookup::Initialize()
  918. {
  919. OVR::Lock::Locker autoLock(&sDbgHelpLock);
  920. if (++sSymUsageCount > 1)
  921. {
  922. OVR_ASSERT(pSymInitializeW != nullptr); // If it was already initialized then the pointers should be valid.
  923. return true;
  924. }
  925. // http://msdn.microsoft.com/en-us/library/windows/desktop/ms679294%28v=vs.85%29.aspx
  926. sDbgHelp = LoadLibraryW(L"DbgHelp.dll"); // It's best if the application supplies a recent version of this.
  927. if (sDbgHelp)
  928. {
  929. pStackWalk64 = (StackWalk64Type)(uintptr_t)::GetProcAddress(sDbgHelp, "StackWalk64");
  930. pSymFunctionTableAccess64 = (SymFunctionTableAccess64Type)(uintptr_t)::GetProcAddress(sDbgHelp, "SymFunctionTableAccess64");
  931. pSymGetModuleBase64 = (SymGetModuleBase64Type)(uintptr_t)::GetProcAddress(sDbgHelp, "SymGetModuleBase64");
  932. pSymSetOptions = (SymSetOptionsType)(uintptr_t)::GetProcAddress(sDbgHelp, "SymSetOptions");
  933. pSymInitializeW = (SymInitializeWType)(uintptr_t)::GetProcAddress(sDbgHelp, "SymInitializeW");
  934. pSymCleanup = (SymCleanupType)(uintptr_t)::GetProcAddress(sDbgHelp, "SymCleanup");
  935. pSymLoadModule64 = (SymLoadModule64Type)(uintptr_t)::GetProcAddress(sDbgHelp, "SymLoadModule64");
  936. pSymFromAddr = (SymFromAddrType)(uintptr_t)::GetProcAddress(sDbgHelp, "SymFromAddr");
  937. pSymGetLineFromAddr64 = (SymGetLineFromAddr64Type)(uintptr_t)::GetProcAddress(sDbgHelp, "SymGetLineFromAddr64");
  938. // To consider: Use a manually created search path:
  939. // wchar_t searchPathW[4096]; // Semicolon-separated strings.
  940. // The current working directory of the application.
  941. // The directory of the application itself (GetModuleFileName).
  942. // The _NT_SYMBOL_PATH environment variable.
  943. // The _NT_ALTERNATE_SYMBOL_PATH environment variable.
  944. if (pSymInitializeW)
  945. {
  946. if (pSymInitializeW(GetCurrentProcess(), nullptr /*searchPathW*/, FALSE))
  947. {
  948. if (pSymSetOptions)
  949. {
  950. pSymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS);
  951. }
  952. return true;
  953. }
  954. }
  955. }
  956. return false;
  957. }
  958. bool SymbolLookup::IsInitialized()
  959. {
  960. // Note that it's possible that another thread could change the state of this right after the return.
  961. OVR::Lock::Locker autoLock(&sDbgHelpLock);
  962. return (sSymUsageCount != 0);
  963. }
  964. void SymbolLookup::Shutdown()
  965. {
  966. OVR::Lock::Locker autoLock(&sDbgHelpLock);
  967. if (sSymUsageCount > 0 &&
  968. --sSymUsageCount <= 0)
  969. {
  970. pSymCleanup(GetCurrentProcess());
  971. pStackWalk64 = nullptr;
  972. pSymFunctionTableAccess64 = nullptr;
  973. pSymGetModuleBase64 = nullptr;
  974. pSymSetOptions = nullptr;
  975. pSymInitializeW = nullptr;
  976. pSymCleanup = nullptr;
  977. pSymLoadModule64 = nullptr;
  978. pSymFromAddr = nullptr;
  979. pSymGetLineFromAddr64 = nullptr;
  980. FreeLibrary(sDbgHelp);
  981. sDbgHelp = nullptr;
  982. }
  983. }
  984. #else
  985. bool SymbolLookup::Initialize()
  986. {
  987. return true;
  988. }
  989. bool SymbolLookup::IsInitialized()
  990. {
  991. return true;
  992. }
  993. void SymbolLookup::Shutdown()
  994. {
  995. }
  996. #endif
  997. SymbolLookup::SymbolLookup() :
  998. AllowMemoryAllocation(true),
  999. ModuleListUpdated(false),
  1000. ModuleInfoArray(),
  1001. ModuleInfoArraySize(0)
  1002. {
  1003. }
  1004. SymbolLookup::~SymbolLookup()
  1005. {
  1006. }
  1007. void SymbolLookup::AddSourceCodeDirectory(const char* pDirectory)
  1008. {
  1009. OVR_UNUSED(pDirectory);
  1010. }
  1011. void SymbolLookup::EnableMemoryAllocation(bool enabled)
  1012. {
  1013. AllowMemoryAllocation = enabled;
  1014. }
  1015. bool SymbolLookup::Refresh()
  1016. {
  1017. ModuleListUpdated = false;
  1018. return RefreshModuleList();
  1019. }
  1020. OVR_DISABLE_MSVC_WARNING(4740) // flow in or out of inline asm code suppresses global optimization
  1021. OVR_DISABLE_MSVC_WARNING(4748) // /GS can not protect parameters and local variables from local buffer overrun because optimizations are disabled in function
  1022. size_t SymbolLookup::GetBacktrace(void* addressArray[], size_t addressArrayCapacity, size_t skipCount, void* platformThreadContext, OVR::ThreadSysId threadSysIdHelp)
  1023. {
  1024. #if defined(OVR_OS_WIN64)
  1025. OVR_UNUSED(threadSysIdHelp);
  1026. // The DbgHelp library must be loaded already.
  1027. OVR_ASSERT(sSymUsageCount > 0);
  1028. if(platformThreadContext == nullptr)
  1029. return RtlCaptureStackBackTrace((DWORD)skipCount, (ULONG)addressArrayCapacity, addressArray, nullptr);
  1030. // We need to get the call stack of another thread.
  1031. size_t frameIndex = 0;
  1032. CONTEXT context;
  1033. PRUNTIME_FUNCTION pRuntimeFunction;
  1034. ULONG64 imageBase = 0;
  1035. ULONG64 imageBasePrev = 0;
  1036. memcpy(&context, (CONTEXT*)platformThreadContext, sizeof(CONTEXT));
  1037. context.ContextFlags = CONTEXT_CONTROL;
  1038. if(context.Rip && (frameIndex < addressArrayCapacity))
  1039. addressArray[frameIndex++] = (void*)(uintptr_t)context.Rip;
  1040. while(context.Rip && (frameIndex < addressArrayCapacity))
  1041. {
  1042. imageBasePrev = imageBase;
  1043. pRuntimeFunction = (PRUNTIME_FUNCTION)RtlLookupFunctionEntry(context.Rip, &imageBase, nullptr);
  1044. if(pRuntimeFunction)
  1045. {
  1046. VOID* handlerData = nullptr;
  1047. ULONG64 establisherFramePointers[2] = { 0, 0 };
  1048. RtlVirtualUnwind(UNW_FLAG_NHANDLER, imageBase, context.Rip, pRuntimeFunction, &context, &handlerData, establisherFramePointers, nullptr);
  1049. }
  1050. else
  1051. {
  1052. context.Rip = (ULONG64)(*(PULONG64)context.Rsp);
  1053. context.Rsp += 8;
  1054. }
  1055. if(context.Rip && (frameIndex < addressArrayCapacity))
  1056. {
  1057. if(skipCount)
  1058. --skipCount;
  1059. else
  1060. addressArray[frameIndex++] = (void*)(uintptr_t)context.Rip;
  1061. }
  1062. }
  1063. return frameIndex;
  1064. #elif defined(OVR_OS_WIN32)
  1065. OVR_UNUSED(threadSysIdHelp);
  1066. OVR::Lock::Locker autoLock(&sDbgHelpLock);
  1067. size_t frameIndex = 0;
  1068. if(pStackWalk64)
  1069. {
  1070. CONTEXT context;
  1071. if(platformThreadContext)
  1072. {
  1073. memcpy(&context, platformThreadContext, sizeof(context));
  1074. context.ContextFlags = CONTEXT_CONTROL;
  1075. }
  1076. else
  1077. {
  1078. memset(&context, 0, sizeof(context));
  1079. context.ContextFlags = CONTEXT_CONTROL;
  1080. __asm {
  1081. mov context.Ebp, EBP
  1082. mov context.Esp, ESP
  1083. call GetEIP
  1084. GetEIP:
  1085. pop context.Eip
  1086. }
  1087. }
  1088. STACKFRAME64 sf;
  1089. memset(&sf, 0, sizeof(sf));
  1090. sf.AddrPC.Offset = context.Eip;
  1091. sf.AddrPC.Mode = AddrModeFlat;
  1092. sf.AddrStack.Offset = context.Esp;
  1093. sf.AddrStack.Mode = AddrModeFlat;
  1094. sf.AddrFrame.Offset = context.Ebp;
  1095. sf.AddrFrame.Mode = AddrModeFlat;
  1096. const HANDLE hCurrentProcess = ::GetCurrentProcess();
  1097. const HANDLE hCurrentThread = ::GetCurrentThread();
  1098. if(!platformThreadContext) // If we are reading the current thread's call stack then we ignore this current function.
  1099. skipCount++;
  1100. while(frameIndex < addressArrayCapacity)
  1101. {
  1102. if(!pStackWalk64(IMAGE_FILE_MACHINE_I386, hCurrentProcess, hCurrentThread, &sf, &context, nullptr, pSymFunctionTableAccess64, pSymGetModuleBase64, nullptr))
  1103. break;
  1104. if(sf.AddrFrame.Offset == 0)
  1105. break;
  1106. if(skipCount)
  1107. --skipCount;
  1108. else
  1109. addressArray[frameIndex++] = ((void*)(uintptr_t)sf.AddrPC.Offset);
  1110. }
  1111. }
  1112. return frameIndex;
  1113. #elif defined(OVR_OS_APPLE)
  1114. struct StackFrame
  1115. {
  1116. StackFrame* pParentStackFrame;
  1117. void* pReturnPC;
  1118. };
  1119. void* pInstruction;
  1120. StackFrame* pStackFrame;
  1121. size_t frameIndex = 0;
  1122. if(platformThreadContext)
  1123. {
  1124. #if defined(OVR_CPU_ARM)
  1125. arm_thread_state_t* pThreadState = (arm_thread_state_t*)platformThreadContext;
  1126. pStackFrame = (StackFrame*)pThreadState->__fp;
  1127. pInstruction = (void*) pThreadState->__pc;
  1128. #define FrameIsAligned(pStackFrame) ((((uintptr_t)pStackFrame) & 0x1) == 0)
  1129. #elif defined(OVR_CPU_X86_64)
  1130. x86_thread_state_t* pThreadState = (x86_thread_state_t*)platformThreadContext;
  1131. pInstruction = (void*) pThreadState->uts.ts64.__rip;
  1132. pStackFrame = (StackFrame*)pThreadState->uts.ts64.__rbp;
  1133. #define FrameIsAligned(pStackFrame) ((((uintptr_t)pStackFrame) & 0xf) == 0)
  1134. #elif defined(OVR_CPU_X86)
  1135. x86_thread_state_t* pThreadState = (x86_thread_state_t*)platformThreadContext;
  1136. pInstruction = (void*) pThreadState->uts.ts32.__eip;
  1137. pStackFrame = (StackFrame*)pThreadState->uts.ts32.__ebp;
  1138. #define FrameIsAligned(pStackFrame) ((((uintptr_t)pStackFrame) & 0xf) == 8)
  1139. #endif
  1140. if(frameIndex < addressArrayCapacity)
  1141. addressArray[frameIndex++] = pInstruction;
  1142. }
  1143. else // Else get the current values...
  1144. {
  1145. pStackFrame = (StackFrame*)__builtin_frame_address(0);
  1146. GetInstructionPointer(pInstruction);
  1147. }
  1148. pthread_t threadSelf = pthread_self();
  1149. void* pCurrentStackBase = pthread_get_stackaddr_np(threadSelf);
  1150. void* pCurrentStackLimit = (void*)((uintptr_t)pCurrentStackBase - pthread_get_stacksize_np(threadSelf));
  1151. bool threadIsCurrent = (platformThreadContext == nullptr) || (((void*)pStackFrame > pCurrentStackLimit) && ((void*)pStackFrame <= pCurrentStackBase));
  1152. StackFrame* pStackBase;
  1153. StackFrame* pStackLimit;
  1154. if(threadIsCurrent)
  1155. {
  1156. pStackBase = (StackFrame*)pCurrentStackBase;
  1157. pStackLimit = (StackFrame*)pCurrentStackLimit;
  1158. }
  1159. else if(threadSysIdHelp)
  1160. {
  1161. pthread_t threadHandle = pthread_from_mach_thread_np((mach_port_t)threadSysIdHelp);
  1162. pStackBase = (StackFrame*)pthread_get_stackaddr_np(threadHandle);
  1163. pStackLimit = (StackFrame*)((uintptr_t)pStackBase - pthread_get_stacksize_np(threadHandle));
  1164. }
  1165. else
  1166. { // We guess what the limits are.
  1167. pStackBase = pStackFrame + ((384 * 1024) / sizeof(StackFrame));
  1168. pStackLimit = pStackFrame - ((384 * 1024) / sizeof(StackFrame));
  1169. }
  1170. if((frameIndex < addressArrayCapacity) && pStackFrame && FrameIsAligned(pStackFrame))
  1171. {
  1172. addressArray[frameIndex++] = pStackFrame->pReturnPC;
  1173. while(pStackFrame && pStackFrame->pReturnPC && (frameIndex < addressArrayCapacity))
  1174. {
  1175. pStackFrame = pStackFrame->pParentStackFrame;
  1176. if(pStackFrame && FrameIsAligned(pStackFrame) && pStackFrame->pReturnPC && (pStackFrame > pStackLimit) && (pStackFrame < pStackBase))
  1177. {
  1178. if(skipCount)
  1179. --skipCount;
  1180. else
  1181. addressArray[frameIndex++] = pStackFrame->pReturnPC;
  1182. }
  1183. else
  1184. break;
  1185. }
  1186. }
  1187. return frameIndex;
  1188. #elif defined(OVR_OS_LINUX) && (defined( __LIBUNWIND__) || defined(LIBUNWIND_AVAIL))
  1189. // Libunwind-based solution. Requires installation of libunwind package.
  1190. // Libunwind isn't always safe for threads that are in signal handlers.
  1191. // An approach to get the callstack of another thread is to use signal injection into the target thread.
  1192. OVR_UNUSED(platformThreadContext);
  1193. OVR_UNUSED(threadSysIdHelp);
  1194. size_t frameIndex = 0;
  1195. unw_cursor_t cursor;
  1196. unw_context_t uc;
  1197. unw_word_t ip, sp;
  1198. unw_getcontext(&uc); // This gets the current thread's context. We could alternatively initialize another thread's context with it.
  1199. unw_init_local(&cursor, &uc);
  1200. while((unw_step(&cursor) > 0) && (frameIndex < addressArrayCapacity))
  1201. {
  1202. // We can get the function name here too on some platforms with unw_get_proc_info() and unw_get_proc_name().
  1203. if(skipCount)
  1204. --skipCount;
  1205. else
  1206. {
  1207. unw_get_reg(&cursor, UNW_REG_IP, &ip);
  1208. addressArray[frameIndex++] = (void*)ip;
  1209. }
  1210. }
  1211. return frameIndex;
  1212. #else
  1213. OVR_UNUSED(addressArray);
  1214. OVR_UNUSED(addressArrayCapacity);
  1215. OVR_UNUSED(skipCount);
  1216. OVR_UNUSED(platformThreadContext);
  1217. OVR_UNUSED(threadSysIdHelp);
  1218. return 0;
  1219. #endif
  1220. }
  1221. size_t SymbolLookup::GetBacktraceFromThreadHandle(void* addressArray[], size_t addressArrayCapacity, size_t skipCount, OVR::ThreadHandle threadHandle)
  1222. {
  1223. #if defined(OVR_OS_MS)
  1224. size_t count = 0;
  1225. DWORD threadSysId = (DWORD)ConvertThreadHandleToThreadSysId(threadHandle);
  1226. // Compare to 0, compare to the self 'pseudohandle' and compare to the self id.
  1227. if((threadHandle == OVR_THREADHANDLE_INVALID) || (threadHandle == ::GetCurrentThread()) || (threadSysId == ::GetCurrentThreadId())) // If threadSysId refers to the current thread...
  1228. return GetBacktrace(addressArray, addressArrayCapacity, skipCount, nullptr);
  1229. // We are working with another thread. We need to suspend it and get its CONTEXT.
  1230. // Suspending other threads is risky, as they may be in some state that cannot be safely blocked.
  1231. BOOL result = false;
  1232. DWORD suspendResult = ::SuspendThread(threadHandle); // Requires that the handle have THREAD_SUSPEND_RESUME rights.
  1233. if(suspendResult != (DWORD)-1) // Returns previous suspend count, or -1 if failed.
  1234. {
  1235. CONTEXT context;
  1236. context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER; // Requires that the handle have THREAD_GET_CONTEXT rights.
  1237. result = ::GetThreadContext(threadHandle, &context);
  1238. count = GetBacktrace(addressArray, addressArrayCapacity, skipCount, &context);
  1239. suspendResult = ::ResumeThread(threadHandle);
  1240. OVR_ASSERT_AND_UNUSED(suspendResult != (DWORD)-1, suspendResult);
  1241. }
  1242. return count;
  1243. #elif defined(OVR_OS_APPLE)
  1244. mach_port_t threadSysID = pthread_mach_thread_np((pthread_t)threadHandle); // Convert pthread_t to mach thread id.
  1245. return GetBacktraceFromThreadSysId(addressArray, addressArrayCapacity, skipCount, (OVR::ThreadSysId)threadSysID);
  1246. #elif defined(OVR_OS_LINUX)
  1247. // To do.
  1248. OVR_UNUSED(addressArray);
  1249. OVR_UNUSED(addressArrayCapacity);
  1250. OVR_UNUSED(skipCount);
  1251. OVR_UNUSED(threadHandle);
  1252. return 0;
  1253. #endif
  1254. }
  1255. size_t SymbolLookup::GetBacktraceFromThreadSysId(void* addressArray[], size_t addressArrayCapacity, size_t skipCount, OVR::ThreadSysId threadSysId)
  1256. {
  1257. #if defined(OVR_OS_MS)
  1258. OVR::ThreadHandle threadHandle = ConvertThreadSysIdToThreadHandle(threadSysId);
  1259. if(threadHandle)
  1260. {
  1261. size_t count = GetBacktraceFromThreadHandle(addressArray, addressArrayCapacity, skipCount, threadHandle);
  1262. FreeThreadHandle(threadHandle);
  1263. return count;
  1264. }
  1265. return 0;
  1266. #elif defined(OVR_OS_APPLE)
  1267. mach_port_t threadCurrent = pthread_mach_thread_np(pthread_self());
  1268. mach_port_t thread = (mach_port_t)threadSysId;
  1269. if(thread == threadCurrent)
  1270. {
  1271. return GetBacktrace(addressArray, addressArrayCapacity, skipCount, nullptr);
  1272. }
  1273. else
  1274. {
  1275. kern_return_t result = thread_suspend(thread); // Do we need to do this if it's an thread who exception is being handled?
  1276. size_t count = 0;
  1277. if(result == KERN_SUCCESS)
  1278. {
  1279. #if defined(OVR_CPU_X86) || defined(OVR_CPU_X86_64)
  1280. x86_thread_state_t threadState;
  1281. #elif defined(OVR_CPU_ARM)
  1282. arm_thread_state_t threadState;
  1283. #endif
  1284. mach_msg_type_number_t stateCount = MACHINE_THREAD_STATE_COUNT;
  1285. result = thread_get_state(thread, MACHINE_THREAD_STATE, (natural_t*)(uintptr_t)&threadState, &stateCount);
  1286. if(result == KERN_SUCCESS)
  1287. count = GetBacktrace(addressArray, addressArrayCapacity, skipCount, &threadState, threadSysId);
  1288. thread_resume(thread);
  1289. return count;
  1290. }
  1291. }
  1292. return 0;
  1293. #elif defined(OVR_OS_LINUX)
  1294. // To do.
  1295. OVR_UNUSED(addressArray);
  1296. OVR_UNUSED(addressArrayCapacity);
  1297. OVR_UNUSED(skipCount);
  1298. OVR_UNUSED(threadSysId);
  1299. return 0;
  1300. #endif
  1301. }
  1302. // We need to return the required moduleInfoArrayCapacity.
  1303. size_t SymbolLookup::GetModuleInfoArray(ModuleInfo* pModuleInfoArray, size_t moduleInfoArrayCapacity)
  1304. {
  1305. #if defined(OVR_OS_MS)
  1306. size_t moduleCountRequired = 0; // The count we would copy to pModuleInfoArray if moduleInfoArrayCapacity was enough.
  1307. size_t moduleCount = 0; // The count we actually copy to pModuleInfoArray. Will be <= moduleInfoArrayCapacity.
  1308. HANDLE hProcess = GetCurrentProcess();
  1309. HMODULE hModuleArray[200];
  1310. DWORD cbNeeded = 0;
  1311. MODULEINFO mi;
  1312. if(EnumProcessModules(hProcess, hModuleArray, sizeof(hModuleArray), &cbNeeded))
  1313. {
  1314. moduleCountRequired = ((cbNeeded / sizeof(HMODULE)) < OVR_ARRAY_COUNT(hModuleArray)) ? (cbNeeded / sizeof(HMODULE)) : OVR_ARRAY_COUNT(hModuleArray);
  1315. moduleCount = MIN(moduleCountRequired, OVR_ARRAY_COUNT(hModuleArray));
  1316. moduleCount = MIN(moduleCount, moduleInfoArrayCapacity);
  1317. for(size_t i = 0; i < moduleCount; i++)
  1318. {
  1319. ModuleInfo& moduleInfo = pModuleInfoArray[i];
  1320. memset(&mi, 0, sizeof(mi));
  1321. BOOL result = GetModuleInformation(hProcess, hModuleArray[i], &mi, sizeof(mi));
  1322. if(result)
  1323. {
  1324. wchar_t pathW[OVR_MAX_PATH];
  1325. char pathA[OVR_MAX_PATH * 3]; // *3 to handle UTF8 multibyte encoding.
  1326. moduleInfo.handle = hModuleArray[i];
  1327. moduleInfo.baseAddress = (uintptr_t)mi.lpBaseOfDll;
  1328. moduleInfo.size = mi.SizeOfImage;
  1329. GetModuleFileNameW(hModuleArray[i], pathW, OVR_ARRAY_COUNT(pathW));
  1330. OVR::UTF8Util::EncodeString(pathA, pathW, -1); // Problem: DecodeString provides no way to specify the destination capacity.
  1331. OVR::OVR_strlcpy(moduleInfo.filePath, pathA, OVR_ARRAY_COUNT(moduleInfo.filePath));
  1332. const char* fileName = GetFileNameFromPath(pathA);
  1333. OVR::OVR_strlcpy(moduleInfo.name, fileName, OVR_ARRAY_COUNT(moduleInfo.name));
  1334. }
  1335. else
  1336. {
  1337. moduleInfo.handle = 0;
  1338. moduleInfo.baseAddress = 0;
  1339. moduleInfo.size = 0;
  1340. moduleInfo.filePath[0] = 0;
  1341. moduleInfo.name[0] = 0;
  1342. }
  1343. }
  1344. }
  1345. return moduleCountRequired;
  1346. #elif defined(OVR_OS_MAC)
  1347. size_t moduleCountRequired = 0;
  1348. size_t moduleCount = 0;
  1349. struct MacModuleInfo // This struct exists solely so we can have a local function within this function..
  1350. {
  1351. static void AddMacModuleInfo(ModuleInfo* pModuleInfoArrayL, size_t& moduleCountRequiredL, size_t& moduleCountL, size_t moduleInfoArrayCapacityL,
  1352. const char* pTypeFilterL, const char* pModulePath, uintptr_t currentSegmentPos, const MachHeader* pMachHeader, uint64_t offset)
  1353. {
  1354. for(size_t i = 0; i < pMachHeader->ncmds; i++)
  1355. {
  1356. const SegmentCommand* pSegmentCommand = reinterpret_cast<const SegmentCommand*>(currentSegmentPos);
  1357. if(pSegmentCommand->cmd == kLCSegment)
  1358. {
  1359. const size_t segnameSize = (sizeof(pSegmentCommand->segname) + 1); // +1 so we can have a trailing '\0'.
  1360. char segname[segnameSize];
  1361. memcpy(segname, pSegmentCommand->segname, sizeof(pSegmentCommand->segname));
  1362. segname[segnameSize - 1] = '\0';
  1363. if(!pTypeFilterL || OVR_strncmp(segname, pTypeFilterL, sizeof(segname)))
  1364. {
  1365. moduleCountRequiredL++;
  1366. if(moduleCountL < moduleInfoArrayCapacityL)
  1367. {
  1368. ModuleInfo& info = pModuleInfoArrayL[moduleCountL++];
  1369. info.baseAddress = (uint64_t)(pSegmentCommand->vmaddr + offset);
  1370. info.handle = reinterpret_cast<ModuleHandle>((uintptr_t)info.baseAddress);
  1371. info.size = (uint64_t)pSegmentCommand->vmsize;
  1372. OVR_strlcpy(info.filePath, pModulePath, OVR_ARRAY_COUNT(info.filePath));
  1373. OVR_strlcpy(info.name, GetFileNameFromPath(pModulePath), OVR_ARRAY_COUNT(info.name));
  1374. info.permissions[0] = (pSegmentCommand->initprot & VM_PROT_READ) ? 'r' : '-';
  1375. info.permissions[1] = (pSegmentCommand->initprot & VM_PROT_WRITE) ? 'w' : '-';
  1376. info.permissions[2] = (pSegmentCommand->initprot & VM_PROT_EXECUTE) ? 'x' : '-';
  1377. info.permissions[3] = '/';
  1378. info.permissions[4] = (pSegmentCommand->maxprot & VM_PROT_READ) ? 'r' : '-';
  1379. info.permissions[5] = (pSegmentCommand->maxprot & VM_PROT_WRITE) ? 'w' : '-';
  1380. info.permissions[6] = (pSegmentCommand->maxprot & VM_PROT_EXECUTE) ? 'x' : '-';
  1381. info.permissions[7] = '\0';
  1382. OVR_strlcpy(info.type, pSegmentCommand->segname, OVR_ARRAY_COUNT(info.type));
  1383. }
  1384. }
  1385. }
  1386. currentSegmentPos += pSegmentCommand->cmdsize;
  1387. }
  1388. }
  1389. };
  1390. // Iterate dyld_all_image_infos->infoArray
  1391. const struct dyld_all_image_infos* pAllImageInfos = _dyld_get_all_image_infos();
  1392. for(uint32_t i = 0; i < pAllImageInfos->infoArrayCount; i++)
  1393. {
  1394. const char* pModulePath = pAllImageInfos->infoArray[i].imageFilePath;
  1395. if(pModulePath && *pModulePath)
  1396. {
  1397. uintptr_t currentSegmentPos = (uintptr_t)pAllImageInfos->infoArray[i].imageLoadAddress;
  1398. const MachHeader* pMachHeader = reinterpret_cast<const MachHeader*>(currentSegmentPos);
  1399. uint64_t offset = (uint64_t)_dyld_get_image_vmaddr_slide(i);
  1400. currentSegmentPos += sizeof(*pMachHeader);
  1401. MacModuleInfo::AddMacModuleInfo(pModuleInfoArray, moduleCountRequired, moduleCount, moduleInfoArrayCapacity,
  1402. nullptr /*"__TEXT"*/, pModulePath, currentSegmentPos, pMachHeader, offset);
  1403. }
  1404. }
  1405. // In addition to iterating dyld_all_image_infos->infoArray we need to also iterate /usr/lib/dyld entries.
  1406. const MachHeader* pMachHeader = (const MachHeader*)pAllImageInfos->dyldImageLoadAddress;
  1407. uintptr_t currentSegmentPos = (uintptr_t)pMachHeader + sizeof(*pMachHeader);
  1408. char modulePath[OVR_MAX_PATH] = "";
  1409. pid_t pid = getpid();
  1410. int filenameLen = proc_regionfilename((int)pid, currentSegmentPos, modulePath, (uint32_t)sizeof(modulePath));
  1411. if(filenameLen > 0)
  1412. MacModuleInfo::AddMacModuleInfo(pModuleInfoArray, moduleCountRequired, moduleCount, moduleInfoArrayCapacity,
  1413. "__TEXT", modulePath, currentSegmentPos, pMachHeader, 0);
  1414. return moduleCountRequired;
  1415. #elif defined(OVR_OS_LINUX)
  1416. // One approach is to read /proc/self/maps, which is supported by Linux (though not BSD).
  1417. // Linux glibc dladdr() can tell us what module an arbitrary function address comes from, but can't tell us the list of modules.
  1418. OVR_UNUSED(pModuleInfoArray);
  1419. OVR_UNUSED(moduleInfoArrayCapacity);
  1420. return 0;
  1421. #else
  1422. OVR_UNUSED(pModuleInfoArray);
  1423. OVR_UNUSED(moduleInfoArrayCapacity);
  1424. return 0;
  1425. #endif
  1426. }
  1427. size_t SymbolLookup::GetThreadList(ThreadHandle* threadHandleArray, ThreadSysId* threadSysIdArray, size_t threadArrayCapacity)
  1428. {
  1429. size_t countRequired = 0;
  1430. size_t count = 0;
  1431. #if defined(OVR_OS_MS)
  1432. // Print a list of threads.
  1433. DWORD currentProcessId = GetCurrentProcessId();
  1434. HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, currentProcessId); // ICreateToolhelp32Snapshot actually ignores currentProcessId.
  1435. if(hThreadSnap != INVALID_HANDLE_VALUE)
  1436. {
  1437. THREADENTRY32 te32;
  1438. te32.dwSize = sizeof(THREADENTRY32);
  1439. if(Thread32First(hThreadSnap, &te32))
  1440. {
  1441. do
  1442. {
  1443. if(te32.th32OwnerProcessID == currentProcessId)
  1444. {
  1445. HANDLE hThread = ConvertThreadSysIdToThreadHandle(te32.th32ThreadID);
  1446. if(hThread)
  1447. {
  1448. ++countRequired;
  1449. if((threadHandleArray || threadSysIdArray) && (count < threadArrayCapacity))
  1450. {
  1451. if(threadHandleArray)
  1452. threadHandleArray[count] = hThread; // The caller must call CloseHandle on this thread, or call DoneThreadList on the returned array.
  1453. if(threadSysIdArray)
  1454. threadSysIdArray[count] = ConvertThreadHandleToThreadSysId(hThread);
  1455. ++count;
  1456. }
  1457. if(!threadHandleArray) // If we aren't giving this back to the user...
  1458. FreeThreadHandle(hThread);
  1459. }
  1460. }
  1461. } while(Thread32Next(hThreadSnap, &te32));
  1462. }
  1463. CloseHandle(hThreadSnap);
  1464. }
  1465. #elif defined(OVR_OS_APPLE)
  1466. mach_port_t taskSelf = mach_task_self();
  1467. thread_act_port_array_t threadArray;
  1468. mach_msg_type_number_t threadCount;
  1469. kern_return_t result = task_threads(taskSelf, &threadArray, &threadCount);
  1470. if(result == KERN_SUCCESS)
  1471. {
  1472. for(mach_msg_type_number_t i = 0; i < threadCount; i++)
  1473. {
  1474. ++countRequired;
  1475. if((threadHandleArray || threadSysIdArray) && (count < threadArrayCapacity))
  1476. {
  1477. if(threadHandleArray)
  1478. threadHandleArray[count] = pthread_from_mach_thread_np(threadArray[i]);
  1479. if(threadSysIdArray)
  1480. threadSysIdArray[count] = threadArray[i];
  1481. ++count;
  1482. }
  1483. }
  1484. vm_deallocate(taskSelf, (vm_address_t)threadArray, threadCount * sizeof(thread_act_t));
  1485. }
  1486. #elif defined(OVR_OS_LINUX)
  1487. // To do.
  1488. OVR_UNUSED(count);
  1489. OVR_UNUSED(threadHandleArray);
  1490. OVR_UNUSED(threadSysIdArray);
  1491. OVR_UNUSED(threadArrayCapacity);
  1492. #endif
  1493. return countRequired;
  1494. }
  1495. void SymbolLookup::DoneThreadList(ThreadHandle* threadHandleArray, ThreadSysId* threadSysIdArray, size_t threadArrayCount)
  1496. {
  1497. #if defined(OVR_OS_MS)
  1498. for(size_t i = 0; i != threadArrayCount; ++i)
  1499. {
  1500. if(threadHandleArray[i])
  1501. {
  1502. CloseHandle(threadHandleArray[i]);
  1503. threadHandleArray[i] = OVR_THREADHANDLE_INVALID;
  1504. }
  1505. }
  1506. OVR_UNUSED(threadSysIdArray);
  1507. #else
  1508. OVR_UNUSED(threadHandleArray);
  1509. OVR_UNUSED(threadSysIdArray);
  1510. OVR_UNUSED(threadArrayCount);
  1511. #endif
  1512. }
  1513. // Writes a given thread's callstack wity symbols to the given output.
  1514. // It may not be safe to call this from an exception handler, as sOutput allocates memory.
  1515. bool SymbolLookup::ReportThreadCallstack(OVR::String& sOutput, size_t skipCount, ThreadSysId threadSysId)
  1516. {
  1517. sOutput.Clear();
  1518. if(!threadSysId)
  1519. threadSysId = GetCurrentThreadSysId();
  1520. void* addressArray[64];
  1521. size_t addressCount = GetBacktraceFromThreadSysId(addressArray, OVR_ARRAY_COUNT(addressArray), skipCount, threadSysId);
  1522. // Print the header
  1523. char headerBuffer[256];
  1524. char threadName[32];
  1525. char threadHandleStr[24];
  1526. char threadSysIdStr[48];
  1527. char stackBaseStr[24];
  1528. char stackLimitStr[24];
  1529. void* pStackBase;
  1530. void* pStackLimit;
  1531. //void* pStackCurrent; // Current stack pointer. To do: support reporting this.
  1532. ThreadHandle threadHandle = ConvertThreadSysIdToThreadHandle(threadSysId);
  1533. OVR::GetThreadStackBounds(pStackBase, pStackLimit, threadHandle);
  1534. Thread::GetThreadName(threadName, OVR_ARRAY_COUNT(threadName), threadName);
  1535. SprintfThreadHandle(threadHandleStr, OVR_ARRAY_COUNT(threadHandleStr), threadHandle);
  1536. SprintfThreadSysId(threadSysIdStr, OVR_ARRAY_COUNT(threadSysIdStr), threadSysId);
  1537. SprintfAddress(stackBaseStr, OVR_ARRAY_COUNT(stackBaseStr), pStackBase);
  1538. SprintfAddress(stackLimitStr, OVR_ARRAY_COUNT(stackLimitStr), pStackLimit);
  1539. if(threadName[0])
  1540. OVR_snprintf(headerBuffer, OVR_ARRAY_COUNT(headerBuffer), "Thread \"%s\" handle: %s, id: %s, stack base: %s, stack limit: %s\n", threadName, threadHandleStr, threadSysIdStr, stackBaseStr, stackLimitStr);
  1541. else
  1542. OVR_snprintf(headerBuffer, OVR_ARRAY_COUNT(headerBuffer), "Thread handle: %s, id: %s, stack base: %s, stack limit: %s\n", threadHandleStr, threadSysIdStr, stackBaseStr, stackLimitStr);
  1543. sOutput += headerBuffer;
  1544. // Print the backtrace info
  1545. char backtraceBuffer[1024]; // Sometimes function symbol names are very long.
  1546. SymbolInfo symbolInfo;
  1547. const char* pModuleName;
  1548. if(addressCount == 0)
  1549. {
  1550. sOutput += "<Unable to read backtrace>\n";
  1551. }
  1552. else
  1553. {
  1554. for(size_t i = 0; i < addressCount; ++i)
  1555. {
  1556. LookupSymbol((uint64_t)addressArray[i], symbolInfo);
  1557. if(symbolInfo.pModuleInfo && symbolInfo.pModuleInfo->name[0])
  1558. pModuleName = symbolInfo.pModuleInfo->name;
  1559. else
  1560. pModuleName = "(unknown module)";
  1561. char addressStr[24];
  1562. SprintfAddress(addressStr, OVR_ARRAY_COUNT(addressStr), addressArray[i]);
  1563. if(symbolInfo.filePath[0])
  1564. OVR_snprintf(backtraceBuffer, OVR_ARRAY_COUNT(backtraceBuffer), "%-2u %-24s %s %s+%d %s:%d\n", (unsigned)i, pModuleName, addressStr, symbolInfo.function, symbolInfo.functionOffset, symbolInfo.filePath, symbolInfo.fileLineNumber);
  1565. else
  1566. OVR_snprintf(backtraceBuffer, OVR_ARRAY_COUNT(backtraceBuffer), "%-2u %-24s %s %s+%d\n", (unsigned)i, pModuleName, addressStr, symbolInfo.function, symbolInfo.functionOffset);
  1567. sOutput += backtraceBuffer;
  1568. }
  1569. }
  1570. FreeThreadHandle(threadHandle);
  1571. return (addressCount > 0);
  1572. }
  1573. // Writes all thread's callstacks with symbols to the given output.
  1574. // It may not be safe to call this from an exception handler, as sOutput allocates memory.
  1575. bool SymbolLookup::ReportThreadCallstacks(OVR::String& sOutput, size_t skipCount)
  1576. {
  1577. sOutput.Clear();
  1578. ThreadSysId threadSysIdArray[64];
  1579. size_t threadSysIdCount = GetThreadList(nullptr, threadSysIdArray, OVR_ARRAY_COUNT(threadSysIdArray));
  1580. if (threadSysIdCount > OVR_ARRAY_COUNT(threadSysIdArray))
  1581. threadSysIdCount = OVR_ARRAY_COUNT(threadSysIdArray);
  1582. for (size_t i = 0; i < threadSysIdCount; i++)
  1583. {
  1584. String sTemp;
  1585. ReportThreadCallstack(sTemp, skipCount, threadSysIdArray[i]);
  1586. if(i > 0)
  1587. sOutput += "\n";
  1588. sOutput += sTemp;
  1589. }
  1590. return (threadSysIdCount > 0);
  1591. }
  1592. bool SymbolLookup::ReportModuleInformation(OVR::String& sOutput)
  1593. {
  1594. sOutput.Clear();
  1595. RefreshModuleList();
  1596. char backtraceBuffer[1024];
  1597. for (size_t i = 0; i < ModuleInfoArraySize; ++i)
  1598. {
  1599. OVR_snprintf(backtraceBuffer, OVR_ARRAY_COUNT(backtraceBuffer), "Base: 0x%llx Size: 0x%llx Name: '%s' Path: '%s'\n",
  1600. ModuleInfoArray[i].baseAddress, ModuleInfoArray[i].size, ModuleInfoArray[i].name, ModuleInfoArray[i].filePath);
  1601. sOutput += backtraceBuffer;
  1602. }
  1603. return true;
  1604. }
  1605. bool SymbolLookup::RefreshModuleList()
  1606. {
  1607. if(!ModuleListUpdated)
  1608. {
  1609. #if defined(OVR_OS_MS)
  1610. OVR::Lock::Locker autoLock(&sDbgHelpLock);
  1611. // We can't rely on SymRefreshModuleList because it's present in DbgHelp 6.5,
  1612. // which doesn't distribute with Windows 7.
  1613. // Currently we support only refreshing the list once ever. With a little effort we could revise this code to
  1614. // support re-refreshing the list at runtime to account for the possibility that modules have recently been
  1615. // added or removed.
  1616. if(pSymLoadModule64)
  1617. {
  1618. const size_t requiredCount = GetModuleInfoArray(ModuleInfoArray, OVR_ARRAY_COUNT(ModuleInfoArray));
  1619. ModuleInfoArraySize = MIN(requiredCount, OVR_ARRAY_COUNT(ModuleInfoArray));
  1620. HANDLE hProcess = GetCurrentProcess();
  1621. for(size_t i = 0; i < ModuleInfoArraySize; i++)
  1622. pSymLoadModule64(hProcess, nullptr, ModuleInfoArray[i].filePath, nullptr, ModuleInfoArray[i].baseAddress, (DWORD)ModuleInfoArray[i].size);
  1623. ModuleListUpdated = true;
  1624. }
  1625. #else
  1626. const size_t requiredCount = GetModuleInfoArray(ModuleInfoArray, OVR_ARRAY_COUNT(ModuleInfoArray));
  1627. ModuleInfoArraySize = MIN(requiredCount, OVR_ARRAY_COUNT(ModuleInfoArray));
  1628. ModuleListUpdated = true;
  1629. #endif
  1630. }
  1631. return true;
  1632. }
  1633. bool SymbolLookup::LookupSymbol(uint64_t address, SymbolInfo& symbolInfo)
  1634. {
  1635. return LookupSymbols(&address, &symbolInfo, 1);
  1636. }
  1637. bool SymbolLookup::LookupSymbols(uint64_t* addressArray, SymbolInfo* pSymbolInfoArray, size_t arraySize)
  1638. {
  1639. bool success = false;
  1640. if(!ModuleListUpdated)
  1641. {
  1642. RefreshModuleList();
  1643. }
  1644. #if defined(OVR_OS_MS)
  1645. OVR::Lock::Locker autoLock(&sDbgHelpLock);
  1646. union SYMBOL_INFO_UNION
  1647. {
  1648. SYMBOL_INFO msSymbolInfo;
  1649. char suffixPadding[sizeof(SYMBOL_INFO) + 1024];
  1650. };
  1651. for(size_t i = 0; i < arraySize; i++)
  1652. {
  1653. uint64_t& address = addressArray[i];
  1654. SymbolInfo& symbolInfo = pSymbolInfoArray[i];
  1655. // Copy the address and ModuleInfo
  1656. symbolInfo.address = addressArray[i];
  1657. symbolInfo.pModuleInfo = GetModuleInfoForAddress(address); // We could also use siu.msSymbolInfo.ModBase to get the module slightly faster.
  1658. // Get the function/offset.
  1659. SYMBOL_INFO_UNION siu;
  1660. memset(&siu, 0, sizeof(siu));
  1661. siu.msSymbolInfo.SizeOfStruct = sizeof(siu.msSymbolInfo);
  1662. siu.msSymbolInfo.MaxNameLen = sizeof(siu.suffixPadding) - sizeof(SYMBOL_INFO) + 1; // +1 because SYMBOL_INFO itself has Name[1].
  1663. HANDLE hProcess = GetCurrentProcess();
  1664. DWORD64 displacement64 = 0;
  1665. bool bResult = (pSymFromAddr != nullptr) && (pSymFromAddr(hProcess, address, &displacement64, &siu.msSymbolInfo) != FALSE);
  1666. if(bResult)
  1667. {
  1668. success = true;
  1669. symbolInfo.size = siu.msSymbolInfo.Size;
  1670. OVR_strlcpy(symbolInfo.function, siu.msSymbolInfo.Name, OVR_ARRAY_COUNT(symbolInfo.function));
  1671. symbolInfo.functionOffset = (int32_t)displacement64;
  1672. }
  1673. else
  1674. {
  1675. symbolInfo.size = kMISizeInvalid;
  1676. symbolInfo.function[0] = 0;
  1677. symbolInfo.functionOffset = kMIFunctionOffsetInvalid;
  1678. }
  1679. // Get the file/line
  1680. IMAGEHLP_LINE64 iLine64;
  1681. DWORD displacement = 0;
  1682. memset(&iLine64, 0, sizeof(iLine64));
  1683. iLine64.SizeOfStruct = sizeof(iLine64);
  1684. bResult = (pSymGetLineFromAddr64 != nullptr) && (pSymGetLineFromAddr64(hProcess, address, &displacement, &iLine64) != FALSE);
  1685. if(bResult)
  1686. {
  1687. success = true;
  1688. OVR_strlcpy(symbolInfo.filePath, iLine64.FileName, OVR_ARRAY_COUNT(symbolInfo.filePath));
  1689. symbolInfo.fileLineNumber = (int32_t)iLine64.LineNumber;
  1690. }
  1691. else
  1692. {
  1693. symbolInfo.filePath[0] = 0;
  1694. symbolInfo.fileLineNumber = kMILineNumberInvalid;
  1695. }
  1696. // To do: get the source code when possible. We need to use the user-registered directory paths and the symbolInfo.filePath
  1697. // and find the given file in the tree(s), then open the file and find the symbolInfo.fileLineNumber line (and surrounding lines).
  1698. // symbolInfo.sourceCode[1024]
  1699. symbolInfo.sourceCode[0] = '\0';
  1700. }
  1701. #elif defined(OVR_OS_APPLE)
  1702. // Apple has an internal CoreSymbolication library which could help with this.
  1703. // Third party implementations of the CoreSymbolication header are available and could be used
  1704. // to get file/line info better than other means. It used Objective C, so we'll need a .m or .mm file.
  1705. memset(pSymbolInfoArray, 0, arraySize * sizeof(SymbolInfo));
  1706. for(size_t i = 0; i < arraySize; i++)
  1707. {
  1708. pSymbolInfoArray[i].address = addressArray[i];
  1709. pSymbolInfoArray[i].pModuleInfo = GetModuleInfoForAddress(addressArray[i]);
  1710. }
  1711. // Problem: backtrace_symbols allocates memory from malloc. If you got into a SIGSEGV due to
  1712. // malloc arena corruption (quite common) you will likely fault in backtrace_symbols.
  1713. // To do: Use allowMemoryAllocation here.
  1714. #if (OVR_PTR_SIZE == 4)
  1715. // backtrace_symbols takes a void* array, but we have a uint64_t array. So for 32 bit we
  1716. // need to convert the 64 bit array to 32 bit temporarily for the backtrace_symbols call.
  1717. void* ptr32Array[256]; // To do: Remove this limit.
  1718. for(size_t i = 0, iEnd = MIN(arraySize, OVR_ARRAY_COUNT(ptr32Array)); i < iEnd; i++)
  1719. ptr32Array[i] = reinterpret_cast<void*>(addressArray[i]);
  1720. char** symbolArray = backtrace_symbols(reinterpret_cast<void**>(ptr32Array), (int)arraySize);
  1721. #else
  1722. char** symbolArray = backtrace_symbols(reinterpret_cast<void**>(addressArray), (int)arraySize);
  1723. #endif
  1724. if(symbolArray)
  1725. {
  1726. success = true;
  1727. for(size_t i = 0; i < arraySize; i++)
  1728. {
  1729. // Generates a string like this: "0 OculusWorldDemo 0x000000010000cfd5 _ZN18OculusWorldDemoApp9OnStartupEiPPKc + 213"
  1730. static_assert(OVR_ARRAY_COUNT(pSymbolInfoArray[i].function) == 128, "Need to change the string format size below");
  1731. sscanf(symbolArray[i], "%*d %*s %*x %128s + %d", pSymbolInfoArray[i].function, &pSymbolInfoArray[i].functionOffset);
  1732. if(AllowMemoryAllocation)
  1733. {
  1734. int status = 0;
  1735. char* strDemangled = abi::__cxa_demangle(pSymbolInfoArray[i].function, nullptr, nullptr, &status);
  1736. if(strDemangled)
  1737. {
  1738. OVR_strlcpy(pSymbolInfoArray[i].function, strDemangled, OVR_ARRAY_COUNT(pSymbolInfoArray[i].function));
  1739. free(strDemangled);
  1740. }
  1741. }
  1742. }
  1743. free(symbolArray);
  1744. }
  1745. // To consider: use CoreSybolication to get file/line info instead. atos is a bit slow and cumbersome.
  1746. // https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/atos.1.html
  1747. // atos -p <pid> <addr> <addr> ...
  1748. // atos -o <binary image path> -l <load-address> <addr> <addr> ...
  1749. // Generates output like this: "OVR::CreateException(OVR::CreateExceptionType) (in OculusWorldDemo) (ExceptionHandler.cpp:598)"
  1750. for(size_t i = 0; i < arraySize; i++)
  1751. {
  1752. struct stat statStruct;
  1753. if(pSymbolInfoArray[i].pModuleInfo && pSymbolInfoArray[i].pModuleInfo->filePath[0] && (stat(pSymbolInfoArray[i].pModuleInfo->filePath, &statStruct) == 0))
  1754. {
  1755. char command[PATH_MAX * 2]; // Problem: We can't unilaterally use pSymbolInfoArray[0] for all addresses. We need to match addresses to the corresponding modules.
  1756. // FIXME: atos is moving. Should start with 'xcrun atos'.
  1757. OVR_snprintf(command, OVR_ARRAY_COUNT(command), "atos -o %s -l 0x%llx 0x%llx",
  1758. pSymbolInfoArray[i].pModuleInfo->filePath, (int64_t)pSymbolInfoArray[i].pModuleInfo->baseAddress, (int64_t)pSymbolInfoArray[i].address);
  1759. char output[512];
  1760. if(SpawnShellCommand(command, output, OVR_ARRAY_COUNT(output)) != (size_t)-1)
  1761. {
  1762. char* pLastOpenParen = strrchr(output, '(');
  1763. char* pColon = strrchr(output, ':');
  1764. if(pLastOpenParen && (pColon > pLastOpenParen))
  1765. {
  1766. *pColon = '\0';
  1767. OVR_strlcpy(pSymbolInfoArray[i].filePath, pLastOpenParen + 1, OVR_ARRAY_COUNT(pSymbolInfoArray[i].filePath));
  1768. }
  1769. }
  1770. }
  1771. }
  1772. #elif defined(OVR_OS_LINUX)
  1773. // We can use libunwind's unw_get_proc_name to try to get function name info. It can work regardless of relocation.
  1774. // Use backtrace_symbols and addr2line. Need to watch out for module load-time relocation.
  1775. // Ned to pass the -rdynamic flag to the linker. It will cause the linker to out in the link
  1776. // tables the name of all the none static functions in your code, not just the exported ones.
  1777. OVR_UNUSED(addressArray);
  1778. OVR_UNUSED(pSymbolInfoArray);
  1779. OVR_UNUSED(arraySize);
  1780. #endif
  1781. return success;
  1782. }
  1783. const ModuleInfo* SymbolLookup::GetModuleInfoForAddress(uint64_t address)
  1784. {
  1785. // This is a linear seach. To consider: it would be significantly faster to search by
  1786. // address if we ordered it by base address and did a binary search.
  1787. for(size_t i = 0; i < ModuleInfoArraySize; ++i)
  1788. {
  1789. const ModuleInfo& mi = ModuleInfoArray[i];
  1790. if((mi.baseAddress <= address) && (address < (mi.baseAddress + mi.size)))
  1791. return &mi;
  1792. }
  1793. return nullptr;
  1794. }
  1795. ExceptionInfo::ExceptionInfo()
  1796. : time()
  1797. , timeVal(0)
  1798. , backtrace()
  1799. , backtraceCount(0)
  1800. , threadHandle(OVR_THREADHANDLE_INVALID)
  1801. , threadSysId(OVR_THREADSYSID_INVALID)
  1802. , threadName()
  1803. , pExceptionInstructionAddress(nullptr)
  1804. , pExceptionMemoryAddress(nullptr)
  1805. , cpuContext()
  1806. , exceptionDescription()
  1807. , symbolInfo()
  1808. #if defined(OVR_OS_MS)
  1809. , exceptionRecord()
  1810. #elif defined(OVR_OS_APPLE)
  1811. , exceptionType(0)
  1812. , cpuExceptionId(0)
  1813. , cpuExceptionIdError(0)
  1814. , machExceptionData()
  1815. , machExceptionDataCount(0)
  1816. #endif
  1817. {
  1818. }
  1819. ExceptionHandler::ExceptionHandler()
  1820. : enabled(false)
  1821. , pauseCount(0)
  1822. , reportPrivacyEnabled(true)
  1823. , exceptionResponse(kERHandle)
  1824. , exceptionListener(nullptr)
  1825. , exceptionListenerUserValue(0)
  1826. , appDescription()
  1827. , codeBasePathArray()
  1828. , reportFilePath()
  1829. , miniDumpFlags(0)
  1830. , miniDumpFilePath()
  1831. , LogFile(nullptr)
  1832. , scratchBuffer()
  1833. , exceptionOccurred(false)
  1834. , handlingBusy(0)
  1835. , reportFilePathActual()
  1836. , minidumpFilePathActual()
  1837. , terminateReturnValue(0)
  1838. , exceptionInfo()
  1839. #if defined(OVR_OS_MS)
  1840. , vectoredHandle(nullptr)
  1841. , previousFilter(nullptr)
  1842. , pExceptionPointers(nullptr)
  1843. #elif defined(OVR_OS_MAC)
  1844. , machHandlerInitialized(false)
  1845. , machExceptionPort(0)
  1846. , machExceptionPortsSaved()
  1847. , machThreadShouldContinue(false)
  1848. , machThreadExecuting(false)
  1849. , machThread((pthread_t)OVR_THREADHANDLE_INVALID)
  1850. #endif
  1851. {
  1852. SetExceptionPaths("default", "default");
  1853. }
  1854. void ExceptionHandler::SetPathsFromNames(const char* organizationName, const char* ApplicationName, const char* exceptionFormat, const char* minidumpFormat)
  1855. {
  1856. char exceptionPath[OVR_MAX_PATH];
  1857. char miniDumpPath[OVR_MAX_PATH];
  1858. GetCrashDumpDirectory(exceptionPath, OVR_MAX_PATH);
  1859. OVR_strlcat(exceptionPath, organizationName, OVR_MAX_PATH);
  1860. //make the organization folder if necessary
  1861. #ifdef OVR_OS_MS
  1862. WCHAR wpath[128];
  1863. OVR::UTF8Util::DecodeString(wpath, exceptionPath);
  1864. CreateDirectoryW(wpath,NULL);
  1865. #else
  1866. mkdir(exceptionPath,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
  1867. #endif
  1868. #ifdef OVR_OS_MS
  1869. const char* separator = "\\";
  1870. #else
  1871. const char* separator = "/";
  1872. #endif
  1873. OVR_strlcat(exceptionPath, separator, OVR_MAX_PATH);
  1874. OVR_strlcat(exceptionPath, ApplicationName, OVR_MAX_PATH);
  1875. #ifdef OVR_OS_MS
  1876. OVR::UTF8Util::DecodeString(wpath, exceptionPath);
  1877. CreateDirectoryW(wpath, NULL);
  1878. #else
  1879. mkdir(exceptionPath,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
  1880. #endif
  1881. OVR_strlcat(exceptionPath, separator, OVR_MAX_PATH);
  1882. OVR_strcpy(miniDumpPath, OVR_MAX_PATH, exceptionPath);
  1883. OVR::OVR_strlcat(exceptionPath, exceptionFormat, OVR_MAX_PATH);
  1884. OVR::OVR_strlcat(miniDumpPath, minidumpFormat, OVR_MAX_PATH);
  1885. SetExceptionPaths(exceptionPath, miniDumpPath);
  1886. }
  1887. ExceptionHandler::~ExceptionHandler()
  1888. {
  1889. if(enabled)
  1890. {
  1891. Enable(false);
  1892. }
  1893. }
  1894. size_t ExceptionHandler::GetCrashDumpDirectory(char* directoryPath, size_t directoryPathCapacity)
  1895. {
  1896. #if defined(OVR_OS_MS)
  1897. wchar_t pathW[OVR_MAX_PATH];
  1898. HRESULT hr = SHGetFolderPathW(nullptr, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, pathW); // Expects pathW to be MAX_PATH. The returned path does not include a trailing backslash.
  1899. if (SUCCEEDED(hr))
  1900. {
  1901. intptr_t requiredUTF8Length = OVR::UTF8Util::GetEncodeStringSize(pathW); // Returns required strlen. Never returns a negative value.
  1902. if ((size_t)requiredUTF8Length < directoryPathCapacity) // We need space for a trailing path separator.
  1903. {
  1904. OVR::UTF8Util::EncodeString(directoryPath, pathW, -1);
  1905. if((requiredUTF8Length == 0) || (directoryPath[requiredUTF8Length - 1] != '\\')) // If there is no trailing \ char...
  1906. {
  1907. OVR::OVR_strlcat(directoryPath, "\\", directoryPathCapacity);
  1908. requiredUTF8Length++;
  1909. }
  1910. }
  1911. return requiredUTF8Length; // Returns the required strlen.
  1912. }
  1913. #elif defined(OVR_OS_MAC)
  1914. // This is the same location that Apple puts its OS-generated .crash files.
  1915. const char* home = getenv("HOME");
  1916. size_t requiredStrlen = OVR::OVR_snprintf(directoryPath, directoryPathCapacity, "%s/Library/Logs/DiagnosticReports/", home ? home : "/Users/Shared/Logs/DiagnosticReports/");
  1917. // To do: create the directory if it doesn't already exist.
  1918. return requiredStrlen;
  1919. #elif defined(OVR_OS_UNIX)
  1920. const char* home = getenv("HOME");
  1921. size_t requiredStrlen = OVR::OVR_snprintf(directoryPath, directoryPathCapacity, "%s/Library/", home ? home : "/Users/Shared/");
  1922. // To do: create the directory if it doesn't already exist.
  1923. return requiredStrlen;
  1924. #endif
  1925. return 0;
  1926. }
  1927. #if defined(OVR_OS_MS)
  1928. static ExceptionHandler* sExceptionHandler = nullptr;
  1929. unsigned WINAPI ExceptionHandler::ExceptionHandlerThreadExec(void * callingHandler)
  1930. {
  1931. ExceptionHandler* caller = reinterpret_cast<ExceptionHandler*>(callingHandler);
  1932. if (caller->miniDumpFilePath[0])
  1933. caller->WriteMiniDump();
  1934. if (caller->reportFilePath[0])
  1935. caller->WriteReport();
  1936. if (caller->exceptionListener)
  1937. caller->exceptionListener->HandleException(caller->exceptionListenerUserValue, caller, &caller->exceptionInfo, caller->reportFilePathActual);
  1938. return 1;
  1939. }
  1940. LONG WINAPI Win32ExceptionFilter(LPEXCEPTION_POINTERS pExceptionPointersArg)
  1941. {
  1942. if(sExceptionHandler)
  1943. return (LONG)sExceptionHandler->ExceptionFilter(pExceptionPointersArg);
  1944. return EXCEPTION_CONTINUE_SEARCH;
  1945. }
  1946. LONG ExceptionHandler::ExceptionFilter(LPEXCEPTION_POINTERS pExceptionPointersArg)
  1947. {
  1948. if(pauseCount)
  1949. return EXCEPTION_CONTINUE_SEARCH;
  1950. // Exception codes < 0x80000000 are not true exceptions but rather are debugger notifications. They include DBG_TERMINATE_THREAD,
  1951. // DBG_TERMINATE_PROCESS, DBG_CONTROL_BREAK, DBG_COMMAND_EXCEPTION, DBG_CONTROL_C, DBG_PRINTEXCEPTION_C, DBG_RIPEXCEPTION,
  1952. // and 0x406d1388 (thread named, http://blogs.msdn.com/b/stevejs/archive/2005/12/19/505815.aspx).
  1953. if(pExceptionPointersArg->ExceptionRecord->ExceptionCode < 0x80000000)
  1954. return EXCEPTION_CONTINUE_SEARCH;
  1955. // VC++ C++ exceptions use code 0xe06d7363 ('Emsc')
  1956. // http://support.microsoft.com/kb/185294
  1957. // http://blogs.msdn.com/b/oldnewthing/archive/2010/07/30/10044061.aspx
  1958. if(pExceptionPointersArg->ExceptionRecord->ExceptionCode == 0xe06d7363)
  1959. return EXCEPTION_CONTINUE_SEARCH;
  1960. if(handlingBusy.CompareAndSet_Acquire(0, 1)) // If we can successfully change it from 0 to 1.
  1961. {
  1962. exceptionOccurred = true;
  1963. SymbolLookup::Initialize();
  1964. this->pExceptionPointers = pExceptionPointersArg;
  1965. // Disable the handler while we do this processing.
  1966. ULONG result = RemoveVectoredExceptionHandler(vectoredHandle);
  1967. OVR_ASSERT_AND_UNUSED(result != 0, result);
  1968. // Time
  1969. exceptionInfo.timeVal = time(nullptr);
  1970. exceptionInfo.time = *gmtime(&exceptionInfo.timeVal);
  1971. // Thread id
  1972. // This is the thread id of the current thread and not the exception thread.
  1973. if(!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &exceptionInfo.threadHandle, 0, true, DUPLICATE_SAME_ACCESS))
  1974. exceptionInfo.threadHandle = 0;
  1975. exceptionInfo.threadSysId = ConvertThreadHandleToThreadSysId(exceptionInfo.threadHandle);
  1976. OVR::GetThreadName(exceptionInfo.threadHandle, exceptionInfo.threadName, OVR_ARRAY_COUNT(exceptionInfo.threadName));
  1977. // Backtraces
  1978. exceptionInfo.backtraceCount = symbolLookup.GetBacktrace(exceptionInfo.backtrace, OVR_ARRAY_COUNT(exceptionInfo.backtrace));
  1979. // Context
  1980. exceptionInfo.cpuContext = *pExceptionPointersArg->ContextRecord;
  1981. exceptionInfo.exceptionRecord = *pExceptionPointersArg->ExceptionRecord;
  1982. exceptionInfo.pExceptionInstructionAddress = exceptionInfo.exceptionRecord.ExceptionAddress;
  1983. if((exceptionInfo.exceptionRecord.ExceptionCode == EXCEPTION_ACCESS_VIOLATION) || (exceptionInfo.exceptionRecord.ExceptionCode == EXCEPTION_IN_PAGE_ERROR))
  1984. exceptionInfo.pExceptionMemoryAddress = (void*)exceptionInfo.exceptionRecord.ExceptionInformation[1]; // ExceptionInformation[0] indicates if it was a read (0), write (1), or data execution attempt (8).
  1985. else
  1986. exceptionInfo.pExceptionMemoryAddress = pExceptionPointersArg->ExceptionRecord->ExceptionAddress;
  1987. WriteExceptionDescription();
  1988. if (pExceptionPointersArg->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW){
  1989. unsigned int IdValue;
  1990. void* ThreadHandle = (HANDLE)_beginthreadex(0, (unsigned)128 * 1024,
  1991. ExceptionHandlerThreadExec, this, 0, (unsigned*)&IdValue);
  1992. WaitForSingleObject(ThreadHandle, INFINITE);
  1993. CloseHandle(ThreadHandle);
  1994. }
  1995. else
  1996. {
  1997. if (miniDumpFilePath[0])
  1998. WriteMiniDump();
  1999. if (reportFilePath[0])
  2000. WriteReport();
  2001. if (exceptionListener)
  2002. exceptionListener->HandleException(exceptionListenerUserValue, this, &exceptionInfo, reportFilePathActual);
  2003. }
  2004. if(exceptionInfo.threadHandle)
  2005. {
  2006. CloseHandle(exceptionInfo.threadHandle);
  2007. exceptionInfo.threadHandle = 0;
  2008. }
  2009. SymbolLookup::Shutdown();
  2010. // Restore the handler that we temporarily disabled above.
  2011. vectoredHandle = AddVectoredExceptionHandler(1, Win32ExceptionFilter);
  2012. handlingBusy.Store_Release(0);
  2013. }
  2014. if(exceptionResponse == ExceptionHandler::kERContinue)
  2015. return EXCEPTION_CONTINUE_EXECUTION;
  2016. else if(exceptionResponse == ExceptionHandler::kERHandle)
  2017. return EXCEPTION_EXECUTE_HANDLER;
  2018. else if(exceptionResponse == ExceptionHandler::kERTerminate)
  2019. {
  2020. TerminateProcess(GetCurrentProcess(), (UINT)terminateReturnValue);
  2021. return terminateReturnValue;
  2022. }
  2023. else if(exceptionResponse == ExceptionHandler::kERThrow)
  2024. return EXCEPTION_CONTINUE_SEARCH;
  2025. // kERDefault
  2026. return EXCEPTION_EXECUTE_HANDLER;
  2027. }
  2028. #endif // defined(OVR_OS_MS)
  2029. #if defined(OVR_OS_APPLE)
  2030. // http://www.opensource.apple.com/source/xnu/xnu-2050.22.13/
  2031. // http://www.opensource.apple.com/source/xnu/xnu-2050.22.13/osfmk/man/
  2032. // http://www.opensource.apple.com/source/Libc/Libc-825.26/
  2033. // https://mikeash.com/pyblog/friday-qa-2013-01-11-mach-exception-handlers.html
  2034. void* ExceptionHandler::MachHandlerThreadFunction()
  2035. {
  2036. __Request__mach_exception_raise_state_identity_t msg;
  2037. __Reply__mach_exception_raise_state_identity_t reply;
  2038. mach_msg_return_t result;
  2039. machThreadExecuting = true;
  2040. pthread_setname_np("ExceptionHandler");
  2041. while(machThreadShouldContinue)
  2042. {
  2043. mach_msg_option_t options = MACH_RCV_MSG | MACH_RCV_LARGE;
  2044. natural_t timeout = 0; // Would be better to support a non-zero time.
  2045. if(timeout)
  2046. options |= MACH_RCV_TIMEOUT;
  2047. result = mach_msg(&msg.Head, options, 0, sizeof(msg), machExceptionPort, timeout, MACH_PORT_NULL);
  2048. if(msg.Head.msgh_id != sMachCancelMessageType)
  2049. {
  2050. if(result == MACH_MSG_SUCCESS)
  2051. {
  2052. if(mach_exc_server_OVR(&msg.Head, &reply.Head) == 0) //This will call our HandleMachException function.
  2053. result = ~MACH_MSG_SUCCESS;
  2054. }
  2055. // Send the reply
  2056. if(result == MACH_MSG_SUCCESS)
  2057. {
  2058. result = mach_msg(&reply.Head, MACH_SEND_MSG, reply.Head.msgh_size, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
  2059. if(result != MACH_MSG_SUCCESS)
  2060. {
  2061. // Failure.
  2062. }
  2063. }
  2064. }
  2065. }
  2066. machThreadExecuting = false;
  2067. return nullptr;
  2068. }
  2069. kern_return_t ExceptionHandler::HandleMachException(mach_port_t /*machPort*/, mach_port_t threadSysId, mach_port_t machTask,
  2070. exception_type_t machExceptionType, mach_exception_data_type_t* pMachExceptionData,
  2071. mach_msg_type_number_t exceptionDataCount, int* /*pMachExceptionFlavor*/, thread_state_t threadStatePrev,
  2072. mach_msg_type_number_t /*threadStatePrevCount*/, thread_state_t /*threadStateNew*/,
  2073. mach_msg_type_number_t* /*pThreadStateNewCount*/)
  2074. {
  2075. // We don't want to handle exceptions for other processes.
  2076. if(machTask != mach_task_self())
  2077. return ForwardMachException(threadSysId, machTask, machExceptionType, pMachExceptionData, exceptionDataCount);
  2078. if(handlingBusy.CompareAndSet_Acquire(0, 1)) // If we can successfully change it from 0 to 1.
  2079. {
  2080. exceptionOccurred = true;
  2081. // Disable the handler while we do this processing.
  2082. // To do.
  2083. // Time
  2084. exceptionInfo.timeVal = time(nullptr);
  2085. exceptionInfo.time = *gmtime(&exceptionInfo.timeVal);
  2086. // Thread id
  2087. exceptionInfo.threadHandle = pthread_from_mach_thread_np(threadSysId);
  2088. exceptionInfo.threadSysId = threadSysId;
  2089. pthread_getname_np((pthread_t)exceptionInfo.threadHandle, exceptionInfo.threadName, sizeof(exceptionInfo.threadName));
  2090. // Backtraces
  2091. exceptionInfo.backtraceCount = symbolLookup.GetBacktraceFromThreadSysId(exceptionInfo.backtrace, OVR_ARRAY_COUNT(exceptionInfo.backtrace), 0, threadSysId);
  2092. // Context
  2093. #if defined(OVR_CPU_X86) || defined(OVR_CPU_X86_64)
  2094. // We can read x86_THREAD_STATE directly fromk threadStatePrev.
  2095. exceptionInfo.cpuContext.threadState = *reinterpret_cast<x86_thread_state_t*>(threadStatePrev);
  2096. mach_msg_type_number_t stateCount = x86_FLOAT_STATE_COUNT;
  2097. thread_get_state(threadSysId, x86_FLOAT_STATE, (natural_t*)&exceptionInfo.cpuContext.floatState, &stateCount);
  2098. stateCount = x86_DEBUG_STATE_COUNT;
  2099. thread_get_state(threadSysId, x86_DEBUG_STATE, (natural_t*)&exceptionInfo.cpuContext.debugState, &stateCount);
  2100. stateCount = x86_AVX_STATE_COUNT;
  2101. thread_get_state(threadSysId, x86_AVX_STATE, (natural_t*)&exceptionInfo.cpuContext.avxState, &stateCount);
  2102. stateCount = x86_EXCEPTION_STATE_COUNT;
  2103. thread_get_state(threadSysId, x86_EXCEPTION_STATE, (natural_t*)&exceptionInfo.cpuContext.exceptionState, &stateCount);
  2104. #if defined(OVR_CPU_X86)
  2105. exceptionInfo.pExceptionInstructionAddress = (void*)exceptionInfo.cpuContext.threadState.uts.ts32.__eip;
  2106. exceptionInfo.pExceptionMemoryAddress = (void*)exceptionInfo.cpuContext.exceptionState.ues.es32.__faultvaddr;
  2107. exceptionInfo.cpuExceptionId = exceptionInfo.cpuContext.exceptionState.ues.es32.__trapno;
  2108. exceptionInfo.cpuExceptionIdError = exceptionInfo.cpuContext.exceptionState.ues.es32.__err;
  2109. #else
  2110. exceptionInfo.pExceptionInstructionAddress = (void*)exceptionInfo.cpuContext.threadState.uts.ts64.__rip;
  2111. exceptionInfo.pExceptionMemoryAddress = (void*)exceptionInfo.cpuContext.exceptionState.ues.es64.__faultvaddr;
  2112. exceptionInfo.cpuExceptionId = exceptionInfo.cpuContext.exceptionState.ues.es64.__trapno;
  2113. exceptionInfo.cpuExceptionIdError = exceptionInfo.cpuContext.exceptionState.ues.es64.__err;
  2114. #endif
  2115. #endif
  2116. exceptionInfo.exceptionType = machExceptionType;
  2117. exceptionInfo.machExceptionDataCount = MIN(exceptionDataCount, OVR_ARRAY_COUNT(exceptionInfo.machExceptionData));
  2118. for(int i = 0; i < exceptionInfo.machExceptionDataCount; i++)
  2119. exceptionInfo.machExceptionData[i] = pMachExceptionData[i];
  2120. WriteExceptionDescription();
  2121. if(reportFilePath[0])
  2122. WriteReport();
  2123. if(miniDumpFilePath[0])
  2124. WriteMiniDump();
  2125. if(exceptionListener)
  2126. exceptionListener->HandleException(exceptionListenerUserValue, this, &exceptionInfo, reportFilePathActual);
  2127. // Re-restore the handler.
  2128. // To do.
  2129. handlingBusy.Store_Release(0);
  2130. }
  2131. kern_return_t result = KERN_FAILURE; // By default pass on the exception to another handler after we are done here.
  2132. if(exceptionResponse == ExceptionHandler::kERContinue)
  2133. result = KERN_SUCCESS; // This will trigger a re-execution of the function.
  2134. else if(exceptionResponse == ExceptionHandler::kERTerminate)
  2135. ::exit(terminateReturnValue);
  2136. else if(exceptionResponse == ExceptionHandler::kERThrow)
  2137. ForwardMachException(threadSysId, machTask, machExceptionType, pMachExceptionData, exceptionDataCount);
  2138. else if(exceptionResponse == ExceptionHandler::kERDefault)
  2139. ::exit(terminateReturnValue);
  2140. // kERHandle
  2141. return result;
  2142. }
  2143. bool ExceptionHandler::InitMachExceptionHandler()
  2144. {
  2145. if(!machHandlerInitialized)
  2146. {
  2147. mach_port_t machTaskSelf = mach_task_self();
  2148. kern_return_t result = MACH_MSG_SUCCESS;
  2149. exception_mask_t mask = EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION | EXC_MASK_ARITHMETIC | EXC_MASK_CRASH;
  2150. if(machExceptionPort == MACH_PORT_NULL)
  2151. {
  2152. result = mach_port_allocate(machTaskSelf, MACH_PORT_RIGHT_RECEIVE, &machExceptionPort);
  2153. if(result == MACH_MSG_SUCCESS)
  2154. {
  2155. result = mach_port_insert_right(machTaskSelf, machExceptionPort, machExceptionPort, MACH_MSG_TYPE_MAKE_SEND);
  2156. if(result == MACH_MSG_SUCCESS)
  2157. result = task_get_exception_ports(machTaskSelf, mask, machExceptionPortsSaved.masks, &machExceptionPortsSaved.count,
  2158. machExceptionPortsSaved.ports, machExceptionPortsSaved.behaviors, machExceptionPortsSaved.flavors);
  2159. }
  2160. }
  2161. if(result == MACH_MSG_SUCCESS)
  2162. {
  2163. result = task_set_exception_ports(machTaskSelf, mask, machExceptionPort, EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, MACHINE_THREAD_STATE);
  2164. if(result == MACH_MSG_SUCCESS)
  2165. {
  2166. machThreadShouldContinue = true;
  2167. pthread_attr_t attr;
  2168. pthread_attr_init(&attr);
  2169. result = pthread_create(&machThread, &attr, MachHandlerThreadFunctionStatic, (void*)this);
  2170. pthread_attr_destroy(&attr);
  2171. machHandlerInitialized = (result == 0);
  2172. }
  2173. }
  2174. if(!machHandlerInitialized)
  2175. ShutdownMachExceptionHandler();
  2176. }
  2177. return machHandlerInitialized;
  2178. }
  2179. void ExceptionHandler::ShutdownMachExceptionHandler()
  2180. {
  2181. if(machThreadExecuting)
  2182. {
  2183. machThreadShouldContinue = false; // Tell it to stop.
  2184. // Cancel the current exception handler thread (which is probably blocking in a call to mach_msg) by sending it a cencel message.
  2185. struct CancelMessage
  2186. {
  2187. mach_msg_header_t msgHeader;
  2188. };
  2189. CancelMessage msg;
  2190. memset(&msg.msgHeader, 0, sizeof(CancelMessage));
  2191. msg.msgHeader.msgh_id = sMachCancelMessageType;
  2192. msg.msgHeader.msgh_size = sizeof(CancelMessage);
  2193. msg.msgHeader.msgh_bits = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_MAKE_SEND);
  2194. msg.msgHeader.msgh_remote_port = machExceptionPort;
  2195. msg.msgHeader.msgh_local_port = MACH_PORT_NULL;
  2196. mach_msg_return_t result = mach_msg(&msg.msgHeader, MACH_SEND_MSG, msg.msgHeader.msgh_size, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
  2197. if(result == MACH_MSG_SUCCESS)
  2198. {
  2199. const time_t secondsLater = time(NULL) + 4;
  2200. while(machThreadExecuting && (time(NULL) < secondsLater))
  2201. {
  2202. timespec ts = { 0, 1000000000 };
  2203. nanosleep(&ts, nullptr);
  2204. }
  2205. }
  2206. void* joinResult = nullptr;
  2207. pthread_join(machThread, &joinResult);
  2208. machThread = 0;
  2209. }
  2210. if(machExceptionPort != MACH_PORT_NULL)
  2211. {
  2212. // Restore the previous ports
  2213. kern_return_t result = KERN_SUCCESS;
  2214. mach_port_t machTaskSelf = mach_task_self();
  2215. for(unsigned i = 0; (i < machExceptionPortsSaved.count) && (result == KERN_SUCCESS); i++)
  2216. {
  2217. result = task_set_exception_ports(machTaskSelf, machExceptionPortsSaved.masks[i], machExceptionPortsSaved.ports[i],
  2218. machExceptionPortsSaved.behaviors[i], machExceptionPortsSaved.flavors[i]);
  2219. }
  2220. mach_port_deallocate(machTaskSelf, machExceptionPort);
  2221. machExceptionPort = MACH_PORT_NULL;
  2222. }
  2223. machHandlerInitialized = false;
  2224. }
  2225. kern_return_t ExceptionHandler::ForwardMachException(mach_port_t thread, mach_port_t task, exception_type_t exceptionType,
  2226. mach_exception_data_t pMachExceptionData, mach_msg_type_number_t exceptionDataCount)
  2227. {
  2228. kern_return_t result = KERN_FAILURE;
  2229. mach_msg_type_number_t i;
  2230. for(i = 0; i < machExceptionPortsSaved.count; i++)
  2231. {
  2232. if(machExceptionPortsSaved.masks[i] & (1 << exceptionType))
  2233. break;
  2234. }
  2235. if(i < machExceptionPortsSaved.count)
  2236. {
  2237. mach_port_t port = machExceptionPortsSaved.ports[i];
  2238. exception_behavior_t behavior = machExceptionPortsSaved.behaviors[i];
  2239. thread_state_flavor_t flavor = machExceptionPortsSaved.flavors[i];
  2240. mach_msg_type_number_t threadStateCount = THREAD_STATE_MAX;
  2241. thread_state_data_t threadState;
  2242. if(behavior != EXCEPTION_DEFAULT)
  2243. thread_get_state(thread, flavor, threadState, &threadStateCount);
  2244. switch(behavior)
  2245. {
  2246. case EXCEPTION_DEFAULT:
  2247. result = mach_exception_raise_OVR(port, thread, task, exceptionType, pMachExceptionData, exceptionDataCount);
  2248. break;
  2249. case EXCEPTION_STATE:
  2250. result = mach_exception_raise_state_OVR(port, exceptionType, pMachExceptionData, exceptionDataCount,
  2251. &flavor, threadState, threadStateCount, threadState, &threadStateCount);
  2252. break;
  2253. case EXCEPTION_STATE_IDENTITY:
  2254. result = mach_exception_raise_state_identity_OVR(port, thread, task, exceptionType, pMachExceptionData,
  2255. exceptionDataCount, &flavor, threadState, threadStateCount, threadState, &threadStateCount);
  2256. break;
  2257. default:
  2258. result = KERN_FAILURE;
  2259. break;
  2260. }
  2261. if(behavior != EXCEPTION_DEFAULT)
  2262. result = thread_set_state(thread, flavor, threadState, threadStateCount);
  2263. }
  2264. return result;
  2265. }
  2266. #endif // OVR_OS_APPLE
  2267. bool ExceptionHandler::Enable(bool enable)
  2268. {
  2269. #if defined(OVR_OS_MS)
  2270. if(enable && !enabled)
  2271. {
  2272. OVR_ASSERT(vectoredHandle == nullptr);
  2273. vectoredHandle = AddVectoredExceptionHandler(1, Win32ExceptionFilter); // Windows call.
  2274. enabled = (vectoredHandle != nullptr);
  2275. OVR_ASSERT(enabled);
  2276. sExceptionHandler = this;
  2277. return enabled;
  2278. }
  2279. else if(!enable && enabled)
  2280. {
  2281. if(sExceptionHandler == this)
  2282. sExceptionHandler = nullptr;
  2283. OVR_ASSERT(vectoredHandle != nullptr);
  2284. ULONG result = RemoveVectoredExceptionHandler(vectoredHandle); // Windows call.
  2285. OVR_ASSERT_AND_UNUSED(result != 0, result);
  2286. vectoredHandle = nullptr;
  2287. enabled = false;
  2288. return true;
  2289. }
  2290. #elif defined(OVR_OS_APPLE)
  2291. if(enable && !enabled)
  2292. {
  2293. enabled = InitMachExceptionHandler();
  2294. OVR_ASSERT(enabled);
  2295. sExceptionHandler = this;
  2296. return enabled;
  2297. }
  2298. else if(!enable && enabled)
  2299. {
  2300. if(sExceptionHandler == this)
  2301. sExceptionHandler = nullptr;
  2302. ShutdownMachExceptionHandler();
  2303. enabled = false;
  2304. return true;
  2305. }
  2306. #else
  2307. OVR_UNUSED(enable);
  2308. #endif
  2309. return true;
  2310. }
  2311. int ExceptionHandler::PauseHandling(bool pause)
  2312. {
  2313. if(pause)
  2314. return ++pauseCount;
  2315. OVR_ASSERT(pauseCount > 0);
  2316. return --pauseCount;
  2317. }
  2318. void ExceptionHandler::EnableReportPrivacy(bool enable)
  2319. {
  2320. reportPrivacyEnabled = enable;
  2321. }
  2322. void ExceptionHandler::WriteExceptionDescription()
  2323. {
  2324. #if defined(OVR_OS_MS)
  2325. // There is some extra information available for AV exception.
  2326. if(exceptionInfo.exceptionRecord.ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
  2327. {
  2328. const char* error = (exceptionInfo.exceptionRecord.ExceptionInformation[0] == 0) ? "reading" :
  2329. ((exceptionInfo.exceptionRecord.ExceptionInformation[0] == 1) ? "writing" : "executing");
  2330. char addressStr[24];
  2331. SprintfAddress(addressStr, OVR_ARRAY_COUNT(addressStr), exceptionInfo.pExceptionMemoryAddress);
  2332. OVR::OVR_snprintf(exceptionInfo.exceptionDescription, OVR_ARRAY_COUNT(exceptionInfo.exceptionDescription), "ACCESS_VIOLATION %s address %s", error, addressStr);
  2333. }
  2334. else
  2335. {
  2336. exceptionInfo.exceptionDescription[0] = 0;
  2337. // Process "standard" exceptions, other than 'access violation'
  2338. #define FORMAT_EXCEPTION(x) \
  2339. case EXCEPTION_##x: \
  2340. OVR::OVR_strlcpy(exceptionInfo.exceptionDescription, #x, OVR_ARRAY_COUNT(exceptionInfo.exceptionDescription)); \
  2341. break;
  2342. switch(exceptionInfo.exceptionRecord.ExceptionCode)
  2343. {
  2344. //FORMAT_EXCEPTION(ACCESS_VIOLATION) Already handled above.
  2345. FORMAT_EXCEPTION(DATATYPE_MISALIGNMENT)
  2346. FORMAT_EXCEPTION(BREAKPOINT)
  2347. FORMAT_EXCEPTION(SINGLE_STEP)
  2348. FORMAT_EXCEPTION(ARRAY_BOUNDS_EXCEEDED)
  2349. FORMAT_EXCEPTION(FLT_DENORMAL_OPERAND)
  2350. FORMAT_EXCEPTION(FLT_DIVIDE_BY_ZERO)
  2351. FORMAT_EXCEPTION(FLT_INEXACT_RESULT)
  2352. FORMAT_EXCEPTION(FLT_INVALID_OPERATION)
  2353. FORMAT_EXCEPTION(FLT_OVERFLOW)
  2354. FORMAT_EXCEPTION(FLT_STACK_CHECK)
  2355. FORMAT_EXCEPTION(FLT_UNDERFLOW)
  2356. FORMAT_EXCEPTION(INT_DIVIDE_BY_ZERO)
  2357. FORMAT_EXCEPTION(INT_OVERFLOW)
  2358. FORMAT_EXCEPTION(PRIV_INSTRUCTION)
  2359. FORMAT_EXCEPTION(IN_PAGE_ERROR)
  2360. FORMAT_EXCEPTION(ILLEGAL_INSTRUCTION)
  2361. FORMAT_EXCEPTION(NONCONTINUABLE_EXCEPTION)
  2362. FORMAT_EXCEPTION(STACK_OVERFLOW)
  2363. FORMAT_EXCEPTION(INVALID_DISPOSITION)
  2364. FORMAT_EXCEPTION(GUARD_PAGE)
  2365. FORMAT_EXCEPTION(INVALID_HANDLE)
  2366. #if defined(EXCEPTION_POSSIBLE_DEADLOCK) && defined(STATUS_POSSIBLE_DEADLOCK) // This type seems to be non-existant in practice.
  2367. FORMAT_EXCEPTION(POSSIBLE_DEADLOCK)
  2368. #endif
  2369. }
  2370. // If not one of the "known" exceptions, try to get the string from NTDLL.DLL's message table.
  2371. if(exceptionInfo.exceptionDescription[0] == 0)
  2372. {
  2373. char addressStr[24];
  2374. SprintfAddress(addressStr, OVR_ARRAY_COUNT(addressStr), exceptionInfo.pExceptionMemoryAddress);
  2375. char buffer[384];
  2376. DWORD capacity = OVR_ARRAY_COUNT(buffer);
  2377. const size_t length = (size_t)FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_HMODULE,
  2378. GetModuleHandleW(L"NTDLL.DLL"), exceptionInfo.exceptionRecord.ExceptionCode, 0, buffer, capacity, nullptr);
  2379. if(length)
  2380. OVR::OVR_snprintf(exceptionInfo.exceptionDescription, OVR_ARRAY_COUNT(exceptionInfo.exceptionDescription),
  2381. "%s at instruction %s", buffer, addressStr);
  2382. // If everything else failed just show the hex code.
  2383. if(exceptionInfo.exceptionDescription[0] == 0)
  2384. OVR::OVR_snprintf(exceptionInfo.exceptionDescription, OVR_ARRAY_COUNT(exceptionInfo.exceptionDescription),
  2385. "Unknown exception 0x%08x at instruction %s", exceptionInfo.exceptionRecord.ExceptionCode, addressStr);
  2386. }
  2387. }
  2388. #elif defined(OVR_OS_APPLE)
  2389. struct MachExceptionInfo
  2390. {
  2391. static const char* GetCPUExceptionIdString(uint32_t cpuExceptionId)
  2392. {
  2393. const char* id;
  2394. #if defined(OVR_CPU_X86) || defined(OVR_CPU_X86_64)
  2395. switch (cpuExceptionId)
  2396. {
  2397. case 0: id = "integer div/0"; break;
  2398. case 1: id = "breakpoint fault"; break;
  2399. case 2: id = "non-maskable interrupt"; break;
  2400. case 3: id = "int 3"; break;
  2401. case 4: id = "overflow"; break;
  2402. case 5: id = "bounds check failure"; break;
  2403. case 6: id = "invalid instruction"; break;
  2404. case 7: id = "coprocessor unavailable"; break;
  2405. case 8: id = "exception within exception"; break;
  2406. case 9: id = "coprocessor segment overrun"; break;
  2407. case 10: id = "invalid task switch"; break;
  2408. case 11: id = "segment not present"; break;
  2409. case 12: id = "stack exception"; break;
  2410. case 13: id = "general protection fault"; break;
  2411. case 14: id = "page fault"; break;
  2412. case 16: id = "coprocessor error"; break;
  2413. default: id = "<unknown>"; break;
  2414. }
  2415. #else
  2416. // To do: Support ARM or others.
  2417. #endif
  2418. return id;
  2419. }
  2420. static const char* GetMachExceptionTypeString(uint64_t exceptionCause)
  2421. {
  2422. switch (exceptionCause)
  2423. {
  2424. case EXC_ARITHMETIC: return "EXC_ARITHMETIC";
  2425. case EXC_BAD_ACCESS: return "EXC_BAD_ACCESS";
  2426. case EXC_BAD_INSTRUCTION: return "EXC_BAD_INSTRUCTION";
  2427. case EXC_BREAKPOINT: return "EXC_BREAKPOINT";
  2428. case EXC_CRASH: return "EXC_CRASH";
  2429. case EXC_EMULATION: return "EXC_EMULATION";
  2430. case EXC_MACH_SYSCALL: return "EXC_MACH_SYSCALL";
  2431. case EXC_RPC_ALERT: return "EXC_RPC_ALERT";
  2432. case EXC_SOFTWARE: return "EXC_SOFTWARE";
  2433. case EXC_SYSCALL: return "EXC_SYSCALL";
  2434. };
  2435. return "EXC_<unknown>";
  2436. }
  2437. static const char* GetMachExceptionIdString(uint64_t machExceptionId, uint64_t code0)
  2438. {
  2439. const char* id = "<unknown>";
  2440. #if defined(OVR_CPU_X86) || defined(OVR_CPU_X86_64)
  2441. switch (machExceptionId)
  2442. {
  2443. case EXC_ARITHMETIC:
  2444. switch (code0)
  2445. {
  2446. case EXC_I386_BOUND: id = "EXC_I386_BOUND"; break;
  2447. case EXC_I386_DIV: id = "EXC_I386_DIV"; break;
  2448. case EXC_I386_EMERR: id = "EXC_I386_EMERR"; break;
  2449. case EXC_I386_EXTERR: id = "EXC_I386_EXTERR"; break;
  2450. case EXC_I386_EXTOVR: id = "EXC_I386_EXTOVR"; break;
  2451. case EXC_I386_INTO: id = "EXC_I386_INTO"; break;
  2452. case EXC_I386_NOEXT: id = "EXC_I386_NOEXT"; break;
  2453. case EXC_I386_SSEEXTERR: id = "EXC_I386_SSEEXTERR"; break;
  2454. }
  2455. break;
  2456. case EXC_BAD_INSTRUCTION:
  2457. if(code0 == EXC_I386_INVOP)
  2458. id = "EXC_I386_INVOP";
  2459. break;
  2460. case EXC_BREAKPOINT:
  2461. if(code0 == EXC_I386_BPT)
  2462. id = "EXC_I386_BPT";
  2463. else if(code0 == EXC_I386_SGL)
  2464. id = "EXC_I386_SGL";
  2465. break;
  2466. };
  2467. #else
  2468. // To do.
  2469. #endif
  2470. return id;
  2471. }
  2472. };
  2473. OVR::OVR_snprintf(exceptionInfo.exceptionDescription, OVR_ARRAY_COUNT(exceptionInfo.exceptionDescription),
  2474. "Mach exception type: %llu (%s)\n", exceptionInfo.exceptionType, MachExceptionInfo::GetMachExceptionTypeString(exceptionInfo.exceptionType));
  2475. OVR::OVR_snprintf(scratchBuffer, OVR_ARRAY_COUNT(scratchBuffer), "CPU exception info: exception id: %u (%s), exception id error: %u, fault memory address: %p\n",
  2476. exceptionInfo.cpuExceptionId, MachExceptionInfo::GetCPUExceptionIdString(exceptionInfo.cpuExceptionId), exceptionInfo.cpuExceptionIdError, exceptionInfo.pExceptionMemoryAddress);
  2477. OVR::OVR_strlcat(exceptionInfo.exceptionDescription, scratchBuffer, OVR_ARRAY_COUNT(exceptionInfo.exceptionDescription));
  2478. OVR::OVR_snprintf(scratchBuffer, OVR_ARRAY_COUNT(scratchBuffer), "Mach exception info: exception id: %llu (%s), 0x%llx (%llu)\n", (uint64_t)exceptionInfo.machExceptionData[0],
  2479. MachExceptionInfo::GetMachExceptionIdString(exceptionInfo.exceptionType, exceptionInfo.machExceptionData[0]),
  2480. (uint64_t)exceptionInfo.machExceptionData[1], (uint64_t)exceptionInfo.machExceptionData[1]);
  2481. OVR::OVR_strlcat(exceptionInfo.exceptionDescription, scratchBuffer, OVR_ARRAY_COUNT(exceptionInfo.exceptionDescription));
  2482. #else
  2483. // To do.
  2484. exceptionInfo.exceptionDescription[0] = 0;
  2485. #endif
  2486. }
  2487. void ExceptionHandler::writeLogLine(const char* buffer, int length)
  2488. {
  2489. OVR_ASSERT((int)strlen(buffer) == length); // Input must be null-terminated.
  2490. if (LogFile != nullptr)
  2491. fwrite(buffer, length, 1, LogFile);
  2492. fwrite(buffer, length, 1, stdout);
  2493. #if defined(OVR_OS_WIN32)
  2494. ::OutputDebugStringA(buffer);
  2495. #endif
  2496. }
  2497. void ExceptionHandler::WriteReportLine(const char* pLine)
  2498. {
  2499. writeLogLine(pLine, (int)strlen(pLine));
  2500. }
  2501. void ExceptionHandler::WriteReportLineF(const char* format, ...)
  2502. {
  2503. va_list args;
  2504. va_start(args, format);
  2505. int length = OVR_vsnprintf(scratchBuffer, OVR_ARRAY_COUNT(scratchBuffer), format, args);
  2506. if(length >= (int)OVR_ARRAY_COUNT(scratchBuffer)) // If we didn't have enough space...
  2507. length = (OVR_ARRAY_COUNT(scratchBuffer) - 1); // ... use what we have.
  2508. va_end(args);
  2509. writeLogLine(scratchBuffer, length);
  2510. }
  2511. // Thread <name> <handle> <id>
  2512. // 0 <module> <address> <function> <file>:<line>
  2513. // 1 <module> <address> <function> <file>:<line>
  2514. // . . .
  2515. //
  2516. void ExceptionHandler::WriteThreadCallstack(ThreadHandle threadHandle, ThreadSysId threadSysId, const char* additionalInfo)
  2517. {
  2518. // We intentionally do not directly use the SymbolInfo::ReportThreadCallstack function because that function allocates memory,
  2519. // which we cannot do due to possibly being within an exception handler.
  2520. // Print the header
  2521. char threadName[32];
  2522. char threadHandleStr[32];
  2523. char threadSysIdStr[32];
  2524. char stackBaseStr[24];
  2525. char stackLimitStr[24];
  2526. char stackCurrentStr[24];
  2527. void* pStackBase;
  2528. void* pStackLimit;
  2529. bool isExceptionThread = (threadSysId == exceptionInfo.threadSysId);
  2530. #if defined(OVR_OS_MS) && (OVR_PTR_SIZE == 8)
  2531. void* pStackCurrent = (threadSysId == exceptionInfo.threadSysId) ? (void*)exceptionInfo.cpuContext.Rsp : nullptr; // We would need to suspend the thread, get its context, resume it, then read the rsp register. It turns out we are already doing that suspend/resume below in the backtrace call.
  2532. #elif defined(OVR_OS_MS)
  2533. void* pStackCurrent = (threadSysId == exceptionInfo.threadSysId) ? (void*)exceptionInfo.cpuContext.Esp : nullptr;
  2534. #elif defined(OVR_OS_MAC) && (OVR_PTR_SIZE == 8)
  2535. void* pStackCurrent = (threadSysId == exceptionInfo.threadSysId) ? (void*)exceptionInfo.cpuContext.threadState.uts.ts64.__rsp : nullptr;
  2536. #elif defined(OVR_OS_MAC)
  2537. void* pStackCurrent = (threadSysId == exceptionInfo.threadSysId) ? (void*)exceptionInfo.cpuContext.threadState.uts.ts32.__esp : nullptr;
  2538. #elif defined(OVR_OS_LINUX)
  2539. void* pStackCurrent = nullptr; // To do.
  2540. #endif
  2541. OVR::GetThreadStackBounds(pStackBase, pStackLimit, threadHandle);
  2542. OVR::Thread::GetThreadName(threadName, OVR_ARRAY_COUNT(threadName), threadName);
  2543. SprintfThreadHandle(threadHandleStr, OVR_ARRAY_COUNT(threadHandleStr), threadHandle);
  2544. SprintfThreadSysId(threadSysIdStr, OVR_ARRAY_COUNT(threadSysIdStr), threadSysId);
  2545. SprintfAddress(stackBaseStr, OVR_ARRAY_COUNT(stackBaseStr), pStackBase);
  2546. SprintfAddress(stackLimitStr, OVR_ARRAY_COUNT(stackLimitStr), pStackLimit);
  2547. SprintfAddress(stackCurrentStr, OVR_ARRAY_COUNT(stackCurrentStr), pStackCurrent);
  2548. if(threadName[0])
  2549. WriteReportLineF("Thread \"%s\" handle: %s, id: %s, stack base: %s, stack limit: %s, stack current: %s, %s\n", threadName, threadHandleStr, threadSysIdStr, stackBaseStr, stackLimitStr, stackCurrentStr, additionalInfo ? additionalInfo : "");
  2550. else
  2551. WriteReportLineF("Thread handle: %s, id: %s, stack base: %s, stack limit: %s, stack current: %s, %s\n", threadHandleStr, threadSysIdStr, stackBaseStr, stackLimitStr, stackCurrentStr, additionalInfo ? additionalInfo : "");
  2552. // Print the backtrace info
  2553. void* addressArray[64];
  2554. size_t addressCount = symbolLookup.GetBacktraceFromThreadSysId(addressArray, OVR_ARRAY_COUNT(addressArray), 0, threadSysId);
  2555. SymbolInfo symbolInfo;
  2556. const char* pModuleName;
  2557. size_t backtraceSkipCount = 0;
  2558. if(isExceptionThread)
  2559. {
  2560. // If this thread is the exception thread, skip some frames.
  2561. #if defined(OVR_OS_MS)
  2562. size_t i, iEnd = MIN(16, addressCount);
  2563. for(i = 0; i < iEnd; i++)
  2564. {
  2565. symbolLookup.LookupSymbol((uint64_t)addressArray[i], symbolInfo);
  2566. if(strstr(symbolInfo.function, "UserExceptionDispatcher") != nullptr)
  2567. break;
  2568. }
  2569. if(i < iEnd) // If found...
  2570. backtraceSkipCount = i;
  2571. else if(addressCount >= 9) // Else default to 9, which is coincidentally what works.
  2572. backtraceSkipCount = 9;
  2573. else
  2574. backtraceSkipCount = 0;
  2575. addressArray[backtraceSkipCount] = exceptionInfo.pExceptionInstructionAddress;
  2576. #endif
  2577. }
  2578. if(addressCount == 0)
  2579. {
  2580. WriteReportLine("<Unable to read backtrace>\n\n");
  2581. }
  2582. else
  2583. {
  2584. for(size_t i = backtraceSkipCount; i < addressCount; ++i)
  2585. {
  2586. symbolLookup.LookupSymbol((uint64_t)addressArray[i], symbolInfo);
  2587. if(symbolInfo.pModuleInfo && symbolInfo.pModuleInfo->name[0])
  2588. pModuleName = symbolInfo.pModuleInfo->name;
  2589. else
  2590. pModuleName = "(unknown module)";
  2591. char addressStr[24];
  2592. SprintfAddress(addressStr, OVR_ARRAY_COUNT(addressStr), addressArray[i]);
  2593. if(symbolInfo.filePath[0])
  2594. WriteReportLineF("%-2u %-24s %s %s+%d %s:%d\n%s", (unsigned)i, pModuleName, addressStr,
  2595. symbolInfo.function, symbolInfo.functionOffset, symbolInfo.filePath,
  2596. symbolInfo.fileLineNumber, (i + 1) == addressCount ? "\n" : "");
  2597. else
  2598. WriteReportLineF("%-2u %-24s %s %s+%d\n%s", (unsigned)i, pModuleName, addressStr,
  2599. symbolInfo.function, symbolInfo.functionOffset, (i + 1) == addressCount ? "\n" : ""); // If this is the last line, append another \n.
  2600. }
  2601. }
  2602. }
  2603. void ExceptionHandler::WriteReport()
  2604. {
  2605. // It's important that we don't allocate any memory here if we can help it.
  2606. using namespace OVR;
  2607. if(strstr(reportFilePath, "%s")) // If the user-specified file path includes a date/time component...
  2608. {
  2609. char dateTimeBuffer[64];
  2610. FormatDateTime(dateTimeBuffer, OVR_ARRAY_COUNT(dateTimeBuffer), exceptionInfo.timeVal, true, true, false, true);
  2611. OVR_snprintf(reportFilePathActual, OVR_ARRAY_COUNT(reportFilePathActual), reportFilePath, dateTimeBuffer);
  2612. }
  2613. else
  2614. {
  2615. OVR_strlcpy(reportFilePathActual, reportFilePath, OVR_ARRAY_COUNT(reportFilePathActual));
  2616. }
  2617. // Since LogFile is still null at this point,
  2618. OVR_ASSERT(LogFile == nullptr);
  2619. // ...we are writing this to the console/syslog but not the log file.
  2620. WriteReportLineF("[ExceptionHandler] Exception caught! Writing report to file: %s\n", reportFilePathActual);
  2621. #if defined(OVR_OS_WIN32)
  2622. HANDLE hEventSource = ::RegisterEventSourceW(nullptr, OVR_SYSLOG_NAME);
  2623. if (hEventSource)
  2624. {
  2625. // This depends on the scratch buffer containing the file location.
  2626. const char* lines = scratchBuffer;
  2627. ::ReportEventA(hEventSource, EVENTLOG_ERROR_TYPE, 0, 0, nullptr, 1, 0, &lines, nullptr);
  2628. ::DeregisterEventSource(hEventSource);
  2629. }
  2630. #endif
  2631. LogFile = fopen(reportFilePathActual, "w");
  2632. OVR_ASSERT(LogFile != nullptr);
  2633. if(!LogFile)
  2634. return;
  2635. SymbolLookup::Initialize();
  2636. {
  2637. // Exception information
  2638. WriteReportLine("Exception Info\n");
  2639. WriteReportLineF("Exception report file: %s\n", reportFilePathActual);
  2640. #if defined(OVR_OS_MS)
  2641. if(miniDumpFilePath[0])
  2642. WriteReportLineF("Exception minidump file: %s\n", minidumpFilePathActual);
  2643. #endif
  2644. char dateTimeBuffer[64];
  2645. FormatDateTime(dateTimeBuffer, OVR_ARRAY_COUNT(dateTimeBuffer), exceptionInfo.timeVal, true, true, false, false);
  2646. WriteReportLineF("Time (GMT): %s\n", dateTimeBuffer);
  2647. FormatDateTime(dateTimeBuffer, OVR_ARRAY_COUNT(scratchBuffer), exceptionInfo.timeVal, true, true, true, false);
  2648. WriteReportLineF("Time (local): %s\n", dateTimeBuffer);
  2649. WriteReportLineF("Thread name: %s\n", exceptionInfo.threadName[0] ? exceptionInfo.threadName : "(not available)"); // It's never possible on Windows to get thread names, as they are stored in the debugger at runtime.
  2650. SprintfThreadHandle(scratchBuffer, OVR_ARRAY_COUNT(scratchBuffer), exceptionInfo.threadHandle);
  2651. OVR_strlcat(scratchBuffer, "\n", OVR_ARRAY_COUNT(scratchBuffer));
  2652. WriteReportLine("Thread handle: ");
  2653. WriteReportLine(scratchBuffer);
  2654. SprintfThreadSysId(scratchBuffer, OVR_ARRAY_COUNT(scratchBuffer), exceptionInfo.threadSysId);
  2655. OVR_strlcat(scratchBuffer, "\n", OVR_ARRAY_COUNT(scratchBuffer));
  2656. WriteReportLine("Thread sys id: ");
  2657. WriteReportLine(scratchBuffer);
  2658. char addressStr[24];
  2659. SprintfAddress(addressStr, OVR_ARRAY_COUNT(addressStr), exceptionInfo.pExceptionInstructionAddress);
  2660. WriteReportLineF("Exception instruction address: %s (see callstack below)\n", addressStr);
  2661. WriteReportLineF("Exception description: %s\n", exceptionInfo.exceptionDescription);
  2662. if (symbolLookup.LookupSymbol((uint64_t)exceptionInfo.pExceptionInstructionAddress, exceptionInfo.symbolInfo))
  2663. {
  2664. if(exceptionInfo.symbolInfo.filePath[0])
  2665. WriteReportLineF("Exception location: %s (%d)\n", exceptionInfo.symbolInfo.filePath, exceptionInfo.symbolInfo.fileLineNumber);
  2666. else
  2667. WriteReportLineF("Exception location: %s (%d)\n", exceptionInfo.symbolInfo.function, exceptionInfo.symbolInfo.functionOffset);
  2668. }
  2669. // To consider: print exceptionInfo.cpuContext registers
  2670. }
  2671. #if 0 // Disabled while we move this to the Util module or some other location.
  2672. /*
  2673. // OVR information
  2674. WriteReportLine("\nOVR Info\n");
  2675. WriteReportLineF("OVR time: %f\n", ovr_GetTimeInSeconds());
  2676. WriteReportLineF("OVR version: %s\n", ovr_GetVersionString());
  2677. // OVR util information
  2678. // The following would be useful to use if they didn't allocate memory, which we can't do.
  2679. // To do: see if we can have versions of the functions below which don't allocate memory
  2680. // or allocate it safely (e.g. use an alternative heap).
  2681. // String OVR::GetDisplayDriverVersion();
  2682. // String OVR::GetCameraDriverVersion();
  2683. // OVR HMD information
  2684. WriteReportLine("\nOVR HMD Info\n");
  2685. // XXX rewrite this to use EnumerateHMDStateList() with a callback...
  2686. const OVR::List<OVR::CAPI::HMDState>& hmdStateList = OVR::CAPI::HMDState::GetHMDStateList();
  2687. const OVR::CAPI::HMDState* pHMDState = hmdStateList.GetFirst();
  2688. if(hmdStateList.IsNull(pHMDState))
  2689. {
  2690. WriteReportLine("No HMDs found.\n");
  2691. }
  2692. while(!hmdStateList.IsNull(pHMDState))
  2693. {
  2694. if(pHMDState->pProfile)
  2695. {
  2696. const char* user = pHMDState->pProfile->GetValue(OVR_KEY_USER);
  2697. if(user)
  2698. WriteReportLineF("Profile user: %s\n", reportPrivacyEnabled ? "<disabled by report privacy settings>" : user);
  2699. else
  2700. WriteReportLine("Null profile user\n");
  2701. float NeckEyeDistance[2];
  2702. float EyeToNoseDistance[2];
  2703. float MaxEyeToPlateDist[2];
  2704. pHMDState->pProfile->GetFloatValues(OVR_KEY_NECK_TO_EYE_DISTANCE, NeckEyeDistance, 2);
  2705. pHMDState->pProfile->GetFloatValues(OVR_KEY_EYE_TO_NOSE_DISTANCE, EyeToNoseDistance, 2);
  2706. pHMDState->pProfile->GetFloatValues(OVR_KEY_MAX_EYE_TO_PLATE_DISTANCE, MaxEyeToPlateDist, 2);
  2707. WriteReportLineF("Player height: %f, eye height: %f, IPD: %f, Neck eye distance: %f,%f, eye relief dial: %d, eye to nose distance: %f,%f, max eye to plate distance: %f,%f, custom eye render: %s\n",
  2708. pHMDState->pProfile->GetFloatValue(OVR_KEY_PLAYER_HEIGHT, 0.f),
  2709. pHMDState->pProfile->GetFloatValue(OVR_KEY_EYE_HEIGHT, 0.f),
  2710. pHMDState->pProfile->GetFloatValue(OVR_KEY_IPD, 0.f),
  2711. NeckEyeDistance[0], NeckEyeDistance[1],
  2712. pHMDState->pProfile->GetIntValue(OVR_KEY_EYE_RELIEF_DIAL, 0),
  2713. EyeToNoseDistance[0], EyeToNoseDistance[1],
  2714. MaxEyeToPlateDist[0], MaxEyeToPlateDist[1],
  2715. pHMDState->pProfile->GetBoolValue(OVR_KEY_CUSTOM_EYE_RENDER, false) ? "yes" : "no");
  2716. // Not currently used:
  2717. // OVR_KEY_NAME
  2718. // OVR_KEY_GENDER
  2719. // OVR_KEY_EYE_CUP
  2720. // OVR_KEY_CAMERA_POSITION
  2721. }
  2722. else
  2723. {
  2724. WriteReportLine("Null HMD profile\n");
  2725. }
  2726. if(pHMDState->pHmdDesc) // This should usually be true.
  2727. {
  2728. WriteReportLineF("HMD %d: Type: %u ProductName: %s, Manufacturer: %s VendorId: %d, ProductId: %d, SerialNumber: %s, FirmwareMajor: %d, FirmwareMinor: %d, Resolution: %dx%d, DisplayDeviceName: %s, DisplayId: %d\n",
  2729. 0, (unsigned)pHMDState->pHmdDesc->Type, pHMDState->pHmdDesc->ProductName, pHMDState->pHmdDesc->Manufacturer, pHMDState->pHmdDesc->VendorId,
  2730. pHMDState->pHmdDesc->ProductId, pHMDState->pHmdDesc->SerialNumber, pHMDState->pHmdDesc->FirmwareMajor, pHMDState->pHmdDesc->FirmwareMinor,
  2731. pHMDState->pHmdDesc->Resolution.w, pHMDState->pHmdDesc->Resolution.h, pHMDState->pHmdDesc->DisplayDeviceName, pHMDState->pHmdDesc->DisplayId);
  2732. }
  2733. char threadIdStr[24];
  2734. SprintfAddress(threadIdStr, OVR_ARRAY_COUNT(threadIdStr), pHMDState->BeginFrameThreadId);
  2735. WriteReportLineF("Hmd Caps: %x, Hmd Service Caps: %x, Latency test active: %s, Last frame time: %f, Last get frame time: %f, Rendering configred: %s, Begin frame called: %s, Begin frame thread id: %s\n",
  2736. pHMDState->EnabledHmdCaps, pHMDState->EnabledServiceHmdCaps, pHMDState->LatencyTestDk1Active ? "yes" : "no", pHMDState->LastFrameTimeSeconds, pHMDState->LastGetFrameTimeSeconds, pHMDState->RenderingConfigured ? "yes" : "no",
  2737. pHMDState->BeginFrameCalled ? "yes" : "no", threadIdStr);
  2738. if(pHMDState->pLastError)
  2739. {
  2740. WriteReportLineF("OVR last error for hmd: %s\n", pHMDState->pLastError);
  2741. }
  2742. pHMDState = hmdStateList.GetNext(pHMDState);
  2743. }
  2744. */
  2745. #endif // #if 0
  2746. #if defined(OVR_OS_WIN32)
  2747. {
  2748. WriteReportLine("\nApp Info\n");
  2749. // Print the app path.
  2750. char appPath[OVR_MAX_PATH];
  2751. GetCurrentProcessFilePath(appPath, OVR_ARRAY_COUNT(appPath));
  2752. WriteReportLineF("Process path: %s\n", appPath);
  2753. #if (OVR_PTR_SIZE == 4)
  2754. WriteReportLine("App format: 32 bit\n");
  2755. #else
  2756. WriteReportLine("App format: 64 bit\n");
  2757. #endif
  2758. // Print the app version
  2759. wchar_t pathW[OVR_MAX_PATH] = {};
  2760. GetModuleFileNameW(0, pathW, (DWORD)OVR_ARRAY_COUNT(pathW));
  2761. DWORD dwUnused;
  2762. DWORD dwSize = GetFileVersionInfoSizeW(pathW, &dwUnused);
  2763. scratchBuffer[0] = 0;
  2764. if(dwSize > 0)
  2765. {
  2766. void* const pVersionData = SafeMMapAlloc(dwSize);
  2767. if(pVersionData)
  2768. {
  2769. if(GetFileVersionInfoW(pathW, 0, dwSize, pVersionData))
  2770. {
  2771. VS_FIXEDFILEINFO* pFFI;
  2772. UINT size;
  2773. if(VerQueryValueA(pVersionData, "\\", (void**)&pFFI, &size))
  2774. {
  2775. WriteReportLineF("App version: %u.%u.%u.%u\n",
  2776. HIWORD(pFFI->dwFileVersionMS), LOWORD(pFFI->dwFileVersionMS),
  2777. HIWORD(pFFI->dwFileVersionLS), LOWORD(pFFI->dwFileVersionLS));
  2778. }
  2779. }
  2780. SafeMMapFree(pVersionData, dwSize);
  2781. }
  2782. }
  2783. if(!scratchBuffer[0]) // If version info couldn't be found or read...
  2784. WriteReportLine("App version info not present\n");
  2785. }
  2786. {
  2787. WriteReportLine("\nSystem Info\n");
  2788. OSVERSIONINFOEXW vi;
  2789. memset(&vi, 0, sizeof(vi));
  2790. vi.dwOSVersionInfoSize = sizeof(vi);
  2791. GetVersionExW((LPOSVERSIONINFOW)&vi); // Cast to the older type.
  2792. char osVersionName[256];
  2793. GetOSVersionName(osVersionName, OVR_ARRAY_COUNT(osVersionName));
  2794. WriteReportLineF("OS name: %s, version: %u.%u build %u, %s, platform id: %u, service pack: %ls\n",
  2795. osVersionName, vi.dwMajorVersion, vi.dwMinorVersion, vi.dwBuildNumber, Is64BitOS() ? "64 bit" : "32 bit",
  2796. vi.dwPlatformId, vi.szCSDVersion[0] ? vi.szCSDVersion : L"<none>");
  2797. WriteReportLineF("Debugger present: %s\n", OVRIsDebuggerPresent() ? "yes" : "no");
  2798. // System info
  2799. SYSTEM_INFO systemInfo;
  2800. GetNativeSystemInfo(&systemInfo);
  2801. WriteReportLineF("Processor count: %u\n", systemInfo.dwNumberOfProcessors);
  2802. // Windows Vista and later:
  2803. // BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer, PDWORD ReturnLength);
  2804. if(systemInfo.wProcessorArchitecture == 0)
  2805. WriteReportLineF("Processor type: x86\n");
  2806. else if(systemInfo.wProcessorArchitecture == 9)
  2807. WriteReportLineF("Processor type: x86-64\n");
  2808. else if(systemInfo.wProcessorArchitecture == 10)
  2809. WriteReportLineF("Processor type: x86 on x86-64\n");
  2810. WriteReportLineF("Processor level: %u\n", systemInfo.wProcessorLevel);
  2811. WriteReportLineF("Processor revision: %u\n", systemInfo.wProcessorRevision);
  2812. // Memory information
  2813. MEMORYSTATUSEX memoryStatusEx;
  2814. memset(&memoryStatusEx, 0, sizeof(memoryStatusEx));
  2815. memoryStatusEx.dwLength = sizeof(memoryStatusEx);
  2816. GlobalMemoryStatusEx(&memoryStatusEx);
  2817. WriteReportLineF("Memory load: %d%%\n", memoryStatusEx.dwMemoryLoad);
  2818. WriteReportLineF("Total physical memory: %I64d MiB\n", memoryStatusEx.ullTotalPhys / (1024 * 1024)); // Or are Mebibytes equal to (1024 * 1000)
  2819. WriteReportLineF("Available physical memory: %I64d MiB\n", memoryStatusEx.ullAvailPhys / (1024 * 1024));
  2820. WriteReportLineF("Total page file memory: %I64d MiB\n", memoryStatusEx.ullTotalPageFile / (1024 * 1024));
  2821. WriteReportLineF("Available page file memory: %I64d MiB\n", memoryStatusEx.ullAvailPageFile / (1024 * 1024));
  2822. WriteReportLineF("Total virtual memory: %I64d MiB\n", memoryStatusEx.ullTotalVirtual / (1024 * 1024));
  2823. WriteReportLineF("Free virtual memory: %I64d MiB\n", memoryStatusEx.ullAvailVirtual / (1024 * 1024));
  2824. DISPLAY_DEVICEW dd;
  2825. memset(&dd, 0, sizeof(DISPLAY_DEVICE));
  2826. dd.cb = sizeof(DISPLAY_DEVICE);
  2827. for(int i = 0; EnumDisplayDevicesW(nullptr, (DWORD)i, &dd, EDD_GET_DEVICE_INTERFACE_NAME); ++i)
  2828. {
  2829. WriteReportLineF("Display Device %d name: %ls, context: %ls, primary: %s, mirroring: %s\n",
  2830. i, dd.DeviceName, dd.DeviceString, (dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) ? "yes" : "no", (dd.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER) ? "yes" : "no");
  2831. }
  2832. }
  2833. // Print video card information
  2834. // http://msdn.microsoft.com/en-us/library/aa394512%28v=vs.85%29.aspx
  2835. {
  2836. IWbemLocator* pIWbemLocator = nullptr;
  2837. BSTR bstrServer = nullptr;
  2838. IWbemServices* pIWbemServices = nullptr;
  2839. BSTR bstrWQL = nullptr;
  2840. BSTR bstrPath = nullptr;
  2841. IEnumWbemClassObject* pEnum = nullptr;
  2842. CoInitializeEx(nullptr, COINIT_MULTITHREADED);
  2843. HRESULT hr = CoCreateInstance(__uuidof(WbemLocator), nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWbemLocator), (LPVOID*)&pIWbemLocator);
  2844. if(FAILED(hr))
  2845. goto End;
  2846. bstrServer = SysAllocString(L"\\\\.\\root\\cimv2");
  2847. hr = pIWbemLocator->ConnectServer(bstrServer, nullptr, nullptr, 0L, 0L, nullptr, nullptr, &pIWbemServices);
  2848. if(FAILED(hr))
  2849. goto End;
  2850. hr = CoSetProxyBlanket(pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, nullptr, RPC_C_AUTHN_LEVEL_CALL,
  2851. RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_DEFAULT);
  2852. if(FAILED(hr))
  2853. goto End;
  2854. bstrWQL = SysAllocString(L"WQL");
  2855. bstrPath = SysAllocString(L"select * from Win32_VideoController");
  2856. hr = pIWbemServices->ExecQuery(bstrWQL, bstrPath, WBEM_FLAG_FORWARD_ONLY, nullptr, &pEnum);
  2857. if(FAILED(hr))
  2858. goto End;
  2859. ULONG uReturned;
  2860. IWbemClassObject* pObj = nullptr;
  2861. hr = pEnum->Next(WBEM_INFINITE, 1, &pObj, &uReturned);
  2862. if(FAILED(hr))
  2863. goto End;
  2864. WriteReportLine("\nDisplay adapter list\n");
  2865. for(unsigned i = 0; SUCCEEDED(hr) && uReturned; i++)
  2866. {
  2867. char sString[256];
  2868. VARIANT var;
  2869. if(i > 0)
  2870. WriteReportLine("\n");
  2871. WriteReportLineF("Info for display adapter %u\n", i);
  2872. hr = pObj->Get(L"Name", 0, &var, nullptr, nullptr);
  2873. if(SUCCEEDED(hr))
  2874. {
  2875. WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, sString, sizeof(sString), nullptr, nullptr);
  2876. WriteReportLineF("Display Adapter Name: %s\n", sString);
  2877. }
  2878. hr = pObj->Get(L"AdapterRAM", 0, &var, nullptr, nullptr);
  2879. if(SUCCEEDED(hr))
  2880. {
  2881. WriteReportLineF("Display Adapter RAM: %u %s\n",
  2882. ((uint32_t)var.lVal > (1024*1024*1024) ? (uint32_t)var.lVal/(1024*1024*1024) : (uint32_t)var.lVal/(1024*1024)), ((uint32_t)var.lVal > (1024*1024*1024) ? "GiB" : "MiB"));
  2883. }
  2884. hr = pObj->Get(L"DeviceID", 0, &var, nullptr, nullptr);
  2885. if(SUCCEEDED(hr))
  2886. {
  2887. WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, sString, sizeof(sString), nullptr, nullptr);
  2888. WriteReportLineF("Display Adapter DeviceID: %s\n", sString);
  2889. }
  2890. hr = pObj->Get(L"DriverVersion", 0, &var, nullptr, nullptr);
  2891. if(SUCCEEDED(hr))
  2892. {
  2893. WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, sString, sizeof(sString), nullptr, nullptr);
  2894. WriteReportLineF("Display Adapter DriverVersion: %s\n", sString);
  2895. }
  2896. hr = pObj->Get(L"DriverDate", 0, &var, nullptr, nullptr);
  2897. if(SUCCEEDED(hr))
  2898. {
  2899. // http://technet.microsoft.com/en-us/library/ee156576.aspx
  2900. wchar_t year[5] = { var.bstrVal[0], var.bstrVal[1], var.bstrVal[2], var.bstrVal[3], 0 };
  2901. wchar_t month[3] = { var.bstrVal[4], var.bstrVal[5], 0 };
  2902. wchar_t monthDay[3] = { var.bstrVal[6], var.bstrVal[7], 0 };
  2903. WriteReportLineF("Display Adapter DriverDate (US format): %ls/%ls/%ls\n", month, monthDay, year);
  2904. }
  2905. // VideoProcessor
  2906. hr = pObj->Get(L"VideoProcessor", 0, &var, nullptr, nullptr);
  2907. if(SUCCEEDED(hr))
  2908. {
  2909. WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, sString, sizeof(sString), nullptr, nullptr);
  2910. WriteReportLineF("Display Adapter VideoProcessor %s\n", sString);
  2911. }
  2912. hr = pObj->Get(L"VideoModeDescription", 0, &var, nullptr, nullptr);
  2913. if(SUCCEEDED(hr))
  2914. {
  2915. WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, sString, sizeof(sString), nullptr, nullptr);
  2916. WriteReportLineF("Display Adapter VideoModeDescription: %s\n", sString);
  2917. }
  2918. pObj->Release();
  2919. hr = pEnum->Next(WBEM_INFINITE, 1, &pObj, &uReturned);
  2920. }
  2921. End:
  2922. if(pEnum)
  2923. pEnum->Release();
  2924. if(bstrPath)
  2925. SysFreeString(bstrPath);
  2926. if(bstrWQL)
  2927. SysFreeString(bstrWQL);
  2928. if(pIWbemServices)
  2929. pIWbemServices->Release();
  2930. if(bstrServer)
  2931. SysFreeString(bstrServer);
  2932. if(pIWbemLocator)
  2933. pIWbemLocator->Release();
  2934. CoUninitialize();
  2935. }
  2936. {
  2937. // Print a list of threads.
  2938. DWORD currentProcessId = GetCurrentProcessId();
  2939. HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, currentProcessId); // ICreateToolhelp32Snapshot actually ignores currentProcessId.
  2940. if(hThreadSnap != INVALID_HANDLE_VALUE)
  2941. {
  2942. THREADENTRY32 te32;
  2943. te32.dwSize = sizeof(THREADENTRY32);
  2944. if(Thread32First(hThreadSnap, &te32))
  2945. {
  2946. WriteReportLine("\nThread list\n");
  2947. do {
  2948. if(te32.th32OwnerProcessID == currentProcessId)
  2949. {
  2950. HANDLE hThread = ConvertThreadSysIdToThreadHandle(te32.th32ThreadID);
  2951. if(hThread)
  2952. {
  2953. char buffer[96]; // Can't use scratchBuffer, because it's used by WriteThreadCallstack.
  2954. OVR_snprintf(buffer, OVR_ARRAY_COUNT(buffer), "base priority: %ld, delta priority: %ld", te32.tpBasePri, te32.tpDeltaPri);
  2955. bool threadIsExceptionThread = (te32.th32ThreadID == (DWORD)exceptionInfo.threadSysId);
  2956. if(threadIsExceptionThread)
  2957. OVR_strlcat(buffer, ", exception thread", OVR_ARRAY_COUNT(buffer));
  2958. WriteThreadCallstack(hThread, (OVR::ThreadSysId)te32.th32ThreadID, buffer);
  2959. FreeThreadHandle(hThread);
  2960. }
  2961. }
  2962. } while(Thread32Next(hThreadSnap, &te32));
  2963. }
  2964. CloseHandle(hThreadSnap);
  2965. }
  2966. }
  2967. {
  2968. // Print a list of the current modules within this process.
  2969. // DbgHelp.dll also provides a EnumerateLoadedModules64 function.
  2970. // To do: Convert the code below to use the GetModuleInfoArray function which we now have.
  2971. HMODULE hModule = LoadLibraryW(L"psapi.dll");
  2972. if(hModule)
  2973. {
  2974. typedef BOOL (WINAPI * ENUMPROCESSMODULES) (HANDLE hProcess, HMODULE* phModule, DWORD cb, LPDWORD lpcbNeeded);
  2975. typedef DWORD (WINAPI * GETMODULEBASENAME) (HANDLE hProcess, HMODULE hModule, LPWSTR lpFilename, DWORD nSize);
  2976. typedef DWORD (WINAPI * GETMODULEFILENAMEEX) (HANDLE hProcess, HMODULE hModule, LPWSTR lpFilename, DWORD nSize);
  2977. typedef BOOL (WINAPI * GETMODULEINFORMATION)(HANDLE hProcess, HMODULE hModule, MODULEINFO* pmi, DWORD nSize);
  2978. ENUMPROCESSMODULES pEnumProcessModules = (ENUMPROCESSMODULES) (uintptr_t)GetProcAddress(hModule, "EnumProcessModules");
  2979. GETMODULEBASENAME pGetModuleBaseName = (GETMODULEBASENAME) (uintptr_t)GetProcAddress(hModule, "GetModuleBaseNameW");
  2980. GETMODULEFILENAMEEX pGetModuleFileNameEx = (GETMODULEFILENAMEEX) (uintptr_t)GetProcAddress(hModule, "GetModuleFileNameExW");
  2981. GETMODULEINFORMATION pGetModuleInformation = (GETMODULEINFORMATION)(uintptr_t)GetProcAddress(hModule, "GetModuleInformation");
  2982. HANDLE hProcess = GetCurrentProcess();
  2983. HMODULE hModuleArray[200];
  2984. DWORD cbNeeded;
  2985. if(pEnumProcessModules(hProcess, hModuleArray, sizeof(hModuleArray), &cbNeeded))
  2986. {
  2987. size_t actualModuleCount = (cbNeeded / sizeof(HMODULE));
  2988. if(actualModuleCount > OVR_ARRAY_COUNT(hModuleArray)) //If hModuleArray's capacity was not enough...
  2989. actualModuleCount = OVR_ARRAY_COUNT(hModuleArray);
  2990. // Print a header
  2991. WriteReportLine("\nModule list\n");
  2992. #if (OVR_PTR_SIZE == 4)
  2993. WriteReportLine("Base Size Entrypoint Name Path\n");
  2994. #else
  2995. WriteReportLine("Base Size Entrypoint Name Path\n");
  2996. #endif
  2997. // And go through the list one by one
  2998. for(size_t i = 0; i < actualModuleCount; i++)
  2999. {
  3000. MODULEINFO mi;
  3001. size_t length;
  3002. if(!pGetModuleInformation(hProcess, hModuleArray[i], &mi, sizeof(mi)))
  3003. {
  3004. mi.EntryPoint = nullptr;
  3005. mi.lpBaseOfDll = nullptr;
  3006. mi.SizeOfImage = 0;
  3007. }
  3008. // Write the base name.
  3009. wchar_t name[OVR_MAX_PATH + 3];
  3010. name[0] = '"';
  3011. if(pGetModuleBaseName(hProcess, hModuleArray[i], name + 1, OVR_MAX_PATH))
  3012. length = wcslen(name);
  3013. else
  3014. {
  3015. wcscpy(name + 1, L"(unknown)");
  3016. length = 10;
  3017. }
  3018. name[length] = '"';
  3019. name[length + 1] = '\0';
  3020. // Write the path
  3021. wchar_t path[OVR_MAX_PATH + 3];
  3022. path[0] = '"';
  3023. if(pGetModuleFileNameEx(hProcess, hModuleArray[i], path + 1, OVR_MAX_PATH))
  3024. length = wcslen(path);
  3025. else
  3026. {
  3027. wcscpy(path + 1, L"(unknown)");
  3028. length = 10;
  3029. }
  3030. path[length] = '"';
  3031. path[length + 1] = '\0';
  3032. #if (OVR_PTR_SIZE == 4)
  3033. WriteReportLineF("0x%08x, 0x%08x 0x%08x %-24ls %ls\n", (uint32_t)mi.lpBaseOfDll, (uint32_t)mi.SizeOfImage, (uint32_t)mi.EntryPoint, name, path);
  3034. #else
  3035. WriteReportLineF("0x%016I64x 0x%016I64x 0x%016I64x %-24ls %ls\n", (uint64_t)mi.lpBaseOfDll, (uint64_t)mi.SizeOfImage, (uint64_t)mi.EntryPoint, name, path);
  3036. #endif
  3037. }
  3038. }
  3039. }
  3040. }
  3041. {
  3042. // Print a list of processes.
  3043. // DbgHelp.dll provides a SymEnumProcesses function, but it's available with DbgHelp.dll v6.2 which doesn't ship with Windows until Windows 8.
  3044. WriteReportLine("\nProcess list\n");
  3045. if(reportPrivacyEnabled)
  3046. WriteReportLine("Disabled by report privacy settings\n");
  3047. else
  3048. {
  3049. HANDLE hProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  3050. if(hProcessSnapshot != INVALID_HANDLE_VALUE)
  3051. {
  3052. PROCESSENTRY32W pe32;
  3053. memset(&pe32, 0, sizeof(pe32));
  3054. pe32.dwSize = sizeof(pe32);
  3055. if(Process32FirstW(hProcessSnapshot, &pe32))
  3056. {
  3057. WriteReportLine("Process Id File\n");
  3058. do {
  3059. // Try to get the full path to the process, as pe32.szExeFile holds only the process file name.
  3060. // This will typically fail with a privilege error unless this process has debug privileges: http://support.microsoft.com/kb/131065/en-us
  3061. wchar_t filePathW[OVR_MAX_PATH];
  3062. const wchar_t* pFilePathW = pe32.szExeFile;
  3063. HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pe32.th32ProcessID); // With Windows Vista+ we can use PROCESS_QUERY_LIMITED_INFORMATION.
  3064. if(hProcess)
  3065. {
  3066. if(GetProcessImageFileNameW(hProcess, filePathW, (DWORD)OVR_ARRAY_COUNT(filePathW)))
  3067. pFilePathW = filePathW;
  3068. }
  3069. WriteReportLineF("0x%08x %ls\n", pe32.th32ProcessID, pFilePathW);
  3070. } while(Process32NextW(hProcessSnapshot, &pe32));
  3071. }
  3072. CloseHandle(hProcessSnapshot);
  3073. }
  3074. else
  3075. {
  3076. WriteReportLine("Unable to read process list\n");
  3077. }
  3078. }
  3079. }
  3080. #elif defined(OVR_OS_APPLE)
  3081. WriteReportLine("\nApp Info\n");
  3082. // App path
  3083. const pid_t processId = getpid();
  3084. WriteReportLineF("Process id: ", "%lld (0x%llx)\n", (int64_t)processId, (int64_t)processId);
  3085. char appPath[PATH_MAX];
  3086. GetCurrentProcessFilePath(appPath, OVR_ARRAY_COUNT(appPath));
  3087. WriteReportLineF("Process path: %s\n", appPath);
  3088. #if (OVR_PTR_SIZE == 4)
  3089. WriteReportLine("App format: 32 bit\n");
  3090. #else
  3091. WriteReportLine("App format: 64 bit\n");
  3092. #endif
  3093. // App version
  3094. // To do.
  3095. // System Info
  3096. WriteReportLine("\nSystem Info\n");
  3097. char osVersionName[256];
  3098. GetOSVersionName(osVersionName, OVR_ARRAY_COUNT(osVersionName));
  3099. WriteReportLineF("OS name: %s, %s\n", osVersionName, Is64BitOS() ? "64 bit" : "32 bit");
  3100. int name[2];
  3101. int intValue;
  3102. size_t length;
  3103. char tempBuffer[256];
  3104. name[0] = CTL_KERN;
  3105. name[1] = KERN_OSTYPE;
  3106. length = sizeof(tempBuffer);
  3107. tempBuffer[0] = 0;
  3108. if(sysctl(name, 2, tempBuffer, &length, nullptr, 0) == 0)
  3109. {
  3110. WriteReportLineF("KERN_OSTYPE: %s\n", tempBuffer);
  3111. }
  3112. name[0] = CTL_KERN;
  3113. name[1] = KERN_OSREV;
  3114. length = sizeof(intValue);
  3115. intValue = 0;
  3116. if(sysctl(name, 2, &intValue, &length, nullptr, 0) == 0)
  3117. {
  3118. WriteReportLineF("KERN_OSREV: %d\n", intValue);
  3119. }
  3120. name[0] = CTL_KERN;
  3121. name[1] = KERN_OSRELEASE;
  3122. length = sizeof(tempBuffer);
  3123. tempBuffer[0] = 0;
  3124. if(sysctl(name, 2, tempBuffer, &length, nullptr, 0) == 0)
  3125. WriteReportLineF("KERN_OSRELEASE: %s\n", tempBuffer);
  3126. name[0] = CTL_HW;
  3127. name[1] = HW_MACHINE;
  3128. length = sizeof(tempBuffer);
  3129. tempBuffer[0] = 0;
  3130. if(sysctl(name, 2, tempBuffer, &length, nullptr, 0) == 0)
  3131. WriteReportLineF("HW_MACHINE: %s\n", tempBuffer);
  3132. name[0] = CTL_HW;
  3133. name[1] = HW_MODEL;
  3134. length = sizeof(tempBuffer);
  3135. tempBuffer[0] = 0;
  3136. if(sysctl(name, 2, tempBuffer, &length, nullptr, 0) == 0)
  3137. WriteReportLineF("sHW_MODEL: %s\n", tempBuffer);
  3138. name[0] = CTL_HW;
  3139. name[1] = HW_NCPU;
  3140. length = sizeof(intValue);
  3141. intValue = 0;
  3142. if(sysctl(name, 2, &intValue, &length, nullptr, 0) == 0)
  3143. WriteReportLineF("HW_NCPU: %d\n", intValue);
  3144. length = sizeof(tempBuffer);
  3145. tempBuffer[0] = 0;
  3146. if(sysctlbyname("machdep.cpu.brand_string", &tempBuffer, &length, nullptr, 0) == 0)
  3147. WriteReportLineF("machdep.cpu.brand_string: %s\n", tempBuffer);
  3148. length = sizeof(tempBuffer);
  3149. tempBuffer[0] = 0;
  3150. if(sysctlbyname("hw.acpi.thermal.tz0.temperature", &tempBuffer, &length, nullptr, 0) == 0)
  3151. WriteReportLineF("hw.acpi.thermal.tz0.temperature: %s\n", tempBuffer);
  3152. host_basic_info_data_t hostinfo;
  3153. mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
  3154. kern_return_t kr = host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostinfo, &count);
  3155. if(kr == KERN_SUCCESS)
  3156. {
  3157. const uint64_t memoryMib = (uint64_t)hostinfo.max_mem / (1024 * 1024);
  3158. WriteReportLineF("System memory: %lld Mib (%.1f Gib)\n", memoryMib, (double)memoryMib / 1024);
  3159. }
  3160. // Video card info
  3161. // To do.
  3162. // Thread list
  3163. mach_port_t taskSelf = mach_task_self();
  3164. thread_act_port_array_t threadArray;
  3165. mach_msg_type_number_t threadCount;
  3166. kern_return_t result = task_threads(taskSelf, &threadArray, &threadCount);
  3167. if(result == KERN_SUCCESS)
  3168. {
  3169. WriteReportLine("\nThread list\n");
  3170. for(mach_msg_type_number_t i = 0; i < threadCount; i++)
  3171. {
  3172. union TBIUnion{
  3173. natural_t words[THREAD_INFO_MAX];
  3174. thread_basic_info tbi;
  3175. };
  3176. TBIUnion tbiUnion;
  3177. mach_port_t thread = threadArray[i];
  3178. pthread_t pthread = pthread_from_mach_thread_np(thread); // We assume the thread was created through pthreads.
  3179. char threadState[32] = "unknown";
  3180. mach_msg_type_number_t threadInfoCount = THREAD_INFO_MAX;
  3181. result = thread_info(thread, THREAD_BASIC_INFO, (thread_info_t)&tbiUnion, &threadInfoCount);
  3182. if(result == KERN_SUCCESS)
  3183. {
  3184. const char* state;
  3185. switch (tbiUnion.tbi.run_state)
  3186. {
  3187. case TH_STATE_HALTED: state = "halted"; break;
  3188. case TH_STATE_RUNNING: state = "running"; break;
  3189. case TH_STATE_STOPPED: state = "stopped"; break;
  3190. case TH_STATE_UNINTERRUPTIBLE: state = "uninterruptible"; break;
  3191. case TH_STATE_WAITING: state = "waiting"; break;
  3192. default: state = "<unknown>"; break;
  3193. }
  3194. OVR_snprintf(threadState, OVR_ARRAY_COUNT(threadState), "%s", state);
  3195. if(tbiUnion.tbi.flags & TH_FLAGS_IDLE)
  3196. OVR_strlcat(threadState, ", idle", sizeof(threadState));
  3197. if(tbiUnion.tbi.flags & TH_FLAGS_SWAPPED)
  3198. OVR_strlcat(threadState, ", swapped", sizeof(threadState));
  3199. }
  3200. thread_identifier_info threadIdentifierInfo;
  3201. memset(&threadIdentifierInfo, 0, sizeof(threadIdentifierInfo));
  3202. mach_msg_type_number_t threadIdentifierInfoCount = THREAD_IDENTIFIER_INFO_COUNT;
  3203. thread_info(thread, THREAD_IDENTIFIER_INFO, (thread_info_t)&threadIdentifierInfo, &threadIdentifierInfoCount);
  3204. proc_threadinfo procThreadInfo;
  3205. memset(&procThreadInfo, 0, sizeof(procThreadInfo));
  3206. result = proc_pidinfo(processId, PROC_PIDTHREADINFO, threadIdentifierInfo.thread_handle, &procThreadInfo, sizeof(procThreadInfo));
  3207. OVR_UNUSED(result);
  3208. char buffer[256]; // Can't use scratchBuffer, because it's used by WriteThreadCallstack.
  3209. OVR_snprintf(buffer, OVR_ARRAY_COUNT(buffer), "state: %s, suspend count: %d, kernel priority: %d", threadState, (int)tbiUnion.tbi.suspend_count, (int)procThreadInfo.pth_curpri);
  3210. bool threadIsExceptionThread = (thread == exceptionInfo.threadSysId);
  3211. if(threadIsExceptionThread)
  3212. OVR_strlcat(buffer, ", exception thread", OVR_ARRAY_COUNT(buffer));
  3213. WriteThreadCallstack(pthread, thread, buffer);
  3214. }
  3215. vm_deallocate(taskSelf, (vm_address_t)threadArray, threadCount * sizeof(thread_act_t));
  3216. }
  3217. WriteReportLine("\nModule list\n");
  3218. const size_t mifCapacity = 256;
  3219. const size_t mifAllocSize = mifCapacity * sizeof(ModuleInfo);
  3220. ModuleInfo* moduleInfoArray = (ModuleInfo*)SafeMMapAlloc(mifAllocSize);
  3221. if(moduleInfoArray)
  3222. {
  3223. #if (OVR_PTR_SIZE == 4)
  3224. WriteReportLine("Base Size Name Path\n");
  3225. #else
  3226. WriteReportLine("Base Size Name Path\n");
  3227. #endif
  3228. size_t moduleCount = symbolLookup.GetModuleInfoArray(moduleInfoArray, mifCapacity);
  3229. if(moduleCount > mifCapacity)
  3230. moduleCount = mifCapacity;
  3231. for(size_t i = 0; i < moduleCount; i++)
  3232. {
  3233. const ModuleInfo& mi = moduleInfoArray[i];
  3234. #if (OVR_PTR_SIZE == 4)
  3235. WriteReportLineF("0x%08x, 0x%08x %-24s %s\n", (uint32_t)mi.baseAddress, (uint32_t)mi.size, mi.name, mi.filePath);
  3236. #else
  3237. WriteReportLineF("0x%016llx 0x%016llx %-24s %s\n", (uint64_t)mi.baseAddress, (uint64_t)mi.size, mi.name, mi.filePath);
  3238. #endif
  3239. }
  3240. SafeMMapFree(moduleInfoArray, mifAllocSize);
  3241. }
  3242. WriteReportLine("\nProcess list\n");
  3243. if(reportPrivacyEnabled)
  3244. WriteReportLine("Disabled by report privacy settings\n");
  3245. else
  3246. {
  3247. WriteReportLine("Process Id File\n");
  3248. pid_t pidArray[1024];
  3249. int processCount = proc_listpids(PROC_ALL_PIDS, 0, pidArray, sizeof(pidArray)); // Important that we use sizeof not OVR_ARRAY_COUNT.
  3250. char processFilePath[PATH_MAX];
  3251. for(int i = 0; i < processCount; i++)
  3252. {
  3253. if(proc_pidpath(pidArray[i], processFilePath, sizeof(processFilePath)) > 0)
  3254. WriteReportLineF("%-10d %s\n", pidArray[i], processFilePath);
  3255. }
  3256. if(!processCount)
  3257. WriteReportLine("Unable to read process list\n");
  3258. }
  3259. #elif defined(OVR_OS_UNIX)
  3260. Is64BitOS();
  3261. GetCurrentProcessFilePath(nullptr, 0);
  3262. GetFileNameFromPath(nullptr);
  3263. GetOSVersionName(nullptr, 0);
  3264. #endif // OVR_OS_MS
  3265. SymbolLookup::Shutdown();
  3266. fclose(LogFile);
  3267. LogFile = nullptr;
  3268. }
  3269. void ExceptionHandler::WriteMiniDump()
  3270. {
  3271. if(strstr(miniDumpFilePath, "%s")) // If the user-specified file path includes a date/time component...
  3272. {
  3273. char dateTimeBuffer[64];
  3274. FormatDateTime(dateTimeBuffer, OVR_ARRAY_COUNT(dateTimeBuffer), exceptionInfo.timeVal, true, true, false, true);
  3275. OVR_snprintf(minidumpFilePathActual, OVR_ARRAY_COUNT(minidumpFilePathActual), miniDumpFilePath, dateTimeBuffer);
  3276. }
  3277. else
  3278. {
  3279. OVR_strlcpy(minidumpFilePathActual, miniDumpFilePath, OVR_ARRAY_COUNT(minidumpFilePathActual));
  3280. }
  3281. #if defined(OVR_OS_WIN32) || defined(OVR_OS_WIN64)
  3282. typedef BOOL (WINAPI * MINIDUMPWRITEDUMP)(HANDLE hProcess, DWORD ProcessId, HANDLE hFile, MINIDUMP_TYPE dumpType, CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam);
  3283. HMODULE hModuleDbgHelp = LoadLibraryW(L"DbgHelp.dll");
  3284. MINIDUMPWRITEDUMP pMiniDumpWriteDump = hModuleDbgHelp ? (MINIDUMPWRITEDUMP)(void*)GetProcAddress(hModuleDbgHelp, "MiniDumpWriteDump") : nullptr;
  3285. if(pMiniDumpWriteDump)
  3286. {
  3287. wchar_t miniDumpFilePathW[OVR_MAX_PATH];
  3288. OVR::UTF8Util::DecodeString(miniDumpFilePathW, minidumpFilePathActual, -1); // Problem: DecodeString provides no way to specify the destination capacity.
  3289. HANDLE hFile = CreateFileW(miniDumpFilePathW, GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, 0);
  3290. if(hFile != INVALID_HANDLE_VALUE)
  3291. {
  3292. MINIDUMP_EXCEPTION_INFORMATION minidumpExceptionInfo = { ::GetCurrentThreadId(), pExceptionPointers, TRUE };
  3293. BOOL result = pMiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile,
  3294. (MINIDUMP_TYPE)miniDumpFlags, &minidumpExceptionInfo,
  3295. (CONST PMINIDUMP_USER_STREAM_INFORMATION)nullptr, (CONST PMINIDUMP_CALLBACK_INFORMATION)nullptr);
  3296. OVR_ASSERT_AND_UNUSED(result, result);
  3297. CloseHandle(hFile);
  3298. hFile = 0;
  3299. }
  3300. else
  3301. {
  3302. OVR_ASSERT(pMiniDumpWriteDump); // OVR_FAIL_F(("ExceptionHandler::WriteMiniDump: Failed to create minidump file at %s", minidumpFilePathActual));
  3303. }
  3304. }
  3305. FreeLibrary(hModuleDbgHelp);
  3306. #else
  3307. // Some platforms support various forms or exception reports and core dumps which are automatically generated upon us
  3308. // returning from our own exception handling. We might want to put something here if we are using a custom version of
  3309. // this, such as Google Breakpad.
  3310. #endif
  3311. }
  3312. void ExceptionHandler::SetExceptionListener(ExceptionListener* pExceptionListener, uintptr_t userValue)
  3313. {
  3314. exceptionListener = pExceptionListener;
  3315. exceptionListenerUserValue = userValue;
  3316. }
  3317. void ExceptionHandler::SetAppDescription(const char* pAppDescription)
  3318. {
  3319. appDescription = pAppDescription;
  3320. }
  3321. void ExceptionHandler::SetExceptionPaths(const char* exceptionReportPath, const char* exceptionMiniDumpFilePath)
  3322. {
  3323. char tempPath[OVR_MAX_PATH];
  3324. if(exceptionReportPath)
  3325. {
  3326. if(OVR_stricmp(exceptionReportPath, "default") == 0)
  3327. {
  3328. GetCrashDumpDirectory(tempPath, OVR_ARRAY_COUNT(tempPath));
  3329. OVR::OVR_strlcat(tempPath, "Exception Report (%s).txt", OVR_ARRAY_COUNT(tempPath));
  3330. exceptionReportPath = tempPath;
  3331. }
  3332. OVR_strlcpy(reportFilePath, exceptionReportPath, OVR_ARRAY_COUNT(reportFilePath));
  3333. }
  3334. else
  3335. {
  3336. reportFilePath[0] = '\0';
  3337. }
  3338. if(exceptionMiniDumpFilePath)
  3339. {
  3340. if(OVR_stricmp(exceptionMiniDumpFilePath, "default") == 0)
  3341. {
  3342. GetCrashDumpDirectory(tempPath, OVR_ARRAY_COUNT(tempPath));
  3343. OVR::OVR_strlcat(tempPath, "Exception Minidump (%s).mdmp", OVR_ARRAY_COUNT(tempPath));
  3344. exceptionMiniDumpFilePath = tempPath;
  3345. }
  3346. OVR_strlcpy(miniDumpFilePath, exceptionMiniDumpFilePath, OVR_ARRAY_COUNT(miniDumpFilePath));
  3347. }
  3348. else
  3349. {
  3350. miniDumpFilePath[0] = '\0';
  3351. }
  3352. }
  3353. void ExceptionHandler::SetCodeBaseDirectoryPaths(const char* codeBaseDirectoryPathArray[], size_t codeBaseDirectoryPathCount)
  3354. {
  3355. for(size_t i = 0, iCount = OVR::Alg::Min<size_t>(codeBaseDirectoryPathCount, OVR_ARRAY_COUNT(codeBasePathArray)); i != iCount; ++i)
  3356. {
  3357. codeBasePathArray[i] = codeBaseDirectoryPathArray[i];
  3358. }
  3359. }
  3360. const char* ExceptionHandler::GetExceptionUIText(const char* exceptionReportPath)
  3361. {
  3362. char* uiText = nullptr;
  3363. OVR::SysFile file(exceptionReportPath, SysFile::Open_Read, SysFile::Mode_ReadWrite);
  3364. if(file.IsValid())
  3365. {
  3366. size_t length = (size_t)file.GetLength();
  3367. uiText = (char*)OVR::SafeMMapAlloc(length + 1);
  3368. if(uiText)
  3369. {
  3370. file.Read((uint8_t*)uiText, (int)length);
  3371. uiText[length] = '\0';
  3372. file.Close();
  3373. // Currently on Mac our message box implementation is unable to display arbitrarily large amounts of text.
  3374. // So we reduce its size to a more summary version before presenting.
  3375. #if defined(OVR_OS_MAC)
  3376. struct Find { static char* PreviousChar(char* p, char c){ while(*p != c) p--; return p; } }; // Assumes the given c is present prior to p.
  3377. // Print that the full report is at <file path>
  3378. // Exception Info section
  3379. // Exception thread callstack.
  3380. char empty[] = "";
  3381. char* pExceptionInfoBegin = strstr(uiText, "Exception Info") ? strstr(uiText, "Exception Info") : empty;
  3382. char* pExceptionInfoEnd = (pExceptionInfoBegin == empty) ? (empty + 1) : strstr(uiText, "\n\n");
  3383. char* pExceptionThreadArea = strstr(uiText, ", exception thread");
  3384. char* pExceptionThreadBegin = pExceptionThreadArea ? Find::PreviousChar(pExceptionThreadArea, '\n') + 1 : empty;
  3385. char* pExceptionThreadEnd = (pExceptionThreadBegin == empty) ? (empty + 1) : strstr(pExceptionThreadArea, "\n\n");
  3386. if(!pExceptionInfoEnd)
  3387. pExceptionInfoEnd = pExceptionInfoBegin;
  3388. *pExceptionInfoEnd = '\0';
  3389. if(!pExceptionThreadEnd)
  3390. pExceptionThreadEnd = pExceptionThreadBegin;
  3391. *pExceptionThreadEnd = '\0';
  3392. size_t uiTextBriefLength = OVR_snprintf(nullptr, 0, "Full report:%s\n\nSummary report:\n%s\n\n%s", exceptionReportPath, pExceptionInfoBegin, pExceptionThreadBegin);
  3393. char* uiTextBrief = (char*)OVR::SafeMMapAlloc(uiTextBriefLength + 1);
  3394. if(uiTextBrief)
  3395. {
  3396. OVR_snprintf(uiTextBrief, uiTextBriefLength + 1, "Full report:%s\n\nSummary report:\n%s\n\n%s", exceptionReportPath, pExceptionInfoBegin, pExceptionThreadBegin);
  3397. OVR::SafeMMapFree(uiText, length);
  3398. uiText = uiTextBrief;
  3399. }
  3400. #endif
  3401. }
  3402. }
  3403. return uiText;
  3404. }
  3405. void ExceptionHandler::FreeExceptionUIText(const char* messageBoxText)
  3406. {
  3407. OVR::SafeMMapFree(messageBoxText, OVR_strlen(messageBoxText));
  3408. }
  3409. void ExceptionHandler::ReportDeadlock(const char* threadName,
  3410. const char* organizationName,
  3411. const char* applicationName)
  3412. {
  3413. ExceptionHandler handler;
  3414. if (!organizationName || !organizationName[0] ||
  3415. !applicationName || !applicationName[0])
  3416. {
  3417. char tempPath[OVR_MAX_PATH];
  3418. GetCrashDumpDirectory(tempPath, OVR_ARRAY_COUNT(tempPath));
  3419. OVR_strlcat(tempPath, "Deadlock Report (%s).txt", OVR_ARRAY_COUNT(tempPath));
  3420. handler.SetExceptionPaths(tempPath);
  3421. }
  3422. else
  3423. {
  3424. handler.SetPathsFromNames(organizationName, applicationName, "Deadlock Report (%s).txt");
  3425. }
  3426. OVR_snprintf(handler.exceptionInfo.exceptionDescription,
  3427. sizeof(handler.exceptionInfo.exceptionDescription),
  3428. "Deadlock in thread '%s'", threadName ? threadName : "(null)");
  3429. handler.exceptionInfo.timeVal = time(nullptr);
  3430. handler.exceptionInfo.time = *gmtime(&handler.exceptionInfo.timeVal);
  3431. handler.WriteReport();
  3432. }
  3433. //-----------------------------------------------------------------------------
  3434. // GUI Exception Listener
  3435. GUIExceptionListener::GUIExceptionListener() :
  3436. Handler()
  3437. {
  3438. }
  3439. int GUIExceptionListener::HandleException(uintptr_t userValue,
  3440. ExceptionHandler* pExceptionHandler,
  3441. ExceptionInfo* pExceptionInfo,
  3442. const char* reportFilePath)
  3443. {
  3444. OVR_UNUSED3(userValue, pExceptionHandler, pExceptionInfo);
  3445. // If debugger is not present,
  3446. if (!OVRIsDebuggerPresent())
  3447. {
  3448. const char* uiText = ExceptionHandler::GetExceptionUIText(reportFilePath);
  3449. if (uiText)
  3450. {
  3451. OVR::Util::DisplayMessageBox("Exception occurred", uiText);
  3452. ExceptionHandler::FreeExceptionUIText(uiText);
  3453. }
  3454. }
  3455. return 0;
  3456. }
  3457. } // namespace OVR
  3458. OVR_RESTORE_MSVC_WARNING()