]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - win/inspircd_win32wrapper.cpp
a25544aab95f3ab891b8fe68090017652b3f99df
[user/henk/code/inspircd.git] / win / inspircd_win32wrapper.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd_win32wrapper.h"
15 #include "inspircd.h"
16 #include "configreader.h"
17 #include <string>
18 #include <errno.h>
19 #include <assert.h>
20 #pragma comment(lib, "winmm.lib")
21 using namespace std;
22
23 #ifndef INADDR_NONE
24 #define INADDR_NONE 0xffffffff
25 #endif
26
27 #include <mmsystem.h>
28
29 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
30 static DWORD owner_processid = 0;
31
32
33 int inet_aton(const char *cp, struct in_addr *addr)
34 {
35         unsigned long ip = inet_addr(cp);
36         addr->s_addr = ip;
37         return (addr->s_addr == INADDR_NONE) ? 0 : 1;
38 }
39
40 const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
41 {
42
43         if (af == AF_INET)
44         {
45                 struct sockaddr_in in;
46                 memset(&in, 0, sizeof(in));
47                 in.sin_family = AF_INET;
48                 memcpy(&in.sin_addr, src, sizeof(struct in_addr));
49                 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
50                 return dst;
51         }
52         else if (af == AF_INET6)
53         {
54                 struct sockaddr_in6 in;
55                 memset(&in, 0, sizeof(in));
56                 in.sin6_family = AF_INET6;
57                 memcpy(&in.sin6_addr, src, sizeof(struct in_addr6));
58                 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
59                 return dst;
60         }
61         return NULL;
62 }
63
64 int geteuid()
65 {
66         return 1;
67 }
68
69 int inet_pton(int af, const char *src, void *dst)
70 {
71         sockaddr_in sa;
72         int len = sizeof(SOCKADDR);
73         int rv = WSAStringToAddress((LPSTR)src, af, NULL, (LPSOCKADDR)&sa, &len);
74         if(rv >= 0)
75         {
76                 if(WSAGetLastError() == 10022)                  // Invalid Argument
77                         rv = 0;
78                 else
79                         rv = 1;
80         }
81         memcpy(dst, &sa.sin_addr, sizeof(struct in_addr));
82         return rv;
83 }
84
85 char * strtok_r(char *_String, const char *_Control, char **_Context)
86 {
87         unsigned char *str;
88         const unsigned char *ctl = (const unsigned char*)_Control;
89         unsigned char map[32];
90
91         if (_Context == 0 || !_Control)
92                 return 0;
93
94         if (!(_String != NULL || *_Context != NULL))
95                 return 0;
96
97         memset(map, 0, 32);
98
99         do {
100                 map[*ctl >> 3] |= (1 << (*ctl & 7));
101         } while (*ctl++);
102
103         /* If string is NULL, set str to the saved
104         * pointer (i.e., continue breaking tokens out of the string
105         * from the last strtok call) */
106         if (_String != NULL)
107         {
108                 str = (unsigned char*)_String;
109         }
110         else
111         {
112                 str = (unsigned char*)*_Context;
113         }
114
115         /* Find beginning of token (skip over leading delimiters). Note that
116         * there is no token iff this loop sets str to point to the terminal
117         * null (*str == 0) */
118         while ((map[*str >> 3] & (1 << (*str & 7))) && *str != 0)
119         {
120                 str++;
121         }
122
123         _String = (char*)str;
124
125         /* Find the end of the token. If it is not the end of the string,
126         * put a null there. */
127         for ( ; *str != 0 ; str++ )
128         {
129                 if (map[*str >> 3] & (1 << (*str & 7)))
130                 {
131                         *str++ = 0;
132                         break;
133                 }
134         }
135
136         /* Update context */
137         *_Context = (char*)str;
138
139         /* Determine if a token has been found. */
140         if (_String == (char*)str)
141         {
142                 return NULL;
143         }
144         else
145         {
146                 return _String;
147         }
148 }
149
150 void setcolor(int color_code)
151 {
152         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_code);
153 }
154
155 DIR * opendir(const char * path)
156 {
157         std::string search_path = string(path) + "\\*.*";
158         WIN32_FIND_DATA fd;
159         HANDLE f = FindFirstFile(search_path.c_str(), &fd);
160         if (f != INVALID_HANDLE_VALUE)
161         {
162                 DIR * d = new DIR;
163                 memcpy(&d->find_data, &fd, sizeof(WIN32_FIND_DATA));
164                 d->find_handle = f;
165                 d->first = true;
166                 return d;
167         }
168         else
169         {
170                 return 0;
171         }
172 }
173
174 dirent * readdir(DIR * handle)
175 {
176         if (handle->first)
177                 handle->first = false;
178         else
179         {
180                 if (!FindNextFile(handle->find_handle, &handle->find_data))
181                         return 0;
182         }
183
184         strncpy(handle->dirent_pointer.d_name, handle->find_data.cFileName, MAX_PATH);
185         return &handle->dirent_pointer;
186 }
187
188 void closedir(DIR * handle)
189 {
190         FindClose(handle->find_handle);
191         delete handle;
192 }
193
194 const char * dlerror()
195 {
196         static char errormessage[500];
197         DWORD error = GetLastError();
198         SetLastError(0);
199         if (error == 0)
200                 return 0;
201
202         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)errormessage, 500, 0);
203         return errormessage;
204 }
205
206 #define TRED FOREGROUND_RED | FOREGROUND_INTENSITY
207 #define TGREEN FOREGROUND_GREEN | FOREGROUND_INTENSITY
208 #define TYELLOW FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
209 #define TNORMAL FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE
210 #define TWHITE TNORMAL | FOREGROUND_INTENSITY
211 #define TBLUE FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
212
213 /* Handles colors in printf */
214 int printf_c(const char * format, ...)
215 {
216         // Better hope we're not multithreaded, otherwise we'll have chickens crossing the road other side to get the to :P
217         static char message[MAXBUF];
218         static char temp[MAXBUF];
219         int color1, color2;
220
221         /* parse arguments */
222         va_list ap;
223         va_start(ap, format);
224         vsnprintf(message, 500, format, ap);
225         va_end(ap);
226
227         /* search for unix-style escape sequences */
228         int t;
229         int c = 0;
230         const char * p = message;
231         while (*p != 0)
232         {
233                 if (*p == '\033')
234                 {
235                         // Escape sequence -> copy into the temp buffer, and parse the color.
236                         p++;
237                         t = 0;
238                         while ((*p) && (*p != 'm'))
239                         {
240                                 temp[t++] = *p;
241                                 ++p;
242                         }
243
244                         temp[t] = 0;
245                         p++;
246
247                         if (*temp == '[')
248                         {
249                                 if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
250                                 {
251                                         switch(color2)
252                                         {
253                                         case 32:                // Green
254                                                 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY);              // Yellow
255                                                 break;
256
257                                         default:                // Unknown
258                                                 // White
259                                                 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
260                                                 break;
261                                         }
262                                 }
263                                 else
264                                 {
265                                         switch (*(temp+1))
266                                         {
267                                                 case '0':
268                                                         // Returning to normal colour.
269                                                         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
270                                                         break;
271
272                                                 case '1':
273                                                         // White
274                                                         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
275                                                         break;
276
277                                                 default:
278                                                         char message[50];
279                                                         sprintf(message, "Unknown color code: %s", temp);
280                                                         MessageBox(0, message, message, MB_OK);
281                                                         break;
282                                         }
283                                 }
284                         }
285                 }
286
287                 putchar(*p);
288                 ++c;
289                 ++p;
290         }
291
292         return c;
293 }
294
295 int arg_counter = 1;
296 char optarg[514];
297 int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
298 {
299         // burlex todo: handle the shortops, at the moment it only works with longopts.
300
301         if (___argc == 1 || arg_counter == ___argc)                     // No arguments (apart from filename)
302                 return -1;
303
304         const char * opt = ___argv[arg_counter];
305         int return_val = 0;
306
307         // if we're not an option, return an error.
308         if (strnicmp(opt, "--", 2) != 0)
309                 return 1;
310         else
311                 opt += 2;
312
313
314         // parse argument list
315         int i = 0;
316         for (; __longopts[i].name != 0; ++i)
317         {
318                 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
319                 {
320                         // woot, found a valid argument =)
321                         char * par = 0;
322                         if ((arg_counter + 1) != ___argc)
323                         {
324                                 // grab the parameter from the next argument (if its not another argument)
325                                 if (strnicmp(___argv[arg_counter+1], "--", 2) != 0)
326                                 {
327                                         arg_counter++;          // Trash this next argument, we won't be needing it.
328                                         par = ___argv[arg_counter];
329                                 }
330                         }                       
331
332                         // increment the argument for next time
333                         arg_counter++;
334
335                         // determine action based on type
336                         if (__longopts[i].has_arg == required_argument && !par)
337                         {
338                                 // parameter missing and its a required parameter option
339                                 return 1;
340                         }
341
342                         // store argument in optarg
343                         if (par)
344                                 strncpy(optarg, par, 514);
345
346                         if (__longopts[i].flag != 0)
347                         {
348                                 // this is a variable, we have to set it if this argument is found.
349                                 *__longopts[i].flag = 1;
350                                 return 0;
351                         }
352                         else
353                         {
354                                 if (__longopts[i].val == -1 || par == 0)
355                                         return 1;
356                                 
357                                 return __longopts[i].val;
358                         }                       
359                         break;
360                 }
361         }
362
363         // return 1 (invalid argument)
364         return 1;
365 }
366
367 /* IPC Messages */
368 #define IPC_MESSAGE_REHASH      1
369 #define IPC_MESSAGE_DIE         2
370 #define IPC_MESSAGE_RESTART     3
371
372 IPC::IPC(InspIRCd* Srv) : Instance(Srv)
373 {
374         static DWORD buflen = 1024;
375         static const char * pipename = "\\\\.\\mailslot\\Inspircd";
376         hIPCPipe = CreateMailslot(pipename, buflen, 0, 0);
377         if (hIPCPipe == INVALID_HANDLE_VALUE)
378                 printf("IPC Pipe could not be created. Are you sure you didn't start InspIRCd twice?\n");
379 }
380
381 void IPC::Check()
382 {
383         if (hIPCPipe == INVALID_HANDLE_VALUE)
384                 return;
385
386         DWORD bytes;
387         DWORD action;
388
389         BOOL res = ReadFile(hIPCPipe, &action, sizeof(DWORD), &bytes, 0);
390         if (!res)
391         {
392                 if (GetLastError() != ERROR_SEM_TIMEOUT)
393                         Instance->Log(DEFAULT, "IPC Pipe Error %u: %s", GetLastError(), dlerror());
394                 return;
395         }
396
397         switch (action)
398         {
399                 case IPC_MESSAGE_REHASH:
400                         Instance->Rehash();
401                 break;
402                 
403                 case IPC_MESSAGE_DIE:
404                         Instance->Exit(0);
405                 break;
406
407                 case IPC_MESSAGE_RESTART:
408                         Instance->Restart("IPC_MESSAGE_RESTART received by mailslot.");
409                 break;
410         }
411 }
412
413 IPC::~IPC()
414 {
415         CloseHandle(hIPCPipe);
416 }
417
418
419 /* These three functions were created from looking at how ares does it
420  * (...and they look far tidier in C++)
421  */
422
423 /* Get active nameserver */
424 bool GetNameServer(HKEY regkey, const char *key, char* &output)
425 {
426         DWORD size = 0;
427         DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
428         if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
429                 return false;
430
431         output = new char[size+1];
432
433         if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
434         {
435                 delete output;
436                 return false;
437         }
438         return true;
439 }
440
441 /* Check a network interface for its nameserver */
442 bool GetInterface(HKEY regkey, const char *key, char* &output)
443 {
444         char buf[39];
445         DWORD size = 39;
446         int idx = 0;
447         HKEY top;
448
449         while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
450         {
451                 size = 39;
452                 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
453                         continue;
454                 int rc = GetNameServer(top, key, output);
455                 RegCloseKey(top);
456                 if (rc)
457                         return true;
458         }
459         return false;
460 }
461
462
463 std::string FindNameServerWin()
464 {
465         std::string returnval = "127.0.0.1";
466         HKEY top, key;
467         char* dns = NULL;
468
469         /* Lets see if the correct registry hive and tree exist */
470         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
471         {
472                 /* If they do, attempt to get the nameserver name */
473                 RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
474                 if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
475                         || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
476                 {
477                         if (dns)
478                         {
479                                 returnval = dns;
480                                 delete dns;
481                         }
482                 }
483                 RegCloseKey(key);
484                 RegCloseKey(top);
485         }
486         return returnval;
487 }
488
489
490 void ClearConsole()
491 {
492         COORD coordScreen = { 0, 0 };    /* here's where we'll home the cursor */
493         HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
494         DWORD cCharsWritten;
495         CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */ 
496         DWORD dwConSize;                 /* number of character cells in the current buffer */ 
497
498         /* get the number of character cells in the current buffer */ 
499
500         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
501         {
502                 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
503                 /* fill the entire screen with blanks */ 
504                 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
505                 {
506                         /* get the current text attribute */ 
507                         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
508                         {
509                                 /* now set the buffer's attributes accordingly */
510                                 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
511                                 {
512                                         /* put the cursor at (0, 0) */
513                                         SetConsoleCursorPosition( hConsole, coordScreen );
514                                 }
515                         }
516                 }
517         }
518         return;
519 }
520
521 /* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
522  * of code. This function repoints these pointers and functors so that calls are windows specific.
523  */
524 void ChangeWindowsSpecificPointers(InspIRCd* Instance)
525 {
526         Instance->Log(DEBUG,"Changing to windows specific pointer and functor set");
527         Instance->Config->DNSServerValidator = &ValidateWindowsDnsServer;
528 }
529
530 DWORD WindowsForkStart(InspIRCd* Instance)
531 {
532         /* Windows implementation of fork() :P */
533         if (owner_processid)
534                 return 0;
535
536         char module[MAX_PATH];
537         if(!GetModuleFileName(NULL, module, MAX_PATH))
538         {
539                 printf("GetModuleFileName() failed.\n");
540                 return false;
541         }
542
543         STARTUPINFO startupinfo;
544         PROCESS_INFORMATION procinfo;
545         ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
546         ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
547
548         // Fill in the startup info struct
549         GetStartupInfo(&startupinfo);
550
551         /* Default creation flags create the processes suspended */
552         DWORD startupflags = CREATE_SUSPENDED;
553
554         /* On windows 2003/XP and above, we can use the value
555          * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
556          * to the process which we may require on these operating systems.
557          */
558         OSVERSIONINFO vi;
559         vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
560         GetVersionEx(&vi);
561         if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
562                 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
563
564         // Launch our "forked" process.
565         BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
566                 strdup(GetCommandLine()),       // Command line (exe plus parameters from the OS)
567                                                 // NOTE: We cannot return the direct value of the
568                                                 // GetCommandLine function here, as the pointer is
569                                                 // passed straight to the child process, and will be
570                                                 // invalid once we exit as it goes out of context.
571                                                 // strdup() seems ok, though.
572                 0,                              // PROCESS_SECURITY_ATTRIBUTES
573                 0,                              // THREAD_SECURITY_ATTRIBUTES
574                 TRUE,                           // We went to inherit handles.
575                 startupflags,                   // Allow us full access to the process and suspend it.
576                 0,                              // ENVIRONMENT
577                 0,                              // CURRENT_DIRECTORY
578                 &startupinfo,                   // startup info
579                 &procinfo);                     // process info
580
581         if(!bSuccess)
582         {
583                 printf("CreateProcess() error: %s\n", dlerror());
584                 return false;
585         }
586
587         // Set the owner process id in the target process.
588         SIZE_T written = 0;
589         DWORD pid = GetCurrentProcessId();
590         if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
591         {
592                 printf("WriteProcessMemory() failed: %s\n", dlerror());
593                 return false;
594         }
595
596         // Resume the other thread (let it start)
597         ResumeThread(procinfo.hThread);
598
599         // Wait for the new process to kill us. If there is some error, the new process will end and we will end up at the next line.
600         WaitForSingleObject(procinfo.hProcess, INFINITE);
601
602         // If we hit this it means startup failed, default to 14 if this fails.
603         DWORD ExitCode = 14;
604         GetExitCodeProcess(procinfo.hProcess, &ExitCode);
605         CloseHandle(procinfo.hThread);
606         CloseHandle(procinfo.hProcess);
607         return ExitCode;
608 }
609
610 void WindowsForkKillOwner(InspIRCd * Instance)
611 {
612         HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
613         if(!hProcess || !owner_processid)
614         {
615                 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
616                 Instance->Exit(14);
617         }
618
619         // die die die
620         if(!TerminateProcess(hProcess, 0))
621         {
622                 printf("Could not TerminateProcess(): %s\n", dlerror());
623                 Instance->Exit(14);
624         }
625
626         CloseHandle(hProcess);
627 }
628
629 bool ValidateWindowsDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
630 {
631         if (!*(data.GetString()))
632         {
633                 std::string nameserver;
634                 conf->GetInstance()->Log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in the registry...");
635                 nameserver = FindNameServerWin();
636                 /* Windows stacks multiple nameservers in one registry key, seperated by commas.
637                  * Spotted by Cataclysm.
638                  */
639                 if (nameserver.find(',') != std::string::npos)
640                         nameserver = nameserver.substr(0, nameserver.find(','));
641                 data.Set(nameserver.c_str());
642                 conf->GetInstance()->Log(DEFAULT,"<dns:server> set to '%s' as first active resolver in registry.", nameserver.c_str());
643         }
644         return true;
645 }
646
647 int gettimeofday(struct timeval * tv, void * tz)
648 {
649         if(tv == NULL)
650                 return -1;
651
652         DWORD mstime = timeGetTime();
653         tv->tv_sec   = time(NULL);
654         tv->tv_usec  = (mstime - (tv->tv_sec * 1000)) * 1000;
655     return 0;   
656 }
657
658 int __exceptionHandler(PEXCEPTION_POINTERS pExceptPtrs)
659 {
660         SYSTEMTIME _time;
661         HANDLE hDump;
662         char mod[MAX_PATH*2];
663         char * pMod = mod;
664         char dump_filename[MAX_PATH];
665         MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
666         DWORD code;
667
668         if(pExceptPtrs == NULL) {
669                 __try {
670                         RaiseException(EXCEPTION_BREAKPOINT, 0, 0, NULL);
671                 } __except(__exceptionHandler(GetExceptionInformation()), EXCEPTION_CONTINUE_EXECUTION) {}
672         }
673
674         printf("Exception caught at 0x%.8X! Attempting to write crash dump file.\n", (unsigned long)pExceptPtrs->ExceptionRecord->ExceptionAddress);
675
676         if(GetModuleFileName(0, mod, MAX_PATH*2) > 0)
677         {
678                 if( (pMod = strrchr(mod, '\\')) != NULL )
679                         ++pMod;
680                 else
681                         strcpy(mod, "unk");
682         }
683         else
684                 strcpy(mod, "unk");
685
686         GetSystemTime(&_time);
687         snprintf(dump_filename, MAX_PATH, "dump-%s-%u-%u-%u-%u-%u-%u.dmp",
688                 pMod, _time.wYear, _time.wMonth, _time.wDay, _time.wHour, _time.wMinute, _time.wSecond);
689
690         hDump = CreateFile(dump_filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0);
691         if(hDump != INVALID_HANDLE_VALUE)
692         {
693                 dumpInfo.ClientPointers = FALSE;
694                 dumpInfo.ExceptionPointers = pExceptPtrs;
695                 dumpInfo.ThreadId = GetCurrentThreadId();
696
697                 /* let's write a full memory dump. insp shouldn't be using much memory anyway, and it will help a lot with debugging. */
698                 MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDump, MiniDumpWithFullMemory, &dumpInfo, NULL, NULL);
699                 FlushFileBuffers(hDump);
700                 CloseHandle(hDump);
701         }
702
703         /* check for a debugger */
704         __asm {
705                 pushad
706                 pushfd
707                 mov eax, fs:[18h]
708                 mov eax, dword ptr [eax+30h]
709                 mov ebx, dword ptr [eax]
710                 mov code, ebx
711                 popfd
712                 popad
713         }
714
715         /* break into debugger if we have one */
716         if(code & 0x10000)
717                 return EXCEPTION_CONTINUE_SEARCH;
718         else    /* otherwise exit abnormally */
719                 return EXCEPTION_CONTINUE_EXECUTION;
720 }