]> gitweb.factorcode.org Git - factor.git/blob - core/alien/alien-docs.factor
change CALLBACK: to use the ABI of the current LIBRARY: and get rid of STDCALL-CALLBACK:
[factor.git] / core / alien / alien-docs.factor
1 USING: byte-arrays arrays help.syntax help.markup
2 alien.syntax compiler definitions math libc eval
3 debugger parser io io.backend system alien.accessors
4 alien.libraries ;
5 IN: alien
6
7 HELP: alien
8 { $class-description "The class of alien pointers. See " { $link "syntax-aliens" } " for syntax and " { $link "c-data" } " for general information." } ;
9
10 HELP: dll
11 { $class-description "The class of native library handles. See " { $link "syntax-aliens" } " for syntax and " { $link "dll.private" } " for general information." } ;
12
13 HELP: dll-valid? ( dll -- ? )
14 { $values { "dll" dll } { "?" "a boolean" } }
15 { $description "Returns true if the library exists and is loaded." } ;
16
17 HELP: expired?
18 { $values { "c-ptr" c-ptr } { "?" "a boolean" } }
19 { $description "Tests if the alien is a relic from an earlier session. A byte array is never considered to have expired, whereas passing " { $link f } " always yields true." } ;
20
21 HELP: <bad-alien>
22 { $values  { "alien" c-ptr } }
23 { $description "Constructs an invalid alien pointer that has expired." } ;
24
25 HELP: <displaced-alien> ( displacement c-ptr -- alien )
26 { $values { "displacement" "an integer" } { "c-ptr" c-ptr } { "alien" "a new alien" } }
27 { $description "Creates a new alien address object, wrapping a raw memory address. The alien points to a location in memory which is offset by " { $snippet "displacement" } " from the address of " { $snippet "c-ptr" } "." }
28 { $notes "Passing a value of " { $link f } " for " { $snippet "c-ptr" } " creates an alien with an absolute address; this is how " { $link <alien> } " is implemented."
29 $nl
30 "Passing a zero absolute address does not construct a new alien object, but instead makes the word output " { $link f } "." } ;
31
32 { <alien> <displaced-alien> alien-address } related-words
33
34 HELP: alien-address ( c-ptr -- addr )
35 { $values { "c-ptr" c-ptr } { "addr" "a non-negative integer" } }
36 { $description "Outputs the address of an alien." }
37 { $notes "Taking the address of a " { $link byte-array } " is explicitly prohibited since byte arrays can be moved by the garbage collector between the time the address is taken, and when it is accessed. If you need to pass pointers to C functions which will persist across alien calls, you must allocate unmanaged memory instead. See " { $link "malloc" } "." } ;
38
39 HELP: <alien>
40 { $values { "address" "a non-negative integer" } { "alien" "a new alien address" } }
41 { $description "Creates an alien object, wrapping a raw memory address." }
42 { $notes "Alien objects are invalidated between image saves and loads." } ;
43
44 HELP: c-ptr
45 { $class-description "Class of objects consisting of aliens, byte arrays and " { $link f } ". These objects can convert to pointer C types, which are all aliases of " { $snippet "void*" } "." } ;
46
47 HELP: alien-invoke
48 { $values { "..." "zero or more objects passed to the C function" } { "return" "a C return type" } { "library" "a logical library name" } { "function" "a C function name" } { "parameters" "a sequence of C parameter types" } }
49 { $description "Calls a C library function with the given name. Input parameters are taken from the data stack, and the return value is pushed on the data stack after the function returns. A return type of " { $snippet "\"void\"" } " indicates that no value is to be expected." }
50 { $notes "C type names are documented in " { $link "c-types-specs" } "." }
51 { $errors "Throws an " { $link alien-invoke-error } " if the word calling " { $link alien-invoke } " was not compiled with the optimizing compiler." } ;
52
53 HELP: alien-indirect-error
54 { $error-description "Thrown if the word calling " { $link alien-indirect } " was not compiled with the optimizing compiler. This may be a result of one of several failure conditions:"
55     { $list
56         { "This can happen when experimenting with " { $link alien-indirect } " in this listener. To fix the problem, place the " { $link alien-indirect } " call in a word; word definitions are automatically compiled with the optimizing compiler." }
57         { "The return type or parameter list references an unknown C type." }
58         { "One of the three inputs to " { $link alien-indirect } " is not a literal value." }
59     }
60 } ;
61
62 HELP: alien-indirect
63 { $values { "..." "zero or more objects passed to the C function" } { "funcptr" "a C function pointer" } { "return" "a C return type" } { "parameters" "a sequence of C parameter types" } { "abi" "one of " { $snippet "\"cdecl\"" } " or " { $snippet "\"stdcall\"" } } }
64 { $description
65     "Invokes a C function pointer passed on the data stack. Input parameters are taken from the data stack following the function pointer, and the return value is pushed on the data stack after the function returns. A return type of " { $snippet "\"void\"" } " indicates that no value is to be expected."
66 }
67 { $notes "C type names are documented in " { $link "c-types-specs" } "." }
68 { $errors "Throws an " { $link alien-indirect-error } " if the word calling " { $link alien-indirect } " is not compiled." } ;
69
70 HELP: alien-callback-error
71 { $error-description "Thrown if the word calling " { $link alien-callback } " was not compiled with the optimizing compiler. This may be a result of one of several failure conditions:"
72     { $list
73         { "This can happen when experimenting with " { $link alien-callback } " in this listener. To fix the problem, place the " { $link alien-callback } " call in a word; word definitions are automatically compiled with the optimizing compiler." }
74         { "The return type or parameter list references an unknown C type." }
75         { "One of the four inputs to " { $link alien-callback } " is not a literal value." }
76     }
77 } ;
78
79 HELP: alien-callback
80 { $values { "return" "a C return type" } { "parameters" "a sequence of C parameter types" } { "abi" "one of " { $snippet "\"cdecl\"" } " or " { $snippet "\"stdcall\"" } } { "quot" "a quotation" } { "alien" alien } }
81 { $description
82     "Defines a callback from C to Factor which accepts the given set of parameters from the C caller, pushes them on the data stack, calls the quotation, and passes a return value back to the C caller. A return type of " { $snippet "\"void\"" } " indicates that no value is to be returned."
83     $nl
84     "When a compiled reference to this word is called, it pushes the callback's alien address on the data stack. This address can be passed to any C function expecting a C function pointer with the correct signature. The callback is actually generated when the word calling " { $link alien-callback } " is compiled."
85     $nl
86     "Callback quotations run with freshly-allocated stacks. This means the data stack contains the values passed by the C function, and nothing else. It also means that if the callback throws an error which is not caught, the Factor runtime will halt. See " { $link "errors" } " for error handling options."
87 }
88 { $notes "C type names are documented in " { $link "c-types-specs" } "." }
89 { $examples
90     "A simple example, showing a C function which returns the difference of two given integers:"
91     { $code
92         ": difference-callback ( -- alien )"
93         "    \"int\" { \"int\" \"int\" } \"cdecl\" [ - ] alien-callback ;"
94     }
95 }
96 { $errors "Throws an " { $link alien-callback-error } " if the word calling " { $link alien-callback } " is not compiled." } ;
97
98 { alien-invoke alien-indirect alien-callback } related-words
99
100 ARTICLE: "alien-expiry" "Alien expiry"
101 "When an image is loaded, any alien objects which persisted from the previous session are marked as having expired. This is because the C pointers they contain are almost certainly no longer valid."
102 $nl
103 "For this reason, the " { $link POSTPONE: ALIEN: } " word should not be used in source files, since loading the source file then saving the image will result in the literal becoming expired. Use " { $link <alien> } " instead, and ensure the word calling " { $link <alien> } " is not declared " { $link POSTPONE: flushable } "."
104 { $subsection expired? } ;
105
106 ARTICLE: "aliens" "Alien addresses"
107 "Instances of the " { $link alien } " class represent pointers to C data outside the Factor heap:"
108 { $subsection <alien> }
109 { $subsection <displaced-alien> }
110 { $subsection alien-address }
111 "Anywhere that a " { $link alien } " instance is accepted, the " { $link f } " singleton may be passed in to denote a null pointer."
112 $nl
113 "Usually alien objects do not have to created and dereferenced directly; instead declaring C function parameters and return values as having a pointer type such as " { $snippet "void*" } " takes care of the details."
114 { $subsection "syntax-aliens" }
115 { $subsection "alien-expiry" }
116 "When higher-level abstractions won't do:"
117 { $subsection "reading-writing-memory" }
118 { $see-also "c-data" "c-types-specs" } ;
119
120 ARTICLE: "reading-writing-memory" "Reading and writing memory directly"
121 "Numerical values can be read from memory addresses and converted to Factor objects using the various typed memory accessor words:"
122 { $subsection alien-signed-1 }
123 { $subsection alien-unsigned-1 }
124 { $subsection alien-signed-2 }
125 { $subsection alien-unsigned-2 }
126 { $subsection alien-signed-4 }
127 { $subsection alien-unsigned-4 }
128 { $subsection alien-signed-cell }
129 { $subsection alien-unsigned-cell }
130 { $subsection alien-signed-8 }
131 { $subsection alien-unsigned-8 }
132 { $subsection alien-float }
133 { $subsection alien-double }
134 "Factor numbers can also be converted to C values and stored to memory:"
135 { $subsection set-alien-signed-1 }
136 { $subsection set-alien-unsigned-1 }
137 { $subsection set-alien-signed-2 }
138 { $subsection set-alien-unsigned-2 }
139 { $subsection set-alien-signed-4 }
140 { $subsection set-alien-unsigned-4 }
141 { $subsection set-alien-signed-cell }
142 { $subsection set-alien-unsigned-cell }
143 { $subsection set-alien-signed-8 }
144 { $subsection set-alien-unsigned-8 }
145 { $subsection set-alien-float }
146 { $subsection set-alien-double } ;
147
148 ARTICLE: "alien-invoke" "Calling C from Factor"
149 "The easiest way to call into a C library is to define bindings using a pair of parsing words:"
150 { $subsection POSTPONE: LIBRARY: }
151 { $subsection POSTPONE: FUNCTION: }
152 "The above parsing words create word definitions which call a lower-level word; you can use it directly, too:"
153 { $subsection alien-invoke }
154 "Sometimes it is necessary to invoke a C function pointer, rather than a named C function:"
155 { $subsection alien-indirect }
156 "There are some details concerning the conversion of Factor objects to C values, and vice versa. See " { $link "c-data" } "." ;
157
158 HELP: alien-invoke-error
159 { $error-description "Thrown if the word calling " { $link alien-invoke } " was not compiled with the optimizing compiler. This may be a result of one of several failure conditions:"
160     { $list
161         { "This can happen when experimenting with " { $link alien-invoke } " in this listener. To fix the problem, place the " { $link alien-invoke } " call in a word; word definitions are automatically compiled with the optimizing compiler." }
162         { "The return type or parameter list references an unknown C type." }
163         { "The symbol or library could not be found." }
164         { "One of the four inputs to " { $link alien-invoke } " is not a literal value. To call functions which are not known at compile-time, use " { $link alien-indirect } "." }
165     }
166 } ;
167
168 ARTICLE: "alien-callback-gc" "Callbacks and code GC"
169 "A callback consits of two parts; the callback word, which pushes the address of the callback on the stack when executed, and the callback body itself. If the callback word is redefined, removed from the dictionary using " { $link forget } ", or recompiled, the callback body will not be reclaimed by the garbage collector, since potentially C code may be holding a reference to the callback body."
170 $nl
171 "This is the safest approach, however it can lead to code heap leaks when repeatedly reloading code which defines callbacks. If you are " { $emphasis "completely sure" } " that no running C code is holding a reference to any callbacks, you can blow them all away:"
172 { $code "USE: alien callbacks get clear-hash gc" }
173 "This will reclaim all callback bodies which are otherwise unreachable from the dictionary (that is, their associated callback words have since been redefined, recompiled or forgotten)." ;
174
175 ARTICLE: "alien-callback" "Calling Factor from C"
176 "Callbacks can be defined and passed to C code as function pointers; the C code can then invoke the callback and run Factor code:"
177 { $subsection alien-callback }
178 { $subsection POSTPONE: CALLBACK: }
179 "There are some caveats concerning the conversion of Factor objects to C values, and vice versa. See " { $link "c-data" } "."
180 { $subsection "alien-callback-gc" }
181 { $see-also "byte-arrays-gc" } ;
182
183 ARTICLE: "dll.private" "DLL handles"
184 "DLL handles are a built-in class of objects which represent loaded native libraries. DLL handles are instances of the " { $link dll } " class, and have a literal syntax used for debugging prinouts; see " { $link "syntax-aliens" } "."
185 $nl
186 "Usually one never has to deal with DLL handles directly; the C library interface creates them as required. However if direct access to these operating system facilities is required, the following primitives can be used:"
187 { $subsection dlopen }
188 { $subsection dlsym }
189 { $subsection dlclose }
190 { $subsection dll-valid? } ;
191
192 ARTICLE: "embedding-api" "Factor embedding API"
193 "The Factor embedding API is defined in " { $snippet "vm/master.h" } "."
194 $nl
195 "The " { $snippet "F_CHAR" } " type is an alias for the character type used for path names by the operating system; " { $snippet "char" } " on Unix and " { $snippet "wchar_t" } " on Windows."
196 $nl
197 "Including this header file into a C compilation unit will declare the following functions:"
198 { $table
199     { {
200         { $code "void init_factor_from_args("
201             "    F_CHAR *image, int argc, F_CHAR **argv, bool embedded"
202             ")" }
203         "Initializes Factor."
204         $nl
205         "If " { $snippet "image" } " is " { $snippet "NULL" } ", Factor will load an image file whose name is obtained by suffixing the executable name with " { $snippet ".image" } "."
206         $nl
207         "The " { $snippet "argc" } " and " { $snippet "argv" } " parameters are interpreted just like normal command line arguments when running Factor stand-alone; see " { $link "cli" } "."
208         $nl
209         "The " { $snippet "embedded" } " flag ensures that this function returns as soon as Factor has been initialized. Otherwise, Factor will start up normally."
210     } }
211     { {
212         { $code "char *factor_eval_string(char *string)" }
213         "Evaluates a piece of code in the embedded Factor instance by passing the string to " { $link eval>string } " and returning the result. The result must be explicitly freed by a call to " { $snippet "factor_eval_free" } "."
214     } }
215     { {
216         { $code "void factor_eval_free(char *result)" }
217         "Frees a string returned by " { $snippet "factor_eval_string()" } "."
218     } }
219     { {
220         { $code "void factor_yield(void)" }
221         "Gives all Factor threads a chance to run."
222     } }
223     { {
224         { $code "void factor_sleep(long us)" }
225         "Gives all Factor threads a chance to run for " { $snippet "us" } " microseconds."
226     } }
227 } ;
228
229 ARTICLE: "embedding-restrictions" "Embedding API restrictions" 
230 "The Factor VM is not thread safe, and does not support multiple instances. There must only be one Factor instance per process, and this instance must be consistently accessed from the same thread for its entire lifetime. Once initialized, a Factor instance cannot be destroyed other than by exiting the process." ;
231
232 ARTICLE: "embedding-factor" "What embedding looks like from Factor"
233 "Factor code will run inside an embedded instance in the same way it would run in a stand-alone instance."
234 $nl
235 "One exception is that the global " { $link input-stream } " and " { $link output-stream } " streams are not bound by default, to avoid conflicting with any I/O the host process might perform. The " { $link init-stdio } " words must be called explicitly to initialize terminal streams."
236 $nl
237 "There is a word which can detect when Factor is embedded:"
238 { $subsection embedded? }
239 "No special support is provided for calling out from Factor into the owner process. The C library inteface works fine for this task - see " { $link "alien" } "." ;
240
241 ARTICLE: "embedding" "Embedding Factor into C applications"
242 "The Factor " { $snippet "Makefile" } " builds the Factor VM both as an executable and a library. The library can be used by other applications. File names for the library on various operating systems:"
243 { $table
244     { "OS" "Library name" "Shared?" }
245     { "Windows XP/Vista" { $snippet "factor.dll" } "Yes" }
246     ! { "Windows CE" { $snippet "factor-ce.dll" } "Yes" }
247     { "Mac OS X" { $snippet "libfactor.dylib" } "Yes" }
248     { "Other Unix" { $snippet "libfactor.a" } "No" }
249 }
250 "An image file must be supplied; a minimal image can be built, however the compiler must be included for the embedding API to work (see " { $link "bootstrap-cli-args" } ")."
251 { $subsection "embedding-api" }
252 { $subsection "embedding-factor" }
253 { $subsection "embedding-restrictions" } ;
254
255 ARTICLE: "alien" "C library interface"
256 "Factor can directly call C functions in native libraries. It is also possible to compile callbacks which run Factor code, and pass them to native libraries as function pointers."
257 $nl
258 "The C library interface is entirely self-contained; there is no C code which one must write in order to wrap a library."
259 $nl
260 "C library interface words are found in the " { $vocab-link "alien" } " vocabulary and its subvocabularies."
261 { $warning "C does not perform runtime type checking, automatic memory management or array bounds checks. Incorrect usage of C library functions can lead to crashes, data corruption, and security exploits." }
262 { $subsection "loading-libs" }
263 { $subsection "alien-invoke" }
264 { $subsection "alien-callback" }
265 { $subsection "c-data" }
266 { $subsection "classes.struct" }
267 { $subsection "dll.private" }
268 { $subsection "embedding" } ;
269
270 ABOUT: "alien"