- implement loading and saving of MSI advertised shortcut info
[wine] / documentation / winedev-kernel.sgml
1   <chapter>
2     <title>Kernel modules</title>
3     <para>
4       This section cover the kernel modules. As already stated, Wine
5       implements the NT architecture, hence provides NTDLL for the
6       core kernel functions, and KERNEL32, which is the
7       implementation of the basis of the Win32 subsystem, on top of
8       NTDLL.
9     </para>
10     <sect1 id="ntdll">
11       <title>NTDLL</title>
12       <para>
13         NTDLL provides most of the services you'd expect from a
14         kernel.
15       </para>
16       <para>
17         Process and thread management are part of them (even if
18         process management is still mainly done in KERNEL32, unlike
19         NT). A Windows process runs as a Unix process, and a Windows
20         thread runs as a Unix thread.
21       </para>
22       <para>
23         Wine also provide fibers (which is the Windows name of
24         co-routines).
25       </para>
26       <para>
27         Most of the Windows memory handling (Heap, Global and Local
28         functions, virtual memory...) are easily mapped upon their
29         Unix equivalents. Note the NTDLL doesn't know about 16 bit
30         memory, which is only handled in KERNEL32/KRNL386.EXE (and
31         also the DOS routines).
32       </para>
33       
34       <sect2>
35         <title>File management</title>
36         <para>
37           Wine uses some configuration in order to map Windows
38           filenames (either defined with drive letters, or as UNC
39           names) to the unix filenames. Wine also uses some
40           incantation so that most of file related APIs can also
41           take full unix names. This is handy when passing filenames
42           on the command line.
43         </para>
44         <para>
45           File handles can be waitable objects, as Windows define
46           them.
47         </para>
48         <para>
49           Asynchronous I/O is implemented on file handles by
50           queueing pseudo APC. They are not real APC in the sense
51           that they have the same priority as the threads in the
52           considered process (while APCs on NT have normally a
53           higher priority). These APCs get called when invoking
54           Wine server (which should lead to correct behavior when the
55           program ends up waiting on some object - waiting always
56           implies calling Wine server).
57         </para>
58         <para>
59           FIXME: this should be enhanced and updated to latest work
60           on FS.
61         </para>
62       </sect2>
63
64       <sect2>
65         <title>Synchronization</title>
66         <para>
67           Most of the synchronization (between threads or processes)
68           is done in Wine server, which handles both the waiting
69           operation (on a single object or a set of objects) and the
70           signaling of objects. 
71         </para>
72       </sect2>
73
74       <sect2>
75         <title>Module (DLL) loading</title>
76         <para>
77           Wine is able to load any NE and PE module. In all cases,
78           the module's binary code is directly executed by the
79           processor.
80         </para>
81       </sect2>
82
83       <sect2>
84         <title>Device management</title>
85         <para>
86           Wine allows usage a wide variety of devices:
87           <itemizedlist>
88             <listitem>
89               <para>
90                 Communication ports are mapped to Unix
91                 communication ports (if they have sufficient
92                 permissions).
93               </para>
94             </listitem>
95             <listitem>
96               <para>
97                 Parallel ports are mapped to Unix parallel ports (if
98                 they have sufficient permissions).
99               </para>
100             </listitem>
101             <listitem>
102               <para>
103                 CDROM: the Windows device I/O control calls are
104                 mapped onto Unix <function>ioctl()</function>.
105               </para>
106             </listitem>
107             <listitem>
108               <para>
109                 Some Win9x VxDs are supported, by rewriting some of
110                 their internal behavior. But this support is
111                 limited. Portable programs to Windows NT shouldn't
112                 need them.
113               </para>
114               <para>
115                 Wine will not support native VxD.
116               </para>
117             </listitem>
118           </itemizedlist>
119         </para>
120       </sect2>
121       <sect2 id="threading">
122         <title>Multi-threading in Wine</title>
123
124         <para>
125           This section will assume you understand the basics of
126           multithreading. If not there are plenty of good tutorials
127           available on the net to get you started.
128         </para>
129
130         <para>
131           Threading in Wine is somewhat complex due to several
132           factors. The first is the advanced level of multithreading
133           support provided by Windows - there are far more threading
134           related constructs available in Win32 than the Linux
135           equivalent (pthreads). The second is the need to be able to
136           map Win32 threads to native Linux threads which provides us
137           with benefits like having the kernel schedule them without
138           our intervention. While it's possible to implement threading
139           entirely without kernel support, doing so is not desirable
140           on most platforms that Wine runs on.
141         </para>
142
143         <sect3>
144           <title> Threading support in Win32 </title>
145
146           <para>
147             Win32 is an unusually thread friendly API. Not only is it
148             entirely thread safe, but it provides many different
149             facilities for working with threads. These range from the
150             basics such as starting and stopping threads, to the
151             extremely complex such as injecting threads into other
152             processes and COM inter-thread marshalling.
153           </para>
154
155           <para>
156             One of the primary challenges of writing Wine code
157             therefore is ensuring that all our DLLs are thread safe,
158             free of race conditions and so on. This isn't simple -
159             don't be afraid to ask if you aren't sure whether a piece
160             of code is thread safe or not!
161           </para>
162
163           <para>
164             Win32 provides many different ways you can make your code
165             thread safe however the most common are <emphasis>critical
166               section</emphasis> and the <emphasis>interlocked
167               functions</emphasis>. Critical sections are a type of
168             mutex designed to protect a geographic area of code. If
169             you don't want multiple threads running in a piece of code
170             at once, you can protect them with calls to
171             <function>EnterCriticalSection</function> and
172             <function>LeaveCriticalSection</function>. The first call
173             to <function>EnterCriticalSection</function> by a thread
174             will lock the section and continue without stopping. If
175             another thread calls it then it will block until the
176             original thread calls
177             <function>LeaveCriticalSection</function> again.
178           </para>
179
180           <para>
181             It is therefore vitally important that if you use critical
182             sections to make some code thread-safe, that you check
183             every possible codepath out of the code to ensure that any
184             held sections are left. Code like this:
185           </para>
186
187           <programlisting>
188 if (res != ERROR_SUCCESS) return res;
189           </programlisting>
190
191           <para>
192             is extremely suspect in a function that also contains a
193             call to <function>EnterCriticalSection</function>. Be
194             careful.
195           </para>
196
197           <para>
198             If a thread blocks while waiting for another thread to
199             leave a critical section, you will see an error from the
200             <function>RtlpWaitForCriticalSection</function> function,
201             along with a note of which thread is holding the
202             lock. This only appears after a certain timeout, normally
203             a few seconds. It's possible the thread holding the lock
204             is just being really slow which is why Wine won't
205             terminate the app like a non-checked build of Windows
206             would, but the most common cause is that for some reason a
207             thread forgot to call
208             <function>LeaveCriticalSection</function>, or died while
209             holding the lock (perhaps because it was in turn waiting
210             for another lock). This doesn't just happen in Wine code:
211             a deadlock while waiting for a critical section could be
212             due to a bug in the app triggered by a slight difference
213             in the emulation.
214           </para>
215     
216           <para>
217             Another popular mechanism available is the use of
218             functions like <function>InterlockedIncrement</function>
219             and <function>InterlockedExchange</function>. These make
220             use of native CPU abilities to execute a single
221             instruction while ensuring any other processors on the
222             system cannot access memory, and allow you to do common
223             operations like add/remove/check a variable in thread-safe
224             code without holding a mutex. These are useful for
225             reference counting especially in free-threaded (thread
226             safe) COM objects.
227           </para>
228
229           <para>
230             Finally, the usage of TLS slots are also popular. TLS
231             stands for thread-local storage, and is a set of slots
232             scoped local to a thread which you can store pointers
233             in. Look on MSDN for the <function>TlsAlloc</function>
234             function to learn more about the Win32 implementation of
235             this. Essentially, the contents of a given slot will be
236             different in each thread, so you can use this to store
237             data that is only meaningful in the context of a single
238             thread. On recent versions of Linux the __thread keyword
239             provides a convenient interface to this functionality - a
240             more portable API is exposed in the pthread
241             library. However, these facilities are not used by Wine,
242             rather, we implement Win32 TLS entirely ourselves.
243           </para>
244         </sect3>
245
246         <sect3>
247           <title> SysLevels </title>
248
249           <para>
250             SysLevels are an undocumented Windows-internal
251             thread-safety system. They are basically critical sections
252             which must be taken in a particular order. The mechanism
253             is generic but there are always three syslevels: level 1
254             is the Win16 mutex, level 2 is the USER mutex and level 3
255             is the GDI mutex.
256           </para>
257
258           <para>
259             When entering a syslevel, the code (in
260             <filename>dlls/kernel/syslevel.c</filename>) will check
261             that a higher syslevel is not already held and produce an
262             error if so. This is because it's not legal to enter level
263             2 while holding level 3 - first, you must leave level 3.
264           </para>
265
266           <para>
267             Throughout the code you may see calls to
268             <function>_ConfirmSysLevel()</function> and
269             <function>_CheckNotSysLevel()</function>. These functions
270             are essentially assertions about the syslevel states and
271             can be used to check that the rules have not been
272             accidentally violated. In particular,
273             <function>_CheckNotSysLevel()</function> will break
274             (probably into the debugger) if the check fails. If this
275             happens the solution is to get a backtrace and find out,
276             by reading the source of the wine functions called along
277             the way, how Wine got into the invalid state.
278           </para>
279     
280         </sect3>
281
282         <sect3>
283           <title> POSIX threading vs kernel threading </title>
284
285           <para>
286             Wine runs in one of two modes: either pthreads (posix
287             threading) or kthreads (kernel threading). This section
288             explains the differences between them. The one that is
289             used is automatically selected on startup by a small test
290             program which then execs the correct binary, either
291             wine-kthread or wine-pthread. On NPTL-enabled systems
292             pthreads will be used, and on older non-NPTL systems
293             kthreads is selected.
294           </para>
295
296           <para>
297             Let's start with a bit of history. Back in the dark ages
298             when Wine's threading support was first implemented a
299             problem was faced - Windows had much more capable
300             threading APIs than Linux did. This presented a problem -
301             Wine works either by reimplementing an API entirely or by
302             mapping it onto the underlying systems equivalent. How
303             could Win32 threading be implemented using a library which
304             did not have all the needed features? The answer, of
305             course, was that it couldn't be.
306           </para>
307
308           <para>
309             On Linux the pthreads interface is used to start, stop and
310             control threads. The pthreads library in turn is based on
311             top of so-called "kernel threads" which are created using
312             the <function>clone(2)</function> syscall. Pthreads
313             provides a nicer (more portable) interface to this
314             functionality and also provides APIs for controlling
315             mutexes. There is a <ulink 
316             url="http://www.llnl.gov/computing/tutorials/pthreads/">
317             good tutorial on pthreads </ulink> available if you want
318             to learn more.
319           </para>
320
321           <para>
322             As pthreads did not provide the necessary semantics to
323             implement Win32 threading, the decision was made to
324             implement Win32 threading on top of the underlying kernel
325             threads by using syscalls like <function>clone</function>
326             directly. This provided maximum flexibility and allowed a
327             correct implementation but caused some bad side
328             effects. Most notably, all the userland Linux APIs assumed
329             that the user was utilising the pthreads library. Some
330             only enabled thread safety when they detected that
331             pthreads was in use - this is true of glibc, for
332             instance. Worse, pthreads and pure kernel threads had
333             strange interactions when run in the same process yet some
334             libraries used by Wine used pthreads internally. Throw in
335             source code porting using WineLib - where you have both
336             UNIX and Win32 code in the same process - and chaos was
337             the result.
338           </para>
339
340           <para>
341             The solution was simple yet ingenious: Wine would provide
342             its own implementation of the pthread library
343             <emphasis>inside</emphasis> its own binary. Due to the
344             semantics of ELF symbol scoping, this would cause Wine's
345             own implementation to override any implementation loaded
346             later on (like the real libpthread.so). Therefore, any
347             calls to the pthread APIs in external libraries would be
348             linked to Wine's instead of the system's pthreads library,
349             and Wine implemented pthreads by using the standard
350             Windows threading APIs it in turn implemented itself.
351           </para>
352
353           <para>
354             As a result, libraries that only became thread-safe in the
355             presence of a loaded pthreads implementation would now do
356             so, and any external code that used pthreads would
357             actually end up creating Win32 threads that Wine was aware
358             of and controlled. This worked quite nicely for a long
359             time, even though it required doing some extremely
360             un-kosher things like overriding internal libc structures
361             and functions. That is, it worked until NPTL was developed
362             at which point the underlying thread implementation on
363             Linux changed dramatically.
364           </para>
365
366           <para>
367             The fake pthread implementation can be found in
368             <filename>loader/kthread.c</filename>, which is used to
369             produce the wine-kthread binary. In contrast,
370             loader/pthread.c produces the wine-pthread binary which is
371             used on newer NPTL systems.
372           </para>
373
374           <para>
375             NPTL is a new threading subsystem for Linux that hugely
376             improves its performance and flexibility. By allowing
377             threads to become much more scalable and adding new
378             pthread APIs, NPTL made Linux competitive with Windows in
379             the multi-threaded world. Unfortunately it also broke many
380             assumptions made by Wine (as well as other applications
381             such as the Sun JVM and RealPlayer) in the process.
382           </para>
383
384           <para>
385             There was, however, some good news. NPTL made Linux
386             threading powerful enough that Win32 threads could now be
387             implemented on top of pthreads like any other normal
388             application. There would no longer be problems with mixing
389             win32-kthreads and pthreads created by external libraries,
390             and no need to override glibc internals. As you can see
391             from the relative sizes of the
392             <filename>loader/kthread.c</filename> and
393             <filename>loader/pthread.c</filename> files, the
394             difference in code complexity is considerable. NPTL also
395             made several other semantic changes to things such as
396             signal delivery so changes were required in many different
397             places in Wine.
398           </para>
399
400           <para>
401             On non-Linux systems the threading interface is typically
402             not powerful enough to replicate the semantics Win32
403             applications expect and so kthreads with the pthread
404             overrides are used.
405           </para>
406         </sect3>
407
408         <sect3>
409           <title> The Win32 thread environment </title>
410
411           <para>
412             All Win32 code, whether from a native EXE/DLL or in Wine 
413             itself, expects certain constructs to be present in its
414             environment. This section explores what those constructs
415             are and how Wine sets them up. The lack of this
416             environment is one thing that makes it hard to use Wine
417             code directly from standard Linux applications - in order
418             to interact with Win32 code a thread must first be
419             "adopted" by Wine.
420           </para>
421
422           <para>
423             The first thing Win32 code requires is the
424             <emphasis>TEB</emphasis> or "Thread Environment
425             Block". This is an internal (undocumented) Windows
426             structure associated with every thread which stores a
427             variety of things such as TLS slots, a pointer to the
428             threads message queue, the last error code and so on. You
429             can see the definition of the TEB in
430             <filename>include/thread.h</filename>, or at least what we
431             know of it so far. Being internal and subject to change,
432             the layout of the TEB has had to be reverse engineered
433             from scratch.
434           </para>
435
436           <para>
437             A pointer to the TEB is stored in the %fs register and can
438             be accessed using <function>NtCurrentTeb()</function> from
439             within Wine code. %fs actually stores a selector, and
440             setting it therefore requires modifying the processes
441             local descriptor table (LDT) - the code to do this is in
442             <filename>lib/wine/ldt.c</filename>. 
443           </para>
444
445           <para>
446             The TEB is required by nearly all Win32 code run in the
447             Wine environment, as any wineserver RPC will use it, which
448             in turn implies that any code which could possibly block
449             (for instance by using a critical section) needs it. The
450             TEB also holds the SEH exception handler chain as the
451             first element, so if disassembling you see code like this:
452           </para>
453
454           <programlisting> movl %esp, %fs:0 </programlisting>
455
456           <para>
457             ... then you are seeing the program set up an SEH handler
458             frame. All threads must have at least one SEH entry, which
459             normally points to the backstop handler which is
460             ultimately responsible for popping up the all-too-familiar
461             "This program has performed an illegal operation and will
462             be terminated" message. On Wine we just drop straight into
463             the debugger. A full description of SEH is out of the
464             scope of this section, however there are some good
465             articles in MSJ if you are interested.
466           </para>
467
468           <para>
469             All Win32-aware threads must have a wineserver
470             connection. Many different APIs require the ability to
471             communicate with the wineserver. In turn, the wineserver
472             must be aware of Win32 threads in order to be able to
473             accurately report information to other parts of the program
474             and do things like route inter-thread messages, dispatch
475             APCs (asynchronous procedure calls) and so on. Therefore a
476             part of thread initialization is initializing the thread
477             serverside. The result is not only correct information in
478             the server, but a set of file descriptors the thread can use
479             to communicate with the server - the request fd, reply fd
480             and wait fd (used for blocking).
481           </para>
482         </sect3>
483       </sect2>
484     </sect1>
485
486     <sect1>
487       <title>KERNEL Module</title>
488       
489       <para>
490         FIXME: Needs some content...
491       </para>
492       <sect2 id="consoles">
493         <title>Consoles in Wine</title>
494         <para>
495           As described in the Wine User Guide's CUI section, Wine
496           manipulates three kinds of "consoles" in order to support
497           properly the Win32 CUI API.
498         </para>
499         <para>
500           The following table describes the main implementation
501           differences between the three approaches.
502           <table>
503             <title>Function consoles implementation comparison</title>
504             <tgroup cols="4" align="left">
505               <thead>
506                 <row>
507                   <entry>Function</entry>
508                   <entry>Bare streams</entry>
509                   <entry>Wineconsole &amp; user backend</entry>
510                   <entry>Wineconsole &amp; curses backend</entry>
511                 </row>
512               </thead>
513               <tbody>
514                 <row>
515                   <entry>
516                     Console as a Win32 Object (and associated
517                     handles)
518                   </entry> 
519                   <entry>
520                     No specific Win32 object is used in this
521                     case. The handles manipulated for the standard
522                     Win32 streams are in fact "bare handles" to
523                     their corresponding Unix streams. The mode
524                     manipulation functions
525                     (<function>GetConsoleMode</function> /
526                     <function>SetConsoleMode</function>) are not
527                     supported.
528                   </entry>
529                   <entry>
530                     Implemented in server, and a specific Winelib
531                     program (wineconsole) is in charge of the
532                     rendering and user input. The mode manipulation
533                     functions behave as expected.
534                   </entry>
535                   <entry>
536                     Implemented in server, and a specific Winelib
537                     program (wineconsole) is in charge of the
538                     rendering and user input. The mode manipulation
539                     functions behave as expected.
540                   </entry>
541                 </row>
542                 <row>
543                   <entry>
544                     Inheritance (including handling in
545                     <function>CreateProcess</function> of
546                     <constant>CREATE_DETACHED</constant>,
547                     <constant>CREATE_NEW_CONSOLE</constant> flags).
548                   </entry>
549                   <entry>
550                     Not supported. Every process child of a process
551                     will inherit the Unix streams, so will also
552                     inherit the Win32 standard streams.
553                   </entry>
554                   <entry>
555                     Fully supported (each new console creation will
556                     be handled by the creation of a new USER32
557                     window)
558                   </entry>
559                   <entry>
560                     Fully supported, except for the creation of a
561                     new console, which will be rendered on the same
562                     Unix terminal as the previous one, leading to
563                     unpredictable results.
564                   </entry>
565                 </row>
566                 <row>
567                   <entry>
568                     <function>ReadFile</function> /
569                     <function>WriteFile</function>
570                     operations
571                   </entry> 
572                   <entry>Fully supported</entry>
573                   <entry>Fully supported</entry>
574                   <entry>Fully supported</entry>
575                 </row>
576                 <row>
577                   <entry>
578                     Screen-buffer manipulation (creation, deletion,
579                     resizing...)
580                   </entry>
581                   <entry>Not supported</entry>
582                   <entry>Fully supported</entry>
583                   <entry>
584                     Partly supported (this won't work too well as we
585                     don't control (so far) the size of underlying
586                     Unix terminal
587                   </entry>
588                 </row>
589                 <row>
590                   <entry>
591                     APIs for reading/writing screen-buffer content,
592                     cursor position
593                   </entry>
594                   <entry>Not supported</entry>
595                   <entry>Fully supported</entry>
596                   <entry>Fully supported</entry>
597                 </row>
598                 <row>
599                   <entry>
600                     APIs for manipulating the rendering window size
601                   </entry>
602                   <entry>Not supported</entry>
603                   <entry>Fully supported</entry>
604                   <entry>
605                     Partly supported (this won't work too well as we
606                     don't control (so far) the size of underlying
607                     Unix terminal
608                   </entry>
609                 </row>
610                 <row>
611                   <entry>
612                     Signaling (in particular, Ctrl-C handling)
613                   </entry>
614                   <entry>
615                     Nothing is done, which means that Ctrl-C will
616                     generate (as usual) a
617                     <constant>SIGINT</constant> which will terminate
618                     the program.
619                   </entry>
620                   <entry>
621                     Partly supported (Ctrl-C behaves as expected,
622                     however the other Win32 CUI signaling isn't
623                     properly implemented).
624                   </entry>
625                   <entry>
626                     Partly supported (Ctrl-C behaves as expected,
627                     however the other Win32 CUI signaling isn't
628                     properly implemented).
629                   </entry>
630                 </row>
631               </tbody>
632             </tgroup>
633           </table>
634         </para>
635
636         <para>
637           The Win32 objects behind a console can be created in
638           several occasions:
639           <itemizedlist>
640             <listitem>
641               <para>
642                 When the program is started from wineconsole, a new
643                 console object is created and will be used
644                 (inherited) by the process launched from
645                 wineconsole.
646               </para>
647             </listitem>
648             <listitem>
649               <para>
650                 When a program, which isn't attached to a console,
651                 calls <function>AllocConsole</function>, Wine then
652                 launches wineconsole, and attaches the current
653                 program to this console. In this mode, the USER32
654                 mode is always selected as Wine cannot tell the
655                 current state of the Unix console.
656               </para>
657             </listitem>
658           </itemizedlist>
659         </para>
660         <para>
661           Please also note, that starting a child process with the
662           <constant>CREATE_NEW_CONSOLE</constant> flag, will end-up
663           calling <function>AllocConsole</function> in the child
664           process, hence creating a wineconsole with the USER32
665           backend.
666         </para>
667       </sect2>
668     </sect1>
669     
670     <sect1 id="initialization">
671
672       <title> The Wine initialization process </title>
673
674       <para>
675         Wine has a rather complex startup procedure, so unlike many
676         programs the best place to begin exploring the code-base is
677         <emphasis>not</emphasis> in fact at the
678         <function>main()</function> function but instead at some of the
679         more straightforward DLLs that exist on the periphery such as
680         MSI, the widget library (in USER and COMCTL32) etc. The purpose
681         of this section is to document and explain how Wine starts up
682         from the moment the user runs "wine myprogram.exe" to the point
683         at which myprogram gets control.
684       </para>
685
686       <sect2>
687         <title> First Steps </title>
688
689         <para>
690           The actual wine binary that the user runs does not do very much, in fact it is only
691           responsible for checking the threading model in use (NPTL vs LinuxThreads) and then invoking
692           a new binary which performs the next stage in the startup sequence. See the beginning of this chapter 
693           for more information on this check and why it's necessary. You can find this code in
694           <filename>loader/glibc.c</filename>. The result of this check is an exec of either
695           wine-pthread or wine-kthread, potentially (on Linux) via
696           the <emphasis>preloader</emphasis>. We need to use separate binaries here because overriding
697           the native pthreads library requires us to exploit a property of ELF symbol fixup semantics:
698           it's not possible to do this without starting a new process.
699         </para>
700
701         <para>
702           The Wine preloader is found in <filename>loader/preloader.c</filename>, and is required in
703           order to impose a Win32 style address space layout upon the newly created Win32 process. The
704           details of what this does is covered in the address space layout chapter. The preloader is a
705           statically linked ELF binary which is passed the name of the actual Wine binary to run (either
706           wine-kthread or wine-pthread) along with the arguments the user passed in from the command
707           line. The preloader is an unusual program: it does not have a main() function. In standard ELF
708           applications, the entry point is actually at a symbol named _start: this is provided by the
709           standard gcc infrastructure and normally jumps to <function>__libc_start_main</function> which
710           initializes glibc before passing control to the main function as defined by the programmer.
711         </para>
712
713         <para>
714           The preloader takes control direct from the entry point for a few reasons. Firstly, it is
715           required that glibc is not initialized twice: the result of such behaviour is undefined and
716           subject to change without notice. Secondly, it's possible that as part of initializing glibc,
717           the address space layout could be changed - for instance, any call to malloc will initialize a
718           heap arena which modifies the VM mappings. Finally, glibc does not return to _start at any
719           point, so by reusing it we avoid the need to recreate the ELF bootstrap stack (env, argv,
720           auxiliary array etc).
721         </para>
722
723         <para>
724           The preloader is responsible for two things: protecting important regions of the address
725           space so the dynamic linker does not map shared libraries into them, and once that is done
726           loading the real Wine binary off disk, linking it and starting it up. Normally all this is
727           done automatically by glibc and the kernel but as we intercepted this process by using a
728           static binary it's up to us to restart the process. The bulk of the code in the preloader is
729           about loading wine-[pk]thread and ld-linux.so.2 off disk, linking them together, then
730           starting the dynamic linking process.
731         </para>
732
733         <para>
734           One of the last things the preloader does before jumping into the dynamic linker is scan the
735           symbol table of the loaded Wine binary and set the value of a global variable directly: this
736           is a more efficient way of passing information to the main Wine program than flattening the
737           data structures into an environment variable or command line parameter then unpacking it on
738           the other side, but it achieves pretty much the same thing. The global variable set points to
739           the preload descriptor table, which contains the VMA regions protected by the preloader. This
740           allows Wine to unmap them once the dynamic linker has been run, so leaving gaps we can
741           initialize properly later on.
742         </para>
743
744       </sect2>
745     
746       <sect2>
747         <title> Starting the emulator </title>
748
749         <para>
750           The process of starting up the emulator itself is mostly one of chaining through various
751           initializer functions defined in the core libraries and DLLs: libwine, then NTDLL, then kernel32.
752         </para>
753
754         <para>
755           Both the wine-pthread and wine-kthread binaries share a common <function>main</function>
756           function, defined in <filename>loader/main.c</filename>, so no matter which binary is selected
757           after the preloader has run we start here. This passes the information provided by the
758           preloader into libwine and then calls wine_init, defined
759           in <filename>libs/wine/loader.c</filename>. This is where the emulation really starts:
760           <function>wine_init</function> can, with the correct preparation,
761           be called from programs other than the wine loader itself.
762         </para>
763
764         <para>
765           <function>wine_init</function> does some very basic setup tasks such as initializing the
766           debugging infrastructure, yet more address space manipulation (see the information on the
767           4G/4G VM split in the address space chapter), before loading NTDLL - the core of both Wine and
768           the Windows NT series - and jumping to the <function>__wine_process_init</function> function defined
769           in <filename>dlls/ntdll/loader.c</filename>
770         </para>
771
772         <para>
773           This function is responsible for initializing the primary Win32 environment. In thread_init(),
774           it sets up the TEB, the wineserver connection for the main thread and the process heap. See
775           the beginning of this chapter for more information on this.
776         </para>
777
778         <para>
779           Finally, it loads and jumps to <function>__wine_kernel_init</function> in kernel32.dll: this
780           is defined in <filename>dlls/kernel32/process.c</filename>. This is where the bulk of the work
781           is done. The kernel32 initialization code retrieves the startup info for the process from the
782           server, initializes the registry, sets up the drive mapping system and locale data, then
783           begins loading the requested application itself. Each process has a STARTUPINFO block that can
784           be passed into <function>CreateProcess</function> specifying various things like how the first
785           window should be displayed: this is sent to the new process via the wineserver.
786         </para>
787
788         <para>
789           After determining the type of file given to Wine by the user (a Win32 EXE file, a Win16 EXE, a
790           Winelib app etc), the program is loaded into memory (which may involve loading and
791           initializing other DLLs, the bulk of Wines startup code), before control reaches the end of
792           <function>__wine_kernel_init</function>. This function ends with the new process stack being
793           initialized, and start_process being called on the new stack. Nearly there!
794         </para>
795
796         <para>
797           The final element of initializing Wine is starting the newly loaded program
798           itself. <function>start_process</function> sets up the SEH backstop handler, calls
799           <function>LdrInitializeThunk</function> which performs the last part of the process
800           initialization (such as performing relocations and calling the DllMains with PROCESS_ATTACH),
801           grabs the entry point of the executable and then on this line:
802         </para>
803
804         <programlisting>
805 ExitProcess( entry( peb ) );
806         </programlisting>
807
808         <para>
809           ... jumps to the entry point of the program. At this point the users program is running and
810           the API provided by Wine is ready to be used. When entry returns,
811           the <function>ExitProcess</function> API will be used to initialize a graceful shutdown.
812         </para>
813       </sect2>
814     </sect1>
815
816     <sect1 id="seh">
817       <title>Structured Exception Handling</title>
818       
819       <para>
820         Structured Exception Handling (or SEH) is an implementation of
821         exceptions inside the Windows core. It allows code written in
822         different languages to throw exceptions across DLL boundaries, and
823         Windows reports various errors like access violations by throwing
824         them. This section looks at how it works, and how it's implemented
825         in Wine.
826       </para>
827
828       <sect2>
829         <title> How SEH works </title>
830
831         <para>
832           SEH is based on embedding EXCEPTION_REGISTRATION_RECORD
833           structures in the stack. Together they form a linked list rooted
834           at offset zero in the TEB (see the threading section if you
835           don't know what this is). A registration record points to a
836           handler function, and when an exception is thrown the handlers
837           are executed in turn. Each handler returns a code, and they can
838           elect to either continue through the handler chain or it can
839           handle the exception and then restart the program. This is
840           referred to as unwinding the stack. After each handler is called
841           it's popped off the chain.
842         </para>
843
844         <para>
845           Before the system begins unwinding the stack, it runs vectored
846           handlers. This is an extension to SEH available in Windows XP,
847           and allows registered functions to get a first chance to watch
848           or deal with any exceptions thrown in the entire program, from
849           any thread.
850         </para>
851
852         <para>
853           A thrown exception is represented by an EXCEPTION_RECORD
854           structure. It consists of a code, flags, an address and an
855           arbitrary number of DWORD parameters. Language runtimes can use
856           these parameters to associate language-specific information with
857           the exception.
858         </para>
859         
860         <para>
861           Exceptions can be triggered by many things. They can be thrown
862           explicitly by using the RaiseException API, or they can be
863           triggered by a crash (ie, translated from a signal). They may be
864           used internally by a language runtime to implement
865           language-specific exceptions. They can also be thrown across
866           DCOM connections.
867         </para>
868
869         <para>
870           Visual C++ has various extensions to SEH which it uses to
871           implement, eg, object destruction on stack unwind as well as the
872           ability to throw arbitrary types. The code for this is in dlls/msvcrt/except.c
873         </para>
874
875       </sect2>
876       
877       <sect2>
878         <title> Translating signals to exceptions </title>
879
880         <para>
881           In Windows, compilers are expected to use the system exception
882           interface, and the kernel itself uses the same interface to
883           dynamically insert exceptions into a running program. By contrast
884           on Linux the exception ABI is implemented at the compiler level
885           (inside GCC and the linker) and the kernel tells a thread of
886           exceptional events by sending <emphasis>signals</emphasis>. The
887           language runtime may or may not translate these signals into
888           native exceptions, but whatever happens the kernel does not care.
889         </para>
890
891         <para>
892           You may think that if an app crashes, it's game over and it
893           really shouldn't matter how Wine handles this. It's what you might
894           intuitively guess, but you'd be wrong. In fact some Windows
895           programs expect to be able to crash themselves and recover later
896           without the user noticing, some contain buggy binary-only
897           components from third parties and use SEH to swallow crashes, and
898           still others execute priviledged (kernel-level) instructions and
899           expect it to work. In fact, at least one set of APIs (the
900           IsBad*Ptr series) can only be implemented by performing an
901           operation that may crash and returning TRUE if it does, and FALSE
902           if it doesn't! So, Wine needs to not only implement the SEH
903           infrastructure but also translate Unix signals into SEH
904           exceptions.
905         </para>
906
907         <para>
908           The code to translate signals into exceptions is a part of NTDLL,
909           and can be found in dlls/ntdll/signal_i386.c. This file sets up
910           handlers for various signals during Wine startup, and for the ones
911           that indicate exceptional conditions translates them into
912           exceptions. Some signals are used by Wine internally and have
913           nothing to do with SEH.
914         </para>
915
916         <para>
917           Signal handlers in Wine run on their own stack. Each thread has
918           its own signal stack which resides 4k after the TEB. This is
919           important for a couple of reasons. Firstly, because there's no
920           guarantee that the app thread which triggered the signal has
921           enough stack space for the Wine signal handling code. In
922           Windows, if a thread hits the limits of its stack it triggers a
923           fault on the stack guard page. The language runtime can use this
924           to grow the stack if it wants to.
925
926           <!-- fixme: is it really the language runtime that does this? i
927                can't find any code in Wine to reallocate the stack on
928                STATUS_GUARD_PAGE_VIOLATION -->
929
930           However, because a guard page violation is just a regular
931           segfault to the kernel, that would lead to a nested signal
932           handler and that gets messy really quick so we disallow that in
933           Wine. Secondly, setting up the exception to throw requires
934           modifying the stack of the thread which triggered it, which is
935           quite hard to do when you're still running on it.
936         </para>
937
938         <para>
939           Windows exceptions typically contain more information than the
940           Unix standard APIs provide. For instance, a
941           STATUS_ACCESS_VIOLATION exception (0xC0000005) structure
942           contains the faulting address, whereas a standard Unix SIGSEGV
943           just tells the app that it crashed. Usually this information is
944           passed as an extra parameter to the signal handler, however its
945           location and contents vary between kernels (BSD, Solaris,
946           etc). This data is provided in a SIGCONTEXT structure, and on
947           entry to the signal handler it contains the register state of
948           the CPU before the signal was sent. Modifying it will cause the
949           kernel to adjust the context before restarting the thread.
950         </para>
951         
952       </sect2>
953       
954     </sect1>
955
956   </chapter>
957
958 <!-- Keep this comment at the end of the file
959 Local variables:
960 mode: sgml
961 sgml-parent-document:("wine-devel.sgml" "set" "book" "part" "chapter" "")
962 End:
963 -->