1 ! Copyright (C) 2004, 2005 Mackenzie Straight
2 ! Copyright (C) 2007, 2010 Slava Pestov
3 ! Copyright (C) 2007, 2008 Doug Coleman
4 ! See http://factorcode.org/license.txt for BSD license.
5 USING: accessors alien alien.c-types alien.destructors
6 alien.syntax destructors destructors.private kernel math
7 namespaces sequences sets summary system vocabs ;
10 HOOK: strerror os ( errno -- str )
17 FUNCTION-ALIAS: set-errno
18 void set_err_no ( int err-no ) ;
23 : preserve-errno ( quot -- )
24 errno [ call ] dip set-errno ; inline
28 FUNCTION-ALIAS: (malloc)
29 void* malloc ( size_t size ) ;
31 FUNCTION-ALIAS: (calloc)
32 void* calloc ( size_t count, size_t size ) ;
34 FUNCTION-ALIAS: (free)
35 void free ( void* alien ) ;
37 FUNCTION-ALIAS: (realloc)
38 void* realloc ( void* alien, size_t size ) ;
40 FUNCTION-ALIAS: strerror_unsafe
41 char* strerror ( int errno ) ;
43 ! Add a default strerror even though it's not threadsafe
44 M: object strerror strerror_unsafe ;
46 ERROR: libc-error errno message ;
48 : (io-error) ( -- * ) errno dup strerror libc-error ;
50 : io-error ( n -- ) 0 < [ (io-error) ] when ;
54 ! We stick malloc-ptr instances in the global disposables set
55 TUPLE: malloc-ptr value continuation ;
57 M: malloc-ptr hashcode* value>> hashcode* ;
60 over malloc-ptr? [ [ value>> ] same? ] [ 2drop f ] if ;
62 : <malloc-ptr> ( value -- malloc-ptr )
63 malloc-ptr new swap >>value ;
70 drop "Memory allocation failed" ;
72 : check-ptr ( c-ptr -- c-ptr )
75 ERROR: realloc-error ptr size ;
77 M: realloc-error summary
78 drop "Memory reallocation failed" ;
82 : add-malloc ( alien -- alien )
83 dup <malloc-ptr> register-disposable ;
85 : delete-malloc ( alien -- )
86 [ <malloc-ptr> unregister-disposable ] when* ;
88 : malloc-exists? ( alien -- ? )
89 <malloc-ptr> disposables get in? ;
93 : malloc ( size -- alien )
94 (malloc) check-ptr add-malloc ;
96 : calloc ( count size -- alien )
97 (calloc) check-ptr add-malloc ;
99 : realloc ( alien size -- newalien )
101 over malloc-exists? [ realloc-error ] unless
102 [ drop ] [ (realloc) check-ptr ] 2bi
103 [ delete-malloc ] [ add-malloc ] bi* ;
106 >c-ptr [ delete-malloc ] [ (free) ] bi ;
108 FUNCTION: void memset ( void* buf, int char, size_t size ) ;
110 FUNCTION: void memcpy ( void* dst, void* src, ulong size ) ;
112 FUNCTION: int memcmp ( void* a, void* b, ulong size ) ;
114 : memory= ( a b size -- ? ) memcmp 0 = ; inline
116 FUNCTION: size_t strlen ( c-string alien ) ;
118 FUNCTION: int system ( c-string command ) ;
123 ! For libc.linux, libc.windows, libc.macosx...
124 << "libc." os name>> append require >>