factor/basis/libc/libc.factor

90 lines
2.0 KiB
Factor
Raw Normal View History

2007-09-20 18:09:08 -04:00
! Copyright (C) 2004, 2005 Mackenzie Straight
! Copyright (C) 2007, 2009 Slava Pestov
2008-05-15 00:23:12 -04:00
! Copyright (C) 2007, 2008 Doug Coleman
2007-09-20 18:09:08 -04:00
! See http://factorcode.org/license.txt for BSD license.
USING: alien assocs continuations alien.destructors kernel
2008-07-30 05:12:17 -04:00
namespaces accessors sets summary ;
2007-09-20 18:09:08 -04:00
IN: libc
<PRIVATE
: (malloc) ( size -- alien )
"void*" "libc" "malloc" { "ulong" } alien-invoke ;
: (calloc) ( count size -- alien )
"void*" "libc" "calloc" { "ulong" "ulong" } alien-invoke ;
: (free) ( alien -- )
"void" "libc" "free" { "void*" } alien-invoke ;
: (realloc) ( alien size -- newalien )
"void*" "libc" "realloc" { "void*" "ulong" } alien-invoke ;
2008-07-28 23:57:43 -04:00
SYMBOL: malloc-expiry
: mallocs ( -- assoc )
malloc-expiry get-global expired? [
2008-07-28 23:57:43 -04:00
-1 <alien> malloc-expiry set-global
H{ } clone dup \ mallocs set-global
] [
\ mallocs get-global
] if ;
2007-09-20 18:09:08 -04:00
PRIVATE>
2008-03-20 16:00:49 -04:00
ERROR: bad-ptr ;
2007-09-20 18:09:08 -04:00
2008-07-30 05:12:17 -04:00
M: bad-ptr summary
drop "Memory allocation failed" ;
2007-09-20 18:09:08 -04:00
: check-ptr ( c-ptr -- c-ptr )
2008-03-20 16:00:49 -04:00
[ bad-ptr ] unless* ;
2007-09-20 18:09:08 -04:00
2008-03-20 16:00:49 -04:00
ERROR: double-free ;
2007-09-20 18:09:08 -04:00
2008-07-30 05:12:17 -04:00
M: double-free summary
drop "Free failed since memory is not allocated" ;
2008-03-20 16:00:49 -04:00
ERROR: realloc-error ptr size ;
2007-09-20 18:09:08 -04:00
2008-07-30 05:12:17 -04:00
M: realloc-error summary
drop "Memory reallocation failed" ;
2007-09-20 18:09:08 -04:00
<PRIVATE
2009-01-17 21:10:56 -05:00
: add-malloc ( alien -- alien )
dup mallocs conjoin ;
2007-09-20 18:09:08 -04:00
: delete-malloc ( alien -- )
[
2008-07-28 23:57:43 -04:00
mallocs delete-at*
2009-01-17 21:10:56 -05:00
[ drop ] [ double-free ] if
2007-09-20 18:09:08 -04:00
] when* ;
: malloc-exists? ( alien -- ? )
2008-07-28 23:57:43 -04:00
mallocs key? ;
2007-09-20 18:09:08 -04:00
PRIVATE>
: malloc ( size -- alien )
2009-01-17 21:10:56 -05:00
(malloc) check-ptr add-malloc ;
2007-09-20 18:09:08 -04:00
: calloc ( count size -- alien )
2009-01-17 21:10:56 -05:00
(calloc) check-ptr add-malloc ;
2007-09-20 18:09:08 -04:00
: realloc ( alien size -- newalien )
over malloc-exists? [ realloc-error ] unless
2009-01-17 21:10:56 -05:00
[ drop ] [ (realloc) check-ptr ] 2bi
[ delete-malloc ] [ add-malloc ] bi* ;
2007-09-20 18:09:08 -04:00
: free ( alien -- )
2009-01-17 21:10:56 -05:00
[ delete-malloc ] [ (free) ] bi ;
2007-09-20 18:09:08 -04:00
: memcpy ( dst src size -- )
"void" "libc" "memcpy" { "void*" "void*" "ulong" } alien-invoke ;
2008-05-11 18:43:34 -04:00
: strlen ( alien -- len )
"size_t" "libc" "strlen" { "char*" } alien-invoke ;
2008-05-15 00:23:12 -04:00
DESTRUCTOR: free