2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 #include <afs/param.h>
12 #include <afs/afs_args.h>
24 #include <rx\rx_null.h>
26 #include <WINNT/syscfg.h>
30 #include "lanahelper.h"
32 extern int RXAFSCB_ExecuteRequest(struct rx_call *z_call);
33 extern int RXSTATS_ExecuteRequest(struct rx_call *z_call);
35 extern afs_int32 cryptall;
37 char AFSConfigKeyName[] =
38 "SYSTEM\\CurrentControlSet\\Services\\TransarcAFSDaemon\\Parameters";
42 char cm_rootVolumeName[64];
43 DWORD cm_rootVolumeNameLen;
44 cm_volume_t *cm_rootVolumep = NULL;
45 cm_cell_t *cm_rootCellp = NULL;
47 cm_scache_t *cm_rootSCachep;
48 char cm_mountRoot[1024];
49 DWORD cm_mountRootLen;
52 #ifdef AFS_FREELANCE_CLIENT
54 #endif /* freelance */
67 char cm_HostName[200];
70 char cm_NetbiosName[MAX_NB_NAME_LENGTH];
72 char cm_CachePath[200];
73 DWORD cm_CachePathLen;
75 BOOL isGateway = FALSE;
77 BOOL reportSessionStartups = FALSE;
79 cm_initparams_v1 cm_initParams;
82 * AFSD Initialization Log
84 * This is distinct from the regular debug logging facility.
85 * Log items go directly to a file, not to an array in memory, so that even
86 * if AFSD crashes, the log can be inspected.
92 int cm_dnsEnabled = 1;
95 char cm_NetBiosName[32];
105 afsi_file = INVALID_HANDLE_VALUE;
108 strcpy(wd, getenv("TEMP"));
112 code = GetWindowsDirectory(wd, sizeof(wd));
113 if (code == 0) return;
115 strcat(wd, "\\afsd_init.log");
116 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
117 afsi_file = CreateFile(wd, GENERIC_WRITE, FILE_SHARE_READ, NULL,
118 OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
119 SetFilePointer(afsi_file, 0, NULL, FILE_END);
120 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, u, sizeof(u));
121 strcat(t, ": Create log file\n");
122 strcat(u, ": Created log file\n");
123 WriteFile(afsi_file, t, strlen(t), &zilch, NULL);
124 WriteFile(afsi_file, u, strlen(u), &zilch, NULL);
127 static int afsi_log_useTimestamp = 1;
130 afsi_log(char *pattern, ...)
132 char s[100], t[100], d[100], u[300];
135 va_start(ap, pattern);
137 vsprintf(s, pattern, ap);
138 if ( afsi_log_useTimestamp ) {
139 GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, t, sizeof(t));
140 GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, NULL, d, sizeof(d));
141 sprintf(u, "%s %s: %s\n", d, t, s);
142 if (afsi_file != INVALID_HANDLE_VALUE)
143 WriteFile(afsi_file, u, strlen(u), &zilch, NULL);
148 if (afsi_file != INVALID_HANDLE_VALUE)
149 WriteFile(afsi_file, s, strlen(s), &zilch, NULL);
154 * Standard AFSD trace
157 void afsd_ForceTrace(BOOL flush)
163 if (!logReady) return;
165 len = GetTempPath(99, buf);
166 strcpy(&buf[len], "/afsd.log");
167 handle = CreateFile(buf, GENERIC_WRITE, FILE_SHARE_READ,
168 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
169 if (handle == INVALID_HANDLE_VALUE) {
171 osi_panic("Cannot create log file", __FILE__, __LINE__);
173 osi_LogPrint(afsd_logp, handle);
175 FlushFileBuffers(handle);
180 * AFSD Initialization
183 int afsd_InitCM(char **reasonP)
192 long rx_mtu, rx_nojumbo;
193 char rootCellName[256];
194 struct rx_service *serverp;
195 static struct rx_securityClass *nullServerSecurityClassp;
202 /*int freelanceEnabled;*/
204 lana_number_t lanaNum;
206 WSAStartup(0x0101, &WSAjunk);
208 /* setup osidebug server at RPC slot 1000 */
209 osi_LongToUID(1000, &debugID);
210 code = osi_InitDebug(&debugID);
211 afsi_log("osi_InitDebug code %d", code);
212 // osi_LockTypeSetDefault("stat"); /* comment this out for speed *
214 *reasonP = "unknown error";
219 gethostname(cm_HostName, sizeof(cm_HostName));
220 afsi_log("gethostname %s", cm_HostName);
221 thp = gethostbyname(cm_HostName);
222 memcpy(&cm_HostAddr, thp->h_addr_list[0], 4);
224 /* seed random number generator */
225 srand(ntohl(cm_HostAddr));
227 /* Look up configuration parameters in Registry */
228 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSConfigKeyName,
229 0, KEY_QUERY_VALUE, &parmKey);
230 if (code != ERROR_SUCCESS) {
231 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
232 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
233 NULL, code, 0, (LPTSTR)&msgBuf, 0, NULL);
235 "Failure in configuration while opening Registry: %s",
237 osi_panic(buf, __FILE__, __LINE__);
240 dummyLen = sizeof(cacheSize);
241 code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
242 (BYTE *) &cacheSize, &dummyLen);
243 if (code == ERROR_SUCCESS)
244 afsi_log("Cache size %d", cacheSize);
246 cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
247 afsi_log("Default cache size %d", cacheSize);
250 dummyLen = sizeof(logChunkSize);
251 code = RegQueryValueEx(parmKey, "ChunkSize", NULL, NULL,
252 (BYTE *) &logChunkSize, &dummyLen);
253 if (code == ERROR_SUCCESS) {
254 if (logChunkSize < 12 || logChunkSize > 30) {
255 afsi_log("Invalid chunk size %d, using default",
257 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
259 afsi_log("Chunk size %d", logChunkSize);
261 logChunkSize = CM_CONFIGDEFAULT_CHUNKSIZE;
262 afsi_log("Default chunk size %d", logChunkSize);
264 cm_logChunkSize = logChunkSize;
265 cm_chunkSize = 1 << logChunkSize;
267 dummyLen = sizeof(numBkgD);
268 code = RegQueryValueEx(parmKey, "Daemons", NULL, NULL,
269 (BYTE *) &numBkgD, &dummyLen);
270 if (code == ERROR_SUCCESS)
271 afsi_log("%d background daemons", numBkgD);
273 numBkgD = CM_CONFIGDEFAULT_DAEMONS;
274 afsi_log("Defaulting to %d background daemons", numBkgD);
277 dummyLen = sizeof(numSvThreads);
278 code = RegQueryValueEx(parmKey, "ServerThreads", NULL, NULL,
279 (BYTE *) &numSvThreads, &dummyLen);
280 if (code == ERROR_SUCCESS)
281 afsi_log("%d server threads", numSvThreads);
283 numSvThreads = CM_CONFIGDEFAULT_SVTHREADS;
284 afsi_log("Defaulting to %d server threads", numSvThreads);
287 dummyLen = sizeof(stats);
288 code = RegQueryValueEx(parmKey, "Stats", NULL, NULL,
289 (BYTE *) &stats, &dummyLen);
290 if (code == ERROR_SUCCESS)
291 afsi_log("Status cache size %d", stats);
293 stats = CM_CONFIGDEFAULT_STATS;
294 afsi_log("Default status cache size %d", stats);
297 dummyLen = sizeof(ltt);
298 code = RegQueryValueEx(parmKey, "LogoffTokenTransfer", NULL, NULL,
299 (BYTE *) <t, &dummyLen);
300 if (code == ERROR_SUCCESS)
301 afsi_log("Logoff token transfer %s", (ltt ? "on" : "off"));
304 afsi_log("Logoff token transfer on by default");
306 smb_LogoffTokenTransfer = ltt;
309 dummyLen = sizeof(ltto);
310 code = RegQueryValueEx(parmKey, "LogoffTokenTransferTimeout",
311 NULL, NULL, (BYTE *) <to, &dummyLen);
312 if (code == ERROR_SUCCESS)
313 afsi_log("Logoff token tranfer timeout %d seconds",
317 afsi_log("Default logoff token transfer timeout 10 seconds");
320 smb_LogoffTransferTimeout = ltto;
322 dummyLen = sizeof(cm_rootVolumeName);
323 code = RegQueryValueEx(parmKey, "RootVolume", NULL, NULL,
324 cm_rootVolumeName, &dummyLen);
325 if (code == ERROR_SUCCESS)
326 afsi_log("Root volume %s", cm_rootVolumeName);
328 strcpy(cm_rootVolumeName, "root.afs");
329 afsi_log("Default root volume name root.afs");
332 cm_mountRootLen = sizeof(cm_mountRoot);
333 code = RegQueryValueEx(parmKey, "Mountroot", NULL, NULL,
334 cm_mountRoot, &cm_mountRootLen);
335 if (code == ERROR_SUCCESS) {
336 afsi_log("Mount root %s", cm_mountRoot);
337 cm_mountRootLen = strlen(cm_mountRoot);
339 strcpy(cm_mountRoot, "/afs");
344 dummyLen = sizeof(cm_CachePath);
345 code = RegQueryValueEx(parmKey, "CachePath", NULL, NULL,
346 cm_CachePath, &dummyLen);
347 if (code == ERROR_SUCCESS)
348 afsi_log("Cache path %s", cm_CachePath);
350 GetWindowsDirectory(cm_CachePath, sizeof(cm_CachePath));
351 cm_CachePath[2] = 0; /* get drive letter only */
352 strcat(cm_CachePath, "\\AFSCache");
353 afsi_log("Default cache path %s", cm_CachePath);
356 dummyLen = sizeof(traceOnPanic);
357 code = RegQueryValueEx(parmKey, "TrapOnPanic", NULL, NULL,
358 (BYTE *) &traceOnPanic, &dummyLen);
359 if (code == ERROR_SUCCESS)
360 afsi_log("Set to %s on panic",
361 traceOnPanic ? "trap" : "not trap");
367 dummyLen = sizeof(reportSessionStartups);
368 code = RegQueryValueEx(parmKey, "ReportSessionStartups", NULL, NULL,
369 (BYTE *) &reportSessionStartups, &dummyLen);
370 if (code == ERROR_SUCCESS)
371 afsi_log("Session startups %s be recorded in the Event Log",
372 reportSessionStartups ? "will" : "will not");
374 reportSessionStartups = 0;
378 dummyLen = sizeof(traceBufSize);
379 code = RegQueryValueEx(parmKey, "TraceBufferSize", NULL, NULL,
380 (BYTE *) &traceBufSize, &dummyLen);
381 if (code == ERROR_SUCCESS)
382 afsi_log("Trace Buffer size %d", traceBufSize);
384 traceBufSize = CM_CONFIGDEFAULT_TRACEBUFSIZE;
385 afsi_log("Default trace buffer size %d", traceBufSize);
388 dummyLen = sizeof(cm_sysName);
389 code = RegQueryValueEx(parmKey, "SysName", NULL, NULL,
390 cm_sysName, &dummyLen);
391 if (code == ERROR_SUCCESS)
392 afsi_log("Sys name %s", cm_sysName);
394 strcat(cm_sysName, "i386_nt40");
395 afsi_log("Default sys name %s", cm_sysName);
398 dummyLen = sizeof(cryptall);
399 code = RegQueryValueEx(parmKey, "SecurityLevel", NULL, NULL,
400 (BYTE *) &cryptall, &dummyLen);
401 if (code == ERROR_SUCCESS)
402 afsi_log("SecurityLevel is %s", cryptall?"crypt":"clear");
404 cryptall = rxkad_clear;
405 afsi_log("Default SecurityLevel is clear");
409 dummyLen = sizeof(cm_dnsEnabled);
410 code = RegQueryValueEx(parmKey, "UseDNS", NULL, NULL,
411 (BYTE *) &cm_dnsEnabled, &dummyLen);
412 if (code == ERROR_SUCCESS) {
413 afsi_log("DNS %s be used to find AFS cell servers",
414 cm_dnsEnabled ? "will" : "will not");
417 cm_dnsEnabled = 1; /* default on */
418 afsi_log("Default to use DNS to find AFS cell servers");
420 #else /* AFS_AFSDB_ENV */
421 afsi_log("AFS not built with DNS support to find AFS cell servers");
422 #endif /* AFS_AFSDB_ENV */
424 #ifdef AFS_FREELANCE_CLIENT
425 dummyLen = sizeof(cm_freelanceEnabled);
426 code = RegQueryValueEx(parmKey, "FreelanceClient", NULL, NULL,
427 (BYTE *) &cm_freelanceEnabled, &dummyLen);
428 if (code == ERROR_SUCCESS) {
429 afsi_log("Freelance client feature %s activated",
430 cm_freelanceEnabled ? "is" : "is not");
433 cm_freelanceEnabled = 0; /* default off */
435 #endif /* AFS_FREELANCE_CLIENT */
437 dummyLen = sizeof(cm_NetBiosName);
438 code = RegQueryValueEx(parmKey, "NetbiosName", NULL, NULL,
439 (BYTE *) &cm_NetBiosName, &dummyLen);
440 if (code == ERROR_SUCCESS) {
441 afsi_log("Explicit NetBios name is used %s", cm_NetBiosName);
444 cm_NetBiosName[0] = 0; /* default off */
447 dummyLen = sizeof(smb_hideDotFiles);
448 code = RegQueryValueEx(parmKey, "HideDotFiles", NULL, NULL,
449 (BYTE *) &smb_hideDotFiles, &dummyLen);
450 if (code != ERROR_SUCCESS) {
451 smb_hideDotFiles = 1; /* default on */
453 afsi_log("Dot files/dirs will %sbe marked hidden",
454 smb_hideDotFiles ? "" : "not ");
456 dummyLen = sizeof(smb_maxMpxRequests);
457 code = RegQueryValueEx(parmKey, "MaxMpxRequests", NULL, NULL,
458 (BYTE *) &smb_maxMpxRequests, &dummyLen);
459 if (code != ERROR_SUCCESS) {
460 smb_maxMpxRequests = 50;
462 afsi_log("Maximum number of multiplexed sessions is %d", smb_maxMpxRequests);
464 dummyLen = sizeof(smb_maxVCPerServer);
465 code = RegQueryValueEx(parmKey, "MaxVCPerServer", NULL, NULL,
466 (BYTE *) &smb_maxVCPerServer, &dummyLen);
467 if (code != ERROR_SUCCESS) {
468 smb_maxVCPerServer = 100;
470 afsi_log("Maximum number of VCs per server is %d", smb_maxVCPerServer);
472 dummyLen = sizeof(rx_nojumbo);
473 code = RegQueryValueEx(parmKey, "RxNoJumbo", NULL, NULL,
474 (BYTE *) &rx_nojumbo, &dummyLen);
475 if (code != ERROR_SUCCESS) {
479 afsi_log("RX Jumbograms are disabled");
481 dummyLen = sizeof(rx_mtu);
482 code = RegQueryValueEx(parmKey, "RxMaxMTU", NULL, NULL,
483 (BYTE *) &rx_mtu, &dummyLen);
484 if (code != ERROR_SUCCESS || !rx_mtu) {
488 afsi_log("RX maximum MTU is %d", rx_mtu);
490 RegCloseKey (parmKey);
492 /* Call lanahelper to get Netbios name, lan adapter number and gateway flag */
493 if(SUCCEEDED(code = lana_GetUncServerNameEx(cm_NetbiosName, &lanaNum, &isGateway, LANA_NETBIOS_NAME_FULL))) {
494 LANadapter = (lanaNum == LANA_INVALID)? -1: lanaNum;
497 afsi_log("LAN adapter number %d", LANadapter);
499 afsi_log("LAN adapter number not determined");
502 afsi_log("Set for gateway service");
504 afsi_log("Using >%s< as SMB server name", cm_NetbiosName);
506 /* something went horribly wrong. We can't proceed without a netbios name */
507 sprintf(buf,"Netbios name could not be determined: %li", code);
508 osi_panic(buf, __FILE__, __LINE__);
511 /* setup early variables */
512 /* These both used to be configurable. */
514 buf_bufferSize = CM_CONFIGDEFAULT_BLOCKSIZE;
516 /* turn from 1024 byte units into memory blocks */
517 cacheBlocks = (cacheSize * 1024) / buf_bufferSize;
519 /* setup and enable debug log */
520 afsd_logp = osi_LogCreate("afsd", traceBufSize);
521 afsi_log("osi_LogCreate log addr %x", (int)afsd_logp);
522 osi_LogEnable(afsd_logp);
525 osi_Log0(afsd_logp, "Log init");
527 /* get network related info */
528 cm_noIPAddr = CM_MAXINTERFACE_ADDR;
529 code = syscfg_GetIFInfo(&cm_noIPAddr,
530 cm_IPAddr, cm_SubnetMask,
531 cm_NetMtu, cm_NetFlags);
533 if ( (cm_noIPAddr <= 0) || (code <= 0 ) )
534 afsi_log("syscfg_GetIFInfo error code %d", code);
536 afsi_log("First Network address %x SubnetMask %x",
537 cm_IPAddr[0], cm_SubnetMask[0]);
540 * Save client configuration for GetCacheConfig requests
542 cm_initParams.nChunkFiles = 0;
543 cm_initParams.nStatCaches = stats;
544 cm_initParams.nDataCaches = 0;
545 cm_initParams.nVolumeCaches = 0;
546 cm_initParams.firstChunkSize = cm_chunkSize;
547 cm_initParams.otherChunkSize = cm_chunkSize;
548 cm_initParams.cacheSize = cacheSize;
549 cm_initParams.setTime = 0;
550 cm_initParams.memCache = 0;
552 /* Set RX parameters before initializing RX */
557 rx_SetMaxMTU(rx_mtu);
559 /* initialize RX, and tell it to listen to port 7001, which is used for
560 * callback RPC messages.
562 code = rx_Init(htons(7001));
563 afsi_log("rx_Init code %x", code);
565 *reasonP = "afsd: failed to init rx client on port 7001";
569 /* Initialize the RPC server for session keys */
572 /* create an unauthenticated service #1 for callbacks */
573 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
574 serverp = rx_NewService(0, 1, "AFS", &nullServerSecurityClassp, 1,
575 RXAFSCB_ExecuteRequest);
576 afsi_log("rx_NewService addr %x", (int)serverp);
577 if (serverp == NULL) {
578 *reasonP = "unknown error";
582 nullServerSecurityClassp = rxnull_NewServerSecurityObject();
583 serverp = rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats",
584 &nullServerSecurityClassp, 1, RXSTATS_ExecuteRequest);
585 afsi_log("rx_NewService addr %x", (int)serverp);
586 if (serverp == NULL) {
587 *reasonP = "unknown error";
591 /* start server threads, *not* donating this one to the pool */
593 afsi_log("rx_StartServer");
595 /* init user daemon, and other packages */
598 cm_InitACLCache(2*stats);
614 cm_InitSCache(stats);
616 code = cm_InitDCache(0, cacheBlocks);
617 afsi_log("cm_InitDCache code %x", code);
619 *reasonP = "error initializing cache";
624 #if !defined(_WIN32_WINNT) || _WIN32_WINNT < 0x500
625 if (cm_InitDNS(cm_dnsEnabled) == -1)
626 cm_dnsEnabled = 0; /* init failed, so deactivate */
627 afsi_log("cm_InitDNS %d", cm_dnsEnabled);
631 code = cm_GetRootCellName(rootCellName);
632 afsi_log("cm_GetRootCellName code %d, cm_freelanceEnabled= %d, rcn= %s",
633 code, cm_freelanceEnabled, (code ? "<none>" : rootCellName));
634 if (code != 0 && !cm_freelanceEnabled)
636 *reasonP = "can't find root cell name in afsd.ini";
639 else if (cm_freelanceEnabled)
642 if (code == 0 && !cm_freelanceEnabled)
644 cm_rootCellp = cm_GetCell(rootCellName, CM_FLAG_CREATE);
645 afsi_log("cm_GetCell addr %x", (int)cm_rootCellp);
646 if (cm_rootCellp == NULL)
648 *reasonP = "can't find root cell in afsdcell.ini";
653 #ifdef AFS_FREELANCE_CLIENT
654 if (cm_freelanceEnabled)
661 int afsd_InitDaemons(char **reasonP)
668 /* this should really be in an init daemon from here on down */
670 if (!cm_freelanceEnabled) {
671 code = cm_GetVolumeByName(cm_rootCellp, cm_rootVolumeName, cm_rootUserp,
672 &req, CM_FLAG_CREATE, &cm_rootVolumep);
673 afsi_log("cm_GetVolumeByName code %x root vol %x", code,
674 (code ? (cm_volume_t *)-1 : cm_rootVolumep));
676 *reasonP = "can't find root volume in root cell";
681 /* compute the root fid */
682 if (!cm_freelanceEnabled) {
683 cm_rootFid.cell = cm_rootCellp->cellID;
684 cm_rootFid.volume = cm_GetROVolumeID(cm_rootVolumep);
685 cm_rootFid.vnode = 1;
686 cm_rootFid.unique = 1;
689 cm_FakeRootFid(&cm_rootFid);
691 code = cm_GetSCache(&cm_rootFid, &cm_rootSCachep, cm_rootUserp, &req);
692 afsi_log("cm_GetSCache code %x scache %x", code,
693 (code ? (cm_scache_t *)-1 : cm_rootSCachep));
695 *reasonP = "unknown error";
699 cm_InitDaemon(numBkgD);
700 afsi_log("cm_InitDaemon");
705 int afsd_InitSMB(char **reasonP, void *aMBfunc)
707 /* Do this last so that we don't handle requests before init is done.
708 * Here we initialize the SMB listener.
710 smb_Init(afsd_logp, cm_NetbiosName, smb_UseV3, LANadapter, numSvThreads, aMBfunc);
711 afsi_log("smb_Init");
724 #pragma pack( push, before_imagehlp, 8 )
725 #include <imagehlp.h>
726 #pragma pack( pop, before_imagehlp )
728 #define MAXNAMELEN 1024
730 void afsd_printStack(HANDLE hThread, CONTEXT *c)
732 HANDLE hProcess = GetCurrentProcess();
736 char functionName[MAXNAMELEN];
738 IMAGEHLP_MODULE Module;
742 IMAGEHLP_SYMBOL *pSym;
744 afsi_log_useTimestamp = 0;
746 pSym = (IMAGEHLP_SYMBOL *) GlobalAlloc(0, sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN);
748 memset( &s, '\0', sizeof s );
749 if (!SymInitialize(hProcess, NULL, 1) )
751 afsi_log("SymInitialize(): GetLastError() = %lu\n", GetLastError() );
753 SymCleanup( hProcess );
759 symOptions = SymGetOptions();
760 symOptions |= SYMOPT_LOAD_LINES;
761 symOptions &= ~SYMOPT_UNDNAME;
762 SymSetOptions( symOptions );
765 * init STACKFRAME for first call
766 * Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
767 * Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
770 #if defined (_ALPHA_) || defined (_MIPS_) || defined (_PPC_)
771 #error The STACKFRAME initialization in afsd_printStack() for this platform
772 #error must be properly configured
774 s.AddrPC.Offset = c->Eip;
775 s.AddrPC.Mode = AddrModeFlat;
776 s.AddrFrame.Offset = c->Ebp;
777 s.AddrFrame.Mode = AddrModeFlat;
780 memset( pSym, '\0', sizeof (IMAGEHLP_SYMBOL) + MAXNAMELEN );
781 pSym->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
782 pSym->MaxNameLength = MAXNAMELEN;
784 memset( &Line, '\0', sizeof Line );
785 Line.SizeOfStruct = sizeof Line;
787 memset( &Module, '\0', sizeof Module );
788 Module.SizeOfStruct = sizeof Module;
792 afsi_log("\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol" );
794 for ( frameNum = 0; ; ++ frameNum )
797 * get next stack frame (StackWalk(), SymFunctionTableAccess(),
798 * SymGetModuleBase()). if this returns ERROR_INVALID_ADDRESS (487) or
799 * ERROR_NOACCESS (998), you can assume that either you are done, or
800 * that the stack is so hosed that the next deeper frame could not be
803 if ( ! StackWalk( IMAGE_FILE_MACHINE_I386, hProcess, hThread, &s, c,
804 NULL, SymFunctionTableAccess, SymGetModuleBase,
808 /* display its contents */
809 afsi_log("\n%3d %c%c %08lx %08lx %08lx %08lx ",
810 frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
811 s.AddrPC.Offset, s.AddrReturn.Offset,
812 s.AddrFrame.Offset, s.AddrStack.Offset );
814 if ( s.AddrPC.Offset == 0 )
816 afsi_log("(-nosymbols- PC == 0)" );
820 /* show procedure info from a valid PC */
821 if (!SymGetSymFromAddr(hProcess, s.AddrPC.Offset, &offset, pSym))
823 if ( GetLastError() != ERROR_INVALID_ADDRESS )
825 afsi_log("SymGetSymFromAddr(): errno = %lu",
831 UnDecorateSymbolName(pSym->Name, functionName, MAXNAMELEN,
833 afsi_log("%s", functionName );
837 afsi_log(" %+ld bytes", (long) offset);
841 if (!SymGetLineFromAddr(hProcess, s.AddrPC.Offset, &offset, &Line))
843 if (GetLastError() != ERROR_INVALID_ADDRESS)
845 afsi_log("Error: SymGetLineFromAddr(): errno = %lu",
851 afsi_log(" Line: %s(%lu) %+ld bytes", Line.FileName,
852 Line.LineNumber, offset);
856 /* no return address means no deeper stackframe */
857 if (s.AddrReturn.Offset == 0)
864 if (GetLastError() != 0)
866 afsi_log("\nStackWalk(): errno = %lu\n", GetLastError());
869 SymCleanup(hProcess);
874 static DWORD *afsd_crtDbgBreakCurrent = NULL;
875 static DWORD afsd_crtDbgBreaks[256];
878 LONG __stdcall afsd_ExceptionFilter(EXCEPTION_POINTERS *ep)
882 BOOL allocRequestBrk = FALSE;
885 afsi_log("UnhandledException : code : 0x%x, address: 0x%x\n",
886 ep->ExceptionRecord->ExceptionCode,
887 ep->ExceptionRecord->ExceptionAddress);
890 if (afsd_crtDbgBreakCurrent &&
891 *afsd_crtDbgBreakCurrent == _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent))
893 allocRequestBrk = TRUE;
894 afsi_log("Breaking on alloc request # %d\n", *afsd_crtDbgBreakCurrent);
898 /* save context if we want to print the stack information */
899 context = *ep->ContextRecord;
901 afsd_printStack(GetCurrentThread(), &context);
903 if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
905 afsi_log("\nEXCEPTION_BREAKPOINT - continue execition ...\n");
910 afsd_crtDbgBreakCurrent++;
911 _CrtSetBreakAlloc(*afsd_crtDbgBreakCurrent);
915 ep->ContextRecord->Eip++;
916 return EXCEPTION_CONTINUE_EXECUTION;
920 return EXCEPTION_CONTINUE_SEARCH;
924 void afsd_SetUnhandledExceptionFilter()
926 SetUnhandledExceptionFilter(afsd_ExceptionFilter);
930 void afsd_DbgBreakAllocInit()
932 memset(afsd_crtDbgBreaks, -1, sizeof(afsd_crtDbgBreaks));
933 afsd_crtDbgBreakCurrent = afsd_crtDbgBreaks;
936 void afsd_DbgBreakAdd(DWORD requestNumber)
939 for (i = 0; i < sizeof(afsd_crtDbgBreaks) - 1; i++)
941 if (afsd_crtDbgBreaks[i] == -1)
946 afsd_crtDbgBreaks[i] = requestNumber;
948 _CrtSetBreakAlloc(afsd_crtDbgBreaks[0]);