]> gitweb.factorcode.org Git - factor.git/blob - core/alien/alien-docs.factor
Reformat
[factor.git] / core / alien / alien-docs.factor
1 USING: alien.accessors alien.c-types alien.libraries
2 alien.strings alien.syntax byte-arrays cpu.x86 eval help.markup
3 help.syntax io io.backend io.encodings.utf16 io.encodings.utf8
4 kernel math quotations sequences system ;
5 IN: alien
6
7 HELP: callee-cleanup?
8 { $values { "abi" abi } { "?" boolean } }
9 { $description { $link t } " if the calling convention is callee cleanup." } ;
10
11 HELP: cdecl
12 { $description "This symbol is passed as the " { $snippet "abi" } " argument to " { $link alien-indirect } ", " { $link alien-callback } ", " { $link alien-assembly } ", and " { $link add-library } " to indicate that the standard C calling convention should be used, where the caller cleans up the stack frame after calling the function." } ;
13
14 HELP: callsite-not-compiled
15 { $error-description "Thrown if the word calling the given word was not compiled with the optimizing compiler. This can happen when experimenting with the word in this listener. To fix the problem, place the word call in a word; word definitions are automatically compiled with the optimizing compiler. Only a few words relating to calling FFI functions throws this error." } ;
16
17 HELP: stdcall
18 { $description "This symbol is passed as the " { $snippet "abi" } " argument to " { $link alien-indirect } ", " { $link alien-callback } ", " { $link alien-assembly } ", and " { $link add-library } " to indicate that the Windows API calling convention should be used, where the called function cleans up its own stack frame before returning to the caller." } ;
19
20 HELP: fastcall
21 { $warning "In the current implementation this ABI only works for functions that take only integer and pointer arguments." }
22 { $description "This symbol is passed as the " { $snippet "abi" } " argument to " { $link alien-indirect } ", " { $link alien-callback } ", " { $link alien-assembly } ", and " { $link add-library } " to indicate that the \"fast call\" calling convention should be used, where the first two integer or pointer arguments are passed in registers and the function cleans up its own stack frame before returning to the caller." } ;
23
24 HELP: thiscall
25 { $description "This symbol is passed as the " { $snippet "abi" } " argument to " { $link alien-indirect } ", " { $link alien-callback } ", " { $link alien-assembly } ", and " { $link add-library } " to indicate that Microsoft Visual C++ calling convention should be used, where the first argument (which must be a \"this\" pointer) is passed in a register and the function cleans up its own stack frame before returning to the caller." } ;
26
27 HELP: mingw
28 { $description "This symbol is passed as the " { $snippet "abi" } " argument to " { $link alien-indirect } ", " { $link alien-callback } ", " { $link alien-assembly } ", and " { $link add-library } " to indicate that MinGW calling convention should be used." } ;
29
30 { cdecl stdcall fastcall thiscall mingw } related-words
31
32 HELP: >c-ptr
33 { $values { "obj" object } { "c-ptr" c-ptr } }
34 { $contract "Outputs a pointer to the binary data of this object." } ;
35
36 HELP: byte-length
37 { $values { "obj" object } { "n" "a non-negative integer" } }
38 { $contract "Outputs the number of bytes of binary data that will be output by " { $link >c-ptr } "." } ;
39
40 HELP: element-size
41 { $values { "seq" sequence } { "n" "a non-negative integer" } }
42 { $contract "Outputs the number of bytes used for each element of the sequence." }
43 { $notes "If a sequence class implements " { $link element-size } " and " { $link >c-ptr } ", then instances of this sequence, as well as slices of this sequence, can be used as binary objects." } ;
44
45 { >c-ptr element-size byte-length } related-words
46
47 HELP: alien
48 { $class-description "The class of alien pointers. See " { $link "syntax-aliens" } " for syntax and " { $link "c-data" } " for general information." } ;
49
50 HELP: dll
51 { $class-description "The class of native library handles. See " { $link "syntax-aliens" } " for syntax and " { $link "dll.private" } " for general information."
52 $nl
53 "The dll tuple has one slot 'path' which holds the filesystem path to the library being loaded in the systems " { $link native-string-encoding } ", usually " { $link utf8 } " on unices and " { $link utf16n } " on windows." } ;
54
55 HELP: dll-valid?
56 { $values { "dll" dll } { "?" boolean } }
57 { $description "Returns true if the library exists and is loaded." } ;
58
59 HELP: expired?
60 { $values { "c-ptr" c-ptr } { "?" boolean } }
61 { $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." } ;
62
63 HELP: <bad-alien>
64 { $values { "alien" c-ptr } }
65 { $description "Constructs an invalid alien pointer that has expired." } ;
66
67 HELP: <displaced-alien>
68 { $values { "displacement" integer } { "c-ptr" c-ptr } { "alien" "a new alien" } }
69 { $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" } "." }
70 { $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."
71 $nl
72 "Passing a zero absolute address does not construct a new alien object, but instead makes the word output " { $link f } "." } ;
73
74 { <alien> <displaced-alien> alien-address } related-words
75
76 HELP: free-callback
77 { $values { "alien" alien } }
78 { $description "Releases the callback heap memory allocated for an alien callback." }
79 { $warning "If the callback is invoked (either from C or Factor) after it has been freed, then Factor may crash." } ;
80
81 HELP: with-callback
82 { $values { "alien" alien } { "quot" quotation } }
83 { $description "Calls the quotation with an alien value on the stack which is supposed to be a callback. Resources for the callback is guaranteed to be released afterwards." } ;
84
85 { <callback> free-callback unregister-and-free-callback with-callback } related-words
86
87 HELP: alien-address
88 { $values { "c-ptr" c-ptr } { "addr" "a non-negative integer" } }
89 { $description "Outputs the address of an alien." }
90 { $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" } "." } ;
91
92 HELP: <alien>
93 { $values { "address" "a non-negative integer" } { "alien" "a new alien address" } }
94 { $description "Creates an alien object, wrapping a raw memory address." }
95 { $notes "Alien objects are invalidated between image saves and loads." } ;
96
97 HELP: c-ptr
98 { $class-description "Class of objects consisting of aliens, byte arrays and " { $link f } ". These objects all can be used as values of " { $link pointer } " C types." } ;
99
100 HELP: alien-invoke
101 { $values { "args..." "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" } { "varargs?" boolean } { "return..." "the return value of the function, if not " { $link void } } }
102 { $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 " { $link void } " indicates that no value is to be expected." }
103 { $notes "C type names are documented in " { $link "c-types-specs" } "." }
104 { $errors "Throws an " { $link callsite-not-compiled } " if the word calling " { $link alien-invoke } " was not compiled with the optimizing compiler." } ;
105
106 HELP: alien-indirect
107 { $values { "args..." "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 " { $link cdecl } " or " { $link stdcall } } { "return..." "the return value of the function, if not " { $link void } } }
108 { $description
109     "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 " { $link void } " indicates that no value is to be expected."
110 }
111 { $notes "C type names are documented in " { $link "c-types-specs" } "." }
112 { $errors "Throws an " { $link callsite-not-compiled } " if the word calling " { $link alien-indirect } " is not compiled." } ;
113
114 HELP: alien-callback
115 { $values { "return" "a C return type" } { "parameters" "a sequence of C parameter types" } { "abi" "one of " { $link cdecl } " or " { $link stdcall } } { "quot" quotation } { "alien" alien } }
116 { $description
117     "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."
118     $nl
119     "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."
120     $nl
121     "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."
122 }
123 { $notes "C type names are documented in " { $link "c-types-specs" } "." }
124 { $examples
125     "A simple example, showing a C function which returns the difference of two given integers:"
126     { $code
127         ": difference-callback ( -- alien )"
128         "    int { int int } cdecl [ - ] alien-callback ;"
129     }
130 }
131 { $errors "Throws an " { $link callsite-not-compiled } " if the word calling " { $link alien-callback } " is not compiled." } ;
132
133 HELP: alien-assembly
134 { $values { "args..." "zero or more objects passed to the C function" } { "return" "a C return type" } { "parameters" "a sequence of C parameter types" } { "abi" "one of " { $link cdecl } " or " { $link stdcall } } { "quot" quotation } { "return..." "the return value of the function, if not " { $link void } } }
135 { $description
136     "Invokes arbitrary machine code, generated at compile-time by the quotation. 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 " { $link void } " indicates that no value is to be expected."
137     $nl
138     "The quotation passed to this word must preserve the " { $link ds-reg } " and " { $link rs-reg } " registers. Note that this is not a " { $snippet "call" } " in the assembly sense, so there is no return address on the stack."
139     $nl
140     "It's important to mind the ABI. For instance, on x86.32, parameters are passed on the stack in " { $snippet "ESP" } ", while on x86.64 arguments are passed in " { $snippet "RDI" } ", " { $snippet "RSI" } ", " { $snippet "RDX" } ", and " { $snippet "RCX" } ", and then on the stack. On Windows 64, integers and pointers are passed in " { $snippet "RCX" } ", " { $snippet "RDX" } ", " { $snippet "R8" } ", and " { $snippet "R9" } "."
141     $nl
142     "There are Factor words for the input parameters, such as " { $snippet "param-reg-0" } " and " { $snippet "param-reg-1" } "."
143     $nl
144     "For output parameters, use " { $link return-reg } "."
145     $nl
146 }
147 { $notes "C type names are documented in " { $link "c-types-specs" } "." }
148 { $errors "Throws an " { $link callsite-not-compiled } " if the word calling " { $link alien-assembly } " is not compiled." } ;
149
150 { alien-invoke alien-indirect alien-assembly alien-callback } related-words
151
152 ARTICLE: "alien-expiry" "Alien expiry"
153 "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."
154 $nl
155 "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 } "."
156 { $subsections expired? } ;
157
158 ARTICLE: "aliens" "Alien addresses"
159 "Instances of the " { $link alien } " class represent pointers to C data outside the Factor heap:"
160 { $subsections
161     <alien>
162     <displaced-alien>
163     alien-address
164 }
165 "Anywhere that an " { $link alien } " instance is accepted, the " { $link f } " singleton may be passed in to denote a null pointer."
166 $nl
167 "Usually alien objects do not have to be created and dereferenced directly; instead declaring C function parameters and return values as having a " { $link pointer } " type such as " { $snippet "void*" } " takes care of the details."
168 { $subsections
169     "syntax-aliens"
170     "alien-expiry"
171 }
172 "When higher-level abstractions won't do:"
173 { $subsections "reading-writing-memory" }
174 { $see-also "c-data" "c-types-specs" } ;
175
176 ARTICLE: "reading-writing-memory" "Reading and writing memory directly"
177 "Numerical values can be read from memory addresses and converted to Factor objects using the various typed memory accessor words:"
178 { $subsections
179     alien-signed-1
180     alien-unsigned-1
181     alien-signed-2
182     alien-unsigned-2
183     alien-signed-4
184     alien-unsigned-4
185     alien-signed-cell
186     alien-unsigned-cell
187     alien-signed-8
188     alien-unsigned-8
189     alien-float
190     alien-double
191 }
192 "Factor numbers can also be converted to C values and stored to memory:"
193 { $subsections
194     set-alien-signed-1
195     set-alien-unsigned-1
196     set-alien-signed-2
197     set-alien-unsigned-2
198     set-alien-signed-4
199     set-alien-unsigned-4
200     set-alien-signed-cell
201     set-alien-unsigned-cell
202     set-alien-signed-8
203     set-alien-unsigned-8
204     set-alien-float
205     set-alien-double
206 } ;
207
208 ARTICLE: "alien-invoke" "Calling C from Factor"
209 "The easiest way to call into a C library is to define bindings using a pair of parsing words:"
210 { $subsections
211     POSTPONE: LIBRARY:
212     POSTPONE: FUNCTION:
213     POSTPONE: FUNCTION-ALIAS:
214 }
215 "The above parsing words create word definitions which call a lower-level word; you can use it directly, too:"
216 { $subsections alien-invoke }
217 "Sometimes it is necessary to invoke a C function pointer, rather than a named C function:"
218 { $subsections alien-indirect }
219 "There are some details concerning the conversion of Factor objects to C values, and vice versa. See " { $link "c-data" } "." ;
220
221 ARTICLE: "alien-callback" "Calling Factor from C"
222 "Callbacks can be defined and passed to C code as function pointers; the C code can then invoke the callback and run Factor code:"
223 { $subsections
224     alien-callback
225     POSTPONE: CALLBACK:
226 }
227 "There are some caveats concerning the conversion of Factor objects to C values, and vice versa. See " { $link "c-data" } "."
228 { $see-also "byte-arrays-gc" } ;
229
230 ARTICLE: "alien-globals" "Accessing C global variables"
231 "The " { $vocab-link "alien.syntax" } " vocabulary defines two parsing words for accessing the value of a global variable, and get the address of a global variable, respectively."
232 { $subsections
233     POSTPONE: C-GLOBAL:
234     POSTPONE: &:
235 } ;
236
237 ARTICLE: "alien-assembly" "Calling arbitrary assembly code"
238 "It is possible to write a word whose body consists of arbitrary assembly code. The assembly receives parameters and returns values as per the platform's ABI; marshalling and unmarshalling Factor values is taken care of by the C library interface, as with " { $link alien-invoke } "."
239 $nl
240 "Assembler opcodes are defined in CPU-specific vocabularies:"
241 { $list
242     { $vocab-link "cpu.arm.assembler" }
243     { $vocab-link "cpu.ppc.assembler" }
244     { $vocab-link "cpu.x86.assembler" }
245 }
246 "The combinator for generating arbitrary assembly by calling a quotation at compile time:"
247 { $subsection alien-assembly } ;
248
249 ARTICLE: "dll.private" "DLL handles"
250 "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 printouts; see " { $link "syntax-aliens" } "."
251 $nl
252 "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:"
253 { $subsections
254     dlopen
255     dlsym
256     dlclose
257     dll-valid?
258 } ;
259
260 ARTICLE: "embedding-api" "Factor embedding API"
261 "The Factor embedding API is defined in " { $snippet "vm/master.h" } "."
262 $nl
263 "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."
264 $nl
265 "Including this header file into a C compilation unit will declare the following functions:"
266 { $table
267     { {
268         { $code "void init_factor_from_args("
269             "    F_CHAR *image, int argc, F_CHAR **argv, bool embedded"
270             ")" }
271         "Initializes Factor."
272         $nl
273         "If " { $snippet "image" } " is " { $snippet "NULL" } ", Factor will load an image file whose name is obtained by suffixing the executable name with " { $snippet ".image" } "."
274         $nl
275         "The " { $snippet "argc" } " and " { $snippet "argv" } " parameters are interpreted just like normal command line arguments when running Factor stand-alone; see " { $link "command-line" } "."
276         $nl
277         "The " { $snippet "embedded" } " flag ensures that this function returns as soon as Factor has been initialized. Otherwise, Factor will start up normally."
278     } }
279     { {
280         { $code "char *factor_eval_string(char *string)" }
281         "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" } "."
282     } }
283     { {
284         { $code "void factor_eval_free(char *result)" }
285         "Frees a string returned by " { $snippet "factor_eval_string()" } "."
286     } }
287     { {
288         { $code "void factor_yield(void)" }
289         "Gives all Factor threads a chance to run."
290     } }
291     { {
292         { $code "void factor_sleep(long us)" }
293         "Gives all Factor threads a chance to run for " { $snippet "us" } " microseconds."
294     } }
295 } ;
296
297 ARTICLE: "embedding-restrictions" "Embedding API restrictions"
298 "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." ;
299
300 ARTICLE: "embedding-factor" "What embedding looks like from Factor"
301 "Factor code will run inside an embedded instance in the same way it would run in a stand-alone instance."
302 $nl
303 "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."
304 $nl
305 "There is a word which can detect when Factor is embedded:"
306 { $subsections embedded? }
307 "No special support is provided for calling out from Factor into the owner process. The C library interface works fine for this task - see " { $link "alien" } "." ;
308
309 ARTICLE: "embedding" "Embedding Factor into C applications"
310 "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:"
311 { $table
312     { { $strong "OS" } { $strong "Library name" } { $strong "Shared?" } }
313     { "Windows XP/Vista" { $snippet "factor.dll" } "Yes" }
314     { "Mac OS X" { $snippet "libfactor.dylib" } "Yes" }
315     { "Other Unix" { $snippet "libfactor.a" } "No" }
316 }
317 "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" } ")."
318 { $subsections
319     "embedding-api"
320     "embedding-factor"
321     "embedding-restrictions"
322 } ;
323
324 ARTICLE: "alien" "C library interface"
325 "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."
326 $nl
327 "The C library interface is entirely self-contained; there is no C code which one must write in order to wrap a library."
328 $nl
329 "C library interface words are found in the " { $vocab-link "alien" } " vocabulary and its subvocabularies."
330 { $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." }
331 { $subsections
332     "loading-libs"
333     "alien-invoke"
334     "alien-callback"
335     "c-data"
336     "classes.struct"
337     "alien-globals"
338     "alien-assembly"
339     "dll.private"
340     "embedding"
341 } ;
342
343 ABOUT: "alien"