VirtualBox

source: vbox/trunk/src/VBox/Additions/common/crOpenGL/load.c@ 53361

最後變更 在這個檔案從53361是 52552,由 vboxsync 提交於 10 年 前

Additions/crOpenGL: Linux: reset signal handlers when our shared object is unloaded.

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Id
檔案大小: 41.0 KB
 
1/* Copyright (c) 2001, Stanford University
2 * All rights reserved
3 *
4 * See the file LICENSE.txt for information on redistributing this software.
5 */
6
7#include "cr_spu.h"
8#include "cr_net.h"
9#include "cr_error.h"
10#include "cr_mem.h"
11#include "cr_string.h"
12#include "cr_net.h"
13#include "cr_environment.h"
14#include "cr_process.h"
15#include "cr_rand.h"
16#include "cr_netserver.h"
17#include "stub.h"
18#include <stdlib.h>
19#include <string.h>
20#include <signal.h>
21#include <iprt/initterm.h>
22#include <iprt/thread.h>
23#include <iprt/err.h>
24#include <iprt/asm.h>
25#ifndef WINDOWS
26# include <sys/types.h>
27# include <unistd.h>
28#endif
29
30#ifdef VBOX_WITH_WDDM
31#include <d3d9types.h>
32#include <D3dumddi.h>
33#include "../../WINNT/Graphics/Video/common/wddm/VBoxMPIf.h"
34#endif
35
36/**
37 * If you change this, see the comments in tilesortspu_context.c
38 */
39#define MAGIC_CONTEXT_BASE 500
40
41#define CONFIG_LOOKUP_FILE ".crconfigs"
42
43#ifdef WINDOWS
44#define PYTHON_EXE "python.exe"
45#else
46#define PYTHON_EXE "python"
47#endif
48
49static bool stub_initialized = 0;
50#ifdef WINDOWS
51static CRmutex stub_init_mutex;
52#define STUB_INIT_LOCK() do { crLockMutex(&stub_init_mutex); } while (0)
53#define STUB_INIT_UNLOCK() do { crUnlockMutex(&stub_init_mutex); } while (0)
54#else
55#define STUB_INIT_LOCK() do { } while (0)
56#define STUB_INIT_UNLOCK() do { } while (0)
57#endif
58
59/* NOTE: 'SPUDispatchTable glim' is declared in NULLfuncs.py now */
60/* NOTE: 'SPUDispatchTable stubThreadsafeDispatch' is declared in tsfuncs.c */
61Stub stub;
62#ifdef CHROMIUM_THREADSAFE
63static bool g_stubIsCurrentContextTSDInited;
64CRtsd g_stubCurrentContextTSD;
65#endif
66
67
68static void stubInitNativeDispatch( void )
69{
70#define MAX_FUNCS 1000
71 SPUNamedFunctionTable gl_funcs[MAX_FUNCS];
72 int numFuncs;
73
74 numFuncs = crLoadOpenGL( &stub.wsInterface, gl_funcs );
75
76 stub.haveNativeOpenGL = (numFuncs > 0);
77
78 /* XXX call this after context binding */
79 numFuncs += crLoadOpenGLExtensions( &stub.wsInterface, gl_funcs + numFuncs );
80
81 CRASSERT(numFuncs < MAX_FUNCS);
82
83 crSPUInitDispatchTable( &stub.nativeDispatch );
84 crSPUInitDispatch( &stub.nativeDispatch, gl_funcs );
85 crSPUInitDispatchNops( &stub.nativeDispatch );
86#undef MAX_FUNCS
87}
88
89
90/** Pointer to the SPU's real glClear and glViewport functions */
91static ClearFunc_t origClear;
92static ViewportFunc_t origViewport;
93static SwapBuffersFunc_t origSwapBuffers;
94static DrawBufferFunc_t origDrawBuffer;
95static ScissorFunc_t origScissor;
96
97static void stubCheckWindowState(WindowInfo *window, GLboolean bFlushOnChange)
98{
99 bool bForceUpdate = false;
100 bool bChanged = false;
101
102#ifdef WINDOWS
103 /* @todo install hook and track for WM_DISPLAYCHANGE */
104 {
105 DEVMODE devMode;
106
107 devMode.dmSize = sizeof(DEVMODE);
108 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &devMode);
109
110 if (devMode.dmPelsWidth!=window->dmPelsWidth || devMode.dmPelsHeight!=window->dmPelsHeight)
111 {
112 crDebug("Resolution changed(%d,%d), forcing window Pos/Size update", devMode.dmPelsWidth, devMode.dmPelsHeight);
113 window->dmPelsWidth = devMode.dmPelsWidth;
114 window->dmPelsHeight = devMode.dmPelsHeight;
115 bForceUpdate = true;
116 }
117 }
118#endif
119
120 bChanged = stubUpdateWindowGeometry(window, bForceUpdate) || bForceUpdate;
121
122#if defined(GLX) || defined (WINDOWS)
123 if (stub.trackWindowVisibleRgn)
124 {
125 bChanged = stubUpdateWindowVisibileRegions(window) || bChanged;
126 }
127#endif
128
129 if (stub.trackWindowVisibility && window->type == CHROMIUM && window->drawable) {
130 const int mapped = stubIsWindowVisible(window);
131 if (mapped != window->mapped) {
132 crDebug("Dispatched: WindowShow(%i, %i)", window->spuWindow, mapped);
133 stub.spu->dispatch_table.WindowShow(window->spuWindow, mapped);
134 window->mapped = mapped;
135 bChanged = true;
136 }
137 }
138
139 if (bFlushOnChange && bChanged)
140 {
141 stub.spu->dispatch_table.Flush();
142 }
143}
144
145static bool stubSystemWindowExist(WindowInfo *pWindow)
146{
147#ifdef WINDOWS
148 if (pWindow->hWnd!=WindowFromDC(pWindow->drawable))
149 {
150 return false;
151 }
152#else
153 Window root;
154 int x, y;
155 unsigned int border, depth, w, h;
156 Display *dpy;
157
158 dpy = stubGetWindowDisplay(pWindow);
159
160 XLOCK(dpy);
161 if (!XGetGeometry(dpy, pWindow->drawable, &root, &x, &y, &w, &h, &border, &depth))
162 {
163 XUNLOCK(dpy);
164 return false;
165 }
166 XUNLOCK(dpy);
167#endif
168
169 return true;
170}
171
172static void stubCheckWindowsCB(unsigned long key, void *data1, void *data2)
173{
174 WindowInfo *pWindow = (WindowInfo *) data1;
175 ContextInfo *pCtx = (ContextInfo *) data2;
176
177 if (pWindow == pCtx->currentDrawable
178 || pWindow->type!=CHROMIUM
179 || pWindow->pOwner!=pCtx)
180 {
181 return;
182 }
183
184 if (!stubSystemWindowExist(pWindow))
185 {
186#ifdef WINDOWS
187 stubDestroyWindow(CR_CTX_CON(pCtx), (GLint)pWindow->hWnd);
188#else
189 stubDestroyWindow(CR_CTX_CON(pCtx), (GLint)pWindow->drawable);
190#endif
191 return;
192 }
193
194 stubCheckWindowState(pWindow, GL_FALSE);
195}
196
197static void stubCheckWindowsState(void)
198{
199 ContextInfo *context = stubGetCurrentContext();
200
201 CRASSERT(stub.trackWindowSize || stub.trackWindowPos);
202
203 if (!context)
204 return;
205
206#if defined(WINDOWS) && defined(VBOX_WITH_WDDM)
207 if (stub.bRunningUnderWDDM)
208 return;
209#endif
210
211 /* Try to keep a consistent locking order. */
212 crHashtableLock(stub.windowTable);
213#if defined(CR_NEWWINTRACK) && !defined(WINDOWS)
214 crLockMutex(&stub.mutex);
215#endif
216
217 stubCheckWindowState(context->currentDrawable, GL_TRUE);
218 crHashtableWalkUnlocked(stub.windowTable, stubCheckWindowsCB, context);
219
220#if defined(CR_NEWWINTRACK) && !defined(WINDOWS)
221 crUnlockMutex(&stub.mutex);
222#endif
223 crHashtableUnlock(stub.windowTable);
224}
225
226
227/**
228 * Override the head SPU's glClear function.
229 * We're basically trapping this function so that we can poll the
230 * application window size at a regular interval.
231 */
232static void SPU_APIENTRY trapClear(GLbitfield mask)
233{
234 stubCheckWindowsState();
235 /* call the original SPU glClear function */
236 origClear(mask);
237}
238
239/**
240 * As above, but for glViewport. Most apps call glViewport before
241 * glClear when a window is resized.
242 */
243static void SPU_APIENTRY trapViewport(GLint x, GLint y, GLsizei w, GLsizei h)
244{
245 stubCheckWindowsState();
246 /* call the original SPU glViewport function */
247 origViewport(x, y, w, h);
248}
249
250static void SPU_APIENTRY trapSwapBuffers(GLint window, GLint flags)
251{
252 stubCheckWindowsState();
253 origSwapBuffers(window, flags);
254}
255
256static void SPU_APIENTRY trapDrawBuffer(GLenum buf)
257{
258 stubCheckWindowsState();
259 origDrawBuffer(buf);
260}
261
262static void SPU_APIENTRY trapScissor(GLint x, GLint y, GLsizei w, GLsizei h)
263{
264 int winX, winY;
265 unsigned int winW, winH;
266 WindowInfo *pWindow;
267 ContextInfo *context = stubGetCurrentContext();
268 pWindow = context->currentDrawable;
269 stubGetWindowGeometry(pWindow, &winX, &winY, &winW, &winH);
270 origScissor(0, 0, winW, winH);
271}
272
273/**
274 * Use the GL function pointers in <spu> to initialize the static glim
275 * dispatch table.
276 */
277static void stubInitSPUDispatch(SPU *spu)
278{
279 crSPUInitDispatchTable( &stub.spuDispatch );
280 crSPUCopyDispatchTable( &stub.spuDispatch, &(spu->dispatch_table) );
281
282 if (stub.trackWindowSize || stub.trackWindowPos || stub.trackWindowVisibleRgn) {
283 /* patch-in special glClear/Viewport function to track window sizing */
284 origClear = stub.spuDispatch.Clear;
285 origViewport = stub.spuDispatch.Viewport;
286 origSwapBuffers = stub.spuDispatch.SwapBuffers;
287 origDrawBuffer = stub.spuDispatch.DrawBuffer;
288 origScissor = stub.spuDispatch.Scissor;
289 stub.spuDispatch.Clear = trapClear;
290 stub.spuDispatch.Viewport = trapViewport;
291
292 /*stub.spuDispatch.SwapBuffers = trapSwapBuffers;
293 stub.spuDispatch.DrawBuffer = trapDrawBuffer;*/
294 }
295
296 crSPUCopyDispatchTable( &glim, &stub.spuDispatch );
297}
298
299// Callback function, used to destroy all created contexts
300static void hsWalkStubDestroyContexts(unsigned long key, void *data1, void *data2)
301{
302 stubDestroyContext(key);
303}
304
305/**
306 * This is called when we exit.
307 * We call all the SPU's cleanup functions.
308 */
309static void stubSPUTearDownLocked(void)
310{
311 crDebug("stubSPUTearDownLocked");
312
313#ifdef WINDOWS
314# ifndef CR_NEWWINTRACK
315 stubUninstallWindowMessageHook();
316# endif
317#endif
318
319#ifdef CR_NEWWINTRACK
320 ASMAtomicWriteBool(&stub.bShutdownSyncThread, true);
321#endif
322
323 //delete all created contexts
324 stubMakeCurrent( NULL, NULL);
325
326 /* the lock order is windowTable->contextTable (see wglMakeCurrent_prox, glXMakeCurrent)
327 * this is why we need to take a windowTable lock since we will later do stub.windowTable access & locking */
328 crHashtableLock(stub.windowTable);
329 crHashtableWalk(stub.contextTable, hsWalkStubDestroyContexts, NULL);
330 crHashtableUnlock(stub.windowTable);
331
332 /* shutdown, now trap any calls to a NULL dispatcher */
333 crSPUCopyDispatchTable(&glim, &stubNULLDispatch);
334
335 crSPUUnloadChain(stub.spu);
336 stub.spu = NULL;
337
338#ifndef Linux
339 crUnloadOpenGL();
340#endif
341
342#ifndef WINDOWS
343 crNetTearDown();
344#endif
345
346#ifdef GLX
347 if (stub.xshmSI.shmid>=0)
348 {
349 shmctl(stub.xshmSI.shmid, IPC_RMID, 0);
350 shmdt(stub.xshmSI.shmaddr);
351 }
352 crFreeHashtable(stub.pGLXPixmapsHash, crFree);
353#endif
354
355 crFreeHashtable(stub.windowTable, crFree);
356 crFreeHashtable(stub.contextTable, NULL);
357
358 crMemset(&stub, 0, sizeof(stub));
359
360}
361
362/**
363 * This is called when we exit.
364 * We call all the SPU's cleanup functions.
365 */
366static void stubSPUTearDown(void)
367{
368 STUB_INIT_LOCK();
369 if (stub_initialized)
370 {
371 stubSPUTearDownLocked();
372 stub_initialized = 0;
373 }
374 STUB_INIT_UNLOCK();
375}
376
377static void stubSPUSafeTearDown(void)
378{
379#ifdef CHROMIUM_THREADSAFE
380 CRmutex *mutex;
381#endif
382
383 if (!stub_initialized) return;
384 stub_initialized = 0;
385
386#ifdef CHROMIUM_THREADSAFE
387 mutex = &stub.mutex;
388 crLockMutex(mutex);
389#endif
390 crDebug("stubSPUSafeTearDown");
391
392#ifdef WINDOWS
393# ifndef CR_NEWWINTRACK
394 stubUninstallWindowMessageHook();
395# endif
396#endif
397
398#if defined(CR_NEWWINTRACK)
399 crUnlockMutex(mutex);
400# if defined(WINDOWS)
401 if (stub.hSyncThread && RTThreadGetState(stub.hSyncThread)!=RTTHREADSTATE_TERMINATED)
402 {
403 HANDLE hNative;
404 DWORD ec=0;
405
406 hNative = OpenThread(SYNCHRONIZE|THREAD_QUERY_INFORMATION|THREAD_TERMINATE,
407 false, RTThreadGetNative(stub.hSyncThread));
408 if (!hNative)
409 {
410 crWarning("Failed to get handle for sync thread(%#x)", GetLastError());
411 }
412 else
413 {
414 crDebug("Got handle %p for thread %#x", hNative, RTThreadGetNative(stub.hSyncThread));
415 }
416
417 ASMAtomicWriteBool(&stub.bShutdownSyncThread, true);
418
419 if (PostThreadMessage(RTThreadGetNative(stub.hSyncThread), WM_QUIT, 0, 0))
420 {
421 RTThreadWait(stub.hSyncThread, 1000, NULL);
422
423 /*Same issue as on linux, RTThreadWait exits before system thread is terminated, which leads
424 * to issues as our dll goes to be unloaded.
425 *@todo
426 *We usually call this function from DllMain which seems to be holding some lock and thus we have to
427 * kill thread via TerminateThread.
428 */
429 if (WaitForSingleObject(hNative, 100)==WAIT_TIMEOUT)
430 {
431 crDebug("Wait failed, terminating");
432 if (!TerminateThread(hNative, 1))
433 {
434 crDebug("TerminateThread failed");
435 }
436 }
437 if (GetExitCodeThread(hNative, &ec))
438 {
439 crDebug("Thread %p exited with ec=%i", hNative, ec);
440 }
441 else
442 {
443 crDebug("GetExitCodeThread failed(%#x)", GetLastError());
444 }
445 }
446 else
447 {
448 crDebug("Sync thread killed before DLL_PROCESS_DETACH");
449 }
450
451 if (hNative)
452 {
453 CloseHandle(hNative);
454 }
455 }
456#else
457 if (stub.hSyncThread!=NIL_RTTHREAD)
458 {
459 ASMAtomicWriteBool(&stub.bShutdownSyncThread, true);
460 {
461 int rc = RTThreadWait(stub.hSyncThread, RT_INDEFINITE_WAIT, NULL);
462 if (RT_FAILURE(rc))
463 {
464 WARN(("RTThreadWait_join failed %i", rc));
465 }
466 }
467 }
468#endif
469 crLockMutex(mutex);
470#endif
471
472#ifndef WINDOWS
473 crNetTearDown();
474#endif
475
476#ifdef CHROMIUM_THREADSAFE
477 crUnlockMutex(mutex);
478 crFreeMutex(mutex);
479#endif
480 crMemset(&stub, 0, sizeof(stub));
481}
482
483
484static void stubExitHandler(void)
485{
486 stubSPUSafeTearDown();
487 signal(SIGTERM, SIG_DFL);
488 signal(SIGINT, SIG_DFL);
489}
490
491/**
492 * Called when we receive a SIGTERM signal.
493 */
494static void stubSignalHandler(int signo)
495{
496 stubSPUSafeTearDown();
497 exit(0); /* this causes stubExitHandler() to be called */
498}
499
500#ifndef RT_OS_WINDOWS
501# ifdef CHROMIUM_THREADSAFE
502static DECLCALLBACK(void) stubThreadTlsDtor(void *pvValue)
503{
504 ContextInfo *pCtx = (ContextInfo*)pvValue;
505 VBoxTlsRefRelease(pCtx);
506}
507# endif
508#endif
509
510
511/**
512 * Init variables in the stub structure, install signal handler.
513 */
514static void stubInitVars(void)
515{
516 WindowInfo *defaultWin;
517
518#ifdef CHROMIUM_THREADSAFE
519 crInitMutex(&stub.mutex);
520#endif
521
522 /* At the very least we want CR_RGB_BIT. */
523 stub.haveNativeOpenGL = GL_FALSE;
524 stub.spu = NULL;
525 stub.appDrawCursor = 0;
526 stub.minChromiumWindowWidth = 0;
527 stub.minChromiumWindowHeight = 0;
528 stub.maxChromiumWindowWidth = 0;
529 stub.maxChromiumWindowHeight = 0;
530 stub.matchChromiumWindowCount = 0;
531 stub.matchChromiumWindowID = NULL;
532 stub.matchWindowTitle = NULL;
533 stub.ignoreFreeglutMenus = 0;
534 stub.threadSafe = GL_FALSE;
535 stub.trackWindowSize = 0;
536 stub.trackWindowPos = 0;
537 stub.trackWindowVisibility = 0;
538 stub.trackWindowVisibleRgn = 0;
539 stub.mothershipPID = 0;
540 stub.spu_dir = NULL;
541
542 stub.freeContextNumber = MAGIC_CONTEXT_BASE;
543 stub.contextTable = crAllocHashtable();
544#ifndef RT_OS_WINDOWS
545# ifdef CHROMIUM_THREADSAFE
546 if (!g_stubIsCurrentContextTSDInited)
547 {
548 crInitTSDF(&g_stubCurrentContextTSD, stubThreadTlsDtor);
549 g_stubIsCurrentContextTSDInited = true;
550 }
551# endif
552#endif
553 stubSetCurrentContext(NULL);
554
555 stub.windowTable = crAllocHashtable();
556
557#ifdef CR_NEWWINTRACK
558 stub.bShutdownSyncThread = false;
559 stub.hSyncThread = NIL_RTTHREAD;
560#endif
561
562 defaultWin = (WindowInfo *) crCalloc(sizeof(WindowInfo));
563 defaultWin->type = CHROMIUM;
564 defaultWin->spuWindow = 0; /* window 0 always exists */
565#ifdef WINDOWS
566 defaultWin->hVisibleRegion = INVALID_HANDLE_VALUE;
567#elif defined(GLX)
568 defaultWin->pVisibleRegions = NULL;
569 defaultWin->cVisibleRegions = 0;
570#endif
571 crHashtableAdd(stub.windowTable, 0, defaultWin);
572
573#if 1
574 atexit(stubExitHandler);
575 signal(SIGTERM, stubSignalHandler);
576 signal(SIGINT, stubSignalHandler);
577#ifndef WINDOWS
578 signal(SIGPIPE, SIG_IGN); /* the networking code should catch this */
579#endif
580#else
581 (void) stubExitHandler;
582 (void) stubSignalHandler;
583#endif
584}
585
586
587/**
588 * Return a free port number for the mothership to use, or -1 if we
589 * can't find one.
590 */
591static int
592GenerateMothershipPort(void)
593{
594 const int MAX_PORT = 10100;
595 unsigned short port;
596
597 /* generate initial port number randomly */
598 crRandAutoSeed();
599 port = (unsigned short) crRandInt(10001, MAX_PORT);
600
601#ifdef WINDOWS
602 /* XXX should implement a free port check here */
603 return port;
604#else
605 /*
606 * See if this port number really is free, try another if needed.
607 */
608 {
609 struct sockaddr_in servaddr;
610 int so_reuseaddr = 1;
611 int sock, k;
612
613 /* create socket */
614 sock = socket(AF_INET, SOCK_STREAM, 0);
615 CRASSERT(sock > 2);
616
617 /* deallocate socket/port when we exit */
618 k = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
619 (char *) &so_reuseaddr, sizeof(so_reuseaddr));
620 CRASSERT(k == 0);
621
622 /* initialize the servaddr struct */
623 crMemset(&servaddr, 0, sizeof(servaddr) );
624 servaddr.sin_family = AF_INET;
625 servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
626
627 while (port < MAX_PORT) {
628 /* Bind to the given port number, return -1 if we fail */
629 servaddr.sin_port = htons((unsigned short) port);
630 k = bind(sock, (struct sockaddr *) &servaddr, sizeof(servaddr));
631 if (k) {
632 /* failed to create port. try next one. */
633 port++;
634 }
635 else {
636 /* free the socket/port now so mothership can make it */
637 close(sock);
638 return port;
639 }
640 }
641 }
642#endif /* WINDOWS */
643 return -1;
644}
645
646
647/**
648 * Try to determine which mothership configuration to use for this program.
649 */
650static char **
651LookupMothershipConfig(const char *procName)
652{
653 const int procNameLen = crStrlen(procName);
654 FILE *f;
655 const char *home;
656 char configPath[1000];
657
658 /* first, check if the CR_CONFIG env var is set */
659 {
660 const char *conf = crGetenv("CR_CONFIG");
661 if (conf && crStrlen(conf) > 0)
662 return crStrSplit(conf, " ");
663 }
664
665 /* second, look up config name from config file */
666 home = crGetenv("HOME");
667 if (home)
668 sprintf(configPath, "%s/%s", home, CONFIG_LOOKUP_FILE);
669 else
670 crStrcpy(configPath, CONFIG_LOOKUP_FILE); /* from current dir */
671 /* Check if the CR_CONFIG_PATH env var is set. */
672 {
673 const char *conf = crGetenv("CR_CONFIG_PATH");
674 if (conf)
675 crStrcpy(configPath, conf); /* from env var */
676 }
677
678 f = fopen(configPath, "r");
679 if (!f) {
680 return NULL;
681 }
682
683 while (!feof(f)) {
684 char line[1000];
685 char **args;
686 fgets(line, 999, f);
687 line[crStrlen(line) - 1] = 0; /* remove trailing newline */
688 if (crStrncmp(line, procName, procNameLen) == 0 &&
689 (line[procNameLen] == ' ' || line[procNameLen] == '\t'))
690 {
691 crWarning("Using Chromium configuration for %s from %s",
692 procName, configPath);
693 args = crStrSplit(line + procNameLen + 1, " ");
694 return args;
695 }
696 }
697 fclose(f);
698 return NULL;
699}
700
701
702static int Mothership_Awake = 0;
703
704
705/**
706 * Signal handler to determine when mothership is ready.
707 */
708static void
709MothershipPhoneHome(int signo)
710{
711 crDebug("Got signal %d: mothership is awake!", signo);
712 Mothership_Awake = 1;
713}
714
715void stubSetDefaultConfigurationOptions(void)
716{
717 unsigned char key[16]= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
718
719 stub.appDrawCursor = 0;
720 stub.minChromiumWindowWidth = 0;
721 stub.minChromiumWindowHeight = 0;
722 stub.maxChromiumWindowWidth = 0;
723 stub.maxChromiumWindowHeight = 0;
724 stub.matchChromiumWindowID = NULL;
725 stub.numIgnoreWindowID = 0;
726 stub.matchWindowTitle = NULL;
727 stub.ignoreFreeglutMenus = 0;
728 stub.trackWindowSize = 1;
729 stub.trackWindowPos = 1;
730 stub.trackWindowVisibility = 1;
731 stub.trackWindowVisibleRgn = 1;
732 stub.matchChromiumWindowCount = 0;
733 stub.spu_dir = NULL;
734 crNetSetRank(0);
735 crNetSetContextRange(32, 35);
736 crNetSetNodeRange("iam0", "iamvis20");
737 crNetSetKey(key,sizeof(key));
738 stub.force_pbuffers = 0;
739
740#ifdef WINDOWS
741# ifdef VBOX_WITH_WDDM
742 stub.bRunningUnderWDDM = false;
743# endif
744#endif
745}
746
747#ifdef CR_NEWWINTRACK
748# ifdef VBOX_WITH_WDDM
749static stubDispatchVisibleRegions(WindowInfo *pWindow)
750{
751 DWORD dwCount;
752 LPRGNDATA lpRgnData;
753
754 dwCount = GetRegionData(pWindow->hVisibleRegion, 0, NULL);
755 lpRgnData = crAlloc(dwCount);
756
757 if (lpRgnData)
758 {
759 GetRegionData(pWindow->hVisibleRegion, dwCount, lpRgnData);
760 crDebug("Dispatched WindowVisibleRegion (%i, cRects=%i)", pWindow->spuWindow, lpRgnData->rdh.nCount);
761 stub.spuDispatch.WindowVisibleRegion(pWindow->spuWindow, lpRgnData->rdh.nCount, (GLint*) lpRgnData->Buffer);
762 crFree(lpRgnData);
763 }
764 else crWarning("GetRegionData failed, VisibleRegions update failed");
765}
766
767static HRGN stubMakeRegionFromRects(PVBOXVIDEOCM_CMD_RECTS pRegions, uint32_t start)
768{
769 HRGN hRgn, hTmpRgn;
770 uint32_t i;
771
772 if (pRegions->RectsInfo.cRects<=start)
773 {
774 return INVALID_HANDLE_VALUE;
775 }
776
777 hRgn = CreateRectRgn(0, 0, 0, 0);
778 for (i=start; i<pRegions->RectsInfo.cRects; ++i)
779 {
780 hTmpRgn = CreateRectRgnIndirect(&pRegions->RectsInfo.aRects[i]);
781 CombineRgn(hRgn, hRgn, hTmpRgn, RGN_OR);
782 DeleteObject(hTmpRgn);
783 }
784 return hRgn;
785}
786
787# endif /* VBOX_WITH_WDDM */
788
789static void stubSyncTrCheckWindowsCB(unsigned long key, void *data1, void *data2)
790{
791 WindowInfo *pWindow = (WindowInfo *) data1;
792 (void) data2;
793
794 if (pWindow->type!=CHROMIUM || pWindow->spuWindow==0)
795 {
796 return;
797 }
798
799 stub.spu->dispatch_table.VBoxPackSetInjectID(pWindow->u32ClientID);
800
801 if (!stubSystemWindowExist(pWindow))
802 {
803#ifdef WINDOWS
804 stubDestroyWindow(0, (GLint)pWindow->hWnd);
805#else
806 stubDestroyWindow(0, (GLint)pWindow->drawable);
807#endif
808 /*No need to flush here as crWindowDestroy does it*/
809 return;
810 }
811
812#if defined(WINDOWS) && defined(VBOX_WITH_WDDM)
813 if (stub.bRunningUnderWDDM)
814 return;
815#endif
816 stubCheckWindowState(pWindow, GL_TRUE);
817}
818
819static DECLCALLBACK(int) stubSyncThreadProc(RTTHREAD ThreadSelf, void *pvUser)
820{
821#ifdef WINDOWS
822 MSG msg;
823# ifdef VBOX_WITH_WDDM
824 HMODULE hVBoxD3D = NULL;
825 GLint spuConnection = 0;
826# endif
827#endif
828
829 (void) pvUser;
830
831 crDebug("Sync thread started");
832#ifdef WINDOWS
833 PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
834# ifdef VBOX_WITH_WDDM
835 hVBoxD3D = NULL;
836 if (!GetModuleHandleEx(0, VBOX_MODNAME_DISPD3D, &hVBoxD3D))
837 {
838 crDebug("GetModuleHandleEx failed err %d", GetLastError());
839 hVBoxD3D = NULL;
840 }
841
842 if (hVBoxD3D)
843 {
844 crDebug("running with " VBOX_MODNAME_DISPD3D);
845 stub.trackWindowVisibleRgn = 0;
846 stub.bRunningUnderWDDM = true;
847 }
848# endif /* VBOX_WITH_WDDM */
849#endif /* WINDOWS */
850
851 crLockMutex(&stub.mutex);
852#if defined(WINDOWS) && defined(VBOX_WITH_WDDM)
853 spuConnection =
854#endif
855 stub.spu->dispatch_table.VBoxPackSetInjectThread(NULL);
856#if defined(WINDOWS) && defined(VBOX_WITH_WDDM)
857 if (stub.bRunningUnderWDDM && !spuConnection)
858 {
859 crError("VBoxPackSetInjectThread failed!");
860 }
861#endif
862 crUnlockMutex(&stub.mutex);
863
864 RTThreadUserSignal(ThreadSelf);
865
866 while(!stub.bShutdownSyncThread)
867 {
868#ifdef WINDOWS
869 if (!PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
870 {
871# ifdef VBOX_WITH_WDDM
872 if (stub.bRunningUnderWDDM)
873 {
874
875 }
876 else
877# endif
878 {
879 crHashtableWalk(stub.windowTable, stubSyncTrCheckWindowsCB, NULL);
880 RTThreadSleep(50);
881 }
882 }
883 else
884 {
885 if (WM_QUIT==msg.message)
886 {
887 crDebug("Sync thread got WM_QUIT");
888 break;
889 }
890 else
891 {
892 TranslateMessage(&msg);
893 DispatchMessage(&msg);
894 }
895 }
896#else
897 /* Try to keep a consistent locking order. */
898 crHashtableLock(stub.windowTable);
899 crLockMutex(&stub.mutex);
900 crHashtableWalkUnlocked(stub.windowTable, stubSyncTrCheckWindowsCB, NULL);
901 crUnlockMutex(&stub.mutex);
902 crHashtableUnlock(stub.windowTable);
903 RTThreadSleep(50);
904#endif
905 }
906
907#ifdef VBOX_WITH_WDDM
908 if (spuConnection)
909 {
910 stub.spu->dispatch_table.VBoxConDestroy(spuConnection);
911 }
912 if (hVBoxD3D)
913 {
914 FreeLibrary(hVBoxD3D);
915 }
916#endif
917 crDebug("Sync thread stopped");
918 return 0;
919}
920#endif /* CR_NEWWINTRACK */
921
922/**
923 * Do one-time initializations for the faker.
924 * Returns TRUE on success, FALSE otherwise.
925 */
926static bool
927stubInitLocked(void)
928{
929 /* Here is where we contact the mothership to find out what we're supposed
930 * to be doing. Networking code in a DLL initializer. I sure hope this
931 * works :)
932 *
933 * HOW can I pass the mothership address to this if I already know it?
934 */
935
936 CRConnection *conn = NULL;
937 char response[1024];
938 char **spuchain;
939 int num_spus;
940 int *spu_ids;
941 char **spu_names;
942 const char *app_id;
943 int i;
944 int disable_sync = 0;
945#if defined(WINDOWS) && defined(VBOX_WITH_WDDM)
946 HMODULE hVBoxD3D = NULL;
947#endif
948
949 stubInitVars();
950
951 crGetProcName(response, 1024);
952 crDebug("Stub launched for %s", response);
953
954#if defined(CR_NEWWINTRACK) && !defined(WINDOWS)
955 /*@todo when vm boots with compiz turned on, new code causes hang in xcb_wait_for_reply in the sync thread
956 * as at the start compiz runs our code under XGrabServer.
957 */
958 if (!crStrcmp(response, "compiz") || !crStrcmp(response, "compiz_real") || !crStrcmp(response, "compiz.real")
959 || !crStrcmp(response, "compiz-bin"))
960 {
961 disable_sync = 1;
962 }
963#endif
964
965 /* @todo check if it'd be of any use on other than guests, no use for windows */
966 app_id = crGetenv( "CR_APPLICATION_ID_NUMBER" );
967
968 crNetInit( NULL, NULL );
969
970#ifndef WINDOWS
971 {
972 CRNetServer ns;
973
974 ns.name = "vboxhgcm://host:0";
975 ns.buffer_size = 1024;
976 crNetServerConnect(&ns
977#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
978 , NULL
979#endif
980 );
981 if (!ns.conn)
982 {
983 crWarning("Failed to connect to host. Make sure 3D acceleration is enabled for this VM.");
984 return false;
985 }
986 else
987 {
988 crNetFreeConnection(ns.conn);
989 }
990 }
991#endif
992
993 strcpy(response, "2 0 feedback 1 pack");
994 spuchain = crStrSplit( response, " " );
995 num_spus = crStrToInt( spuchain[0] );
996 spu_ids = (int *) crAlloc( num_spus * sizeof( *spu_ids ) );
997 spu_names = (char **) crAlloc( num_spus * sizeof( *spu_names ) );
998 for (i = 0 ; i < num_spus ; i++)
999 {
1000 spu_ids[i] = crStrToInt( spuchain[2*i+1] );
1001 spu_names[i] = crStrdup( spuchain[2*i+2] );
1002 crDebug( "SPU %d/%d: (%d) \"%s\"", i+1, num_spus, spu_ids[i], spu_names[i] );
1003 }
1004
1005 stubSetDefaultConfigurationOptions();
1006
1007#if defined(WINDOWS) && defined(VBOX_WITH_WDDM)
1008 hVBoxD3D = NULL;
1009 if (!GetModuleHandleEx(0, VBOX_MODNAME_DISPD3D, &hVBoxD3D))
1010 {
1011 crDebug("GetModuleHandleEx failed err %d", GetLastError());
1012 hVBoxD3D = NULL;
1013 }
1014
1015 if (hVBoxD3D)
1016 {
1017 disable_sync = 1;
1018 crDebug("running with %s", VBOX_MODNAME_DISPD3D);
1019 stub.trackWindowVisibleRgn = 0;
1020 /* @todo: should we enable that? */
1021 stub.trackWindowSize = 0;
1022 stub.trackWindowPos = 0;
1023 stub.trackWindowVisibility = 0;
1024 stub.bRunningUnderWDDM = true;
1025 }
1026#endif
1027
1028 stub.spu = crSPULoadChain( num_spus, spu_ids, spu_names, stub.spu_dir, NULL );
1029
1030 crFree( spuchain );
1031 crFree( spu_ids );
1032 for (i = 0; i < num_spus; ++i)
1033 crFree(spu_names[i]);
1034 crFree( spu_names );
1035
1036 // spu chain load failed somewhere
1037 if (!stub.spu) {
1038 return false;
1039 }
1040
1041 crSPUInitDispatchTable( &glim );
1042
1043 /* This is unlikely to change -- We still want to initialize our dispatch
1044 * table with the functions of the first SPU in the chain. */
1045 stubInitSPUDispatch( stub.spu );
1046
1047 /* we need to plug one special stub function into the dispatch table */
1048 glim.GetChromiumParametervCR = stub_GetChromiumParametervCR;
1049
1050#if !defined(VBOX_NO_NATIVEGL)
1051 /* Load pointers to native OpenGL functions into stub.nativeDispatch */
1052 stubInitNativeDispatch();
1053#endif
1054
1055/*crDebug("stub init");
1056raise(SIGINT);*/
1057
1058#ifdef WINDOWS
1059# ifndef CR_NEWWINTRACK
1060 stubInstallWindowMessageHook();
1061# endif
1062#endif
1063
1064#ifdef CR_NEWWINTRACK
1065 {
1066 int rc;
1067
1068 RTR3InitDll(RTR3INIT_FLAGS_UNOBTRUSIVE);
1069
1070 if (!disable_sync)
1071 {
1072 crDebug("Starting sync thread");
1073
1074 rc = RTThreadCreate(&stub.hSyncThread, stubSyncThreadProc, NULL, 0, RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "Sync");
1075 if (RT_FAILURE(rc))
1076 {
1077 crError("Failed to start sync thread! (%x)", rc);
1078 }
1079 RTThreadUserWait(stub.hSyncThread, 60 * 1000);
1080 RTThreadUserReset(stub.hSyncThread);
1081
1082 crDebug("Going on");
1083 }
1084 }
1085#endif
1086
1087#ifdef GLX
1088 stub.xshmSI.shmid = -1;
1089 stub.bShmInitFailed = GL_FALSE;
1090 stub.pGLXPixmapsHash = crAllocHashtable();
1091
1092 stub.bXExtensionsChecked = GL_FALSE;
1093 stub.bHaveXComposite = GL_FALSE;
1094 stub.bHaveXFixes = GL_FALSE;
1095#endif
1096
1097 return true;
1098}
1099
1100/**
1101 * Do one-time initializations for the faker.
1102 * Returns TRUE on success, FALSE otherwise.
1103 */
1104bool
1105stubInit(void)
1106{
1107 bool bRc = true;
1108 /* we need to serialize the initialization, otherwise racing is possible
1109 * for XPDM-based d3d when a d3d switcher is testing the gl lib in two or more threads
1110 * NOTE: the STUB_INIT_LOCK/UNLOCK is a NOP for non-win currently */
1111 STUB_INIT_LOCK();
1112 if (!stub_initialized)
1113 bRc = stub_initialized = stubInitLocked();
1114 STUB_INIT_UNLOCK();
1115 return bRc;
1116}
1117
1118/* Sigh -- we can't do initialization at load time, since Windows forbids
1119 * the loading of other libraries from DLLMain. */
1120
1121#ifdef LINUX
1122/* GCC crap
1123 *void (*stub_init_ptr)(void) __attribute__((section(".ctors"))) = __stubInit; */
1124#endif
1125
1126#ifdef WINDOWS
1127#define WIN32_LEAN_AND_MEAN
1128#include <windows.h>
1129
1130#if 1//def DEBUG_misha
1131 /* debugging: this is to be able to catch first-chance notifications
1132 * for exceptions other than EXCEPTION_BREAKPOINT in kernel debugger */
1133# define VDBG_VEHANDLER
1134#endif
1135
1136#ifdef VDBG_VEHANDLER
1137# include <dbghelp.h>
1138# include <cr_string.h>
1139static PVOID g_VBoxVehHandler = NULL;
1140static DWORD g_VBoxVehEnable = 0;
1141
1142/* generate a crash dump on exception */
1143#define VBOXVEH_F_DUMP 0x00000001
1144/* generate a debugger breakpoint exception */
1145#define VBOXVEH_F_BREAK 0x00000002
1146/* exit on exception */
1147#define VBOXVEH_F_EXIT 0x00000004
1148
1149static DWORD g_VBoxVehFlags = 0;
1150
1151typedef BOOL WINAPI FNVBOXDBG_MINIDUMPWRITEDUMP(HANDLE hProcess,
1152 DWORD ProcessId,
1153 HANDLE hFile,
1154 MINIDUMP_TYPE DumpType,
1155 PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
1156 PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
1157 PMINIDUMP_CALLBACK_INFORMATION CallbackParam);
1158typedef FNVBOXDBG_MINIDUMPWRITEDUMP *PFNVBOXDBG_MINIDUMPWRITEDUMP;
1159
1160static HMODULE g_hVBoxMdDbgHelp = NULL;
1161static PFNVBOXDBG_MINIDUMPWRITEDUMP g_pfnVBoxMdMiniDumpWriteDump = NULL;
1162static size_t g_cVBoxMdFilePrefixLen = 0;
1163static WCHAR g_aszwVBoxMdFilePrefix[MAX_PATH];
1164static WCHAR g_aszwVBoxMdDumpCount = 0;
1165static MINIDUMP_TYPE g_enmVBoxMdDumpType = MiniDumpNormal
1166 | MiniDumpWithDataSegs
1167 | MiniDumpWithFullMemory
1168 | MiniDumpWithHandleData
1169//// | MiniDumpFilterMemory
1170//// | MiniDumpScanMemory
1171// | MiniDumpWithUnloadedModules
1172//// | MiniDumpWithIndirectlyReferencedMemory
1173//// | MiniDumpFilterModulePaths
1174// | MiniDumpWithProcessThreadData
1175// | MiniDumpWithPrivateReadWriteMemory
1176//// | MiniDumpWithoutOptionalData
1177// | MiniDumpWithFullMemoryInfo
1178// | MiniDumpWithThreadInfo
1179// | MiniDumpWithCodeSegs
1180// | MiniDumpWithFullAuxiliaryState
1181// | MiniDumpWithPrivateWriteCopyMemory
1182// | MiniDumpIgnoreInaccessibleMemory
1183// | MiniDumpWithTokenInformation
1184//// | MiniDumpWithModuleHeaders
1185//// | MiniDumpFilterTriage
1186 ;
1187
1188
1189
1190#define VBOXMD_DUMP_DIR_DEFAULT "C:\\dumps"
1191#define VBOXMD_DUMP_NAME_PREFIX_W L"VBoxDmp_"
1192
1193static HMODULE loadSystemDll(const char *pszName)
1194{
1195 char szPath[MAX_PATH];
1196 UINT cchPath = GetSystemDirectoryA(szPath, sizeof(szPath));
1197 size_t cbName = strlen(pszName) + 1;
1198 if (cchPath + 1 + cbName > sizeof(szPath))
1199 {
1200 SetLastError(ERROR_FILENAME_EXCED_RANGE);
1201 return NULL;
1202 }
1203 szPath[cchPath] = '\\';
1204 memcpy(&szPath[cchPath + 1], pszName, cbName);
1205 return LoadLibraryA(szPath);
1206}
1207
1208static DWORD vboxMdMinidumpCreate(struct _EXCEPTION_POINTERS *pExceptionInfo)
1209{
1210 WCHAR aszwMdFileName[MAX_PATH];
1211 HANDLE hProcess = GetCurrentProcess();
1212 DWORD ProcessId = GetCurrentProcessId();
1213 MINIDUMP_EXCEPTION_INFORMATION ExceptionInfo;
1214 HANDLE hFile;
1215 DWORD winErr = ERROR_SUCCESS;
1216
1217 if (!g_pfnVBoxMdMiniDumpWriteDump)
1218 {
1219 if (!g_hVBoxMdDbgHelp)
1220 {
1221 g_hVBoxMdDbgHelp = loadSystemDll("DbgHelp.dll");
1222 if (!g_hVBoxMdDbgHelp)
1223 return GetLastError();
1224 }
1225
1226 g_pfnVBoxMdMiniDumpWriteDump = (PFNVBOXDBG_MINIDUMPWRITEDUMP)GetProcAddress(g_hVBoxMdDbgHelp, "MiniDumpWriteDump");
1227 if (!g_pfnVBoxMdMiniDumpWriteDump)
1228 return GetLastError();
1229 }
1230
1231 ++g_aszwVBoxMdDumpCount;
1232
1233 memcpy(aszwMdFileName, g_aszwVBoxMdFilePrefix, g_cVBoxMdFilePrefixLen * sizeof (g_aszwVBoxMdFilePrefix[0]));
1234 swprintf(aszwMdFileName + g_cVBoxMdFilePrefixLen, RT_ELEMENTS(aszwMdFileName) - g_cVBoxMdFilePrefixLen, L"%d_%d.dmp", ProcessId, g_aszwVBoxMdDumpCount);
1235
1236 hFile = CreateFileW(aszwMdFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1237 if (hFile == INVALID_HANDLE_VALUE)
1238 return GetLastError();
1239
1240 ExceptionInfo.ThreadId = GetCurrentThreadId();
1241 ExceptionInfo.ExceptionPointers = pExceptionInfo;
1242 ExceptionInfo.ClientPointers = FALSE;
1243
1244 if (!g_pfnVBoxMdMiniDumpWriteDump(hProcess, ProcessId, hFile, g_enmVBoxMdDumpType, &ExceptionInfo, NULL, NULL))
1245 winErr = GetLastError();
1246
1247 CloseHandle(hFile);
1248 return winErr;
1249}
1250
1251LONG WINAPI vboxVDbgVectoredHandler(struct _EXCEPTION_POINTERS *pExceptionInfo)
1252{
1253 PEXCEPTION_RECORD pExceptionRecord = pExceptionInfo->ExceptionRecord;
1254 PCONTEXT pContextRecord = pExceptionInfo->ContextRecord;
1255 switch (pExceptionRecord->ExceptionCode)
1256 {
1257 case EXCEPTION_BREAKPOINT:
1258 case EXCEPTION_ACCESS_VIOLATION:
1259 case EXCEPTION_STACK_OVERFLOW:
1260 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1261 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
1262 case EXCEPTION_FLT_INVALID_OPERATION:
1263 case EXCEPTION_INT_DIVIDE_BY_ZERO:
1264 case EXCEPTION_ILLEGAL_INSTRUCTION:
1265 if (g_VBoxVehFlags & VBOXVEH_F_BREAK)
1266 {
1267 BOOL fBreak = TRUE;
1268#ifndef DEBUG_misha
1269 if (pExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
1270 {
1271 HANDLE hProcess = GetCurrentProcess();
1272 BOOL fDebuggerPresent = FALSE;
1273 /* we do not want to generate breakpoint exceptions recursively, so do it only when running under debugger */
1274 if (CheckRemoteDebuggerPresent(hProcess, &fDebuggerPresent))
1275 fBreak = !!fDebuggerPresent;
1276 else
1277 fBreak = FALSE; /* <- the function has failed, don't break for sanity */
1278 }
1279#endif
1280
1281 if (fBreak)
1282 {
1283 RT_BREAKPOINT();
1284 }
1285 }
1286
1287 if (g_VBoxVehFlags & VBOXVEH_F_DUMP)
1288 vboxMdMinidumpCreate(pExceptionInfo);
1289
1290 if (g_VBoxVehFlags & VBOXVEH_F_EXIT)
1291 exit(1);
1292 break;
1293 default:
1294 break;
1295 }
1296 return EXCEPTION_CONTINUE_SEARCH;
1297}
1298
1299void vboxVDbgVEHandlerRegister()
1300{
1301 CRASSERT(!g_VBoxVehHandler);
1302 g_VBoxVehHandler = AddVectoredExceptionHandler(1,vboxVDbgVectoredHandler);
1303 CRASSERT(g_VBoxVehHandler);
1304}
1305
1306void vboxVDbgVEHandlerUnregister()
1307{
1308 ULONG uResult;
1309 if (g_VBoxVehHandler)
1310 {
1311 uResult = RemoveVectoredExceptionHandler(g_VBoxVehHandler);
1312 CRASSERT(uResult);
1313 g_VBoxVehHandler = NULL;
1314 }
1315}
1316#endif
1317
1318/* Windows crap */
1319BOOL WINAPI DllMain(HINSTANCE hDLLInst, DWORD fdwReason, LPVOID lpvReserved)
1320{
1321 (void) lpvReserved;
1322
1323 switch (fdwReason)
1324 {
1325 case DLL_PROCESS_ATTACH:
1326 {
1327 CRNetServer ns;
1328 const char * env;
1329#if defined(DEBUG_misha)
1330 HMODULE hCrUtil;
1331 char aName[MAX_PATH];
1332
1333 GetModuleFileNameA(hDLLInst, aName, RT_ELEMENTS(aName));
1334 crDbgCmdSymLoadPrint(aName, hDLLInst);
1335
1336 hCrUtil = GetModuleHandleA("VBoxOGLcrutil.dll");
1337 Assert(hCrUtil);
1338 crDbgCmdSymLoadPrint("VBoxOGLcrutil.dll", hCrUtil);
1339#endif
1340#ifdef CHROMIUM_THREADSAFE
1341 crInitTSD(&g_stubCurrentContextTSD);
1342#endif
1343
1344 crInitMutex(&stub_init_mutex);
1345
1346#ifdef VDBG_VEHANDLER
1347 env = crGetenv("CR_DBG_VEH_ENABLE");
1348 g_VBoxVehEnable = crStrParseI32(env,
1349# ifdef DEBUG_misha
1350 1
1351# else
1352 0
1353# endif
1354 );
1355
1356 if (g_VBoxVehEnable)
1357 {
1358 char procName[1024];
1359 size_t cProcName;
1360 size_t cChars;
1361
1362 env = crGetenv("CR_DBG_VEH_FLAGS");
1363 g_VBoxVehFlags = crStrParseI32(env,
1364 0
1365# ifdef DEBUG_misha
1366 | VBOXVEH_F_BREAK
1367# else
1368 | VBOXVEH_F_DUMP
1369# endif
1370 );
1371
1372 env = crGetenv("CR_DBG_VEH_DUMP_DIR");
1373 if (!env)
1374 env = VBOXMD_DUMP_DIR_DEFAULT;
1375
1376 g_cVBoxMdFilePrefixLen = strlen(env);
1377
1378 if (RT_ELEMENTS(g_aszwVBoxMdFilePrefix) <= g_cVBoxMdFilePrefixLen + 26 + (sizeof (VBOXMD_DUMP_NAME_PREFIX_W) - sizeof (WCHAR)) / sizeof (WCHAR))
1379 {
1380 g_cVBoxMdFilePrefixLen = 0;
1381 env = "";
1382 }
1383
1384 mbstowcs_s(&cChars, g_aszwVBoxMdFilePrefix, g_cVBoxMdFilePrefixLen + 1, env, _TRUNCATE);
1385
1386 Assert(cChars == g_cVBoxMdFilePrefixLen + 1);
1387
1388 g_cVBoxMdFilePrefixLen = cChars - 1;
1389
1390 if (g_cVBoxMdFilePrefixLen && g_aszwVBoxMdFilePrefix[g_cVBoxMdFilePrefixLen - 1] != L'\\')
1391 g_aszwVBoxMdFilePrefix[g_cVBoxMdFilePrefixLen++] = L'\\';
1392
1393 memcpy(g_aszwVBoxMdFilePrefix + g_cVBoxMdFilePrefixLen, VBOXMD_DUMP_NAME_PREFIX_W, sizeof (VBOXMD_DUMP_NAME_PREFIX_W) - sizeof (WCHAR));
1394 g_cVBoxMdFilePrefixLen += (sizeof (VBOXMD_DUMP_NAME_PREFIX_W) - sizeof (WCHAR)) / sizeof (WCHAR);
1395
1396 crGetProcName(procName, RT_ELEMENTS(procName));
1397 cProcName = strlen(procName);
1398
1399 if (RT_ELEMENTS(g_aszwVBoxMdFilePrefix) > g_cVBoxMdFilePrefixLen + cProcName + 1 + 26)
1400 {
1401 mbstowcs_s(&cChars, g_aszwVBoxMdFilePrefix + g_cVBoxMdFilePrefixLen, cProcName + 1, procName, _TRUNCATE);
1402 Assert(cChars == cProcName + 1);
1403 g_cVBoxMdFilePrefixLen += cChars - 1;
1404 g_aszwVBoxMdFilePrefix[g_cVBoxMdFilePrefixLen++] = L'_';
1405 }
1406
1407 /* sanity */
1408 g_aszwVBoxMdFilePrefix[g_cVBoxMdFilePrefixLen] = L'\0';
1409
1410 env = crGetenv("CR_DBG_VEH_DUMP_TYPE");
1411
1412 g_enmVBoxMdDumpType = crStrParseI32(env,
1413 MiniDumpNormal
1414 | MiniDumpWithDataSegs
1415 | MiniDumpWithFullMemory
1416 | MiniDumpWithHandleData
1417 //// | MiniDumpFilterMemory
1418 //// | MiniDumpScanMemory
1419 // | MiniDumpWithUnloadedModules
1420 //// | MiniDumpWithIndirectlyReferencedMemory
1421 //// | MiniDumpFilterModulePaths
1422 // | MiniDumpWithProcessThreadData
1423 // | MiniDumpWithPrivateReadWriteMemory
1424 //// | MiniDumpWithoutOptionalData
1425 // | MiniDumpWithFullMemoryInfo
1426 // | MiniDumpWithThreadInfo
1427 // | MiniDumpWithCodeSegs
1428 // | MiniDumpWithFullAuxiliaryState
1429 // | MiniDumpWithPrivateWriteCopyMemory
1430 // | MiniDumpIgnoreInaccessibleMemory
1431 // | MiniDumpWithTokenInformation
1432 //// | MiniDumpWithModuleHeaders
1433 //// | MiniDumpFilterTriage
1434 );
1435
1436 vboxVDbgVEHandlerRegister();
1437 }
1438#endif
1439
1440 crNetInit(NULL, NULL);
1441 ns.name = "vboxhgcm://host:0";
1442 ns.buffer_size = 1024;
1443 crNetServerConnect(&ns
1444#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
1445 , NULL
1446#endif
1447);
1448 if (!ns.conn)
1449 {
1450 crDebug("Failed to connect to host (is guest 3d acceleration enabled?), aborting ICD load.");
1451#ifdef VDBG_VEHANDLER
1452 if (g_VBoxVehEnable)
1453 vboxVDbgVEHandlerUnregister();
1454#endif
1455 return FALSE;
1456 }
1457 else
1458 {
1459 crNetFreeConnection(ns.conn);
1460 }
1461
1462 break;
1463 }
1464
1465 case DLL_PROCESS_DETACH:
1466 {
1467 /* do exactly the same thing as for DLL_THREAD_DETACH since
1468 * DLL_THREAD_DETACH is not called for the thread doing DLL_PROCESS_DETACH according to msdn docs */
1469 stubSetCurrentContext(NULL);
1470 if (stub_initialized)
1471 {
1472 CRASSERT(stub.spu);
1473 stub.spu->dispatch_table.VBoxDetachThread();
1474 }
1475
1476 stubSPUSafeTearDown();
1477
1478#ifdef CHROMIUM_THREADSAFE
1479 crFreeTSD(&g_stubCurrentContextTSD);
1480#endif
1481
1482#ifdef VDBG_VEHANDLER
1483 if (g_VBoxVehEnable)
1484 vboxVDbgVEHandlerUnregister();
1485#endif
1486 break;
1487 }
1488
1489 case DLL_THREAD_ATTACH:
1490 {
1491 if (stub_initialized)
1492 {
1493 CRASSERT(stub.spu);
1494 stub.spu->dispatch_table.VBoxAttachThread();
1495 }
1496 break;
1497 }
1498
1499 case DLL_THREAD_DETACH:
1500 {
1501 stubSetCurrentContext(NULL);
1502 if (stub_initialized)
1503 {
1504 CRASSERT(stub.spu);
1505 stub.spu->dispatch_table.VBoxDetachThread();
1506 }
1507 break;
1508 }
1509
1510 default:
1511 break;
1512 }
1513
1514 return TRUE;
1515}
1516#endif
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette