Update a few points about shared libs in other sections
[ghc.git] / docs / users_guide / win32-dlls.xml
1 <?xml version="1.0" encoding="iso-8859-1"?>
2 <chapter id="win32">
3 <title>Running GHC on Win32 systems</title>
4
5 <sect1 id="ghc-windows">
6 <title>
7 Starting GHC on Windows platforms</title>
8
9 <para>
10 The installer that installs GHC on Win32 also sets up the file-suffix associations
11 for ".hs" and ".lhs" files so that double-clicking them starts <command>ghci</command>.
12 </para>
13 <para>
14 Be aware of that <command>ghc</command> and <command>ghci</command> do
15 require filenames containing spaces to be escaped using quotes:
16 <programlisting>
17 c:\ghc\bin\ghci "c:\\Program Files\\Haskell\\Project.hs"
18 </programlisting>
19 If the quotes are left off in the above command, <command>ghci</command> will
20 interpret the filename as two, "c:\\Program" and "Files\\Haskell\\Project.hs".
21 </para>
22
23 <!-- not clear whether there are current editions of Win32 OSes that
24 doesn't do this by default.
25
26 <para> Solution: don't use "Open With...", avoid spaces in file names,
27 or fiddle with the appropriate registry setting:
28 <programlisting>
29 HKEY_CLASSES_ROOT\Unknown\shell\openas\command
30 </programlisting>
31 Notice how the "%1" argument is quoted (or not).
32 </para>
33 <para> This problem doesn't occur when double-clicking.
34 </para>
35 -->
36
37 </sect1>
38
39 <sect1 id="ghci-windows">
40 <title>Running GHCi on Windows</title>
41
42 <para>We recommend running GHCi in a standard Windows console:
43 select the <literal>GHCi</literal> option from the start menu item
44 added by the GHC installer, or use
45 <literal>Start->Run->cmd</literal> to get a Windows console and
46 invoke <literal>ghci</literal> from there (as long as it's in your
47 <literal>PATH</literal>).</para>
48
49 <para>If you run GHCi in a Cygwin or MSYS shell, then the Control-C
50 behaviour is adversely affected. In one of these environments you
51 should use the <literal>ghcii.sh</literal> script to start GHCi,
52 otherwise when you hit Control-C you'll be returned to the shell
53 prompt but the GHCi process will still be running. However, even
54 using the <literal>ghcii.sh</literal> script, if you hit Control-C
55 then the GHCi process will be killed immediately, rather than
56 letting you interrupt a running program inside GHCi as it should.
57 This problem is caused by the fact that the Cygwin and MSYS shell
58 environments don't pass Control-C events to non-Cygwin child
59 processes, because in order to do that there needs to be a Windows
60 console.</para>
61
62 <para>There's an exception: you can use a Cygwin shell if the
63 <literal>CYGWIN</literal> environment variable does
64 <emphasis>not</emphasis> contain <literal>tty</literal>. In this
65 mode, the Cygwin shell behaves like a Windows console shell and
66 console events are propagated to child processes. Note that the
67 <literal>CYGWIN</literal> environment variable must be set
68 <emphasis>before</emphasis> starting the Cygwin shell; changing it
69 afterwards has no effect on the shell.</para>
70
71 <para>This problem doesn't just affect GHCi, it affects any
72 GHC-compiled program that wants to catch console events. See the
73 <ulink
74 url="../libraries/base/GHC-ConsoleHandler.html">GHC.ConsoleHandler</ulink>
75 module.</para>
76 </sect1>
77
78 <sect1 id="terminal-interaction">
79 <title>
80 Interacting with the terminal</title>
81
82 <para>By default GHC builds applications that open a console window when they start.
83 If you want to build a GUI-only application, with no console window, use the flag
84 <literal>-optl-mwindows</literal> in the link step.
85 </para>
86
87 <para> <emphasis>Warning:</emphasis> Windows GUI-only programs have no
88 stdin, stdout or stderr so using the ordinary Haskell
89 input/output functions will cause your program to fail with an
90 IO exception, such as:
91 <screen>
92 Fail: &lt;stdout&gt;: hPutChar: failed (Bad file descriptor)
93 </screen>
94 However using Debug.Trace.trace is alright because it uses
95 Windows debugging output support rather than stderr.</para>
96
97 <para>For some reason, Mingw ships with the <literal>readline</literal> library,
98 but not with the <literal>readline</literal> headers. As a result, GHC (like Hugs) does not
99 use <literal>readline</literal> for interactive input on Windows.
100 You can get a close simulation by using an emacs shell buffer!
101 </para>
102
103 </sect1>
104
105 <sect1 id="library-differences">
106 <title>
107 Differences in library behaviour </title>
108
109 <para>
110 Some of the standard Haskell libraries behave slightly differently on Windows.
111
112 <itemizedlist>
113 <listitem> <para>
114 On Windows, the '<literal>^Z</literal>' character is interpreted as an
115 end-of-file character, so if you read a file containing this character
116 the file will appear to end just before it. To avoid this,
117 use <literal>IOExts.openFileEx</literal> to open a file in binary
118 (untranslated) mode or change an already opened file handle into
119 binary mode using <literal>IOExts.hSetBinaryMode</literal>. The
120 <literal>IOExts</literal> module is part of the
121 <literal>lang</literal> package.
122 </para>
123 </listitem>
124 </itemizedlist>
125 </para>
126 </sect1>
127
128 <sect1 id="ghci-cygwin">
129 <title>
130 Using GHC (and other GHC-compiled executables) with cygwin</title>
131
132 <sect2>
133 <title>Background</title> <para>The cygwin tools aim to provide a
134 unix-style API on top of the windows libraries, to facilitate ports of
135 unix software to windows. To this end, they introduce a unix-style
136 directory hierarchy under some root directory (typically
137 <filename>/</filename> is <filename>C:\cygwin\</filename>). Moreover,
138 everything built against the cygwin API (including the cygwin tools
139 and programs compiled with cygwin's ghc) will see / as the root of
140 their file system, happily pretending to work in a typical unix
141 environment, and finding things like <filename>/bin</filename> and <filename>/usr/include</filename> without
142 ever explicitly bothering with their actual location on the windows
143 system (probably <filename>C:\cygwin\bin</filename> and <filename>C:\cygwin\usr\include</filename>).
144 </para>
145 </sect2>
146
147 <sect2><title>The problem</title>
148 <para>GHC, by default, no longer depends on cygwin, but is a native
149 windows program. It is built using mingw, and it uses mingw's ghc
150 while compiling your Haskell sources (even if you call it from
151 cygwin's bash), but what matters here is that - just like any other
152 normal windows program - neither GHC nor the executables it produces
153 are aware of cygwin's pretended unix hierarchy. GHC will happily
154 accept either '/' or '\' as path separators, but it won't know where
155 to find <filename>/home/joe/Main.hs</filename> or <filename>/bin/bash</filename>
156 or the like. This causes all
157 kinds of fun when GHC is used from within cygwin's bash, or in
158 make-sessions running under cygwin.
159 </para>
160 </sect2>
161
162 <sect2><title>Things to do</title>
163 <itemizedlist>
164 <listitem>
165 <para> Don't use absolute paths in make, configure &amp; co if there is any chance
166 that those might be passed to GHC (or to GHC-compiled programs). Relative
167 paths are fine because cygwin tools are happy with them and GHC accepts
168 '/' as path-separator. And relative paths don't depend on where cygwin's
169 root directory is located, or on which partition or network drive your source
170 tree happens to reside, as long as you 'cd' there first.
171 </para></listitem>
172
173 <listitem>
174 <para> If you have to use absolute paths (beware of the innocent-looking
175 <literal>ROOT=`pwd`</literal> in makefile hierarchies or configure scripts), cygwin provides
176 a tool called <command>cygpath</command> that can convert cygwin's unix-style paths to their
177 actual windows-style counterparts. Many cygwin tools actually accept
178 absolute windows-style paths (remember, though, that you either need
179 to escape '\' or convert '\' to '/'), so you should be fine just using those
180 everywhere. If you need to use tools that do some kind of path-mangling
181 that depends on unix-style paths (one fun example is trying to interpret ':'
182 as a separator in path lists..), you can still try to convert paths using
183 <command>cygpath</command> just before they are passed to GHC and friends.
184 </para></listitem>
185
186 <listitem>
187 <para> If you don't have <command>cygpath</command>, you probably don't have cygwin and hence
188 no problems with it... unless you want to write one build process for several
189 platforms. Again, relative paths are your friend, but if you have to use
190 absolute paths, and don't want to use different tools on different platforms,
191 you can simply write a short Haskell program to print the current directory
192 (thanks to George Russell for this idea): compiled with GHC, this will give
193 you the view of the file system that GHC depends on (which will differ
194 depending on whether GHC is compiled with cygwin's gcc or mingw's
195 gcc or on a real unix system..) - that little program can also deal with
196 escaping '\' in paths. Apart from the banner and the startup time,
197 something like this would also do:
198 <programlisting>
199 $ echo "Directory.getCurrentDirectory >>= putStrLn . init . tail . show " | ghci
200 </programlisting>
201 </para></listitem>
202 </itemizedlist>
203 </sect2>
204 </sect1>
205
206
207 <sect1 id="win32-dlls">
208 <title>Building and using Win32 DLLs
209 </title>
210
211 <para>
212 <emphasis>Making Haskell libraries into DLLs doesn't work on Windows at the
213 moment; we hope to re-instate this facility in the future
214 (see <xref linkend="using-shared-libs"/>). Note that
215 building an entire Haskell application as a single DLL is still supported: it's
216 just multi-DLL Haskell programs that don't work. The Windows
217 distribution of GHC contains static libraries only.</emphasis></para>
218
219 <!--
220 <para>
221 <indexterm><primary>Dynamic link libraries, Win32</primary></indexterm>
222 <indexterm><primary>DLLs, Win32</primary></indexterm>
223 On Win32 platforms, the compiler is capable of both producing and using
224 dynamic link libraries (DLLs) containing ghc-compiled code. This
225 section shows you how to make use of this facility.
226 </para>
227
228 <para>
229 Until recently, <command>strip</command> didn't work reliably on DLLs, so you
230 should test your version with care, or make sure you have the latest
231 binutils. Unfortunately, we don't know exactly which version of binutils
232 cured the problem (it was supposedly fixed some years ago).
233 </para>
234
235
236 <sect2 id="win32-dlls-link">
237 <title>Linking with DLLs</title>
238
239 <para>
240 The default on Win32 platforms is to link applications in such a way
241 that the executables will use the Prelude and system libraries DLLs,
242 rather than contain (large chunks of) them. This is transparent at the
243 command-line, so
244 </para>
245
246 <para>
247 <screen>
248 sh$ cat main.hs
249 module Main where
250 main = putStrLn "hello, world!"
251 sh$ ghc -o main main.hs
252 ghc: module version changed to 1; reason: no old .hi file
253 sh$ strip main.exe
254 sh$ ls -l main.exe
255 -rwxr-xr-x 1 544 everyone 4608 May 3 17:11 main.exe*
256 sh$ ./main
257 hello, world!
258 sh$
259 </screen>
260 </para>
261
262 <para>
263 will give you a binary as before, but the <filename>main.exe</filename>
264 generated will use the Prelude and RTS DLLs instead of linking them in
265 statically.
266 </para>
267
268 <para>
269 4K for a <literal>"hello, world"</literal> application&mdash;not bad, huh? :-)
270 </para>
271
272 </sect2>
273
274 <sect2 id="win32-dlls-linking-static">
275 <title>Not linking with DLLs
276 <indexterm><primary>-static option (Win32)</primary></indexterm></title>
277
278 <para>
279 If you want to build an executable that doesn't depend on any
280 ghc-compiled DLLs, use the <option>-static</option> option to link in
281 the code statically.
282 </para>
283
284 <para>
285 Notice that you cannot mix code that has been compiled with
286 <option>-static</option> and not, so you have to use the <option>-static</option>
287 option on all the Haskell modules that make up your application.
288 </para>
289
290 </sect2>
291 -->
292
293 <sect2 id="win32-dlls-create">
294 <title>Creating a DLL</title>
295
296 <para>
297 <indexterm><primary>Creating a Win32 DLL</primary></indexterm>
298 <indexterm><primary>&ndash;shared</primary></indexterm>
299 Sealing up your Haskell library inside a DLL is straightforward;
300 compile up the object files that make up the library, and then build
301 the DLL by issuing a command of the form:
302 </para>
303
304 <para>
305 <screen>
306 ghc &ndash;shared -o foo.dll bar.o baz.o wibble.a -lfooble
307 </screen>
308 </para>
309
310 <para>
311 By feeding the ghc compiler driver the option <option>&ndash;shared</option>, it
312 will build a DLL rather than produce an executable. The DLL will
313 consist of all the object files and archives given on the command
314 line.
315 </para>
316
317 <!--
318 <para>
319 To create a `static' DLL, i.e. one that does not depend on the GHC DLLs,
320 use the <option>-static</option> when compiling up your Haskell code and
321 building the DLL.
322 </para>
323 -->
324
325 <para>
326 A couple of things to notice:
327 </para>
328
329 <para>
330
331 <itemizedlist>
332 <!--
333 <listitem>
334 <para>
335 Since DLLs correspond to packages (see <xref linkend="packages"/>) you need
336 to use <option>-package-name dll-name</option> when compiling modules that
337 belong to a DLL if you're going to call them from Haskell. Otherwise, Haskell
338 code that calls entry points in that DLL will do so incorrectly, and crash.
339 For similar reasons, you can only compile a single module tree into a DLL,
340 as <function>startupHaskell</function> needs to be able to call its
341 initialisation function, and only takes one such argument (see <xref
342 linkend="win32-dlls-foreign"/>). Hence the modules
343 you compile into a DLL must have a common root.
344 </para>
345 </listitem>
346 -->
347
348 <listitem>
349 <para>
350 By default, the entry points of all the object files will be exported from
351 the DLL when using <option>&ndash;shared</option>. Should you want to constrain
352 this, you can specify the <emphasis>module definition file</emphasis> to use
353 on the command line as follows:
354
355 <screen>
356 ghc &ndash;shared -o .... MyDef.def
357 </screen>
358
359 See Microsoft documentation for details, but a module definition file
360 simply lists what entry points you want to export. Here's one that's
361 suitable when building a Haskell COM server DLL:
362
363 <programlisting>
364 EXPORTS
365 DllCanUnloadNow = DllCanUnloadNow@0
366 DllGetClassObject = DllGetClassObject@12
367 DllRegisterServer = DllRegisterServer@0
368 DllUnregisterServer = DllUnregisterServer@0
369 </programlisting>
370 </para>
371 </listitem>
372
373 <listitem>
374 <para>
375 In addition to creating a DLL, the <option>&ndash;shared</option> option also
376 creates an import library. The import library name is derived from the
377 name of the DLL, as follows:
378
379 <programlisting>
380 DLL: HScool.dll ==&#62; import lib: libHScool.dll.a
381 </programlisting>
382
383 The naming scheme may look a bit weird, but it has the purpose of allowing
384 the co-existence of import libraries with ordinary static libraries (e.g.,
385 <filename>libHSfoo.a</filename> and
386 <filename>libHSfoo.dll.a</filename>.
387
388 Additionally, when the compiler driver is linking in non-static mode, it
389 will rewrite occurrence of <option>-lHSfoo</option> on the command line to
390 <option>-lHSfoo.dll</option>. By doing this for you, switching from
391 non-static to static linking is simply a question of adding
392 <option>-static</option> to your command line.
393
394 </para>
395 </listitem>
396 </itemizedlist>
397 </para>
398
399 </sect2>
400
401
402 <sect2 id="win32-dlls-foreign">
403 <title>Making DLLs to be called from other languages</title>
404
405 <para>
406 If you want to package up Haskell code to be called from other languages,
407 such as Visual Basic or C++, there are some extra things it is useful to
408 know. This is a special case of <xref linkend="ffi-library" />; we'll deal with
409 the DLL-specific issues that arise below. Here's an example:
410 </para>
411
412 <itemizedlist>
413
414 <listitem>
415 <para>
416 Use <literal>foreign export</literal> declarations to export the Haskell
417 functions you want to call from the outside. For example,
418
419 <programlisting>
420 module Adder where
421
422 adder :: Int -> Int -> IO Int &ndash;&ndash; gratuitous use of IO
423 adder x y = return (x+y)
424
425 foreign export stdcall adder :: Int -> Int -> IO Int
426 </programlisting>
427 </para>
428 </listitem>
429
430 <listitem>
431 <para>
432 Compile it up:
433
434 <screen>
435 ghc -c adder.hs -fglasgow-exts
436 </screen>
437
438 This will produce two files, adder.o and adder_stub.o
439 </para>
440 </listitem>
441
442 <listitem>
443 <para>
444 compile up a <function>DllMain()</function> that starts up the Haskell
445 RTS-&ndash;&ndash;a possible implementation is:
446
447 <programlisting>
448 #include &lt;windows.h&gt;
449 #include &lt;Rts.h&gt;
450
451 extern void __stginit_Adder(void);
452
453 static char* args[] = { "ghcDll", NULL };
454 /* N.B. argv arrays must end with NULL */
455 BOOL
456 STDCALL
457 DllMain
458 ( HANDLE hModule
459 , DWORD reason
460 , void* reserved
461 )
462 {
463 if (reason == DLL_PROCESS_ATTACH) {
464 /* By now, the RTS DLL should have been hoisted in, but we need to start it up. */
465 startupHaskell(1, args, __stginit_Adder);
466 return TRUE;
467 }
468 return TRUE;
469 }
470 </programlisting>
471
472 Here, <literal>Adder</literal> is the name of the root module in the module
473 tree (as mentioned above, there must be a single root module, and hence a
474 single module tree in the DLL).
475
476 Compile this up:
477
478 <screen>
479 ghc -c dllMain.c
480 </screen>
481 </para>
482 </listitem>
483
484 <listitem>
485 <para>
486 Construct the DLL:
487
488 <screen>
489 ghc &ndash;shared -o adder.dll adder.o adder_stub.o dllMain.o
490 </screen>
491
492 </para>
493 </listitem>
494
495 <listitem>
496 <para>
497 Start using <function>adder</function> from VBA-&ndash;&ndash;here's how I would
498 <constant>Declare</constant> it:
499
500 <programlisting>
501 Private Declare Function adder Lib "adder.dll" Alias "adder@8"
502 (ByVal x As Long, ByVal y As Long) As Long
503 </programlisting>
504
505 Since this Haskell DLL depends on a couple of the DLLs that come with GHC,
506 make sure that they are in scope/visible.
507 </para>
508
509 <para>
510 Building statically linked DLLs is the same as in the previous section: it
511 suffices to add <option>-static</option> to the commands used to compile up
512 the Haskell source and build the DLL.
513 </para>
514
515 </listitem>
516
517 </itemizedlist>
518
519 </sect2>
520
521 <sect2>
522 <title>Beware of DllMain()!</title>
523
524 <para>The body of a <literal>DllMain()</literal> function is an
525 extremely dangerous place! This is because the order in which DLLs are
526 unloaded when a process is terminating is unspecified. This means that
527 the <literal>DllMain()</literal> for your DLL may be called when other DLLs containing
528 functions that you call when de-initializing your DLL have already
529 been unloaded. In other words, you can't put shutdown code inside
530 <literal>DllMain()</literal>, unless your shutdown code only requires use of certain
531 functions which are guaranteed to be available (see the Platform SDK
532 docs for more info).</para>
533
534 <para>In particular, if you are writing a DLL that's statically
535 linked with Haskell, it is not safe to call
536 <literal>hs_exit()</literal> from <literal>DllMain()</literal>, since
537 <literal>hs_exit()</literal> may make use of other DLLs (see also <xref
538 linkend="hs-exit" />). What's more, if you
539 wait until program shutdown to execute your deinitialisation code, Windows will have
540 terminated all the threads in your program except the one calling
541 <literal>DllMain()</literal>, which can cause even more
542 problems.</para>
543
544 <para>A solution is to always export <literal>Begin()</literal> and <literal>End()</literal> functions from your
545 DLL, and call these from the application that uses the DLL, so that
546 you can be sure that all DLLs needed by any shutdown code in your
547 End() function are available when it is called.</para>
548
549 <para>The following example is untested but illustrates the idea (please let us
550 know if you find problems with this example or have a better one). Suppose we have a DLL called Lewis which makes use of 2
551 Haskell modules <literal>Bar</literal> and <literal>Zap</literal>,
552 where <literal>Bar</literal> imports <literal>Zap</literal> and is
553 therefore the root module in the sense of <xref
554 linkend="using-own-main" />. Then the main C++ unit for the DLL would
555 look something like:</para>
556
557 <programlisting>
558 // Lewis.cpp -- compiled using GCC
559 #include &lt;Windows.h&gt;
560 #include "HsFFI.h"
561
562 #define __LEWIS_DLL_EXPORT
563 #include "Lewis.h"
564
565 #include "Bar_stub.h" // generated by GHC
566 #include "Zap_stub.h"
567
568 BOOL APIENTRY DllMain( HANDLE hModule,
569 DWORD ul_reason_for_call,
570 LPVOID lpReserved
571 ){
572 return TRUE;
573 }
574
575 extern "C"{
576
577 LEWIS_API HsBool lewis_Begin(){
578 int argc = ...
579 char *argv[] = ...
580
581 // Initialize Haskell runtime
582 hs_init(&amp;argc, &amp;argv);
583
584 // Tell Haskell about all root modules
585 hs_add_root(__stginit_Bar);
586
587 // do any other initialization here and
588 // return false if there was a problem
589 return HS_BOOL_TRUE;
590 }
591
592 LEWIS_API void lewis_End(){
593 hs_exit();
594 }
595
596 LEWIS_API HsInt lewis_Test(HsInt x){
597 // use Haskell functions exported by
598 // modules Bar and/or Zap
599
600 return ...
601 }
602
603 } // extern "C"
604
605 and some application which used the functions in the DLL would have a main() function like:
606
607 // MyApp.cpp
608 #include "stdafx.h"
609 #include "Lewis.h"
610
611 int main(int argc, char *argv[]){
612 if (lewis_Begin()){
613 // can now safely call other functions
614 // exported by Lewis DLL
615
616 }
617 lewis_End();
618 return 0;
619 }
620 </programlisting>
621
622 <para><literal>Lewis.h</literal> would have to have some appropriate <literal>#ifndef</literal> to ensure that the
623 Haskell FFI types were defined for external users of the DLL (who
624 wouldn't necessarily have GHC installed and therefore wouldn't have
625 the include files like <literal>HsFFI.h</literal> etc).
626 </para>
627 </sect2>
628
629 </sect1>
630 </chapter>
631
632 <!-- Emacs stuff:
633 ;;; Local Variables: ***
634 ;;; mode: xml ***
635 ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") ***
636 ;;; End: ***
637 -->