]> gitweb.factorcode.org Git - factor.git/blob - core/alien/alien-docs.factor
60c1cdaf69dc3a623e79f2bf79c7dc5688e260f0
[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 alien.c-types quotations kernel ;
5 IN: alien
6
7 HELP: >c-ptr
8 { $values { "object" object } { "c-ptr" c-ptr } }
9 { $contract "Outputs a pointer to the binary data of this object." } ;
10
11 HELP: byte-length
12 { $values { "object" object } { "n" "a non-negative integer" } }
13 { $contract "Outputs the number of bytes of binary data that will be output by " { $link >c-ptr } "." } ;
14
15 { >c-ptr byte-length } related-words
16
17 HELP: alien
18 { $class-description "The class of alien pointers. See " { $link "syntax-aliens" } " for syntax and " { $link "c-data" } " for general information." } ;
19
20 HELP: dll
21 { $class-description "The class of native library handles. See " { $link "syntax-aliens" } " for syntax and " { $link "dll.private" } " for general information." } ;
22
23 HELP: dll-valid? ( dll -- ? )
24 { $values { "dll" dll } { "?" "a boolean" } }
25 { $description "Returns true if the library exists and is loaded." } ;
26
27 HELP: expired?
28 { $values { "c-ptr" c-ptr } { "?" "a boolean" } }
29 { $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." } ;
30
31 HELP: <bad-alien>
32 { $values  { "alien" c-ptr } }
33 { $description "Constructs an invalid alien pointer that has expired." } ;
34
35 HELP: <displaced-alien> ( displacement c-ptr -- alien )
36 { $values { "displacement" "an integer" } { "c-ptr" c-ptr } { "alien" "a new alien" } }
37 { $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" } "." }
38 { $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."
39 $nl
40 "Passing a zero absolute address does not construct a new alien object, but instead makes the word output " { $link f } "." } ;
41
42 { <alien> <displaced-alien> alien-address } related-words
43
44 HELP: alien-address ( c-ptr -- addr )
45 { $values { "c-ptr" c-ptr } { "addr" "a non-negative integer" } }
46 { $description "Outputs the address of an alien." }
47 { $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" } "." } ;
48
49 HELP: <alien>
50 { $values { "address" "a non-negative integer" } { "alien" "a new alien address" } }
51 { $description "Creates an alien object, wrapping a raw memory address." }
52 { $notes "Alien objects are invalidated between image saves and loads." } ;
53
54 HELP: c-ptr
55 { $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." } ;
56
57 HELP: alien-invoke-error
58 { $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:"
59     { $list
60         { "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." }
61         { "The return type or parameter list references an unknown C type." }
62         { "The symbol or library could not be found." }
63         { "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 } "." }
64     }
65 } ;
66
67 HELP: alien-invoke
68 { $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" } }
69 { $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." }
70 { $notes "C type names are documented in " { $link "c-types-specs" } "." }
71 { $errors "Throws an " { $link alien-invoke-error } " if the word calling " { $link alien-invoke } " was not compiled with the optimizing compiler." } ;
72
73 HELP: alien-indirect-error
74 { $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 two failure conditions:"
75     { $list
76         { "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." }
77         { "One of the three inputs to " { $link alien-indirect } " is not a literal value." }
78     }
79 } ;
80
81 HELP: alien-indirect
82 { $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\"" } } }
83 { $description
84     "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."
85 }
86 { $notes "C type names are documented in " { $link "c-types-specs" } "." }
87 { $errors "Throws an " { $link alien-indirect-error } " if the word calling " { $link alien-indirect } " is not compiled." } ;
88
89 HELP: alien-callback-error
90 { $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 two failure conditions:"
91     { $list
92         { "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." }
93         { "One of the four inputs to " { $link alien-callback } " is not a literal value." }
94     }
95 } ;
96
97 HELP: alien-callback
98 { $values { "return" "a C return type" } { "parameters" "a sequence of C parameter types" } { "abi" "one of " { $snippet "\"cdecl\"" } " or " { $snippet "\"stdcall\"" } } { "quot" quotation } { "alien" alien } }
99 { $description
100     "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."
101     $nl
102     "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."
103     $nl
104     "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."
105 }
106 { $notes "C type names are documented in " { $link "c-types-specs" } "." }
107 { $examples
108     "A simple example, showing a C function which returns the difference of two given integers:"
109     { $code
110         ": difference-callback ( -- alien )"
111         "    int { int int } \"cdecl\" [ - ] alien-callback ;"
112     }
113 }
114 { $errors "Throws an " { $link alien-callback-error } " if the word calling " { $link alien-callback } " is not compiled." } ;
115
116 HELP: alien-assembly-error
117 { $error-description "Thrown if the word calling " { $link alien-assembly } " was not compiled with the optimizing compiler. This may be a result of one of two failure conditions:"
118     { $list
119         { "This can happen when experimenting with " { $link alien-assembly } " in this listener. To fix the problem, place the " { $link alien-assembly } " call in a word; word definitions are automatically compiled with the optimizing compiler." }
120         { "One of the four inputs to " { $link alien-assembly } " is not a literal value." }
121     }
122 } ;
123
124 HELP: alien-assembly
125 { $values { "..." "zero or more objects passed to the C function" } { "return" "a C return type" } { "parameters" "a sequence of C parameter types" } { "abi" "one of " { $snippet "\"cdecl\"" } " or " { $snippet "\"stdcall\"" } } { "quot" quotation } }
126 { $description
127     "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."
128 }
129 { $notes "C type names are documented in " { $link "c-types-specs" } "." }
130 { $errors "Throws an " { $link alien-assembly-error } " if the word calling " { $link alien-assembly } " is not compiled." } ;
131
132 { alien-invoke alien-indirect alien-assembly alien-callback } related-words
133
134 ARTICLE: "alien-expiry" "Alien expiry"
135 "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."
136 $nl
137 "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 } "."
138 { $subsections expired? } ;
139
140 ARTICLE: "aliens" "Alien addresses"
141 "Instances of the " { $link alien } " class represent pointers to C data outside the Factor heap:"
142 { $subsections
143     <alien>
144     <displaced-alien>
145     alien-address
146 }
147 "Anywhere that a " { $link alien } " instance is accepted, the " { $link f } " singleton may be passed in to denote a null pointer."
148 $nl
149 "Usually alien objects do not have to 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."
150 { $subsections
151     "syntax-aliens"
152     "alien-expiry"
153 }
154 "When higher-level abstractions won't do:"
155 { $subsections "reading-writing-memory" }
156 { $see-also "c-data" "c-types-specs" } ;
157
158 ARTICLE: "reading-writing-memory" "Reading and writing memory directly"
159 "Numerical values can be read from memory addresses and converted to Factor objects using the various typed memory accessor words:"
160 { $subsections
161     alien-signed-1
162     alien-unsigned-1
163     alien-signed-2
164     alien-unsigned-2
165     alien-signed-4
166     alien-unsigned-4
167     alien-signed-cell
168     alien-unsigned-cell
169     alien-signed-8
170     alien-unsigned-8
171     alien-float
172     alien-double
173 }
174 "Factor numbers can also be converted to C values and stored to memory:"
175 { $subsections
176     set-alien-signed-1
177     set-alien-unsigned-1
178     set-alien-signed-2
179     set-alien-unsigned-2
180     set-alien-signed-4
181     set-alien-unsigned-4
182     set-alien-signed-cell
183     set-alien-unsigned-cell
184     set-alien-signed-8
185     set-alien-unsigned-8
186     set-alien-float
187     set-alien-double
188 } ;
189
190 ARTICLE: "alien-invoke" "Calling C from Factor"
191 "The easiest way to call into a C library is to define bindings using a pair of parsing words:"
192 { $subsections
193     POSTPONE: LIBRARY:
194     POSTPONE: FUNCTION:
195 }
196 "The above parsing words create word definitions which call a lower-level word; you can use it directly, too:"
197 { $subsections alien-invoke }
198 "Sometimes it is necessary to invoke a C function pointer, rather than a named C function:"
199 { $subsections alien-indirect }
200 "There are some details concerning the conversion of Factor objects to C values, and vice versa. See " { $link "c-data" } "." ;
201
202 ARTICLE: "alien-callback" "Calling Factor from C"
203 "Callbacks can be defined and passed to C code as function pointers; the C code can then invoke the callback and run Factor code:"
204 { $subsections
205     alien-callback
206     POSTPONE: CALLBACK:
207 }
208 "There are some caveats concerning the conversion of Factor objects to C values, and vice versa. See " { $link "c-data" } "."
209 { $see-also "byte-arrays-gc" } ;
210
211 ARTICLE: "alien-globals" "Accessing C global variables"
212 "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."
213 { $subsections
214     POSTPONE: C-GLOBAL:
215     POSTPONE: &:
216 } ;
217
218 ARTICLE: "alien-assembly" "Calling arbitrary assembly code"
219 "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 } "."
220 $nl
221 "Assembler opcodes are defined in CPU-specific vocabularies:"
222 { $list
223     { $vocab-link "cpu.arm.assembler" }
224     { $vocab-link "cpu.ppc.assembler" }
225     { $vocab-link "cpu.x86.assembler" }
226 }
227 "The combinator for generating arbitrary assembly by calling a quotation at compile time:"
228 { $subsection alien-assembly } ;
229
230 ARTICLE: "dll.private" "DLL handles"
231 "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" } "."
232 $nl
233 "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:"
234 { $subsections
235     dlopen
236     dlsym
237     dlclose
238     dll-valid?
239 } ;
240
241 ARTICLE: "embedding-api" "Factor embedding API"
242 "The Factor embedding API is defined in " { $snippet "vm/master.h" } "."
243 $nl
244 "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."
245 $nl
246 "Including this header file into a C compilation unit will declare the following functions:"
247 { $table
248     { {
249         { $code "void init_factor_from_args("
250             "    F_CHAR *image, int argc, F_CHAR **argv, bool embedded"
251             ")" }
252         "Initializes Factor."
253         $nl
254         "If " { $snippet "image" } " is " { $snippet "NULL" } ", Factor will load an image file whose name is obtained by suffixing the executable name with " { $snippet ".image" } "."
255         $nl
256         "The " { $snippet "argc" } " and " { $snippet "argv" } " parameters are interpreted just like normal command line arguments when running Factor stand-alone; see " { $link "cli" } "."
257         $nl
258         "The " { $snippet "embedded" } " flag ensures that this function returns as soon as Factor has been initialized. Otherwise, Factor will start up normally."
259     } }
260     { {
261         { $code "char *factor_eval_string(char *string)" }
262         "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" } "."
263     } }
264     { {
265         { $code "void factor_eval_free(char *result)" }
266         "Frees a string returned by " { $snippet "factor_eval_string()" } "."
267     } }
268     { {
269         { $code "void factor_yield(void)" }
270         "Gives all Factor threads a chance to run."
271     } }
272     { {
273         { $code "void factor_sleep(long us)" }
274         "Gives all Factor threads a chance to run for " { $snippet "us" } " microseconds."
275     } }
276 } ;
277
278 ARTICLE: "embedding-restrictions" "Embedding API restrictions" 
279 "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." ;
280
281 ARTICLE: "embedding-factor" "What embedding looks like from Factor"
282 "Factor code will run inside an embedded instance in the same way it would run in a stand-alone instance."
283 $nl
284 "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."
285 $nl
286 "There is a word which can detect when Factor is embedded:"
287 { $subsections embedded? }
288 "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" } "." ;
289
290 ARTICLE: "embedding" "Embedding Factor into C applications"
291 "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:"
292 { $table
293     { "OS" "Library name" "Shared?" }
294     { "Windows XP/Vista" { $snippet "factor.dll" } "Yes" }
295     ! { "Windows CE" { $snippet "factor-ce.dll" } "Yes" }
296     { "Mac OS X" { $snippet "libfactor.dylib" } "Yes" }
297     { "Other Unix" { $snippet "libfactor.a" } "No" }
298 }
299 "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" } ")."
300 { $subsections
301     "embedding-api"
302     "embedding-factor"
303     "embedding-restrictions"
304 } ;
305
306 ARTICLE: "alien" "C library interface"
307 "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."
308 $nl
309 "The C library interface is entirely self-contained; there is no C code which one must write in order to wrap a library."
310 $nl
311 "C library interface words are found in the " { $vocab-link "alien" } " vocabulary and its subvocabularies."
312 { $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." }
313 { $subsections
314     "loading-libs"
315     "alien-invoke"
316     "alien-callback"
317     "c-data"
318     "classes.struct"
319     "alien-globals"
320     "alien-assembly"
321     "dll.private"
322     "embedding"
323 } ;
324
325 ABOUT: "alien"