pax_global_header 0000666 0000000 0000000 00000000064 14045766433 0014526 g ustar 00root root 0000000 0000000 52 comment=3a0014883be08ef06a7749836c4d94ca7df55a82
ocaml-extunix-0.3.2/ 0000775 0000000 0000000 00000000000 14045766433 0014325 5 ustar 00root root 0000000 0000000 ocaml-extunix-0.3.2/.gitignore 0000664 0000000 0000000 00000000077 14045766433 0016321 0 ustar 00root root 0000000 0000000 _build
_opam
.merlin
*.install
web/index.html
*~
/userns_test/
ocaml-extunix-0.3.2/.travis.yml 0000664 0000000 0000000 00000000662 14045766433 0016442 0 ustar 00root root 0000000 0000000 language: c
sudo: required
install: wget https://raw.githubusercontent.com/ocaml/ocaml-ci-scripts/master/.travis-opam.sh
script: bash -ex .travis-opam.sh
env:
- OCAML_VERSION=4.02
- OCAML_VERSION=4.03
- OCAML_VERSION=4.04
- OCAML_VERSION=4.05
- OCAML_VERSION=4.06
- OCAML_VERSION=4.07
- OCAML_VERSION=4.08
- OCAML_VERSION=4.09
- OCAML_VERSION=4.10
- OCAML_VERSION=4.11
- OCAML_VERSION=4.12
os:
- linux
- osx
ocaml-extunix-0.3.2/CHANGES.txt 0000664 0000000 0000000 00000011134 14045766433 0016136 0 ustar 00root root 0000000 0000000 ## v0.3.2 - 09 May 2021
* Emulate statvfs on Windows
* build: mark ppxlib as build-time dep, depend on OCaml >= 4.06
## v0.3.1 - 11 Apr 2021
* temporarily keep backward compatibility wrt top-level module names
## v0.3.0 - 10 Apr 2021
* build: switch to dune, dune-configurator and ppxlib
* sockopt: handle missing options at runtime
* Add IPv6 support to getifaddrs
* better Windows support
+ Support Endian module on Windows
+ Enable asctime, strftime, tzname, timezone, timegm on Windows
## v0.2.0 - 8 Nov 2019
* camlp4 dependency replaced with ppx
* use available endian functions on Mac OS
## v0.1.7 - 27 Mar 2019
* detect endian functions on more platforms
* fix openlog
* improve gettid on Mac OS
## v0.1.6 - 11 Mar 2018
* OCaml 4.05 compatibility (O_KEEPEXEC)
* sockopt: add BPF options
* make tests less fragile
* New bindings:
* syslog
## v0.1.5 - 28 Jun 2017
* build with -safe-string
## v0.1.4 - 11 Nov 2016
+ SO_REUSEPORT
* fix sendmsg bug
* fix build on mingw
## v0.1.3 - 24 Nov 2015
* New bindings :
* fchmodat
* fchownat
+ ExtUnix.Config
* fix sysconf detection wrt non-standard options
## v0.1.2 - 24 Jul 2015
* New bindings :
* sysinfo uptime
* mtrace muntrace
* mount umount2
* unshare
* chroot
+ U.Poll.is_inter inter
* TCP_KEEPCNT TCP_KEEPIDLE TCP_KEEPINTLV are now detected one by one and
can be available or not available independently. Extunix currently doesn't
have a mechanism to expose only selected variants from a single type in
module [Specific], hence one should use [have_sockopt] function to check
for options presence at runtime.
## v0.1.1 - 18 May 2014
* New bindings :
* gettid
* poll
* OCaml 4.02 compatibility (install all .cmi)
* sendmsg/sendfd : fix sending binary data
## v0.1.0 - 8 Oct 2013
* statvfs: add f_flags - decoded f_flag field
* New bindings :
* sysconf
* splice tee vmsplice
* setsockopt_int getsockopt_int (TCP keepalive)
* sync syncfs
* timezone
* OCaml 4.01 compatibility (Unix.open_flag)
* relax restrictions on bigarray types
## v0.0.6 - 1 Apr 2013
* New string and bigarray functions :
* get_uint63 set_uint63 get_int63 set_int63
* fstatat: flags parameter was omitted
* New bindings :
* readlinkat
* getifaddrs
## v0.0.5 - 16 Jun 2012
* src/discover.ml :
* New option -q to suppress stderr
* --disable-* options to exclude selected features from build
* More precise test for `sendmsg` (bug #1162)
* Fix FTBFS on kfreebsd-* (Debian patch)
* Unit tests are disabled by default and oUnit is now an optional dependency,
configure with --enable-tests to build tests
* OCaml 4 compatibility (Unix.open_flag)
* List email contacts (bug #1108)
## v0.0.4 - 19 May 2012
* ExtUnix now depends on Bigarray and provides variants of
some bindings operating on bigarray buffers (BA submodule)
* New bindings :
* timegm
* malloc_stats
* malloc_info
* read_credentials
* fexecve
* sendmsg recvmsg
* pread pwrite (+ LargeFile and BA variants)
* read write (+ LargeFile and BA variants)
* mkstemp mkostemp
* setresuid setresgid
* posix_memalign
* New submodules: BigEndian LittleEndian HostEndian
* New bindings
* uint16_from_host uint16_to_host
* int16_from_host int16_to_host
* uint31_from_host uint31_to_host
* int31_from_host int31_to_host
* int32_from_host int32_to_host
* int64_from_host int64_to_host
* New string and bigarray functions
* get_uint8 set_uint8 get_int8 set_int8
* get_uint16 set_uint16 get_int16 set_int16
* get_uint31 set_uint31 get_int31 set_int31
* get_int32 set_int32
* get_int64 set_int64
## v0.0.3 - 12 Jul 2011
* Keep unlinkat interface compatible with Netsys
* statvfs : return all fields, use POSIX names
* realpath : fix segfault on non-glibc systems
* New bindings :
* backtrace
* setenv unsetenv clearenv
* linkat symlinkat
* mkdtemp
## v0.0.2 - 26 Dec 2010
* New bindings :
* getrlimit setrlimit
* getpriority setpriority
* ptrace (minimal)
* renameat mkdirat
* mlockall munlockall
* strftime strptime asctime
* tzname
* posix_openpt grantpt unlockpt ptsname (Niki Yoshiuchi)
* getsid
* ctermid
* is_open_descr
* tcgetpgrp tcsetpgrp
* int_of_file_descr file_descr_of_int
* sys_exit
* Separate configure test for fsync and fdatasync
* ExtUnix.All.have function to test for features at runtime
* Skip tests of functions not available on the current platform
## v0.0.1 - 7 Nov 2010
* First release, implemented bindings :
* fsync fdatasync
* eventfd signalfd
* statvfs fstatvfs
* dirfd openat unlinkat fstatat
* uname
* fadvise fallocate
* ttyname setpgid getpgid setreuid setregid
* realpath
ocaml-extunix-0.3.2/Makefile 0000664 0000000 0000000 00000000616 14045766433 0015770 0 ustar 00root root 0000000 0000000 build:
dune build @install
clean:
dune clean
doc:
dune build @doc
test:
dune runtest
VERSION=0.3.2
NAME=ocaml-extunix-$(VERSION)
release:
git tag -a -m $(VERSION) v$(VERSION)
git archive --prefix=$(NAME)/ v$(VERSION) | gzip > $(NAME).tar.gz
gpg -a -b $(NAME).tar.gz -o $(NAME).tar.gz.asc
dune-release:
dune-release tag
dune-release
.PHONY: build clean doc release dune-release test
ocaml-extunix-0.3.2/README.md 0000664 0000000 0000000 00000011356 14045766433 0015612 0 ustar 00root root 0000000 0000000 ExtUnix OCaml library
=====================
[](https://travis-ci.org/ygrek/extunix)
[](https://ci.appveyor.com/project/ygrek/extunix/branch/master)
A collection of thin bindings to various low-level system API.
Our motto: "Be to Unix, what extlib is to stdlib"
* Implement thin C bindings that directly map to underlying system API.
* Provide common consistent ocaml interface: naming convention, exceptions.
* Simple to build - no extra dependencies.
Homepage:
Why?
----
Most of the system API don't deserve fully fledged library.
The ExtUnix project aims to collect these in one place. Read the
"[ExtUnix integration requirements](#extunix-integration-requirements)"
to know what kind of system API we can integrate.
Installation
------------
Dependencies :
* OCaml, Dune, ppxlib for build and installation
* (optional) oUnit2 for tests, odoc for documentation
Build and install:
make
make install
Alternatively use the underlying Dune build system directly (plain ocaml,
no sh and make needed):
dune build @install
Usage example:
$ ocaml
# #use "topfind";;
# #require "extunix";;
# module U = ExtUnix.Specific;;
# U.ttyname Unix.stdout;;
- : string = "/dev/pts/8"
Run unit tests:
make test
Guidelines
----------
For OCaml programming style, we follow Unix module:
* Values and types should be named by the name of the underlying C function
* Raise `Unix_error` on runtime errors
* Uniformly raise `Not_available` exception for functions not available on the
current platform
* Be MT friendly by default - i.e. release runtime lock for blocking
operations, (FIXME) optionally provide ST variants
Portability:
* No shell scripting for build and install (think windows :) )
* Write portable C code (use compiler options to catch compatibility issues),
NB: msvc doesn't support C99.
* Provide module (`ExtUnix.Specific`) exposing only functions available on the
platform where library is built - i.e. guaranteed to not throw
`Not_available` exception (experimental).
Build infrastructure:
* [`discover`][] is used to discover available functions during
configure step.
* Generated `config.h` describes "features" discovered - it is
responsible for inclusion of system-specific headers - this ensures
coherent result at configure and build steps.
* Generated `extUnixConfig.ml` describes the same features for the ocaml
syntax extension [`ppx_have`][], which preprocesses
[`src/extUnix.pp.ml`][] and generates two modules: `ExtUnix.All`
where bindings to missing functions are rewritten to raise exception
and `ExtUnix.Specific` which drops bindings to missing functions.
[`discover`]: discover/discover.ml
[`ppx_have`]: ppx_have/ppx_have.ml
[`src/extUnix.pp.ml`]: src/extUnix.pp.ml
ExtUnix integration requirements
--------------------------------
We can integrate into ExtUnix:
* Official POSIX calls not in Unix module.
* Drafted POSIX calls which are at least present on two systems among:
Linux, *BSD, MacOS X.
* System specific calls, as long as they don't need additional library,
that they are marked as such in the documentation and that we have an
automatic configure system test for them.
We should avoid system calls that are complex and would deserve a library on
their own. For example, a family of more than 10 functions and datatypes should
deserve its own library. If an external library already exists and works, like
for inotify system call, we also won't consider it for integration.
Regarding Win32 portability:
If there is a sane default to create a portable equivalent of the function on
Windows, we can consider it. And we will mark it as such in the documentation.
Checklist for adding new bindings
---------------------------------
* Add the C code to [`src`][] (follow the code style of existing bindings)
* Add the required checks to [`discover/discover.ml`][]
* Add the name of the C bindings to [`src/dune`][]
* Add the OCaml code to [`src/extUnix.pp.ml`][] guarded with `HAVE ... END`
* Add some tests to [`test/test.ml`][]
* Add note to [`CHANGES.txt`][]
* Run `make`
[`src`]: src
[`discover/discover.ml`]: discover/discover.ml
[`src/dune`]: src/dune
[`test/test.ml`]: test/test.ml
[`CHANGES.txt`]: CHANGES.txt
Checklist for release
---------------------
* Review `git log` and update [`CHANGES.txt`][]
* Increase VERSION in Makefile
* Commit
* `make release`
Development
-----------
Many people contribute to extunix. Please submit your patches and/or feature requests
to the project bugtracker at .
The current maintainer is reachable at .
ocaml-extunix-0.3.2/TODO 0000664 0000000 0000000 00000001363 14045766433 0015020 0 ustar 00root root 0000000 0000000 TODO
====
* comments: mark "emulated" (windows) functions
* unsetenv winapi? see http://old.nabble.com/-patch--(msvc)-use-more-modern-facilities-for-setenv()-unsetenv()-td15877005.html
* investigate F_FULLFSYNC fcntl and fsync on Mac OS
* nanosleep
* fdtruncate win32
* waitid
DONE
====
* INRIA request for extended UNIX:
http://caml.inria.fr/mantis/view.php?id=5063
http://caml.inria.fr/mantis/view.php?id=2533
http://caml.inria.fr/mantis/view.php?id=3851
http://caml.inria.fr/mantis/view.php?id=480
* mkdtemp (see Jane Street Core)
* sysconf: get system configuration constants. In particular, PAGESIZE,
_SC_PHYS_PAGES, _SC_AVPHYS_PAGES, _SC_NPROCESSORS_CONF, _SC_NPROCESSORS_ONLN
(see Jane Street Core)
* sysinfo (see Jane Street Core)
ocaml-extunix-0.3.2/appveyor.yml 0000664 0000000 0000000 00000001670 14045766433 0016721 0 ustar 00root root 0000000 0000000 image:
- Visual Studio 2019
platform:
- x64
environment:
FORK_USER: ocaml
FORK_BRANCH: master
CYG_ROOT: C:\cygwin64
matrix:
- OPAM_SWITCH: 4.12.0+mingw64c
- OPAM_SWITCH: 4.12.0+msvc64c
# - OPAM_SWITCH: 4.11.2+mingw64c
# - OPAM_SWITCH: 4.11.2+msvc64c
# - OPAM_SWITCH: 4.10.2+mingw64c
# - OPAM_SWITCH: 4.10.2+msvc64c
# - OPAM_SWITCH: 4.09.1+mingw64c
# - OPAM_SWITCH: 4.09.1+msvc64c
# - OPAM_SWITCH: 4.08.1+mingw64c
# - OPAM_SWITCH: 4.08.1+msvc64c
- OPAM_SWITCH: 4.07.1+mingw64c
- OPAM_SWITCH: 4.07.1+msvc64c
install:
- ps: (New-Object Net.WebClient).DownloadFile('https://cygwin.com/setup-x86_64.exe', "C:\cygwin64\setup-x86_64.exe")
- ps: iex ((new-object net.webclient).DownloadString("https://raw.githubusercontent.com/$env:FORK_USER/ocaml-ci-scripts/$env:FORK_BRANCH/appveyor-install.ps1"))
build_script:
- call %CYG_ROOT%\bin\bash.exe -l %APPVEYOR_BUILD_FOLDER%\appveyor-opam.sh
ocaml-extunix-0.3.2/discover/ 0000775 0000000 0000000 00000000000 14045766433 0016143 5 ustar 00root root 0000000 0000000 ocaml-extunix-0.3.2/discover/discover.ml 0000664 0000000 0000000 00000040644 14045766433 0020323 0 ustar 00root root 0000000 0000000 (**
Discover features available on this platform.
There are two stages: actual discover by means of trying to compile snippets of test code
and generation of config file listing all the discovered features
*)
module C = Configurator.V1
open Printf
type arg =
| I of string (* check header file (#include) available (promoted to config) *)
| T of string (* check type available *)
| DEFINE of string (* define symbol prior to including header files (promoted to config) *)
| Z of string (* define symbol to zero if not defined after the includes (promoted to config) *)
| IF of string * string * string
(* let [(cond, symbol, value)], then if [cond] is met after the
includes, define [symbol] to [value] (promoted to config) *)
| S of string (* check symbol available (e.g. function name) *)
| V of string (* check value available (e.g. enum member) *)
| D of string (* check symbol defined *)
| ND of string (* check symbol not defined *)
| F of string * string (* check structure type available and specified field present in it *)
| Ldlib of string (* ccomp_type *) * string (* library flag or name given to compilers when they
are supposed to invoke the linker *)
type test =
| L of arg list
| ANY of arg list list
type t =
| YES of {
name : string;
args : arg list;
ldlibs : string list;
(* list of flags to give to the linker. Required if functions
looked for with this test aren't in the set of libraries
linked by default. *)
}
| NO of string
let verbose = ref 1
let disabled = ref []
let print_define b s = bprintf b "#define %s\n" s
let print_include b s = bprintf b "#include <%s>\n" s
let print_zdefine b s = bprintf b "#ifndef %s\n#define %s 0\n#endif\n" s s
let print_ifdefine b (condition,symbol,value) = bprintf b "#if %s\n#define %s (%s)\n#endif\n" condition symbol value
let filter_map f l = List.rev (List.fold_left (fun acc x -> match f x with Some s -> s::acc | None -> acc) [] l)
let get_defines = filter_map (function DEFINE s -> Some s | _ -> None)
let get_zdefines = filter_map (function Z s -> Some s | _ -> None)
let get_ifdefines = filter_map (function IF (c,s,v) -> Some (c,s,v) | _ -> None)
let get_includes = filter_map (function I s -> Some s | _ -> None)
let get_ldlibs ccomp_type = filter_map (function Ldlib (ct, lib) when ct = ccomp_type -> Some lib | _ -> None)
let config_defines = [
"_POSIX_C_SOURCE 200809L";
"_XOPEN_SOURCE 700";
"_BSD_SOURCE";
"_DEFAULT_SOURCE";
"_DARWIN_C_SOURCE";
"_LARGEFILE64_SOURCE";
"WIN32_LEAN_AND_MEAN";
"_WIN32_WINNT 0x0602"; (* Windows 8 *)
"CAML_NAME_SPACE";
"_GNU_SOURCE"
]
let config_includes = [
"string.h";
"errno.h";
"assert.h";
"caml/memory.h";
"caml/fail.h";
"caml/unixsupport.h";
"caml/signals.h";
"caml/alloc.h";
"caml/custom.h";
"caml/bigarray.h";
]
let build_code args =
let b = Buffer.create 10 in
let pr fmt = ksprintf (fun s -> Buffer.add_string b (s^"\n")) fmt in
let fresh = let n = ref 0 in fun () -> incr n; !n in
List.iter (print_define b) config_defines;
List.iter (print_define b) (get_defines args);
List.iter (print_include b) config_includes;
List.iter (print_include b) (get_includes args);
(* pr "#include "; (* size_t *)*)
List.iter begin function
| I _ | Ldlib _ -> ()
| T s -> pr "%s var_%d;" s (fresh ())
| DEFINE _ -> ()
| Z _ | IF _ -> () (* no test required *)
| D s -> pr "#ifndef %s" s; pr "#error %s not defined" s; pr "#endif"
| ND s -> pr "#ifdef %s" s; pr "#error %s defined" s; pr "#endif"
| S s -> pr "size_t var_%d = (size_t)&%s;" (fresh ()) s
| V s -> pr "int var_%d = (0 == %s);" (fresh ()) s
| F (s,f) -> pr "size_t var_%d = (size_t)&((struct %s*)0)->%s;" (fresh ()) s f
end args;
pr "int main() { return 0; }";
Buffer.contents b
let discover c (name,test) =
print_string ("checking " ^ name ^ (String.make (20 - String.length name) '.'));
(* Workaround for a bug in dune-configurator. To remove when a
release of Dune (> 2.8.2) contains
https://github.com/ocaml/dune/pull/4088. *)
let c_libraries =
match C.ocaml_config_var c "native_c_libraries" with
| Some c_libraries -> C.Flags.extract_blank_separated_words c_libraries
| None ->
match C.ocaml_config_var c "bytecomp_c_libraries" with
| Some c_libraries -> C.Flags.extract_blank_separated_words c_libraries
| None -> []
in
let ccomp_type = C.ocaml_config_var_exn c "ccomp_type" in
let rec loop args other =
let code = build_code args in
let ldlibs = get_ldlibs ccomp_type args in
let link_flags = c_libraries @ ldlibs in
match C.c_test c ~link_flags code, other with
| false, [] ->
if !verbose >= 2 then prerr_endline code;
print_endline "failed"; NO name
| false, (x::xs) -> loop x xs
| true, _ -> print_endline "ok"; YES {name; args; ldlibs}
in
match List.mem name !disabled with
| true -> print_endline "disabled"; NO name
| false ->
match test with
| L l -> loop l []
| ANY (x::xs) -> loop x xs
| ANY [] -> assert false
let show_c file result =
let b = Buffer.create 10 in
let pr fmt = ksprintf (fun s -> Buffer.add_string b (s^"\n")) fmt in
pr "";
List.iter (print_define b) config_defines;
List.iter begin function
| NO _ -> ();
| YES {name; args; _} ->
match get_defines args with
| [] -> ()
| l ->
pr "";
pr "#if defined(EXTUNIX_WANT_%s)" name;
List.iter (print_define b) l;
pr "#endif";
end result;
pr "";
List.iter (print_include b) config_includes;
pr "#include \"common.h\"";
List.iter begin function
| NO name ->
pr "";
pr "#undef EXTUNIX_HAVE_%s" name;
| YES {name; args; _} ->
pr "";
pr "#define EXTUNIX_HAVE_%s" name;
match get_includes args, get_zdefines args, get_ifdefines args with
| [],[],[] -> ()
| includes,zdefines,ifdefines ->
pr "#if defined(EXTUNIX_WANT_%s)" name;
List.iter (print_include b) includes;
List.iter (print_zdefine b) zdefines;
List.iter (print_ifdefine b) ifdefines;
pr "#endif";
end result;
pr "";
let ch = open_out file in
Buffer.output_buffer ch b;
close_out ch
let show_ml file result =
let ch = open_out file in
let pr fmt = ksprintf (fun s -> output_string ch (s^"\n")) fmt in
pr "(** @return whether feature is available *)";
pr "let feature = function";
List.iter (function
| YES {name; _} -> pr "| %S -> Some true" name
| NO name -> pr "| %S -> Some false" name) result;
pr "| _ -> None";
pr "";
pr "(** @return whether feature is available *)";
pr "let have = function";
List.iter (function
| YES {name; _} -> pr "| `%s -> true" name
| NO name -> pr "| `%s -> false" name) result;
close_out ch
let show_ldlibs_sexp file result =
let ch = open_out file in
let pr fmt = ksprintf (fun s -> output_string ch s) fmt in
pr "(";
List.(fold_left (fun acc -> function
| YES {ldlibs; _} when not (mem ldlibs acc) -> ldlibs :: acc
| _ -> acc)
[]
result |> concat |> iter (fun ldlib -> pr "%s " ldlib));
pr ")\n";
close_out ch
let main c config =
let result = List.map (discover c) config in
show_c "config.h" result;
show_ml "extUnixConfig.ml" result;
show_ldlibs_sexp "ldlibs.sexp" result
let features =
let fd_int = ND "Handle_val" in (* marker for bindings code assuming fd is represented as int *)
let statvfs =
[
I "sys/statvfs.h";
T "struct statvfs";
D "ST_RDONLY"; D "ST_NOSUID";
Z "ST_NODEV"; Z "ST_NOEXEC"; Z "ST_SYNCHRONOUS"; Z "ST_MANDLOCK"; Z "ST_WRITE";
Z "ST_APPEND"; Z "ST_IMMUTABLE"; Z "ST_NOATIME"; Z "ST_NODIRATIME"; Z "ST_RELATIME";
]
in
[
"EVENTFD", L[
fd_int;
I "sys/eventfd.h";
T "eventfd_t";
S "eventfd"; S "eventfd_read"; S "eventfd_write";
];
"ATFILE", L[
fd_int;
DEFINE "_ATFILE_SOURCE";
I "fcntl.h";
I "sys/types.h"; I "sys/stat.h";
I "unistd.h"; I "stdio.h";
D "S_IFREG";
S "fstatat"; S "openat"; S "unlinkat"; S "renameat"; S "mkdirat"; S "linkat"; S "symlinkat"; S "readlinkat"; S "fchownat"; S "fchmodat";
];
"DIRFD", L[
fd_int;
I "sys/types.h";
I "dirent.h";
S "dirfd";
];
"STATVFS", ANY [
statvfs@[S"statvfs"];
[ DEFINE "CAML_INTERNALS"; I "windows.h"; S "GetDiskFreeSpaceW"; S "GetDiskFreeSpaceExW"; S "GetVolumeInformationW"];
];
"FSTATVFS", L ([fd_int]@statvfs@[S"fstatvfs"]);
"SIOCGIFCONF", L[
fd_int;
I "sys/ioctl.h";
I "net/if.h";
D "SIOCGIFCONF";
S "ioctl";
T "struct ifconf"; T "struct ifreq";
];
"IFADDRS", L[
I "sys/types.h";
I "ifaddrs.h";
S "getifaddrs";
S "freeifaddrs";
T "struct ifaddrs";
];
"INET_NTOA", ANY[
[ I "sys/socket.h"; I "netinet/in.h"; I "arpa/inet.h"; S "inet_ntoa"; ];
[ I "winsock2.h"; I "ws2tcpip.h"; S "inet_ntoa"; ];
];
"INET_NTOP", ANY[
[ I "arpa/inet.h"; S "inet_ntop"; ];
[ I "winsock2.h"; I "ws2tcpip.h"; S "inet_ntop"; ];
];
"UNAME", L[
I "sys/utsname.h";
T "struct utsname";
S "uname";
];
"FADVISE", L[
fd_int;
I "fcntl.h";
S "posix_fadvise"; S "posix_fadvise64";
D "POSIX_FADV_NORMAL";
];
"FALLOCATE", ANY[
[I "fcntl.h"; S "posix_fallocate"; S "posix_fallocate64"; ];
[D "WIN32"; S "GetFileSizeEx"; ];
];
"TTY_IOCTL", L[
fd_int;
I "termios.h"; I "sys/ioctl.h";
S "ioctl"; S "tcsetattr"; S "tcgetattr";
D "CRTSCTS"; D "TCSANOW"; D "TIOCMGET"; D "TIOCMSET"; D "TIOCMBIC"; D "TIOCMBIS";
];
"TTYNAME", L[ fd_int; I "unistd.h"; S "ttyname"; ];
"CTERMID", L[ I "stdio.h"; S "ctermid"; V "L_ctermid"; ];
"GETTID", ANY[
[ D "WIN32"; S "GetCurrentThreadId" ];
[ DEFINE "EXTUNIX_USE_THREADID"; I "pthread.h"; S "pthread_threadid_np" ];
[ DEFINE "EXTUNIX_USE_THREAD_SELFID"; I "sys/syscall.h"; S "syscall"; V "SYS_thread_selfid"];
[ I "sys/syscall.h"; S "syscall"; V "SYS_gettid"; ];
];
"PGID", L[ I "unistd.h"; S "getpgid"; S "setpgid"; S "getsid"; ];
"SETREUID", L[ I "sys/types.h"; I "unistd.h"; S "setreuid"; S "setregid" ];
"FSYNC", ANY[
[I "unistd.h"; S "fsync";];
[D "WIN32"; S "FlushFileBuffers"; ];
];
"FDATASYNC", ANY[
[I "unistd.h"; S "fdatasync";];
[D "WIN32"; S "FlushFileBuffers"; ];
];
"SYNC", L[ I "unistd.h"; S "sync"];
"SYNCFS", ANY[
[fd_int;I "unistd.h"; S "syncfs"];
[fd_int;DEFINE "EXTUNIX_USE_SYS_SYNCFS"; I "unistd.h"; I "sys/syscall.h"; S"syscall"; V"SYS_syncfs"];
];
"REALPATH", L[ I "limits.h"; I "stdlib.h"; S "realpath"; ];
"SIGNALFD", L[ fd_int; I "sys/signalfd.h"; S "signalfd"; I "signal.h"; S "sigemptyset"; S "sigaddset"; ];
"PTRACE", L[ I "sys/ptrace.h"; S "ptrace"; V "PTRACE_TRACEME"; V "PTRACE_ATTACH"; ];
"RESOURCE", L[
I "sys/time.h"; I "sys/resource.h";
S "getpriority"; S "setpriority"; S "getrlimit"; S "setrlimit";
V "PRIO_PROCESS"; V "RLIMIT_NOFILE"; V "RLIM_INFINITY";
];
"MLOCKALL", L[ I "sys/mman.h"; S "mlockall"; S "munlockall"; V "MCL_CURRENT"; V "MCL_FUTURE"; ];
"STRPTIME", L[ I "time.h"; S "strptime"; ];
"STRTIME", ANY[
[ I "time.h"; S"strftime"; S"asctime_r"; S"tzset"; S"tzname"; ];
[ DEFINE"CAML_INTERNALS"; I"caml/osdeps.h"; I "time.h"; Ldlib ("cc", "-lucrtbase");
S"wcsftime"; S"_wasctime_s"; S"_tzset"; S"_get_tzname"; ];
];
"TIMEZONE", ANY[
[ I "time.h"; S"tzset"; S"timezone"; S"daylight" ];
[ I "time.h"; Ldlib ("cc", "-lucrtbase"); S"_tzset"; S"_get_timezone"; S"_get_daylight" ];
];
"TIMEGM", ANY[
[ I "time.h"; S"timegm"; ];
[ I "time.h"; Ldlib ("cc", "-lucrtbase"); S"_mkgmtime" ];
];
"PTS", L[
fd_int;
I "fcntl.h"; I "stdlib.h";
S "posix_openpt"; S "grantpt"; S "unlockpt"; S "ptsname";
];
"FCNTL", L[ fd_int; I"unistd.h"; I"fcntl.h"; S"fcntl"; V"F_GETFL"; ];
"TCPGRP", L[ fd_int; I"unistd.h"; S"tcgetpgrp"; S"tcsetpgrp"; ];
"EXECINFO", ANY[
[ I"execinfo.h"; S"backtrace"; S"backtrace_symbols"; ];
[ I"execinfo.h"; S"backtrace"; S"backtrace_symbols"; Ldlib ("cc", "-lexecinfo")];
];
"SETENV", L[ I"stdlib.h"; S"setenv"; S"unsetenv"; ];
"CLEARENV", L[ I"stdlib.h"; S"clearenv"; ];
"MKDTEMP", L[ I"stdlib.h"; I"unistd.h"; S"mkdtemp"; ];
"MALLOC_INFO", L[ I"malloc.h"; S"malloc_info"; ];
"MALLOC_STATS", L[ I"malloc.h"; S"malloc_stats"; ];
"MEMALIGN", L[ I "stdlib.h"; S"posix_memalign"; ];
"ENDIAN", ANY[
[
I"endian.h";
D"htobe16"; D"htole16"; D"be16toh"; D"le16toh";
D"htobe32"; D"htole32"; D"be32toh"; D"le32toh";
D"htobe64"; D"htole64"; D"be64toh"; D"le64toh";
];
[
I"sys/endian.h";
D"htobe16"; D"htole16";
D"htobe32"; D"htole32";
D"htobe64"; D"htole64";
];
[
DEFINE "EXTUNIX_USE_OSBYTEORDER_H";
I"libkern/OSByteOrder.h";
D"OSSwapHostToBigInt32";
];
[
DEFINE "EXTUNIX_USE_WINSOCK2_H";
I"winsock2.h";
S"htons"; S"ntohs";
S"htonl"; S"ntohl";
(* S"htonll"; S"ntohll"; 2020-01-06: not supported by mingw-w64 yet *)
]
];
"READ_CREDENTIALS", L[ fd_int; I"sys/types.h"; I"sys/socket.h"; D"SO_PEERCRED"; ];
"FEXECVE", L[ fd_int; I "unistd.h"; S"fexecve"; ];
"SENDMSG", ANY[
[ fd_int; I"sys/types.h"; I"sys/socket.h"; S"sendmsg"; S"recvmsg"; D"CMSG_SPACE"; ];
[ fd_int; I"sys/types.h"; I"sys/socket.h"; S"sendmsg"; S"recvmsg"; F("msghdr","msg_accrights"); ];
];
"PREAD", L[ fd_int; I "unistd.h"; S"pread"; ];
"PWRITE", L[ fd_int; I "unistd.h"; S"pwrite"; ];
"READ", L[ fd_int; I "unistd.h"; S"read"; ];
"WRITE", L[ fd_int; I "unistd.h"; S"write"; ];
"MKSTEMPS", L[ fd_int; I "stdlib.h"; I "unistd.h"; S"mkstemps"; ];
"MKOSTEMPS", L[ fd_int; I "stdlib.h"; I "unistd.h"; S"mkostemps"; ];
"SETRESUID", L[ I"sys/types.h"; I"unistd.h"; S"setresuid"; S"setresgid" ];
"SYSCONF", L[
I "unistd.h";
S "sysconf";
(* check for standard values and extensions *)
D "_SC_VERSION"; D "_SC_2_VERSION";
];
"SPLICE", L[ fd_int; I "fcntl.h"; S"splice"; ];
"TEE", L[ fd_int; I "fcntl.h"; S"tee"; ];
"VMSPLICE", L[ fd_int; I "fcntl.h"; S"vmsplice"; ];
"SOCKOPT", ANY[
[
fd_int;
I "sys/socket.h"; I "netinet/in.h"; I"netinet/tcp.h";
S"setsockopt"; S"getsockopt";
];
[
I "winsock2.h"; I "ws2tcpip.h";
S"setsockopt"; S"getsockopt";
]
];
"TCP_KEEPIDLE", ANY[
[ I "netinet/in.h"; I "netinet/tcp.h"; V "TCP_KEEPIDLE" ];
[ I "winsock2.h"; I "ws2tcpip.h"; IF ("!defined(TCP_KEEPIDLE) && defined(__MINGW32__)", "TCP_KEEPIDLE", "0x03") ];
];
"TCP_KEEPCNT", ANY[
[ I "netinet/in.h"; I "netinet/tcp.h"; V "TCP_KEEPCNT" ];
[ I "winsock2.h"; I "ws2tcpip.h"; IF ("!defined(TCP_KEEPCNT) && defined(__MINGW32__)", "TCP_KEEPCNT", "0x10") ];
];
"TCP_KEEPINTVL", ANY[
[ I "netinet/in.h"; I "netinet/tcp.h"; V "TCP_KEEPINTVL" ];
[ I "winsock2.h"; I "ws2tcpip.h"; IF ("!defined(TCP_KEEPINTVL) && defined(__MINGW32__)", "TCP_KEEPINTVL", "0x11") ];
];
"SO_REUSEPORT", L[I"sys/socket.h"; V"SO_REUSEPORT"];
"POLL", L[ fd_int; I "poll.h"; S "poll"; D "POLLIN"; D "POLLOUT"; Z "POLLRDHUP" ];
"SYSINFO", L[ I"sys/sysinfo.h"; S"sysinfo"; F ("sysinfo","mem_unit")];
"MCHECK", L[ I"mcheck.h"; S"mtrace"; S"muntrace" ];
"MOUNT", L[ I"sys/mount.h"; S "mount"; S "umount2"; D "MS_REC" ];
"UNSHARE", L[ I"sched.h"; S "unshare"; D "CLONE_NEWPID"; D "CLONE_NEWUSER"];
"CHROOT", L[ I"unistd.h"; S "chroot"; ];
"SYSLOG", L[I"syslog.h"; S "syslog"; S "openlog"; S "closelog"; S "setlogmask"; D "LOG_PID"; D "LOG_CONS"; D "LOG_NDELAY"; D "LOG_ODELAY"; D "LOG_NOWAIT"; D "LOG_EMERG"; D "LOG_ALERT"; D "LOG_CRIT"; D "LOG_ERR"; D "LOG_WARNING"; D "LOG_NOTICE"; D "LOG_INFO"; D "LOG_DEBUG"];
]
let () =
let args0 = [
"-v", Arg.Unit (fun () -> verbose := 2), " Show code for failed tests";
"-q", Arg.Unit (fun () -> verbose := 0), " Do not show stderr from children";
] in
let args1 = List.map (fun (name,_) ->
assert (not (String.contains name ' '));
"--disable-" ^ String.lowercase_ascii name,
Arg.Unit (fun () -> disabled := name :: !disabled),
" disable " ^ name) features
in
let args = Arg.align (args0 @ args1) in
C.main ~args:args ~name:"extunix" (fun c -> main c features)
ocaml-extunix-0.3.2/discover/discover.mli 0000664 0000000 0000000 00000000000 14045766433 0020452 0 ustar 00root root 0000000 0000000 ocaml-extunix-0.3.2/discover/dune 0000664 0000000 0000000 00000000075 14045766433 0017023 0 ustar 00root root 0000000 0000000 (executable
(name discover)
(libraries dune.configurator))
ocaml-extunix-0.3.2/dune-project 0000664 0000000 0000000 00000002416 14045766433 0016652 0 ustar 00root root 0000000 0000000 (lang dune 2.2)
;(use_standard_c_and_cxx_flags true)
(name extunix)
(generate_opam_files true)
(package
(name extunix)
(depends
(ocaml (>= 4.06))
(dune-configurator :build)
(ppxlib (and (>= 0.18) :build))
(ounit2 :with-test)
base-bytes
base-bigarray
base-unix
)
(synopsis "Collection of thin bindings to various low-level system API")
(description
"\| Motto: "Be to Unix, what extlib is to stdlib"
"\|
"\| * Implement thin C bindings that directly map to underlying system API.
"\| * Provide common consistent ocaml interface: naming convention, exceptions.
"\| * Simple to build - no extra dependencies.
)
(license "LGPL-2.1-only with OCaml-LGPL-linking-exception")
(authors
"Andre Nathan"
"Antonin Décimo"
"Dmitry Grebeniuk"
"François Bobot"
"Gerd Stolpmann"
"Goswin von Brederlow"
"Joshua Smith"
"Kaustuv Chaudhuri"
"Markus W. Weissmann"
"Mehdi Dogguy"
"Niki Yoshiuchi"
"Pierre Chambart"
"Roman Vorobets"
"Stéphane Glondu"
"Sylvain Le Gall"
"ygrek"
"Zhenya Lykhovyd"
)
(maintainers "ygrek@autistici.org")
(source (github ygrek/extunix))
(bug_reports "https://github.com/ygrek/extunix/issues")
(homepage "https://ygrek.org/p/ocaml-extunix")
(documentation "https://ygrek.org/p/ocaml-extunix")
(tags ("org:ygrek")))
ocaml-extunix-0.3.2/extunix.opam 0000664 0000000 0000000 00000002674 14045766433 0016720 0 ustar 00root root 0000000 0000000 # This file is generated by dune, edit dune-project instead
opam-version: "2.0"
synopsis: "Collection of thin bindings to various low-level system API"
description: """
Motto: "Be to Unix, what extlib is to stdlib"
* Implement thin C bindings that directly map to underlying system API.
* Provide common consistent ocaml interface: naming convention, exceptions.
* Simple to build - no extra dependencies.
"""
maintainer: ["ygrek@autistici.org"]
authors: [
"Andre Nathan"
"Antonin Décimo"
"Dmitry Grebeniuk"
"François Bobot"
"Gerd Stolpmann"
"Goswin von Brederlow"
"Joshua Smith"
"Kaustuv Chaudhuri"
"Markus W. Weissmann"
"Mehdi Dogguy"
"Niki Yoshiuchi"
"Pierre Chambart"
"Roman Vorobets"
"Stéphane Glondu"
"Sylvain Le Gall"
"ygrek"
"Zhenya Lykhovyd"
]
license: "LGPL-2.1-only with OCaml-LGPL-linking-exception"
tags: ["org:ygrek"]
homepage: "https://ygrek.org/p/ocaml-extunix"
doc: "https://ygrek.org/p/ocaml-extunix"
bug-reports: "https://github.com/ygrek/extunix/issues"
depends: [
"dune" {>= "2.2"}
"ocaml" {>= "4.06"}
"dune-configurator" {build}
"ppxlib" {>= "0.18" & build}
"ounit2" {with-test}
"base-bytes"
"base-bigarray"
"base-unix"
]
build: [
["dune" "subst"] {pinned}
[
"dune"
"build"
"-p"
name
"-j"
jobs
"@install"
"@runtest" {with-test}
"@doc" {with-doc}
]
]
dev-repo: "git+https://github.com/ygrek/extunix.git"
depexts: [["libexecinfo-dev"] {os = "alpine"}]
ocaml-extunix-0.3.2/extunix.opam.template 0000664 0000000 0000000 00000000057 14045766433 0020523 0 ustar 00root root 0000000 0000000 depexts: [["libexecinfo-dev"] {os = "alpine"}]
ocaml-extunix-0.3.2/ppx_have/ 0000775 0000000 0000000 00000000000 14045766433 0016137 5 ustar 00root root 0000000 0000000 ocaml-extunix-0.3.2/ppx_have/dune 0000664 0000000 0000000 00000000262 14045766433 0017015 0 ustar 00root root 0000000 0000000 (copy_files ../src/extUnixConfig.ml)
(library
(name ppx_have)
(modules Ppx_have ExtUnixConfig)
(kind ppx_rewriter)
(libraries ppxlib)
(preprocess
(pps ppxlib.metaquot)))
ocaml-extunix-0.3.2/ppx_have/ppx_have.ml 0000664 0000000 0000000 00000011074 14045766433 0020306 0 ustar 00root root 0000000 0000000 let all = ref false
let funcs = Hashtbl.create 16
let args_spec =
[
("--gen-all", Arg.Set all, "generate values from all [%%have ...] sections");
]
(* module ExtUnixConfig = Config *)
open Ppxlib
let check ~loc name =
match ExtUnixConfig.feature name with
| None -> Location.raise_errorf ~loc "Unregistered feature %s" name
| Some have -> have
let ident x = Ocaml_common.Location.mknoloc (lident x)
(* Evaluating conditions *)
let atom_of_expr ~loc expr =
match expr.pexp_desc with
| Pexp_construct ({ txt = Longident.Lident x; _ }, None) -> x
| _ -> Location.raise_errorf ~loc "have: atom_of_expr"
let conj_of_expr ~loc expr =
match expr.pexp_desc with
| Pexp_construct _ -> [ atom_of_expr ~loc expr ]
| Pexp_tuple args -> List.map (atom_of_expr ~loc) args
| _ -> Location.raise_errorf ~loc "have: conj_of_expr"
let disj_of_expr ~loc expr =
match expr.pexp_desc with
| Pexp_construct _ -> [ [ atom_of_expr ~loc expr ] ]
| Pexp_tuple args -> List.map (conj_of_expr ~loc) args
| _ -> Location.raise_errorf ~loc "have: disj_of_expr"
let eval_cond ~loc cond =
match cond.pstr_desc with
| Pstr_eval (expr, _attributes) ->
List.exists (List.for_all (check ~loc)) (disj_of_expr ~loc expr)
| _ -> Location.raise_errorf ~loc "have: eval_cond"
(* have rule *)
let invalid_external ~loc =
let open Ast_builder.Default in
let rec make_dummy_f ~loc body typ =
match typ.ptyp_desc with
| Ptyp_arrow (l, arg, ret) ->
let arg =
match l with Optional _ -> [%type: [%t arg] option] | _ -> arg
in
let e = make_dummy_f ~loc body ret in
pexp_fun ~loc l None [%pat? (_ : [%t arg])] e
| _ -> [%expr ([%e body] : [%t typ])]
in
let raise_not_available ~loc x =
let e = pexp_constant ~loc (Pconst_string (x, loc, None)) in
[%expr raise (Not_available [%e e])]
in
let externals_of =
object
inherit Ast_traverse.map as super
method! structure_item x =
match x.pstr_desc with
| Pstr_primitive p ->
let body = raise_not_available ~loc p.pval_name.txt in
let expr = make_dummy_f ~loc body p.pval_type in
let pat = ppat_var ~loc p.pval_name in
let vb = value_binding ~loc ~pat ~expr in
let vb =
{ vb with pvb_attributes = p.pval_attributes @ vb.pvb_attributes }
in
pstr_value ~loc Nonrecursive [ vb ]
| _ -> super#structure_item x
end
in
externals_of#structure_item
let record_external have =
let externals_of =
object
inherit Ast_traverse.iter as super
method! structure_item x =
match x.pstr_desc with
| Pstr_primitive p -> Hashtbl.replace funcs p.pval_name.txt have
| _ -> super#structure_item x
end
in
externals_of#structure_item
let have_expand ~ctxt cond items =
let loc = Expansion_context.Extension.extension_point_loc ctxt in
let have = eval_cond ~loc cond in
List.iter (record_external have) items;
match (have, !all) with
| true, _ -> items
| false, true -> List.map (invalid_external ~loc) items
| false, false -> []
let have_extension =
Extension.V3.declare_inline "have" Extension.Context.structure_item
Ast_pattern.(pstr (__ ^:: __))
have_expand
let have_rule = Context_free.Rule.extension have_extension
(* show_me_the_money rule *)
let show_me_the_money_expand ~ctxt doc =
let loc = Expansion_context.Extension.extension_point_loc ctxt in
let open Ast_builder.Default in
let make_have () =
Hashtbl.fold
(fun func have acc ->
let lhs = ppat_constant ~loc (Pconst_string (func, loc, None)) in
let e = pexp_construct ~loc (ident (string_of_bool have)) None in
case ~lhs ~guard:None ~rhs:[%expr Some [%e e]] :: acc)
funcs
[ case ~lhs:[%pat? _] ~guard:None ~rhs:[%expr None] ]
in
if !all then
let expr = pexp_function ~loc (make_have ()) in
let pat = ppat_var ~loc (Ocaml_common.Location.mknoloc "have") in
let vb = value_binding ~loc ~pat ~expr in
let vb = { vb with pvb_attributes = doc :: vb.pvb_attributes } in
[ pstr_value ~loc Nonrecursive [ vb ] ]
else []
let show_me_the_money_extension =
Extension.V3.declare_inline "show_me_the_money"
Extension.Context.structure_item
Ast_pattern.(pstr (pstr_attribute __ ^:: nil))
show_me_the_money_expand
let show_me_the_money_rule =
Context_free.Rule.extension show_me_the_money_extension
let () =
List.iter (fun (key, spec, doc) -> Driver.add_arg key spec ~doc) args_spec;
let rules = [ have_rule; show_me_the_money_rule ] in
Driver.register_transformation ~rules "ppx_have"
ocaml-extunix-0.3.2/src/ 0000775 0000000 0000000 00000000000 14045766433 0015114 5 ustar 00root root 0000000 0000000 ocaml-extunix-0.3.2/src/TODO/ 0000775 0000000 0000000 00000000000 14045766433 0015661 5 ustar 00root root 0000000 0000000 ocaml-extunix-0.3.2/src/TODO/ftruncate/ 0000775 0000000 0000000 00000000000 14045766433 0017654 5 ustar 00root root 0000000 0000000 ocaml-extunix-0.3.2/src/TODO/ftruncate/ftruncate.ml 0000664 0000000 0000000 00000001032 14045766433 0022175 0 ustar 00root root 0000000 0000000
(** Truncate file
@author Sylvain Le Gall
*)
(**/**)
let is_win32 =
Sys.os_type = "Win32"
;;
external win32_ftruncate: Unix.file_descr -> int -> unit =
"caml_ftruncate_win32"
;;
(**/**)
let ftruncate =
if is_win32 then
win32_ftruncate
else
Unix.ftruncate
;;
module LargeFile =
struct
(**/**)
external win32_ftruncate: Unix.file_descr -> int64 -> unit =
"caml_ftruncate64_win32"
(**/**)
let ftruncate =
if is_win32 then
win32_ftruncate
else
Unix.LargeFile.ftruncate
end;;
ocaml-extunix-0.3.2/src/TODO/ftruncate/ftruncateC.c 0000664 0000000 0000000 00000003613 14045766433 0022121 0 ustar 00root root 0000000 0000000
/*
* ftruncate C binding
*
* Copyright 2008-2009 Talend, Inc.
*
* License LGPL-2.1 with OCaml linking static exception
*
* For more information go to: www.talend.com
*
* author: Sylvain Le Gall
*
*/
#include
#include
#include
#ifdef WINDOWS
static void caml_ftruncate_win32_error (void)
{
win32_maperr(GetLastError());
uerror("ftruncate", Val_unit);
};
static __int64 caml_ftruncate_win32_lseek (HANDLE hFile, __int64 i64Pos, DWORD dwMoveMethod)
{
LARGE_INTEGER liRes;
liRes.QuadPart = i64Pos;
liRes.LowPart = SetFilePointer(hFile, liRes.LowPart, &liRes.HighPart, dwMoveMethod);
if (liRes.LowPart == INVALID_SET_FILE_POINTER &&
GetLastError() != NO_ERROR)
{
caml_ftruncate_win32_error();
};
return liRes.QuadPart;
};
static void caml_ftruncate_win32_do (HANDLE hFile, __int64 i64Len)
{
__int64 i64Cur = 0;
/* Save actual file offset */
i64Cur = caml_ftruncate_win32_lseek(hFile, 0, FILE_CURRENT);
/* Goto expected end */
caml_ftruncate_win32_lseek(hFile, i64Len, FILE_BEGIN);
/* Set end */
if (!SetEndOfFile(hFile))
{
caml_ftruncate_win32_error();
};
/* Restore file offset */
caml_ftruncate_win32_lseek(hFile, i64Cur, FILE_BEGIN);
};
CAMLprim value caml_ftruncate_win32 (value vfd, value vlen)
{
CAMLparam2(vfd, vlen);
caml_ftruncate_win32_do(Handle_val(vfd), Long_val(vlen));
CAMLreturn(Val_unit);
}
CAMLprim value caml_ftruncate64_win32 (value vfd, value vlen)
{
CAMLparam2(vfd, vlen);
caml_ftruncate_win32_do(Handle_val(vfd), Int64_val(vlen));
CAMLreturn(Val_unit);
}
#else
CAMLprim value caml_ftruncate_win32 (value vfd, value vlen)
{
CAMLparam2(vfd, vlen);
caml_failwith("Not implemented");
CAMLreturn(Val_unit);
}
CAMLprim value caml_ftruncate64_win32 (value vfd, value vlen)
{
CAMLparam2(vfd, vlen);
caml_failwith("Not implemented");
CAMLreturn(Val_unit);
}
#endif
ocaml-extunix-0.3.2/src/atfile.c 0000664 0000000 0000000 00000014734 14045766433 0016535 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_ATFILE
#include "config.h"
#if defined(EXTUNIX_HAVE_ATFILE)
/* otherlibs/unix/cst2constr.h */
extern value cst_to_constr(int n, int * tbl, int size, int deflt);
static int file_kind_table[] = {
S_IFREG, S_IFDIR, S_IFCHR, S_IFBLK, S_IFLNK, S_IFIFO, S_IFSOCK
};
#ifndef AT_EACCESS
#define AT_EACCESS 0
#endif
#ifndef AT_SYMLINK_NOFOLLOW
#define AT_SYMLINK_NOFOLLOW 0
#endif
#ifndef AT_SYMLINK_FOLLOW
#define AT_SYMLINK_FOLLOW 0
#endif
#ifndef AT_NO_AUTOMOUNT
#define AT_NO_AUTOMOUNT 0
#endif
static int at_flags_table[] = {
AT_EACCESS, AT_SYMLINK_NOFOLLOW, AT_REMOVEDIR, AT_SYMLINK_FOLLOW, AT_NO_AUTOMOUNT,
};
static value stat_aux(/*int use_64,*/ struct stat *buf)
{
CAMLparam0();
CAMLlocal5(atime, mtime, ctime, offset, v);
atime = caml_copy_double((double) buf->st_atime);
mtime = caml_copy_double((double) buf->st_mtime);
ctime = caml_copy_double((double) buf->st_ctime);
offset = /*use_64 ? Val_file_offset(buf->st_size) :*/ Val_int (buf->st_size);
v = caml_alloc_small(12, 0);
Field (v, 0) = Val_int (buf->st_dev);
Field (v, 1) = Val_int (buf->st_ino);
Field (v, 2) = cst_to_constr(buf->st_mode & S_IFMT, file_kind_table,
sizeof(file_kind_table) / sizeof(int), 0);
Field (v, 3) = Val_int (buf->st_mode & 07777);
Field (v, 4) = Val_int (buf->st_nlink);
Field (v, 5) = Val_int (buf->st_uid);
Field (v, 6) = Val_int (buf->st_gid);
Field (v, 7) = Val_int (buf->st_rdev);
Field (v, 8) = offset;
Field (v, 9) = atime;
Field (v, 10) = mtime;
Field (v, 11) = ctime;
CAMLreturn(v);
}
CAMLprim value caml_extunix_fstatat(value v_dirfd, value v_name, value v_flags)
{
CAMLparam3(v_dirfd, v_name, v_flags);
int ret;
struct stat buf;
char* p = strdup(String_val(v_name));
int flags = caml_convert_flag_list(v_flags, at_flags_table);
flags &= (AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT); /* only allowed flags here */
caml_enter_blocking_section();
ret = fstatat(Int_val(v_dirfd), p, &buf, flags);
caml_leave_blocking_section();
free(p);
if (ret != 0) uerror("fstatat", v_name);
if (buf.st_size > Max_long && (buf.st_mode & S_IFMT) == S_IFREG)
unix_error(EOVERFLOW, "fstatat", v_name);
CAMLreturn(stat_aux(/*0,*/ &buf));
}
CAMLprim value caml_extunix_unlinkat(value v_dirfd, value v_name, value v_flags)
{
CAMLparam3(v_dirfd, v_name, v_flags);
char* p = strdup(String_val(v_name));
int ret = 0;
int flags = caml_convert_flag_list(v_flags, at_flags_table);
flags &= AT_REMOVEDIR; /* only allowed flag here */
caml_enter_blocking_section();
ret = unlinkat(Int_val(v_dirfd), p, flags);
caml_leave_blocking_section();
free(p);
if (ret != 0) uerror("unlinkat", v_name);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_renameat(value v_oldfd, value v_oldname, value v_newfd, value v_newname)
{
CAMLparam4(v_oldfd, v_oldname, v_newfd, v_newname);
int ret = renameat(Int_val(v_oldfd), String_val(v_oldname), Int_val(v_newfd), String_val(v_newname));
if (ret != 0) uerror("renameat", v_oldname);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_mkdirat(value v_dirfd, value v_name, value v_mode)
{
CAMLparam3(v_dirfd, v_name, v_mode);
int ret = mkdirat(Int_val(v_dirfd), String_val(v_name), Int_val(v_mode));
if (ret != 0) uerror("mkdirat", v_name);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_linkat(value v_olddirfd, value v_oldname, value v_newdirfd, value v_newname, value v_flags)
{
CAMLparam5(v_olddirfd, v_oldname, v_newdirfd, v_newname, v_flags);
int ret = 0;
int flags = caml_convert_flag_list(v_flags, at_flags_table);
flags &= AT_SYMLINK_FOLLOW; /* only allowed flag here */
ret = linkat(Int_val(v_olddirfd), String_val(v_oldname), Int_val(v_newdirfd), String_val(v_newname), flags);
if (ret != 0) uerror("linkat", v_oldname);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_fchownat(value v_dirfd, value v_name, value v_owner, value v_group, value v_flags)
{
CAMLparam5(v_dirfd, v_name, v_owner, v_group, v_flags);
int ret = 0;
int flags = caml_convert_flag_list(v_flags, at_flags_table);
flags &= (AT_SYMLINK_NOFOLLOW /* | AT_EMPTY_PATH */); /* only allowed flag here */
ret = fchownat(Int_val(v_dirfd), String_val(v_name), Int_val(v_owner), Int_val(v_group), flags);
if (ret != 0) uerror("fchownat", v_name);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_fchmodat(value v_dirfd, value v_name, value v_mode, value v_flags)
{
CAMLparam4(v_dirfd, v_name, v_mode, v_flags);
int ret = 0;
int flags = caml_convert_flag_list(v_flags, at_flags_table);
flags &= AT_SYMLINK_NOFOLLOW; /* only allowed flag here */
ret = fchmodat(Int_val(v_dirfd), String_val(v_name), Int_val(v_mode), flags);
if (ret != 0) uerror("fchmodat", v_name);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_symlinkat(value v_path, value v_newdirfd, value v_newname)
{
CAMLparam3(v_path, v_newdirfd, v_newname);
int ret = symlinkat(String_val(v_path), Int_val(v_newdirfd), String_val(v_newname));
if (ret != 0) uerror("symlinkat", v_path);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_openat(value v_dirfd, value path, value flags, value perm)
{
CAMLparam4(v_dirfd, path, flags, perm);
int ret, cv_flags;
char * p;
cv_flags = extunix_open_flags(flags);
p = strdup(String_val(path));
/* open on a named FIFO can block (PR#1533) */
caml_enter_blocking_section();
ret = openat(Int_val(v_dirfd), p, cv_flags, Int_val(perm));
caml_leave_blocking_section();
free(p);
if (ret == -1) uerror("openat", path);
CAMLreturn (Val_int(ret));
}
char *readlinkat_malloc (int dirfd, const char *filename)
{
int size = 100;
int nchars;
char *buffer = NULL;
char *tmp;
while (1)
{
tmp = (char *) realloc (buffer, size);
if (tmp == NULL)
{
free(buffer); /* if failed, dealloc is not performed */
return NULL;
}
buffer = tmp;
nchars = readlinkat (dirfd, filename, buffer, size);
if (nchars < 0)
{
free (buffer);
return NULL;
}
if (nchars < size)
{
buffer[nchars] = '\0';
return buffer;
}
size *= 2;
}
}
CAMLprim value caml_extunix_readlinkat(value v_dirfd, value v_name)
{
CAMLparam2(v_dirfd, v_name);
CAMLlocal1(v_link);
char* res;
char* p = strdup(String_val(v_name));
caml_enter_blocking_section();
res = readlinkat_malloc(Int_val(v_dirfd), p);
caml_leave_blocking_section();
free(p);
if (res == NULL) uerror("readlinkat", v_name);
v_link = caml_copy_string(res);
free(res);
CAMLreturn(v_link);
}
#endif
ocaml-extunix-0.3.2/src/bigarray.c 0000664 0000000 0000000 00000001414 14045766433 0017060 0 ustar 00root root 0000000 0000000 #include "config.h"
/* Copyright © 2012 Goswin von Brederlow */
CAMLprim value caml_extunixba_get_substr(value v_buf, value v_off, value v_len)
{
CAMLparam3(v_buf, v_off, v_len);
CAMLlocal1(v_str);
char *buf = (char*)Caml_ba_data_val(v_buf);
size_t off = Long_val(v_off);
size_t len = Long_val(v_len);
v_str = caml_alloc_initialized_string(len, buf + off);
CAMLreturn(v_str);
}
CAMLprim value caml_extunixba_set_substr(value v_buf, value v_off, value v_str)
{
CAMLparam3(v_buf, v_off, v_str);
char *buf = (char*)Caml_ba_data_val(v_buf);
size_t off = Long_val(v_off);
size_t len = caml_string_length(v_str);
const char *str = String_val(v_str);
memcpy(buf + off, str, len);
CAMLreturn(Val_unit);
}
ocaml-extunix-0.3.2/src/common.c 0000664 0000000 0000000 00000001677 14045766433 0016563 0 ustar 00root root 0000000 0000000 #include "config.h"
#include
/* otherlibs/unix/open.c */
#ifndef O_NONBLOCK
#ifndef O_NDELAY
#define O_NDELAY 0
#endif
#define O_NONBLOCK O_NDELAY
#endif
#ifndef O_NOCTTY
#define O_NOCTTY 0
#endif
#ifndef O_DSYNC
#define O_DSYNC 0
#endif
#ifndef O_SYNC
#define O_SYNC 0
#endif
#ifndef O_RSYNC
#define O_RSYNC 0
#endif
#ifndef O_CLOEXEC
#define O_CLOEXEC 0
#endif
#ifndef O_KEEPEXEC
#define O_KEEPEXEC 0
#endif
static int open_flag_table[] = {
O_RDONLY, O_WRONLY, O_RDWR, O_NONBLOCK, O_APPEND, O_CREAT, O_TRUNC, O_EXCL,
O_NOCTTY, O_DSYNC, O_SYNC, O_RSYNC, 0 /* O_SHARE_DELETE */, O_CLOEXEC, O_KEEPEXEC,
};
int extunix_open_flags(value list)
{
int res;
int flag;
res = 0;
while (list != Val_int(0))
{
flag = Int_val(Field(list, 0));
if (flag >= 0 && (size_t)flag < sizeof(open_flag_table)/sizeof(open_flag_table[0])) /* new flags - ignore */
res |= open_flag_table[flag];
list = Field(list, 1);
}
return res;
}
ocaml-extunix-0.3.2/src/common.h 0000664 0000000 0000000 00000000263 14045766433 0016556 0 ustar 00root root 0000000 0000000 #define UNUSED(x) (void)(x)
#include
#if OCAML_VERSION < 41200
#define Val_none Val_int(0)
#define Some_val(v) Field(v,0)
#endif
int extunix_open_flags(value);
ocaml-extunix-0.3.2/src/dirfd.c 0000664 0000000 0000000 00000000545 14045766433 0016354 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_DIRFD
#include "config.h"
#if defined(EXTUNIX_HAVE_DIRFD)
CAMLprim value caml_extunix_dirfd(value v_dir)
{
CAMLparam1(v_dir);
int fd = -1;
DIR* dir = DIR_Val(v_dir);
if (dir == (DIR *) NULL) unix_error(EBADF, "dirfd", Nothing);
fd = dirfd(dir);
if (fd < 0) uerror("dirfd", Nothing);
CAMLreturn(Val_int(fd));
}
#endif
ocaml-extunix-0.3.2/src/dune 0000664 0000000 0000000 00000002155 14045766433 0015775 0 ustar 00root root 0000000 0000000 (rule
(targets config.h extUnixConfig.ml ldlibs.sexp)
(deps
(:gen ../discover/discover.exe))
(action
(run %{gen})))
(rule
(action
(progn
(copy extUnix.pp.ml extUnixAll.ml)
(copy extUnix.pp.ml extUnixSpecific.ml))))
(library
(name ExtUnix)
(public_name extunix)
(modules_without_implementation ExtUnix)
(wrapped (transition "use ExtUnix.All or ExtUnix.Specific instead, top-level modules ExtUnixAll and ExtUnixSpecific will be gone soon."))
(libraries unix bigarray bytes)
(preprocess
(per_module
((pps ppx_have --gen-all)
ExtUnixAll)
((pps ppx_have)
ExtUnixSpecific)))
(c_library_flags
(:include ldlibs.sexp))
(foreign_stubs
(language c)
(flags :standard)
(names
atfile
bigarray
common
dirfd
endian
endianba
execinfo
fadvise
fallocate
fexecve
fsync
ioctl_siocgifconf
malloc
memalign
mktemp
mman
mount
poll
pread_pwrite_ba
ptrace
pts
read_cred
resource
sendmsg
signalfd
sockopt
splice
statvfs
stdlib
sysconf
sysinfo
syslog
time
tty_ioctl
uname
unistd
unshare
eventfd)))
ocaml-extunix-0.3.2/src/endian.c 0000664 0000000 0000000 00000010443 14045766433 0016520 0 ustar 00root root 0000000 0000000 #define EXTUNIX_WANT_ENDIAN
#include "config.h"
#include "endian_helper.h"
#include
/* Copyright © 2012 Goswin von Brederlow */
/* Convert an intX_t from one endianness to another */
#define CONV(name, type, conv, type_val, val_type) \
CAMLprim value caml_extunix_##name(value v_x) \
{ \
type x = type_val(v_x); \
x = conv(x); \
return (val_type(x)); \
}
/* Get an intX_t out of a string */
#define GET(name, type, conv, Val_type) \
CAMLprim value caml_extunix_get_##name(value v_str, value v_off) { \
const char *str = String_val(v_str); \
size_t off = Long_val(v_off); \
type x; \
memcpy(&x, str + off, sizeof(x)); \
x = conv(x); \
return (Val_type(x)); \
}
/* Store an intX_t in a string */
#define SET(name, type, conv, Type_val) \
CAMLprim value caml_extunix_set_##name(value v_str, value v_off, value v_x) { \
unsigned char *str = Bytes_val(v_str); \
size_t off = Long_val(v_off); \
type x = Type_val(v_x); \
x = conv(x); \
memcpy(str + off, &x, sizeof(x)); \
return Val_unit; \
}
#if defined(EXTUNIX_HAVE_ENDIAN)
/* Big endian */
CONV(htobe16, uint16_t, htobe16, Long_val, Val_long)
CONV(htobe16_signed, int16_t, htobe16, Long_val, Val_long)
CONV(be16toh, uint16_t, be16toh, Long_val, Val_long)
CONV(be16toh_signed, int16_t, be16toh, Long_val, Val_long)
CONV(htobe31, uint32_t, htobe32, Long_val, Val_long)
CONV(htobe31_signed, int32_t, htobe32, Long_val, Val_long)
CONV(be31toh, uint32_t, be32toh, Long_val, Val_long)
CONV(be31toh_signed, int32_t, be32toh, Long_val, Val_long)
CONV(htobe32, int32_t, htobe32, Int32_val, caml_copy_int32)
CONV(be32toh, int32_t, be32toh, Int32_val, caml_copy_int32)
CONV(htobe64, int64_t, htobe64, Int64_val, caml_copy_int64)
CONV(be64toh, int64_t, be64toh, Int64_val, caml_copy_int64)
GET(bu16, uint16_t, be16toh, Val_long)
GET(bs16, int16_t, be16toh, Val_long)
GET(bu31, uint32_t, be32toh, Val_long)
GET(bs31, int32_t, be32toh, Val_long)
GET(bs32, int32_t, be32toh, caml_copy_int32)
GET(bu63, uint64_t, be64toh, Val_long)
GET(bs63, int64_t, be64toh, Val_long)
GET(bs64, int64_t, be64toh, caml_copy_int64)
SET(b16, uint16_t, htobe16, Long_val)
SET(b31, uint32_t, htobe32, Long_val)
SET(b32, uint32_t, htobe32, Int32_val)
SET(b63, uint64_t, htobe64, Long_val)
SET(b64, uint64_t, htobe64, Int64_val)
/* Little endian */
CONV(htole16, uint16_t, htole16, Long_val, Val_long)
CONV(htole16_signed, int16_t, htole16, Long_val, Val_long)
CONV(le16toh, uint16_t, le16toh, Long_val, Val_long)
CONV(le16toh_signed, int16_t, le16toh, Long_val, Val_long)
CONV(htole31, uint32_t, htole32, Long_val, Val_long)
CONV(htole31_signed, int32_t, htole32, Long_val, Val_long)
CONV(le31toh, uint32_t, le32toh, Long_val, Val_long)
CONV(le31toh_signed, int32_t, le32toh, Long_val, Val_long)
CONV(htole32, int32_t, htole32, Int32_val, caml_copy_int32)
CONV(le32toh, int32_t, le32toh, Int32_val, caml_copy_int32)
CONV(htole64, int64_t, htole64, Int64_val, caml_copy_int64)
CONV(le64toh, int64_t, le64toh, Int64_val, caml_copy_int64)
GET(lu16, uint16_t, le16toh, Val_long)
GET(ls16, int16_t, le16toh, Val_long)
GET(lu31, uint32_t, le32toh, Val_long)
GET(ls31, int32_t, le32toh, Val_long)
GET(ls32, int32_t, le32toh, caml_copy_int32)
GET(lu63, uint64_t, le64toh, Val_long)
GET(ls63, int64_t, le64toh, Val_long)
GET(ls64, int64_t, le64toh, caml_copy_int64)
SET(l16, uint16_t, htole16, Long_val)
SET(l31, uint32_t, htole32, Long_val)
SET(l32, uint32_t, htole32, Int32_val)
SET(l63, uint64_t, htole64, Long_val)
SET(l64, uint64_t, htole64, Int64_val)
#endif /* EXTUNIX_HAVE_ENDIAN */
/* Host endian */
#define id(x) x
GET(u8, uint8_t, id, Val_long)
GET(s8, int8_t, id, Val_long)
GET(hu16, uint16_t, id, Val_long)
GET(hs16, int16_t, id, Val_long)
GET(hu31, uint32_t, id, Val_long)
GET(hs31, int32_t, id, Val_long)
GET(hs32, int32_t, id, caml_copy_int32)
GET(hu63, uint64_t, id, Val_long)
GET(hs63, int64_t, id, Val_long)
GET(hs64, int64_t, id, caml_copy_int64)
SET(8, uint8_t, id, Long_val)
SET(h16, uint16_t, id, Long_val)
SET(h31, uint32_t, id, Long_val)
SET(h32, uint32_t, id, Int32_val)
SET(h63, uint64_t, id, Long_val)
SET(h64, uint64_t, id, Int64_val)
ocaml-extunix-0.3.2/src/endian_helper.h 0000664 0000000 0000000 00000005002 14045766433 0020057 0 ustar 00root root 0000000 0000000 /*
From https://gist.github.com/panzi/6856583
// "License": Public Domain
// I, Mathias Panzenböck, place this file hereby into the public domain. Use it at your own risk for whatever you like.
// In case there are jurisdictions that don't support putting things in the public domain you can also consider it to
// be "dual licensed" under the BSD, MIT and Apache licenses, if you want to. This code is trivial anyway. Consider it
// an example on how to get the endian conversion functions on different platforms.
*/
/* Mac OS */
#if defined(EXTUNIX_USE_OSBYTEORDER_H)
# define htobe16(x) OSSwapHostToBigInt16(x)
# define htole16(x) OSSwapHostToLittleInt16(x)
# define be16toh(x) OSSwapBigToHostInt16(x)
# define le16toh(x) OSSwapLittleToHostInt16(x)
# define htobe32(x) OSSwapHostToBigInt32(x)
# define htole32(x) OSSwapHostToLittleInt32(x)
# define be32toh(x) OSSwapBigToHostInt32(x)
# define le32toh(x) OSSwapLittleToHostInt32(x)
# define htobe64(x) OSSwapHostToBigInt64(x)
# define htole64(x) OSSwapHostToLittleInt64(x)
# define be64toh(x) OSSwapBigToHostInt64(x)
# define le64toh(x) OSSwapLittleToHostInt64(x)
#endif
/* Windows */
#if defined(EXTUNIX_USE_WINSOCK2_H)
# if BYTE_ORDER == LITTLE_ENDIAN
# define htobe16(x) htons(x)
# define htole16(x) (x)
# define be16toh(x) ntohs(x)
# define le16toh(x) (x)
# define htobe32(x) htonl(x)
# define htole32(x) (x)
# define be32toh(x) ntohl(x)
# define le32toh(x) (x)
# if defined(__MINGW32__)
# define htobe64(x) __builtin_bswap64(x)
# define be64toh(x) __builtin_bswap64(x)
# else
# define htobe64(x) htonll(x)
# define be64toh(x) ntohll(x)
# endif
# define htole64(x) (x)
# define le64toh(x) (x)
# elif BYTE_ORDER == BIG_ENDIAN
/* that would be xbox 360 */
# define htobe16(x) (x)
# define htole16(x) __builtin_bswap16(x)
# define be16toh(x) (x)
# define le16toh(x) __builtin_bswap16(x)
# define htobe32(x) (x)
# define htole32(x) __builtin_bswap32(x)
# define be32toh(x) (x)
# define le32toh(x) __builtin_bswap32(x)
# define htobe64(x) (x)
# define htole64(x) __builtin_bswap64(x)
# define be64toh(x) (x)
# define le64toh(x) __builtin_bswap64(x)
# else
# error byte order not supported
# endif
#endif
/* various BSD */
#ifndef be16toh
# define be16toh(x) betoh16(x)
#endif
#ifndef le16toh
# define le16toh(x) letoh16(x)
#endif
#ifndef be32toh
# define be32toh(x) betoh32(x)
#endif
#ifndef le32toh
# define le32toh(x) letoh32(x)
#endif
#ifndef be64toh
# define be64toh(x) betoh64(x)
#endif
#ifndef le64toh
# define le64toh(x) letoh64(x)
#endif
ocaml-extunix-0.3.2/src/endianba.c 0000664 0000000 0000000 00000005123 14045766433 0017022 0 ustar 00root root 0000000 0000000 #define EXTUNIX_WANT_ENDIAN
#include "config.h"
#include "endian_helper.h"
#include
/* Copyright © 2012 Goswin von Brederlow */
/* Get intX_t out of a buffer */
#define GET(name, type, conv, Val_type) \
CAMLprim value caml_extunixba_get_##name(value v_buf, value v_off) { \
int8_t *buf = (int8_t*)Caml_ba_data_val(v_buf); \
size_t off = Long_val(v_off); \
type x; \
memcpy(&x, buf + off, sizeof(x)); \
x = conv(x); \
return (Val_type(x)); \
}
/* Store intX_t in a buffer */
#define SET(name, type, conv, Type_val) \
CAMLprim value caml_extunixba_set_##name(value v_buf, value v_off, value v_x) { \
int8_t *buf = (int8_t*)Caml_ba_data_val(v_buf); \
size_t off = Long_val(v_off); \
type x = Type_val(v_x); \
x = conv(x); \
memcpy(buf + off, &x, sizeof(x)); \
return Val_unit; \
}
#if defined(EXTUNIX_HAVE_ENDIAN)
/* Big endian */
GET(bu16, uint16_t, be16toh, Val_long)
GET(bs16, int16_t, be16toh, Val_long)
GET(bu31, uint32_t, be32toh, Val_long)
GET(bs31, int32_t, be32toh, Val_long)
GET(bs32, int32_t, be32toh, caml_copy_int32)
GET(bu63, uint64_t, be64toh, Val_long)
GET(bs63, int64_t, be64toh, Val_long)
GET(bs64, int64_t, be64toh, caml_copy_int64)
SET(b16, uint16_t, htobe16, Long_val)
SET(b31, uint32_t, htobe32, Long_val)
SET(b32, uint32_t, htobe32, Int32_val)
SET(b63, uint64_t, htobe64, Long_val)
SET(b64, uint64_t, htobe64, Int64_val)
/* Little endian */
GET(lu16, uint16_t, le16toh, Val_long)
GET(ls16, int16_t, le16toh, Val_long)
GET(lu31, uint32_t, le32toh, Val_long)
GET(ls31, int32_t, le32toh, Val_long)
GET(ls32, int32_t, le32toh, caml_copy_int32)
GET(lu63, uint64_t, le64toh, Val_long)
GET(ls63, int64_t, le64toh, Val_long)
GET(ls64, int64_t, le64toh, caml_copy_int64)
SET(l16, uint16_t, htole16, Long_val)
SET(l31, uint32_t, htole32, Long_val)
SET(l32, uint32_t, htole32, Int32_val)
SET(l63, uint64_t, htole64, Long_val)
SET(l64, uint64_t, htole64, Int64_val)
#endif /* EXTUNIX_HAVE_ENDIAN */
/* Host endian */
#define id(x) x
GET( u8, uint8_t, id, Val_long)
GET( s8, int8_t, id, Val_long)
GET(hu16, uint16_t, id, Val_long)
GET(hs16, int16_t, id, Val_long)
GET(hu31, uint32_t, id, Val_long)
GET(hs31, int32_t, id, Val_long)
GET(hs32, int32_t, id, caml_copy_int32)
GET(hu63, uint64_t, id, Val_long)
GET(hs63, int64_t, id, Val_long)
GET(hs64, int64_t, id, caml_copy_int64)
SET( 8, uint8_t, id, Long_val)
SET(h16, uint16_t, id, Long_val)
SET(h31, uint32_t, id, Long_val)
SET(h32, uint32_t, id, Int32_val)
SET(h63, uint64_t, id, Long_val)
SET(h64, uint64_t, id, Int64_val)
ocaml-extunix-0.3.2/src/eventfd.c 0000664 0000000 0000000 00000001307 14045766433 0016714 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_EVENTFD
#include "config.h"
#if defined(EXTUNIX_HAVE_EVENTFD)
CAMLprim value caml_extunix_eventfd(value v_init)
{
CAMLparam1(v_init);
int fd = eventfd(Int_val(v_init), 0);
if (-1 == fd) uerror("eventfd",Nothing);
CAMLreturn(Val_int(fd));
}
CAMLprim value caml_extunix_eventfd_read(value v_fd)
{
CAMLparam1(v_fd);
eventfd_t v;
if (-1 == eventfd_read(Int_val(v_fd), &v))
uerror("eventfd_read",Nothing);
CAMLreturn(caml_copy_int64(v));
}
CAMLprim value caml_extunix_eventfd_write(value v_fd, value v_val)
{
CAMLparam2(v_fd, v_val);
if (-1 == eventfd_write(Int_val(v_fd), Int64_val(v_val)))
uerror("eventfd_write",Nothing);
CAMLreturn(Val_unit);
}
#endif
ocaml-extunix-0.3.2/src/execinfo.c 0000664 0000000 0000000 00000001024 14045766433 0017055 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_EXECINFO
#include "config.h"
#if defined(EXTUNIX_HAVE_EXECINFO)
CAMLprim value caml_extunix_backtrace(value unit)
{
CAMLparam1(unit);
CAMLlocal1(v_ret);
void *buffer[100];
int nptrs = backtrace(buffer, 100);
int j;
char **strings = backtrace_symbols(buffer, nptrs);
if (NULL == strings)
uerror("backtrace", Nothing);
v_ret = caml_alloc_tuple(nptrs);
for (j = 0; j < nptrs; j++)
Store_field(v_ret,j,caml_copy_string(strings[j]));
free(strings);
CAMLreturn(v_ret);
}
#endif
ocaml-extunix-0.3.2/src/extUnix.mli 0000664 0000000 0000000 00000000511 14045766433 0017260 0 ustar 00root root 0000000 0000000 (** ExtUnix *)
module Specific = ExtUnixSpecific
(** Only functions available on this platform *)
module All = ExtUnixAll
(** All functions,
those not available on this platform will raise [Not_available]
with function name as an argument *)
module Config = ExtUnixConfig
(** Compile-time configuration information *)
ocaml-extunix-0.3.2/src/extUnix.pp.ml 0000664 0000000 0000000 00000343532 14045766433 0017542 0 ustar 00root root 0000000 0000000 (** ExtUnix
These functions are thin wrappers for underlying system API, consult
the corresponding man pages and/or system documentation for details.
*)
(** [Not_available "symbol"] may be raised by functions in {!ExtUnix.All}
if the wrapped C function or constant is not available on this platform.
{!ExtUnix.Specific} includes only functions available on the current
platform and will not raise [Not_available].
Note that libc wrappers underlying {!ExtUnix.Specific} functions may still raise
[ENOSYS] (Not implemented) error even though the function is available. *)
exception Not_available of string
(** type of bigarray used by BA submodules that read from files into
bigarrays or write bigarrays into files. The only constraint here
is [Bigarray.c_layout].
Naming: "bigarray with C layout" -> "carray". *)
type ('a, 'b) carray =
('a, 'b, Bigarray.c_layout) Bigarray.Array1.t
(** type of bigarray used by BA submodules that work with endianness
and memory. Constraints are:
+ [Bigarray.c_layout],
+ bigarray contains 8-bit integers.
Naming: "bigarray with C layout and 8-bit elements" -> "carray8". *)
type 'a carray8 =
('a, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t
type open_flag = Unix.open_flag
(*
= O_RDONLY | O_WRONLY | O_RDWR | O_NONBLOCK | O_APPEND | O_CREAT
| O_TRUNC | O_EXCL | O_NOCTTY | O_DSYNC | O_SYNC | O_RSYNC
| O_SHARE_DELETE | O_CLOEXEC
*)
[%%have EVENTFD
external eventfd : int -> Unix.file_descr = "caml_extunix_eventfd"
external eventfd_read : Unix.file_descr -> int64 = "caml_extunix_eventfd_read"
external eventfd_write : Unix.file_descr -> int64 -> unit = "caml_extunix_eventfd_write"
]
[%%have SYSLOG
module Syslog : sig
type options = LOG_PID | LOG_CONS | LOG_NDELAY | LOG_ODELAY | LOG_NOWAIT
type facility = LOG_KERN | LOG_USER | LOG_MAIL | LOG_NEWS | LOG_UUCP
| LOG_DAEMON | LOG_AUTH | LOG_CRON | LOG_LPR | LOG_LOCAL0 | LOG_LOCAL1
| LOG_LOCAL2 | LOG_LOCAL3 | LOG_LOCAL4 | LOG_LOCAL5 | LOG_LOCAL6
| LOG_LOCAL7
type level = LOG_EMERG | LOG_ALERT | LOG_CRIT | LOG_ERR | LOG_WARNING
| LOG_NOTICE | LOG_INFO | LOG_DEBUG
val setlogmask : level list -> level list
val openlog : ?ident:string -> options list -> facility -> unit
val closelog : unit -> unit
val syslog : ?facility:facility -> level -> ('a, unit, string, unit) format4 -> 'a
val log_upto : level -> level list
end = struct
type options = LOG_PID | LOG_CONS | LOG_NDELAY | LOG_ODELAY | LOG_NOWAIT
type facility = LOG_KERN | LOG_USER | LOG_MAIL | LOG_NEWS | LOG_UUCP
| LOG_DAEMON | LOG_AUTH | LOG_CRON | LOG_LPR | LOG_LOCAL0 | LOG_LOCAL1
| LOG_LOCAL2 | LOG_LOCAL3 | LOG_LOCAL4 | LOG_LOCAL5 | LOG_LOCAL6
| LOG_LOCAL7
type level = LOG_EMERG | LOG_ALERT | LOG_CRIT | LOG_ERR | LOG_WARNING
| LOG_NOTICE | LOG_INFO | LOG_DEBUG
external setlogmask : level list -> level list = "caml_extunix_setlogmask"
external openlog : ?ident:string -> options list -> facility -> unit = "caml_extunix_openlog"
external closelog : unit -> unit = "caml_extunix_closelog"
external ext_syslog : facility option -> level -> string -> unit = "caml_extunix_syslog"
let syslog ?facility lvl = Printf.ksprintf (ext_syslog facility lvl)
let log_upto lvl =
let rec f = function
| [] -> assert false
| x::xs -> if x=lvl then x::xs else f xs
in
f [LOG_DEBUG; LOG_INFO; LOG_NOTICE; LOG_WARNING; LOG_ERR; LOG_CRIT;
LOG_ALERT; LOG_EMERG]
end
]
[%%have UNAME
(** @author Sylvain Le Gall *)
module Uname = struct
type t =
{
sysname: string;
nodename: string;
release: string;
version: string;
machine: string;
}
let to_string t =
String.concat " " [ t.sysname; t.nodename; t.release; t.version; t.machine ]
end
external uname : unit -> Uname.t = "caml_extunix_uname"
]
(** {2 Filesystem} *)
[%%have FSYNC
(** synchronize a file's in-core state with storage device *)
external fsync : Unix.file_descr -> unit = "caml_extunix_fsync"
]
[%%have FDATASYNC
external fdatasync : Unix.file_descr -> unit = "caml_extunix_fdatasync"
]
[%%have SYNC
(** causes all buffered modifications to file metadata and data to be written to the underlying file systems *)
external sync : unit -> unit = "caml_extunix_sync"
]
[%%have SYNCFS
(** like {!sync}, but synchronizes just the file system containing file referred to by the open file descriptor [fd] *)
external syncfs : Unix.file_descr -> unit = "caml_extunix_syncfs"
]
[%%have DIRFD
external dirfd : Unix.dir_handle -> Unix.file_descr = "caml_extunix_dirfd"
]
[%%have (STATVFS, FSTATVFS)
(** file system flags *)
type st_flag =
| ST_RDONLY (** Mount read-only. *)
| ST_NOSUID (** Ignore suid and sgid bits. *)
| ST_NODEV (** Disallow access to device special files. *)
| ST_NOEXEC (** Disallow program execution. *)
| ST_SYNCHRONOUS (** Writes are synced at once. *)
| ST_MANDLOCK (** Allow mandatory locks on an FS. *)
| ST_WRITE (** Write on file/directory/symlink. *)
| ST_APPEND (** Append-only file. *)
| ST_IMMUTABLE (** Immutable file. *)
| ST_NOATIME (** Do not update access times. *)
| ST_NODIRATIME (** Do not update directory access times. *)
| ST_RELATIME (** Update atime relative to mtime/ctime. *)
type statvfs = {
f_bsize : int; (** file system block size *)
f_blocks : int64; (** size of file system in blocks *)
f_bfree : int64; (** free blocks *)
f_bavail : int64; (** free blocks for unprivileged users *)
f_files : int64; (** inodes *)
f_ffree : int64; (** free inodes *)
f_favail : int64; (** free inodes for unprivileged users *)
f_fsid : int64; (** file system ID *)
f_flag : int; (** mount flags (raw value) *)
f_flags : st_flag list; (** mount flags (decoded) *)
f_namemax : int; (** maximum filename length *)
}
]
[%%have STATVFS
(** On Windows, [statvfs root] is emulated. [root] must be the root
directory of the volume to be described. A trailing backslash is
required. The [f_flag] and [f_fsid] fields are retrieved from a
call to [GetVolumeInformation]. Filesystem flags are provided raw
in [f_flag], and only [FILE_READ_ONLY_VOLUME] is mapped to
[ST_RDONLY] in [f_flags]. *)
external statvfs : string -> statvfs = "caml_extunix_statvfs"
]
[%%have FSTATVFS
external fstatvfs : Unix.file_descr -> statvfs = "caml_extunix_fstatvfs"
]
[%%have ATFILE
(*
external at_fdcwd : unit -> Unix.file_descr
(** Pseudo file descriptor denoting current directory *)
let at_fdcwd = at_fdcwd ()
*)
type at_flag = AT_EACCESS | AT_SYMLINK_NOFOLLOW | AT_REMOVEDIR | AT_SYMLINK_FOLLOW | AT_NO_AUTOMOUNT
external openat : Unix.file_descr -> string -> open_flag list -> Unix.file_perm -> Unix.file_descr = "caml_extunix_openat"
(** Supported flags : [AT_SYMLINK_NOFOLLOW AT_NO_AUTOMOUNT] *)
external fstatat : Unix.file_descr -> string -> at_flag list -> Unix.stats = "caml_extunix_fstatat"
(** Supported flags : [AT_REMOVEDIR] *)
external unlinkat : Unix.file_descr -> string -> at_flag list -> unit = "caml_extunix_unlinkat"
external renameat : Unix.file_descr -> string -> Unix.file_descr -> string -> unit = "caml_extunix_renameat"
external mkdirat : Unix.file_descr -> string -> int -> unit = "caml_extunix_mkdirat"
(** Supported flags : [AT_SYMLINK_FOLLOW] *)
external linkat : Unix.file_descr -> string -> Unix.file_descr -> string -> at_flag list -> unit = "caml_extunix_linkat"
external symlinkat : string -> Unix.file_descr -> string -> unit = "caml_extunix_symlinkat"
external readlinkat : Unix.file_descr -> string -> string = "caml_extunix_readlinkat"
external fchownat : Unix.file_descr -> string -> int -> int -> at_flag list -> unit = "caml_extunix_fchownat"
external fchmodat : Unix.file_descr -> string -> int -> at_flag list -> unit = "caml_extunix_fchmodat"
]
(** @raise Not_available if OS does not represent file descriptors as numbers *)
let int_of_file_descr : Unix.file_descr -> int =
if Obj.is_block (Obj.repr Unix.stdin) then
fun _ -> raise (Not_available "int_of_file_descr")
else
Obj.magic
(** @raise Not_available if OS does not represent file descriptors as numbers *)
let file_descr_of_int : int -> Unix.file_descr =
if Obj.is_block (Obj.repr Unix.stdin) then
fun _ -> raise (Not_available "file_descr_of_int")
else
Obj.magic
[%%have FCNTL
(** @return whether file descriptor is open *)
external is_open_descr : Unix.file_descr -> bool = "caml_extunix_is_open_descr"
]
[%%have REALPATH
(** [realpath path]
@return the canonicalized absolute pathname of [path]
*)
external realpath : string -> string = "caml_extunix_realpath"
]
[%%have FADVISE
(** {3 posix_fadvise}
@author Sylvain Le Gall *)
(** access pattern *)
type advice =
| POSIX_FADV_NORMAL (** Indicates that the application has no advice to
give about its access pattern for the specified
data. *)
| POSIX_FADV_SEQUENTIAL (** The application expects to access the specified
data sequentially. *)
| POSIX_FADV_RANDOM (** The specified data will be accessed in random
order. *)
| POSIX_FADV_NOREUSE (** The specified data will be accessed only once. *)
| POSIX_FADV_WILLNEED (** The specified data will be accessed in the near
future. *)
| POSIX_FADV_DONTNEED (** The specified data will not be accessed in the
near future. *)
(** predeclare an access pattern for file data *)
external fadvise: Unix.file_descr -> int -> int -> advice -> unit = "caml_extunix_fadvise"
]
[%%have FALLOCATE
(** {3 posix_fallocate} *)
(** Allocate disk space for file
@author Sylvain Le Gall
*)
(** [fallocate fd off len] allocates disk space to ensure that subsequent writes
between [off] and [off + len] in [fd] will not fail because of lack of disk
space. The file size is modified if [off + len] is bigger than the current size.
*)
external fallocate: Unix.file_descr -> int -> int -> unit = "caml_extunix_fallocate"
]
[%%have PREAD
(** {3 pread}
@author Goswin von Brederlow *)
(** [all_pread fd off buf ofs len] reads up to [len] bytes from file
descriptor [fd] at offset [off] (from the start of the file) into
the string [buf] at offset [ofs]. The file offset is not changed.
[all_pread] repeats the read operation until all characters have
been read or an error occurs. Returns less than the number of
characters requested on EAGAIN, EWOULDBLOCK or End-of-file but
only ever returns 0 on End-of-file. Continues the read operation
on EINTR. Raises an Unix.Unix_error exception in all other
cases. *)
external unsafe_all_pread: Unix.file_descr -> int -> Bytes.t -> int -> int -> int = "caml_extunix_all_pread"
let all_pread fd off buf ofs len =
if off < 0 || ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "ExtUnix.all_pread"
else unsafe_all_pread fd off buf ofs len
(** [single_pread fd off buf ifs len] reads up to [len] bytes from
file descriptor [fd] at offset [off] (from the start of the file)
into the string [buf] at offset [ofs]. The file offset is not
changed.
[single_pread] attempts to read only once. Returns the number of
characters read or raises an Unix.Unix_error exception. *)
external unsafe_single_pread: Unix.file_descr -> int -> Bytes.t -> int -> int -> int = "caml_extunix_single_pread"
let single_pread fd off buf ofs len =
if off < 0 || ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "ExtUnix.single_pread"
else unsafe_single_pread fd off buf ofs len
(** [pread fd off buf ofs len] reads up to [len] bytes from file
descriptor [fd] at offset [off] (from the start of the file) into
the string [buf] at offset [ofs]. The file offset is not changed.
[pread] repeats the read operation until all characters have
been read or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be read before an error occurs. Continues
the read operation on EINTR. Returns the number of characters
written in all other cases. *)
external unsafe_pread: Unix.file_descr -> int -> Bytes.t -> int -> int -> int = "caml_extunix_pread"
let pread fd off buf ofs len =
if off < 0 || ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "ExtUnix.pread"
else unsafe_pread fd off buf ofs len
(** [intr_pread fd off buf ofs len] reads up to [len] bytes from file
descriptor [fd] at offset [off] (from the start of the file) into
the string [buf] at offset [ofs]. The file offset is not changed.
[intr_pread] repeats the read operation until all characters have
been read or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be read before an error occurs. Does NOT
continue on EINTR. Returns the number of characters written in all
other cases. *)
external unsafe_intr_pread: Unix.file_descr -> int -> Bytes.t -> int -> int -> int = "caml_extunix_intr_pread"
let intr_pread fd off buf ofs len =
if off < 0 || ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "ExtUnix.intr_pread"
else unsafe_intr_pread fd off buf ofs len
]
[%%have PWRITE
(** {3 pwrite}
@author Goswin von Brederlow *)
(** [all_pwrite fd off buf ofs len] writes up to [len] bytes from file
descriptor [fd] at offset [off] (from the start of the file) into
the string [buf] at offset [ofs]. The file offset is not changed.
[all_pwrite] repeats the write operation until all characters have
been written or an error occurs. Returns less than the number of
characters requested on EAGAIN, EWOULDBLOCK but never 0. Continues
the write operation on EINTR. Raises an Unix.Unix_error exception
in all other cases. *)
external unsafe_all_pwrite: Unix.file_descr -> int -> string -> int -> int -> int = "caml_extunix_all_pwrite"
let all_pwrite fd off buf ofs len =
if off < 0 || ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "ExtUnix.all_pwrite"
else unsafe_all_pwrite fd off buf ofs len
(** [single_pwrite fd off buf ofs len] writes up to [len] bytes from
file descriptor [fd] at offset [off] (from the start of the file)
into the string [buf] at offset [ofs]. The file offset is not
changed.
[single_pwrite] attempts to write only once. Returns the number of
characters written or raises an Unix.Unix_error exception. *)
external unsafe_single_pwrite: Unix.file_descr -> int -> string -> int -> int -> int = "caml_extunix_single_pwrite"
let single_pwrite fd off buf ofs len =
if off < 0 || ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "ExtUnix.single_pwrite"
else unsafe_single_pwrite fd off buf ofs len
(** [pwrite fd off buf ofs len] writes up to [len] bytes from file
descriptor [fd] at offset [off] (from the start of the file) into
the string [buf] at offset [ofs]. The file offset is not changed.
[pwrite] repeats the write operation until all characters have
been written or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be written before an error occurs. Continues
the write operation on EINTR. Returns the number of characters
written in all other cases. *)
external unsafe_pwrite: Unix.file_descr -> int -> string -> int -> int -> int = "caml_extunix_pwrite"
let pwrite fd off buf ofs len =
if off < 0 || ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "ExtUnix.pwrite"
else unsafe_pwrite fd off buf ofs len
(** [intr_pwrite fd off buf ofs len] writes up to [len] bytes from
file descriptor [fd] at offset [off] (from the start of the file)
into the string [buf] at offset [ofs]. The file offset is not
changed.
[intr_pwrite] repeats the write operation until all characters have
been written or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be written before an error occurs. Does NOT
continue on EINTR. Returns the number of characters written in all
other cases. *)
external unsafe_intr_pwrite: Unix.file_descr -> int -> string -> int -> int -> int = "caml_extunix_intr_pwrite"
let intr_pwrite fd off buf ofs len =
if off < 0 || ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "ExtUnix.intr_pwrite"
else unsafe_intr_pwrite fd off buf ofs len
]
[%%have READ
(** {3 read}
@author Goswin von Brederlow *)
(** [all_read fd buf ofs len] reads up to [len] bytes from file
descriptor [fd] into the string [buf] at offset [ofs].
[all_read] repeats the read operation until all characters have
been read or an error occurs. Returns less than the number of
characters requested on EAGAIN, EWOULDBLOCK or End-of-file but
only ever returns 0 on End-of-file. Continues the read operation
on EINTR. Raises an Unix.Unix_error exception in all other
cases. *)
external unsafe_all_read: Unix.file_descr -> Bytes.t -> int -> int -> int = "caml_extunix_all_read"
let all_read fd buf ofs len =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "ExtUnix.all_read"
else unsafe_all_read fd buf ofs len
(** [single_read fd buf ifs len] reads up to [len] bytes from file
descriptor [fd] into the string [buf] at offset [ofs].
[single_read] attempts to read only once. Returns the number of
characters read or raises an Unix.Unix_error exception. *)
external unsafe_single_read: Unix.file_descr -> Bytes.t -> int -> int -> int = "caml_extunix_single_read"
let single_read fd buf ofs len =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "ExtUnix.single_read"
else unsafe_single_read fd buf ofs len
(** [read fd buf ofs len] reads up to [len] bytes from file descriptor
[fd] into the string [buf] at offset [ofs].
[read] repeats the read operation until all characters have
been read or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be read before an error occurs. Continues
the read operation on EINTR. Returns the number of characters
written in all other cases. *)
external unsafe_read: Unix.file_descr -> Bytes.t -> int -> int -> int = "caml_extunix_read"
let read fd buf ofs len =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "ExtUnix.read"
else unsafe_read fd buf ofs len
(** [intr_read fd buf ofs len] reads up to [len] bytes from file
descriptor [fd] into the string [buf] at offset [ofs].
[intr_read] repeats the read operation until all characters have
been read or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be read before an error occurs. Does NOT
continue on EINTR. Returns the number of characters written in all
other cases. *)
external unsafe_intr_read: Unix.file_descr -> Bytes.t -> int -> int -> int = "caml_extunix_intr_read"
let intr_read fd buf ofs len =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
then invalid_arg "ExtUnix.intr_read"
else unsafe_intr_read fd buf ofs len
]
[%%have WRITE
(** {3 write}
@author Goswin von Brederlow *)
(** [all_write fd buf ofs len] writes up to [len] bytes from file
descriptor [fd] into the string [buf] at offset [ofs].
[all_write] repeats the write operation until all characters have
been written or an error occurs. Returns less than the number of
characters requested on EAGAIN, EWOULDBLOCK but never 0. Continues
the write operation on EINTR. Raises an Unix.Unix_error exception
in all other cases. *)
external unsafe_all_write: Unix.file_descr -> string -> int -> int -> int = "caml_extunix_all_write"
let all_write fd buf ofs len =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "ExtUnix.all_write"
else unsafe_all_write fd buf ofs len
(** [single_write fd buf ofs len] writes up to [len] bytes from file
descriptor [fd] into the string [buf] at offset [ofs].
[single_write] attempts to write only once. Returns the number of
characters written or raises an Unix.Unix_error exception. *)
external unsafe_single_write: Unix.file_descr -> string -> int -> int -> int = "caml_extunix_single_write"
let single_write fd buf ofs len =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "ExtUnix.single_write"
else unsafe_single_write fd buf ofs len
(** [write fd buf ofs len] writes up to [len] bytes from file
descriptor [fd] into the string [buf] at offset [ofs].
[write] repeats the write operation until all characters have
been written or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be written before an error occurs. Continues
the write operation on EINTR. Returns the number of characters
written in all other cases. *)
external unsafe_write: Unix.file_descr -> string -> int -> int -> int = "caml_extunix_write"
let write fd buf ofs len =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "ExtUnix.write"
else unsafe_write fd buf ofs len
(** [intr_write fd buf ofs len] writes up to [len] bytes from file
descriptor [fd] into the string [buf] at offset [ofs].
[intr_write] repeats the write operation until all characters have
been written or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be written before an error occurs. Does NOT
continue on EINTR. Returns the number of characters written in all
other cases. *)
external unsafe_intr_write: Unix.file_descr -> string -> int -> int -> int = "caml_extunix_intr_write"
let intr_write fd buf ofs len =
if ofs < 0 || len < 0 || ofs > String.length buf - len
then invalid_arg "ExtUnix.intr_write"
else unsafe_intr_write fd buf ofs len
]
(** {2 File operations on large files} *)
(** File operations on large files. This sub-module provides 64-bit
variants of the functions [ExtUnix.fadvise] (for predeclaring an
access pattern for file data), [ExtUnix.fallocate] (for allocating
disk space for a file), [ExtUnix.all_pread], [ExtUnix.single_pread],
[ExtUnix.pread], [ExtUnix.intr_pread], [ExtUnix.all_pwrite],
[ExtUnix.single_pwrite], [ExtUnix.pwrite] and [ExtUnix.intr_pwrite]
(for reading from or writing to a file descriptor at a given
offset). These alternate functions represent positions and sizes
by 64-bit integers (type int64) instead of regular integers
(type int), thus allowing operating on files whose sizes are
greater than max_int. *)
module LargeFile =
struct
[%%have FADVISE
external fadvise: Unix.file_descr -> int64 -> int64 -> advice -> unit = "caml_extunix_fadvise64"
]
[%%have FALLOCATE
external fallocate: Unix.file_descr -> int64 -> int64 -> unit = "caml_extunix_fallocate64"
]
[%%have PREAD
external unsafe_all_pread: Unix.file_descr -> int64 -> Bytes.t -> int -> int -> int = "caml_extunix_all_pread64"
let all_pread fd off buf ofs len =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.all_pread"
else unsafe_all_pread fd off buf ofs len
external unsafe_single_pread: Unix.file_descr -> int64 -> Bytes.t -> int -> int -> int = "caml_extunix_single_pread64"
let single_pread fd off buf ofs len =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.single_pread"
else unsafe_single_pread fd off buf ofs len
external unsafe_pread: Unix.file_descr -> int64 -> Bytes.t -> int -> int -> int = "caml_extunix_pread64"
let pread fd off buf ofs len =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.pread"
else unsafe_pread fd off buf ofs len
external unsafe_intr_pread: Unix.file_descr -> int64 -> Bytes.t -> int -> int -> int = "caml_extunix_intr_pread64"
let intr_pread fd off buf ofs len =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.intr_pread"
else unsafe_intr_pread fd off buf ofs len
]
[%%have PWRITE
external unsafe_all_pwrite: Unix.file_descr -> int64 -> string -> int -> int -> int = "caml_extunix_all_pwrite64"
let all_pwrite fd off buf ofs len =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.all_pwrite"
else unsafe_all_pwrite fd off buf ofs len
external unsafe_single_pwrite: Unix.file_descr -> int64 -> string -> int -> int -> int = "caml_extunix_single_pwrite64"
let single_pwrite fd off buf ofs len =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.single_pwrite"
else unsafe_single_pwrite fd off buf ofs len
external unsafe_pwrite: Unix.file_descr -> int64 -> string -> int -> int -> int = "caml_extunix_pwrite64"
let pwrite fd off buf ofs len =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.pwrite"
else unsafe_pwrite fd off buf ofs len
external unsafe_intr_pwrite: Unix.file_descr -> int64 -> string -> int -> int -> int = "caml_extunix_intr_pwrite64"
let intr_pwrite fd off buf ofs len =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.intr_pwrite"
else unsafe_intr_pwrite fd off buf ofs len
]
(** {2 Bigarray variants} *)
(** *)
module BA = struct
[%%have PREAD
external unsafe_all_pread: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_all_pread64"
let all_pread fd off buf =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.all_pread"
else unsafe_all_pread fd off buf
external unsafe_single_pread: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_single_pread64"
let single_pread fd off buf =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.single_pread"
else unsafe_single_pread fd off buf
external unsafe_pread: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_pread64"
let pread fd off buf =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.pread"
else unsafe_pread fd off buf
external unsafe_intr_pread: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_intr_pread64"
let intr_pread fd off buf =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.intr_pread"
else unsafe_intr_pread fd off buf
]
[%%have PWRITE
external unsafe_all_pwrite: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_all_pwrite64"
let all_pwrite fd off buf =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.all_pwrite"
else unsafe_all_pwrite fd off buf
external unsafe_single_pwrite: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_single_pwrite64"
let single_pwrite fd off buf =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.single_pwrite"
else unsafe_single_pwrite fd off buf
external unsafe_pwrite: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_pwrite64"
let pwrite fd off buf =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.pwrite"
else unsafe_pwrite fd off buf
external unsafe_intr_pwrite: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_intr_pwrite64"
let intr_pwrite fd off buf =
if off < Int64.zero
then invalid_arg "ExtUnix.LargeFile.intr_pwrite"
else unsafe_intr_pwrite fd off buf
]
end (* module BA *)
end (* module LargeFile *)
[%%have MOUNT
(** {3 mount system call} *)
type mount_flag =
| MS_RDONLY | MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_SYNCHRONOUS | MS_REMOUNT
| MS_MANDLOCK | MS_DIRSYNC | MS_NOATIME | MS_NODIRATIME | MS_BIND | MS_MOVE
| MS_REC | MS_SILENT | MS_POSIXACL | MS_UNBINDABLE | MS_PRIVATE | MS_SLAVE
| MS_SHARED | MS_RELATIME | MS_KERNMOUNT | MS_I_VERSION | MS_STRICTATIME
| MS_NOUSER
external mount: source:string -> target:string -> fstype:string ->
mount_flag list -> data:string -> unit = "caml_extunix_mount"
type umount2_flag =
| MNT_FORCE | MNT_DETACH | MNT_EXPIRE | UMOUNT_NOFOLLOW
external umount2: string -> umount2_flag list -> unit = "caml_extunix_umount2"
]
[%%have CHROOT
(** {3 chroot system call} *)
external chroot: string -> unit = "caml_extunix_chroot"
]
(** {2 namespace} *)
[%%have UNSHARE
type clone_flag =
| CLONE_FS | CLONE_FILES | CLONE_NEWNS | CLONE_SYSVSEM | CLONE_NEWUTS
| CLONE_NEWIPC | CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNET
external unshare: clone_flag list -> unit = "caml_extunix_unshare"
]
(** {2 ioctl} *)
(** Control the underlying device parameters of special files *)
module Ioctl = struct
[%%have SIOCGIFCONF
(** [siocgifconf sock], where [sock] is any socket, e.g. [socket PF_INET SOCK_DGRAM 0]
@return the list of interfaces and corresponding addresses ({b FIXME max 32}) ({b may change}) *)
external siocgifconf : sock:Unix.file_descr -> (string * string) list = "caml_extunix_ioctl_siocgifconf"
]
[%%have TTY_IOCTL
(** Enable RTS/CTS (hardware) flow control. See CRTSCTS in tcsetattr(3).
{b FIXME this is likely to disappear when separate interface for [tcsetattr] and [tcgetattr] gets implemented} *)
external crtscts : Unix.file_descr -> int = "caml_extunix_crtscts"
(** Get the status of modem bits. See TIOCMGET in tty_ioctl(4). *)
external tiocmget : Unix.file_descr -> int = "caml_extunix_ioctl_TIOCMGET"
(** Set the status of modem bits. See TIOCMSET in tty_ioctl(4). *)
external tiocmset : Unix.file_descr -> int -> unit = "caml_extunix_ioctl_TIOCMSET"
(** Clear the indicated modem bits. See TIOCMBIC in tty_ioctl(4). *)
external tiocmbic : Unix.file_descr -> int -> unit = "caml_extunix_ioctl_TIOCMBIC"
(** Set the indicated modem bits. See TIOCMBIS in tty_ioctl(4). *)
external tiocmbis : Unix.file_descr -> int -> unit = "caml_extunix_ioctl_TIOCMBIS"
]
end (* module Ioctl *)
(** {2 Miscellaneous} *)
[%%have TTYNAME
(** @return name of terminal *)
external ttyname : Unix.file_descr -> string = "caml_extunix_ttyname"
]
[%%have CTERMID
(** Get controlling terminal name *)
external ctermid : unit -> string = "caml_extunix_ctermid"
]
[%%have GETTID
(** @return thread id *)
external gettid : unit -> int = "caml_extunix_gettid"
]
[%%have PGID
(** [setpgid pid pgid] sets the process group of the process specified by [pid] to [pgid].
If [pid] is zero, then the process ID of the calling process is used. If
[pgid] is zero, then the PGID of the process specified by [pid] is made the same as its process ID. *)
external setpgid : int -> int -> unit = "caml_extunix_setpgid"
(** [getpgid pid] returns the PGID of the process specified by [pid].
If [pid] is zero, the process ID of the calling process is used. *)
external getpgid : int -> int = "caml_extunix_getpgid"
(** [getsid pid] returns the session ID of the process specified by [pid].
If [pid] is zero, the process ID of the calling process is used. *)
external getsid : int -> int = "caml_extunix_getsid"
]
[%%have SETREUID
(** [setreuid ruid euid] sets real and effective user IDs of the calling process.
Supplying a value of -1 for either the real or effective user ID forces the system to leave that ID unchanged.
*)
external setreuid : int -> int -> unit = "caml_extunix_setreuid"
(** [setregid rgid egid] sets real and effective group IDs of the calling process.
Supplying a value of -1 for either the real or effective group ID forces the system to leave that ID unchanged.
*)
external setregid : int -> int -> unit = "caml_extunix_setregid"
]
[%%have SETRESUID
(** [setresuid ruid euid suid] sets real, effective and saved user IDs of the calling process.
Supplying a value of -1 for either the real or effective user ID forces the system to leave that ID unchanged.
*)
external setresuid: int -> int -> int -> unit = "caml_extunix_setresuid"
(** [setresgid rgid egid sgid] sets real, effective and saved group IDs of the calling process.
Supplying a value of -1 for either the real or effective group ID forces the system to leave that ID unchanged.
*)
external setresgid: int -> int -> int -> unit = "caml_extunix_setresgid"
]
[%%have TCPGRP
external tcgetpgrp : Unix.file_descr -> int = "caml_extunix_tcgetpgrp"
external tcsetpgrp : Unix.file_descr -> int -> unit = "caml_extunix_tcsetpgrp"
]
(** Exit process without running any [at_exit] hooks (implemented in Pervasives) *)
external sys_exit : int -> 'a = "caml_sys_exit"
[%%have SYSINFO
(** NB all memory fields in this structure are the multiplies of [mem_unit] bytes *)
type sysinfo = {
uptime : int; (** Seconds since boot *)
loads : (float * float * float); (** 1, 5, and 15 minute load averages *)
totalram : int; (** Total usable main memory size *)
freeram : int; (** Available memory size *)
sharedram : int; (** Amount of shared memory *)
bufferram : int; (** Memory used by buffers *)
totalswap : int; (** Total swap space size *)
freeswap : int; (** swap space still available *)
procs : int; (** Number of current processes *)
totalhigh : int; (** Total high memory size *)
freehigh : int; (** Available high memory size *)
mem_unit : int; (** Memory unit size in bytes *)
}
(** @return overall system statistics *)
external sysinfo : unit -> sysinfo = "caml_extunix_sysinfo"
(** @return seconds since boot *)
external uptime : unit -> int = "caml_extunix_uptime"
]
(** {2 Network} *)
[%%have IFADDRS
(** @return the list of [AF_INET] and [AF_INET6] interfaces and corresponding addresses ({b may change}) *)
external getifaddrs : unit -> (string * string) list = "caml_extunix_getifaddrs"
]
[%%have SOCKOPT
(**/**)
type socket_int_option_ =
| TCP_KEEPCNT_
| TCP_KEEPIDLE_
| TCP_KEEPINTVL_
| SO_REUSEPORT_
| SO_ATTACH_BPF_
| SO_ATTACH_REUSEPORT_EBPF_
| SO_DETACH_FILTER_
| SO_DETACH_BPF_
| SO_LOCK_FILTER_
let string_of_socket_int_option_ = function
| TCP_KEEPCNT_ -> "TCP_KEEPCNT"
| TCP_KEEPIDLE_ -> "TCP_KEEPIDLE"
| TCP_KEEPINTVL_ -> "TCP_KEEPINTVL"
| SO_REUSEPORT_ -> "SO_REUSEPORT"
| SO_ATTACH_BPF_ -> "SO_ATTACH_BPF"
| SO_ATTACH_REUSEPORT_EBPF_ -> "SO_ATTACH_REUSEPORT_EBPF"
| SO_DETACH_FILTER_ -> "SO_DETACH_FILTER"
| SO_DETACH_BPF_ -> "SO_DETACH_BPF"
| SO_LOCK_FILTER_ -> "SO_LOCK_FILTER"
external setsockopt_int : Unix.file_descr -> socket_int_option_ -> int -> unit = "caml_extunix_setsockopt_int"
external getsockopt_int : Unix.file_descr -> socket_int_option_ -> int = "caml_extunix_getsockopt_int"
external have_sockopt_int : socket_int_option_ -> bool = "caml_extunix_have_sockopt"
let setsockopt_int sock opt v =
try setsockopt_int sock opt v
with Not_found -> raise (Not_available ("setsockopt " ^ string_of_socket_int_option_ opt))
let getsockopt_int sock opt =
try getsockopt_int sock opt
with Not_found -> raise (Not_available ("getsockopt " ^ string_of_socket_int_option_ opt))
(**/**)
(** Extra socket options with integer value not covered in {!Unix} module.
NB: Not all options available on all platforms, use {!have_sockopt_int} to check at runtime
(even when function is defined in [Specific] module).
*)
type socket_int_option =
| TCP_KEEPCNT (** The maximum number of keepalive probes TCP should send before dropping the connection *)
| TCP_KEEPIDLE (** The time (in seconds) the connection needs to remain idle before TCP starts sending
keepalive probes, if the socket option SO_KEEPALIVE has been set on this socket *)
| TCP_KEEPINTVL (** The time (in seconds) between individual keepalive probes *)
| SO_ATTACH_BPF (** file descriptor returned by the bpf(2), with program of type [BPF_PROG_TYPE_SOCKET_FILTER] *)
| SO_ATTACH_REUSEPORT_EBPF (** same as for SO_ATTACH_BPF *)
type socket_bool_option =
| SO_REUSEPORT (** Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. *)
| SO_LOCK_FILTER (** Prevent changing the filters associated with the socket *)
type socket_unit_option =
| SO_DETACH_FILTER (** Remove classic or extended BPF program attached to a socket *)
| SO_DETACH_BPF (** same *)
(**/**)
let make_socket_int_option = function
| TCP_KEEPCNT -> TCP_KEEPCNT_
| TCP_KEEPIDLE -> TCP_KEEPIDLE_
| TCP_KEEPINTVL -> TCP_KEEPINTVL_
| SO_ATTACH_BPF -> SO_ATTACH_BPF_
| SO_ATTACH_REUSEPORT_EBPF -> SO_ATTACH_REUSEPORT_EBPF_
let make_socket_bool_option = function
| SO_REUSEPORT -> SO_REUSEPORT_
| SO_LOCK_FILTER -> SO_LOCK_FILTER_
let make_socket_unit_option = function
| SO_DETACH_FILTER -> SO_DETACH_FILTER_
| SO_DETACH_BPF -> SO_DETACH_BPF_
(**/**)
let have_sockopt_unit x = have_sockopt_int (make_socket_unit_option x)
let have_sockopt_bool x = have_sockopt_int (make_socket_bool_option x)
let have_sockopt_int x = have_sockopt_int (make_socket_int_option x)
(** Obsolete, compatibility, use {!have_sockopt_int}.
@deprecated *)
let have_sockopt = have_sockopt_int
[@@deprecated "Obsolete, compatibility, use have_sockopt_int."]
(** Set the option without value on the given socket *)
let setsockopt_unit sock opt = setsockopt_int sock (make_socket_unit_option opt) 0
(** Set a boolean-valued option in the given socket *)
let setsockopt sock opt v = setsockopt_int sock (make_socket_bool_option opt) (if v then 1 else 0)
(** Get the current value for the boolean-valued option in the given socket *)
let getsockopt sock opt = 0 <> getsockopt_int sock (make_socket_bool_option opt)
(** Set an integer-valued option in the given socket *)
let setsockopt_int sock opt v = setsockopt_int sock (make_socket_int_option opt) v
(** Get the current value for the integer-valued option in the given socket *)
let getsockopt_int sock opt = getsockopt_int sock (make_socket_int_option opt)
]
[%%have POLL
module Poll : sig
type t = private int
(** [is_set flags flag]
@return whether [flag] is set in [flags] *)
val is_set : t -> t -> bool
(** [is_inter flags1 flags2]
@return whether [flags1] and [flags2] have non-empty intersection *)
val is_inter : t -> t -> bool
(** @return intersection of two flags (AND) *)
val inter : t -> t -> t
(** @return union of two flags (OR) *)
val union : t -> t -> t
(** @return union of several flags (OR) *)
val join : t list -> t
(** equivalent to [union] *)
val (+) : t -> t -> t
val pollin : t
val pollpri : t
val pollout : t
val pollerr : t
val pollhup : t
val pollnval : t
(** may not be present on all platforms (=0) *)
val pollrdhup : t
(** no poll flags (=0) *)
val none : t
end = struct
type t = int
external poll_constants : unit -> (int*int*int*int*int*int*int) = "caml_extunix_poll_constants"
let (pollin,pollpri,pollout,pollerr,pollhup,pollnval,pollrdhup) = try poll_constants () with Not_available _ -> (0,0,0,0,0,0,0)
let none = 0
let is_set xs x = xs land x = x
let inter x y = x land y
let is_inter x y = x land y <> 0
let union a b = a lor b
let (+) = union
let join = List.fold_left (lor) 0
end
external poll : (Unix.file_descr * Poll.t) array -> int -> float -> (Unix.file_descr * Poll.t) list = "caml_extunix_poll"
let poll a ?(n=Array.length a) t = poll a n t
]
[%%have SIGNALFD
(** {2 signalfd} *)
(** OCaml bindings for signalfd(2) and related functions
@author Kaustuv Chaudhuri
*)
(******************************************************************************)
(* signalfd bindings *)
(* *)
(* NO COPYRIGHT -- RELEASED INTO THE PUBLIC DOMAIN *)
(* *)
(* Author: Kaustuv Chaudhuri *)
(******************************************************************************)
(** [signalfd ?fd sigs flags ()]
If the first optional argument is omitted, then a new file descriptor is allocated.
Otherwise, the given file descriptor is modified (in which case it
must have been created with [signalfd] previously). When you are
done with the fd, remember to {!Unix.close} it. Do not forget
to block [sigs] with {!Unix.sigprocmask} to prevent signal handling
according to default dispositions.
*)
external signalfd : ?fd:Unix.file_descr -> sigs:int list -> flags:int list -> unit -> Unix.file_descr ="caml_extunix_signalfd"
(** This type represents signal information that is read(2) from the
signalfd. *)
type ssi
(** Blocking read(2) on a signalfd. Has undefined behaviour on
non-signalfds. Every successful read consumes a pending signal. *)
external signalfd_read : Unix.file_descr -> ssi = "caml_extunix_signalfd_read"
(** {3 Functions to query the signal information structure.} *)
(** Get the signal value. This form is compatible with the signal
values defined in the standard {!Sys} module.
See signalfd(2) for the details of the remaining functions. Most
of these integers are actually unsigned. *)
external ssi_signo_sys : ssi -> int = "caml_extunix_ssi_signo_sys"
external ssi_signo : ssi -> int32 = "caml_extunix_ssi_signo"
external ssi_errno : ssi -> int32 = "caml_extunix_ssi_errno"
external ssi_code : ssi -> int32 = "caml_extunix_ssi_code"
external ssi_pid : ssi -> int32 = "caml_extunix_ssi_pid"
external ssi_uid : ssi -> int32 = "caml_extunix_ssi_uid"
external ssi_fd : ssi -> Unix.file_descr = "caml_extunix_ssi_fd"
external ssi_tid : ssi -> int32 = "caml_extunix_ssi_tid"
external ssi_band : ssi -> int32 = "caml_extunix_ssi_band"
external ssi_overrun : ssi -> int32 = "caml_extunix_ssi_overrun"
external ssi_trapno : ssi -> int32 = "caml_extunix_ssi_trapno"
external ssi_status : ssi -> int32 = "caml_extunix_ssi_status"
external ssi_int : ssi -> int32 = "caml_extunix_ssi_int"
external ssi_ptr : ssi -> int64 = "caml_extunix_ssi_ptr"
external ssi_utime : ssi -> int64 = "caml_extunix_ssi_utime"
external ssi_stime : ssi -> int64 = "caml_extunix_ssi_stime"
external ssi_addr : ssi -> int64 = "caml_extunix_ssi_addr"
]
[%%have RESOURCE
(**
{2 POSIX resource operations}
@author Sylvain Le Gall
*)
(** priority target *)
type which_prio_t =
| PRIO_PROCESS of int (** Priority for a process id *)
| PRIO_PGRP of int (** Priority for a process group id *)
| PRIO_USER of int (** Priority for a user id *)
type priority = int
type resource =
| RLIMIT_CORE (** Limit on size of core dump file. *)
| RLIMIT_CPU (** Limit on CPU time per process. *)
| RLIMIT_DATA (** Limit on data segment size. *)
| RLIMIT_FSIZE (** Limit on file size. *)
| RLIMIT_NOFILE (** Limit on number of open files. *)
| RLIMIT_STACK (** Limit on stack size. *)
| RLIMIT_AS (** Limit on address space size. *)
(** get resource name *)
let string_of_resource = function
| RLIMIT_CORE -> "RLIMIT_CORE"
| RLIMIT_CPU -> "RLIMIT_CPU"
| RLIMIT_DATA -> "RLIMIT_DATA"
| RLIMIT_FSIZE -> "RLIMIT_FSIZE"
| RLIMIT_NOFILE -> "RLIMIT_NOFILE"
| RLIMIT_STACK -> "RLIMIT_STACK"
| RLIMIT_AS -> "RLIMIT_AS"
(** Limits *)
module Rlimit = struct
type t = int64 option (** [Some limit] is fixed limit, [None] is RLIM_INFINITY *)
let string_of_bytes n =
let sz, acc = List.fold_left (fun (sz, acc) e ->
let q = Int64.div sz 1024L in
let r = Int64.rem sz 1024L in
let acc = if r <> 0L then Printf.sprintf "%Ld %s" r e :: acc else acc in
(q, acc)) (n, []) ["B"; "KB"; "MB"; "GB"]
in
let acc = if sz <> 0L then Printf.sprintf "%Ld TB" sz :: acc else acc in
match acc with
| [] -> "0 B"
| _ -> String.concat " " acc
let to_string ?r = function
| None -> "infinity"
| Some l ->
match r with
| None -> Int64.to_string l
| Some RLIMIT_CORE
| Some RLIMIT_DATA
| Some RLIMIT_FSIZE
| Some RLIMIT_STACK
| Some RLIMIT_AS -> string_of_bytes l
| Some RLIMIT_NOFILE -> Int64.to_string l
| Some RLIMIT_CPU -> Printf.sprintf "%Ld s" l
let compare l1 l2 =
match l1, l2 with
| Some l1, Some l2 -> Int64.compare l1 l2
| None, None -> 0
| Some _, None -> -1
| None, Some _ -> 1
let eq l1 l2 = compare l1 l2 = 0
let gt l1 l2 = compare l1 l2 > 0
let ge l1 l2 = compare l1 l2 >= 0
let lt l1 l2 = compare l1 l2 < 0
let le l1 l2 = compare l1 l2 <= 0
end (* Rlimit *)
(** Get nice value *)
external getpriority : which_prio_t -> priority = "caml_extunix_getpriority"
(** Set nice value *)
external setpriority : which_prio_t -> priority -> unit = "caml_extunix_setpriority"
(** Get maximum resource consumption.
@return [(soft,hard)] limits *)
external getrlimit : resource -> Rlimit.t * Rlimit.t = "caml_extunix_getrlimit"
(** Set maximum resource consumption *)
external setrlimit : resource -> soft:Rlimit.t -> hard:Rlimit.t -> unit = "caml_extunix_setrlimit"
(* let unlimit_soft r = let (_,hard) = getrlimit r in setrlimit r ~soft:hard ~hard *)
(** [getrusage] is not implemented because the only meaningful information it
provides are [ru_utime] and [ru_stime] which can be accessed through
[Unix.times].
*)
]
(** {2 Memory management} *)
[%%have MLOCKALL
(** mlockall flag *)
type mlockall_flag = MCL_CURRENT | MCL_FUTURE
(** Lock all pages mapped into the address space of the calling process. *)
external mlockall : mlockall_flag list -> unit = "caml_extunix_mlockall"
(** Unlock all pages mapped into the address space of the calling process. *)
external munlockall : unit -> unit = "caml_extunix_munlockall"
]
[%%have MEMALIGN
(** [memalign alignment size] creates a {!Bigarray.Array1.t} of [size] bytes,
which data is aligned to [alignment] (must be a power of 2)
@author Goswin von Brederlow
*)
external memalign: int -> int -> Bigarray.int8_unsigned_elt carray8 = "caml_extunix_memalign"
]
(** {2 Time conversion} *)
[%%have STRPTIME
(** This function is the converse of the {!strftime} function.
[strptime fmt data] convert a string containing time information [data]
into a [tm] struct according to the format specified by [fmt]. *)
external strptime: string -> string -> Unix.tm = "caml_extunix_strptime"
]
[%%have STRTIME
(** Return the ascii representation of a given [tm] argument. The
ascii time is returned in the form of a string like
'Wed Jun 30, 21:21:21 2005\n' *)
external asctime: Unix.tm -> string = "caml_extunix_asctime"
(** This functions is the converse of the {!strptime} function.
[strftime fmt data] converts a [tm] structure [data] into a string
according to the format specified by [fmt]. *)
external strftime: string -> Unix.tm -> string = "caml_extunix_strftime"
(** [tzname isdst]
@param isdst specifies whether daylight saving is in effect
@return abbreviated name of the current timezone
*)
external tzname : bool -> string = "caml_extunix_tzname"
]
[%%have TIMEZONE
(** @return timezone (seconds West of UTC) and daylight (whether there is time during
the year when daylight saving time applies in this timezone) *)
external timezone : unit -> int * bool = "caml_extunix_timezone"
]
[%%have TIMEGM
(** Inverse of [Unix.gmtime] *)
external timegm : Unix.tm -> float = "caml_extunix_timegm"
]
[%%have PTS
(**
{2 Pseudo terminal management}
@author Niki Yoshiuchi
*)
(** This function opens a pseudo-terminal device. *)
external posix_openpt : open_flag list ->
Unix.file_descr = "caml_extunix_posix_openpt"
(** This function grants access to the slave pseudo-terminal. *)
external grantpt: Unix.file_descr -> unit = "caml_extunix_grantpt"
(** This function unlock a pseudo-terminal master/slave pair. *)
external unlockpt: Unix.file_descr -> unit = "caml_extunix_unlockpt"
(** This function get the name of the slave pseudo-terminal. *)
external ptsname: Unix.file_descr -> string = "caml_extunix_ptsname"
]
(** {2 Application self-debugging and diagnostics} *)
[%%have EXECINFO
(** @return a backtrace for the calling program
{b NB} native function [backtrace] may fail to unwind the OCaml callstack
correctly or even segfault. Do not use lightly.
See {{:https://forge.ocamlcore.org/tracker/index.php?func=detail&aid=1290}bug #1290},
{{:http://caml.inria.fr/mantis/view.php?id=5334}PR#5344}
and {{:http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=637360}Debian bug #637380} for details.
*)
external backtrace : unit -> string array = "caml_extunix_backtrace"
]
[%%have MALLOC_STATS
(** Print brief heap summary statistics on stderr *)
external malloc_stats : unit -> unit = "caml_extunix_malloc_stats"
]
[%%have MALLOC_INFO
(** @return the information about state of allocator *)
external malloc_info : unit -> string = "caml_extunix_malloc_info"
]
[%%have MCHECK
external mtrace : unit -> unit = "caml_extunix_mtrace"
external muntrace : unit -> unit = "caml_extunix_muntrace"
]
[%%have PTRACE
external ptrace_traceme : unit -> unit = "caml_extunix_ptrace_traceme"
external ptrace_peekdata : int -> nativeint -> nativeint = "caml_extunix_ptrace_peekdata"
external ptrace_peektext : int -> nativeint -> nativeint = "caml_extunix_ptrace_peektext"
type ptrace_request =
| PTRACE_ATTACH
| PTRACE_DETACH
external ptrace : int -> ptrace_request -> unit = "caml_extunix_ptrace"
]
(** {2 Environment manipulation} *)
[%%have SETENV
(** [setenv name value overwrite] adds the variable [name] to the environment with the value [value], if [name]
does not already exist or [overwrite] is true *)
external setenv : string -> string -> bool -> unit = "caml_extunix_setenv"
(** [unsetenv name] removes variable [name] from the environment. If [name] does not exist in the environment, then the function
succeeds, and the environment is unchanged. *)
external unsetenv : string -> unit = "caml_extunix_unsetenv"
]
[%%have CLEARENV
(** Clear the environment of all name-value pairs *)
external clearenv : unit -> unit = "caml_extunix_clearenv"
]
(** {2 Temporary directories} *)
[%%have MKDTEMP
(** [mkdtemp template] creates a unique temporary directory (with permissions 0700).
Last six characters of [template] must be "XXXXXX". *)
external mkdtemp : string -> string = "caml_extunix_mkdtemp"
]
[%%have MKSTEMPS
(**/**)
(** internal use only *)
external internal_mkstemps : bytes -> int -> Unix.file_descr = "caml_extunix_internal_mkstemps"
(**/**)
(** [mkstemp ?(suffix="") prefix] generates a unique temporary
filename in the form [prefix]XXXXXX[suffix], creates and opens the
file, and returns an open file descriptor and name for the
file. *)
let mkstemp ?(suffix="") prefix =
let s = Bytes.of_string (prefix ^ "XXXXXX" ^ suffix) in
let fd = internal_mkstemps s (String.length suffix) in
(fd, Bytes.to_string s)
]
[%%have MKOSTEMPS
(**/**)
(** internal use only *)
external internal_mkostemps : bytes -> int -> open_flag list -> Unix.file_descr = "caml_extunix_internal_mkostemps"
(**/**)
(** [mkostemp ?(suffix="") ?(flags=[]) prefix] generates a unique temporary
filename in the form [prefix]XXXXXX[suffix], creates and opens the
file with [flags], and returns an open file descriptor and name
for the file. *)
let mkostemp ?(suffix="") ?(flags=[]) prefix =
let s = Bytes.of_string (prefix ^ "XXXXXX" ^ suffix) in
let fd = internal_mkostemps s (String.length suffix) flags in
(fd, Bytes.to_string s)
]
(** {2 Byte order conversion} *)
(** {2 big endian functions}
@author Goswin von Brederlow *)
module BigEndian = struct
[%%have ENDIAN
(** Conversion functions from host to big endian byte order and back *)
(** Conversion of 16bit integers *)
(** [uint16_from_host u16] converts an unsigned 16bit integer from host to
big endian byte order *)
external uint16_from_host : int -> int = "caml_extunix_htobe16" [@@noalloc]
(** [int16_from_host i16] converts a signed 16bit integer from host to
big endian byte order *)
external int16_from_host : int -> int = "caml_extunix_htobe16_signed" [@@noalloc]
(** [uint16_to_host u16] converts an unsigned 16bit integer from big
endian to host byte order *)
external uint16_to_host : int -> int = "caml_extunix_be16toh" [@@noalloc]
(** [int16_to_host i16] converts a signed 16bit integer from big
endian to host byte order *)
external int16_to_host : int -> int = "caml_extunix_be16toh_signed" [@@noalloc]
(** Conversion of 31bit integeres
On 64bit platforms this actualy converts 32bit integers without
the need to allocate a new int32. On 32bit platforms it produces
garbage. For use on 64bit platforms only! *)
(** [uint31_from_host u31] converts an unsigned 31bit integer from
host to big endian byte order *)
external uint31_from_host : int -> int = "caml_extunix_htobe31" [@@noalloc]
(** [int31_from_host i31] converts a signed 31bit integer from host to
big endian byte order *)
external int31_from_host : int -> int = "caml_extunix_htobe31_signed" [@@noalloc]
(** [uint31_to_host u31] converts an unsigned 31bit integer from big
endian to host byte order *)
external uint31_to_host : int -> int = "caml_extunix_be31toh" [@@noalloc]
(** [int31_to_host i31] converts a signed 31bit integer from big
endian to host byte order *)
external int31_to_host : int -> int = "caml_extunix_be31toh_signed" [@@noalloc]
(** Conversion of 32bit integers *)
(** [int32_from_host int32] converts a 32bit integer from host to big
endian byte order *)
external int32_from_host : int32 -> int32 = "caml_extunix_htobe32"
(** [int32_to_host int32] converts a 32bit integer from big endian to
host byte order *)
external int32_to_host : int32 -> int32 = "caml_extunix_be32toh"
(** Conversion of 64bit integers *)
(** [int64_from_host int64] converts a 64bit integer from host to big
endian byte order *)
external int64_from_host : int64 -> int64 = "caml_extunix_htobe64"
(** [int64_to_host int64] converts a 64bit integer from big endian to
host byte order *)
external int64_to_host : int64 -> int64 = "caml_extunix_be64toh"
(** [unsafe_get_X str off] extract integer of type [X] from string
[str] starting at offset [off]. Unsigned types are 0 extended
and signed types are sign extended to fill the ocaml type.
Bounds checking is not performed. Use with caution and only when
the program logic guarantees that the access is within bounds.
Note: The 31bit functions extract a 32bit integer and return it
as ocaml int. On 32bit platforms this can overflow as ocaml
integers are 31bit signed there. No error is reported if this
occurs. Use with care.
Note: The same applies to 63bit functions.
*)
external unsafe_get_uint8 : string -> int -> int = "caml_extunix_get_u8" [@@noalloc]
external unsafe_get_int8 : string -> int -> int = "caml_extunix_get_s8" [@@noalloc]
external unsafe_get_uint16 : string -> int -> int = "caml_extunix_get_bu16" [@@noalloc]
external unsafe_get_int16 : string -> int -> int = "caml_extunix_get_bs16" [@@noalloc]
external unsafe_get_uint31 : string -> int -> int = "caml_extunix_get_bu31" [@@noalloc]
external unsafe_get_int31 : string -> int -> int = "caml_extunix_get_bs31" [@@noalloc]
external unsafe_get_int32 : string -> int -> int32 = "caml_extunix_get_bs32"
external unsafe_get_uint63 : string -> int -> int = "caml_extunix_get_bu63" [@@noalloc]
external unsafe_get_int63 : string -> int -> int = "caml_extunix_get_bs63" [@@noalloc]
external unsafe_get_int64 : string -> int -> int64 = "caml_extunix_get_bs64"
(** [get_X str off] same as [unsafe_get_X] but with bounds checking. *)
let get_uint8 str off =
if off < 0 || off >= String.length str
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint8 str off
let get_int8 str off =
if off < 0 || off >= String.length str
then raise (Invalid_argument "index out of bounds");
unsafe_get_int8 str off
let get_uint16 str off =
if off < 0 || off > String.length str - 2
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint16 str off
let get_int16 str off =
if off < 0 || off > String.length str - 2
then raise (Invalid_argument "index out of bounds");
unsafe_get_int16 str off
let get_uint31 str off =
if off < 0 || off > String.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint31 str off
let get_int31 str off =
if off < 0 || off > String.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_int31 str off
let get_int32 str off =
if off < 0 || off > String.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_int32 str off
let get_uint63 str off =
if off < 0 || off > String.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint63 str off
let get_int63 str off =
if off < 0 || off > String.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_int63 str off
let get_int64 str off =
if off < 0 || off > String.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_int64 str off
(** [unsafe_set_X buf off v] stores the integer [v] as type [X] in
the buffer [buf] starting at offset [off]. Bounds checking is not
performed. Use with caution and only when the program logic
guarantees that the access is within bounds.
Note: The 31bit functions store an ocaml int as 32bit
integer. On 32bit platforms ocaml integers are 31bit signed and
will be sign extended to 32bit first. Use with care.
Note: The same applies to 63bit functions.
*)
external unsafe_set_uint8 : Bytes.t -> int -> int -> unit = "caml_extunix_set_8" [@@noalloc]
external unsafe_set_int8 : Bytes.t -> int -> int -> unit = "caml_extunix_set_8" [@@noalloc]
external unsafe_set_uint16 : Bytes.t -> int -> int -> unit = "caml_extunix_set_b16" [@@noalloc]
external unsafe_set_int16 : Bytes.t -> int -> int -> unit = "caml_extunix_set_b16" [@@noalloc]
external unsafe_set_uint31 : Bytes.t -> int -> int -> unit = "caml_extunix_set_b31" [@@noalloc]
external unsafe_set_int31 : Bytes.t -> int -> int -> unit = "caml_extunix_set_b31" [@@noalloc]
external unsafe_set_int32 : Bytes.t -> int -> int32 -> unit = "caml_extunix_set_b32" [@@noalloc]
external unsafe_set_uint63 : Bytes.t -> int -> int -> unit = "caml_extunix_set_b63" [@@noalloc]
external unsafe_set_int63 : Bytes.t -> int -> int -> unit = "caml_extunix_set_b63" [@@noalloc]
external unsafe_set_int64 : Bytes.t -> int -> int64 -> unit = "caml_extunix_set_b64" [@@noalloc]
(** [set_X buf off v] same as [unsafe_set_X] but with bounds checking. *)
let set_uint8 str off v =
if off < 0 || off >= Bytes.length str
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint8 str off v
let set_int8 str off v =
if off < 0 || off >= Bytes.length str
then raise (Invalid_argument "index out of bounds");
unsafe_set_int8 str off v
let set_uint16 str off v =
if off < 0 || off > Bytes.length str - 2
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint16 str off v
let set_int16 str off v =
if off < 0 || off > Bytes.length str - 2
then raise (Invalid_argument "index out of bounds");
unsafe_set_int16 str off v
let set_uint31 str off v =
if off < 0 || off > Bytes.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint31 str off v
let set_int31 str off v =
if off < 0 || off > Bytes.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_int31 str off v
let set_int32 str off v =
if off < 0 || off > Bytes.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_int32 str off v
let set_uint63 str off v =
if off < 0 || off > Bytes.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint63 str off v
let set_int63 str off v =
if off < 0 || off > Bytes.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_int63 str off v
let set_int64 str off v =
if off < 0 || off > Bytes.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_int64 str off v
]
end
(** {2 little endian functions}
@author Goswin von Brederlow *)
module LittleEndian = struct
[%%have ENDIAN
(** Conversion functions from host to little endian byte order and back *)
(** Conversion of 16bit integers *)
(** [uint16_from_host u16] converts an unsigned 16bit integer from host to
little endian byte order *)
external uint16_from_host : int -> int = "caml_extunix_htole16" [@@noalloc]
(** [int16_from_host i16] converts a signed 16bit integer from host to
little endian byte order *)
external int16_from_host : int -> int = "caml_extunix_htole16_signed" [@@noalloc]
(** [uint16_to_host u16] converts an unsigned 16bit integer from little
endian to host byte order *)
external uint16_to_host : int -> int = "caml_extunix_le16toh" [@@noalloc]
(** [int16_to_host i16] converts a signed 16bit integer from little
endian to host byte order *)
external int16_to_host : int -> int = "caml_extunix_le16toh_signed" [@@noalloc]
(** Conversion of 31bit integeres
On 64bit platforms this actualy converts 32bit integers without
the need to allocate a new int32. On 32bit platforms it produces
garbage. For use on 64bit platforms only! *)
(** [uint31_from_host u31] converts an unsigned 31bit integer from
host to little endian byte order *)
external uint31_from_host : int -> int = "caml_extunix_htole31" [@@noalloc]
(** [int31_from_host i31] converts a signed 31bit integer from host to
little endian byte order *)
external int31_from_host : int -> int = "caml_extunix_htole31_signed" [@@noalloc]
(** [uint31_to_host u31] converts an unsigned 31bit integer from little
endian to host byte order *)
external uint31_to_host : int -> int = "caml_extunix_le31toh" [@@noalloc]
(** [int31_to_host i31] converts a signed 31bit integer from little
endian to host byte order *)
external int31_to_host : int -> int = "caml_extunix_le31toh_signed" [@@noalloc]
(** Conversion of 32bit integers *)
(** [int32_from_host int32] converts a 32bit integer from host to little
endian byte order *)
external int32_from_host : int32 -> int32 = "caml_extunix_htole32"
(** [int32_to_host int32] converts a 32bit integer from little endian to
host byte order *)
external int32_to_host : int32 -> int32 = "caml_extunix_le32toh"
(** Conversion of 64bit integers *)
(** [int64_from_host int64] converts a 64bit integer from host to little
endian byte order *)
external int64_from_host : int64 -> int64 = "caml_extunix_htole64"
(** [int64_to_host int64] converts a 64bit integer from little endian to
host byte order *)
external int64_to_host : int64 -> int64 = "caml_extunix_le64toh"
(** [unsafe_get_X str off] extract integer of type [X] from string
[str] starting at offset [off]. Unsigned types are 0 extended
and signed types are sign extended to fill the ocaml type.
Bounds checking is not performed. Use with caution and only when
the program logic guarantees that the access is within bounds.
Note: The 31bit functions extract a 32bit integer and return it
as ocaml int. On 32bit platforms this can overflow as ocaml
integers are 31bit signed there. No error is reported if this
occurs. Use with care. *)
external unsafe_get_uint8 : string -> int -> int = "caml_extunix_get_u8" [@@noalloc]
external unsafe_get_int8 : string -> int -> int = "caml_extunix_get_s8" [@@noalloc]
external unsafe_get_uint16 : string -> int -> int = "caml_extunix_get_lu16" [@@noalloc]
external unsafe_get_int16 : string -> int -> int = "caml_extunix_get_ls16" [@@noalloc]
external unsafe_get_uint31 : string -> int -> int = "caml_extunix_get_lu31" [@@noalloc]
external unsafe_get_int31 : string -> int -> int = "caml_extunix_get_ls31" [@@noalloc]
external unsafe_get_int32 : string -> int -> int32 = "caml_extunix_get_ls32"
external unsafe_get_uint63 : string -> int -> int = "caml_extunix_get_lu63" [@@noalloc]
external unsafe_get_int63 : string -> int -> int = "caml_extunix_get_ls63" [@@noalloc]
external unsafe_get_int64 : string -> int -> int64 = "caml_extunix_get_ls64"
(** [get_X str off] same as [unsafe_get_X] but with bounds checking. *)
let get_uint8 str off =
if off < 0 || off >= String.length str
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint8 str off
let get_int8 str off =
if off < 0 || off >= String.length str
then raise (Invalid_argument "index out of bounds");
unsafe_get_int8 str off
let get_uint16 str off =
if off < 0 || off > String.length str - 2
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint16 str off
let get_int16 str off =
if off < 0 || off > String.length str - 2
then raise (Invalid_argument "index out of bounds");
unsafe_get_int16 str off
let get_uint31 str off =
if off < 0 || off > String.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint31 str off
let get_int31 str off =
if off < 0 || off > String.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_int31 str off
let get_int32 str off =
if off < 0 || off > String.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_int32 str off
let get_uint63 str off =
if off < 0 || off > String.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint63 str off
let get_int63 str off =
if off < 0 || off > String.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_int63 str off
let get_int64 str off =
if off < 0 || off > String.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_int64 str off
(** [unsafe_set_X buf off v] stores the integer [v] as type [X] in
the buffer [buf] starting at offset [off]. Bounds checking is not
performed. Use with caution and only when the program logic
guarantees that the access is within bounds.
Note: The 31bit functions store an ocaml int as 32bit
integer. On 32bit platforms ocaml integers are 31bit signed and
will be sign extended to 32bit first. Use with care. *)
external unsafe_set_uint8 : Bytes.t -> int -> int -> unit = "caml_extunix_set_8" [@@noalloc]
external unsafe_set_int8 : Bytes.t -> int -> int -> unit = "caml_extunix_set_8" [@@noalloc]
external unsafe_set_uint16 : Bytes.t -> int -> int -> unit = "caml_extunix_set_l16" [@@noalloc]
external unsafe_set_int16 : Bytes.t -> int -> int -> unit = "caml_extunix_set_l16" [@@noalloc]
external unsafe_set_uint31 : Bytes.t -> int -> int -> unit = "caml_extunix_set_l31" [@@noalloc]
external unsafe_set_int31 : Bytes.t -> int -> int -> unit = "caml_extunix_set_l31" [@@noalloc]
external unsafe_set_int32 : Bytes.t -> int -> int32 -> unit = "caml_extunix_set_l32" [@@noalloc]
external unsafe_set_uint63 : Bytes.t -> int -> int -> unit = "caml_extunix_set_l63" [@@noalloc]
external unsafe_set_int63 : Bytes.t -> int -> int -> unit = "caml_extunix_set_l63" [@@noalloc]
external unsafe_set_int64 : Bytes.t -> int -> int64 -> unit = "caml_extunix_set_l64" [@@noalloc]
(** [set_X buf off v] same as [unsafe_set_X] but with bounds checking. *)
let set_uint8 str off v =
if off < 0 || off >= Bytes.length str
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint8 str off v
let set_int8 str off v =
if off < 0 || off >= Bytes.length str
then raise (Invalid_argument "index out of bounds");
unsafe_set_int8 str off v
let set_uint16 str off v =
if off < 0 || off > Bytes.length str - 2
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint16 str off v
let set_int16 str off v =
if off < 0 || off > Bytes.length str - 2
then raise (Invalid_argument "index out of bounds");
unsafe_set_int16 str off v
let set_uint31 str off v =
if off < 0 || off > Bytes.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint31 str off v
let set_int31 str off v =
if off < 0 || off > Bytes.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_int31 str off v
let set_int32 str off v =
if off < 0 || off > Bytes.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_int32 str off v
let set_uint63 str off v =
if off < 0 || off > Bytes.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint63 str off v
let set_int63 str off v =
if off < 0 || off > Bytes.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_int63 str off v
let set_int64 str off v =
if off < 0 || off > Bytes.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_int64 str off v
]
end
(** {2 host endian functions}
@author Goswin von Brederlow *)
module HostEndian = struct
(** [unsafe_get_X str off] extract integer of type [X] from string
[str] starting at offset [off]. Unsigned types are 0 extended
and signed types are sign extended to fill the ocaml type.
Bounds checking is not performed. Use with caution and only when
the program logic guarantees that the access is within bounds.
Note: The 31bit functions extract a 32bit integer and return it
as ocaml int. On 32bit platforms this can overflow as ocaml
integers are 31bit signed there. No error is reported if this
occurs. Use with care.
Note: The same applies to 63bit functions.
*)
external unsafe_get_uint8 : string -> int -> int = "caml_extunix_get_u8" [@@noalloc]
external unsafe_get_int8 : string -> int -> int = "caml_extunix_get_s8" [@@noalloc]
external unsafe_get_uint16 : string -> int -> int = "caml_extunix_get_hu16" [@@noalloc]
external unsafe_get_int16 : string -> int -> int = "caml_extunix_get_hs16" [@@noalloc]
external unsafe_get_uint31 : string -> int -> int = "caml_extunix_get_hu31" [@@noalloc]
external unsafe_get_int31 : string -> int -> int = "caml_extunix_get_hs31" [@@noalloc]
external unsafe_get_int32 : string -> int -> int32 = "caml_extunix_get_hs32"
external unsafe_get_uint63 : string -> int -> int = "caml_extunix_get_hu63" [@@noalloc]
external unsafe_get_int63 : string -> int -> int = "caml_extunix_get_hs63" [@@noalloc]
external unsafe_get_int64 : string -> int -> int64 = "caml_extunix_get_hs64"
(** [get_X str off] same as [unsafe_get_X] but with bounds checking. *)
let get_uint8 str off =
if off < 0 || off >= String.length str
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint8 str off
let get_int8 str off =
if off < 0 || off >= String.length str
then raise (Invalid_argument "index out of bounds");
unsafe_get_int8 str off
let get_uint16 str off =
if off < 0 || off > String.length str - 2
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint16 str off
let get_int16 str off =
if off < 0 || off > String.length str - 2
then raise (Invalid_argument "index out of bounds");
unsafe_get_int16 str off
let get_uint31 str off =
if off < 0 || off > String.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint31 str off
let get_int31 str off =
if off < 0 || off > String.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_int31 str off
let get_int32 str off =
if off < 0 || off > String.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_int32 str off
let get_uint63 str off =
if off < 0 || off > String.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint63 str off
let get_int63 str off =
if off < 0 || off > String.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_int63 str off
let get_int64 str off =
if off < 0 || off > String.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_int64 str off
(** [unsafe_set_X buf off v] stores the integer [v] as type [X] in
the buffer [buf] starting at offset [off]. Bounds checking is not
performed. Use with caution and only when the program logic
guarantees that the access is within bounds.
Note: The 31bit functions store an ocaml int as 32bit
integer. On 32bit platforms ocaml integers are 31bit signed and
will be sign extended to 32bit first. Use with care.
Note: The same applies to 63bit functions.
*)
external unsafe_set_uint8 : Bytes.t -> int -> int -> unit = "caml_extunix_set_8" [@@noalloc]
external unsafe_set_int8 : Bytes.t -> int -> int -> unit = "caml_extunix_set_8" [@@noalloc]
external unsafe_set_uint16 : Bytes.t -> int -> int -> unit = "caml_extunix_set_h16" [@@noalloc]
external unsafe_set_int16 : Bytes.t -> int -> int -> unit = "caml_extunix_set_h16" [@@noalloc]
external unsafe_set_uint31 : Bytes.t -> int -> int -> unit = "caml_extunix_set_h31" [@@noalloc]
external unsafe_set_int31 : Bytes.t -> int -> int -> unit = "caml_extunix_set_h31" [@@noalloc]
external unsafe_set_int32 : Bytes.t -> int -> int32 -> unit = "caml_extunix_set_h32" [@@noalloc]
external unsafe_set_uint63 : Bytes.t -> int -> int -> unit = "caml_extunix_set_h63" [@@noalloc]
external unsafe_set_int63 : Bytes.t -> int -> int -> unit = "caml_extunix_set_h63" [@@noalloc]
external unsafe_set_int64 : Bytes.t -> int -> int64 -> unit = "caml_extunix_set_h64" [@@noalloc]
(** [set_X buf off v] same as [unsafe_set_X] but with bounds checking. *)
let set_uint8 str off v =
if off < 0 || off >= Bytes.length str
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint8 str off v
let set_int8 str off v =
if off < 0 || off >= Bytes.length str
then raise (Invalid_argument "index out of bounds");
unsafe_set_int8 str off v
let set_uint16 str off v =
if off < 0 || off > Bytes.length str - 2
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint16 str off v
let set_int16 str off v =
if off < 0 || off > Bytes.length str - 2
then raise (Invalid_argument "index out of bounds");
unsafe_set_int16 str off v
let set_uint31 str off v =
if off < 0 || off > Bytes.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint31 str off v
let set_int31 str off v =
if off < 0 || off > Bytes.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_int31 str off v
let set_int32 str off v =
if off < 0 || off > Bytes.length str - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_int32 str off v
let set_uint63 str off v =
if off < 0 || off > Bytes.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint63 str off v
let set_int63 str off v =
if off < 0 || off > Bytes.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_int63 str off v
let set_int64 str off v =
if off < 0 || off > Bytes.length str - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_int64 str off v
end
[%%have READ_CREDENTIALS
(** {2 read_credentials }
@author Andre Nathan *)
(** Reads sender credentials from a file descriptor, returning a 3-element
tuple containing the sender process' PID, UID and GID. *)
external read_credentials : Unix.file_descr -> int * int * int = "caml_extunix_read_credentials"
]
[%%have FEXECVE
(** {2 fexecve }
@author Andre Nathan *)
(** [fexecve fd args env] executes the program in file represented by
file descriptor [fd] with arguments [args] and environment
variables given by [env]. As with the [execv*] functions, on
success [fexecve] never returns; the current process is replaced
by the new one.
*)
external fexecve: Unix.file_descr -> string array -> string array -> 'a = "caml_extunix_fexecve"
]
[%%have SENDMSG
(** {2 sendmsg / recvmsg }
@author Andre Nathan *)
(** Send a message and optionally a file descriptor through a socket. Passing
file descriptors requires UNIX domain sockets and a non-empty message. *)
external sendmsg: Unix.file_descr -> ?sendfd:Unix.file_descr -> string -> unit = "caml_extunix_sendmsg"
(** Recieve a message and possibly a file descriptor from a socket. *)
external recvmsg_fd: Unix.file_descr -> Unix.file_descr option * string = "caml_extunix_recvmsg"
(** [sendfd sock fd] sends a file descriptor [fd] through a UNIX domain socket [sock].
This will send a sentinel message at the same time, otherwise {!sendmsg} will not pass the file descriptor. *)
let sendfd ~sock ~fd =
sendmsg sock ~sendfd:fd "\001"
(** Receive a file descriptor sent through a UNIX domain socket, ignoring the message. *)
let recvfd fd =
match recvmsg_fd fd with
| (Some recvfd, _) -> recvfd
| _ -> raise (Unix.Unix_error (Unix.EINVAL, "recvfd", "no descriptor"))
(** Receive a message sent through a UNIX domain socket. Raises
Recvfd(fd, msg) if a file descriptor is recieved. *)
exception Recvfd of Unix.file_descr * string
let recvmsg fd =
match recvmsg_fd fd with
| (None, msg) -> msg
| (Some fd, msg) -> raise (Recvfd (fd, msg))
(** Receive a message sent through a UNIX domain socket. Closes and
ignores file descriptors. *)
let recvmsg_nofd fd =
match recvmsg_fd fd with
| (Some fd, msg) -> Unix.close fd; msg
| (None, msg) -> msg
]
[%%have SYSCONF
(** {2 sysconf}
@author Roman Vorobets *)
(** name of the variable *)
type sysconf_name =
| ARG_MAX (** The maximum length of the arguments to the exec(3)
family of functions. *)
| CHILD_MAX (** The max number of simultaneous processes per user
ID. *)
| HOST_NAME_MAX (** Max length of a hostname, not including the
terminating null byte, as returned by
gethostname(2). *)
| LOGIN_NAME_MAX (** Maximum length of a login name, including the
terminating null byte. *)
| CLK_TCK (** The number of clock ticks per second. *)
| OPEN_MAX (** The maximum number of files that a process can
have open at any time. *)
| PAGESIZE (** Size of a page in bytes. *)
| RE_DUP_MAX (** The number of repeated occurrences of a BRE
permitted by regexec(3) and regcomp(3). *)
| STREAM_MAX (** The maximum number of streams that a process can
have open at any time. *)
| SYMLOOP_MAX (** The maximum number of symbolic links seen in a
pathname before resolution returns ELOOP. *)
| TTY_NAME_MAX (** The maximum length of terminal device name,
including the terminating null byte. *)
| TZNAME_MAX (** The maximum number of bytes in a timezone name. *)
| POSIX_VERSION (** Indicates the year and month the POSIX.1 standard
was approved in the format YYYYMML; the value
199009L indicates the Sept. 1990 revision. *)
| LINE_MAX (** The maximum length of a utility's input line,
either from standard input or from a file. This
includes space for a trailing newline. *)
| POSIX2_VERSION (** Indicates the version of the POSIX.2 standard in
the format of YYYYMML. *)
| PHYS_PAGES (** The number of pages of physical memory. Note that
it is possible for the product of this value and the
value of [PAGE_SIZE] to overflow. Non-standard, may be not available *)
| AVPHYS_PAGES (** The number of currently available pages of physical memory. Non-standard, may be not available *)
| NPROCESSORS_CONF (** The number of processors configured. Non-standard, may be not available *)
| NPROCESSORS_ONLN (** The number of processors currently online (available). Non-standard, may be not available *)
external sysconf: sysconf_name -> int64 = "caml_extunix_sysconf"
(** get configuration information at runtime, may raise [Not_available] for non-standard options (see above)
even in [Specific] module *)
let sysconf sc =
try
sysconf sc
with
Not_found -> raise (Not_available "sysconf")
]
[%%have (SPLICE, TEE, VMSPLICE)
(**
{2 splice}
@author Pierre Chambart
*)
(** splice functions flags *)
type splice_flag =
| SPLICE_F_MOVE (** Attempt to move pages instead of copying. Only a hint
to the kernel *)
| SPLICE_F_NONBLOCK (** Do not block on I/O *)
| SPLICE_F_MORE (** Announce that more data will be coming. Hint used by
sockets *)
| SPLICE_F_GIFT (** The user pages are a gift to the kernel. The
application may not modify this memory ever, or page
cache and on-disk data may differ. Gifting pages to
the kernel means that a subsequent splice(2)
SPLICE_F_MOVE can successfully move the pages; if
this flag is not specified, then a subsequent
splice(2) SPLICE_F_MOVE must copy the pages. Data
must also be properly page aligned, both in memory
and length.
Only use for [vmsplice]. *)
]
[%%have SPLICE
(** [splice fd_in off_in fd_out off_out len flags] moves data between two file
descriptors without copying between kernel address space and user address
space. It transfers up to [len] bytes of data from the file descriptor
[fd_in] to the file descriptor [fd_out], where one of the descriptors
must refer to a pipe.
If [fd_in] refers to a pipe, then [off_in] must be [None]. If [fd_in] does
not refer to a pipe and [off_in] is [None], then bytes are read from [fd_in]
starting from the current file offset, and the current file offset is
adjusted appropriately. If [fd_in] does not refer to a pipe and [off_in]
is [Some n], then [n] mspecifies the starting offset from which bytes will
be read from [fd_in]; in this case, the current file offset of [fd_in] is not
changed. Analogous statements apply for [fd_out] and [off_out].
@return the number of bytes spliced to or from the pipe. A return value of 0
means that there was no data to transfer, and it would not make sense to
block, because there are no writers connected to the write end of the pipe
referred to by fd_in.
*)
external splice : Unix.file_descr -> int option -> Unix.file_descr -> int option -> int -> splice_flag list -> int = "caml_extunix_splice_bytecode" "caml_extunix_splice"
]
[%%have TEE
(** [tee fd_in fd_out len flags] duplicates up to [len] bytes of data from the
pipe [fd_in] to the pipe [fd_out]. It does not consume the data that is
duplicated from [fd_in]; therefore, that data can be copied by a subsequent
splice.
@return the number of bytes that were duplicated between the input and
output. A return value of 0 means that there was no data to transfer, and
it would not make sense to block, because there are no writers connected
to the write end of the pipe referred to by fd_in.
*)
external tee : Unix.file_descr -> Unix.file_descr -> int -> splice_flag list -> int = "caml_extunix_tee"
]
(** {2 Bigarray variants} *)
(** *)
module BA = struct
[%%have PREAD
(** {2 pread}
@author Goswin von Brederlow *)
(** [all_pread fd off buf] reads up to [size of buf] bytes from file
descriptor [fd] at offset [off] (from the start of the file) into
the buffer [buf]. The file offset is not changed.
[all_pread] repeats the read operation until all characters have
been read or an error occurs. Returns less than the number of
characters requested on EAGAIN, EWOULDBLOCK or End-of-file but
only ever returns 0 on End-of-file. Continues the read operation
on EINTR. Raises an Unix.Unix_error exception in all other
cases. *)
external unsafe_all_pread: Unix.file_descr -> int -> ('a, 'b) carray -> int = "caml_extunixba_all_pread"
let all_pread fd off buf =
if off < 0
then invalid_arg "ExtUnix.all_pread"
else unsafe_all_pread fd off buf
(** [single_pread fd off buf] reads up to [size of buf] bytes from file
descriptor [fd] at offset [off] (from the start of the file) into
the buffer [buf]. The file offset is not changed.
[single_pread] attempts to read only once. Returns the number of
characters read or raises an Unix.Unix_error exception. Unlike the
string variant of the same name there is no limit on the number of
characters read. *)
external unsafe_single_pread: Unix.file_descr -> int -> ('a, 'b) carray -> int = "caml_extunixba_single_pread"
let single_pread fd off buf =
if off < 0
then invalid_arg "ExtUnix.single_pread"
else unsafe_single_pread fd off buf
(** [pread fd off buf] reads up to [size of buf] bytes from file
descriptor [fd] at offset [off] (from the start of the file) into
the buffer [buf]. The file offset is not changed.
[pread] repeats the read operation until all characters have
been read or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be read before an error occurs. Continues
the read operation on EINTR. Returns the number of characters
written in all other cases. *)
external unsafe_pread: Unix.file_descr -> int -> ('a, 'b) carray -> int = "caml_extunixba_pread"
let pread fd off buf =
if off < 0
then invalid_arg "ExtUnix.pread"
else unsafe_pread fd off buf
(** [intr_pread fd off buf] reads up to [size of buf] bytes from file
descriptor [fd] at offset [off] (from the start of the file) into
the buffer [buf]. The file offset is not changed.
[intr_pread] repeats the read operation until all characters have
been read or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be read before an error occurs. Does NOT
continue on EINTR. Returns the number of characters written in all
other cases. *)
external unsafe_intr_pread: Unix.file_descr -> int -> ('a, 'b) carray -> int = "caml_extunixba_intr_pread"
let intr_pread fd off buf =
if off < 0
then invalid_arg "ExtUnix.intr_pread"
else unsafe_intr_pread fd off buf
]
[%%have PWRITE
(** {2 pwrite}
@author Goswin von Brederlow *)
(** [all_pwrite fd off buf] writes up to [size of buf] bytes from file
descriptor [fd] at offset [off] (from the start of the file) into
the buffer [buf]. The file offset is not changed.
[all_pwrite] repeats the write operation until all characters have
been written or an error occurs. Returns less than the number of
characters requested on EAGAIN, EWOULDBLOCK but never 0. Continues
the write operation on EINTR. Raises an Unix.Unix_error exception
in all other cases. *)
external unsafe_all_pwrite: Unix.file_descr -> int -> ('a, 'b) carray -> int = "caml_extunixba_all_pwrite"
let all_pwrite fd off buf =
if off < 0
then invalid_arg "ExtUnix.all_pwrite"
else unsafe_all_pwrite fd off buf
(** [single_pwrite fd off buf] writes up to [size of buf] bytes from file
descriptor [fd] at offset [off] (from the start of the file) into
the buffer [buf]. The file offset is not changed.
[single_pwrite] attempts to write only once. Returns the number of
characters written or raises an Unix.Unix_error exception. Unlike
the string variant of the same name there is no limit on the
number of characters written. *)
external unsafe_single_pwrite: Unix.file_descr -> int -> ('a, 'b) carray -> int = "caml_extunixba_single_pwrite"
let single_pwrite fd off buf =
if off < 0
then invalid_arg "ExtUnix.single_pwrite"
else unsafe_single_pwrite fd off buf
(** [pwrite fd off buf] writes up to [size of buf] bytes from file
descriptor [fd] at offset [off] (from the start of the file) into
the buffer [buf]. The file offset is not changed.
[pwrite] repeats the write operation until all characters have
been written or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be written before an error occurs. Continues
the write operation on EINTR. Returns the number of characters
written in all other cases. *)
external unsafe_pwrite: Unix.file_descr -> int -> ('a, 'b) carray -> int = "caml_extunixba_pwrite"
let pwrite fd off buf =
if off < 0
then invalid_arg "ExtUnix.pwrite"
else unsafe_pwrite fd off buf
(** [intr_pwrite fd off buf] writes up to [size of buf] bytes from file
descriptor [fd] at offset [off] (from the start of the file) into
the buffer [buf]. The file offset is not changed.
[intr_pwrite] repeats the write operation until all characters have
been written or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be written before an error occurs. Does NOT
continue on EINTR. Returns the number of characters written in all
other cases. *)
external unsafe_intr_pwrite: Unix.file_descr -> int -> ('a, 'b) carray -> int = "caml_extunixba_intr_pwrite"
let intr_pwrite fd off buf =
if off < 0
then invalid_arg "ExtUnix.intr_pwrite"
else unsafe_intr_pwrite fd off buf
]
[%%have READ
(** {2 read}
@author Goswin von Brederlow *)
(** [all_read fd buf] reads up to [size of buf] bytes from file
descriptor [fd] into the buffer [buf].
[all_read] repeats the read operation until all characters have
been read or an error occurs. Returns less than the number of
characters requested on EAGAIN, EWOULDBLOCK or End-of-file but
only ever returns 0 on End-of-file. Continues the read operation
on EINTR. Raises an Unix.Unix_error exception in all other
cases. *)
external all_read: Unix.file_descr -> ('a, 'b) carray -> int = "caml_extunixba_all_read"
(** [single_read fd buf] reads up to [size of buf] bytes from file
descriptor [fd] into the buffer [buf].
[single_read] attempts to read only once. Returns the number of
characters read or raises an Unix.Unix_error exception. Unlike the
string variant of the same name there is no limit on the number of
characters read. *)
external single_read: Unix.file_descr -> ('a, 'b) carray -> int = "caml_extunixba_single_read"
(** [read fd buf] reads up to [size of buf] bytes from file descriptor
[fd] into the buffer [buf].
[read] repeats the read operation until all characters have
been read or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be read before an error occurs. Continues
the read operation on EINTR. Returns the number of characters
written in all other cases. *)
external read: Unix.file_descr -> ('a, 'b) carray -> int = "caml_extunixba_read"
(** [intr_read fd buf] reads up to [size of buf] bytes from file
descriptor [fd] into the buffer [buf].
[intr_read] repeats the read operation until all characters have
been read or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be read before an error occurs. Does NOT
continue on EINTR. Returns the number of characters written in all
other cases. *)
external intr_read: Unix.file_descr -> ('a, 'b) carray -> int = "caml_extunixba_intr_read"
]
[%%have WRITE
(** {2 write}
@author Goswin von Brederlow *)
(** [all_write fd buf] writes up to [size of buf] bytes from file
descriptor [fd] into the buffer [buf].
[all_write] repeats the write operation until all characters have
been written or an error occurs. Returns less than the number of
characters requested on EAGAIN, EWOULDBLOCK but never 0. Continues
the write operation on EINTR. Raises an Unix.Unix_error exception
in all other cases. *)
external all_write: Unix.file_descr -> ('a, 'b) carray -> int = "caml_extunixba_all_write"
(** [single_write fd buf] writes up to [size of buf] bytes from file
descriptor [fd] into the buffer [buf].
[single_write] attempts to write only once. Returns the number of
characters written or raises an Unix.Unix_error exception. Unlike
the string variant of the same name there is no limit on the
number of characters written. *)
external single_write: Unix.file_descr -> ('a, 'b) carray -> int = "caml_extunixba_single_write"
(** [write fd buf] writes up to [size of buf] bytes from file
descriptor [fd] into the buffer [buf].
[write] repeats the write operation until all characters have
been written or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be written before an error occurs. Continues
the write operation on EINTR. Returns the number of characters
written in all other cases. *)
external write: Unix.file_descr -> ('a, 'b) carray -> int = "caml_extunixba_write"
(** [intr_write fd buf] writes up to [size of buf] bytes from file
descriptor [fd] into the buffer [buf].
[intr_write] repeats the write operation until all characters have
been written or an error occurs. Raises an Unix.Unix_error exception
if 0 characters could be written before an error occurs. Does NOT
continue on EINTR. Returns the number of characters written in all
other cases. *)
external intr_write: Unix.file_descr -> ('a, 'b) carray -> int = "caml_extunixba_intr_write"
]
(** {2 Byte order conversion} *)
(** {2 big endian functions}
@author Goswin von Brederlow *)
module BigEndian = struct
[%%have ENDIAN
(** [unsafe_get_X buf off] extract integer of type [X] from a
buffer [buf] starting at offset [off]. Unsigned types are 0
extended and signed types are sign extended to fill the ocaml
type. Bounds checking is not performed. Use with caution and
only when the program logic guarantees that the access is within
bounds.
Note: The 31bit functions extract a 32bit integer and return it
as ocaml int. On 32bit platforms this can overflow as ocaml
integers are 31bit signed there. No error is reported if this
occurs. Use with care.
Note: The same applies to 63bit functions.
*)
external unsafe_get_uint8 : 'a carray8 -> int -> int = "caml_extunixba_get_u8" [@@noalloc]
external unsafe_get_int8 : 'a carray8 -> int -> int = "caml_extunixba_get_s8" [@@noalloc]
external unsafe_get_uint16 : 'a carray8 -> int -> int = "caml_extunixba_get_bu16" [@@noalloc]
external unsafe_get_int16 : 'a carray8 -> int -> int = "caml_extunixba_get_bs16" [@@noalloc]
external unsafe_get_uint31 : 'a carray8 -> int -> int = "caml_extunixba_get_bu31" [@@noalloc]
external unsafe_get_int31 : 'a carray8 -> int -> int = "caml_extunixba_get_bs31" [@@noalloc]
external unsafe_get_int32 : 'a carray8 -> int -> int32 = "caml_extunixba_get_bs32"
external unsafe_get_uint63 : 'a carray8 -> int -> int = "caml_extunixba_get_bu63" [@@noalloc]
external unsafe_get_int63 : 'a carray8 -> int -> int = "caml_extunixba_get_bs63" [@@noalloc]
external unsafe_get_int64 : 'a carray8 -> int -> int64 = "caml_extunixba_get_bs64"
(** [get_X buf off] same as [unsafe_get_X] but with bounds checking. *)
let get_uint8 buf off =
if off < 0 || off >= Bigarray.Array1.dim buf
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint8 buf off
let get_int8 buf off =
if off < 0 || off >= Bigarray.Array1.dim buf
then raise (Invalid_argument "index out of bounds");
unsafe_get_int8 buf off
let get_uint16 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 2
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint16 buf off
let get_int16 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 2
then raise (Invalid_argument "index out of bounds");
unsafe_get_int16 buf off
let get_uint31 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint31 buf off
let get_int31 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_int31 buf off
let get_int32 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_int32 buf off
let get_uint63 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint63 buf off
let get_int63 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_int63 buf off
let get_int64 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_int64 buf off
(** [unsafe_set_X buf off v] stores the integer [v] as type [X] in a
buffer [buf] starting at offset [off]. Bounds checking is not
performed. Use with caution and only when the program logic
guarantees that the access is within bounds.
Note: The 31bit functions store an ocaml int as 32bit
integer. On 32bit platforms ocaml integers are 31bit signed and
will be sign extended to 32bit first. Use with care.
Note: The same applies to 63bit function.
*)
external unsafe_set_uint8 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_8" [@@noalloc]
external unsafe_set_int8 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_8" [@@noalloc]
external unsafe_set_uint16 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_b16" [@@noalloc]
external unsafe_set_int16 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_b16" [@@noalloc]
external unsafe_set_uint31 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_b31" [@@noalloc]
external unsafe_set_int31 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_b31" [@@noalloc]
external unsafe_set_int32 : 'a carray8 -> int -> int32 -> unit = "caml_extunixba_set_b32" [@@noalloc]
external unsafe_set_uint63 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_b63" [@@noalloc]
external unsafe_set_int63 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_b63" [@@noalloc]
external unsafe_set_int64 : 'a carray8 -> int -> int64 -> unit = "caml_extunixba_set_b64" [@@noalloc]
(** [set_X buf off v] same as [unsafe_set_X] but with bounds checking. *)
let set_uint8 buf off v =
if off < 0 || off >= Bigarray.Array1.dim buf
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint8 buf off v
let set_int8 buf off v =
if off < 0 || off >= Bigarray.Array1.dim buf
then raise (Invalid_argument "index out of bounds");
unsafe_set_int8 buf off v
let set_uint16 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 2
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint16 buf off v
let set_int16 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 2
then raise (Invalid_argument "index out of bounds");
unsafe_set_int16 buf off v
let set_uint31 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint31 buf off v
let set_int31 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_int31 buf off v
let set_int32 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_int32 buf off v
let set_uint63 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint63 buf off v
let set_int63 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_int63 buf off v
let set_int64 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_int64 buf off v
]
end (* module BigEndian *)
(** {2 little endian functions}
@author Goswin von Brederlow *)
module LittleEndian = struct
[%%have ENDIAN
(** [unsafe_get_X buf off] extract integer of type [X] from a
buffer [buf] starting at offset [off]. Unsigned types are 0
extended and signed types are sign extended to fill the ocaml
type. Bounds checking is not performed. Use with caution and
only when the program logic guarantees that the access is within
bounds.
Note: The 31bit functions extract a 32bit integer and return it
as ocaml int. On 32bit platforms this can overflow as ocaml
integers are 31bit signed there. No error is reported if this
occurs. Use with care.
Note: The same applies to 63bit functions.
*)
external unsafe_get_uint8 : 'a carray8 -> int -> int = "caml_extunixba_get_u8" [@@noalloc]
external unsafe_get_int8 : 'a carray8 -> int -> int = "caml_extunixba_get_s8" [@@noalloc]
external unsafe_get_uint16 : 'a carray8 -> int -> int = "caml_extunixba_get_lu16" [@@noalloc]
external unsafe_get_int16 : 'a carray8 -> int -> int = "caml_extunixba_get_ls16" [@@noalloc]
external unsafe_get_uint31 : 'a carray8 -> int -> int = "caml_extunixba_get_lu31" [@@noalloc]
external unsafe_get_int31 : 'a carray8 -> int -> int = "caml_extunixba_get_ls31" [@@noalloc]
external unsafe_get_int32 : 'a carray8 -> int -> int32 = "caml_extunixba_get_ls32"
external unsafe_get_uint63 : 'a carray8 -> int -> int = "caml_extunixba_get_lu63" [@@noalloc]
external unsafe_get_int63 : 'a carray8 -> int -> int = "caml_extunixba_get_ls63" [@@noalloc]
external unsafe_get_int64 : 'a carray8 -> int -> int64 = "caml_extunixba_get_ls64"
(** [get_X buf off] same as [unsafe_get_X] but with bounds checking. *)
let get_uint8 buf off =
if off < 0 || off >= Bigarray.Array1.dim buf
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint8 buf off
let get_int8 buf off =
if off < 0 || off >= Bigarray.Array1.dim buf
then raise (Invalid_argument "index out of bounds");
unsafe_get_int8 buf off
let get_uint16 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 2
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint16 buf off
let get_int16 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 2
then raise (Invalid_argument "index out of bounds");
unsafe_get_int16 buf off
let get_uint31 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint31 buf off
let get_int31 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_int31 buf off
let get_int32 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_int32 buf off
let get_uint63 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint63 buf off
let get_int63 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_int63 buf off
let get_int64 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_int64 buf off
(** [unsafe_set_X buf off v] stores the integer [v] as type [X] in a
buffer [buf] starting at offset [off]. Bounds checking is not
performed. Use with caution and only when the program logic
guarantees that the access is within bounds.
Note: The 31bit functions store an ocaml int as 32bit
integer. On 32bit platforms ocaml integers are 31bit signed and
will be sign extended to 32bit first. Use with care.
Note: The same applies to 63bit functions.
*)
external unsafe_set_uint8 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_8" [@@noalloc]
external unsafe_set_int8 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_8" [@@noalloc]
external unsafe_set_uint16 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_l16" [@@noalloc]
external unsafe_set_int16 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_l16" [@@noalloc]
external unsafe_set_uint31 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_l31" [@@noalloc]
external unsafe_set_int31 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_l31" [@@noalloc]
external unsafe_set_int32 : 'a carray8 -> int -> int32 -> unit = "caml_extunixba_set_l32" [@@noalloc]
external unsafe_set_uint63 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_l63" [@@noalloc]
external unsafe_set_int63 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_l63" [@@noalloc]
external unsafe_set_int64 : 'a carray8 -> int -> int64 -> unit = "caml_extunixba_set_l64" [@@noalloc]
(** [set_X buf off v] same as [unsafe_set_X] but with bounds checking. *)
let set_uint8 buf off v =
if off < 0 || off >= Bigarray.Array1.dim buf
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint8 buf off v
let set_int8 buf off v =
if off < 0 || off >= Bigarray.Array1.dim buf
then raise (Invalid_argument "index out of bounds");
unsafe_set_int8 buf off v
let set_uint16 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 2
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint16 buf off v
let set_int16 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 2
then raise (Invalid_argument "index out of bounds");
unsafe_set_int16 buf off v
let set_uint31 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint31 buf off v
let set_int31 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_int31 buf off v
let set_int32 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_int32 buf off v
let set_uint63 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint63 buf off v
let set_int63 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_int63 buf off v
let set_int64 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_int64 buf off v
]
end (* module LittleEndian *)
(** {2 host endian functions}
@author Goswin von Brederlow *)
module HostEndian = struct
(** [unsafe_get_X buf off] extract integer of type [X] from a
buffer [buf] starting at offset [off]. Unsigned types are 0
extended and signed types are sign extended to fill the ocaml
type. Bounds checking is not performed. Use with caution and
only when the program logic guarantees that the access is within
bounds.
Note: The 31bit functions extract a 32bit integer and return it
as ocaml int. On 32bit platforms this can overflow as ocaml
integers are 31bit signed there. No error is reported if this
occurs. Use with care.
Note: The same applies to 63bit functions.
*)
external unsafe_get_uint8 : 'a carray8 -> int -> int = "caml_extunixba_get_u8" [@@noalloc]
external unsafe_get_int8 : 'a carray8 -> int -> int = "caml_extunixba_get_s8" [@@noalloc]
external unsafe_get_uint16 : 'a carray8 -> int -> int = "caml_extunixba_get_hu16" [@@noalloc]
external unsafe_get_int16 : 'a carray8 -> int -> int = "caml_extunixba_get_hs16" [@@noalloc]
external unsafe_get_uint31 : 'a carray8 -> int -> int = "caml_extunixba_get_hu31" [@@noalloc]
external unsafe_get_int31 : 'a carray8 -> int -> int = "caml_extunixba_get_hs31" [@@noalloc]
external unsafe_get_int32 : 'a carray8 -> int -> int32 = "caml_extunixba_get_hs32"
external unsafe_get_uint63 : 'a carray8 -> int -> int = "caml_extunixba_get_hu63" [@@noalloc]
external unsafe_get_int63 : 'a carray8 -> int -> int = "caml_extunixba_get_hs63" [@@noalloc]
external unsafe_get_int64 : 'a carray8 -> int -> int64 = "caml_extunixba_get_hs64"
(** [get_X buf off] same as [unsafe_get_X] but with bounds checking. *)
let get_uint8 buf off =
if off < 0 || off >= Bigarray.Array1.dim buf
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint8 buf off
let get_int8 buf off =
if off < 0 || off >= Bigarray.Array1.dim buf
then raise (Invalid_argument "index out of bounds");
unsafe_get_int8 buf off
let get_uint16 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 2
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint16 buf off
let get_int16 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 2
then raise (Invalid_argument "index out of bounds");
unsafe_get_int16 buf off
let get_uint31 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint31 buf off
let get_int31 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_int31 buf off
let get_int32 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_get_int32 buf off
let get_uint63 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_uint63 buf off
let get_int63 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_int63 buf off
let get_int64 buf off =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_get_int64 buf off
(** [unsafe_set_X buf off v] stores the integer [v] as type [X] in a
buffer [buf] starting at offset [off]. Bounds checking is not
performed. Use with caution and only when the program logic
guarantees that the access is within bounds.
Note: The 31bit functions store an ocaml int as 32bit
integer. On 32bit platforms ocaml integers are 31bit signed and
will be sign extended to 32bit first. Use with care.
Note: The same applies to 63bit functions.
*)
external unsafe_set_uint8 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_8" [@@noalloc]
external unsafe_set_int8 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_8" [@@noalloc]
external unsafe_set_uint16 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_h16" [@@noalloc]
external unsafe_set_int16 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_h16" [@@noalloc]
external unsafe_set_uint31 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_h31" [@@noalloc]
external unsafe_set_int31 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_h31" [@@noalloc]
external unsafe_set_int32 : 'a carray8 -> int -> int32 -> unit = "caml_extunixba_set_h32" [@@noalloc]
external unsafe_set_uint63 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_h63" [@@noalloc]
external unsafe_set_int63 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_h63" [@@noalloc]
external unsafe_set_int64 : 'a carray8 -> int -> int64 -> unit = "caml_extunixba_set_h64" [@@noalloc]
(** [set_X buf off v] same as [unsafe_set_X] but with bounds checking. *)
let set_uint8 buf off v =
if off < 0 || off >= Bigarray.Array1.dim buf
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint8 buf off v
let set_int8 buf off v =
if off < 0 || off >= Bigarray.Array1.dim buf
then raise (Invalid_argument "index out of bounds");
unsafe_set_int8 buf off v
let set_uint16 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 2
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint16 buf off v
let set_int16 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 2
then raise (Invalid_argument "index out of bounds");
unsafe_set_int16 buf off v
let set_uint31 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint31 buf off v
let set_int31 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_int31 buf off v
let set_int32 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 4
then raise (Invalid_argument "index out of bounds");
unsafe_set_int32 buf off v
let set_uint63 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_uint63 buf off v
let set_int63 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_int63 buf off v
let set_int64 buf off v =
if off < 0 || off > Bigarray.Array1.dim buf - 8
then raise (Invalid_argument "index out of bounds");
unsafe_set_int64 buf off v
end (* module HostEndian *)
(** [unsafe_get_substr buf off len] extracts the substring from buffer
[buf] starting at offset [off] and length [len]. Bounds checking
is not performed. Use with caution and only when the program logic
guarantees that the access is within bounds.*)
external unsafe_get_substr : 'a carray8 -> int -> int -> string = "caml_extunixba_get_substr"
(** [get_substr buf off len] same as [unsafe_get_substr] but with
bounds checking. *)
let get_substr buf off len =
if off < 0 || len < 0 || off > Bigarray.Array1.dim buf - len
then raise (Invalid_argument "index out of bounds");
unsafe_get_substr buf off len
(** [unsafe_set_substr buf off str] stores the string in buffer [buf]
starting at offset [off]. Bounds checking is not performed. Use
with caution and only when the program logic guarantees that the
access is within bounds.*)
external unsafe_set_substr : 'a carray8 -> int -> string -> unit = "caml_extunixba_set_substr"
(** [set_substr buf off str] same as [unsafe_set_substr] but with
bounds checking. *)
let set_substr buf off str =
if off < 0 || off > Bigarray.Array1.dim buf - String.length str
then raise (Invalid_argument "index out of bounds");
unsafe_set_substr buf off str
[%%have VMSPLICE
(**
{2 splice}
@author Pierre Chambart
*)
(** I/O vector. Used to send multiple data using a single system call *)
type 'a iov = {
iov_buf : 'a carray8;
iov_off : int;
iov_len : int;
}
(** [vmsplice fd iovs flags] sends the data described by [iovs] to the pipe [fd]
@return the number of bytes transferred to the pipe. *)
external vmsplice : Unix.file_descr -> 'a iov array -> splice_flag list -> int = "caml_extunixba_vmsplice"
]
end (* module BA *)
(* NB Should be after all 'external' definitions *)
(** {2 Meta} *)
[%%show_me_the_money
[@@@ocaml.doc {|
[have name]
@return indication whether function [name] is available
- [Some true] if available
- [Some false] if not available
- [None] if not known
e.g. [have "eventfd"]|}]]
(* vim: ft=ocaml
*)
ocaml-extunix-0.3.2/src/fadvise.c 0000664 0000000 0000000 00000002722 14045766433 0016704 0 ustar 00root root 0000000 0000000 /*
* Binding to posix_fadvise
*
* Copyright 2008-2009 Talend, Inc.
*
* License LGPL-2.1 with OCaml linking static exception
*
* For more information go to: www.talend.com
*
* author: Sylvain Le Gall
*
*/
#define EXTUNIX_WANT_FADVISE
#include "config.h"
#if defined(EXTUNIX_HAVE_FADVISE)
static int caml_advises[] =
{
POSIX_FADV_NORMAL,
POSIX_FADV_SEQUENTIAL,
POSIX_FADV_RANDOM,
POSIX_FADV_NOREUSE,
POSIX_FADV_WILLNEED,
POSIX_FADV_DONTNEED
};
CAMLprim value caml_extunix_fadvise64(value vfd, value voff, value vlen, value vadvise)
{
int errcode = 0;
int fd = -1;
off64_t off = 0;
off64_t len = 0;
int advise = 0;
CAMLparam4(vfd, voff, vlen, vadvise);
fd = Int_val(vfd);
off = Int64_val(voff);
len = Int64_val(vlen);
advise = caml_advises[Int_val(vadvise)];
errcode = posix_fadvise64(fd, off, len, advise);
if (errcode != 0)
{
unix_error(errcode, "fadvise64", Nothing);
};
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_fadvise(value vfd, value voff, value vlen, value vadvise)
{
int errcode = 0;
int fd = -1;
off_t off = 0;
off_t len = 0;
int advise = 0;
CAMLparam4(vfd, voff, vlen, vadvise);
fd = Int_val(vfd);
off = Long_val(voff);
len = Long_val(vlen);
advise = caml_advises[Int_val(vadvise)];
errcode = posix_fadvise(fd, off, len, advise);
if (errcode != 0)
{
unix_error(errcode, "fadvise", Nothing);
};
CAMLreturn(Val_unit);
}
#endif
ocaml-extunix-0.3.2/src/fallocate.c 0000664 0000000 0000000 00000005526 14045766433 0017222 0 ustar 00root root 0000000 0000000 /*
* posix_fallocate binding
*
* Copyright 2008-2009 Talend, Inc.
*
* License LGPL-2.1 with OCaml linking static exception
*
* For more information go to: www.talend.com
*
* author: Sylvain Le Gall
*
*/
#define EXTUNIX_WANT_FALLOCATE
#include "config.h"
#if defined(EXTUNIX_HAVE_FALLOCATE)
#if defined(WIN32)
static void caml_fallocate_error (void)
{
win32_maperr(GetLastError());
uerror("fallocate", Val_unit);
}
static __int64 caml_fallocate_lseek (HANDLE hFile, __int64 i64Pos, DWORD dwMoveMethod)
{
LARGE_INTEGER liRes;
liRes.QuadPart = i64Pos;
liRes.LowPart = SetFilePointer(hFile, liRes.LowPart, &liRes.HighPart, dwMoveMethod);
if (liRes.LowPart == INVALID_SET_FILE_POINTER &&
GetLastError() != NO_ERROR)
{
caml_fallocate_error();
};
return liRes.QuadPart;
}
static void caml_fallocate_do (HANDLE hFile, __int64 i64Off, __int64 i64Len)
{
__int64 i64Cur = 0;
LARGE_INTEGER liFileSize;
/* Check that off + len > file size */
if (!GetFileSizeEx(hFile, &liFileSize))
{
caml_fallocate_error();
};
if (i64Off + i64Len <= liFileSize.QuadPart)
{
return;
};
/* Get the current position in the file */
i64Cur = caml_fallocate_lseek(hFile, 0, FILE_CURRENT);
/* Go to the expected end of file */
caml_fallocate_lseek(hFile, i64Off, FILE_BEGIN);
caml_fallocate_lseek(hFile, i64Len, FILE_CURRENT);
/* Extend file */
if (!SetEndOfFile(hFile))
{
caml_fallocate_error();
};
/* Restore initial file pointer position */
caml_fallocate_lseek(hFile, i64Cur, FILE_BEGIN);
}
CAMLprim value caml_extunix_fallocate64(value vfd, value voff, value vlen)
{
CAMLparam3(vfd, voff, vlen);
caml_fallocate_do(Handle_val(vfd), Int64_val(voff), Int64_val(vlen));
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_fallocate(value vfd, value voff, value vlen)
{
CAMLparam3(vfd, voff, vlen);
caml_fallocate_do(Handle_val(vfd), Long_val(voff), Long_val(vlen));
CAMLreturn(Val_unit);
}
#else
static void caml_fallocate_error (int errcode)
{
if (errcode != 0)
{
unix_error(errcode, "fallocate", Nothing);
};
}
CAMLprim value caml_extunix_fallocate64(value vfd, value voff, value vlen)
{
int errcode = 0;
int fd = -1;
off64_t off = 0;
off64_t len = 0;
CAMLparam3(vfd, voff, vlen);
fd = Int_val(vfd);
off = Int64_val(voff);
len = Int64_val(vlen);
errcode = posix_fallocate64(fd, off, len);
caml_fallocate_error(errcode);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_fallocate(value vfd, value voff, value vlen)
{
int errcode = 0;
int fd = -1;
off_t off = 0;
off_t len = 0;
CAMLparam3(vfd, voff, vlen);
fd = Int_val(vfd);
off = Long_val(voff);
len = Long_val(vlen);
errcode = posix_fallocate(fd, off, len);
caml_fallocate_error(errcode);
CAMLreturn(Val_unit);
}
#endif /* WIN32 */
#endif /* EXTUNIX_HAVE_FALLOCATE */
ocaml-extunix-0.3.2/src/fexecve.c 0000664 0000000 0000000 00000001557 14045766433 0016715 0 ustar 00root root 0000000 0000000 #define EXTUNIX_WANT_FEXECVE
#include "config.h"
#if defined(EXTUNIX_HAVE_FEXECVE)
/* Copyright © 2012 Andre Nathan */
static char **
array_of_value(value v)
{
CAMLparam1(v);
char **arr;
mlsize_t size, i;
size = Wosize_val(v);
arr = caml_stat_alloc((size + 1) * sizeof(char *));
for (i = 0; i < size; i++)
arr[i] = (char *)String_val(Field(v, i));
arr[size] = NULL;
CAMLreturnT (char **, arr);
}
CAMLprim value caml_extunix_fexecve(value fd_val, value argv_val, value envp_val)
{
CAMLparam3(fd_val, argv_val, envp_val);
char **argv;
char **envp;
argv = array_of_value(argv_val);
envp = array_of_value(envp_val);
fexecve(Int_val(fd_val), argv, envp);
caml_stat_free(argv);
caml_stat_free(envp);
uerror("fexecve", Nothing);
CAMLreturn (Val_unit); /* not reached */
}
#endif /* EXTUNIX_HAVE_FEXECVE */
ocaml-extunix-0.3.2/src/fsync.c 0000664 0000000 0000000 00000003710 14045766433 0016403 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_FSYNC
#define EXTUNIX_WANT_FDATASYNC
#define EXTUNIX_WANT_SYNC
#define EXTUNIX_WANT_SYNCFS
#include "config.h"
#if defined(WIN32)
#if defined(EXTUNIX_HAVE_FSYNC)
CAMLprim value caml_extunix_fsync(value v)
{
CAMLparam1(v);
HANDLE h = INVALID_HANDLE_VALUE;
int r = 0;
if (KIND_HANDLE != Descr_kind_val(v))
caml_invalid_argument("fsync");
h = Handle_val(v);
caml_enter_blocking_section();
r = FlushFileBuffers(h);
caml_leave_blocking_section();
if (0 == r)
uerror("fsync",Nothing);
CAMLreturn(Val_unit);
}
#if defined(EXTUNIX_HAVE_FDATASYNC)
CAMLprim value caml_extunix_fdatasync(value v)
{
return caml_extunix_fsync(v);
}
#endif
#endif /* EXTUNIX_HAVE_FSYNC */
#else /* WIN32 */
#if defined(EXTUNIX_HAVE_FSYNC)
CAMLprim value caml_extunix_fsync(value v_fd)
{
CAMLparam1(v_fd);
int r = 0;
caml_enter_blocking_section();
r = fsync(Int_val(v_fd));
caml_leave_blocking_section();
if (0 != r)
uerror("fsync",Nothing);
CAMLreturn(Val_unit);
}
#endif
#if defined(EXTUNIX_HAVE_FDATASYNC)
CAMLprim value caml_extunix_fdatasync(value v_fd)
{
CAMLparam1(v_fd);
int r = 0;
caml_enter_blocking_section();
r = fdatasync(Int_val(v_fd));
caml_leave_blocking_section();
if (0 != r)
uerror("fdatasync",Nothing);
CAMLreturn(Val_unit);
}
#endif
#if defined(EXTUNIX_HAVE_SYNC)
CAMLprim value caml_extunix_sync(value v_unit)
{
(void)v_unit;
caml_enter_blocking_section();
sync();
caml_leave_blocking_section();
return Val_unit;
}
#endif
#if defined(EXTUNIX_HAVE_SYNCFS)
CAMLprim value caml_extunix_syncfs(value v_fd)
{
CAMLparam1(v_fd);
int r = 0;
caml_enter_blocking_section();
#if defined(EXTUNIX_USE_SYS_SYNCFS)
r = syscall(SYS_syncfs, Int_val(v_fd));
#else
r = syncfs(Int_val(v_fd));
#endif
caml_leave_blocking_section();
if (0 != r)
uerror("syncfs",Nothing);
CAMLreturn(Val_unit);
}
#endif
#endif /* !WIN32 */
ocaml-extunix-0.3.2/src/ioctl_siocgifconf.c 0000664 0000000 0000000 00000005030 14045766433 0020741 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_SIOCGIFCONF
#define EXTUNIX_WANT_INET_NTOA
#define EXTUNIX_WANT_INET_NTOP
#define EXTUNIX_WANT_IFADDRS
#include "config.h"
#if defined(EXTUNIX_HAVE_SIOCGIFCONF)
CAMLprim value caml_extunix_ioctl_siocgifconf(value v_sock)
{
CAMLparam1(v_sock);
CAMLlocal3(lst,item,cons);
struct ifreq ifreqs[32];
struct ifconf ifconf;
unsigned int i;
lst = Val_emptylist;
memset(&ifconf, 0, sizeof(ifconf));
ifconf.ifc_req = ifreqs;
ifconf.ifc_len = sizeof(ifreqs);
if (0 != ioctl(Int_val(v_sock), SIOCGIFCONF, (char *)&ifconf))
uerror("ioctl(SIOCGIFCONF)", Nothing);
for (i = 0; i < ifconf.ifc_len/sizeof(struct ifreq); ++i)
{
cons = caml_alloc(2, 0);
item = caml_alloc(2, 0);
Store_field(item, 0, caml_copy_string(ifreqs[i].ifr_name));
Store_field(item, 1, caml_copy_string(inet_ntoa(((struct sockaddr_in *)&ifreqs[i].ifr_addr)->sin_addr)));
Store_field(cons, 0, item); /* head */
Store_field(cons, 1, lst); /* tail */
lst = cons;
}
CAMLreturn(lst);
}
#endif
#if defined(EXTUNIX_HAVE_IFADDRS)
CAMLprim value caml_extunix_getifaddrs(value v)
{
CAMLparam1(v);
CAMLlocal3(lst,item,cons);
struct ifaddrs *ifaddrs = NULL;
struct ifaddrs *iter = NULL;
char addr_str[INET6_ADDRSTRLEN];
lst = Val_emptylist;
if (0 != getifaddrs(&ifaddrs))
{
if (ifaddrs) freeifaddrs(ifaddrs);
uerror("getifaddrs", Nothing);
}
iter = ifaddrs; /* store head for further free */
while(iter != NULL)
{
if (iter->ifa_addr != NULL)
{
const sa_family_t family = iter->ifa_addr->sa_family;
if (family == AF_INET || family == AF_INET6)
{
cons = caml_alloc(2, 0);
item = caml_alloc(2, 0);
Store_field(item, 0, caml_copy_string(iter->ifa_name));
if (family == AF_INET)
{
if (NULL == inet_ntop(family, &((struct sockaddr_in *)iter->ifa_addr)->sin_addr, addr_str, INET_ADDRSTRLEN))
uerror("inet_ntop", Nothing);
}
else
{
if (NULL == inet_ntop(family, &((struct sockaddr_in6 *)iter->ifa_addr)->sin6_addr, addr_str, INET6_ADDRSTRLEN))
uerror("inet_ntop", Nothing);
}
Store_field(item, 1, caml_copy_string(addr_str));
Store_field(cons, 0, item); /* head */
Store_field(cons, 1, lst); /* tail */
lst = cons;
}
}
iter = iter->ifa_next;
}
freeifaddrs(ifaddrs);
CAMLreturn(lst);
}
#endif
ocaml-extunix-0.3.2/src/malloc.c 0000664 0000000 0000000 00000002014 14045766433 0016524 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_MALLOC_INFO
#define EXTUNIX_WANT_MALLOC_STATS
#define EXTUNIX_WANT_MCHECK
#include "config.h"
#if defined(EXTUNIX_HAVE_MALLOC_STATS)
CAMLprim value caml_extunix_malloc_stats(value v_unit)
{
UNUSED(v_unit);
malloc_stats();
return Val_unit;
}
#endif
#if defined(EXTUNIX_HAVE_MALLOC_INFO)
#include
CAMLprim value caml_extunix_malloc_info(value v_unit)
{
CAMLparam0();
CAMLlocal1(v_s);
char* buf = NULL;
size_t size;
int r;
FILE* f = open_memstream(&buf,&size);
UNUSED(v_unit);
if (NULL == f)
uerror("malloc_info", Nothing);
r = malloc_info(0,f);
fclose(f);
if (0 != r)
{
free(buf);
uerror("malloc_info", Nothing);
}
v_s = caml_alloc_string(size);
memcpy(Bp_val(v_s), buf, size);
free(buf);
CAMLreturn(v_s);
}
#endif
#if defined(EXTUNIX_HAVE_MCHECK)
CAMLprim value caml_extunix_mtrace(value v)
{
UNUSED(v);
mtrace();
return Val_unit;
}
CAMLprim value caml_extunix_muntrace(value v)
{
UNUSED(v);
muntrace();
return Val_unit;
}
#endif
ocaml-extunix-0.3.2/src/memalign.c 0000664 0000000 0000000 00000001501 14045766433 0017046 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_MEMALIGN
#include "config.h"
#if defined(EXTUNIX_HAVE_MEMALIGN)
/*
* Binding to posix_memalign
*
* Copyright 2012 Goswin von Brederlow
*
* License LGPL-2.1 with OCaml linking static exception
*
* For more information go to: www.talend.com
*
* author: Goswin von Brederlow
*
*/
CAMLprim value caml_extunix_memalign(value valignment, value vsize)
{
CAMLparam2(valignment, vsize);
size_t alignment;
size_t size;
int errcode;
void *memptr;
alignment = Int_val(valignment);
size = Int_val(vsize);
errcode = posix_memalign(&memptr, alignment, size);
if (errcode != 0)
{
unix_error(errcode, "memalign", Nothing);
};
CAMLreturn(caml_ba_alloc_dims(CAML_BA_UINT8 | CAML_BA_C_LAYOUT | CAML_BA_MANAGED, 1, memptr, size));
}
#endif
ocaml-extunix-0.3.2/src/mktemp.c 0000664 0000000 0000000 00000002774 14045766433 0016567 0 ustar 00root root 0000000 0000000 #define EXTUNIX_WANT_MKDTEMP
#define EXTUNIX_WANT_MKSTEMPS
#define EXTUNIX_WANT_MKOSTEMPS
#include "config.h"
#if defined(EXTUNIX_HAVE_MKDTEMP)
CAMLprim value caml_extunix_mkdtemp(value v_path)
{
CAMLparam1(v_path);
char* path = strdup(String_val(v_path));
char *ret;
caml_enter_blocking_section();
ret = mkdtemp(path);
caml_leave_blocking_section();
if (NULL == ret)
{
free(path);
uerror("mkdtemp", v_path);
}
v_path = caml_copy_string(ret);
free(path);
CAMLreturn(v_path);
}
#endif
#if defined(EXTUNIX_HAVE_MKSTEMPS)
CAMLprim value caml_extunix_internal_mkstemps(value v_template, value v_suffixlen)
{
CAMLparam2(v_template, v_suffixlen);
unsigned char *template = Bytes_val(v_template);
int suffixlen = Int_val(v_suffixlen);
int ret;
ret = mkstemps(template, suffixlen);
if (ret == -1)
{
uerror("mkstemps", v_template);
}
CAMLreturn(Val_int(ret));
}
#endif
#if defined(EXTUNIX_HAVE_MKOSTEMPS)
/* FIXME: also in atfile.c, move to common file */
#include
#ifndef O_CLOEXEC
# define O_CLOEXEC 0
#endif
CAMLprim value caml_extunix_internal_mkostemps(value v_template, value v_suffixlen, value v_flags)
{
CAMLparam3(v_template, v_suffixlen, v_flags);
unsigned char *template = Bytes_val(v_template);
int flags = extunix_open_flags(v_flags) | O_CLOEXEC;
int suffixlen = Int_val(v_suffixlen);
int ret;
ret = mkostemps(template, suffixlen, flags);
if (ret == -1)
{
uerror("mkostemps", v_template);
}
CAMLreturn(Val_int(ret));
}
#endif
ocaml-extunix-0.3.2/src/mman.c 0000664 0000000 0000000 00000001336 14045766433 0016213 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_MLOCKALL
#include "config.h"
#if defined(EXTUNIX_HAVE_MLOCKALL)
static int mlockall_flags[] = { MCL_CURRENT, MCL_FUTURE };
CAMLprim value caml_extunix_mlockall(value v_flags)
{
CAMLparam1(v_flags);
int flags = caml_convert_flag_list(v_flags, mlockall_flags);
int ret = 0;
caml_enter_blocking_section();
ret = mlockall(flags);
caml_leave_blocking_section();
if (ret != 0) uerror("mlockall", Nothing);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_munlockall(value v_unit)
{
CAMLparam1(v_unit);
int ret = 0;
caml_enter_blocking_section();
ret = munlockall();
caml_leave_blocking_section();
if (ret != 0) uerror("munlockall", Nothing);
CAMLreturn(Val_unit);
}
#endif
ocaml-extunix-0.3.2/src/mount.c 0000664 0000000 0000000 00000003371 14045766433 0016426 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_MOUNT
#include "config.h"
#if defined(EXTUNIX_HAVE_MOUNT)
static int mountflags_table[] = {
MS_RDONLY, MS_NOSUID, MS_NODEV, MS_NOEXEC, MS_SYNCHRONOUS, MS_REMOUNT,
MS_MANDLOCK, MS_DIRSYNC, MS_NOATIME, MS_NODIRATIME, MS_BIND, MS_MOVE,
MS_REC, MS_SILENT, MS_POSIXACL, MS_UNBINDABLE, MS_PRIVATE, MS_SLAVE,
MS_SHARED, MS_RELATIME, MS_KERNMOUNT, MS_I_VERSION, MS_STRICTATIME,
MS_NOUSER
};
CAMLprim value caml_extunix_mount(value v_source, value v_target,
value v_fstype, value v_mountflags,
value v_data)
{
CAMLparam5(v_source, v_target, v_fstype, v_mountflags, v_data);
int ret;
char* p_source = strdup(String_val(v_source));
char* p_target = strdup(String_val(v_target));
char* p_fstype = strdup(String_val(v_fstype));
char* p_data = strdup(String_val(v_data));
int p_mountflags = caml_convert_flag_list(v_mountflags, mountflags_table);
caml_enter_blocking_section();
ret = mount(p_source, p_target, p_fstype, p_mountflags, p_data);
caml_leave_blocking_section();
free(p_source);
free(p_target);
free(p_fstype);
free(p_data);
if (ret != 0) uerror("mount", v_target);
CAMLreturn(Val_unit);
}
static int umountflags_table[] = {
MNT_FORCE, MNT_DETACH, MNT_EXPIRE, UMOUNT_NOFOLLOW,
};
CAMLprim value caml_extunix_umount2(value v_target,value v_umountflags)
{
CAMLparam2(v_target, v_umountflags);
int ret;
char* p_target = strdup(String_val(v_target));
int p_umountflags = caml_convert_flag_list(v_umountflags, umountflags_table);
caml_enter_blocking_section();
ret = umount2(p_target, p_umountflags);
caml_leave_blocking_section();
free(p_target);
if (ret != 0) uerror("umount", v_target);
CAMLreturn(Val_unit);
}
#endif
ocaml-extunix-0.3.2/src/poll.c 0000664 0000000 0000000 00000003151 14045766433 0016226 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_POLL
#include "config.h"
#if defined(EXTUNIX_HAVE_POLL)
CAMLprim value caml_extunix_poll_constants(value v_unit)
{
value v = caml_alloc_tuple(7);
UNUSED(v_unit);
Field(v,0) = Val_int(POLLIN);
Field(v,1) = Val_int(POLLPRI);
Field(v,2) = Val_int(POLLOUT);
Field(v,3) = Val_int(POLLERR);
Field(v,4) = Val_int(POLLHUP);
Field(v,5) = Val_int(POLLNVAL);
Field(v,6) = Val_int(POLLRDHUP);
return v;
}
CAMLprim value caml_extunix_poll(value v_fds, value v_n, value v_ms)
{
CAMLparam3(v_fds, v_n, v_ms);
CAMLlocal3(v_l,v_tuple,v_cons);
struct pollfd* fd = NULL;
size_t n = Int_val(v_n);
size_t i = 0;
int result;
int timeout = Double_val(v_ms) * 1000.f;
if (Wosize_val(v_fds) < n)
caml_invalid_argument("poll");
if (0 == n)
CAMLreturn(Val_emptylist);
fd = malloc(n * sizeof(struct pollfd));
if (NULL == fd)
uerror("malloc",Nothing);
for (i = 0; i < n; i++)
{
fd[i].fd = Int_val(Field(Field(v_fds,i),0));
fd[i].events = Int_val(Field(Field(v_fds,i),1));
fd[i].revents = 0;
}
caml_enter_blocking_section();
result = poll(fd, n, timeout);
caml_leave_blocking_section();
if (result < 0)
{
free(fd);
uerror("poll",Nothing);
}
v_l = Val_emptylist;
for (i = 0; i < n; i++)
{
if (fd[i].revents != 0)
{
v_tuple = caml_alloc_tuple(2);
Store_field(v_tuple,0,Val_int(fd[i].fd));
Store_field(v_tuple,1,Val_int(fd[i].revents));
v_cons = caml_alloc_tuple(2);
Store_field(v_cons,0,v_tuple);
Store_field(v_cons,1,v_l);
v_l = v_cons;
}
}
free(fd);
CAMLreturn(v_l);
}
#endif
ocaml-extunix-0.3.2/src/pread_pwrite_ba.c 0000664 0000000 0000000 00000017065 14045766433 0020420 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_PREAD
#define EXTUNIX_WANT_PWRITE
#include "config.h"
enum mode_bits {
BIT_ONCE = 1 << 0,
BIT_NOERROR = 1 << 1,
BIT_NOINTR = 1 << 2
};
#if defined(EXTUNIX_HAVE_PREAD)
/* Copyright © 2012 Goswin von Brederlow */
CAMLprim value caml_extunixba_pread_common(value v_fd, off_t off, value v_buf, int mode) {
CAMLparam2(v_fd, v_buf);
ssize_t ret;
size_t fd = Int_val(v_fd);
size_t len = caml_ba_byte_size(Caml_ba_array_val(v_buf));
size_t processed = 0;
char *buf = (char*)Caml_ba_data_val(v_buf);
while(len > 0) {
caml_enter_blocking_section();
ret = pread(fd, buf, len, off);
caml_leave_blocking_section();
if (ret == 0) break;
if (ret == -1) {
if (errno == EINTR && (mode & BIT_NOINTR)) continue;
if (processed > 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
if (mode & BIT_NOERROR) break;
}
uerror("pread", Nothing);
}
processed += ret;
buf += ret;
off += ret;
len -= ret;
if (mode & BIT_ONCE) break;
}
CAMLreturn(Val_long(processed));
}
value caml_extunixba_all_pread(value v_fd, value v_off, value v_buf)
{
off_t off = Long_val(v_off);
return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_NOINTR);
}
value caml_extunixba_single_pread(value v_fd, value v_off, value v_buf)
{
off_t off = Long_val(v_off);
return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_ONCE);
}
value caml_extunixba_pread(value v_fd, value v_off, value v_buf)
{
off_t off = Long_val(v_off);
return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_NOINTR | BIT_NOERROR);
}
value caml_extunixba_intr_pread(value v_fd, value v_off, value v_buf)
{
off_t off = Long_val(v_off);
return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_NOERROR);
}
value caml_extunixba_all_pread64(value v_fd, value v_off, value v_buf)
{
off_t off = Int64_val(v_off);
return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_NOINTR);
}
value caml_extunixba_single_pread64(value v_fd, value v_off, value v_buf)
{
off_t off = Int64_val(v_off);
return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_ONCE);
}
value caml_extunixba_pread64(value v_fd, value v_off, value v_buf)
{
off_t off = Int64_val(v_off);
return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_NOINTR | BIT_NOERROR);
}
value caml_extunixba_intr_pread64(value v_fd, value v_off, value v_buf)
{
off_t off = Int64_val(v_off);
return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_NOERROR);
}
#endif
#if defined(EXTUNIX_HAVE_PWRITE)
/* Copyright © 2012 Goswin von Brederlow */
CAMLprim value caml_extunixba_pwrite_common(value v_fd, off_t off, value v_buf, int mode) {
CAMLparam2(v_fd, v_buf);
ssize_t ret;
size_t fd = Int_val(v_fd);
size_t len = caml_ba_byte_size(Caml_ba_array_val(v_buf));
size_t processed = 0;
char *buf = (char*)Caml_ba_data_val(v_buf);
while(len > 0) {
caml_enter_blocking_section();
ret = pwrite(fd, buf, len, off);
caml_leave_blocking_section();
if (ret == 0) break;
if (ret == -1) {
if (errno == EINTR && (mode & BIT_NOINTR)) continue;
if (processed > 0){
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
if (mode & BIT_NOERROR) break;
}
uerror("pwrite", Nothing);
}
processed += ret;
buf += ret;
off += ret;
len -= ret;
if (mode & BIT_ONCE) break;
}
CAMLreturn(Val_long(processed));
}
value caml_extunixba_all_pwrite(value v_fd, value v_off, value v_buf)
{
off_t off = Long_val(v_off);
return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_NOINTR);
}
value caml_extunixba_single_pwrite(value v_fd, value v_off, value v_buf)
{
off_t off = Long_val(v_off);
return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_ONCE);
}
value caml_extunixba_pwrite(value v_fd, value v_off, value v_buf)
{
off_t off = Long_val(v_off);
return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_NOINTR | BIT_NOERROR);
}
value caml_extunixba_intr_pwrite(value v_fd, value v_off, value v_buf)
{
off_t off = Long_val(v_off);
return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_NOERROR);
}
value caml_extunixba_all_pwrite64(value v_fd, value v_off, value v_buf)
{
off_t off = Int64_val(v_off);
return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_NOINTR);
}
value caml_extunixba_single_pwrite64(value v_fd, value v_off, value v_buf)
{
off_t off = Int64_val(v_off);
return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_ONCE);
}
value caml_extunixba_pwrite64(value v_fd, value v_off, value v_buf)
{
off_t off = Int64_val(v_off);
return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_NOINTR | BIT_NOERROR);
}
value caml_extunixba_intr_pwrite64(value v_fd, value v_off, value v_buf)
{
off_t off = Int64_val(v_off);
return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_NOERROR);
}
#endif
#if defined(EXTUNIX_HAVE_READ)
/* Copyright © 2012 Goswin von Brederlow */
CAMLprim value caml_extunixba_read_common(value v_fd, value v_buf, int mode) {
CAMLparam2(v_fd, v_buf);
ssize_t ret;
size_t fd = Int_val(v_fd);
size_t len = caml_ba_byte_size(Caml_ba_array_val(v_buf));
size_t processed = 0;
char *buf = (char*)Caml_ba_data_val(v_buf);
while(len > 0) {
caml_enter_blocking_section();
ret = read(fd, buf, len);
caml_leave_blocking_section();
if (ret == 0) break;
if (ret == -1) {
if (errno == EINTR && (mode & BIT_NOINTR)) continue;
if (processed > 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
if (mode & BIT_NOERROR) break;
}
uerror("read", Nothing);
}
processed += ret;
buf += ret;
len -= ret;
if (mode & BIT_ONCE) break;
}
CAMLreturn(Val_long(processed));
}
value caml_extunixba_all_read(value v_fd, value v_buf)
{
return caml_extunixba_read_common(v_fd, v_buf, BIT_NOINTR);
}
value caml_extunixba_single_read(value v_fd, value v_buf)
{
return caml_extunixba_read_common(v_fd, v_buf, BIT_ONCE);
}
value caml_extunixba_read(value v_fd, value v_buf)
{
return caml_extunixba_read_common(v_fd, v_buf, BIT_NOINTR | BIT_NOERROR);
}
value caml_extunixba_intr_read(value v_fd, value v_buf)
{
return caml_extunixba_read_common(v_fd, v_buf, BIT_NOERROR);
}
#endif
#if defined(EXTUNIX_HAVE_WRITE)
/* Copyright © 2012 Goswin von Brederlow */
CAMLprim value caml_extunixba_write_common(value v_fd, value v_buf, int mode) {
CAMLparam2(v_fd, v_buf);
ssize_t ret;
size_t fd = Int_val(v_fd);
size_t len = caml_ba_byte_size(Caml_ba_array_val(v_buf));
size_t processed = 0;
char *buf = (char*)Caml_ba_data_val(v_buf);
while(len > 0) {
caml_enter_blocking_section();
ret = write(fd, buf, len);
caml_leave_blocking_section();
if (ret == 0) break;
if (ret == -1) {
if (errno == EINTR && (mode & BIT_NOINTR)) continue;
if (processed > 0){
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
if (mode & BIT_NOERROR) break;
}
uerror("write", Nothing);
}
processed += ret;
buf += ret;
len -= ret;
if (mode & BIT_ONCE) break;
}
CAMLreturn(Val_long(processed));
}
value caml_extunixba_all_write(value v_fd, value v_buf)
{
return caml_extunixba_write_common(v_fd, v_buf, BIT_NOINTR);
}
value caml_extunixba_single_write(value v_fd, value v_buf)
{
return caml_extunixba_write_common(v_fd, v_buf, BIT_ONCE);
}
value caml_extunixba_write(value v_fd, value v_buf)
{
return caml_extunixba_write_common(v_fd, v_buf, BIT_NOINTR | BIT_NOERROR);
}
value caml_extunixba_intr_write(value v_fd, value v_buf)
{
return caml_extunixba_write_common(v_fd, v_buf, BIT_NOERROR);
}
#endif
ocaml-extunix-0.3.2/src/ptrace.c 0000664 0000000 0000000 00000002360 14045766433 0016537 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_PTRACE
#include "config.h"
#if defined(EXTUNIX_HAVE_PTRACE)
CAMLprim value caml_extunix_ptrace_traceme(value v_unit)
{
long r = ptrace(PTRACE_TRACEME, 0, 0, 0);
UNUSED(v_unit);
if (r != 0)
uerror("ptrace_traceme", Nothing);
return Val_unit;
}
CAMLprim value caml_extunix_ptrace(value v_pid, value v_req)
{
CAMLparam2(v_pid, v_req);
long r = 0;
switch (Int_val(v_req))
{
case 0 : r = ptrace(PTRACE_ATTACH, Int_val(v_pid), 0, 0); break;
case 1 : r = ptrace(PTRACE_DETACH, Int_val(v_pid), 0, 0); break;
default : caml_invalid_argument("ptrace");
}
if (r != 0)
uerror("ptrace", Nothing);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_ptrace_peekdata(value v_pid, value v_addr)
{
CAMLparam2(v_pid, v_addr);
long r = ptrace(PTRACE_PEEKDATA,Int_val(v_pid), Nativeint_val(v_addr), 0);
if (-1 == r && 0 != errno)
uerror("ptrace_peekdata",Nothing);
CAMLreturn(caml_copy_nativeint(r));
}
CAMLprim value caml_extunix_ptrace_peektext(value v_pid, value v_addr)
{
CAMLparam2(v_pid, v_addr);
long r = ptrace(PTRACE_PEEKTEXT,Int_val(v_pid), Nativeint_val(v_addr), 0);
if (-1 == r && 0 != errno)
uerror("ptrace_peektext",Nothing);
CAMLreturn(caml_copy_nativeint(r));
}
#endif
ocaml-extunix-0.3.2/src/pts.c 0000664 0000000 0000000 00000001552 14045766433 0016071 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_PTS
#include "config.h"
#if defined(EXTUNIX_HAVE_PTS)
CAMLprim value caml_extunix_posix_openpt(value flags)
{
CAMLparam1(flags);
int ret, cv_flags;
cv_flags = extunix_open_flags(flags);
ret = posix_openpt(cv_flags);
if(ret == -1)
uerror("posix_openpt", Nothing);
CAMLreturn(Val_int(ret));
}
CAMLprim value caml_extunix_grantpt(value fd)
{
CAMLparam1(fd);
if(grantpt(Int_val(fd)) == -1)
uerror("grantpt", Nothing);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_unlockpt(value fd)
{
CAMLparam1(fd);
if(unlockpt(Int_val(fd)) == -1)
uerror("unlockpt", Nothing);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_ptsname(value fd)
{
CAMLparam1(fd);
CAMLlocal1(ret);
char *name = ptsname(Int_val(fd));
if(name == 0)
uerror("ptsname", Nothing);
ret = caml_copy_string(name);
CAMLreturn(ret);
}
#endif /* HAVE_PTS */
ocaml-extunix-0.3.2/src/read_cred.c 0000664 0000000 0000000 00000001250 14045766433 0017166 0 ustar 00root root 0000000 0000000 #define EXTUNIX_WANT_READ_CREDENTIALS
#include "config.h"
#if defined(EXTUNIX_HAVE_READ_CREDENTIALS)
/* Copyright © 2012 Andre Nathan */
CAMLprim value caml_extunix_read_credentials(value fd_val)
{
CAMLparam1(fd_val);
CAMLlocal1(res);
struct ucred crd;
socklen_t crdlen = sizeof crd;
int fd = Int_val(fd_val);
if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &crd, &crdlen) == -1)
uerror("read_credentials", Nothing);
res = caml_alloc_tuple(3);
Store_field(res, 0, Val_int(crd.pid));
Store_field(res, 1, Val_int(crd.uid));
Store_field(res, 2, Val_int(crd.gid));
CAMLreturn (res);
}
#endif /* EXTUNIX_HAVE_READ_CREDENTIALS */
ocaml-extunix-0.3.2/src/resource.c 0000664 0000000 0000000 00000010775 14045766433 0017121 0 ustar 00root root 0000000 0000000 /******************************************************************************/
/* ocaml-posix-resource: POSIX resource operations */
/* */
/* Copyright (C) 2009 Sylvain Le Gall */
/* */
/* This library is free software; you can redistribute it and/or modify it */
/* under the terms of the GNU Lesser General Public License as published by */
/* the Free Software Foundation; either version 2.1 of the License, or (at */
/* your option) any later version; with the OCaml static compilation */
/* exception. */
/* */
/* This library is distributed in the hope that it will be useful, but */
/* WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser */
/* General Public License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License */
/* along with this library; if not, write to the Free Software Foundation, */
/* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/******************************************************************************/
/*
* POSIX resource for OCaml
*
* Author: Sylvain Le Gall
*
*/
#define EXTUNIX_WANT_RESOURCE
#include "config.h"
#if defined(EXTUNIX_HAVE_RESOURCE)
static void decode_which_prio(value vwprio, int *pwhich, id_t *pwho)
{
CAMLparam1(vwprio);
assert(Is_block(vwprio) && Wosize_val(vwprio) == 1);
*pwho=Long_val(Field(vwprio, 0));
switch(Tag_val(vwprio))
{
case 0:
*pwhich = PRIO_PROCESS;
break;
case 1:
*pwhich = PRIO_PGRP;
break;
case 2:
*pwhich = PRIO_USER;
break;
default:
caml_invalid_argument("decode_which_prio");
}
CAMLreturn0;
}
CAMLprim value caml_extunix_getpriority(value vwprio)
{
CAMLparam1(vwprio);
int which;
id_t who;
int res = -1;
decode_which_prio(vwprio, &which, &who);
errno = 0;
res = getpriority(which, who);
if (res == -1 && errno != 0)
{
uerror("getpriority", Nothing);
}
CAMLreturn(Val_int(res));
}
CAMLprim value caml_extunix_setpriority(value vwprio, value vprio)
{
CAMLparam2(vwprio, vprio);
int which;
id_t who;
decode_which_prio(vwprio, &which, &who);
if (setpriority(which, who, Int_val(vprio)) != 0)
{
uerror("setpriority", Nothing);
}
CAMLreturn(Val_unit);
}
#define RESOURCE_LEN 7
static int resource_map[RESOURCE_LEN] =
{
RLIMIT_CORE,
RLIMIT_CPU,
RLIMIT_DATA,
RLIMIT_FSIZE,
RLIMIT_NOFILE,
RLIMIT_STACK,
RLIMIT_AS
};
static int decode_resource(value vrsrc)
{
CAMLparam1(vrsrc);
assert(Int_val(vrsrc) < RESOURCE_LEN && Int_val(vrsrc) >= 0);
CAMLreturnT(int, resource_map[Int_val(vrsrc)]);
}
static value encode_limit(rlim_t v)
{
CAMLparam0();
CAMLlocal1(vres);
if (v == RLIM_INFINITY)
{
vres = Val_int(0);
}
else
{
vres = caml_alloc(1, 0);
Store_field(vres, 0, caml_copy_int64(v));
}
CAMLreturn(vres);
}
static rlim_t decode_limit(value vchglimit)
{
CAMLparam1(vchglimit);
rlim_t res = RLIM_INFINITY;
if (Is_block(vchglimit))
{
assert(Tag_val(vchglimit) == 0);
res = Int64_val(Field(vchglimit, 0));
}
CAMLreturnT(rlim_t, res);
}
CAMLprim value caml_extunix_getrlimit(value vrsrc)
{
CAMLparam1(vrsrc);
CAMLlocal1(vres);
struct rlimit rlmt;
if (getrlimit(decode_resource(vrsrc), &rlmt) != 0)
{
uerror("getrlimit", Nothing);
}
vres = caml_alloc(2, 0);
Store_field(vres, 0, encode_limit(rlmt.rlim_cur));
Store_field(vres, 1, encode_limit(rlmt.rlim_max));
CAMLreturn(vres);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
CAMLprim value caml_extunix_setrlimit(value vrsrc, value vslimit, value vhlimit)
{
CAMLparam3(vrsrc, vslimit, vhlimit);
struct rlimit rlmt = { 0 };
rlmt.rlim_cur = decode_limit(vslimit);
rlmt.rlim_max = decode_limit(vhlimit);
if (setrlimit(decode_resource(vrsrc), &rlmt) != 0)
{
uerror("setrlimit", Nothing);
}
CAMLreturn(Val_unit);
}
#pragma GCC diagnostic pop
#endif /* EXTUNIX_HAVE_RESOURCE */
ocaml-extunix-0.3.2/src/sendmsg.c 0000664 0000000 0000000 00000007151 14045766433 0016724 0 ustar 00root root 0000000 0000000 /* Copyright © 2012 Andre Nathan */
/*
* These functions are adapted from Stevens, Fenner and Rudoff, UNIX Network
* Programming, Volume 1, Third Edition. We use CMSG_LEN instead of CMSG_SPACE
* for the msg_controllen field of struct msghdr to avoid breaking LP64
* systems (cf. Postfix source code).
*/
#define EXTUNIX_WANT_SENDMSG
#include "config.h"
#if defined(EXTUNIX_HAVE_SENDMSG)
CAMLprim value caml_extunix_sendmsg(value fd_val, value sendfd_val, value data_val)
{
CAMLparam3(fd_val, sendfd_val, data_val);
CAMLlocal1(data);
size_t datalen;
struct msghdr msg;
struct iovec iov[1];
int fd = Int_val(fd_val);
ssize_t ret;
char *buf;
#if defined(CMSG_SPACE)
union {
struct cmsghdr cmsg; /* for alignment */
char control[CMSG_SPACE(sizeof(int))]; /* sizeof sendfd */
} control_un;
#endif
memset(&msg, 0, sizeof msg);
if (sendfd_val != Val_none)
{
int sendfd = Int_val(Some_val(sendfd_val));
#if defined(CMSG_SPACE)
struct cmsghdr *cmsgp;
msg.msg_control = control_un.control;
msg.msg_controllen = CMSG_LEN(sizeof sendfd);
cmsgp = CMSG_FIRSTHDR(&msg);
cmsgp->cmsg_len = CMSG_LEN(sizeof sendfd);
cmsgp->cmsg_level = SOL_SOCKET;
cmsgp->cmsg_type = SCM_RIGHTS;
*(int *)CMSG_DATA(cmsgp) = sendfd;
#else
msg.msg_accrights = (caddr_t)&sendfd;
msg.msg_accrightslen = sizeof sendfd;
#endif
}
datalen = caml_string_length(data_val);
buf = malloc(datalen);
if (NULL == buf)
uerror("sendmsg", Nothing);
memcpy(buf, String_val(data_val), datalen);
iov[0].iov_base = buf;
iov[0].iov_len = datalen;
msg.msg_iov = iov;
msg.msg_iovlen = 1;
caml_enter_blocking_section();
ret = sendmsg(fd, &msg, 0);
caml_leave_blocking_section();
free(buf);
if (ret == -1)
uerror("sendmsg", Nothing);
CAMLreturn (Val_unit);
}
CAMLprim value caml_extunix_recvmsg(value fd_val)
{
CAMLparam1(fd_val);
CAMLlocal2(data, res);
struct msghdr msg;
int fd = Int_val(fd_val);
int recvfd;
ssize_t len;
struct iovec iov[1];
char buf[4096];
#if defined(CMSG_SPACE)
union {
struct cmsghdr cmsg; /* just for alignment */
char control[CMSG_SPACE(sizeof recvfd)];
} control_un;
struct cmsghdr *cmsgp;
memset(&msg, 0, sizeof msg);
msg.msg_control = control_un.control;
msg.msg_controllen = CMSG_LEN(sizeof recvfd);
#else
msg.msg_accrights = (caddr_t)&recvfd;
msg.msg_accrightslen = sizeof recvfd;
#endif
iov[0].iov_base = buf;
iov[0].iov_len = sizeof buf;
msg.msg_iov = iov;
msg.msg_iovlen = 1;
caml_enter_blocking_section();
len = recvmsg(fd, &msg, 0);
caml_leave_blocking_section();
if (len == -1)
uerror("recvmsg", Nothing);
res = caml_alloc(2, 0);
#if defined(CMSG_SPACE)
cmsgp = CMSG_FIRSTHDR(&msg);
if (cmsgp == NULL) {
Store_field(res, 0, Val_none);
} else {
CAMLlocal1(some_fd);
if (cmsgp->cmsg_len != CMSG_LEN(sizeof recvfd))
unix_error(EINVAL, "recvmsg", caml_copy_string("wrong descriptor size"));
if (cmsgp->cmsg_level != SOL_SOCKET || cmsgp->cmsg_type != SCM_RIGHTS)
unix_error(EINVAL, "recvmsg", caml_copy_string("invalid protocol"));
some_fd = caml_alloc(1, 0);
Store_field(some_fd, 0, Val_int(*(int *)CMSG_DATA(cmsgp)));
Store_field(res, 0, some_fd);
}
#else
if (msg.msg_accrightslen != sizeof recvfd) {
Store_field(res, 0, Val_none);
} else {
CAMLlocal1(some_fd);
some_fd = caml_alloc(1, 0);
Store_field(some_fd, 0, Val_int(recvfd));
Store_field(res, 0, some_fd);
}
#endif
data = caml_alloc_initialized_string(len, buf);
Store_field(res, 1, data);
CAMLreturn (res);
}
#endif /* EXTUNIX_HAVE_SENDMSG */
ocaml-extunix-0.3.2/src/signalfd.c 0000664 0000000 0000000 00000007647 14045766433 0017065 0 ustar 00root root 0000000 0000000 /******************************************************************************/
/* signalfd stubs */
/* */
/* NO COPYRIGHT -- RELEASED INTO THE PUBLIC DOMAIN */
/* */
/* Author: Kaustuv Chaudhuri */
/******************************************************************************/
#define EXTUNIX_WANT_SIGNALFD
#include "config.h"
#if defined(EXTUNIX_HAVE_SIGNALFD)
extern int caml_convert_signal_number(int signo);
extern int caml_rev_convert_signal_number(int signo);
CAMLprim
value caml_extunix_signalfd(value vfd, value vsigs, value vflags, value v_unit)
{
CAMLparam4(vfd, vsigs, vflags, v_unit);
int fd = ((Val_none == vfd) ? -1 : Int_val(Some_val(vfd)));
int flags = 0;
int ret = 0;
sigset_t ss;
sigemptyset (&ss);
while (!Is_long (vsigs)) {
int sig = caml_convert_signal_number (Int_val (Field (vsigs, 0)));
if (sigaddset (&ss, sig) < 0) uerror ("sigaddset", Nothing);
vsigs = Field (vsigs, 1);
}
while (!Is_long (vflags)) {
int f = Int_val (Field (vflags, 0));
if (SFD_NONBLOCK == f) flags |= SFD_NONBLOCK;
if (SFD_CLOEXEC == f) flags |= SFD_CLOEXEC;
vflags = Field (vflags, 1);
}
ret = signalfd (fd, &ss, flags);
if (ret < 0) uerror ("signalfd", Nothing);
CAMLreturn (Val_int (ret));
}
/* [HACK] improve these -- bytestream representation is OK */
static struct custom_operations ssi_ops = {
"signalfd.signalfd_siginfo",
custom_finalize_default,
custom_compare_default, custom_hash_default,
custom_serialize_default, custom_deserialize_default,
#if defined(custom_compare_ext_default)
custom_compare_ext_default,
#endif
#if defined(custom_fixed_length_default)
custom_fixed_length_default,
#endif
};
#define SSI_SIZE sizeof(struct signalfd_siginfo)
CAMLprim
value caml_extunix_signalfd_read(value vfd)
{
CAMLparam1(vfd);
CAMLlocal1(vret);
struct signalfd_siginfo ssi;
ssize_t nread = 0;
caml_enter_blocking_section();
nread = read(Int_val(vfd), &ssi, SSI_SIZE);
caml_leave_blocking_section();
if (nread != SSI_SIZE)
unix_error(EINVAL,"signalfd_read",Nothing);
vret = caml_alloc_custom(&ssi_ops, SSI_SIZE, 0, 1);
memcpy(Data_custom_val(vret),&ssi,SSI_SIZE);
CAMLreturn(vret);
}
CAMLprim
value caml_extunix_ssi_signo_sys(value vssi)
{
CAMLparam1(vssi);
struct signalfd_siginfo *ssi = (void *)(Data_custom_val(vssi));
CAMLreturn(Val_int(caml_rev_convert_signal_number(ssi->ssi_signo)));
}
#define SSI_GET_FIELD(field,coerce) \
CAMLprim \
value caml_extunix_ssi_##field(value vssi) \
{ \
CAMLparam1(vssi); \
struct signalfd_siginfo *ssi = (void *)Data_custom_val(vssi); \
CAMLreturn(coerce(ssi->ssi_##field)); \
} \
SSI_GET_FIELD( signo , caml_copy_int32 )
SSI_GET_FIELD( errno , caml_copy_int32 )
SSI_GET_FIELD( code , caml_copy_int32 )
SSI_GET_FIELD( pid , caml_copy_int32 )
SSI_GET_FIELD( uid , caml_copy_int32 )
SSI_GET_FIELD( fd , Val_int )
SSI_GET_FIELD( tid , caml_copy_int32 )
SSI_GET_FIELD( band , caml_copy_int32 )
SSI_GET_FIELD( overrun , caml_copy_int32 )
SSI_GET_FIELD( trapno , caml_copy_int32 )
SSI_GET_FIELD( status , caml_copy_int32 )
SSI_GET_FIELD( int , caml_copy_int32 )
SSI_GET_FIELD( ptr , caml_copy_int64 )
SSI_GET_FIELD( utime , caml_copy_int64 )
SSI_GET_FIELD( stime , caml_copy_int64 )
SSI_GET_FIELD( addr , caml_copy_int64 )
#endif /* EXTUNIX_HAVE_SIGNALFD */
ocaml-extunix-0.3.2/src/sockopt.c 0000664 0000000 0000000 00000006170 14045766433 0016746 0 ustar 00root root 0000000 0000000 #define EXTUNIX_WANT_SOCKOPT
#define EXTUNIX_WANT_TCP_KEEPIDLE
#define EXTUNIX_WANT_TCP_KEEPCNT
#define EXTUNIX_WANT_TCP_KEEPINTVL
#include "config.h"
#if defined(EXTUNIX_HAVE_SOCKOPT)
#ifndef TCP_KEEPCNT
#define TCP_KEEPCNT (-1)
#endif
#ifndef TCP_KEEPIDLE
#define TCP_KEEPIDLE (-1)
#endif
#ifndef TCP_KEEPINTVL
#define TCP_KEEPINTVL (-1)
#endif
#ifndef SO_REUSEPORT
#define SO_REUSEPORT (-1)
#endif
#ifndef SO_ATTACH_BPF
#define SO_ATTACH_BPF (-1)
#endif
#ifndef SO_ATTACH_REUSEPORT_EBPF
#define SO_ATTACH_REUSEPORT_EBPF (-1)
#endif
#ifndef SO_DETACH_FILTER
#define SO_DETACH_FILTER (-1)
#endif
#ifndef SO_DETACH_BPF
#define SO_DETACH_BPF (-1)
#endif
#ifndef SO_LOCK_FILTER
#define SO_LOCK_FILTER (-1)
#endif
struct option {
int opt;
int level;
};
static struct option tcp_options[] = {
{ TCP_KEEPCNT, IPPROTO_TCP },
{ TCP_KEEPIDLE, IPPROTO_TCP },
{ TCP_KEEPINTVL, IPPROTO_TCP },
{ SO_REUSEPORT, SOL_SOCKET },
{ SO_ATTACH_BPF, SOL_SOCKET },
{ SO_ATTACH_REUSEPORT_EBPF, SOL_SOCKET },
{ SO_DETACH_FILTER, SOL_SOCKET },
{ SO_DETACH_BPF, SOL_SOCKET },
{ SO_LOCK_FILTER, SOL_SOCKET },
};
CAMLprim value caml_extunix_have_sockopt(value k)
{
if (Int_val(k) < 0 || (unsigned int)Int_val(k) >= sizeof(tcp_options) / sizeof(tcp_options[0]))
{
caml_invalid_argument("have_sockopt");
}
return Val_bool(tcp_options[Int_val(k)].opt != -1);
}
CAMLprim value caml_extunix_setsockopt_int(value fd, value k, value v)
{
int optval = Int_val(v);
socklen_t optlen = sizeof(optval);
#ifdef _WIN32
SOCKET s = INVALID_SOCKET;
if (KIND_SOCKET != Descr_kind_val(fd))
caml_invalid_argument("setsockopt_int");
s = Socket_val(fd);
#else
int s = Int_val(fd);
#endif
if (Int_val(k) < 0 || (unsigned int)Int_val(k) >= sizeof(tcp_options) / sizeof(tcp_options[0]))
{
caml_invalid_argument("setsockopt_int");
}
if (tcp_options[Int_val(k)].opt == -1)
{
caml_raise_not_found();
assert(0);
}
if (0 != setsockopt(s, tcp_options[Int_val(k)].level, tcp_options[Int_val(k)].opt, (void *)&optval, optlen))
{
#ifdef _WIN32
if (WSAGetLastError() == WSAENOPROTOOPT) {
#else
if (errno == ENOPROTOOPT) {
#endif
caml_raise_not_found();
assert(0);
}
uerror("setsockopt_int", Nothing);
}
return Val_unit;
}
CAMLprim value caml_extunix_getsockopt_int(value fd, value k)
{
int optval;
socklen_t optlen = sizeof(optval);
#ifdef _WIN32
SOCKET s = INVALID_SOCKET;
if (KIND_SOCKET != Descr_kind_val(fd))
caml_invalid_argument("getsockopt_int");
s = Socket_val(fd);
#else
int s = Int_val(fd);
#endif
if (Int_val(k) < 0 || (unsigned int)Int_val(k) >= sizeof(tcp_options) / sizeof(tcp_options[0]))
{
caml_invalid_argument("getsockopt_int");
}
if (tcp_options[Int_val(k)].opt == -1)
{
caml_raise_not_found();
assert(0);
}
if (0 != getsockopt(s, tcp_options[Int_val(k)].level, tcp_options[Int_val(k)].opt, (void *)&optval, &optlen))
{
#ifdef _WIN32
if (WSAGetLastError() == WSAENOPROTOOPT) {
#else
if (errno == ENOPROTOOPT) {
#endif
caml_raise_not_found();
assert(0);
}
uerror("getsockopt_int", Nothing);
}
return Val_int(optval);
}
#endif
ocaml-extunix-0.3.2/src/splice.c 0000664 0000000 0000000 00000005716 14045766433 0016550 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_VMSPLICE
#define EXTUNIX_WANT_SPLICE
#define EXTUNIX_WANT_TEE
#include "config.h"
#if defined(EXTUNIX_HAVE_SPLICE) | defined(EXTUNIX_HAVE_TEE) | defined(EXTUNIX_HAVE_VMSPLICE)
static int splice_flags[] =
{
SPLICE_F_MOVE,
SPLICE_F_NONBLOCK,
SPLICE_F_MORE,
SPLICE_F_GIFT
};
#endif
#if defined(EXTUNIX_HAVE_SPLICE)
static loff_t* get_offset(value v_off)
{
return (Is_long(v_off) ? NULL : &(Field(v_off, 0)));
}
CAMLprim value caml_extunix_splice(value v_fd_in, value v_off_in, value v_fd_out, value v_off_out, value v_len, value v_flags)
{
CAMLparam5(v_fd_in, v_off_in, v_fd_out, v_off_out, v_len);
CAMLxparam1(v_flags);
unsigned int flags = caml_convert_flag_list(v_flags, splice_flags);
int fd_in = Int_val(v_fd_in);
int fd_out = Int_val(v_fd_out);
loff_t* off_in = get_offset(v_off_in);
loff_t* off_out = get_offset(v_off_out);
size_t len = Int_val(v_len);
ssize_t ret;
caml_enter_blocking_section();
ret = splice(fd_in, off_in, fd_out, off_out, len, flags);
caml_leave_blocking_section();
if (ret == -1)
uerror("splice", Nothing);
CAMLreturn(Val_long(ret));
}
CAMLprim value caml_extunix_splice_bytecode(value * argv, int argn)
{
(void)argn;
return caml_extunix_splice(argv[0], argv[1], argv[2],
argv[3], argv[4], argv[5]);
}
#endif
#if defined(EXTUNIX_HAVE_TEE)
CAMLprim value caml_extunix_tee(value v_fd_in, value v_fd_out, value v_len, value v_flags)
{
CAMLparam4(v_fd_in, v_fd_out, v_len, v_flags);
unsigned int flags = caml_convert_flag_list(v_flags, splice_flags);
int fd_in = Int_val(v_fd_in);
int fd_out = Int_val(v_fd_out);
size_t len = Int_val(v_len);
ssize_t ret;
caml_enter_blocking_section();
ret = tee(fd_in, fd_out, len, flags);
caml_leave_blocking_section();
if (ret == -1)
uerror("tee", Nothing);
CAMLreturn(Val_long(ret));
}
#endif
#if defined(EXTUNIX_HAVE_VMSPLICE)
CAMLprim value caml_extunixba_vmsplice(value v_fd_out, value v_iov, value v_flags)
{
CAMLparam3(v_fd_out, v_iov, v_flags);
unsigned int flags = caml_convert_flag_list(v_flags, splice_flags);
int fd_out = Int_val(v_fd_out);
int size = Wosize_val(v_iov);
struct iovec* iov = alloca(sizeof(struct iovec) * size);
ssize_t ret;
int i;
value tmp;
struct caml_ba_array* ba;
int offset, length;
for (i = 0; i < size; i++)
{
tmp = Field(v_iov,i);
/* field 0 is a 'a carray8 (bigarray of 8-bit elements)
field 1 is the offset in the bigarray
field 2 is the length */
ba = Caml_ba_array_val(Field(tmp,0));
offset = Int_val(Field(tmp,1));
length = Int_val(Field(tmp,2));
if(offset + length > ba->dim[0])
caml_invalid_argument("vmsplice");
iov[i].iov_base = (char *) ba->data + offset;
iov[i].iov_len = length;
}
caml_enter_blocking_section();
ret = vmsplice(fd_out, iov, size, flags);
caml_leave_blocking_section();
if (ret == -1)
uerror("vmsplice", Nothing);
CAMLreturn(Val_long(ret));
}
#endif
ocaml-extunix-0.3.2/src/statvfs.c 0000664 0000000 0000000 00000010172 14045766433 0016753 0 ustar 00root root 0000000 0000000 #define EXTUNIX_WANT_STATVFS
#include "config.h"
#if defined(EXTUNIX_HAVE_STATVFS) || defined(EXTUNIX_HAVE_FSTATVFS)
static int st_flags_table[] = {
#if defined(_WIN32)
FILE_READ_ONLY_VOLUME
#else
ST_RDONLY, ST_NOSUID, ST_NODEV, ST_NOEXEC, ST_SYNCHRONOUS,
ST_MANDLOCK, ST_WRITE, ST_APPEND, ST_IMMUTABLE, ST_NOATIME,
ST_NODIRATIME, ST_RELATIME
#endif
};
static value convert_st_flags(unsigned long int f_flag)
{
CAMLparam0();
CAMLlocal2(list, tmp);
int i;
list = Val_emptylist;
for (i = 0; i < sizeof(st_flags_table) / sizeof(st_flags_table[0]); i++)
{
if (f_flag & st_flags_table[i])
{
tmp = caml_alloc_small(2, Tag_cons);
Field(tmp, 0) = Val_int(i);
Field(tmp, 1) = list;
list = tmp;
}
}
CAMLreturn(list);
}
#endif
#if defined(EXTUNIX_HAVE_STATVFS) && defined(_WIN32)
#include
CAMLprim value caml_extunix_statvfs(value v_path)
{
CAMLparam1(v_path);
CAMLlocal1(v_s);
ULONG sectorsPerCluster = 0U, bytesPerSector = 0U, numberOfFreeClusters = 0U,
totalNumberOfClusters = 0U, bsize = 0U, serialNumber = 0U, fileSystemFlags = 0U;
ULONGLONG totalNumberOfFreeBytes = 0ULL;
char_os *path = caml_stat_strdup_to_os(String_val(v_path));
BOOL rc;
rc = GetDiskFreeSpaceW(path, §orsPerCluster, &bytesPerSector,
&numberOfFreeClusters, &totalNumberOfClusters)
&& GetDiskFreeSpaceExW(path, NULL, NULL,
(PULARGE_INTEGER) &totalNumberOfFreeBytes)
&& GetVolumeInformationW(path, NULL, 0, &serialNumber, NULL,
&fileSystemFlags, NULL, 0);
caml_stat_free(path);
if (!rc)
{
uerror("statvfs", v_path);
}
bsize = bytesPerSector * sectorsPerCluster;
v_s = caml_alloc(11, 0);
Store_field(v_s, 0, Val_int(bsize)); /* Filesystem block size */
/* don't export s->f_frsize */
Store_field(v_s, 1, caml_copy_int64(totalNumberOfClusters)); /* Size of fs in bsize units */
Store_field(v_s, 2, caml_copy_int64(totalNumberOfFreeBytes / (ULONGLONG) bsize)); /* Number of free blocks */
Store_field(v_s, 3, caml_copy_int64(numberOfFreeClusters)); /* Number of free blocks for
unprivileged users */
Store_field(v_s, 4, caml_copy_int64(LLONG_MAX)); /* Number of inodes */
Store_field(v_s, 5, caml_copy_int64(LLONG_MAX)); /* Number of free inodes */
Store_field(v_s, 6, caml_copy_int64(LLONG_MAX)); /* Number of free inodes for
unprivileged users */
Store_field(v_s, 7, caml_copy_int64((ULONGLONG) serialNumber)); /* Filesystem ID */
Store_field(v_s, 8, Val_int(fileSystemFlags)); /* Mount flags (raw) */
Store_field(v_s, 9, convert_st_flags(fileSystemFlags)); /* Mount flags (decoded) */
Store_field(v_s, 10, Val_int(MAX_PATH)); /* Maximum filename length */
CAMLreturn(v_s);
}
#elif (defined(EXTUNIX_HAVE_STATVFS) || defined(EXTUNIX_HAVE_FSTATVFS)) && !defined(_WIN32)
static value convert(struct statvfs* s)
{
CAMLparam0();
CAMLlocal1(v_s);
v_s = caml_alloc(11,0);
Store_field(v_s,0,Val_int(s->f_bsize));
/* don't export s->f_frsize */
Store_field(v_s,1,caml_copy_int64(s->f_blocks));
Store_field(v_s,2,caml_copy_int64(s->f_bfree));
Store_field(v_s,3,caml_copy_int64(s->f_bavail));
Store_field(v_s,4,caml_copy_int64(s->f_files));
Store_field(v_s,5,caml_copy_int64(s->f_ffree));
Store_field(v_s,6,caml_copy_int64(s->f_favail));
Store_field(v_s,7,caml_copy_int64(s->f_fsid));
Store_field(v_s,8,Val_int(s->f_flag));
Store_field(v_s,9,convert_st_flags(s->f_flag));
Store_field(v_s,10,Val_int(s->f_namemax));
CAMLreturn(v_s);
}
#if defined(EXTUNIX_HAVE_STATVFS)
CAMLprim value caml_extunix_statvfs(value v_path)
{
CAMLparam1(v_path);
struct statvfs s;
if (0 != statvfs(String_val(v_path), &s))
{
uerror("statvfs",v_path);
}
CAMLreturn(convert(&s));
}
#endif
#if defined(EXTUNIX_HAVE_STATVFS)
CAMLprim value caml_extunix_fstatvfs(value v_fd)
{
CAMLparam1(v_fd);
struct statvfs s;
if (0 != fstatvfs(Int_val(v_fd), &s))
{
uerror("fstatvfs",Nothing);
}
CAMLreturn(convert(&s));
}
#endif
#endif
ocaml-extunix-0.3.2/src/stdlib.c 0000664 0000000 0000000 00000003567 14045766433 0016554 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_REALPATH
#define EXTUNIX_WANT_SETENV
#define EXTUNIX_WANT_CLEARENV
#define EXTUNIX_WANT_MKDTEMP
#include "config.h"
#if defined(EXTUNIX_HAVE_REALPATH)
#ifdef __GLIBC__
CAMLprim value caml_extunix_realpath(value v_path)
{
CAMLparam1(v_path);
CAMLlocal1(v_s);
char* path = realpath(String_val(v_path),NULL);
if (NULL == path)
{
uerror("realpath",v_path);
}
v_s = caml_copy_string(path);
free(path);
CAMLreturn(v_s);
}
#else
/* janest-core-0.6.0/lib/unix_ext_stubs.c */
/* Seems like a sane approach to getting a reasonable bound for the
maximum path length */
#ifdef PATH_MAX
#define JANE_PATH_MAX ((PATH_MAX <= 0 || PATH_MAX > 65536) ? 65536 : PATH_MAX)
#else
#define JANE_PATH_MAX (65536)
#endif
CAMLprim value caml_extunix_realpath(value v_path)
{
CAMLparam1(v_path);
const char *path = String_val(v_path);
/* [realpath] is inherently broken without GNU-extension, and this
seems like a reasonable thing to do if we do not build against
GLIBC. */
char resolved_path[JANE_PATH_MAX];
if (realpath(path, resolved_path) == NULL) uerror("realpath", v_path);
return caml_copy_string(resolved_path);
}
#endif /* __GLIBC__ */
#endif
#if defined(EXTUNIX_HAVE_SETENV)
CAMLprim value caml_extunix_setenv(value v_name, value v_val, value v_overwrite)
{
CAMLparam3(v_name, v_val, v_overwrite);
if (0 != setenv(String_val(v_name), String_val(v_val), Bool_val(v_overwrite)))
{
uerror("setenv",v_name);
}
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_unsetenv(value v_name)
{
CAMLparam1(v_name);
if (0 != unsetenv(String_val(v_name)))
{
uerror("unsetenv",v_name);
}
CAMLreturn(Val_unit);
}
#endif
#if defined(EXTUNIX_HAVE_CLEARENV)
CAMLprim value caml_extunix_clearenv(value v_unit)
{
UNUSED(v_unit);
if (0 != clearenv())
{
uerror("clearenv", Nothing);
}
return Val_unit;
}
#endif
ocaml-extunix-0.3.2/src/sysconf.c 0000664 0000000 0000000 00000002324 14045766433 0016745 0 ustar 00root root 0000000 0000000 /*
* Binding to sysconf
*
* Copyright 2013
*
* License LGPL-2.1 with OCaml linking static exception
*
* author: Roman Vorobets
*
*/
#define EXTUNIX_WANT_SYSCONF
#include "config.h"
#if defined(EXTUNIX_HAVE_SYSCONF)
#ifndef _SC_PHYS_PAGES
#define _SC_PHYS_PAGES (-1)
#endif
#ifndef _SC_AVPHYS_PAGES
#define _SC_AVPHYS_PAGES (-1)
#endif
#ifndef _SC_NPROCESSORS_CONF
#define _SC_NPROCESSORS_CONF (-1)
#endif
#ifndef _SC_NPROCESSORS_ONLN
#define _SC_NPROCESSORS_ONLN (-1)
#endif
static int caml_conf_table[] =
{
_SC_ARG_MAX,
_SC_CHILD_MAX,
_SC_HOST_NAME_MAX,
_SC_LOGIN_NAME_MAX,
_SC_CLK_TCK,
_SC_OPEN_MAX,
_SC_PAGESIZE,
_SC_RE_DUP_MAX,
_SC_STREAM_MAX,
_SC_SYMLOOP_MAX,
_SC_TTY_NAME_MAX,
_SC_TZNAME_MAX,
_SC_VERSION,
_SC_LINE_MAX,
_SC_2_VERSION,
_SC_PHYS_PAGES,
_SC_AVPHYS_PAGES,
_SC_NPROCESSORS_CONF,
_SC_NPROCESSORS_ONLN
};
CAMLprim value caml_extunix_sysconf(value name)
{
CAMLparam1(name);
long r = -1;
int sc = caml_conf_table[Int_val(name)];
if (-1 == sc)
{
caml_raise_not_found();
assert(0);
}
r = sysconf(sc);
if (-1 == r)
{
uerror("sysconf", Nothing);
}
CAMLreturn(caml_copy_int64(r));
}
#endif
ocaml-extunix-0.3.2/src/sysinfo.c 0000664 0000000 0000000 00000002604 14045766433 0016754 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_SYSINFO
#include "config.h"
#if defined(EXTUNIX_HAVE_SYSINFO)
static value convert(struct sysinfo* s)
{
CAMLparam0();
CAMLlocal2(v,v_loads);
v_loads = caml_alloc_tuple(3);
Store_field(v_loads, 0, caml_copy_double(s->loads[0] / (float)(1 << SI_LOAD_SHIFT)));
Store_field(v_loads, 1, caml_copy_double(s->loads[1] / (float)(1 << SI_LOAD_SHIFT)));
Store_field(v_loads, 2, caml_copy_double(s->loads[2] / (float)(1 << SI_LOAD_SHIFT)));
v = caml_alloc_tuple(12);
Store_field(v, 0, Val_long(s->uptime));
Store_field(v, 1, v_loads);
Store_field(v, 2, Val_long(s->totalram));
Store_field(v, 3, Val_long(s->freeram));
Store_field(v, 4, Val_long(s->sharedram));
Store_field(v, 5, Val_long(s->bufferram));
Store_field(v, 6, Val_long(s->totalswap));
Store_field(v, 7, Val_long(s->freeswap));
Store_field(v, 8, Val_int(s->procs));
Store_field(v, 9, Val_long(s->totalhigh));
Store_field(v, 10, Val_long(s->freehigh));
Store_field(v, 11, Val_int(s->mem_unit));
CAMLreturn(v);
}
CAMLprim value caml_extunix_sysinfo(value v_unit)
{
CAMLparam1(v_unit);
struct sysinfo s;
if (0 != sysinfo(&s))
{
uerror("sysinfo",Nothing);
}
CAMLreturn(convert(&s));
}
CAMLprim value caml_extunix_uptime(value v_unit)
{
struct sysinfo s;
UNUSED(v_unit);
if (0 != sysinfo(&s))
{
uerror("sysinfo",Nothing);
}
return Val_int(s.uptime);
}
#endif
ocaml-extunix-0.3.2/src/syslog.c 0000664 0000000 0000000 00000005555 14045766433 0016612 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_SYSLOG
#include "config.h"
#if defined(EXTUNIX_HAVE_SYSLOG)
static int mask_table[] = {
LOG_MASK(LOG_EMERG), LOG_MASK(LOG_ALERT), LOG_MASK(LOG_CRIT),
LOG_MASK(LOG_ERR), LOG_MASK(LOG_WARNING), LOG_MASK(LOG_NOTICE),
LOG_MASK(LOG_INFO), LOG_MASK(LOG_DEBUG)
};
CAMLprim value caml_extunix_setlogmask(value v_level)
{
CAMLparam1(v_level);
CAMLlocal2(cli, cons);
int mask, nmask;
size_t i;
mask = caml_convert_flag_list(v_level, mask_table);
caml_enter_blocking_section();
nmask = setlogmask(mask);
caml_leave_blocking_section();
// generate list from mask (invers of "caml_convert_flag_list")
cli = Val_emptylist;
for (i = 0; i < (sizeof(mask_table) / sizeof(int)); i++)
{
if ((mask_table[i] & nmask) == mask_table[i])
{
cons = caml_alloc(2, 0);
Store_field(cons, 0, Val_int(i));
Store_field(cons, 1, cli);
cli = cons;
}
}
CAMLreturn(cli);
}
static int option_table[] = {
LOG_PID, LOG_CONS, LOG_NDELAY, LOG_ODELAY, LOG_NOWAIT
};
static int facility_table[] = {
LOG_KERN, LOG_USER, LOG_MAIL, LOG_NEWS, LOG_UUCP, LOG_DAEMON, LOG_AUTH,
LOG_CRON, LOG_LPR, LOG_LOCAL0, LOG_LOCAL1, LOG_LOCAL2, LOG_LOCAL3,
LOG_LOCAL4, LOG_LOCAL5, LOG_LOCAL6, LOG_LOCAL7
};
CAMLprim value caml_extunix_openlog(value v_ident, value v_option, value v_facility)
{
CAMLparam3(v_ident, v_option, v_facility);
int option, facility;
size_t index_facility;
static char *ident = NULL; /* openlog does _not_ store ident -- keep a heap copy */
if (NULL != ident)
{
free(ident);
ident = NULL;
}
ident = (Val_none == v_ident) ? NULL : strdup(String_val(Some_val(v_ident)));
option = caml_convert_flag_list(v_option, option_table);
index_facility = Int_val(v_facility);
assert(index_facility < (sizeof(facility_table) / sizeof(int)));
facility = facility_table[index_facility];
openlog(ident, option, facility);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_closelog(void)
{
CAMLparam0();
closelog();
CAMLreturn(Val_unit);
}
static int level_table[] = {
LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO,
LOG_DEBUG
};
CAMLprim value caml_extunix_syslog(value v_facility, value v_level, value v_string)
{
CAMLparam3(v_facility, v_level, v_string);
int facility, level;
size_t index_level, index_facility;
char *str;
facility = 0;
if (Val_none != v_facility)
{
index_facility = Int_val(Some_val(v_facility));
assert(index_facility < (sizeof(facility_table) / sizeof(int)));
facility = facility_table[index_facility];
}
index_level = Int_val(v_level);
assert(index_level < (sizeof(level_table) / sizeof(int)));
level = level_table[index_level];
str = strdup(String_val(v_string));
caml_enter_blocking_section();
syslog(level | facility, "%s", str);
caml_leave_blocking_section();
free(str);
CAMLreturn(Val_unit);
}
#endif
ocaml-extunix-0.3.2/src/time.c 0000664 0000000 0000000 00000007654 14045766433 0016232 0 ustar 00root root 0000000 0000000 #define EXTUNIX_WANT_STRPTIME
#define EXTUNIX_WANT_STRTIME
#define EXTUNIX_WANT_TIMEZONE
#define EXTUNIX_WANT_TIMEGM
#include "config.h"
#if defined(EXTUNIX_HAVE_STRPTIME)
/*
* http://caml.inria.fr/mantis/view.php?id=3851
* Author: Joshua Smith
*/
/* from otherlibs/unix/gmtime.c */
static value alloc_tm(struct tm *tm)
{
value res;
res = caml_alloc_small(9, 0);
Field(res,0) = Val_int(tm->tm_sec);
Field(res,1) = Val_int(tm->tm_min);
Field(res,2) = Val_int(tm->tm_hour);
Field(res,3) = Val_int(tm->tm_mday);
Field(res,4) = Val_int(tm->tm_mon);
Field(res,5) = Val_int(tm->tm_year);
Field(res,6) = Val_int(tm->tm_wday);
Field(res,7) = Val_int(tm->tm_yday);
Field(res,8) = tm->tm_isdst ? Val_true : Val_false;
return res;
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
CAMLprim value caml_extunix_strptime(value v_fmt, value v_s)
{
struct tm tm = { 0 };
if (NULL == strptime(String_val(v_s),String_val(v_fmt),&tm))
unix_error(EINVAL, "strptime", v_s);
return alloc_tm(&tm);
}
#pragma GCC diagnostic pop
#endif
#if defined(EXTUNIX_HAVE_STRTIME) || defined(EXTUNIX_HAVE_TIMEGM)
static void fill_tm(struct tm* tm, value t)
{
tm->tm_sec = Int_val(Field(t, 0));
tm->tm_min = Int_val(Field(t, 1));
tm->tm_hour = Int_val(Field(t, 2));
tm->tm_mday = Int_val(Field(t, 3));
tm->tm_mon = Int_val(Field(t, 4));
tm->tm_year = Int_val(Field(t, 5));
tm->tm_wday = Int_val(Field(t, 6));
tm->tm_yday = Int_val(Field(t, 7));
tm->tm_isdst = Bool_val(Field(t, 8)); /* -1 */
}
#endif
#if defined(EXTUNIX_HAVE_STRTIME)
CAMLprim value caml_extunix_asctime(value v_t)
{
CAMLparam1(v_t);
struct tm tm;
char_os buf[32]; /* user-supplied buffer which should have room for
at least 26 bytes */
#if defined(_WIN32)
errno_t err;
#endif
fill_tm(&tm, v_t);
#if defined(_WIN32)
if ((0 != (err = _wasctime_s(buf, sizeof(buf)/sizeof(buf[0]), &tm)))) {
win32_maperr(err);
#else
if (NULL == asctime_r(&tm, buf)) {
#endif
uerror("asctime", Nothing);
}
CAMLreturn(caml_copy_string_of_os(buf));
}
CAMLprim value caml_extunix_strftime(value v_fmt, value v_t)
{
CAMLparam2(v_fmt, v_t);
struct tm tm;
char_os buf[256];
#if defined(_WIN32)
char_os *fmt;
size_t rc;
#endif
fill_tm(&tm, v_t);
#if defined(_WIN32)
fmt = caml_stat_strdup_to_os(String_val(v_fmt));
rc = wcsftime(buf,sizeof(buf)/sizeof(buf[0]),fmt,&tm);
caml_stat_free(fmt);
if (0 == rc)
#else
if (0 == strftime(buf,sizeof(buf),String_val(v_fmt),&tm))
#endif
unix_error(EINVAL, "strftime", v_fmt);
CAMLreturn(caml_copy_string_of_os(buf));
}
CAMLprim value caml_extunix_tzname(value v_isdst)
{
CAMLparam1(v_isdst);
int i = Bool_val(v_isdst) ? 1 : 0;
#if defined(_WIN32)
CAMLlocal1(tzname);
size_t tznameSize;
_tzset();
if (0 != _get_tzname(&tznameSize, NULL, 0, i))
unix_error(EINVAL, "tzname", Nothing);
tzname = caml_alloc_string(tznameSize);
if (0 != _get_tzname(&tznameSize, (char *)String_val(tzname),
tznameSize, i))
unix_error(EINVAL, "tzname", Nothing);
CAMLreturn(tzname);
#else
tzset();
CAMLreturn(caml_copy_string(tzname[i]));
#endif
}
#endif
#if defined(EXTUNIX_HAVE_TIMEZONE)
CAMLprim value caml_extunix_timezone(value v_unit)
{
CAMLparam1(v_unit);
CAMLlocal1(v);
#if defined(_WIN32)
long timezone;
int daylight;
_tzset();
if (0 != _get_timezone(&timezone))
unix_error(EINVAL, "timezone", Nothing);
if (0 != _get_daylight(&daylight))
unix_error(EINVAL, "daylight", Nothing);
#else
tzset();
#endif
v = caml_alloc_tuple(2);
Store_field(v, 0, Val_long(timezone));
Store_field(v, 1, Val_bool(daylight != 0));
CAMLreturn(v);
}
#endif
#if defined(EXTUNIX_HAVE_TIMEGM)
CAMLprim value caml_extunix_timegm(value v_t)
{
CAMLparam1(v_t);
struct tm tm;
time_t t;
fill_tm(&tm, v_t);
#if defined(_WIN32)
t = _mkgmtime(&tm);
#else
t = timegm(&tm);
#endif
CAMLreturn(caml_copy_double(t));
}
#endif
ocaml-extunix-0.3.2/src/tty_ioctl.c 0000664 0000000 0000000 00000002135 14045766433 0017273 0 ustar 00root root 0000000 0000000 /*
* Copyright : (c) 2010, Stéphane Glondu
*/
#define EXTUNIX_WANT_TTY_IOCTL
#include "config.h"
#if defined(EXTUNIX_HAVE_TTY_IOCTL)
/* FIXME implement separate interface for tcsetattr/tcgetattr */
CAMLprim value caml_extunix_crtscts(value mlfd)
{
CAMLparam1(mlfd);
struct termios t;
int r, fd = Int_val(mlfd);
r = tcgetattr(fd, &t);
if (0 == r) {
t.c_cflag |= CRTSCTS;
r = tcsetattr(fd, TCSANOW, &t);
}
if (0 != r) uerror("crtscts",Nothing);
CAMLreturn(Val_unit);
}
#define TTY_IOCTL_INT(cmd) \
CAMLprim value caml_extunix_ioctl_##cmd(value v_fd, value v_arg) \
{ \
CAMLparam2(v_fd, v_arg); \
int arg = Int_val(v_arg); \
int r = ioctl(Int_val(v_fd), cmd, &arg); \
if (r < 0) uerror("ioctl",caml_copy_string(#cmd)); \
CAMLreturn(Val_unit); \
}
CAMLprim value caml_extunix_ioctl_TIOCMGET(value v_fd)
{
CAMLparam1(v_fd);
int arg = 0;
int r = ioctl(Int_val(v_fd), TIOCMGET, &arg);
if (r < 0) uerror("ioctl",caml_copy_string("TIOCMGET"));
CAMLreturn(Val_int(arg));
}
TTY_IOCTL_INT(TIOCMSET)
TTY_IOCTL_INT(TIOCMBIC)
TTY_IOCTL_INT(TIOCMBIS)
#endif
ocaml-extunix-0.3.2/src/uname.c 0000664 0000000 0000000 00000001376 14045766433 0016374 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_UNAME
#include "config.h"
#if defined(EXTUNIX_HAVE_UNAME)
CAMLprim value caml_extunix_uname(value u)
{
struct utsname uname_data;
CAMLparam1(u);
CAMLlocal2(result, domainname);
memset(&uname_data, 0, sizeof(uname_data));
if (uname(&uname_data) == 0)
{
result = caml_alloc(5, 0);
Store_field(result, 0, caml_copy_string(&(uname_data.sysname[0])));
Store_field(result, 1, caml_copy_string(&(uname_data.nodename[0])));
Store_field(result, 2, caml_copy_string(&(uname_data.release[0])));
Store_field(result, 3, caml_copy_string(&(uname_data.version[0])));
Store_field(result, 4, caml_copy_string(&(uname_data.machine[0])));
}
else
{
uerror("uname",Nothing);
}
CAMLreturn(result);
}
#endif
ocaml-extunix-0.3.2/src/unistd.c 0000664 0000000 0000000 00000031630 14045766433 0016571 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_TTYNAME
#define EXTUNIX_WANT_CTERMID
#define EXTUNIX_WANT_PGID
#define EXTUNIX_WANT_SETREUID
#define EXTUNIX_WANT_SETRESUID
#define EXTUNIX_WANT_FCNTL
#define EXTUNIX_WANT_TCPGRP
#define EXTUNIX_WANT_PREAD
#define EXTUNIX_WANT_PWRITE
#define EXTUNIX_WANT_READ
#define EXTUNIX_WANT_WRITE
#define EXTUNIX_WANT_GETTID
#define EXTUNIX_WANT_CHROOT
#include "config.h"
#if defined(EXTUNIX_HAVE_TTYNAME)
/* Copyright © 2010 Stéphane Glondu */
CAMLprim value caml_extunix_ttyname(value v_fd)
{
CAMLparam1(v_fd);
char *r = ttyname(Int_val(v_fd));
if (r) {
CAMLreturn(caml_copy_string(r));
} else {
uerror("ttyname", Nothing);
}
}
#endif
#if defined(EXTUNIX_HAVE_CTERMID)
CAMLprim value caml_extunix_ctermid(value v_unit)
{
char buf[L_ctermid + 1];
UNUSED(v_unit);
return caml_copy_string(ctermid(buf));
}
#endif
#if defined(EXTUNIX_HAVE_GETTID)
CAMLprim value caml_extunix_gettid(value v_unit)
{
UNUSED(v_unit);
size_t tid = 0;
#if defined(WIN32)
tid = GetCurrentThreadId();
#elif defined(EXTUNIX_USE_THREADID)
pthread_threadid_np(NULL, &tid);
#elif defined(EXTUNIX_USE_THREAD_SELFID)
tid = syscall(SYS_thread_selfid);
#else
tid = syscall(SYS_gettid);
#endif
return Val_int(tid); /* XXX truncating to int */
}
#endif
#if defined(EXTUNIX_HAVE_PGID)
CAMLprim value caml_extunix_setpgid(value v_pid, value v_pgid)
{
CAMLparam2(v_pid, v_pgid);
if (0 != setpgid(Int_val(v_pid), Int_val(v_pgid)))
uerror("setpgid",Nothing);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_getpgid(value v_pid)
{
CAMLparam1(v_pid);
int pgid = getpgid(Int_val(v_pid));
if (pgid < 0)
uerror("getpgid",Nothing);
CAMLreturn(Val_int(pgid));
}
CAMLprim value caml_extunix_getsid(value v_pid)
{
CAMLparam1(v_pid);
int sid = getsid(Int_val(v_pid));
if (sid < 0)
uerror("getsid",Nothing);
CAMLreturn(Val_int(sid));
}
#endif
#if defined(EXTUNIX_HAVE_SETREUID)
CAMLprim value caml_extunix_setreuid(value v_ruid, value v_euid)
{
CAMLparam2(v_ruid,v_euid);
int r = setreuid(Int_val(v_ruid), Int_val(v_euid));
if (r < 0)
uerror("setreuid", Nothing);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_setregid(value v_rgid, value v_egid)
{
CAMLparam2(v_rgid,v_egid);
int r = setregid(Int_val(v_rgid), Int_val(v_egid));
if (r < 0)
uerror("setregid", Nothing);
CAMLreturn(Val_unit);
}
#endif
#if defined(EXTUNIX_HAVE_SETRESUID)
CAMLprim value caml_extunix_setresuid(value r, value e, value s)
{
CAMLparam3(r, e, s);
uid_t ruid = Int_val(r);
uid_t euid = Int_val(e);
uid_t suid = Int_val(s);
if (setresuid(ruid, euid, suid) != 0)
uerror("setresuid", Nothing);
CAMLreturn(Val_unit);
}
CAMLprim value caml_extunix_setresgid(value r, value e, value s)
{
CAMLparam3(r, e, s);
gid_t rgid = Int_val(r);
gid_t egid = Int_val(e);
gid_t sgid = Int_val(s);
if (setresgid(rgid, egid, sgid) == -1)
uerror("setresgid", Nothing);
CAMLreturn(Val_unit);
}
#endif /* EXTUNIX_HAVE_SETRESUID */
#if defined(EXTUNIX_HAVE_FCNTL)
CAMLprim value caml_extunix_is_open_descr(value v_fd)
{
int r = fcntl(Int_val(v_fd), F_GETFL);
if (-1 == r)
{
if (EBADF == errno) return Val_false;
uerror("fcntl", Nothing);
};
return Val_true;
}
#endif
#if defined(EXTUNIX_HAVE_TCPGRP)
CAMLprim value caml_extunix_tcgetpgrp(value v_fd)
{
int pgid = tcgetpgrp(Int_val(v_fd));
if (-1 == pgid)
uerror("tcgetpgrp", Nothing);
return Val_int(pgid);
}
CAMLprim value caml_extunix_tcsetpgrp(value v_fd, value v_pgid)
{
int r = tcsetpgrp(Int_val(v_fd), Int_val(v_pgid));
if (-1 == r)
uerror("tcsetpgrp", Nothing);
return Val_int(r);
}
#endif
enum mode_bits {
BIT_ONCE = 1 << 0,
BIT_NOERROR = 1 << 1,
BIT_NOINTR = 1 << 2
};
#if defined(EXTUNIX_HAVE_PREAD)
/* Copyright © 2012 Goswin von Brederlow */
CAMLprim value caml_extunix_pread_common(value v_fd, off_t off, value v_buf, value v_ofs, value v_len, int mode) {
CAMLparam4(v_fd, v_buf, v_ofs, v_len);
ssize_t ret;
size_t fd = Int_val(v_fd);
size_t ofs = Long_val(v_ofs);
size_t len = Long_val(v_len);
size_t processed = 0;
char iobuf[UNIX_BUFFER_SIZE];
while(len > 0) {
size_t numbytes = (len > UNIX_BUFFER_SIZE) ? UNIX_BUFFER_SIZE : len;
caml_enter_blocking_section();
ret = pread(fd, iobuf, numbytes, off);
caml_leave_blocking_section();
if (ret == 0) break;
if (ret == -1) {
if (errno == EINTR && (mode & BIT_NOINTR)) continue;
if (processed > 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
if (mode & BIT_NOERROR) break;
}
uerror("pread", Nothing);
}
memcpy(&Byte(v_buf, ofs), iobuf, ret);
processed += ret;
off += ret;
ofs += ret;
len -= ret;
if (mode & BIT_ONCE) break;
}
CAMLreturn(Val_long(processed));
}
value caml_extunix_all_pread(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Long_val(v_off);
return caml_extunix_pread_common(v_fd, off, v_buf, v_ofs, v_len, BIT_NOINTR);
}
value caml_extunix_single_pread(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Long_val(v_off);
return caml_extunix_pread_common(v_fd, off, v_buf, v_ofs, v_len, BIT_ONCE);
}
value caml_extunix_pread(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Long_val(v_off);
return caml_extunix_pread_common(v_fd, off, v_buf, v_ofs, v_len, BIT_NOINTR | BIT_NOERROR);
}
value caml_extunix_intr_pread(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Long_val(v_off);
return caml_extunix_pread_common(v_fd, off, v_buf, v_ofs, v_len, BIT_NOERROR);
}
value caml_extunix_all_pread64(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Int64_val(v_off);
return caml_extunix_pread_common(v_fd, off, v_buf, v_ofs, v_len, BIT_NOINTR);
}
value caml_extunix_single_pread64(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Int64_val(v_off);
return caml_extunix_pread_common(v_fd, off, v_buf, v_ofs, v_len, BIT_ONCE);
}
value caml_extunix_pread64(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Int64_val(v_off);
return caml_extunix_pread_common(v_fd, off, v_buf, v_ofs, v_len, BIT_NOINTR | BIT_NOERROR);
}
value caml_extunix_intr_pread64(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Int64_val(v_off);
return caml_extunix_pread_common(v_fd, off, v_buf, v_ofs, v_len, BIT_NOERROR);
}
#endif
#if defined(EXTUNIX_HAVE_PWRITE)
/* Copyright © 2012 Goswin von Brederlow */
CAMLprim value caml_extunix_pwrite_common(value v_fd, off_t off, value v_buf, value v_ofs, value v_len, int mode) {
CAMLparam4(v_fd, v_buf, v_ofs, v_len);
ssize_t ret;
size_t fd = Int_val(v_fd);
size_t ofs = Long_val(v_ofs);
size_t len = Long_val(v_len);
size_t processed = 0;
char iobuf[UNIX_BUFFER_SIZE];
while(len > 0) {
size_t numbytes = (len > UNIX_BUFFER_SIZE) ? UNIX_BUFFER_SIZE : len;
memcpy(iobuf, &Byte(v_buf, ofs), numbytes);
caml_enter_blocking_section();
ret = pwrite(fd, iobuf, numbytes, off);
caml_leave_blocking_section();
if (ret == 0) break;
if (ret == -1) {
if (errno == EINTR && (mode & BIT_NOINTR)) continue;
if (processed > 0){
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
if (mode & BIT_NOERROR) break;
}
uerror("pwrite", Nothing);
}
processed += ret;
off += ret;
ofs += ret;
len -= ret;
if (mode & BIT_ONCE) break;
}
CAMLreturn(Val_long(processed));
}
value caml_extunix_all_pwrite(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Long_val(v_off);
return caml_extunix_pwrite_common(v_fd, off, v_buf, v_ofs, v_len, BIT_NOINTR);
}
value caml_extunix_single_pwrite(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Long_val(v_off);
return caml_extunix_pwrite_common(v_fd, off, v_buf, v_ofs, v_len, BIT_ONCE);
}
value caml_extunix_pwrite(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Long_val(v_off);
return caml_extunix_pwrite_common(v_fd, off, v_buf, v_ofs, v_len, BIT_NOINTR | BIT_NOERROR);
}
value caml_extunix_intr_pwrite(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Long_val(v_off);
return caml_extunix_pwrite_common(v_fd, off, v_buf, v_ofs, v_len, BIT_NOERROR);
}
value caml_extunix_all_pwrite64(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Int64_val(v_off);
return caml_extunix_pwrite_common(v_fd, off, v_buf, v_ofs, v_len, BIT_NOINTR);
}
value caml_extunix_single_pwrite64(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Int64_val(v_off);
return caml_extunix_pwrite_common(v_fd, off, v_buf, v_ofs, v_len, BIT_ONCE);
}
value caml_extunix_pwrite64(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Int64_val(v_off);
return caml_extunix_pwrite_common(v_fd, off, v_buf, v_ofs, v_len, BIT_NOINTR | BIT_NOERROR);
}
value caml_extunix_intr_pwrite64(value v_fd, value v_off, value v_buf, value v_ofs, value v_len)
{
off_t off = Int64_val(v_off);
return caml_extunix_pwrite_common(v_fd, off, v_buf, v_ofs, v_len, BIT_NOERROR);
}
#endif
#if defined(EXTUNIX_HAVE_READ)
/* Copyright © 2012 Goswin von Brederlow */
CAMLprim value caml_extunix_read_common(value v_fd, value v_buf, value v_ofs, value v_len, int mode) {
CAMLparam4(v_fd, v_buf, v_ofs, v_len);
ssize_t ret;
size_t fd = Int_val(v_fd);
size_t ofs = Long_val(v_ofs);
size_t len = Long_val(v_len);
size_t processed = 0;
char iobuf[UNIX_BUFFER_SIZE];
while(len > 0) {
size_t numbytes = (len > UNIX_BUFFER_SIZE) ? UNIX_BUFFER_SIZE : len;
caml_enter_blocking_section();
ret = read(fd, iobuf, numbytes);
caml_leave_blocking_section();
if (ret == 0) break;
if (ret == -1) {
if (errno == EINTR && (mode & BIT_NOINTR)) continue;
if (processed > 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
if (mode & BIT_NOERROR) break;
}
uerror("read", Nothing);
}
memcpy(&Byte(v_buf, ofs), iobuf, ret);
processed += ret;
ofs += ret;
len -= ret;
if (mode & BIT_ONCE) break;
}
CAMLreturn(Val_long(processed));
}
value caml_extunix_all_read(value v_fd, value v_buf, value v_ofs, value v_len)
{
return caml_extunix_read_common(v_fd, v_buf, v_ofs, v_len, BIT_NOINTR);
}
value caml_extunix_single_read(value v_fd, value v_buf, value v_ofs, value v_len)
{
return caml_extunix_read_common(v_fd, v_buf, v_ofs, v_len, BIT_ONCE);
}
value caml_extunix_read(value v_fd, value v_buf, value v_ofs, value v_len)
{
return caml_extunix_read_common(v_fd, v_buf, v_ofs, v_len, BIT_NOINTR | BIT_NOERROR);
}
value caml_extunix_intr_read(value v_fd, value v_buf, value v_ofs, value v_len)
{
return caml_extunix_read_common(v_fd, v_buf, v_ofs, v_len, BIT_NOERROR);
}
#endif
#if defined(EXTUNIX_HAVE_WRITE)
/* Copyright © 2012 Goswin von Brederlow */
CAMLprim value caml_extunix_write_common(value v_fd, value v_buf, value v_ofs, value v_len, int mode) {
CAMLparam4(v_fd, v_buf, v_ofs, v_len);
ssize_t ret;
size_t fd = Int_val(v_fd);
size_t ofs = Long_val(v_ofs);
size_t len = Long_val(v_len);
size_t processed = 0;
char iobuf[UNIX_BUFFER_SIZE];
while(len > 0) {
size_t numbytes = (len > UNIX_BUFFER_SIZE) ? UNIX_BUFFER_SIZE : len;
memcpy(iobuf, &Byte(v_buf, ofs), numbytes);
caml_enter_blocking_section();
ret = write(fd, iobuf, numbytes);
caml_leave_blocking_section();
if (ret == 0) break;
if (ret == -1) {
if (errno == EINTR && (mode & BIT_NOINTR)) continue;
if (processed > 0){
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
if (mode & BIT_NOERROR) break;
}
uerror("write", Nothing);
}
processed += ret;
ofs += ret;
len -= ret;
if (mode & BIT_ONCE) break;
}
CAMLreturn(Val_long(processed));
}
value caml_extunix_all_write(value v_fd, value v_buf, value v_ofs, value v_len)
{
return caml_extunix_write_common(v_fd, v_buf, v_ofs, v_len, BIT_NOINTR);
}
value caml_extunix_single_write(value v_fd, value v_buf, value v_ofs, value v_len)
{
return caml_extunix_write_common(v_fd, v_buf, v_ofs, v_len, BIT_ONCE);
}
value caml_extunix_write(value v_fd, value v_buf, value v_ofs, value v_len)
{
return caml_extunix_write_common(v_fd, v_buf, v_ofs, v_len, BIT_NOINTR | BIT_NOERROR);
}
value caml_extunix_intr_write(value v_fd, value v_buf, value v_ofs, value v_len)
{
return caml_extunix_write_common(v_fd, v_buf, v_ofs, v_len, BIT_NOERROR);
}
#endif
#if defined(EXTUNIX_HAVE_CHROOT)
CAMLprim value caml_extunix_chroot(value v_path)
{
CAMLparam1(v_path);
int ret;
char* p_path = strdup(String_val(v_path));
caml_enter_blocking_section();
ret = chroot(p_path);
caml_leave_blocking_section();
free(p_path);
if (ret != 0) uerror("chroot", v_path);
CAMLreturn(Val_unit);
}
#endif
ocaml-extunix-0.3.2/src/unshare.c 0000664 0000000 0000000 00000001135 14045766433 0016725 0 ustar 00root root 0000000 0000000
#define EXTUNIX_WANT_UNSHARE
#include "config.h"
#if defined(EXTUNIX_HAVE_UNSHARE)
static int umountflags_table[] = {
CLONE_FS, CLONE_FILES, CLONE_NEWNS, CLONE_SYSVSEM, CLONE_NEWUTS,
CLONE_NEWIPC, CLONE_NEWUSER, CLONE_NEWPID, CLONE_NEWNET
};
CAMLprim value caml_extunix_unshare(value v_cloneflags)
{
CAMLparam1(v_cloneflags);
int ret;
int p_cloneflags = caml_convert_flag_list(v_cloneflags, umountflags_table);
caml_enter_blocking_section();
ret = unshare(p_cloneflags);
caml_leave_blocking_section();
if (ret != 0) uerror("unshare", Nothing);
CAMLreturn(Val_unit);
}
#endif
ocaml-extunix-0.3.2/test/ 0000775 0000000 0000000 00000000000 14045766433 0015304 5 ustar 00root root 0000000 0000000 ocaml-extunix-0.3.2/test/dune 0000664 0000000 0000000 00000000075 14045766433 0016164 0 ustar 00root root 0000000 0000000 (tests
(names test testba)
(libraries extunix ounit2 str))
ocaml-extunix-0.3.2/test/test.ml 0000664 0000000 0000000 00000046463 14045766433 0016632 0 ustar 00root root 0000000 0000000
open Printf
open OUnit
open ExtUnix.All
let with_unix_error f () =
try
f ()
with
| Unix.Unix_error(e,f,a) ->
let message = sprintf "Unix_error : %s(%s) : %s" f a (Unix.error_message e) in
skip_if (e = Unix.ENOSYS) message; (* libc may raise Not implemented, not an error in extunix *)
assert_failure message
let require feature =
match have feature with
| None -> assert false
| Some present -> skip_if (not present) (sprintf "%S is not available" feature)
let printer x = x
let test_eventfd () =
require "eventfd";
let e = eventfd 2 in
assert_equal 2L (eventfd_read e);
eventfd_write e 3L;
assert_equal 3L (eventfd_read e)
let test_uname () =
require "uname";
let t = uname () in
let _s: string = Uname.to_string t in
()
let test_fadvise () =
require "fadvise";
let (name,ch) = Filename.open_temp_file "extunix" "test" in
try
fadvise (Unix.descr_of_out_channel ch) 0 0 POSIX_FADV_NORMAL;
LargeFile.fadvise (Unix.descr_of_out_channel ch) 0L 0L POSIX_FADV_SEQUENTIAL;
close_out ch;
Unix.unlink name
with exn -> close_out_noerr ch; Unix.unlink name; raise exn
let test_fallocate () =
require "fallocate";
let (name,ch) = Filename.open_temp_file "extunix" "test" in
try
let fd = Unix.descr_of_out_channel ch in
fallocate fd 0 1;
LargeFile.fallocate fd 1L 1L;
assert_equal (Unix.fstat fd).Unix.st_size 2;
close_out_noerr ch;
Unix.unlink name
with exn -> close_out_noerr ch; Unix.unlink name; raise exn
(* Copied from oUnit.ml *)
(* Utility function to manipulate test *)
let rec test_decorate g tst =
match tst with
| TestCase f ->
TestCase (g f)
| TestList tst_lst ->
TestList (List.map (test_decorate g) tst_lst)
| TestLabel (str, tst) ->
TestLabel (str, test_decorate g tst)
let test_unistd =
[
"ttyname" >:: begin fun () ->
require "ttyname";
if Unix.isatty Unix.stdin then ignore (ttyname Unix.stdin);
if Unix.isatty Unix.stdout then ignore (ttyname Unix.stdout);
end;
"ctermid" >:: (fun () -> require "ctermid"; ignore (ctermid ()));
"pgid" >:: begin fun () ->
require "getpgid";
assert_equal (getsid 0) (getsid (Unix.getpid ()));
let pgid = getpgid 0 in
setpgid 0 0;
assert_equal (getpgid 0) (Unix.getpid ());
setpgid 0 pgid;
assert_equal (getpgid 0) pgid;
end;
"fcntl" >:: begin fun () ->
require "is_open_descr";
assert (is_open_descr Unix.stdin);
assert (is_open_descr Unix.stdout);
end;
"int_of_file_descr" >:: begin fun () ->
try
assert (Unix.stdout = (file_descr_of_int (int_of_file_descr Unix.stdout)))
with
Not_available _ -> skip_if true "int_of_file_descr"
end
]
let test_realpath () =
require "realpath";
assert_equal ~printer (Unix.getcwd ()) (realpath ".");
assert_equal ~printer (Unix.getcwd ()) (realpath "./././/./");
assert_equal ~printer "/" (realpath "///");
assert_equal ~printer "/" (realpath "/../../");
()
let test_signalfd () =
require "signalfd";
let pid = Unix.getpid () in
let (_:int list) = Unix.sigprocmask Unix.SIG_BLOCK [Sys.sigusr1; Sys.sigusr2] in
let fd = signalfd ~sigs:[Sys.sigusr1] ~flags:[] () in
Unix.kill pid Sys.sigusr1;
let fd = signalfd ~fd ~sigs:[Sys.sigusr1; Sys.sigusr2] ~flags:[] () in
Unix.set_nonblock fd;
let printer = string_of_int in
assert_equal ~printer Sys.sigusr1 (ssi_signo_sys (signalfd_read fd));
Unix.kill pid Sys.sigusr2;
assert_equal ~printer Sys.sigusr2 (ssi_signo_sys (signalfd_read fd));
Unix.close fd
let test_resource =
let all_resources =
[
RLIMIT_CORE;
RLIMIT_CPU;
RLIMIT_DATA;
RLIMIT_FSIZE;
(* RLIMIT_NOFILE; *) (* too fragile to test on CI *)
RLIMIT_STACK;
RLIMIT_AS;
]
in
let test_setrlimit r =
require "setrlimit";
let test soft hard =
setrlimit r ~soft ~hard;
let (soft',hard') = getrlimit r in
assert_equal ~printer:Rlimit.to_string ~msg:"soft limit" ~cmp:Rlimit.eq soft soft';
assert_equal ~printer:Rlimit.to_string ~msg:"hard limit" ~cmp:Rlimit.eq hard hard';
in
let (soft,hard) = getrlimit r in
assert_bool "soft <= hard" (Rlimit.le soft hard);
test hard hard;
test soft hard;
match hard with
| Some 0L -> ()
| None -> test soft soft
| Some n -> let lim = Some (Int64.pred n) in test lim lim
in
let test_setrlimit r =
(string_of_resource r) >:: (fun () -> test_setrlimit r)
in
[
"setrlimit" >::: (List.rev_map test_setrlimit all_resources);
"getpriority" >:: (fun () -> require "getpriority"; let (_:int) = getpriority (PRIO_PROCESS (Unix.getpid ())) in ());
"setpriority" >:: (fun () ->
require "setpriority";
let me = PRIO_PROCESS (Unix.getpid ()) in
let prio = getpriority me in
setpriority me (prio + 1);
assert_equal ~printer:string_of_int (prio + 1) (getpriority me));
]
let test_strtime () =
require "strptime";
assert_equal ~printer "2010/12/14" (strftime "%Y/%m/%d" (strptime "%Y-%m-%d" "2010-12-14"));
let tm = Unix.localtime (Unix.gettimeofday ()) in
let (_:string) = asctime tm in
let (_:string) = tzname tm.Unix.tm_isdst in
()
let test_pts () =
require "posix_openpt";
let master =
try
Some (posix_openpt [Unix.O_RDWR])
with
Unix.Unix_error (Unix.EPERM, _, _) -> None
in
match master with
| None -> skip_if true "posix_openpt EPERM"
| Some master ->
grantpt master;
unlockpt master;
let name = ptsname master in
let slave = Unix.openfile name [Unix.O_RDWR; Unix.O_NOCTTY] 0 in
let test = "test" in
let len = Unix.write_substring slave test 0 (String.length test) in
let str =
let b = Bytes.create len in
assert_equal (Unix.read master b 0 len) len;
Bytes.unsafe_to_string b
in
assert_equal str test;
()
let test_execinfo () =
require "backtrace";
(* Disabled - may not work out of the box on all archs or even segfault *)
(* assert_bool "backtrace" ([||] <> backtrace ()) *)
(* let (_:string array) = backtrace () in *)
()
let test_statvfs () =
require "statvfs";
let st = statvfs (if Sys.win32 then "C:\\" else ".") in
assert_bool "blocks" (st.f_blocks >= st.f_bfree && st.f_bfree >= st.f_bavail);
assert_bool "inodes" (st.f_files >= st.f_ffree && st.f_ffree >= st.f_favail);
assert_bool "bsize" (st.f_bsize > 0)
let test_setenv () =
require "setenv";
let k = "EXTUNIX_TEST_VAR" in
let v = string_of_float (Unix.gettimeofday ()) in
setenv k k true;
assert_equal ~printer k (Unix.getenv k);
setenv k v false;
assert_equal ~printer k (Unix.getenv k);
setenv k v true;
assert_equal ~printer v (Unix.getenv k);
unsetenv k;
unsetenv k;
assert_raises Not_found (fun () -> Unix.getenv k)
let test_mkdtemp () =
require "mkdtemp";
let name = "extunix_test_XXXXXX" in
let tmpl = Filename.concat (Filename.get_temp_dir_name ()) name in
let d1 = mkdtemp tmpl in
let d2 = mkdtemp tmpl in
try
assert_bool "different" (d1 <> d2);
assert_bool "d1 exists" ((Unix.stat d1).Unix.st_kind = Unix.S_DIR);
assert_bool "d2 exists" ((Unix.stat d2).Unix.st_kind = Unix.S_DIR);
Unix.rmdir d1;
Unix.rmdir d2
with exn -> Unix.rmdir d1; Unix.rmdir d2; raise exn
let test_endian () =
require "uint16_from_host";
require "uint16_to_host";
require "int16_from_host";
require "int16_to_host";
require "uint31_from_host";
require "uint31_to_host";
require "int31_from_host";
require "int31_to_host";
require "int32_from_host";
require "int32_to_host";
require "int64_from_host";
require "int64_to_host";
let module B = BigEndian in
let module L = LittleEndian in
let u16 = 0xABCD in
let i16 = -0x1234 in
let i32 = 0x89ABCDEFl in
let i64 = 0x0123456789ABCDEFL in
assert (B.uint16_to_host (B.uint16_from_host u16) = u16);
assert (B.int16_to_host (B.int16_from_host i16) = i16);
assert (L.uint16_to_host (L.uint16_from_host u16) = u16);
assert (L.int16_to_host (L.int16_from_host i16) = i16);
assert (B.uint16_from_host u16 <> L.uint16_from_host u16);
assert (B.uint16_to_host u16 <> L.uint16_to_host u16);
assert (B.int16_from_host i16 <> L.int16_from_host i16);
assert (B.int16_to_host i16 <> L.int16_to_host i16);
assert (B.int32_to_host (B.int32_from_host i32) = i32);
assert (L.int32_to_host (L.int32_from_host i32) = i32);
assert (B.int32_from_host i32 <> L.int32_from_host i32);
assert (B.int32_to_host i32 <> L.int32_to_host i32);
assert (B.int64_to_host (B.int64_from_host i64) = i64);
assert (L.int64_to_host (L.int64_from_host i64) = i64);
assert (B.int64_from_host i64 <> L.int64_from_host i64);
assert (B.int64_to_host i64 <> L.int64_to_host i64)
let test_endian_string () =
require "unsafe_get_int8";
require "unsafe_get_int16";
require "unsafe_get_int31";
require "unsafe_get_int32";
require "unsafe_get_int64";
require "unsafe_get_uint8";
require "unsafe_get_uint16";
require "unsafe_get_uint31";
require "unsafe_get_uint63";
require "unsafe_get_int63";
require "unsafe_set_uint8";
require "unsafe_set_uint16";
require "unsafe_set_uint31";
require "unsafe_set_int8";
require "unsafe_set_int16";
require "unsafe_set_int31";
require "unsafe_set_int32";
require "unsafe_set_uint63";
require "unsafe_set_int63";
require "unsafe_set_int64";
let module B = BigEndian in
let module L = LittleEndian in
let src = (* FF FF FEDC FEDC FEDCBA98 FEDCBA9876543210 *)
"\255\255\254\220\254\220\254\220\186\152\254\220\186\152\118\084\050\016"
in
assert_equal (B.get_uint8 src 0) 0xFF;
assert_equal (B.get_int8 src 1) (-0x01);
assert_equal (B.get_uint16 src 2) 0xFEDC;
assert_equal (B.get_int16 src 4) (-0x0124);
assert_equal (B.get_int32 src 6) (0xFEDCBA98l);
assert_equal (B.get_int64 src 10) (0xFEDCBA9876543210L);
assert_equal (L.get_uint8 src 0) 0xFF;
assert_equal (L.get_int8 src 1) (-0x01);
assert_equal (L.get_uint16 src 2) 0xDCFE;
assert_equal (L.get_int16 src 4) (-0x2302);
assert_equal (L.get_int32 src 6) (0x98BADCFEl);
assert_equal (L.get_int64 src 10) (0x1032547698BADCFEL);
assert_equal (B.get_uint31 src 6) (Int64.to_int 0xFEDCBA98L);
assert_equal (B.get_int31 src 6) (Int64.to_int 0x7FFFFFFFFEDCBA98L);
assert_equal (B.get_int31 src 6) (-0x1234568);
assert_equal (B.get_uint63 src 10) (Int64.to_int 0x7EDCBA9876543210L);
assert_equal (B.get_int63 src 10) (Int64.to_int 0x7EDCBA9876543210L);
assert_equal (B.get_int63 src 10) (Int64.to_int (-0x123456789ABCDF0L));
assert_equal (L.get_uint31 src 6) (Int64.to_int 0x98BADCFEL);
assert_equal (L.get_int31 src 6) (Int64.to_int 0x7FFFFFFF98BADCFEL);
assert_equal (L.get_int31 src 6) (-0x67452302);
assert_equal (L.get_uint63 src 10) (Int64.to_int 0x1032547698BADCFEL);
assert_equal (L.get_int63 src 10) (Int64.to_int 0x1032547698BADCFEL);
assert_equal (L.get_int63 src 10) (Int64.to_int (-0x6FCDAB8967452302L));
let b = Bytes.create 18 in
B.set_uint8 b 0 0xFF;
B.set_int8 b 1 (-0x01);
B.set_uint16 b 2 0xFEDC;
B.set_uint16 b 4 (-0x0124);
B.set_int32 b 6 (0xFEDCBA98l);
B.set_int64 b 10 (0xFEDCBA9876543210L);
assert_equal (Bytes.unsafe_to_string b) src;
let l = Bytes.create 18 in
L.set_uint8 l 0 0xFF;
L.set_int8 l 1 (-0x01);
L.set_uint16 l 2 0xDCFE;
L.set_uint16 l 4 (-0x2302);
L.set_int32 l 6 (0x98BADCFEl);
L.set_int64 l 10 (0x1032547698BADCFEL);
assert_equal (Bytes.unsafe_to_string l) src
let test_read_credentials () =
require "read_credentials";
let (_fd1, fd2) = Unix.socketpair Unix.PF_UNIX Unix.SOCK_STREAM 0 in
let (pid, uid, gid) = Unix.getpid (), Unix.getuid (), Unix.getgid () in
assert_equal (read_credentials fd2) (pid, uid, gid)
let test_fexecve () =
require "fexecve";
let s1, s2 = Unix.socketpair Unix.PF_UNIX Unix.SOCK_STREAM 0 in
match Unix.fork () with
| 0 ->
Unix.dup2 s2 Unix.stdout;
Unix.close s1;
Unix.close s2;
let fd = Unix.openfile "/bin/echo" [Unix.O_RDONLY] 0 in
fexecve fd [| "/bin/echo"; "-n"; "fexecve" |] [| |]
| pid ->
Unix.close s2;
let wpid, _ = Unix.wait () in
assert_equal wpid pid;
let str =
let b = Bytes.create 7 in
assert_equal (Unix.read s1 b 0 7) 7;
Bytes.unsafe_to_string b
in
assert_equal "fexecve" str;
Unix.close s1
let test_sendmsg () =
require "sendmsg";
let (s1, s2) = Unix.socketpair Unix.PF_UNIX Unix.SOCK_STREAM 0 in
match Unix.fork () with
| 0 ->
Unix.close s1;
let fd = Unix.openfile "/bin/ls" [Unix.O_RDONLY] 0 in
let st = Unix.fstat fd in
sendmsg s2 ~sendfd:fd (sprintf "%d" st.Unix.st_ino);
Unix.close fd;
Unix.close s2;
| _pid ->
Unix.close s2;
let (some_fd, msg) = recvmsg_fd s1 in
Unix.close s1;
match some_fd with
| None -> assert_failure "no fd"
| Some fd ->
let st = Unix.fstat fd in
assert_equal (int_of_string msg) st.Unix.st_ino;
Unix.close fd
let cmp_bytes str c text =
for i = 0 to Bytes.length str - 1 do
if Bytes.get str i <> c
then assert_failure text;
done
let test_pread () =
require "unsafe_pread";
let name = Filename.temp_file "extunix" "pread" in
let fd =
Unix.openfile name [Unix.O_RDWR] 0
in
try
let size = 65536 in (* Must be larger than UNIX_BUFFER_SIZE (16384) *)
let s = String.make size 'x' in
assert_equal (Unix.write_substring fd s 0 size) size;
let t = Bytes.make size ' ' in
assert_equal (pread fd 0 t 0 size) size;
cmp_bytes t 'x' "pread read bad data";
assert_equal (single_pread fd 0 t 0 size) size;
cmp_bytes t 'x' "single_pread read bad data";
let t = Bytes.make size ' ' in
assert_equal (LargeFile.pread fd Int64.zero t 0 size) size;
cmp_bytes t 'x' "Largefile.pread read bad data";
assert_equal (LargeFile.single_pread fd Int64.zero t 0 size) size;
cmp_bytes t 'x' "Largefile.single_pread read bad data";
Unix.close fd;
Unix.unlink name
with exn -> Unix.close fd; Unix.unlink name; raise exn
let test_pwrite () =
require "unsafe_pwrite";
let name = Filename.temp_file "extunix" "pwrite" in
let fd =
Unix.openfile name [Unix.O_RDWR] 0
in
let read dst =
assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0;
let rec loop off = function
| 0 -> ()
| size ->
let len = Unix.read fd dst off size
in
loop (off + len) (size - len)
in
loop 0 (Bytes.length dst)
in
try
let size = 65536 in (* Must be larger than UNIX_BUFFER_SIZE (16384) *)
let s = String.make size 'x' in
assert_equal (pwrite fd 0 s 0 size) size;
let t = Bytes.make size ' ' in
read t;
cmp_bytes t 'x' "pwrite wrote bad data";
assert_equal (single_pwrite fd 0 s 0 size) size;
read t;
cmp_bytes t 'x' "single_pwrite wrote bad data";
let s = String.make size 'y' in
assert_equal (LargeFile.pwrite fd Int64.zero s 0 size) size;
let t = Bytes.make size ' ' in
read t;
cmp_bytes t 'y' "Largefile.pwrite wrote bad data";
assert_equal (LargeFile.single_pwrite fd Int64.zero s 0 size) size;
read t;
cmp_bytes t 'y' "Largefile.single_pwrite wrote bad data";
Unix.close fd;
Unix.unlink name
with exn -> Unix.close fd; Unix.unlink name; raise exn
let test_read () =
require "unsafe_read";
let name = Filename.temp_file "extunix" "read" in
let fd =
Unix.openfile name [Unix.O_RDWR] 0
in
try
let size = 65536 in (* Must be larger than UNIX_BUFFER_SIZE (16384) *)
let s = String.make size 'x' in
assert_equal (Unix.write_substring fd s 0 size) size;
let t = Bytes.make size ' ' in
assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0;
assert_equal (read fd t 0 size) size;
cmp_bytes t 'x' "read read bad data";
assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0;
assert_equal (single_read fd t 0 size) size;
cmp_bytes t 'x' "single_read read bad data";
Unix.close fd;
Unix.unlink name
with exn -> Unix.close fd; Unix.unlink name; raise exn
let test_write () =
require "unsafe_write";
let name = Filename.temp_file "extunix" "write" in
let fd =
Unix.openfile name [Unix.O_RDWR] 0
in
let read dst =
assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0;
let rec loop off = function
| 0 -> ()
| size ->
let len = Unix.read fd dst off size
in
loop (off + len) (size - len)
in
loop 0 (Bytes.length dst)
in
try
let size = 65536 in (* Must be larger than UNIX_BUFFER_SIZE (16384) *)
let s = String.make size 'x' in
assert_equal (write fd s 0 size) size;
let t = Bytes.make size ' ' in
read t;
cmp_bytes t 'x' "write wrote bad data";
assert_equal (single_write fd s 0 size) size;
read t;
cmp_bytes t 'x' "single_write wrote bad data";
Unix.close fd;
Unix.unlink name
with exn -> Unix.close fd; Unix.unlink name; raise exn
let test_mkstemp () =
require "internal_mkstemps";
let (_fd, name) = mkstemp ~suffix:"mkstemp" "extunix" in
Unix.unlink name
let test_mkostemp () =
require "internal_mkostemps";
let (_fd, name) = mkostemp ~suffix:"mkstemp" ~flags:[Unix.O_APPEND] "extunix" in
Unix.unlink name
let test_memalign () =
require "memalign";
ignore (memalign 512 512);
ignore (memalign 1024 2048);
ignore (memalign 2048 16384);
ignore (memalign 4096 65536)
let test_sockopt () =
require "setsockopt_int";
require "getsockopt_int";
let fd = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
let test msg opt v =
try
setsockopt_int fd opt v;
assert_equal ~printer:string_of_int ~msg v (getsockopt_int fd opt)
with
Not_available _ -> skip_if true msg
in
Unix.setsockopt fd Unix.SO_KEEPALIVE true;
test "TCP_KEEPCNT" TCP_KEEPCNT 5;
test "TCP_KEEPIDLE" TCP_KEEPIDLE 30;
test "TCP_KEEPINTVL" TCP_KEEPINTVL 10;
Unix.close fd
let test_sendmsg_bin () =
require "sendmsg";
let test_msg = "test\x00message\x01" in
let (s,s') = Unix.socketpair Unix.PF_UNIX Unix.SOCK_STREAM 0 in
match Unix.fork () with
| 0 ->
Unix.close s';
sendmsg s ~sendfd:Unix.stdout test_msg;
sendfd ~sock:s ~fd:Unix.stdout
| _ ->
Unix.close s;
let (fd1,msg) = recvmsg_fd s' in
assert_equal ~printer:(sprintf "%S") test_msg msg;
match fd1 with
| None -> assert_failure "expected fd, got nothing"
| Some fd1 ->
Unix.close fd1;
let fd2 = recvfd s' in
Unix.close fd2
let test_sysinfo () =
require "sysinfo";
let t = sysinfo () in
let (_:int) = t.uptime in
()
let () =
let wrap test =
with_unix_error (fun () -> test (); Gc.compact ())
in
let tests = ("tests" >::: [
"eventfd" >:: test_eventfd;
"uname" >:: test_uname;
"fadvise" >:: test_fadvise;
"fallocate" >:: test_fallocate;
"unistd" >::: test_unistd;
"realpath" >:: test_realpath;
"signalfd" >:: test_signalfd;
"resource" >::: test_resource;
"strtime" >:: test_strtime;
"pts" >:: test_pts;
"execinfo" >:: test_execinfo;
"statvfs" >:: test_statvfs;
"setenv" >:: test_setenv;
"mkdtemp" >:: test_mkdtemp;
"endian" >:: test_endian;
"endian_string" >:: test_endian_string;
"read_credentials" >:: test_read_credentials;
"fexecve" >:: test_fexecve;
"sendmsg" >:: test_sendmsg;
"pread" >:: test_pread;
"pwrite" >:: test_pwrite;
"read" >:: test_read;
"write" >:: test_write;
"mkstemp" >:: test_mkstemp;
"mkostemp" >:: test_mkostemp;
"memalign" >:: test_memalign;
"sockopt" >:: test_sockopt;
"sendmsg_bin" >:: test_sendmsg_bin;
"sysinfo" >:: test_sysinfo;
]) in
ignore (run_test_tt_main (test_decorate wrap tests))
ocaml-extunix-0.3.2/test/test_user_namespace.ml 0000664 0000000 0000000 00000032614 14045766433 0021675 0 ustar 00root root 0000000 0000000
open ExtUnix.All
let mkdir ?(perm=0o750) dir =
if not (Sys.file_exists dir) then Unix.mkdir dir perm
let mount_inside ~dir ~src ~tgt ?(fstype="") ~flags ?(data="") () =
let tgt = Filename.concat dir tgt in
mkdir tgt;
mount ~source:src ~target:tgt ~fstype flags ~data
let mount_base dir =
mount_inside ~dir ~src:"proc" ~tgt:"proc" ~fstype:"proc"
~flags:[MS_NOSUID; MS_NOEXEC; MS_NODEV] ();
mount_inside ~dir ~src:"/sys" ~tgt:"sys" ~flags:[MS_BIND; MS_REC] ();
mount_inside ~dir ~src:"/dev" ~tgt:"dev" ~flags:[MS_BIND; MS_REC] ();
mount_inside ~dir ~src:"tmpfs" ~tgt:"dev/shm" ~fstype:"tmpfs"
~flags:[MS_NOSUID; MS_STRICTATIME; MS_NODEV]
~data:"mode=1777" ();
mount_inside ~dir ~src:"tmpfs" ~tgt:"run" ~fstype:"tmpfs"
~flags:[MS_NOSUID; MS_STRICTATIME; MS_NODEV]
~data:"mode=755" ();
(* for aptitude *)
mkdir (Filename.concat dir "/run/lock")
let do_chroot dest =
Sys.chdir dest;
chroot ".";
Sys.chdir "/"
let read_in_file fmt =
Printf.ksprintf (fun file ->
let c = open_in file in
let v = input_line c in
close_in c;
v
) fmt
let test_userns_availability () =
let unpriviledge_userns_clone =
"/proc/sys/kernel/unprivileged_userns_clone" in
if Sys.file_exists unpriviledge_userns_clone then begin
let v = read_in_file "%s" unpriviledge_userns_clone in
if v <> "1" then begin
Printf.eprintf "This kernel is configured to disable unpriviledge user\
namespace: %s must be 1\n" unpriviledge_userns_clone;
exit 1
end
end
let write_in_file fmt =
Printf.ksprintf (fun file ->
Printf.ksprintf (fun towrite ->
try
let cout = open_out file in
output_string cout towrite;
close_out cout
with _ ->
Printf.eprintf "Error during write of %s in %s\n"
towrite file;
exit 1
)
) fmt
let command fmt = Printf.ksprintf (fun cmd -> Sys.command cmd = 0) fmt
let command_no_fail ?(error=(fun () -> ())) fmt =
Printf.ksprintf (fun cmd ->
let c = Sys.command cmd in
if c <> 0 then begin
Printf.eprintf "Error during: %s\n%!" cmd;
error ();
exit 1;
end
) fmt
(** {2 GPG} *)
let download_keyid = "0xBAEFF88C22F6E216"
let download_keyserver = "hkp://pool.sks-keyservers.net"
type gpg_t =
| GPGNotAvailable
| GPGAvailable of string
let gpg_setup ~dir =
let command_raise fmt =
Printf.ksprintf (fun cmd ->
Printf.ksprintf (fun msg ->
let c = Sys.command cmd in
if c <> 0 then begin
Printf.eprintf "%s\n%!" msg;
raise Exit
end
)
) fmt
in
try
command_raise
"which gpg >/dev/null 2>&1"
"The program gpg is not present: can't validate download";
let gpg_dir = Filename.concat dir "gpg" in
mkdir ~perm:0o700 gpg_dir;
command_raise
"GNUPGHOME=%S gpg --keyserver %s --recv-keys %s > /dev/null 2>&1;"
gpg_dir download_keyserver download_keyid
"Can't download gpg key data: can't validate download";
GPGAvailable gpg_dir
with Exit ->
GPGNotAvailable
let gpg_check file = function
| GPGNotAvailable -> ()
| GPGAvailable gpg_dir ->
command_no_fail
~error:(fun () -> Printf.eprintf "Invalid signature for %s\n%!" file)
"GNUPGHOME=%S gpg --verify %S > /dev/null 2>&1" gpg_dir (file^".asc")
(** {2 Download image} *)
(** use lxc download template facilities *)
let download_compat_level=2
let download_server = "images.linuxcontainers.org"
let download ?(quiet=true) fmt =
Printf.ksprintf (fun src ->
Printf.ksprintf (fun dst ->
command "wget -T 30 %s https://%s/%s -O %S %s"
(if quiet then "-q" else "")
download_server src dst
(if quiet then ">/dev/null 2>&1" else "")
)
) fmt
let download_index ~dir ~gpg =
let index = Filename.concat dir "index" in
let url_index = "meta/1.0/index-user" in
Printf.printf "Download the index: %!";
if not (download
"%s.%i" url_index download_compat_level
"%s" index
&& download
"%s.%i.asc" url_index download_compat_level
"%s.asc" index) then
if not (download "%s" url_index "%s" index
&& download
"%s.asc" url_index
"%s.asc" index) then begin
Printf.eprintf "error.\n%!";
exit 1;
end;
gpg_check index gpg;
Printf.printf "done.\n%!";
index
let semicomma = Str.regexp_string ";"
(** return download build and directory url *)
let find_image ~distr ~release ~arch index =
let cin = open_in index in
let rec aux () =
match Str.split semicomma (input_line cin) with
| [d;r;a;_;db;u] when d = distr && r = release && a = arch ->
close_in cin; db,u
| _ -> aux () in
try
aux ()
with End_of_file -> close_in cin;
Printf.eprintf "Can't find url in index corresponding to %s %s %s\n%!"
distr release arch;
exit 1
let download_rootfs_meta ~dir ~gpg (build_id,url) =
let build_id_file = Filename.concat dir "build_id" in
let rootfs_tar = Filename.concat dir "rootfs.tar.xz" in
let meta_tar = Filename.concat dir "meta.tar.xz" in
if not (Sys.file_exists build_id_file)
|| read_in_file "%s" build_id_file <> build_id then begin
if Sys.file_exists build_id_file then Unix.unlink build_id_file;
Printf.printf "Downloading rootfs.\n%!";
if not (download ~quiet:false "%s/rootfs.tar.xz" url "%s/rootfs.tar.xz" dir
&& download "%s/rootfs.tar.xz.asc" url "%s/rootfs.tar.xz.asc" dir
&& download "%s/meta.tar.xz" url "%s/meta.tar.xz" dir
&& download "%s/meta.tar.xz.asc" url "%s/meta.tar.xz.asc" dir)
then begin Printf.printf "error.\n%!"; exit 1 end;
gpg_check rootfs_tar gpg;
gpg_check meta_tar gpg;
write_in_file "%s" build_id_file "%s" build_id
end;
rootfs_tar, meta_tar
(** {2 User namespace} *)
type userns_idmap =
| KeepUser
(** Put only the current user (uid,gid) as root in the userns *)
| IdMap of int * int
(** IdMap(id,rangeid): Map [1;rangeid] (uid,gid) in the userns to
[id,id+rangeid] (current user is root in the userns) *)
let set_usermap idmap pid =
let curr_uid = Unix.getuid () in
let curr_gid = Unix.getgid () in
(* write_in_file "/proc/%i/setgroups" pid "deny"; *)
match idmap with
| KeepUser ->
write_in_file "/proc/%i/uid_map" pid "0 %i 1" curr_uid;
write_in_file "/proc/%i/gid_map" pid "0 %i 1" curr_gid;
| IdMap(id,rangeid) ->
(* Printf.printf "pid: %i, mine: %i\n%!" pid (Unix.getpid ()); *)
let error () = ignore (Unix.kill pid 9); exit 1 in
command_no_fail ~error
"newuidmap %i 0 %i 1 1 %i %i" pid curr_uid id rangeid;
command_no_fail ~error
"newgidmap %i 0 %i 1 1 %i %i" pid curr_gid id rangeid
let goto_child ~exec_in_parent =
let fin,fout = Unix.pipe () in
match Unix.fork () with
| -1 -> Printf.eprintf "Fork failed\n%!"; exit 1
| 0 -> (* child *)
Unix.close fout;
ignore (Unix.read fin (Bytes.create 1) 0 1);
Unix.close fin
| pid ->
Unix.close fin;
(exec_in_parent pid: unit);
ignore (Unix.write fout (Bytes.create 1) 0 1);
Unix.close fout;
let _, status = Unix.waitpid [] pid in
match status with
| Unix.WEXITED s -> exit s
| Unix.WSIGNALED s -> Unix.kill (Unix.getpid ()) s; assert false
| Unix.WSTOPPED _ -> assert false
let exec_in_child (type a) f =
let fin,fout = Unix.pipe () in
match Unix.fork () with
| -1 -> Printf.eprintf "Fork failed\n%!"; exit 1
| 0 -> (* child *)
Unix.close fout;
let cin = Unix.in_channel_of_descr fin in
let arg = (Marshal.from_channel cin : a) in
close_in cin;
f arg;
exit 0
| pid ->
Unix.close fin;
let cout = Unix.out_channel_of_descr fout in
let call_in_child (arg:a) =
Marshal.to_channel cout arg [];
close_out cout;
let _, status = Unix.waitpid [] pid in
match status with
| Unix.WEXITED 0 -> ()
| Unix.WEXITED s -> exit s
| Unix.WSIGNALED s -> Unix.kill (Unix.getpid ()) s; assert false
| Unix.WSTOPPED _ -> assert false
in
call_in_child
let exec_now_in_child f arg =
match Unix.fork () with
| -1 -> Printf.eprintf "Fork failed\n%!"; exit 1
| 0 -> (* child *)
f arg;
exit 0
| pid ->
let _, status = Unix.waitpid [] pid in
match status with
| Unix.WEXITED 0 -> ()
| Unix.WEXITED s -> exit s
| Unix.WSIGNALED s -> Unix.kill (Unix.getpid ()) s; assert false
| Unix.WSTOPPED _ -> assert false
let just_goto_child () =
match Unix.fork () with
| -1 -> Printf.eprintf "Fork failed\n%!"; exit 1
| 0 -> (* child *) ()
| pid ->
let _, status = Unix.waitpid [] pid in
match status with
| Unix.WEXITED s -> exit s
| Unix.WSIGNALED s -> Unix.kill (Unix.getpid ()) s; assert false
| Unix.WSTOPPED _ -> assert false
let go_in_userns idmap =
(* the usermap can be set only completely outside the namespace, so we
keep a child for doing that when we have a pid completely inside the
namespace *)
let call_set_usermap = exec_in_child (set_usermap idmap) in
unshare [ CLONE_NEWNS;
CLONE_NEWIPC;
CLONE_NEWPID;
CLONE_NEWUTS;
CLONE_NEWUSER;
];
(* only the child will be in the new pid namespace, the parent is in
an intermediary state not interesting *)
goto_child ~exec_in_parent:call_set_usermap
(* Printf.printf "User: %i (%i)\n%!" (Unix.getuid ()) (Unix.geteuid ()); *)
(* Printf.printf "Pid: %i\n%!" (Unix.getpid ()); *)
(* Printf.printf "User: %i (%i)\n%!" (Unix.getuid ()) (Unix.geteuid ()); *)
let create_rootfs ~distr ~release ~arch testdir =
let rootfsdir = Filename.concat testdir "rootfs" in
if not (Sys.file_exists rootfsdir) then begin
let gpg = gpg_setup ~dir:testdir in
let index = download_index ~dir:testdir ~gpg in
let url =
find_image ~distr ~release ~arch index in
let rootfs, meta = download_rootfs_meta ~dir:testdir ~gpg url in
let metadir = Filename.concat testdir "meta" in
command_no_fail "rm -rf %S" metadir;
mkdir metadir;
command_no_fail "tar Jxf %S -C %S" meta metadir;
mkdir ~perm:0o750 rootfsdir;
let error () =
Printf.printf "error\n%!";
command_no_fail "rm -rf %S" rootfsdir in
let exclude = Filename.concat metadir "excludes-user" in
Printf.printf "Uncompressing rootfs:%!";
if Sys.file_exists exclude
then command_no_fail ~error
"tar Jxf %S -C %S --exclude-from %S \
--numeric-owner --preserve-permissions --preserve-order --same-owner"
rootfs rootfsdir exclude
else command_no_fail ~error "tar Jxf %S -C %S" rootfs rootfsdir;
Printf.printf "done.\n%!";
end;
rootfsdir
let idmap, (cmd,arg), testdir, setuid, setgid, arch, distr, release =
let open Arg in
let testdir = ref "userns_test" in
let idmap_id = ref (-1) in
let idmap_rangeid = ref (-1) in
let command = ref [] in
let setuid = ref 0 in
let setgid = ref 0 in
let arch = ref "amd64" in
let distr = ref "debian" in
let release = ref "jessie" in
parse (align [
"--dir",
Set_string testdir,
"dir Directory to use for the test \
(dir/rootfs is used for root directory)";
"--idmap",
Tuple [Set_int idmap_id;Set_int idmap_rangeid],
"id_range maps additionally uid/gid [1;range] to [id;id+range]\n\t\
you need a configured /etc/subuid (man subuid)";
"--uid",
Set_int setuid,
"uid Execute the command as this uid inside the user namespace";
"--gid",
Set_int setgid,
"gid Execute the command as this gid inside the user namespace";
"--arch",
Set_string arch,
"arch Specify the architecture of the image \
(eg. amd64, i386, armel,armhf)";
"--distr",
Tuple [Set_string distr; Set_string release],
"distr_release Specify the distribution and release of the image \
(eg. centos 6, debian jessie, ubuntu precise, gentoo current)";
"--",
Rest (fun s -> command := s::!command),
"Instead of running /bin/bash in the usernamespace, run the given command"
])
(fun _ -> raise (Bad "no anonymous option"))
"Test for user-namespace: you need linux at least 3.18. \
In the user-namespace the\n\
current user is root. Use LXC download template facilities for getting\n\
the root filesystem.";
let idmap =
match !idmap_id, !idmap_rangeid with
| (-1), _ | _, (-1) -> KeepUser
| id, range -> IdMap(id,range)
in
let command =
match List.rev !command with
| [] -> "/bin/bash",[|"bash"|]
| (cmd::_) as l -> cmd, Array.of_list l in
idmap, command, !testdir, !setuid, !setgid, !arch, !distr, !release
let () =
if Unix.getuid () = 0 then begin
Printf.eprintf "This program shouldn't be run as root!\n%!";
exit 1
end;
Unix.handle_unix_error begin fun () ->
test_userns_availability ();
mkdir ~perm:0o750 testdir;
go_in_userns idmap;
let rootfsdir = create_rootfs ~arch ~distr ~release testdir in
command_no_fail "cp /etc/resolv.conf %S"
(Filename.concat rootfsdir "etc/resolv.conf");
(* make the mount private and mount basic directories *)
mount_base rootfsdir;
(* chroot in the directory *)
do_chroot rootfsdir;
(* group must be changed before uid... *)
setresgid setgid setgid setgid;
setresuid setuid setuid setuid;
let path =
(if setuid = 0 then "/usr/local/sbin:/usr/sbin:/sbin:" else "")^
"/usr/local/bin:/usr/bin:/bin" in
Unix.putenv "PATH" path;
Unix.execv cmd arg
end ()
ocaml-extunix-0.3.2/test/testba.ml 0000664 0000000 0000000 00000020654 14045766433 0017127 0 ustar 00root root 0000000 0000000
open OUnit
open ExtUnix.All.BA
module LargeFile = ExtUnix.All.LargeFile.BA
let with_unix_error f () =
try
f ()
with
| Unix.Unix_error(e,f,a) ->
let message = Printf.sprintf "Unix_error : %s(%s) : %s" f a (Unix.error_message e) in
skip_if (e = Unix.ENOSYS) message; (* libc may raise Not implemented, not an error in extunix *)
assert_failure message
let require feature =
match ExtUnix.All.have feature with
| None -> assert false
| Some present -> skip_if (not present) (Printf.sprintf "%S is not available" feature)
let printer x = x
let test_endian_bigarray () =
require "unsafe_get_int8";
require "unsafe_get_int16";
require "unsafe_get_int31";
require "unsafe_get_int32";
require "unsafe_get_int64";
require "unsafe_get_uint8";
require "unsafe_get_uint16";
require "unsafe_get_uint31";
require "unsafe_get_uint63";
require "unsafe_get_int63";
require "unsafe_set_uint8";
require "unsafe_set_uint16";
require "unsafe_set_uint31";
require "unsafe_set_int8";
require "unsafe_set_int16";
require "unsafe_set_int31";
require "unsafe_set_int32";
require "unsafe_set_uint63";
require "unsafe_set_int63";
require "unsafe_set_int64";
let module B = BigEndian in
let module L = LittleEndian in
let src = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout 18 in
ignore (List.fold_left (fun off x -> Bigarray.Array1.set src off x; off + 1)
0
[0xFF;
0xFF;
0xFE; 0xDC;
0xFE; 0xDC;
0xFE; 0xDC; 0xBA; 0x98;
0xFE; 0xDC; 0xBA; 0x98; 0x76; 0x54; 0x32; 0x10]);
assert_equal (B.get_uint8 src 0) 0xFF;
assert_equal (B.get_int8 src 1) (-0x01);
assert_equal (B.get_uint16 src 2) 0xFEDC;
assert_equal (B.get_int16 src 4) (-0x0124);
assert_equal (B.get_int32 src 6) (0xFEDCBA98l);
assert_equal (B.get_int64 src 10) (0xFEDCBA9876543210L);
assert_equal (L.get_uint8 src 0) 0xFF;
assert_equal (L.get_int8 src 1) (-0x01);
assert_equal (L.get_uint16 src 2) 0xDCFE;
assert_equal (L.get_int16 src 4) (-0x2302);
assert_equal (L.get_int32 src 6) (0x98BADCFEl);
assert_equal (L.get_int64 src 10) (0x1032547698BADCFEL);
assert_equal (B.get_uint31 src 6) (Int64.to_int 0xFEDCBA98L);
assert_equal (B.get_int31 src 6) (Int64.to_int 0x7FFFFFFFFEDCBA98L);
assert_equal (B.get_int31 src 6) (-0x1234568);
assert_equal (B.get_uint63 src 10) (Int64.to_int 0x7EDCBA9876543210L);
assert_equal (B.get_int63 src 10) (Int64.to_int 0x7EDCBA9876543210L);
assert_equal (B.get_int63 src 10) (Int64.to_int (-0x123456789ABCDF0L));
assert_equal (L.get_uint31 src 6) (Int64.to_int 0x98BADCFEL);
assert_equal (L.get_int31 src 6) (Int64.to_int 0x7FFFFFFF98BADCFEL);
assert_equal (L.get_int31 src 6) (-0x67452302);
assert_equal (L.get_uint63 src 10) (Int64.to_int 0x1032547698BADCFEL);
assert_equal (L.get_int63 src 10) (Int64.to_int 0x1032547698BADCFEL);
assert_equal (L.get_int63 src 10) (Int64.to_int (-0x6FCDAB8967452302L));
let b = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout 18 in
B.set_uint8 b 0 0xFF;
B.set_int8 b 1 (-0x01);
B.set_uint16 b 2 0xFEDC;
B.set_uint16 b 4 (-0x0124);
B.set_int32 b 6 (0xFEDCBA98l);
B.set_int64 b 10 (0xFEDCBA9876543210L);
assert_equal b src;
let l = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout 18 in
L.set_uint8 l 0 0xFF;
L.set_int8 l 1 (-0x01);
L.set_uint16 l 2 0xDCFE;
L.set_uint16 l 4 (-0x2302);
L.set_int32 l 6 (0x98BADCFEl);
L.set_int64 l 10 (0x1032547698BADCFEL);
assert_equal l src
let cmp_buf buf c text =
for i = 0 to Bigarray.Array1.dim buf - 1 do
if Bigarray.Array1.get buf i <> (int_of_char c)
then assert_failure text;
done
let test_pread_bigarray () =
require "unsafe_pread";
let name = Filename.temp_file "extunix" "pread" in
let fd =
Unix.openfile name [Unix.O_RDWR] 0
in
try
let size = 65536 in
let s = String.make size 'x' in
assert_equal (Unix.write_substring fd s 0 size) size;
let t = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout size in
assert_equal (pread fd 0 t) size;
cmp_buf t 'x' "pread read bad data";
assert_equal (single_pread fd 0 t) size;
cmp_buf t 'x' "pread read bad data";
let t = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout size in
assert_equal (LargeFile.pread fd Int64.zero t) size;
cmp_buf t 'x' "Largefile.pread read bad data";
assert_equal (LargeFile.single_pread fd Int64.zero t) size;
cmp_buf t 'x' "Largefile.single_pread read bad data";
Unix.close fd;
Unix.unlink name
with exn -> Unix.close fd; Unix.unlink name; raise exn
let cmp_bytes str c text =
for i = 0 to Bytes.length str - 1 do
if Bytes.get str i <> c
then assert_failure text;
done
let test_pwrite_bigarray () =
require "unsafe_pwrite";
let name = Filename.temp_file "extunix" "pwrite" in
let fd =
Unix.openfile name [Unix.O_RDWR] 0
in
let read dst =
assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0;
let rec loop off = function
| 0 -> ()
| size ->
let len = Unix.read fd dst off size
in
loop (off + len) (size - len)
in
loop 0 (Bytes.length dst)
in
try
let size = 65536 in (* Must be larger than UNIX_BUFFER_SIZE (16384) *)
let s = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout size in
for i = 0 to size - 1 do
Bigarray.Array1.set s i (int_of_char 'x');
done;
assert_equal (pwrite fd 0 s) size;
let t = Bytes.make size ' ' in
read t;
cmp_bytes t 'x' "pwrite wrote bad data";
assert_equal (single_pwrite fd 0 s) size;
read t;
cmp_bytes t 'x' "single_pwrite wrote bad data";
for i = 0 to size - 1 do
Bigarray.Array1.set s i (int_of_char 'y');
done;
assert_equal (LargeFile.pwrite fd Int64.zero s) size;
read t;
cmp_bytes t 'y' "Largefile.pwrite wrote bad data";
assert_equal (LargeFile.single_pwrite fd Int64.zero s) size;
read t;
cmp_bytes t 'y' "Largefile.single_pwrite wrote bad data";
Unix.close fd;
Unix.unlink name
with exn -> Unix.close fd; Unix.unlink name; raise exn
let test_substr () =
let arr = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout 12 in
set_substr arr 0 "Hell";
set_substr arr 4 "o World!";
assert_equal (get_substr arr 0 6) "Hello ";
assert_equal (get_substr arr 6 6) "World!"
let test_read_bigarray () =
require "read";
let name = Filename.temp_file "extunix" "read" in
let fd =
Unix.openfile name [Unix.O_RDWR] 0
in
try
let size = 65536 in
let s = String.make size 'x' in
assert_equal (Unix.write_substring fd s 0 size) size;
let t = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout size in
assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0;
assert_equal (read fd t) size;
cmp_buf t 'x' "read read bad data";
assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0;
assert_equal (single_read fd t) size;
cmp_buf t 'x' "single_read read bad data";
Unix.close fd;
Unix.unlink name
with exn -> Unix.close fd; Unix.unlink name; raise exn
let test_write_bigarray () =
require "write";
let name = Filename.temp_file "extunix" "write" in
let fd =
Unix.openfile name [Unix.O_RDWR] 0
in
let read dst =
assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0;
let rec loop off = function
| 0 -> ()
| size ->
let len = Unix.read fd dst off size
in
loop (off + len) (size - len)
in
loop 0 (Bytes.length dst)
in
try
let size = 65536 in (* Must be larger than UNIX_BUFFER_SIZE (16384) *)
let s = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout size in
for i = 0 to size - 1 do
Bigarray.Array1.set s i (int_of_char 'x');
done;
assert_equal (write fd s) size;
let t = Bytes.make size ' ' in
read t;
cmp_bytes t 'x' "write wrote bad data";
assert_equal (single_write fd s) size;
read t;
cmp_bytes t 'x' "write wrote bad data";
Unix.close fd;
Unix.unlink name
with exn -> Unix.close fd; Unix.unlink name; raise exn
let () =
let wrap test =
with_unix_error (fun () -> test (); Gc.compact ())
in
let tests = ("tests" >::: [
"endian_bigrray" >:: test_endian_bigarray;
"pread_bigarray" >:: test_pread_bigarray;
"pwrite_bigarray" >:: test_pwrite_bigarray;
"substr" >:: test_substr;
"read_bigarray" >:: test_read_bigarray;
"write_bigarray" >:: test_write_bigarray;
]) in
ignore (run_test_tt_main (test_decorate wrap tests))