pax_global_header00006660000000000000000000000064121263710620014512gustar00rootroot0000000000000052 comment=55ab3aecde3fd64984d7c07d5d03376ee8886755 ocaml-extunix-0.0.6/000077500000000000000000000000001212637106200143125ustar00rootroot00000000000000ocaml-extunix-0.0.6/.gitignore000066400000000000000000000001241212637106200162770ustar00rootroot00000000000000_build *.native *.byte *.docdir setup.data setup.log src/config.* web/index.html *~ ocaml-extunix-0.0.6/CHANGES.txt000066400000000000000000000051221212637106200161230ustar00rootroot000000000000000.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 0.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) 0.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 0.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 0.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 0.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.0.6/Makefile000066400000000000000000000016371212637106200157610ustar00rootroot00000000000000# OASIS_START # DO NOT EDIT (digest: bc1e05bfc8b39b664f29dae8dbd3ebbb) SETUP = ocaml setup.ml build: setup.data $(SETUP) -build $(BUILDFLAGS) doc: setup.data build $(SETUP) -doc $(DOCFLAGS) test: setup.data build $(SETUP) -test $(TESTFLAGS) all: $(SETUP) -all $(ALLFLAGS) install: setup.data $(SETUP) -install $(INSTALLFLAGS) uninstall: setup.data $(SETUP) -uninstall $(UNINSTALLFLAGS) reinstall: setup.data $(SETUP) -reinstall $(REINSTALLFLAGS) clean: $(SETUP) -clean $(CLEANFLAGS) distclean: $(SETUP) -distclean $(DISTCLEANFLAGS) setup.data: $(SETUP) -configure $(CONFIGUREFLAGS) .PHONY: build doc test all install uninstall reinstall clean distclean configure # OASIS_STOP VERSION=$(shell oasis query version) NAME=ocaml-extunix-$(VERSION) .PHONY: release release: git tag -a -m $(VERSION) v$(VERSION) git archive --prefix=$(NAME)/ v$(VERSION) | gzip > $(NAME).tar.gz gpg -a -b $(NAME).tar.gz ocaml-extunix-0.0.6/README.txt000066400000000000000000000110641212637106200160120ustar00rootroot00000000000000 ExtUnix OCaml library ===================== 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: http://extunix.forge.ocamlcore.org/ Why? ---- Currently, everybody writes his own bindings to fulfil particular needs. 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" to know what kind of system API we can integrate. Installation ------------ Dependencies : * ocaml and ocamlfind for build and installation * (optional) oUnit for tests (configure with --enable-tests) Build and install : ./configure make make install Alternatively use the underlying OASIS build system directly (plain ocaml, no sh and make needed) : ocaml setup.ml -configure ocaml setup.ml -build ocaml setup.ml -install See other available targets : ocaml setup.ml -help Usage example : $ ocaml # #use "topfind";; # #require "extunix";; # module U = ExtUnix.Specific;; # U.ttyname Unix.stdout;; - : string = "/dev/pts/8" Run unit tests : ./configure --enable-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: * src/discover.ml 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 config.ml describes the same features for the ocaml syntax extension src/pa_have.ml, which preprocesses src/extUnix.mlpp and generates two modules : ExtUnixAll where bindings to missing functions are rewritten to raise exception and ExtUnixSpecific which drops bindings to missing functions. 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 src/discover.ml * Add the path to C bindings to _oasis CSources and run `oasis setup` * Add the OCaml code to src/extUnix.mlpp guarded with HAVE ... END * Add some tests to test/test.ml * Add note to CHANGES.txt * Run ./configure && make Checklist for release --------------------- * Review `git log` and update CHANGES.txt * Update version in _oasis and `oasis setup` * Commit * `make release` * Upload (forge and oasis-db) and update download links on web page * Commit Development ----------- Many people contribute to extunix. Please submit your patches and/or feature requests to project bugtracker at : https://forge.ocamlcore.org/tracker/?group_id=175 Current maintainer is reachable at : mailto:ygrek@autistici.org xmpp:ygrek@jabber.kiev.ua ocaml-extunix-0.0.6/TODO000066400000000000000000000013541212637106200150050ustar00rootroot00000000000000* comments: mark "emulated" (windows) functions * unsetenv winapi? see http://old.nabble.com/-patch--(msvc)-use-more-modern-facilities-for-setenv()-unsetenv()-td15877005.html * INRIA request for extended UNIX: http://caml.inria.fr/mantis/view.php?id=5063 (DONE) http://caml.inria.fr/mantis/view.php?id=2533 (DONE) http://caml.inria.fr/mantis/view.php?id=3851 (DONE) http://caml.inria.fr/mantis/view.php?id=480 (DONE) * investigate F_FULLFSYNC fcntl and fsync on Mac OS Wanted functions: * 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) * mkdtemp (see Jane Street Core) (DONE) ocaml-extunix-0.0.6/_oasis000066400000000000000000000055601212637106200155200ustar00rootroot00000000000000OASISFormat: 0.3 Name: extunix Version: 0.0.6 License: LGPL-2.1 with OCaml linking exception Authors: ygrek, Sylvain Le Gall, Stéphane Glondu, Kaustuv Chaudhuri, Joshua Smith, Niki Yoshiuchi, Gerd Stolpmann, Goswin von Brederlow, Andre Nathan, Zhenya Lykhovyd Copyrights: (C) 2010 ygrek, (C) 2009 Sylvain Le Gall, (C) 2008-2009 Talend Inc., (C) 2010 Stéphane Glondu, (C) 2005 Joshua Smith, (C) 2010 Niki Yoshiuchi, (C) 2001 Gerd Stolpmann, (C) 2012 Goswin von Brederlow, (C) 2012 Andre Nathan, (C) 2013 Zhenya Lykhovyd Homepage: http://extunix.forge.ocamlcore.org/ BuildTools: ocamlbuild, camlp4 Plugins: DevFiles (0.3), META (0.3) Synopsis: Extended functions for OCaml Unix module Description: Thin bindings to various low-level system APIs (often non-portable) which are not covered by Unix module. . Some of the implemented functions : uname, statvfs, fsync, fadvise, fallocate, openat, dirfd, eventfd, signalfd, setrlimit, mlockall, etc PostConfCommand: ocaml src/discover.ml -ocamlc $ocamlc -ext_obj $ext_obj PreDistCleanCommand: $rm $(utoh "src/config.h") PostDistCleanCommand: $rm $(utoh "src/config.ml") # [FORGE#742] Flag strict Description: Strict compile-time checks Default: true Library extunix Path: src/ Modules: ExtUnix InternalModules: ExtUnixAll, ExtUnixSpecific if flag(strict) && ccomp_type(cc) CCOpt: -std=c89 -pedantic -Wno-long-long -Wextra CSources: config.h, eventfd.c, dirfd.c, fsync.c, statvfs.c, atfile.c, ioctl_siocgifconf.c, uname.c, fadvise.c, fallocate.c, tty_ioctl.c, unistd.c, stdlib.c, signalfd.c, ptrace.c, resource.c, mman.c, time.c, pts.c, execinfo.c, malloc.c, endian.c, read_cred.c, fexecve.c, sendmsg.c, memalign.c, endianba.c, pread_pwrite_ba.c, bigarray.c, common.c, common.h BuildDepends: unix, bigarray Executable test Path: test/ Install: false Build$: flag(tests) Custom: true CompiledObject: best MainIs: test.ml BuildDepends: extunix, oUnit (>= 1.0.3) Executable testba Path: test/ Install: false Build$: flag(tests) Custom: true CompiledObject: best MainIs: testba.ml BuildDepends: extunix, oUnit (>= 1.0.3) Test main Command: $test && $testba TestTools: test, testba Document api Title: API reference for extunix Type: ocamlbuild (0.3) Authors: ygrek, Sylvain Le Gall, Stéphane Glondu, Kaustuv Chaudhuri, Joshua Smith, Niki Yoshiuchi, Gerd Stolpmann, Goswin von Brederlow, Andre Nathan, Zhenya Lykhovyd BuildTools: ocamldoc Format: HTML Index: index.html XOCamlbuildPath: src/ XOCamlbuildLibraries: extunix XOCamlbuildModules: ExtUnixAll, ExtUnixSpecific #Document changelog # Title: Changelog # Path: CHANGES.txt ocaml-extunix-0.0.6/_tags000066400000000000000000000101711212637106200153320ustar00rootroot00000000000000# OASIS_START # DO NOT EDIT (digest: 3a2d5131b70c6e1fccdb074c36605a87) # Ignore VCS directories, you can use the same kind of rule outside # OASIS_START/STOP if you want to exclude directories that contains # useless stuff for the build process <**/.svn>: -traverse <**/.svn>: not_hygienic ".bzr": -traverse ".bzr": not_hygienic ".hg": -traverse ".hg": not_hygienic ".git": -traverse ".git": not_hygienic "_darcs": -traverse "_darcs": not_hygienic # Library extunix "src/extunix.cmxs": use_extunix : oasis_library_extunix_ccopt "src/eventfd.c": oasis_library_extunix_ccopt "src/dirfd.c": oasis_library_extunix_ccopt "src/fsync.c": oasis_library_extunix_ccopt "src/statvfs.c": oasis_library_extunix_ccopt "src/atfile.c": oasis_library_extunix_ccopt "src/ioctl_siocgifconf.c": oasis_library_extunix_ccopt "src/uname.c": oasis_library_extunix_ccopt "src/fadvise.c": oasis_library_extunix_ccopt "src/fallocate.c": oasis_library_extunix_ccopt "src/tty_ioctl.c": oasis_library_extunix_ccopt "src/unistd.c": oasis_library_extunix_ccopt "src/stdlib.c": oasis_library_extunix_ccopt "src/signalfd.c": oasis_library_extunix_ccopt "src/ptrace.c": oasis_library_extunix_ccopt "src/resource.c": oasis_library_extunix_ccopt "src/mman.c": oasis_library_extunix_ccopt "src/time.c": oasis_library_extunix_ccopt "src/pts.c": oasis_library_extunix_ccopt "src/execinfo.c": oasis_library_extunix_ccopt "src/malloc.c": oasis_library_extunix_ccopt "src/endian.c": oasis_library_extunix_ccopt "src/read_cred.c": oasis_library_extunix_ccopt "src/fexecve.c": oasis_library_extunix_ccopt "src/sendmsg.c": oasis_library_extunix_ccopt "src/memalign.c": oasis_library_extunix_ccopt "src/endianba.c": oasis_library_extunix_ccopt "src/pread_pwrite_ba.c": oasis_library_extunix_ccopt "src/bigarray.c": oasis_library_extunix_ccopt "src/common.c": oasis_library_extunix_ccopt : use_libextunix_stubs : pkg_unix : pkg_bigarray "src/eventfd.c": pkg_unix "src/eventfd.c": pkg_bigarray "src/dirfd.c": pkg_unix "src/dirfd.c": pkg_bigarray "src/fsync.c": pkg_unix "src/fsync.c": pkg_bigarray "src/statvfs.c": pkg_unix "src/statvfs.c": pkg_bigarray "src/atfile.c": pkg_unix "src/atfile.c": pkg_bigarray "src/ioctl_siocgifconf.c": pkg_unix "src/ioctl_siocgifconf.c": pkg_bigarray "src/uname.c": pkg_unix "src/uname.c": pkg_bigarray "src/fadvise.c": pkg_unix "src/fadvise.c": pkg_bigarray "src/fallocate.c": pkg_unix "src/fallocate.c": pkg_bigarray "src/tty_ioctl.c": pkg_unix "src/tty_ioctl.c": pkg_bigarray "src/unistd.c": pkg_unix "src/unistd.c": pkg_bigarray "src/stdlib.c": pkg_unix "src/stdlib.c": pkg_bigarray "src/signalfd.c": pkg_unix "src/signalfd.c": pkg_bigarray "src/ptrace.c": pkg_unix "src/ptrace.c": pkg_bigarray "src/resource.c": pkg_unix "src/resource.c": pkg_bigarray "src/mman.c": pkg_unix "src/mman.c": pkg_bigarray "src/time.c": pkg_unix "src/time.c": pkg_bigarray "src/pts.c": pkg_unix "src/pts.c": pkg_bigarray "src/execinfo.c": pkg_unix "src/execinfo.c": pkg_bigarray "src/malloc.c": pkg_unix "src/malloc.c": pkg_bigarray "src/endian.c": pkg_unix "src/endian.c": pkg_bigarray "src/read_cred.c": pkg_unix "src/read_cred.c": pkg_bigarray "src/fexecve.c": pkg_unix "src/fexecve.c": pkg_bigarray "src/sendmsg.c": pkg_unix "src/sendmsg.c": pkg_bigarray "src/memalign.c": pkg_unix "src/memalign.c": pkg_bigarray "src/endianba.c": pkg_unix "src/endianba.c": pkg_bigarray "src/pread_pwrite_ba.c": pkg_unix "src/pread_pwrite_ba.c": pkg_bigarray "src/bigarray.c": pkg_unix "src/bigarray.c": pkg_bigarray "src/common.c": pkg_unix "src/common.c": pkg_bigarray # Executable test : use_extunix : pkg_oUnit : pkg_unix : pkg_bigarray : custom # Executable testba : use_extunix : pkg_oUnit : pkg_unix : pkg_bigarray : use_extunix : pkg_oUnit : pkg_unix : pkg_bigarray : custom # OASIS_STOP "src/pa_have.ml": pkg_camlp4.quotations.r, pkg_camlp4.extend, syntax_camlp4o ocaml-extunix-0.0.6/configure000077500000000000000000000005541212637106200162250ustar00rootroot00000000000000#!/bin/sh # OASIS_START # DO NOT EDIT (digest: 425187ed8bfdbdd207fd76392dd243a7) set -e FST=true for i in "$@"; do if $FST; then set -- FST=false fi case $i in --*=*) ARG=${i%%=*} VAL=${i##*=} set -- "$@" "$ARG" "$VAL" ;; *) set -- "$@" "$i" ;; esac done ocaml setup.ml -configure "$@" # OASIS_STOP ocaml-extunix-0.0.6/myocamlbuild.ml000066400000000000000000000353531212637106200173360ustar00rootroot00000000000000(* OASIS_START *) (* DO NOT EDIT (digest: 48f38f82304e2f380f35873de2367b4c) *) module OASISGettext = struct (* # 21 "src/oasis/OASISGettext.ml" *) let ns_ str = str let s_ str = str let f_ (str : ('a, 'b, 'c, 'd) format4) = str let fn_ fmt1 fmt2 n = if n = 1 then fmt1^^"" else fmt2^^"" let init = [] end module OASISExpr = struct (* # 21 "src/oasis/OASISExpr.ml" *) open OASISGettext type test = string type flag = string type t = | EBool of bool | ENot of t | EAnd of t * t | EOr of t * t | EFlag of flag | ETest of test * string type 'a choices = (t * 'a) list let eval var_get t = let rec eval' = function | EBool b -> b | ENot e -> not (eval' e) | EAnd (e1, e2) -> (eval' e1) && (eval' e2) | EOr (e1, e2) -> (eval' e1) || (eval' e2) | EFlag nm -> let v = var_get nm in assert(v = "true" || v = "false"); (v = "true") | ETest (nm, vl) -> let v = var_get nm in (v = vl) in eval' t let choose ?printer ?name var_get lst = let rec choose_aux = function | (cond, vl) :: tl -> if eval var_get cond then vl else choose_aux tl | [] -> let str_lst = if lst = [] then s_ "" else String.concat (s_ ", ") (List.map (fun (cond, vl) -> match printer with | Some p -> p vl | None -> s_ "") lst) in match name with | Some nm -> failwith (Printf.sprintf (f_ "No result for the choice list '%s': %s") nm str_lst) | None -> failwith (Printf.sprintf (f_ "No result for a choice list: %s") str_lst) in choose_aux (List.rev lst) end # 117 "myocamlbuild.ml" module BaseEnvLight = struct (* # 21 "src/base/BaseEnvLight.ml" *) module MapString = Map.Make(String) type t = string MapString.t let default_filename = Filename.concat (Sys.getcwd ()) "setup.data" let load ?(allow_empty=false) ?(filename=default_filename) () = if Sys.file_exists filename then begin let chn = open_in_bin filename in let st = Stream.of_channel chn in let line = ref 1 in let st_line = Stream.from (fun _ -> try match Stream.next st with | '\n' -> incr line; Some '\n' | c -> Some c with Stream.Failure -> None) in let lexer = Genlex.make_lexer ["="] st_line in let rec read_file mp = match Stream.npeek 3 lexer with | [Genlex.Ident nm; Genlex.Kwd "="; Genlex.String value] -> Stream.junk lexer; Stream.junk lexer; Stream.junk lexer; read_file (MapString.add nm value mp) | [] -> mp | _ -> failwith (Printf.sprintf "Malformed data file '%s' line %d" filename !line) in let mp = read_file MapString.empty in close_in chn; mp end else if allow_empty then begin MapString.empty end else begin failwith (Printf.sprintf "Unable to load environment, the file '%s' doesn't exist." filename) end let var_get name env = let rec var_expand str = let buff = Buffer.create ((String.length str) * 2) in Buffer.add_substitute buff (fun var -> try var_expand (MapString.find var env) with Not_found -> failwith (Printf.sprintf "No variable %s defined when trying to expand %S." var str)) str; Buffer.contents buff in var_expand (MapString.find name env) let var_choose lst env = OASISExpr.choose (fun nm -> var_get nm env) lst end # 215 "myocamlbuild.ml" module MyOCamlbuildFindlib = struct (* # 21 "src/plugins/ocamlbuild/MyOCamlbuildFindlib.ml" *) (** OCamlbuild extension, copied from * http://brion.inria.fr/gallium/index.php/Using_ocamlfind_with_ocamlbuild * by N. Pouillard and others * * Updated on 2009/02/28 * * Modified by Sylvain Le Gall *) open Ocamlbuild_plugin (* these functions are not really officially exported *) let run_and_read = Ocamlbuild_pack.My_unix.run_and_read let blank_sep_strings = Ocamlbuild_pack.Lexers.blank_sep_strings let split s ch = let x = ref [] in let rec go s = let pos = String.index s ch in x := (String.before s pos)::!x; go (String.after s (pos + 1)) in try go s with Not_found -> !x let split_nl s = split s '\n' let before_space s = try String.before s (String.index s ' ') with Not_found -> s (* this lists all supported packages *) let find_packages () = List.map before_space (split_nl & run_and_read "ocamlfind list") (* this is supposed to list available syntaxes, but I don't know how to do it. *) let find_syntaxes () = ["camlp4o"; "camlp4r"] (* ocamlfind command *) let ocamlfind x = S[A"ocamlfind"; x] let dispatch = function | Before_options -> (* by using Before_options one let command line options have an higher priority *) (* on the contrary using After_options will guarantee to have the higher priority *) (* override default commands by ocamlfind ones *) Options.ocamlc := ocamlfind & A"ocamlc"; Options.ocamlopt := ocamlfind & A"ocamlopt"; Options.ocamldep := ocamlfind & A"ocamldep"; Options.ocamldoc := ocamlfind & A"ocamldoc"; Options.ocamlmktop := ocamlfind & A"ocamlmktop" | After_rules -> (* When one link an OCaml library/binary/package, one should use -linkpkg *) flag ["ocaml"; "link"; "program"] & A"-linkpkg"; (* For each ocamlfind package one inject the -package option when * compiling, computing dependencies, generating documentation and * linking. *) List.iter begin fun pkg -> flag ["ocaml"; "compile"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "ocamldep"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "doc"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "link"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "infer_interface"; "pkg_"^pkg] & S[A"-package"; A pkg]; end (find_packages ()); (* Like -package but for extensions syntax. Morover -syntax is useless * when linking. *) List.iter begin fun syntax -> flag ["ocaml"; "compile"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "ocamldep"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "doc"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "infer_interface"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; end (find_syntaxes ()); (* The default "thread" tag is not compatible with ocamlfind. * Indeed, the default rules add the "threads.cma" or "threads.cmxa" * options when using this tag. When using the "-linkpkg" option with * ocamlfind, this module will then be added twice on the command line. * * To solve this, one approach is to add the "-thread" option when using * the "threads" package using the previous plugin. *) flag ["ocaml"; "pkg_threads"; "compile"] (S[A "-thread"]); flag ["ocaml"; "pkg_threads"; "doc"] (S[A "-I"; A "+threads"]); flag ["ocaml"; "pkg_threads"; "link"] (S[A "-thread"]); flag ["ocaml"; "pkg_threads"; "infer_interface"] (S[A "-thread"]) | _ -> () end module MyOCamlbuildBase = struct (* # 21 "src/plugins/ocamlbuild/MyOCamlbuildBase.ml" *) (** Base functions for writing myocamlbuild.ml @author Sylvain Le Gall *) open Ocamlbuild_plugin module OC = Ocamlbuild_pack.Ocaml_compiler type dir = string type file = string type name = string type tag = string (* # 56 "src/plugins/ocamlbuild/MyOCamlbuildBase.ml" *) type t = { lib_ocaml: (name * dir list) list; lib_c: (name * dir * file list) list; flags: (tag list * (spec OASISExpr.choices)) list; (* Replace the 'dir: include' from _tags by a precise interdepends in * directory. *) includes: (dir * dir list) list; } let env_filename = Pathname.basename BaseEnvLight.default_filename let dispatch_combine lst = fun e -> List.iter (fun dispatch -> dispatch e) lst let tag_libstubs nm = "use_lib"^nm^"_stubs" let nm_libstubs nm = nm^"_stubs" let dispatch t e = let env = BaseEnvLight.load ~filename:env_filename ~allow_empty:true () in match e with | Before_options -> let no_trailing_dot s = if String.length s >= 1 && s.[0] = '.' then String.sub s 1 ((String.length s) - 1) else s in List.iter (fun (opt, var) -> try opt := no_trailing_dot (BaseEnvLight.var_get var env) with Not_found -> Printf.eprintf "W: Cannot get variable %s" var) [ Options.ext_obj, "ext_obj"; Options.ext_lib, "ext_lib"; Options.ext_dll, "ext_dll"; ] | After_rules -> (* Declare OCaml libraries *) List.iter (function | nm, [] -> ocaml_lib nm | nm, dir :: tl -> ocaml_lib ~dir:dir (dir^"/"^nm); List.iter (fun dir -> List.iter (fun str -> flag ["ocaml"; "use_"^nm; str] (S[A"-I"; P dir])) ["compile"; "infer_interface"; "doc"]) tl) t.lib_ocaml; (* Declare directories dependencies, replace "include" in _tags. *) List.iter (fun (dir, include_dirs) -> Pathname.define_context dir include_dirs) t.includes; (* Declare C libraries *) List.iter (fun (lib, dir, headers) -> (* Handle C part of library *) flag ["link"; "library"; "ocaml"; "byte"; tag_libstubs lib] (S[A"-dllib"; A("-l"^(nm_libstubs lib)); A"-cclib"; A("-l"^(nm_libstubs lib))]); flag ["link"; "library"; "ocaml"; "native"; tag_libstubs lib] (S[A"-cclib"; A("-l"^(nm_libstubs lib))]); flag ["link"; "program"; "ocaml"; "byte"; tag_libstubs lib] (S[A"-dllib"; A("dll"^(nm_libstubs lib))]); (* When ocaml link something that use the C library, then one need that file to be up to date. *) dep ["link"; "ocaml"; "program"; tag_libstubs lib] [dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)]; dep ["compile"; "ocaml"; "program"; tag_libstubs lib] [dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)]; (* TODO: be more specific about what depends on headers *) (* Depends on .h files *) dep ["compile"; "c"] headers; (* Setup search path for lib *) flag ["link"; "ocaml"; "use_"^lib] (S[A"-I"; P(dir)]); ) t.lib_c; (* Add flags *) List.iter (fun (tags, cond_specs) -> let spec = BaseEnvLight.var_choose cond_specs env in flag tags & spec) t.flags | _ -> () let dispatch_default t = dispatch_combine [ dispatch t; MyOCamlbuildFindlib.dispatch; ] end # 476 "myocamlbuild.ml" open Ocamlbuild_plugin;; let package_default = { MyOCamlbuildBase.lib_ocaml = [("extunix", ["src"])]; lib_c = [("extunix", "src/", ["src/config.h"; "src/common.h"])]; flags = [ (["oasis_library_extunix_ccopt"; "compile"], [ (OASISExpr.EBool true, S []); (OASISExpr.EAnd (OASISExpr.EFlag "strict", OASISExpr.ETest ("ccomp_type", "cc")), S [ A "-ccopt"; A "-std=c89"; A "-ccopt"; A "-pedantic"; A "-ccopt"; A "-Wno-long-long"; A "-ccopt"; A "-Wextra" ]) ]) ]; includes = [("test", ["src"])]; } ;; let dispatch_default = MyOCamlbuildBase.dispatch_default package_default;; # 510 "myocamlbuild.ml" (* OASIS_STOP *) let gen gen_all prod = rule ("generate " ^ if gen_all then "all" else "specific") ~deps:["src/extUnix.mlpp";"src/pa_have.cmo";"src/config.cmo"] ~prod (fun _ _ -> Cmd (S([P"camlp4o"; T (tags_of_pathname "src/extUnix.mlpp"++"ocaml"++"pp"); A "src/config.cmo"; A"src/pa_have.cmo"; A"pr_o.cmo"; A"-impl"; A"src/extUnix.mlpp"; A"-o"; A prod; ] @ if gen_all then [A"-gen-all"] else []))) ;; gen true "src/extUnixAll.ml";; gen false "src/extUnixSpecific.ml";; Ocamlbuild_plugin.dispatch dispatch_default;; ocaml-extunix-0.0.6/setup.ml000066400000000000000000005031011212637106200160040ustar00rootroot00000000000000(* setup.ml generated for the first time by OASIS v0.2.0~alpha1 *) (* OASIS_START *) (* DO NOT EDIT (digest: 06275fd8f4bacbe8c0989ce552b097ab) *) (* Regenerated by OASIS v0.3.0 Visit http://oasis.forge.ocamlcore.org for more information and documentation about functions used in this file. *) module OASISGettext = struct (* # 21 "src/oasis/OASISGettext.ml" *) let ns_ str = str let s_ str = str let f_ (str : ('a, 'b, 'c, 'd) format4) = str let fn_ fmt1 fmt2 n = if n = 1 then fmt1^^"" else fmt2^^"" let init = [] end module OASISContext = struct (* # 21 "src/oasis/OASISContext.ml" *) open OASISGettext type level = [ `Debug | `Info | `Warning | `Error] type t = { quiet: bool; info: bool; debug: bool; ignore_plugins: bool; ignore_unknown_fields: bool; printf: level -> string -> unit; } let printf lvl str = let beg = match lvl with | `Error -> s_ "E: " | `Warning -> s_ "W: " | `Info -> s_ "I: " | `Debug -> s_ "D: " in prerr_endline (beg^str) let default = ref { quiet = false; info = false; debug = false; ignore_plugins = false; ignore_unknown_fields = false; printf = printf; } let quiet = {!default with quiet = true} let args () = ["-quiet", Arg.Unit (fun () -> default := {!default with quiet = true}), (s_ " Run quietly"); "-info", Arg.Unit (fun () -> default := {!default with info = true}), (s_ " Display information message"); "-debug", Arg.Unit (fun () -> default := {!default with debug = true}), (s_ " Output debug message")] end module OASISString = struct (* # 1 "src/oasis/OASISString.ml" *) (** Various string utilities. Mostly inspired by extlib and batteries ExtString and BatString libraries. @author Sylvain Le Gall *) let nsplitf str f = if str = "" then [] else let buf = Buffer.create 13 in let lst = ref [] in let push () = lst := Buffer.contents buf :: !lst; Buffer.clear buf in let str_len = String.length str in for i = 0 to str_len - 1 do if f str.[i] then push () else Buffer.add_char buf str.[i] done; push (); List.rev !lst (** [nsplit c s] Split the string [s] at char [c]. It doesn't include the separator. *) let nsplit str c = nsplitf str ((=) c) let find ~what ?(offset=0) str = let what_idx = ref 0 in let str_idx = ref offset in while !str_idx < String.length str && !what_idx < String.length what do if str.[!str_idx] = what.[!what_idx] then incr what_idx else what_idx := 0; incr str_idx done; if !what_idx <> String.length what then raise Not_found else !str_idx - !what_idx let sub_start str len = let str_len = String.length str in if len >= str_len then "" else String.sub str len (str_len - len) let sub_end ?(offset=0) str len = let str_len = String.length str in if len >= str_len then "" else String.sub str 0 (str_len - len) let starts_with ~what ?(offset=0) str = let what_idx = ref 0 in let str_idx = ref offset in let ok = ref true in while !ok && !str_idx < String.length str && !what_idx < String.length what do if str.[!str_idx] = what.[!what_idx] then incr what_idx else ok := false; incr str_idx done; if !what_idx = String.length what then true else false let strip_starts_with ~what str = if starts_with ~what str then sub_start str (String.length what) else raise Not_found let ends_with ~what ?(offset=0) str = let what_idx = ref ((String.length what) - 1) in let str_idx = ref ((String.length str) - 1) in let ok = ref true in while !ok && offset <= !str_idx && 0 <= !what_idx do if str.[!str_idx] = what.[!what_idx] then decr what_idx else ok := false; decr str_idx done; if !what_idx = -1 then true else false let strip_ends_with ~what str = if ends_with ~what str then sub_end str (String.length what) else raise Not_found let replace_chars f s = let buf = String.make (String.length s) 'X' in for i = 0 to String.length s - 1 do buf.[i] <- f s.[i] done; buf end module OASISUtils = struct (* # 21 "src/oasis/OASISUtils.ml" *) open OASISGettext module MapString = Map.Make(String) let map_string_of_assoc assoc = List.fold_left (fun acc (k, v) -> MapString.add k v acc) MapString.empty assoc module SetString = Set.Make(String) let set_string_add_list st lst = List.fold_left (fun acc e -> SetString.add e acc) st lst let set_string_of_list = set_string_add_list SetString.empty let compare_csl s1 s2 = String.compare (String.lowercase s1) (String.lowercase s2) module HashStringCsl = Hashtbl.Make (struct type t = string let equal s1 s2 = (String.lowercase s1) = (String.lowercase s2) let hash s = Hashtbl.hash (String.lowercase s) end) let varname_of_string ?(hyphen='_') s = if String.length s = 0 then begin invalid_arg "varname_of_string" end else begin let buf = OASISString.replace_chars (fun c -> if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') then c else hyphen) s; in let buf = (* Start with a _ if digit *) if '0' <= s.[0] && s.[0] <= '9' then "_"^buf else buf in String.lowercase buf end let varname_concat ?(hyphen='_') p s = let what = String.make 1 hyphen in let p = try OASISString.strip_ends_with ~what p with Not_found -> p in let s = try OASISString.strip_starts_with ~what s with Not_found -> s in p^what^s let is_varname str = str = varname_of_string str let failwithf fmt = Printf.ksprintf failwith fmt end module PropList = struct (* # 21 "src/oasis/PropList.ml" *) open OASISGettext type name = string exception Not_set of name * string option exception No_printer of name exception Unknown_field of name * name let () = Printexc.register_printer (function | Not_set (nm, Some rsn) -> Some (Printf.sprintf (f_ "Field '%s' is not set: %s") nm rsn) | Not_set (nm, None) -> Some (Printf.sprintf (f_ "Field '%s' is not set") nm) | No_printer nm -> Some (Printf.sprintf (f_ "No default printer for value %s") nm) | Unknown_field (nm, schm) -> Some (Printf.sprintf (f_ "Field %s is not defined in schema %s") nm schm) | _ -> None) module Data = struct type t = (name, unit -> unit) Hashtbl.t let create () = Hashtbl.create 13 let clear t = Hashtbl.clear t (* # 71 "src/oasis/PropList.ml" *) end module Schema = struct type ('ctxt, 'extra) value = { get: Data.t -> string; set: Data.t -> ?context:'ctxt -> string -> unit; help: (unit -> string) option; extra: 'extra; } type ('ctxt, 'extra) t = { name: name; fields: (name, ('ctxt, 'extra) value) Hashtbl.t; order: name Queue.t; name_norm: string -> string; } let create ?(case_insensitive=false) nm = { name = nm; fields = Hashtbl.create 13; order = Queue.create (); name_norm = (if case_insensitive then String.lowercase else fun s -> s); } let add t nm set get extra help = let key = t.name_norm nm in if Hashtbl.mem t.fields key then failwith (Printf.sprintf (f_ "Field '%s' is already defined in schema '%s'") nm t.name); Hashtbl.add t.fields key { set = set; get = get; help = help; extra = extra; }; Queue.add nm t.order let mem t nm = Hashtbl.mem t.fields nm let find t nm = try Hashtbl.find t.fields (t.name_norm nm) with Not_found -> raise (Unknown_field (nm, t.name)) let get t data nm = (find t nm).get data let set t data nm ?context x = (find t nm).set data ?context x let fold f acc t = Queue.fold (fun acc k -> let v = find t k in f acc k v.extra v.help) acc t.order let iter f t = fold (fun () -> f) () t let name t = t.name end module Field = struct type ('ctxt, 'value, 'extra) t = { set: Data.t -> ?context:'ctxt -> 'value -> unit; get: Data.t -> 'value; sets: Data.t -> ?context:'ctxt -> string -> unit; gets: Data.t -> string; help: (unit -> string) option; extra: 'extra; } let new_id = let last_id = ref 0 in fun () -> incr last_id; !last_id let create ?schema ?name ?parse ?print ?default ?update ?help extra = (* Default value container *) let v = ref None in (* If name is not given, create unique one *) let nm = match name with | Some s -> s | None -> Printf.sprintf "_anon_%d" (new_id ()) in (* Last chance to get a value: the default *) let default () = match default with | Some d -> d | None -> raise (Not_set (nm, Some (s_ "no default value"))) in (* Get data *) let get data = (* Get value *) try (Hashtbl.find data nm) (); match !v with | Some x -> x | None -> default () with Not_found -> default () in (* Set data *) let set data ?context x = let x = match update with | Some f -> begin try f ?context (get data) x with Not_set _ -> x end | None -> x in Hashtbl.replace data nm (fun () -> v := Some x) in (* Parse string value, if possible *) let parse = match parse with | Some f -> f | None -> fun ?context s -> failwith (Printf.sprintf (f_ "Cannot parse field '%s' when setting value %S") nm s) in (* Set data, from string *) let sets data ?context s = set ?context data (parse ?context s) in (* Output value as string, if possible *) let print = match print with | Some f -> f | None -> fun _ -> raise (No_printer nm) in (* Get data, as a string *) let gets data = print (get data) in begin match schema with | Some t -> Schema.add t nm sets gets extra help | None -> () end; { set = set; get = get; sets = sets; gets = gets; help = help; extra = extra; } let fset data t ?context x = t.set data ?context x let fget data t = t.get data let fsets data t ?context s = t.sets data ?context s let fgets data t = t.gets data end module FieldRO = struct let create ?schema ?name ?parse ?print ?default ?update ?help extra = let fld = Field.create ?schema ?name ?parse ?print ?default ?update ?help extra in fun data -> Field.fget data fld end end module OASISMessage = struct (* # 21 "src/oasis/OASISMessage.ml" *) open OASISGettext open OASISContext let generic_message ~ctxt lvl fmt = let cond = if ctxt.quiet then false else match lvl with | `Debug -> ctxt.debug | `Info -> ctxt.info | _ -> true in Printf.ksprintf (fun str -> if cond then begin ctxt.printf lvl str end) fmt let debug ~ctxt fmt = generic_message ~ctxt `Debug fmt let info ~ctxt fmt = generic_message ~ctxt `Info fmt let warning ~ctxt fmt = generic_message ~ctxt `Warning fmt let error ~ctxt fmt = generic_message ~ctxt `Error fmt end module OASISVersion = struct (* # 21 "src/oasis/OASISVersion.ml" *) open OASISGettext type s = string type t = string type comparator = | VGreater of t | VGreaterEqual of t | VEqual of t | VLesser of t | VLesserEqual of t | VOr of comparator * comparator | VAnd of comparator * comparator (* Range of allowed characters *) let is_digit c = '0' <= c && c <= '9' let is_alpha c = ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') let is_special = function | '.' | '+' | '-' | '~' -> true | _ -> false let rec version_compare v1 v2 = if v1 <> "" || v2 <> "" then begin (* Compare ascii string, using special meaning for version * related char *) let val_ascii c = if c = '~' then -1 else if is_digit c then 0 else if c = '\000' then 0 else if is_alpha c then Char.code c else (Char.code c) + 256 in let len1 = String.length v1 in let len2 = String.length v2 in let p = ref 0 in (** Compare ascii part *) let compare_vascii () = let cmp = ref 0 in while !cmp = 0 && !p < len1 && !p < len2 && not (is_digit v1.[!p] && is_digit v2.[!p]) do cmp := (val_ascii v1.[!p]) - (val_ascii v2.[!p]); incr p done; if !cmp = 0 && !p < len1 && !p = len2 then val_ascii v1.[!p] else if !cmp = 0 && !p = len1 && !p < len2 then - (val_ascii v2.[!p]) else !cmp in (** Compare digit part *) let compare_digit () = let extract_int v p = let start_p = !p in while !p < String.length v && is_digit v.[!p] do incr p done; let substr = String.sub v !p ((String.length v) - !p) in let res = match String.sub v start_p (!p - start_p) with | "" -> 0 | s -> int_of_string s in res, substr in let i1, tl1 = extract_int v1 (ref !p) in let i2, tl2 = extract_int v2 (ref !p) in i1 - i2, tl1, tl2 in match compare_vascii () with | 0 -> begin match compare_digit () with | 0, tl1, tl2 -> if tl1 <> "" && is_digit tl1.[0] then 1 else if tl2 <> "" && is_digit tl2.[0] then -1 else version_compare tl1 tl2 | n, _, _ -> n end | n -> n end else begin 0 end let version_of_string str = str let string_of_version t = t let chop t = try let pos = String.rindex t '.' in String.sub t 0 pos with Not_found -> t let rec comparator_apply v op = match op with | VGreater cv -> (version_compare v cv) > 0 | VGreaterEqual cv -> (version_compare v cv) >= 0 | VLesser cv -> (version_compare v cv) < 0 | VLesserEqual cv -> (version_compare v cv) <= 0 | VEqual cv -> (version_compare v cv) = 0 | VOr (op1, op2) -> (comparator_apply v op1) || (comparator_apply v op2) | VAnd (op1, op2) -> (comparator_apply v op1) && (comparator_apply v op2) let rec string_of_comparator = function | VGreater v -> "> "^(string_of_version v) | VEqual v -> "= "^(string_of_version v) | VLesser v -> "< "^(string_of_version v) | VGreaterEqual v -> ">= "^(string_of_version v) | VLesserEqual v -> "<= "^(string_of_version v) | VOr (c1, c2) -> (string_of_comparator c1)^" || "^(string_of_comparator c2) | VAnd (c1, c2) -> (string_of_comparator c1)^" && "^(string_of_comparator c2) let rec varname_of_comparator = let concat p v = OASISUtils.varname_concat p (OASISUtils.varname_of_string (string_of_version v)) in function | VGreater v -> concat "gt" v | VLesser v -> concat "lt" v | VEqual v -> concat "eq" v | VGreaterEqual v -> concat "ge" v | VLesserEqual v -> concat "le" v | VOr (c1, c2) -> (varname_of_comparator c1)^"_or_"^(varname_of_comparator c2) | VAnd (c1, c2) -> (varname_of_comparator c1)^"_and_"^(varname_of_comparator c2) let version_0_3_or_after t = comparator_apply t (VGreaterEqual (string_of_version "0.3")) end module OASISLicense = struct (* # 21 "src/oasis/OASISLicense.ml" *) (** License for _oasis fields @author Sylvain Le Gall *) type license = string type license_exception = string type license_version = | Version of OASISVersion.t | VersionOrLater of OASISVersion.t | NoVersion type license_dep_5_unit = { license: license; excption: license_exception option; version: license_version; } type license_dep_5 = | DEP5Unit of license_dep_5_unit | DEP5Or of license_dep_5 list | DEP5And of license_dep_5 list type t = | DEP5License of license_dep_5 | OtherLicense of string (* URL *) end module OASISExpr = struct (* # 21 "src/oasis/OASISExpr.ml" *) open OASISGettext type test = string type flag = string type t = | EBool of bool | ENot of t | EAnd of t * t | EOr of t * t | EFlag of flag | ETest of test * string type 'a choices = (t * 'a) list let eval var_get t = let rec eval' = function | EBool b -> b | ENot e -> not (eval' e) | EAnd (e1, e2) -> (eval' e1) && (eval' e2) | EOr (e1, e2) -> (eval' e1) || (eval' e2) | EFlag nm -> let v = var_get nm in assert(v = "true" || v = "false"); (v = "true") | ETest (nm, vl) -> let v = var_get nm in (v = vl) in eval' t let choose ?printer ?name var_get lst = let rec choose_aux = function | (cond, vl) :: tl -> if eval var_get cond then vl else choose_aux tl | [] -> let str_lst = if lst = [] then s_ "" else String.concat (s_ ", ") (List.map (fun (cond, vl) -> match printer with | Some p -> p vl | None -> s_ "") lst) in match name with | Some nm -> failwith (Printf.sprintf (f_ "No result for the choice list '%s': %s") nm str_lst) | None -> failwith (Printf.sprintf (f_ "No result for a choice list: %s") str_lst) in choose_aux (List.rev lst) end module OASISTypes = struct (* # 21 "src/oasis/OASISTypes.ml" *) type name = string type package_name = string type url = string type unix_dirname = string type unix_filename = string type host_dirname = string type host_filename = string type prog = string type arg = string type args = string list type command_line = (prog * arg list) type findlib_name = string type findlib_full = string type compiled_object = | Byte | Native | Best type dependency = | FindlibPackage of findlib_full * OASISVersion.comparator option | InternalLibrary of name type tool = | ExternalTool of name | InternalExecutable of name type vcs = | Darcs | Git | Svn | Cvs | Hg | Bzr | Arch | Monotone | OtherVCS of url type plugin_kind = [ `Configure | `Build | `Doc | `Test | `Install | `Extra ] type plugin_data_purpose = [ `Configure | `Build | `Install | `Clean | `Distclean | `Install | `Uninstall | `Test | `Doc | `Extra | `Other of string ] type 'a plugin = 'a * name * OASISVersion.t option type all_plugin = plugin_kind plugin type plugin_data = (all_plugin * plugin_data_purpose * (unit -> unit)) list (* # 102 "src/oasis/OASISTypes.ml" *) type 'a conditional = 'a OASISExpr.choices type custom = { pre_command: (command_line option) conditional; post_command: (command_line option) conditional; } type common_section = { cs_name: name; cs_data: PropList.Data.t; cs_plugin_data: plugin_data; } type build_section = { bs_build: bool conditional; bs_install: bool conditional; bs_path: unix_dirname; bs_compiled_object: compiled_object; bs_build_depends: dependency list; bs_build_tools: tool list; bs_c_sources: unix_filename list; bs_data_files: (unix_filename * unix_filename option) list; bs_ccopt: args conditional; bs_cclib: args conditional; bs_dlllib: args conditional; bs_dllpath: args conditional; bs_byteopt: args conditional; bs_nativeopt: args conditional; } type library = { lib_modules: string list; lib_pack: bool; lib_internal_modules: string list; lib_findlib_parent: findlib_name option; lib_findlib_name: findlib_name option; lib_findlib_containers: findlib_name list; } type executable = { exec_custom: bool; exec_main_is: unix_filename; } type flag = { flag_description: string option; flag_default: bool conditional; } type source_repository = { src_repo_type: vcs; src_repo_location: url; src_repo_browser: url option; src_repo_module: string option; src_repo_branch: string option; src_repo_tag: string option; src_repo_subdir: unix_filename option; } type test = { test_type: [`Test] plugin; test_command: command_line conditional; test_custom: custom; test_working_directory: unix_filename option; test_run: bool conditional; test_tools: tool list; } type doc_format = | HTML of unix_filename | DocText | PDF | PostScript | Info of unix_filename | DVI | OtherDoc type doc = { doc_type: [`Doc] plugin; doc_custom: custom; doc_build: bool conditional; doc_install: bool conditional; doc_install_dir: unix_filename; doc_title: string; doc_authors: string list; doc_abstract: string option; doc_format: doc_format; doc_data_files: (unix_filename * unix_filename option) list; doc_build_tools: tool list; } type section = | Library of common_section * build_section * library | Executable of common_section * build_section * executable | Flag of common_section * flag | SrcRepo of common_section * source_repository | Test of common_section * test | Doc of common_section * doc type section_kind = [ `Library | `Executable | `Flag | `SrcRepo | `Test | `Doc ] type package = { oasis_version: OASISVersion.t; ocaml_version: OASISVersion.comparator option; findlib_version: OASISVersion.comparator option; name: package_name; version: OASISVersion.t; license: OASISLicense.t; license_file: unix_filename option; copyrights: string list; maintainers: string list; authors: string list; homepage: url option; synopsis: string; description: string option; categories: url list; conf_type: [`Configure] plugin; conf_custom: custom; build_type: [`Build] plugin; build_custom: custom; install_type: [`Install] plugin; install_custom: custom; uninstall_custom: custom; clean_custom: custom; distclean_custom: custom; files_ab: unix_filename list; sections: section list; plugins: [`Extra] plugin list; schema_data: PropList.Data.t; plugin_data: plugin_data; } end module OASISUnixPath = struct (* # 21 "src/oasis/OASISUnixPath.ml" *) type unix_filename = string type unix_dirname = string type host_filename = string type host_dirname = string let current_dir_name = "." let parent_dir_name = ".." let is_current_dir fn = fn = current_dir_name || fn = "" let concat f1 f2 = if is_current_dir f1 then f2 else let f1' = try OASISString.strip_ends_with ~what:"/" f1 with Not_found -> f1 in f1'^"/"^f2 let make = function | hd :: tl -> List.fold_left (fun f p -> concat f p) hd tl | [] -> invalid_arg "OASISUnixPath.make" let dirname f = try String.sub f 0 (String.rindex f '/') with Not_found -> current_dir_name let basename f = try let pos_start = (String.rindex f '/') + 1 in String.sub f pos_start ((String.length f) - pos_start) with Not_found -> f let chop_extension f = try let last_dot = String.rindex f '.' in let sub = String.sub f 0 last_dot in try let last_slash = String.rindex f '/' in if last_slash < last_dot then sub else f with Not_found -> sub with Not_found -> f let capitalize_file f = let dir = dirname f in let base = basename f in concat dir (String.capitalize base) let uncapitalize_file f = let dir = dirname f in let base = basename f in concat dir (String.uncapitalize base) end module OASISHostPath = struct (* # 21 "src/oasis/OASISHostPath.ml" *) open Filename module Unix = OASISUnixPath let make = function | [] -> invalid_arg "OASISHostPath.make" | hd :: tl -> List.fold_left Filename.concat hd tl let of_unix ufn = if Sys.os_type = "Unix" then ufn else make (List.map (fun p -> if p = Unix.current_dir_name then current_dir_name else if p = Unix.parent_dir_name then parent_dir_name else p) (OASISString.nsplit ufn '/')) end module OASISSection = struct (* # 21 "src/oasis/OASISSection.ml" *) open OASISTypes let section_kind_common = function | Library (cs, _, _) -> `Library, cs | Executable (cs, _, _) -> `Executable, cs | Flag (cs, _) -> `Flag, cs | SrcRepo (cs, _) -> `SrcRepo, cs | Test (cs, _) -> `Test, cs | Doc (cs, _) -> `Doc, cs let section_common sct = snd (section_kind_common sct) let section_common_set cs = function | Library (_, bs, lib) -> Library (cs, bs, lib) | Executable (_, bs, exec) -> Executable (cs, bs, exec) | Flag (_, flg) -> Flag (cs, flg) | SrcRepo (_, src_repo) -> SrcRepo (cs, src_repo) | Test (_, tst) -> Test (cs, tst) | Doc (_, doc) -> Doc (cs, doc) (** Key used to identify section *) let section_id sct = let k, cs = section_kind_common sct in k, cs.cs_name let string_of_section sct = let k, nm = section_id sct in (match k with | `Library -> "library" | `Executable -> "executable" | `Flag -> "flag" | `SrcRepo -> "src repository" | `Test -> "test" | `Doc -> "doc") ^" "^nm let section_find id scts = List.find (fun sct -> id = section_id sct) scts module CSection = struct type t = section let id = section_id let compare t1 t2 = compare (id t1) (id t2) let equal t1 t2 = (id t1) = (id t2) let hash t = Hashtbl.hash (id t) end module MapSection = Map.Make(CSection) module SetSection = Set.Make(CSection) end module OASISBuildSection = struct (* # 21 "src/oasis/OASISBuildSection.ml" *) end module OASISExecutable = struct (* # 21 "src/oasis/OASISExecutable.ml" *) open OASISTypes let unix_exec_is (cs, bs, exec) is_native ext_dll suffix_program = let dir = OASISUnixPath.concat bs.bs_path (OASISUnixPath.dirname exec.exec_main_is) in let is_native_exec = match bs.bs_compiled_object with | Native -> true | Best -> is_native () | Byte -> false in OASISUnixPath.concat dir (cs.cs_name^(suffix_program ())), if not is_native_exec && not exec.exec_custom && bs.bs_c_sources <> [] then Some (dir^"/dll"^cs.cs_name^"_stubs"^(ext_dll ())) else None end module OASISLibrary = struct (* # 21 "src/oasis/OASISLibrary.ml" *) open OASISTypes open OASISUtils open OASISGettext open OASISSection type library_name = name type findlib_part_name = name type 'a map_of_findlib_part_name = 'a OASISUtils.MapString.t exception InternalLibraryNotFound of library_name exception FindlibPackageNotFound of findlib_name type group_t = | Container of findlib_name * group_t list | Package of (findlib_name * common_section * build_section * library * group_t list) (* Look for a module file, considering capitalization or not. *) let find_module source_file_exists (cs, bs, lib) modul = let possible_base_fn = List.map (OASISUnixPath.concat bs.bs_path) [modul; OASISUnixPath.uncapitalize_file modul; OASISUnixPath.capitalize_file modul] in (* TODO: we should be able to be able to determine the source for every * files. Hence we should introduce a Module(source: fn) for the fields * Modules and InternalModules *) List.fold_left (fun acc base_fn -> match acc with | `No_sources _ -> begin let file_found = List.fold_left (fun acc ext -> if source_file_exists (base_fn^ext) then (base_fn^ext) :: acc else acc) [] [".ml"; ".mli"; ".mll"; ".mly"] in match file_found with | [] -> acc | lst -> `Sources (base_fn, lst) end | `Sources _ -> acc) (`No_sources possible_base_fn) possible_base_fn let source_unix_files ~ctxt (cs, bs, lib) source_file_exists = List.fold_left (fun acc modul -> match find_module source_file_exists (cs, bs, lib) modul with | `Sources (base_fn, lst) -> (base_fn, lst) :: acc | `No_sources _ -> OASISMessage.warning ~ctxt (f_ "Cannot find source file matching \ module '%s' in library %s") modul cs.cs_name; acc) [] (lib.lib_modules @ lib.lib_internal_modules) let generated_unix_files ~ctxt ~is_native ~has_native_dynlink ~ext_lib ~ext_dll ~source_file_exists (cs, bs, lib) = let find_modules lst ext = let find_module modul = match find_module source_file_exists (cs, bs, lib) modul with | `Sources (base_fn, _) -> [base_fn] | `No_sources lst -> OASISMessage.warning ~ctxt (f_ "Cannot find source file matching \ module '%s' in library %s") modul cs.cs_name; lst in List.map (fun nm -> List.map (fun base_fn -> base_fn ^"."^ext) (find_module nm)) lst in (* The headers that should be compiled along *) let headers = if lib.lib_pack then [] else find_modules lib.lib_modules "cmi" in (* The .cmx that be compiled along *) let cmxs = let should_be_built = (not lib.lib_pack) && (* Do not install .cmx packed submodules *) match bs.bs_compiled_object with | Native -> true | Best -> is_native | Byte -> false in if should_be_built then find_modules (lib.lib_modules @ lib.lib_internal_modules) "cmx" else [] in let acc_nopath = [] in (* Compute what libraries should be built *) let acc_nopath = (* Add the packed header file if required *) let add_pack_header acc = if lib.lib_pack then [cs.cs_name^".cmi"] :: acc else acc in let byte acc = add_pack_header ([cs.cs_name^".cma"] :: acc) in let native acc = let acc = add_pack_header (if has_native_dynlink then [cs.cs_name^".cmxs"] :: acc else acc) in [cs.cs_name^".cmxa"] :: [cs.cs_name^ext_lib] :: acc in match bs.bs_compiled_object with | Native -> byte (native acc_nopath) | Best when is_native -> byte (native acc_nopath) | Byte | Best -> byte acc_nopath in (* Add C library to be built *) let acc_nopath = if bs.bs_c_sources <> [] then begin ["lib"^cs.cs_name^"_stubs"^ext_lib] :: ["dll"^cs.cs_name^"_stubs"^ext_dll] :: acc_nopath end else acc_nopath in (* All the files generated *) List.rev_append (List.rev_map (List.rev_map (OASISUnixPath.concat bs.bs_path)) acc_nopath) (headers @ cmxs) type data = common_section * build_section * library type tree = | Node of (data option) * (tree MapString.t) | Leaf of data let findlib_mapping pkg = (* Map from library name to either full findlib name or parts + parent. *) let fndlb_parts_of_lib_name = let fndlb_parts cs lib = let name = match lib.lib_findlib_name with | Some nm -> nm | None -> cs.cs_name in let name = String.concat "." (lib.lib_findlib_containers @ [name]) in name in List.fold_left (fun mp -> function | Library (cs, _, lib) -> begin let lib_name = cs.cs_name in let fndlb_parts = fndlb_parts cs lib in if MapString.mem lib_name mp then failwithf (f_ "The library name '%s' is used more than once.") lib_name; match lib.lib_findlib_parent with | Some lib_name_parent -> MapString.add lib_name (`Unsolved (lib_name_parent, fndlb_parts)) mp | None -> MapString.add lib_name (`Solved fndlb_parts) mp end | Executable _ | Test _ | Flag _ | SrcRepo _ | Doc _ -> mp) MapString.empty pkg.sections in (* Solve the above graph to be only library name to full findlib name. *) let fndlb_name_of_lib_name = let rec solve visited mp lib_name lib_name_child = if SetString.mem lib_name visited then failwithf (f_ "Library '%s' is involved in a cycle \ with regard to findlib naming.") lib_name; let visited = SetString.add lib_name visited in try match MapString.find lib_name mp with | `Solved fndlb_nm -> fndlb_nm, mp | `Unsolved (lib_nm_parent, post_fndlb_nm) -> let pre_fndlb_nm, mp = solve visited mp lib_nm_parent lib_name in let fndlb_nm = pre_fndlb_nm^"."^post_fndlb_nm in fndlb_nm, MapString.add lib_name (`Solved fndlb_nm) mp with Not_found -> failwithf (f_ "Library '%s', which is defined as the findlib parent of \ library '%s', doesn't exist.") lib_name lib_name_child in let mp = MapString.fold (fun lib_name status mp -> match status with | `Solved _ -> (* Solved initialy, no need to go further *) mp | `Unsolved _ -> let _, mp = solve SetString.empty mp lib_name "" in mp) fndlb_parts_of_lib_name fndlb_parts_of_lib_name in MapString.map (function | `Solved fndlb_nm -> fndlb_nm | `Unsolved _ -> assert false) mp in (* Convert an internal library name to a findlib name. *) let findlib_name_of_library_name lib_nm = try MapString.find lib_nm fndlb_name_of_lib_name with Not_found -> raise (InternalLibraryNotFound lib_nm) in (* Add a library to the tree. *) let add sct mp = let fndlb_fullname = let cs, _, _ = sct in let lib_name = cs.cs_name in findlib_name_of_library_name lib_name in let rec add_children nm_lst (children : tree MapString.t) = match nm_lst with | (hd :: tl) -> begin let node = try add_node tl (MapString.find hd children) with Not_found -> (* New node *) new_node tl in MapString.add hd node children end | [] -> (* Should not have a nameless library. *) assert false and add_node tl node = if tl = [] then begin match node with | Node (None, children) -> Node (Some sct, children) | Leaf (cs', _, _) | Node (Some (cs', _, _), _) -> (* TODO: allow to merge Package, i.e. * archive(byte) = "foo.cma foo_init.cmo" *) let cs, _, _ = sct in failwithf (f_ "Library '%s' and '%s' have the same findlib name '%s'") cs.cs_name cs'.cs_name fndlb_fullname end else begin match node with | Leaf data -> Node (Some data, add_children tl MapString.empty) | Node (data_opt, children) -> Node (data_opt, add_children tl children) end and new_node = function | [] -> Leaf sct | hd :: tl -> Node (None, MapString.add hd (new_node tl) MapString.empty) in add_children (OASISString.nsplit fndlb_fullname '.') mp in let rec group_of_tree mp = MapString.fold (fun nm node acc -> let cur = match node with | Node (Some (cs, bs, lib), children) -> Package (nm, cs, bs, lib, group_of_tree children) | Node (None, children) -> Container (nm, group_of_tree children) | Leaf (cs, bs, lib) -> Package (nm, cs, bs, lib, []) in cur :: acc) mp [] in let group_mp = List.fold_left (fun mp -> function | Library (cs, bs, lib) -> add (cs, bs, lib) mp | _ -> mp) MapString.empty pkg.sections in let groups = group_of_tree group_mp in let library_name_of_findlib_name = Lazy.lazy_from_fun (fun () -> (* Revert findlib_name_of_library_name. *) MapString.fold (fun k v mp -> MapString.add v k mp) fndlb_name_of_lib_name MapString.empty) in let library_name_of_findlib_name fndlb_nm = try MapString.find fndlb_nm (Lazy.force library_name_of_findlib_name) with Not_found -> raise (FindlibPackageNotFound fndlb_nm) in groups, findlib_name_of_library_name, library_name_of_findlib_name let findlib_of_group = function | Container (fndlb_nm, _) | Package (fndlb_nm, _, _, _, _) -> fndlb_nm let root_of_group grp = let rec root_lib_aux = (* We do a DFS in the group. *) function | Container (_, children) -> List.fold_left (fun res grp -> if res = None then root_lib_aux grp else res) None children | Package (_, cs, bs, lib, _) -> Some (cs, bs, lib) in match root_lib_aux grp with | Some res -> res | None -> failwithf (f_ "Unable to determine root library of findlib library '%s'") (findlib_of_group grp) end module OASISFlag = struct (* # 21 "src/oasis/OASISFlag.ml" *) end module OASISPackage = struct (* # 21 "src/oasis/OASISPackage.ml" *) end module OASISSourceRepository = struct (* # 21 "src/oasis/OASISSourceRepository.ml" *) end module OASISTest = struct (* # 21 "src/oasis/OASISTest.ml" *) end module OASISDocument = struct (* # 21 "src/oasis/OASISDocument.ml" *) end module OASISExec = struct (* # 21 "src/oasis/OASISExec.ml" *) open OASISGettext open OASISUtils open OASISMessage (* TODO: I don't like this quote, it is there because $(rm) foo expands to * 'rm -f' foo... *) let run ~ctxt ?f_exit_code ?(quote=true) cmd args = let cmd = if quote then if Sys.os_type = "Win32" then if String.contains cmd ' ' then (* Double the 1st double quote... win32... sigh *) "\""^(Filename.quote cmd) else cmd else Filename.quote cmd else cmd in let cmdline = String.concat " " (cmd :: args) in info ~ctxt (f_ "Running command '%s'") cmdline; match f_exit_code, Sys.command cmdline with | None, 0 -> () | None, i -> failwithf (f_ "Command '%s' terminated with error code %d") cmdline i | Some f, i -> f i let run_read_output ~ctxt ?f_exit_code cmd args = let fn = Filename.temp_file "oasis-" ".txt" in try begin let () = run ~ctxt ?f_exit_code cmd (args @ [">"; Filename.quote fn]) in let chn = open_in fn in let routput = ref [] in begin try while true do routput := (input_line chn) :: !routput done with End_of_file -> () end; close_in chn; Sys.remove fn; List.rev !routput end with e -> (try Sys.remove fn with _ -> ()); raise e let run_read_one_line ~ctxt ?f_exit_code cmd args = match run_read_output ~ctxt ?f_exit_code cmd args with | [fst] -> fst | lst -> failwithf (f_ "Command return unexpected output %S") (String.concat "\n" lst) end module OASISFileUtil = struct (* # 21 "src/oasis/OASISFileUtil.ml" *) open OASISGettext let file_exists_case fn = let dirname = Filename.dirname fn in let basename = Filename.basename fn in if Sys.file_exists dirname then if basename = Filename.current_dir_name then true else List.mem basename (Array.to_list (Sys.readdir dirname)) else false let find_file ?(case_sensitive=true) paths exts = (* Cardinal product of two list *) let ( * ) lst1 lst2 = List.flatten (List.map (fun a -> List.map (fun b -> a,b) lst2) lst1) in let rec combined_paths lst = match lst with | p1 :: p2 :: tl -> let acc = (List.map (fun (a,b) -> Filename.concat a b) (p1 * p2)) in combined_paths (acc :: tl) | [e] -> e | [] -> [] in let alternatives = List.map (fun (p,e) -> if String.length e > 0 && e.[0] <> '.' then p ^ "." ^ e else p ^ e) ((combined_paths paths) * exts) in List.find (if case_sensitive then file_exists_case else Sys.file_exists) alternatives let which ~ctxt prg = let path_sep = match Sys.os_type with | "Win32" -> ';' | _ -> ':' in let path_lst = OASISString.nsplit (Sys.getenv "PATH") path_sep in let exec_ext = match Sys.os_type with | "Win32" -> "" :: (OASISString.nsplit (Sys.getenv "PATHEXT") path_sep) | _ -> [""] in find_file ~case_sensitive:false [path_lst; [prg]] exec_ext (**/**) let rec fix_dir dn = (* Windows hack because Sys.file_exists "src\\" = false when * Sys.file_exists "src" = true *) let ln = String.length dn in if Sys.os_type = "Win32" && ln > 0 && dn.[ln - 1] = '\\' then fix_dir (String.sub dn 0 (ln - 1)) else dn let q = Filename.quote (**/**) let cp ~ctxt ?(recurse=false) src tgt = if recurse then match Sys.os_type with | "Win32" -> OASISExec.run ~ctxt "xcopy" [q src; q tgt; "/E"] | _ -> OASISExec.run ~ctxt "cp" ["-r"; q src; q tgt] else OASISExec.run ~ctxt (match Sys.os_type with | "Win32" -> "copy" | _ -> "cp") [q src; q tgt] let mkdir ~ctxt tgt = OASISExec.run ~ctxt (match Sys.os_type with | "Win32" -> "md" | _ -> "mkdir") [q tgt] let rec mkdir_parent ~ctxt f tgt = let tgt = fix_dir tgt in if Sys.file_exists tgt then begin if not (Sys.is_directory tgt) then OASISUtils.failwithf (f_ "Cannot create directory '%s', a file of the same name already \ exists") tgt end else begin mkdir_parent ~ctxt f (Filename.dirname tgt); if not (Sys.file_exists tgt) then begin f tgt; mkdir ~ctxt tgt end end let rmdir ~ctxt tgt = if Sys.readdir tgt = [||] then begin match Sys.os_type with | "Win32" -> OASISExec.run ~ctxt "rd" [q tgt] | _ -> OASISExec.run ~ctxt "rm" ["-r"; q tgt] end let glob ~ctxt fn = let basename = Filename.basename fn in if String.length basename >= 2 && basename.[0] = '*' && basename.[1] = '.' then begin let ext_len = (String.length basename) - 2 in let ext = String.sub basename 2 ext_len in let dirname = Filename.dirname fn in Array.fold_left (fun acc fn -> try let fn_ext = String.sub fn ((String.length fn) - ext_len) ext_len in if fn_ext = ext then (Filename.concat dirname fn) :: acc else acc with Invalid_argument _ -> acc) [] (Sys.readdir dirname) end else begin if file_exists_case fn then [fn] else [] end end # 2142 "setup.ml" module BaseEnvLight = struct (* # 21 "src/base/BaseEnvLight.ml" *) module MapString = Map.Make(String) type t = string MapString.t let default_filename = Filename.concat (Sys.getcwd ()) "setup.data" let load ?(allow_empty=false) ?(filename=default_filename) () = if Sys.file_exists filename then begin let chn = open_in_bin filename in let st = Stream.of_channel chn in let line = ref 1 in let st_line = Stream.from (fun _ -> try match Stream.next st with | '\n' -> incr line; Some '\n' | c -> Some c with Stream.Failure -> None) in let lexer = Genlex.make_lexer ["="] st_line in let rec read_file mp = match Stream.npeek 3 lexer with | [Genlex.Ident nm; Genlex.Kwd "="; Genlex.String value] -> Stream.junk lexer; Stream.junk lexer; Stream.junk lexer; read_file (MapString.add nm value mp) | [] -> mp | _ -> failwith (Printf.sprintf "Malformed data file '%s' line %d" filename !line) in let mp = read_file MapString.empty in close_in chn; mp end else if allow_empty then begin MapString.empty end else begin failwith (Printf.sprintf "Unable to load environment, the file '%s' doesn't exist." filename) end let var_get name env = let rec var_expand str = let buff = Buffer.create ((String.length str) * 2) in Buffer.add_substitute buff (fun var -> try var_expand (MapString.find var env) with Not_found -> failwith (Printf.sprintf "No variable %s defined when trying to expand %S." var str)) str; Buffer.contents buff in var_expand (MapString.find name env) let var_choose lst env = OASISExpr.choose (fun nm -> var_get nm env) lst end # 2240 "setup.ml" module BaseContext = struct (* # 21 "src/base/BaseContext.ml" *) open OASISContext let args = args let default = default end module BaseMessage = struct (* # 21 "src/base/BaseMessage.ml" *) (** Message to user, overrid for Base @author Sylvain Le Gall *) open OASISMessage open BaseContext let debug fmt = debug ~ctxt:!default fmt let info fmt = info ~ctxt:!default fmt let warning fmt = warning ~ctxt:!default fmt let error fmt = error ~ctxt:!default fmt end module BaseEnv = struct (* # 21 "src/base/BaseEnv.ml" *) open OASISGettext open OASISUtils open PropList module MapString = BaseEnvLight.MapString type origin_t = | ODefault | OGetEnv | OFileLoad | OCommandLine type cli_handle_t = | CLINone | CLIAuto | CLIWith | CLIEnable | CLIUser of (Arg.key * Arg.spec * Arg.doc) list type definition_t = { hide: bool; dump: bool; cli: cli_handle_t; arg_help: string option; group: string option; } let schema = Schema.create "environment" (* Environment data *) let env = Data.create () (* Environment data from file *) let env_from_file = ref MapString.empty (* Lexer for var *) let var_lxr = Genlex.make_lexer [] let rec var_expand str = let buff = Buffer.create ((String.length str) * 2) in Buffer.add_substitute buff (fun var -> try (* TODO: this is a quick hack to allow calling Test.Command * without defining executable name really. I.e. if there is * an exec Executable toto, then $(toto) should be replace * by its real name. It is however useful to have this function * for other variable that depend on the host and should be * written better than that. *) let st = var_lxr (Stream.of_string var) in match Stream.npeek 3 st with | [Genlex.Ident "utoh"; Genlex.Ident nm] -> OASISHostPath.of_unix (var_get nm) | [Genlex.Ident "utoh"; Genlex.String s] -> OASISHostPath.of_unix s | [Genlex.Ident "ocaml_escaped"; Genlex.Ident nm] -> String.escaped (var_get nm) | [Genlex.Ident "ocaml_escaped"; Genlex.String s] -> String.escaped s | [Genlex.Ident nm] -> var_get nm | _ -> failwithf (f_ "Unknown expression '%s' in variable expansion of %s.") var str with | Unknown_field (_, _) -> failwithf (f_ "No variable %s defined when trying to expand %S.") var str | Stream.Error e -> failwithf (f_ "Syntax error when parsing '%s' when trying to \ expand %S: %s") var str e) str; Buffer.contents buff and var_get name = let vl = try Schema.get schema env name with Unknown_field _ as e -> begin try MapString.find name !env_from_file with Not_found -> raise e end in var_expand vl let var_choose ?printer ?name lst = OASISExpr.choose ?printer ?name var_get lst let var_protect vl = let buff = Buffer.create (String.length vl) in String.iter (function | '$' -> Buffer.add_string buff "\\$" | c -> Buffer.add_char buff c) vl; Buffer.contents buff let var_define ?(hide=false) ?(dump=true) ?short_desc ?(cli=CLINone) ?arg_help ?group name (* TODO: type constraint on the fact that name must be a valid OCaml id *) dflt = let default = [ OFileLoad, (fun () -> MapString.find name !env_from_file); ODefault, dflt; OGetEnv, (fun () -> Sys.getenv name); ] in let extra = { hide = hide; dump = dump; cli = cli; arg_help = arg_help; group = group; } in (* Try to find a value that can be defined *) let var_get_low lst = let errors, res = List.fold_left (fun (errors, res) (o, v) -> if res = None then begin try errors, Some (v ()) with | Not_found -> errors, res | Failure rsn -> (rsn :: errors), res | e -> (Printexc.to_string e) :: errors, res end else errors, res) ([], None) (List.sort (fun (o1, _) (o2, _) -> Pervasives.compare o2 o1) lst) in match res, errors with | Some v, _ -> v | None, [] -> raise (Not_set (name, None)) | None, lst -> raise (Not_set (name, Some (String.concat (s_ ", ") lst))) in let help = match short_desc with | Some fs -> Some fs | None -> None in let var_get_lst = FieldRO.create ~schema ~name ~parse:(fun ?(context=ODefault) s -> [context, fun () -> s]) ~print:var_get_low ~default ~update:(fun ?context x old_x -> x @ old_x) ?help extra in fun () -> var_expand (var_get_low (var_get_lst env)) let var_redefine ?hide ?dump ?short_desc ?cli ?arg_help ?group name dflt = if Schema.mem schema name then begin (* TODO: look suspsicious, we want to memorize dflt not dflt () *) Schema.set schema env ~context:ODefault name (dflt ()); fun () -> var_get name end else begin var_define ?hide ?dump ?short_desc ?cli ?arg_help ?group name dflt end let var_ignore (e : unit -> string) = () let print_hidden = var_define ~hide:true ~dump:false ~cli:CLIAuto ~arg_help:"Print even non-printable variable. (debug)" "print_hidden" (fun () -> "false") let var_all () = List.rev (Schema.fold (fun acc nm def _ -> if not def.hide || bool_of_string (print_hidden ()) then nm :: acc else acc) [] schema) let default_filename = BaseEnvLight.default_filename let load ?allow_empty ?filename () = env_from_file := BaseEnvLight.load ?allow_empty ?filename () let unload () = env_from_file := MapString.empty; Data.clear env let dump ?(filename=default_filename) () = let chn = open_out_bin filename in let output nm value = Printf.fprintf chn "%s=%S\n" nm value in let mp_todo = (* Dump data from schema *) Schema.fold (fun mp_todo nm def _ -> if def.dump then begin try let value = Schema.get schema env nm in output nm value with Not_set _ -> () end; MapString.remove nm mp_todo) !env_from_file schema in (* Dump data defined outside of schema *) MapString.iter output mp_todo; (* End of the dump *) close_out chn let print () = let printable_vars = Schema.fold (fun acc nm def short_descr_opt -> if not def.hide || bool_of_string (print_hidden ()) then begin try let value = Schema.get schema env nm in let txt = match short_descr_opt with | Some s -> s () | None -> nm in (txt, value) :: acc with Not_set _ -> acc end else acc) [] schema in let max_length = List.fold_left max 0 (List.rev_map String.length (List.rev_map fst printable_vars)) in let dot_pad str = String.make ((max_length - (String.length str)) + 3) '.' in Printf.printf "\nConfiguration: \n"; List.iter (fun (name,value) -> Printf.printf "%s: %s %s\n" name (dot_pad name) value) (List.rev printable_vars); Printf.printf "\n%!" let args () = let arg_concat = OASISUtils.varname_concat ~hyphen:'-' in [ "--override", Arg.Tuple ( let rvr = ref "" in let rvl = ref "" in [ Arg.Set_string rvr; Arg.Set_string rvl; Arg.Unit (fun () -> Schema.set schema env ~context:OCommandLine !rvr !rvl) ] ), "var+val Override any configuration variable."; ] @ List.flatten (Schema.fold (fun acc name def short_descr_opt -> let var_set s = Schema.set schema env ~context:OCommandLine name s in let arg_name = OASISUtils.varname_of_string ~hyphen:'-' name in let hlp = match short_descr_opt with | Some txt -> txt () | None -> "" in let arg_hlp = match def.arg_help with | Some s -> s | None -> "str" in let default_value = try Printf.sprintf (f_ " [%s]") (Schema.get schema env name) with Not_set _ -> "" in let args = match def.cli with | CLINone -> [] | CLIAuto -> [ arg_concat "--" arg_name, Arg.String var_set, Printf.sprintf (f_ "%s %s%s") arg_hlp hlp default_value ] | CLIWith -> [ arg_concat "--with-" arg_name, Arg.String var_set, Printf.sprintf (f_ "%s %s%s") arg_hlp hlp default_value ] | CLIEnable -> let dflt = if default_value = " [true]" then s_ " [default: enabled]" else s_ " [default: disabled]" in [ arg_concat "--enable-" arg_name, Arg.Unit (fun () -> var_set "true"), Printf.sprintf (f_ " %s%s") hlp dflt; arg_concat "--disable-" arg_name, Arg.Unit (fun () -> var_set "false"), Printf.sprintf (f_ " %s%s") hlp dflt ] | CLIUser lst -> lst in args :: acc) [] schema) end module BaseArgExt = struct (* # 21 "src/base/BaseArgExt.ml" *) open OASISUtils open OASISGettext let parse argv args = (* Simulate command line for Arg *) let current = ref 0 in try Arg.parse_argv ~current:current (Array.concat [[|"none"|]; argv]) (Arg.align args) (failwithf (f_ "Don't know what to do with arguments: '%s'")) (s_ "configure options:") with | Arg.Help txt -> print_endline txt; exit 0 | Arg.Bad txt -> prerr_endline txt; exit 1 end module BaseCheck = struct (* # 21 "src/base/BaseCheck.ml" *) open BaseEnv open BaseMessage open OASISUtils open OASISGettext let prog_best prg prg_lst = var_redefine prg (fun () -> let alternate = List.fold_left (fun res e -> match res with | Some _ -> res | None -> try Some (OASISFileUtil.which ~ctxt:!BaseContext.default e) with Not_found -> None) None prg_lst in match alternate with | Some prg -> prg | None -> raise Not_found) let prog prg = prog_best prg [prg] let prog_opt prg = prog_best prg [prg^".opt"; prg] let ocamlfind = prog "ocamlfind" let version var_prefix cmp fversion () = (* Really compare version provided *) let var = var_prefix^"_version_"^(OASISVersion.varname_of_comparator cmp) in var_redefine ~hide:true var (fun () -> let version_str = match fversion () with | "[Distributed with OCaml]" -> begin try (var_get "ocaml_version") with Not_found -> warning (f_ "Variable ocaml_version not defined, fallback \ to default"); Sys.ocaml_version end | res -> res in let version = OASISVersion.version_of_string version_str in if OASISVersion.comparator_apply version cmp then version_str else failwithf (f_ "Cannot satisfy version constraint on %s: %s (version: %s)") var_prefix (OASISVersion.string_of_comparator cmp) version_str) () let package_version pkg = OASISExec.run_read_one_line ~ctxt:!BaseContext.default (ocamlfind ()) ["query"; "-format"; "%v"; pkg] let package ?version_comparator pkg () = let var = OASISUtils.varname_concat "pkg_" (OASISUtils.varname_of_string pkg) in let findlib_dir pkg = let dir = OASISExec.run_read_one_line ~ctxt:!BaseContext.default (ocamlfind ()) ["query"; "-format"; "%d"; pkg] in if Sys.file_exists dir && Sys.is_directory dir then dir else failwithf (f_ "When looking for findlib package %s, \ directory %s return doesn't exist") pkg dir in let vl = var_redefine var (fun () -> findlib_dir pkg) () in ( match version_comparator with | Some ver_cmp -> ignore (version var ver_cmp (fun _ -> package_version pkg) ()) | None -> () ); vl end module BaseOCamlcConfig = struct (* # 21 "src/base/BaseOCamlcConfig.ml" *) open BaseEnv open OASISUtils open OASISGettext module SMap = Map.Make(String) let ocamlc = BaseCheck.prog_opt "ocamlc" let ocamlc_config_map = (* Map name to value for ocamlc -config output (name ^": "^value) *) let rec split_field mp lst = match lst with | line :: tl -> let mp = try let pos_semicolon = String.index line ':' in if pos_semicolon > 1 then ( let name = String.sub line 0 pos_semicolon in let linelen = String.length line in let value = if linelen > pos_semicolon + 2 then String.sub line (pos_semicolon + 2) (linelen - pos_semicolon - 2) else "" in SMap.add name value mp ) else ( mp ) with Not_found -> ( mp ) in split_field mp tl | [] -> mp in let cache = lazy (var_protect (Marshal.to_string (split_field SMap.empty (OASISExec.run_read_output ~ctxt:!BaseContext.default (ocamlc ()) ["-config"])) [])) in var_redefine "ocamlc_config_map" ~hide:true ~dump:false (fun () -> (* TODO: update if ocamlc change !!! *) Lazy.force cache) let var_define nm = (* Extract data from ocamlc -config *) let avlbl_config_get () = Marshal.from_string (ocamlc_config_map ()) 0 in let chop_version_suffix s = try String.sub s 0 (String.index s '+') with _ -> s in let nm_config, value_config = match nm with | "ocaml_version" -> "version", chop_version_suffix | _ -> nm, (fun x -> x) in var_redefine nm (fun () -> try let map = avlbl_config_get () in let value = SMap.find nm_config map in value_config value with Not_found -> failwithf (f_ "Cannot find field '%s' in '%s -config' output") nm (ocamlc ())) end module BaseStandardVar = struct (* # 21 "src/base/BaseStandardVar.ml" *) open OASISGettext open OASISTypes open OASISExpr open BaseCheck open BaseEnv let ocamlfind = BaseCheck.ocamlfind let ocamlc = BaseOCamlcConfig.ocamlc let ocamlopt = prog_opt "ocamlopt" let ocamlbuild = prog "ocamlbuild" (**/**) let rpkg = ref None let pkg_get () = match !rpkg with | Some pkg -> pkg | None -> failwith (s_ "OASIS Package is not set") let var_cond = ref [] let var_define_cond ~since_version f dflt = let holder = ref (fun () -> dflt) in let since_version = OASISVersion.VGreaterEqual (OASISVersion.version_of_string since_version) in var_cond := (fun ver -> if OASISVersion.comparator_apply ver since_version then holder := f ()) :: !var_cond; fun () -> !holder () (**/**) let pkg_name = var_define ~short_desc:(fun () -> s_ "Package name") "pkg_name" (fun () -> (pkg_get ()).name) let pkg_version = var_define ~short_desc:(fun () -> s_ "Package version") "pkg_version" (fun () -> (OASISVersion.string_of_version (pkg_get ()).version)) let c = BaseOCamlcConfig.var_define let os_type = c "os_type" let system = c "system" let architecture = c "architecture" let ccomp_type = c "ccomp_type" let ocaml_version = c "ocaml_version" (* TODO: Check standard variable presence at runtime *) let standard_library_default = c "standard_library_default" let standard_library = c "standard_library" let standard_runtime = c "standard_runtime" let bytecomp_c_compiler = c "bytecomp_c_compiler" let native_c_compiler = c "native_c_compiler" let model = c "model" let ext_obj = c "ext_obj" let ext_asm = c "ext_asm" let ext_lib = c "ext_lib" let ext_dll = c "ext_dll" let default_executable_name = c "default_executable_name" let systhread_supported = c "systhread_supported" let flexlink = BaseCheck.prog "flexlink" let flexdll_version = var_define ~short_desc:(fun () -> "FlexDLL version (Win32)") "flexdll_version" (fun () -> let lst = OASISExec.run_read_output ~ctxt:!BaseContext.default (flexlink ()) ["-help"] in match lst with | line :: _ -> Scanf.sscanf line "FlexDLL version %s" (fun ver -> ver) | [] -> raise Not_found) (**/**) let p name hlp dflt = var_define ~short_desc:hlp ~cli:CLIAuto ~arg_help:"dir" name dflt let (/) a b = if os_type () = Sys.os_type then Filename.concat a b else if os_type () = "Unix" then OASISUnixPath.concat a b else OASISUtils.failwithf (f_ "Cannot handle os_type %s filename concat") (os_type ()) (**/**) let prefix = p "prefix" (fun () -> s_ "Install architecture-independent files dir") (fun () -> match os_type () with | "Win32" -> let program_files = Sys.getenv "PROGRAMFILES" in program_files/(pkg_name ()) | _ -> "/usr/local") let exec_prefix = p "exec_prefix" (fun () -> s_ "Install architecture-dependent files in dir") (fun () -> "$prefix") let bindir = p "bindir" (fun () -> s_ "User executables") (fun () -> "$exec_prefix"/"bin") let sbindir = p "sbindir" (fun () -> s_ "System admin executables") (fun () -> "$exec_prefix"/"sbin") let libexecdir = p "libexecdir" (fun () -> s_ "Program executables") (fun () -> "$exec_prefix"/"libexec") let sysconfdir = p "sysconfdir" (fun () -> s_ "Read-only single-machine data") (fun () -> "$prefix"/"etc") let sharedstatedir = p "sharedstatedir" (fun () -> s_ "Modifiable architecture-independent data") (fun () -> "$prefix"/"com") let localstatedir = p "localstatedir" (fun () -> s_ "Modifiable single-machine data") (fun () -> "$prefix"/"var") let libdir = p "libdir" (fun () -> s_ "Object code libraries") (fun () -> "$exec_prefix"/"lib") let datarootdir = p "datarootdir" (fun () -> s_ "Read-only arch-independent data root") (fun () -> "$prefix"/"share") let datadir = p "datadir" (fun () -> s_ "Read-only architecture-independent data") (fun () -> "$datarootdir") let infodir = p "infodir" (fun () -> s_ "Info documentation") (fun () -> "$datarootdir"/"info") let localedir = p "localedir" (fun () -> s_ "Locale-dependent data") (fun () -> "$datarootdir"/"locale") let mandir = p "mandir" (fun () -> s_ "Man documentation") (fun () -> "$datarootdir"/"man") let docdir = p "docdir" (fun () -> s_ "Documentation root") (fun () -> "$datarootdir"/"doc"/"$pkg_name") let htmldir = p "htmldir" (fun () -> s_ "HTML documentation") (fun () -> "$docdir") let dvidir = p "dvidir" (fun () -> s_ "DVI documentation") (fun () -> "$docdir") let pdfdir = p "pdfdir" (fun () -> s_ "PDF documentation") (fun () -> "$docdir") let psdir = p "psdir" (fun () -> s_ "PS documentation") (fun () -> "$docdir") let destdir = p "destdir" (fun () -> s_ "Prepend a path when installing package") (fun () -> raise (PropList.Not_set ("destdir", Some (s_ "undefined by construct")))) let findlib_version = var_define "findlib_version" (fun () -> BaseCheck.package_version "findlib") let is_native = var_define "is_native" (fun () -> try let _s : string = ocamlopt () in "true" with PropList.Not_set _ -> let _s : string = ocamlc () in "false") let ext_program = var_define "suffix_program" (fun () -> match os_type () with | "Win32" -> ".exe" | _ -> "") let rm = var_define ~short_desc:(fun () -> s_ "Remove a file.") "rm" (fun () -> match os_type () with | "Win32" -> "del" | _ -> "rm -f") let rmdir = var_define ~short_desc:(fun () -> s_ "Remove a directory.") "rmdir" (fun () -> match os_type () with | "Win32" -> "rd" | _ -> "rm -rf") let debug = var_define ~short_desc:(fun () -> s_ "Turn ocaml debug flag on") ~cli:CLIEnable "debug" (fun () -> "true") let profile = var_define ~short_desc:(fun () -> s_ "Turn ocaml profile flag on") ~cli:CLIEnable "profile" (fun () -> "false") let tests = var_define_cond ~since_version:"0.3" (fun () -> var_define ~short_desc:(fun () -> s_ "Compile tests executable and library and run them") ~cli:CLIEnable "tests" (fun () -> "false")) "true" let docs = var_define_cond ~since_version:"0.3" (fun () -> var_define ~short_desc:(fun () -> s_ "Create documentations") ~cli:CLIEnable "docs" (fun () -> "true")) "true" let native_dynlink = var_define ~short_desc:(fun () -> s_ "Compiler support generation of .cmxs.") ~cli:CLINone "native_dynlink" (fun () -> let res = let ocaml_lt_312 () = OASISVersion.comparator_apply (OASISVersion.version_of_string (ocaml_version ())) (OASISVersion.VLesser (OASISVersion.version_of_string "3.12.0")) in let flexdll_lt_030 () = OASISVersion.comparator_apply (OASISVersion.version_of_string (flexdll_version ())) (OASISVersion.VLesser (OASISVersion.version_of_string "0.30")) in let has_native_dynlink = let ocamlfind = ocamlfind () in try let fn = OASISExec.run_read_one_line ~ctxt:!BaseContext.default ocamlfind ["query"; "-predicates"; "native"; "dynlink"; "-format"; "%d/%a"] in Sys.file_exists fn with _ -> false in if not has_native_dynlink then false else if ocaml_lt_312 () then false else if (os_type () = "Win32" || os_type () = "Cygwin") && flexdll_lt_030 () then begin BaseMessage.warning (f_ ".cmxs generation disabled because FlexDLL needs to be \ at least 0.30. Please upgrade FlexDLL from %s to 0.30.") (flexdll_version ()); false end else true in string_of_bool res) let init pkg = rpkg := Some pkg; List.iter (fun f -> f pkg.oasis_version) !var_cond end module BaseFileAB = struct (* # 21 "src/base/BaseFileAB.ml" *) open BaseEnv open OASISGettext open BaseMessage let to_filename fn = let fn = OASISHostPath.of_unix fn in if not (Filename.check_suffix fn ".ab") then warning (f_ "File '%s' doesn't have '.ab' extension") fn; Filename.chop_extension fn let replace fn_lst = let buff = Buffer.create 13 in List.iter (fun fn -> let fn = OASISHostPath.of_unix fn in let chn_in = open_in fn in let chn_out = open_out (to_filename fn) in ( try while true do Buffer.add_string buff (var_expand (input_line chn_in)); Buffer.add_char buff '\n' done with End_of_file -> () ); Buffer.output_buffer chn_out buff; Buffer.clear buff; close_in chn_in; close_out chn_out) fn_lst end module BaseLog = struct (* # 21 "src/base/BaseLog.ml" *) open OASISUtils let default_filename = Filename.concat (Filename.dirname BaseEnv.default_filename) "setup.log" module SetTupleString = Set.Make (struct type t = string * string let compare (s11, s12) (s21, s22) = match String.compare s11 s21 with | 0 -> String.compare s12 s22 | n -> n end) let load () = if Sys.file_exists default_filename then begin let chn = open_in default_filename in let scbuf = Scanf.Scanning.from_file default_filename in let rec read_aux (st, lst) = if not (Scanf.Scanning.end_of_input scbuf) then begin let acc = try Scanf.bscanf scbuf "%S %S\n" (fun e d -> let t = e, d in if SetTupleString.mem t st then st, lst else SetTupleString.add t st, t :: lst) with Scanf.Scan_failure _ -> failwith (Scanf.bscanf scbuf "%l" (fun line -> Printf.sprintf "Malformed log file '%s' at line %d" default_filename line)) in read_aux acc end else begin close_in chn; List.rev lst end in read_aux (SetTupleString.empty, []) end else begin [] end let register event data = let chn_out = open_out_gen [Open_append; Open_creat; Open_text] 0o644 default_filename in Printf.fprintf chn_out "%S %S\n" event data; close_out chn_out let unregister event data = if Sys.file_exists default_filename then begin let lst = load () in let chn_out = open_out default_filename in let write_something = ref false in List.iter (fun (e, d) -> if e <> event || d <> data then begin write_something := true; Printf.fprintf chn_out "%S %S\n" e d end) lst; close_out chn_out; if not !write_something then Sys.remove default_filename end let filter events = let st_events = List.fold_left (fun st e -> SetString.add e st) SetString.empty events in List.filter (fun (e, _) -> SetString.mem e st_events) (load ()) let exists event data = List.exists (fun v -> (event, data) = v) (load ()) end module BaseBuilt = struct (* # 21 "src/base/BaseBuilt.ml" *) open OASISTypes open OASISGettext open BaseStandardVar open BaseMessage type t = | BExec (* Executable *) | BExecLib (* Library coming with executable *) | BLib (* Library *) | BDoc (* Document *) let to_log_event_file t nm = "built_"^ (match t with | BExec -> "exec" | BExecLib -> "exec_lib" | BLib -> "lib" | BDoc -> "doc")^ "_"^nm let to_log_event_done t nm = "is_"^(to_log_event_file t nm) let register t nm lst = BaseLog.register (to_log_event_done t nm) "true"; List.iter (fun alt -> let registered = List.fold_left (fun registered fn -> if OASISFileUtil.file_exists_case fn then begin BaseLog.register (to_log_event_file t nm) (if Filename.is_relative fn then Filename.concat (Sys.getcwd ()) fn else fn); true end else registered) false alt in if not registered then warning (f_ "Cannot find an existing alternative files among: %s") (String.concat (s_ ", ") alt)) lst let unregister t nm = List.iter (fun (e, d) -> BaseLog.unregister e d) (BaseLog.filter [to_log_event_file t nm; to_log_event_done t nm]) let fold t nm f acc = List.fold_left (fun acc (_, fn) -> if OASISFileUtil.file_exists_case fn then begin f acc fn end else begin warning (f_ "File '%s' has been marked as built \ for %s but doesn't exist") fn (Printf.sprintf (match t with | BExec | BExecLib -> (f_ "executable %s") | BLib -> (f_ "library %s") | BDoc -> (f_ "documentation %s")) nm); acc end) acc (BaseLog.filter [to_log_event_file t nm]) let is_built t nm = List.fold_left (fun is_built (_, d) -> (try bool_of_string d with _ -> false)) false (BaseLog.filter [to_log_event_done t nm]) let of_executable ffn (cs, bs, exec) = let unix_exec_is, unix_dll_opt = OASISExecutable.unix_exec_is (cs, bs, exec) (fun () -> bool_of_string (is_native ())) ext_dll ext_program in let evs = (BExec, cs.cs_name, [[ffn unix_exec_is]]) :: (match unix_dll_opt with | Some fn -> [BExecLib, cs.cs_name, [[ffn fn]]] | None -> []) in evs, unix_exec_is, unix_dll_opt let of_library ffn (cs, bs, lib) = let unix_lst = OASISLibrary.generated_unix_files ~ctxt:!BaseContext.default ~source_file_exists:(fun fn -> OASISFileUtil.file_exists_case (OASISHostPath.of_unix fn)) ~is_native:(bool_of_string (is_native ())) ~has_native_dynlink:(bool_of_string (native_dynlink ())) ~ext_lib:(ext_lib ()) ~ext_dll:(ext_dll ()) (cs, bs, lib) in let evs = [BLib, cs.cs_name, List.map (List.map ffn) unix_lst] in evs, unix_lst end module BaseCustom = struct (* # 21 "src/base/BaseCustom.ml" *) open BaseEnv open BaseMessage open OASISTypes open OASISGettext let run cmd args extra_args = OASISExec.run ~ctxt:!BaseContext.default ~quote:false (var_expand cmd) (List.map var_expand (args @ (Array.to_list extra_args))) let hook ?(failsafe=false) cstm f e = let optional_command lst = let printer = function | Some (cmd, args) -> String.concat " " (cmd :: args) | None -> s_ "No command" in match var_choose ~name:(s_ "Pre/Post Command") ~printer lst with | Some (cmd, args) -> begin try run cmd args [||] with e when failsafe -> warning (f_ "Command '%s' fail with error: %s") (String.concat " " (cmd :: args)) (match e with | Failure msg -> msg | e -> Printexc.to_string e) end | None -> () in let res = optional_command cstm.pre_command; f e in optional_command cstm.post_command; res end module BaseDynVar = struct (* # 21 "src/base/BaseDynVar.ml" *) open OASISTypes open OASISGettext open BaseEnv open BaseBuilt let init pkg = (* TODO: disambiguate exec vs other variable by adding exec_VARNAME. *) (* TODO: provide compile option for library libary_byte_args_VARNAME... *) List.iter (function | Executable (cs, bs, exec) -> if var_choose bs.bs_build then var_ignore (var_redefine (* We don't save this variable *) ~dump:false ~short_desc:(fun () -> Printf.sprintf (f_ "Filename of executable '%s'") cs.cs_name) (OASISUtils.varname_of_string cs.cs_name) (fun () -> let fn_opt = fold BExec cs.cs_name (fun _ fn -> Some fn) None in match fn_opt with | Some fn -> fn | None -> raise (PropList.Not_set (cs.cs_name, Some (Printf.sprintf (f_ "Executable '%s' not yet built.") cs.cs_name))))) | Library _ | Flag _ | Test _ | SrcRepo _ | Doc _ -> ()) pkg.sections end module BaseTest = struct (* # 21 "src/base/BaseTest.ml" *) open BaseEnv open BaseMessage open OASISTypes open OASISExpr open OASISGettext let test lst pkg extra_args = let one_test (failure, n) (test_plugin, cs, test) = if var_choose ~name:(Printf.sprintf (f_ "test %s run") cs.cs_name) ~printer:string_of_bool test.test_run then begin let () = info (f_ "Running test '%s'") cs.cs_name in let back_cwd = match test.test_working_directory with | Some dir -> let cwd = Sys.getcwd () in let chdir d = info (f_ "Changing directory to '%s'") d; Sys.chdir d in chdir dir; fun () -> chdir cwd | None -> fun () -> () in try let failure_percent = BaseCustom.hook test.test_custom (test_plugin pkg (cs, test)) extra_args in back_cwd (); (failure_percent +. failure, n + 1) with e -> begin back_cwd (); raise e end end else begin info (f_ "Skipping test '%s'") cs.cs_name; (failure, n) end in let (failed, n) = List.fold_left one_test (0.0, 0) lst in let failure_percent = if n = 0 then 0.0 else failed /. (float_of_int n) in let msg = Printf.sprintf (f_ "Tests had a %.2f%% failure rate") (100. *. failure_percent) in if failure_percent > 0.0 then failwith msg else info "%s" msg; (* Possible explanation why the tests where not run. *) if OASISVersion.version_0_3_or_after pkg.oasis_version && not (bool_of_string (BaseStandardVar.tests ())) && lst <> [] then BaseMessage.warning "Tests are turned off, consider enabling with \ 'ocaml setup.ml -configure --enable-tests'" end module BaseDoc = struct (* # 21 "src/base/BaseDoc.ml" *) open BaseEnv open BaseMessage open OASISTypes open OASISGettext let doc lst pkg extra_args = let one_doc (doc_plugin, cs, doc) = if var_choose ~name:(Printf.sprintf (f_ "documentation %s build") cs.cs_name) ~printer:string_of_bool doc.doc_build then begin info (f_ "Building documentation '%s'") cs.cs_name; BaseCustom.hook doc.doc_custom (doc_plugin pkg (cs, doc)) extra_args end in List.iter one_doc lst; if OASISVersion.version_0_3_or_after pkg.oasis_version && not (bool_of_string (BaseStandardVar.docs ())) && lst <> [] then BaseMessage.warning "Docs are turned off, consider enabling with \ 'ocaml setup.ml -configure --enable-docs'" end module BaseSetup = struct (* # 21 "src/base/BaseSetup.ml" *) open BaseEnv open BaseMessage open OASISTypes open OASISSection open OASISGettext open OASISUtils type std_args_fun = package -> string array -> unit type ('a, 'b) section_args_fun = name * (package -> (common_section * 'a) -> string array -> 'b) type t = { configure: std_args_fun; build: std_args_fun; doc: ((doc, unit) section_args_fun) list; test: ((test, float) section_args_fun) list; install: std_args_fun; uninstall: std_args_fun; clean: std_args_fun list; clean_doc: (doc, unit) section_args_fun list; clean_test: (test, unit) section_args_fun list; distclean: std_args_fun list; distclean_doc: (doc, unit) section_args_fun list; distclean_test: (test, unit) section_args_fun list; package: package; oasis_fn: string option; oasis_version: string; oasis_digest: Digest.t option; oasis_exec: string option; oasis_setup_args: string list; setup_update: bool; } (* Associate a plugin function with data from package *) let join_plugin_sections filter_map lst = List.rev (List.fold_left (fun acc sct -> match filter_map sct with | Some e -> e :: acc | None -> acc) [] lst) (* Search for plugin data associated with a section name *) let lookup_plugin_section plugin action nm lst = try List.assoc nm lst with Not_found -> failwithf (f_ "Cannot find plugin %s matching section %s for %s action") plugin nm action let configure t args = (* Run configure *) BaseCustom.hook t.package.conf_custom (fun () -> (* Reload if preconf has changed it *) begin try unload (); load (); with _ -> () end; (* Run plugin's configure *) t.configure t.package args; (* Dump to allow postconf to change it *) dump ()) (); (* Reload environment *) unload (); load (); (* Save environment *) print (); (* Replace data in file *) BaseFileAB.replace t.package.files_ab let build t args = BaseCustom.hook t.package.build_custom (t.build t.package) args let doc t args = BaseDoc.doc (join_plugin_sections (function | Doc (cs, e) -> Some (lookup_plugin_section "documentation" (s_ "build") cs.cs_name t.doc, cs, e) | _ -> None) t.package.sections) t.package args let test t args = BaseTest.test (join_plugin_sections (function | Test (cs, e) -> Some (lookup_plugin_section "test" (s_ "run") cs.cs_name t.test, cs, e) | _ -> None) t.package.sections) t.package args let all t args = let rno_doc = ref false in let rno_test = ref false in Arg.parse_argv ~current:(ref 0) (Array.of_list ((Sys.executable_name^" all") :: (Array.to_list args))) [ "-no-doc", Arg.Set rno_doc, s_ "Don't run doc target"; "-no-test", Arg.Set rno_test, s_ "Don't run test target"; ] (failwithf (f_ "Don't know what to do with '%s'")) ""; info "Running configure step"; configure t [||]; info "Running build step"; build t [||]; (* Load setup.log dynamic variables *) BaseDynVar.init t.package; if not !rno_doc then begin info "Running doc step"; doc t [||]; end else begin info "Skipping doc step" end; if not !rno_test then begin info "Running test step"; test t [||] end else begin info "Skipping test step" end let install t args = BaseCustom.hook t.package.install_custom (t.install t.package) args let uninstall t args = BaseCustom.hook t.package.uninstall_custom (t.uninstall t.package) args let reinstall t args = uninstall t args; install t args let clean, distclean = let failsafe f a = try f a with e -> warning (f_ "Action fail with error: %s") (match e with | Failure msg -> msg | e -> Printexc.to_string e) in let generic_clean t cstm mains docs tests args = BaseCustom.hook ~failsafe:true cstm (fun () -> (* Clean section *) List.iter (function | Test (cs, test) -> let f = try List.assoc cs.cs_name tests with Not_found -> fun _ _ _ -> () in failsafe (f t.package (cs, test)) args | Doc (cs, doc) -> let f = try List.assoc cs.cs_name docs with Not_found -> fun _ _ _ -> () in failsafe (f t.package (cs, doc)) args | Library _ | Executable _ | Flag _ | SrcRepo _ -> ()) t.package.sections; (* Clean whole package *) List.iter (fun f -> failsafe (f t.package) args) mains) () in let clean t args = generic_clean t t.package.clean_custom t.clean t.clean_doc t.clean_test args in let distclean t args = (* Call clean *) clean t args; (* Call distclean code *) generic_clean t t.package.distclean_custom t.distclean t.distclean_doc t.distclean_test args; (* Remove generated file *) List.iter (fun fn -> if Sys.file_exists fn then begin info (f_ "Remove '%s'") fn; Sys.remove fn end) (BaseEnv.default_filename :: BaseLog.default_filename :: (List.rev_map BaseFileAB.to_filename t.package.files_ab)) in clean, distclean let version t _ = print_endline t.oasis_version let update_setup_ml, no_update_setup_ml_cli = let b = ref true in b, ("-no-update-setup-ml", Arg.Clear b, s_ " Don't try to update setup.ml, even if _oasis has changed.") let update_setup_ml t = let oasis_fn = match t.oasis_fn with | Some fn -> fn | None -> "_oasis" in let oasis_exec = match t.oasis_exec with | Some fn -> fn | None -> "oasis" in let ocaml = Sys.executable_name in let setup_ml, args = match Array.to_list Sys.argv with | setup_ml :: args -> setup_ml, args | [] -> failwith (s_ "Expecting non-empty command line arguments.") in let ocaml, setup_ml = if Sys.executable_name = Sys.argv.(0) then (* We are not running in standard mode, probably the script * is precompiled. *) "ocaml", "setup.ml" else ocaml, setup_ml in let no_update_setup_ml_cli, _, _ = no_update_setup_ml_cli in let do_update () = let oasis_exec_version = OASISExec.run_read_one_line ~ctxt:!BaseContext.default ~f_exit_code: (function | 0 -> () | 1 -> failwithf (f_ "Executable '%s' is probably an old version \ of oasis (< 0.3.0), please update to version \ v%s.") oasis_exec t.oasis_version | 127 -> failwithf (f_ "Cannot find executable '%s', please install \ oasis v%s.") oasis_exec t.oasis_version | n -> failwithf (f_ "Command '%s version' exited with code %d.") oasis_exec n) oasis_exec ["version"] in if OASISVersion.comparator_apply (OASISVersion.version_of_string oasis_exec_version) (OASISVersion.VGreaterEqual (OASISVersion.version_of_string t.oasis_version)) then begin (* We have a version >= for the executable oasis, proceed with * update. *) (* TODO: delegate this check to 'oasis setup'. *) if Sys.os_type = "Win32" then failwithf (f_ "It is not possible to update the running script \ setup.ml on Windows. Please update setup.ml by \ running '%s'.") (String.concat " " (oasis_exec :: "setup" :: t.oasis_setup_args)) else begin OASISExec.run ~ctxt:!BaseContext.default ~f_exit_code: (function | 0 -> () | n -> failwithf (f_ "Unable to update setup.ml using '%s', \ please fix the problem and retry.") oasis_exec) oasis_exec ("setup" :: t.oasis_setup_args); OASISExec.run ~ctxt:!BaseContext.default ocaml (setup_ml :: args) end end else failwithf (f_ "The version of '%s' (v%s) doesn't match the version of \ oasis used to generate the %s file. Please install at \ least oasis v%s.") oasis_exec oasis_exec_version setup_ml t.oasis_version in if !update_setup_ml then begin try match t.oasis_digest with | Some dgst -> if Sys.file_exists oasis_fn && dgst <> Digest.file "_oasis" then begin do_update (); true end else false | None -> false with e -> error (f_ "Error when updating setup.ml. If you want to avoid this error, \ you can bypass the update of %s by running '%s %s %s %s'") setup_ml ocaml setup_ml no_update_setup_ml_cli (String.concat " " args); raise e end else false let setup t = let catch_exn = ref true in try let act_ref = ref (fun _ -> failwithf (f_ "No action defined, run '%s %s -help'") Sys.executable_name Sys.argv.(0)) in let extra_args_ref = ref [] in let allow_empty_env_ref = ref false in let arg_handle ?(allow_empty_env=false) act = Arg.Tuple [ Arg.Rest (fun str -> extra_args_ref := str :: !extra_args_ref); Arg.Unit (fun () -> allow_empty_env_ref := allow_empty_env; act_ref := act); ] in Arg.parse (Arg.align ([ "-configure", arg_handle ~allow_empty_env:true configure, s_ "[options*] Configure the whole build process."; "-build", arg_handle build, s_ "[options*] Build executables and libraries."; "-doc", arg_handle doc, s_ "[options*] Build documents."; "-test", arg_handle test, s_ "[options*] Run tests."; "-all", arg_handle ~allow_empty_env:true all, s_ "[options*] Run configure, build, doc and test targets."; "-install", arg_handle install, s_ "[options*] Install libraries, data, executables \ and documents."; "-uninstall", arg_handle uninstall, s_ "[options*] Uninstall libraries, data, executables \ and documents."; "-reinstall", arg_handle reinstall, s_ "[options*] Uninstall and install libraries, data, \ executables and documents."; "-clean", arg_handle ~allow_empty_env:true clean, s_ "[options*] Clean files generated by a build."; "-distclean", arg_handle ~allow_empty_env:true distclean, s_ "[options*] Clean files generated by a build and configure."; "-version", arg_handle ~allow_empty_env:true version, s_ " Display version of OASIS used to generate this setup.ml."; "-no-catch-exn", Arg.Clear catch_exn, s_ " Don't catch exception, useful for debugging."; ] @ (if t.setup_update then [no_update_setup_ml_cli] else []) @ (BaseContext.args ()))) (failwithf (f_ "Don't know what to do with '%s'")) (s_ "Setup and run build process current package\n"); (* Build initial environment *) load ~allow_empty:!allow_empty_env_ref (); (** Initialize flags *) List.iter (function | Flag (cs, {flag_description = hlp; flag_default = choices}) -> begin let apply ?short_desc () = var_ignore (var_define ~cli:CLIEnable ?short_desc (OASISUtils.varname_of_string cs.cs_name) (fun () -> string_of_bool (var_choose ~name:(Printf.sprintf (f_ "default value of flag %s") cs.cs_name) ~printer:string_of_bool choices))) in match hlp with | Some hlp -> apply ~short_desc:(fun () -> hlp) () | None -> apply () end | _ -> ()) t.package.sections; BaseStandardVar.init t.package; BaseDynVar.init t.package; if t.setup_update && update_setup_ml t then () else !act_ref t (Array.of_list (List.rev !extra_args_ref)) with e when !catch_exn -> error "%s" (Printexc.to_string e); exit 1 end # 4480 "setup.ml" module InternalConfigurePlugin = struct (* # 21 "src/plugins/internal/InternalConfigurePlugin.ml" *) (** Configure using internal scheme @author Sylvain Le Gall *) open BaseEnv open OASISTypes open OASISUtils open OASISGettext open BaseMessage (** Configure build using provided series of check to be done * and then output corresponding file. *) let configure pkg argv = let var_ignore_eval var = let _s : string = var () in () in let errors = ref SetString.empty in let buff = Buffer.create 13 in let add_errors fmt = Printf.kbprintf (fun b -> errors := SetString.add (Buffer.contents b) !errors; Buffer.clear b) buff fmt in let warn_exception e = warning "%s" (Printexc.to_string e) in (* Check tools *) let check_tools lst = List.iter (function | ExternalTool tool -> begin try var_ignore_eval (BaseCheck.prog tool) with e -> warn_exception e; add_errors (f_ "Cannot find external tool '%s'") tool end | InternalExecutable nm1 -> (* Check that matching tool is built *) List.iter (function | Executable ({cs_name = nm2}, {bs_build = build}, _) when nm1 = nm2 -> if not (var_choose build) then add_errors (f_ "Cannot find buildable internal executable \ '%s' when checking build depends") nm1 | _ -> ()) pkg.sections) lst in let build_checks sct bs = if var_choose bs.bs_build then begin if bs.bs_compiled_object = Native then begin try var_ignore_eval BaseStandardVar.ocamlopt with e -> warn_exception e; add_errors (f_ "Section %s requires native compilation") (OASISSection.string_of_section sct) end; (* Check tools *) check_tools bs.bs_build_tools; (* Check depends *) List.iter (function | FindlibPackage (findlib_pkg, version_comparator) -> begin try var_ignore_eval (BaseCheck.package ?version_comparator findlib_pkg) with e -> warn_exception e; match version_comparator with | None -> add_errors (f_ "Cannot find findlib package %s") findlib_pkg | Some ver_cmp -> add_errors (f_ "Cannot find findlib package %s (%s)") findlib_pkg (OASISVersion.string_of_comparator ver_cmp) end | InternalLibrary nm1 -> (* Check that matching library is built *) List.iter (function | Library ({cs_name = nm2}, {bs_build = build}, _) when nm1 = nm2 -> if not (var_choose build) then add_errors (f_ "Cannot find buildable internal library \ '%s' when checking build depends") nm1 | _ -> ()) pkg.sections) bs.bs_build_depends end in (* Parse command line *) BaseArgExt.parse argv (BaseEnv.args ()); (* OCaml version *) begin match pkg.ocaml_version with | Some ver_cmp -> begin try var_ignore_eval (BaseCheck.version "ocaml" ver_cmp BaseStandardVar.ocaml_version) with e -> warn_exception e; add_errors (f_ "OCaml version %s doesn't match version constraint %s") (BaseStandardVar.ocaml_version ()) (OASISVersion.string_of_comparator ver_cmp) end | None -> () end; (* Findlib version *) begin match pkg.findlib_version with | Some ver_cmp -> begin try var_ignore_eval (BaseCheck.version "findlib" ver_cmp BaseStandardVar.findlib_version) with e -> warn_exception e; add_errors (f_ "Findlib version %s doesn't match version constraint %s") (BaseStandardVar.findlib_version ()) (OASISVersion.string_of_comparator ver_cmp) end | None -> () end; (* FlexDLL *) if BaseStandardVar.os_type () = "Win32" || BaseStandardVar.os_type () = "Cygwin" then begin try var_ignore_eval BaseStandardVar.flexlink with e -> warn_exception e; add_errors (f_ "Cannot find 'flexlink'") end; (* Check build depends *) List.iter (function | Executable (_, bs, _) | Library (_, bs, _) as sct -> build_checks sct bs | Doc (_, doc) -> if var_choose doc.doc_build then check_tools doc.doc_build_tools | Test (_, test) -> if var_choose test.test_run then check_tools test.test_tools | _ -> ()) pkg.sections; (* Check if we need native dynlink (presence of libraries that compile to * native) *) begin let has_cmxa = List.exists (function | Library (_, bs, _) -> var_choose bs.bs_build && (bs.bs_compiled_object = Native || (bs.bs_compiled_object = Best && bool_of_string (BaseStandardVar.is_native ()))) | _ -> false) pkg.sections in if has_cmxa then var_ignore_eval BaseStandardVar.native_dynlink end; (* Check errors *) if SetString.empty != !errors then begin List.iter (fun e -> error "%s" e) (SetString.elements !errors); failwithf (fn_ "%d configuration error" "%d configuration errors" (SetString.cardinal !errors)) (SetString.cardinal !errors) end end module InternalInstallPlugin = struct (* # 21 "src/plugins/internal/InternalInstallPlugin.ml" *) (** Install using internal scheme @author Sylvain Le Gall *) open BaseEnv open BaseStandardVar open BaseMessage open OASISTypes open OASISLibrary open OASISGettext open OASISUtils let exec_hook = ref (fun (cs, bs, exec) -> cs, bs, exec) let lib_hook = ref (fun (cs, bs, lib) -> cs, bs, lib, []) let doc_hook = ref (fun (cs, doc) -> cs, doc) let install_file_ev = "install-file" let install_dir_ev = "install-dir" let install_findlib_ev = "install-findlib" let win32_max_command_line_length = 8000 let split_install_command ocamlfind findlib_name meta files = if Sys.os_type = "Win32" then (* Arguments for the first command: *) let first_args = ["install"; findlib_name; meta] in (* Arguments for remaining commands: *) let other_args = ["install"; findlib_name; "-add"] in (* Extract as much files as possible from [files], [len] is the current command line length: *) let rec get_files len acc files = match files with | [] -> (List.rev acc, []) | file :: rest -> let len = len + 1 + String.length file in if len > win32_max_command_line_length then (List.rev acc, files) else get_files len (file :: acc) rest in (* Split the command into several commands. *) let rec split args files = match files with | [] -> [] | _ -> (* Length of "ocamlfind install [META|-add]" *) let len = List.fold_left (fun len arg -> len + 1 (* for the space *) + String.length arg) (String.length ocamlfind) args in match get_files len [] files with | ([], _) -> failwith (s_ "Command line too long.") | (firsts, others) -> let cmd = args @ firsts in (* Use -add for remaining commands: *) let () = let findlib_ge_132 = OASISVersion.comparator_apply (OASISVersion.version_of_string (BaseStandardVar.findlib_version ())) (OASISVersion.VGreaterEqual (OASISVersion.version_of_string "1.3.2")) in if not findlib_ge_132 then failwithf (f_ "Installing the library %s require to use the flag \ '-add' of ocamlfind because the command line is too \ long. This flag is only available for findlib 1.3.2. \ Please upgrade findlib from %s to 1.3.2") findlib_name (BaseStandardVar.findlib_version ()) in let cmds = split other_args others in cmd :: cmds in (* The first command does not use -add: *) split first_args files else ["install" :: findlib_name :: meta :: files] let install pkg argv = let in_destdir = try let destdir = destdir () in (* Practically speaking destdir is prepended * at the beginning of the target filename *) fun fn -> destdir^fn with PropList.Not_set _ -> fun fn -> fn in let install_file ?tgt_fn src_file envdir = let tgt_dir = in_destdir (envdir ()) in let tgt_file = Filename.concat tgt_dir (match tgt_fn with | Some fn -> fn | None -> Filename.basename src_file) in (* Create target directory if needed *) OASISFileUtil.mkdir_parent ~ctxt:!BaseContext.default (fun dn -> info (f_ "Creating directory '%s'") dn; BaseLog.register install_dir_ev dn) tgt_dir; (* Really install files *) info (f_ "Copying file '%s' to '%s'") src_file tgt_file; OASISFileUtil.cp ~ctxt:!BaseContext.default src_file tgt_file; BaseLog.register install_file_ev tgt_file in (* Install data into defined directory *) let install_data srcdir lst tgtdir = let tgtdir = OASISHostPath.of_unix (var_expand tgtdir) in List.iter (fun (src, tgt_opt) -> let real_srcs = OASISFileUtil.glob ~ctxt:!BaseContext.default (Filename.concat srcdir src) in if real_srcs = [] then failwithf (f_ "Wildcard '%s' doesn't match any files") src; List.iter (fun fn -> install_file fn (fun () -> match tgt_opt with | Some s -> OASISHostPath.of_unix (var_expand s) | None -> tgtdir)) real_srcs) lst in (** Install all libraries *) let install_libs pkg = let files_of_library (f_data, acc) data_lib = let cs, bs, lib, lib_extra = !lib_hook data_lib in if var_choose bs.bs_install && BaseBuilt.is_built BaseBuilt.BLib cs.cs_name then begin let acc = (* Start with acc + lib_extra *) List.rev_append lib_extra acc in let acc = (* Add uncompiled header from the source tree *) let path = OASISHostPath.of_unix bs.bs_path in List.fold_left (fun acc modul -> try List.find OASISFileUtil.file_exists_case (List.map (Filename.concat path) [modul^".mli"; modul^".ml"; String.uncapitalize modul^".mli"; String.capitalize modul^".mli"; String.uncapitalize modul^".ml"; String.capitalize modul^".ml"]) :: acc with Not_found -> begin warning (f_ "Cannot find source header for module %s \ in library %s") modul cs.cs_name; acc end) acc lib.lib_modules in let acc = (* Get generated files *) BaseBuilt.fold BaseBuilt.BLib cs.cs_name (fun acc fn -> fn :: acc) acc in let f_data () = (* Install data associated with the library *) install_data bs.bs_path bs.bs_data_files (Filename.concat (datarootdir ()) pkg.name); f_data () in (f_data, acc) end else begin (f_data, acc) end in (* Install one group of library *) let install_group_lib grp = (* Iterate through all group nodes *) let rec install_group_lib_aux data_and_files grp = let data_and_files, children = match grp with | Container (_, children) -> data_and_files, children | Package (_, cs, bs, lib, children) -> files_of_library data_and_files (cs, bs, lib), children in List.fold_left install_group_lib_aux data_and_files children in (* Findlib name of the root library *) let findlib_name = findlib_of_group grp in (* Determine root library *) let root_lib = root_of_group grp in (* All files to install for this library *) let f_data, files = install_group_lib_aux (ignore, []) grp in (* Really install, if there is something to install *) if files = [] then begin warning (f_ "Nothing to install for findlib library '%s'") findlib_name end else begin let meta = (* Search META file *) let (_, bs, _) = root_lib in let res = Filename.concat bs.bs_path "META" in if not (OASISFileUtil.file_exists_case res) then failwithf (f_ "Cannot find file '%s' for findlib library %s") res findlib_name; res in let files = (* Make filename shorter to avoid hitting command max line length * too early, esp. on Windows. *) let remove_prefix p n = let plen = String.length p in let nlen = String.length n in if plen <= nlen && String.sub n 0 plen = p then begin let fn_sep = if Sys.os_type = "Win32" then '\\' else '/' in let cutpoint = plen + (if plen < nlen && n.[plen] = fn_sep then 1 else 0) in String.sub n cutpoint (nlen - cutpoint) end else n in List.map (remove_prefix (Sys.getcwd ())) files in info (f_ "Installing findlib library '%s'") findlib_name; let ocamlfind = ocamlfind () in let commands = split_install_command ocamlfind findlib_name meta files in List.iter (OASISExec.run ~ctxt:!BaseContext.default ocamlfind) commands; BaseLog.register install_findlib_ev findlib_name end; (* Install data files *) f_data (); in let group_libs, _, _ = findlib_mapping pkg in (* We install libraries in groups *) List.iter install_group_lib group_libs in let install_execs pkg = let install_exec data_exec = let (cs, bs, exec) = !exec_hook data_exec in if var_choose bs.bs_install && BaseBuilt.is_built BaseBuilt.BExec cs.cs_name then begin let exec_libdir () = Filename.concat (libdir ()) pkg.name in BaseBuilt.fold BaseBuilt.BExec cs.cs_name (fun () fn -> install_file ~tgt_fn:(cs.cs_name ^ ext_program ()) fn bindir) (); BaseBuilt.fold BaseBuilt.BExecLib cs.cs_name (fun () fn -> install_file fn exec_libdir) (); install_data bs.bs_path bs.bs_data_files (Filename.concat (datarootdir ()) pkg.name) end in List.iter (function | Executable (cs, bs, exec)-> install_exec (cs, bs, exec) | _ -> ()) pkg.sections in let install_docs pkg = let install_doc data = let (cs, doc) = !doc_hook data in if var_choose doc.doc_install && BaseBuilt.is_built BaseBuilt.BDoc cs.cs_name then begin let tgt_dir = OASISHostPath.of_unix (var_expand doc.doc_install_dir) in BaseBuilt.fold BaseBuilt.BDoc cs.cs_name (fun () fn -> install_file fn (fun () -> tgt_dir)) (); install_data Filename.current_dir_name doc.doc_data_files doc.doc_install_dir end in List.iter (function | Doc (cs, doc) -> install_doc (cs, doc) | _ -> ()) pkg.sections in install_libs pkg; install_execs pkg; install_docs pkg (* Uninstall already installed data *) let uninstall _ argv = List.iter (fun (ev, data) -> if ev = install_file_ev then begin if OASISFileUtil.file_exists_case data then begin info (f_ "Removing file '%s'") data; Sys.remove data end else begin warning (f_ "File '%s' doesn't exist anymore") data end end else if ev = install_dir_ev then begin if Sys.file_exists data && Sys.is_directory data then begin if Sys.readdir data = [||] then begin info (f_ "Removing directory '%s'") data; OASISFileUtil.rmdir ~ctxt:!BaseContext.default data end else begin warning (f_ "Directory '%s' is not empty (%s)") data (String.concat ", " (Array.to_list (Sys.readdir data))) end end else begin warning (f_ "Directory '%s' doesn't exist anymore") data end end else if ev = install_findlib_ev then begin info (f_ "Removing findlib library '%s'") data; OASISExec.run ~ctxt:!BaseContext.default (ocamlfind ()) ["remove"; data] end else failwithf (f_ "Unknown log event '%s'") ev; BaseLog.unregister ev data) (* We process event in reverse order *) (List.rev (BaseLog.filter [install_file_ev; install_dir_ev; install_findlib_ev;])) end # 5233 "setup.ml" module OCamlbuildCommon = struct (* # 21 "src/plugins/ocamlbuild/OCamlbuildCommon.ml" *) (** Functions common to OCamlbuild build and doc plugin *) open OASISGettext open BaseEnv open BaseStandardVar let ocamlbuild_clean_ev = "ocamlbuild-clean" let ocamlbuildflags = var_define ~short_desc:(fun () -> "OCamlbuild additional flags") "ocamlbuildflags" (fun () -> "") (** Fix special arguments depending on environment *) let fix_args args extra_argv = List.flatten [ if (os_type ()) = "Win32" then [ "-classic-display"; "-no-log"; "-no-links"; "-install-lib-dir"; (Filename.concat (standard_library ()) "ocamlbuild") ] else []; if not (bool_of_string (is_native ())) || (os_type ()) = "Win32" then [ "-byte-plugin" ] else []; args; if bool_of_string (debug ()) then ["-tag"; "debug"] else []; if bool_of_string (profile ()) then ["-tag"; "profile"] else []; OASISString.nsplit (ocamlbuildflags ()) ' '; Array.to_list extra_argv; ] (** Run 'ocamlbuild -clean' if not already done *) let run_clean extra_argv = let extra_cli = String.concat " " (Array.to_list extra_argv) in (* Run if never called with these args *) if not (BaseLog.exists ocamlbuild_clean_ev extra_cli) then begin OASISExec.run ~ctxt:!BaseContext.default (ocamlbuild ()) (fix_args ["-clean"] extra_argv); BaseLog.register ocamlbuild_clean_ev extra_cli; at_exit (fun () -> try BaseLog.unregister ocamlbuild_clean_ev extra_cli with _ -> ()) end (** Run ocamlbuild, unregister all clean events *) let run_ocamlbuild args extra_argv = (* TODO: enforce that target in args must be UNIX encoded i.e. toto/index.html *) OASISExec.run ~ctxt:!BaseContext.default (ocamlbuild ()) (fix_args args extra_argv); (* Remove any clean event, we must run it again *) List.iter (fun (e, d) -> BaseLog.unregister e d) (BaseLog.filter [ocamlbuild_clean_ev]) (** Determine real build directory *) let build_dir extra_argv = let rec search_args dir = function | "-build-dir" :: dir :: tl -> search_args dir tl | _ :: tl -> search_args dir tl | [] -> dir in search_args "_build" (fix_args [] extra_argv) end module OCamlbuildPlugin = struct (* # 21 "src/plugins/ocamlbuild/OCamlbuildPlugin.ml" *) (** Build using ocamlbuild @author Sylvain Le Gall *) open OASISTypes open OASISGettext open OASISUtils open BaseEnv open OCamlbuildCommon open BaseStandardVar open BaseMessage let cond_targets_hook = ref (fun lst -> lst) let build pkg argv = (* Return the filename in build directory *) let in_build_dir fn = Filename.concat (build_dir argv) fn in (* Return the unix filename in host build directory *) let in_build_dir_of_unix fn = in_build_dir (OASISHostPath.of_unix fn) in let cond_targets = List.fold_left (fun acc -> function | Library (cs, bs, lib) when var_choose bs.bs_build -> begin let evs, unix_files = BaseBuilt.of_library in_build_dir_of_unix (cs, bs, lib) in let ends_with nd fn = let nd_len = String.length nd in (String.length fn >= nd_len) && (String.sub fn (String.length fn - nd_len) nd_len) = nd in let tgts = List.flatten (List.filter (fun l -> l <> []) (List.map (List.filter (fun fn -> ends_with ".cma" fn || ends_with ".cmxs" fn || ends_with ".cmxa" fn || ends_with (ext_lib ()) fn || ends_with (ext_dll ()) fn)) unix_files)) in match tgts with | _ :: _ -> (evs, tgts) :: acc | [] -> failwithf (f_ "No possible ocamlbuild targets for library %s") cs.cs_name end | Executable (cs, bs, exec) when var_choose bs.bs_build -> begin let evs, unix_exec_is, unix_dll_opt = BaseBuilt.of_executable in_build_dir_of_unix (cs, bs, exec) in let target ext = let unix_tgt = (OASISUnixPath.concat bs.bs_path (OASISUnixPath.chop_extension exec.exec_main_is))^ext in let evs = (* Fix evs, we want to use the unix_tgt, without copying *) List.map (function | BaseBuilt.BExec, nm, lst when nm = cs.cs_name -> BaseBuilt.BExec, nm, [[in_build_dir_of_unix unix_tgt]] | ev -> ev) evs in evs, [unix_tgt] in (* Add executable *) let acc = match bs.bs_compiled_object with | Native -> (target ".native") :: acc | Best when bool_of_string (is_native ()) -> (target ".native") :: acc | Byte | Best -> (target ".byte") :: acc in acc end | Library _ | Executable _ | Test _ | SrcRepo _ | Flag _ | Doc _ -> acc) [] (* Keep the pkg.sections ordered *) (List.rev pkg.sections); in (* Check and register built files *) let check_and_register (bt, bnm, lst) = List.iter (fun fns -> if not (List.exists OASISFileUtil.file_exists_case fns) then failwithf (f_ "No one of expected built files %s exists") (String.concat (s_ ", ") (List.map (Printf.sprintf "'%s'") fns))) lst; (BaseBuilt.register bt bnm lst) in let cond_targets = (* Run the hook *) !cond_targets_hook cond_targets in (* Run a list of target... *) run_ocamlbuild (List.flatten (List.map snd cond_targets)) argv; (* ... and register events *) List.iter check_and_register (List.flatten (List.map fst cond_targets)) let clean pkg extra_args = run_clean extra_args; List.iter (function | Library (cs, _, _) -> BaseBuilt.unregister BaseBuilt.BLib cs.cs_name | Executable (cs, _, _) -> BaseBuilt.unregister BaseBuilt.BExec cs.cs_name; BaseBuilt.unregister BaseBuilt.BExecLib cs.cs_name | _ -> ()) pkg.sections end module OCamlbuildDocPlugin = struct (* # 21 "src/plugins/ocamlbuild/OCamlbuildDocPlugin.ml" *) (* Create documentation using ocamlbuild .odocl files @author Sylvain Le Gall *) open OASISTypes open OASISGettext open OASISMessage open OCamlbuildCommon open BaseStandardVar let doc_build path pkg (cs, doc) argv = let index_html = OASISUnixPath.make [ path; cs.cs_name^".docdir"; "index.html"; ] in let tgt_dir = OASISHostPath.make [ build_dir argv; OASISHostPath.of_unix path; cs.cs_name^".docdir"; ] in run_ocamlbuild [index_html] argv; List.iter (fun glb -> BaseBuilt.register BaseBuilt.BDoc cs.cs_name [OASISFileUtil.glob ~ctxt:!BaseContext.default (Filename.concat tgt_dir glb)]) ["*.html"; "*.css"] let doc_clean t pkg (cs, doc) argv = run_clean argv; BaseBuilt.unregister BaseBuilt.BDoc cs.cs_name end # 5558 "setup.ml" module CustomPlugin = struct (* # 21 "src/plugins/custom/CustomPlugin.ml" *) (** Generate custom configure/build/doc/test/install system @author *) open BaseEnv open OASISGettext open OASISTypes type t = { cmd_main: command_line conditional; cmd_clean: (command_line option) conditional; cmd_distclean: (command_line option) conditional; } let run = BaseCustom.run let main t _ extra_args = let cmd, args = var_choose ~name:(s_ "main command") t.cmd_main in run cmd args extra_args let clean t pkg extra_args = match var_choose t.cmd_clean with | Some (cmd, args) -> run cmd args extra_args | _ -> () let distclean t pkg extra_args = match var_choose t.cmd_distclean with | Some (cmd, args) -> run cmd args extra_args | _ -> () module Build = struct let main t pkg extra_args = main t pkg extra_args; List.iter (fun sct -> let evs = match sct with | Library (cs, bs, lib) when var_choose bs.bs_build -> begin let evs, _ = BaseBuilt.of_library OASISHostPath.of_unix (cs, bs, lib) in evs end | Executable (cs, bs, exec) when var_choose bs.bs_build -> begin let evs, _, _ = BaseBuilt.of_executable OASISHostPath.of_unix (cs, bs, exec) in evs end | _ -> [] in List.iter (fun (bt, bnm, lst) -> BaseBuilt.register bt bnm lst) evs) pkg.sections let clean t pkg extra_args = clean t pkg extra_args; (* TODO: this seems to be pretty generic (at least wrt to ocamlbuild * considering moving this to BaseSetup? *) List.iter (function | Library (cs, _, _) -> BaseBuilt.unregister BaseBuilt.BLib cs.cs_name | Executable (cs, _, _) -> BaseBuilt.unregister BaseBuilt.BExec cs.cs_name; BaseBuilt.unregister BaseBuilt.BExecLib cs.cs_name | _ -> ()) pkg.sections let distclean t pkg extra_args = distclean t pkg extra_args end module Test = struct let main t pkg (cs, test) extra_args = try main t pkg extra_args; 0.0 with Failure s -> BaseMessage.warning (f_ "Test '%s' fails: %s") cs.cs_name s; 1.0 let clean t pkg (cs, test) extra_args = clean t pkg extra_args let distclean t pkg (cs, test) extra_args = distclean t pkg extra_args end module Doc = struct let main t pkg (cs, _) extra_args = main t pkg extra_args; BaseBuilt.register BaseBuilt.BDoc cs.cs_name [] let clean t pkg (cs, _) extra_args = clean t pkg extra_args; BaseBuilt.unregister BaseBuilt.BDoc cs.cs_name let distclean t pkg (cs, _) extra_args = distclean t pkg extra_args end end # 5694 "setup.ml" open OASISTypes;; let setup_t = { BaseSetup.configure = InternalConfigurePlugin.configure; build = OCamlbuildPlugin.build; test = [ ("main", CustomPlugin.Test.main { CustomPlugin.cmd_main = [(OASISExpr.EBool true, ("$test", ["&&"; "$testba"]))]; cmd_clean = [(OASISExpr.EBool true, None)]; cmd_distclean = [(OASISExpr.EBool true, None)]; }) ]; doc = [("api", OCamlbuildDocPlugin.doc_build "src/")]; install = InternalInstallPlugin.install; uninstall = InternalInstallPlugin.uninstall; clean = [OCamlbuildPlugin.clean]; clean_test = [ ("main", CustomPlugin.Test.clean { CustomPlugin.cmd_main = [(OASISExpr.EBool true, ("$test", ["&&"; "$testba"]))]; cmd_clean = [(OASISExpr.EBool true, None)]; cmd_distclean = [(OASISExpr.EBool true, None)]; }) ]; clean_doc = [("api", OCamlbuildDocPlugin.doc_clean "src/")]; distclean = []; distclean_test = [ ("main", CustomPlugin.Test.distclean { CustomPlugin.cmd_main = [(OASISExpr.EBool true, ("$test", ["&&"; "$testba"]))]; cmd_clean = [(OASISExpr.EBool true, None)]; cmd_distclean = [(OASISExpr.EBool true, None)]; }) ]; distclean_doc = []; package = { oasis_version = "0.3"; ocaml_version = None; findlib_version = None; name = "extunix"; version = "0.0.6"; license = OASISLicense.DEP5License (OASISLicense.DEP5Unit { OASISLicense.license = "LGPL"; excption = Some "OCaml linking"; version = OASISLicense.Version "2.1"; }); license_file = None; copyrights = [ "(C) 2010 ygrek"; "(C) 2009 Sylvain Le Gall"; "(C) 2008-2009 Talend Inc."; "(C) 2010 St\195\169phane Glondu"; "(C) 2005 Joshua Smith"; "(C) 2010 Niki Yoshiuchi"; "(C) 2001 Gerd Stolpmann"; "(C) 2012 Goswin von Brederlow"; "(C) 2012 Andre Nathan"; "(C) 2013 Zhenya Lykhovyd" ]; maintainers = []; authors = [ "ygrek"; "Sylvain Le Gall"; "St\195\169phane Glondu"; "Kaustuv Chaudhuri"; "Joshua Smith"; "Niki Yoshiuchi"; "Gerd Stolpmann"; "Goswin von Brederlow"; "Andre Nathan"; "Zhenya Lykhovyd" ]; homepage = Some "http://extunix.forge.ocamlcore.org/"; synopsis = "Extended functions for OCaml Unix module"; description = Some "Thin bindings to various low-level system APIs (often non-portable)\nwhich are not covered by Unix module.\n\nSome of the implemented functions : uname, statvfs, fsync, fadvise,\n fallocate, openat, dirfd, eventfd, signalfd, setrlimit, mlockall, etc"; categories = []; conf_type = (`Configure, "internal", Some "0.3"); conf_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [ (OASISExpr.EBool true, Some (("ocaml", [ "src/discover.ml"; "-ocamlc"; "$ocamlc"; "-ext_obj"; "$ext_obj" ]))) ]; }; build_type = (`Build, "ocamlbuild", Some "0.3"); build_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; install_type = (`Install, "internal", Some "0.3"); install_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; uninstall_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; clean_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; distclean_custom = { pre_command = [ (OASISExpr.EBool true, Some (("$rm", ["$(utoh \"src/config.h\")"]))) ]; post_command = [ (OASISExpr.EBool true, Some (("$rm", ["$(utoh \"src/config.ml\")"]))) ]; }; files_ab = []; sections = [ Flag ({ cs_name = "strict"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { flag_description = Some "Strict compile-time checks"; flag_default = [(OASISExpr.EBool true, true)]; }); Library ({ cs_name = "extunix"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { bs_build = [(OASISExpr.EBool true, true)]; bs_install = [(OASISExpr.EBool true, true)]; bs_path = "src/"; bs_compiled_object = Best; bs_build_depends = [ FindlibPackage ("unix", None); FindlibPackage ("bigarray", None) ]; bs_build_tools = [ExternalTool "ocamlbuild"; ExternalTool "camlp4"]; bs_c_sources = [ "config.h"; "eventfd.c"; "dirfd.c"; "fsync.c"; "statvfs.c"; "atfile.c"; "ioctl_siocgifconf.c"; "uname.c"; "fadvise.c"; "fallocate.c"; "tty_ioctl.c"; "unistd.c"; "stdlib.c"; "signalfd.c"; "ptrace.c"; "resource.c"; "mman.c"; "time.c"; "pts.c"; "execinfo.c"; "malloc.c"; "endian.c"; "read_cred.c"; "fexecve.c"; "sendmsg.c"; "memalign.c"; "endianba.c"; "pread_pwrite_ba.c"; "bigarray.c"; "common.c"; "common.h" ]; bs_data_files = []; bs_ccopt = [ (OASISExpr.EBool true, []); (OASISExpr.EAnd (OASISExpr.EFlag "strict", OASISExpr.ETest ("ccomp_type", "cc")), [ "-std=c89"; "-pedantic"; "-Wno-long-long"; "-Wextra" ]) ]; bs_cclib = [(OASISExpr.EBool true, [])]; bs_dlllib = [(OASISExpr.EBool true, [])]; bs_dllpath = [(OASISExpr.EBool true, [])]; bs_byteopt = [(OASISExpr.EBool true, [])]; bs_nativeopt = [(OASISExpr.EBool true, [])]; }, { lib_modules = ["ExtUnix"]; lib_pack = false; lib_internal_modules = ["ExtUnixAll"; "ExtUnixSpecific"]; lib_findlib_parent = None; lib_findlib_name = None; lib_findlib_containers = []; }); Executable ({ cs_name = "test"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { bs_build = [ (OASISExpr.EBool true, false); (OASISExpr.EFlag "tests", true) ]; bs_install = [(OASISExpr.EBool true, false)]; bs_path = "test/"; bs_compiled_object = Best; bs_build_depends = [ InternalLibrary "extunix"; FindlibPackage ("oUnit", Some (OASISVersion.VGreaterEqual "1.0.3")) ]; bs_build_tools = [ExternalTool "ocamlbuild"; ExternalTool "camlp4"]; bs_c_sources = []; bs_data_files = []; bs_ccopt = [(OASISExpr.EBool true, [])]; bs_cclib = [(OASISExpr.EBool true, [])]; bs_dlllib = [(OASISExpr.EBool true, [])]; bs_dllpath = [(OASISExpr.EBool true, [])]; bs_byteopt = [(OASISExpr.EBool true, [])]; bs_nativeopt = [(OASISExpr.EBool true, [])]; }, {exec_custom = true; exec_main_is = "test.ml"; }); Executable ({ cs_name = "testba"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { bs_build = [ (OASISExpr.EBool true, false); (OASISExpr.EFlag "tests", true) ]; bs_install = [(OASISExpr.EBool true, false)]; bs_path = "test/"; bs_compiled_object = Best; bs_build_depends = [ InternalLibrary "extunix"; FindlibPackage ("oUnit", Some (OASISVersion.VGreaterEqual "1.0.3")) ]; bs_build_tools = [ExternalTool "ocamlbuild"; ExternalTool "camlp4"]; bs_c_sources = []; bs_data_files = []; bs_ccopt = [(OASISExpr.EBool true, [])]; bs_cclib = [(OASISExpr.EBool true, [])]; bs_dlllib = [(OASISExpr.EBool true, [])]; bs_dllpath = [(OASISExpr.EBool true, [])]; bs_byteopt = [(OASISExpr.EBool true, [])]; bs_nativeopt = [(OASISExpr.EBool true, [])]; }, {exec_custom = true; exec_main_is = "testba.ml"; }); Test ({ cs_name = "main"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { test_type = (`Test, "custom", Some "0.3"); test_command = [(OASISExpr.EBool true, ("$test", ["&&"; "$testba"])) ]; test_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; test_working_directory = None; test_run = [ (OASISExpr.ENot (OASISExpr.EFlag "tests"), false); (OASISExpr.EFlag "tests", true) ]; test_tools = [ ExternalTool "ocamlbuild"; ExternalTool "camlp4"; InternalExecutable "test"; InternalExecutable "testba" ]; }); Doc ({ cs_name = "api"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { doc_type = (`Doc, "ocamlbuild", Some "0.3"); doc_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; doc_build = [ (OASISExpr.ENot (OASISExpr.EFlag "docs"), false); (OASISExpr.EFlag "docs", true) ]; doc_install = [(OASISExpr.EBool true, true)]; doc_install_dir = "$htmldir"; doc_title = "API reference for extunix"; doc_authors = [ "ygrek"; "Sylvain Le Gall"; "St\195\169phane Glondu"; "Kaustuv Chaudhuri"; "Joshua Smith"; "Niki Yoshiuchi"; "Gerd Stolpmann"; "Goswin von Brederlow"; "Andre Nathan"; "Zhenya Lykhovyd" ]; doc_abstract = None; doc_format = HTML "index.html"; doc_data_files = []; doc_build_tools = [ ExternalTool "ocamlbuild"; ExternalTool "camlp4"; ExternalTool "ocamldoc" ]; }) ]; plugins = [(`Extra, "DevFiles", Some "0.3"); (`Extra, "META", Some "0.3")]; schema_data = PropList.Data.create (); plugin_data = []; }; oasis_fn = Some "_oasis"; oasis_version = "0.3.0"; oasis_digest = Some "$C\146\1966\135\196\031\245\227K%\rM\244\236"; oasis_exec = None; oasis_setup_args = []; setup_update = false; };; let setup () = BaseSetup.setup setup_t;; # 6096 "setup.ml" (* OASIS_STOP *) let () = setup ();; ocaml-extunix-0.0.6/src/000077500000000000000000000000001212637106200151015ustar00rootroot00000000000000ocaml-extunix-0.0.6/src/META000066400000000000000000000005431212637106200155540ustar00rootroot00000000000000# OASIS_START # DO NOT EDIT (digest: 92e73acdbe98ec4786c197b860a76424) version = "0.0.6" description = "Extended functions for OCaml Unix module" requires = "unix bigarray" archive(byte) = "extunix.cma" archive(byte, plugin) = "extunix.cma" archive(native) = "extunix.cmxa" archive(native, plugin) = "extunix.cmxs" exists_if = "extunix.cma" # OASIS_STOP ocaml-extunix-0.0.6/src/TODO/000077500000000000000000000000001212637106200156465ustar00rootroot00000000000000ocaml-extunix-0.0.6/src/TODO/ftruncate/000077500000000000000000000000001212637106200176415ustar00rootroot00000000000000ocaml-extunix-0.0.6/src/TODO/ftruncate/ftruncate.ml000066400000000000000000000010321212637106200221620ustar00rootroot00000000000000 (** 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.0.6/src/TODO/ftruncate/ftruncateC.c000066400000000000000000000036131212637106200221060ustar00rootroot00000000000000 /* * 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.0.6/src/api.odocl000066400000000000000000000001671212637106200167000ustar00rootroot00000000000000# OASIS_START # DO NOT EDIT (digest: fd350374146f855460acaec852f4e088) ExtUnix ExtUnixAll ExtUnixSpecific # OASIS_STOP ocaml-extunix-0.0.6/src/atfile.c000066400000000000000000000135021212637106200165120ustar00rootroot00000000000000 #define EXTUNIX_WANT_ATFILE #include "config.h" #if defined(EXTUNIX_HAVE_ATFILE) #include "common.h" /* 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 = caml_stat_alloc(caml_string_length(v_name) + 1); int flags = caml_convert_flag_list(v_flags, at_flags_table); flags &= (AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT); /* only allowed flags here */ strcpy(p, String_val(v_name)); caml_enter_blocking_section(); ret = fstatat(Int_val(v_dirfd), p, &buf, flags); caml_leave_blocking_section(); caml_stat_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 = caml_stat_alloc(caml_string_length(v_name) + 1); int ret = 0; int flags = caml_convert_flag_list(v_flags, at_flags_table); flags &= AT_REMOVEDIR; /* only allowed flag here */ strcpy(p, String_val(v_name)); caml_enter_blocking_section(); ret = unlinkat(Int_val(v_dirfd), p, flags); caml_leave_blocking_section(); caml_stat_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_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 = caml_stat_alloc(caml_string_length(path) + 1); strcpy(p, 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(); caml_stat_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 = caml_stat_alloc(caml_string_length(v_name) + 1); strcpy(p, String_val(v_name)); caml_enter_blocking_section(); res = readlinkat_malloc(Int_val(v_dirfd), p); caml_leave_blocking_section(); caml_stat_free(p); if (res == NULL) uerror("readlinkat", v_name); v_link = caml_copy_string(res); free(res); CAMLreturn(v_link); } #endif ocaml-extunix-0.0.6/src/bigarray.c000066400000000000000000000014741212637106200170530ustar00rootroot00000000000000#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); char *str; v_str = caml_alloc_string(len); str = String_val(v_str); memcpy(str, buf + off, len); 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); char *str = String_val(v_str); memcpy(buf + off, str, len); CAMLreturn(Val_unit); } ocaml-extunix-0.0.6/src/common.c000066400000000000000000000010131212637106200165300ustar00rootroot00000000000000 #include "config.h" #include /* otherlibs/unix/open.c */ #ifndef O_NONBLOCK #define O_NONBLOCK O_NDELAY #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 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 */ }; int extunix_open_flags(value v_flags) { return caml_convert_flag_list(v_flags, open_flag_table); } ocaml-extunix-0.0.6/src/common.h000066400000000000000000000000401212637106200165340ustar00rootroot00000000000000 int extunix_open_flags(value); ocaml-extunix-0.0.6/src/dirfd.c000066400000000000000000000005451212637106200163410ustar00rootroot00000000000000 #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.0.6/src/discover.ml000066400000000000000000000230101212637106200172450ustar00rootroot00000000000000(** *) open Printf type arg = | I of string (* check #include available *) | T of string (* check type available *) | DEFINE of string (* define *) | S of string (* check symbol available *) | V of string (* check value available (enum) *) | D of string (* check symbol defined *) | F of string * string (* check structure type available and specified field present in it *) type test = | L of arg list | ANY of arg list list type t = YES of (string * arg list) | NO of string let ocamlc = ref "ocamlc" let ext_obj = ref ".o" 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 filter_map f l = 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_includes = filter_map (function I s -> Some s | _ -> None) let config_defines = [ "_POSIX_C_SOURCE 200809L"; "_XOPEN_SOURCE 700"; "_BSD_SOURCE"; "_LARGEFILE64_SOURCE"; "WIN32_LEAN_AND_MEAN"; "_WIN32_WINNT 0x500"; "CAML_NAME_SPACE"; "_GNU_SOURCE" ] let config_includes = [ "caml/memory.h"; "caml/fail.h"; "caml/unixsupport.h"; "caml/signals.h"; "caml/alloc.h"; "caml/custom.h"; "caml/bigarray.h"; "string.h"; "errno.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 s -> () | T s -> pr "%s var_%d;" s (fresh ()) | DEFINE s -> () | D s -> pr "#ifndef %s" s; pr "#error %s not 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 dev_null = match Sys.os_type with "Win32" -> "NUL" | _ -> "/dev/null" let execute code = let (tmp,ch) = Filename.open_temp_file "discover" ".c" in output_string ch code; flush ch; close_out ch; let cmd = sprintf "%s -c %s%s" !ocamlc (Filename.quote tmp) (if !verbose >= 1 then "" else " 2> " ^ dev_null) in let ret = Sys.command cmd in Sys.remove tmp; (* assumption: C compiler puts object file in current directory *) let base = Filename.chop_extension (Filename.basename tmp) in begin try Sys.remove (base ^ !ext_obj) with Sys_error _ -> () end; ret = 0 let discover (name,test) = print_string ("checking " ^ name ^ (String.make (20 - String.length name) '.')); let rec loop args other = let code = build_code args in match execute 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) 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 ""; pr "#define UNUSED(x) (void)(x)"; 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; 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 with | [] -> () | l -> pr "#if defined(EXTUNIX_WANT_%s)" name; List.iter (print_include b) l; 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 "let have = function"; List.iter (function | YES (name,_) -> pr "| %S -> Some true" name | NO name -> pr "| %S -> Some false" name) result; pr "| _ -> None"; close_out ch let main config = let result = List.map discover config in show_c "src/config.h" result; show_ml "src/config.ml" result let features = [ "EVENTFD", L[ I "sys/eventfd.h"; T "eventfd_t"; S "eventfd"; S "eventfd_read"; S "eventfd_write"; ]; "ATFILE", L[ 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"; ]; "DIRFD", L[ I "sys/types.h"; I "dirent.h"; S "dirfd"; ]; "STATVFS", L[ I "sys/statvfs.h"; T "struct statvfs"; S "statvfs"; S "fstatvfs"; ]; "SIOCGIFCONF", L[ 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", L[ I "sys/socket.h"; I "netinet/in.h"; I "arpa/inet.h"; S "inet_ntoa"; ]; "UNAME", L[ I "sys/utsname.h"; T "struct utsname"; S "uname"; ]; "FADVISE", L[ 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[ 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[ I "unistd.h"; S "ttyname"; ]; "CTERMID", L[ I "stdio.h"; S "ctermid"; V "L_ctermid"; ]; "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"; ]; ]; "REALPATH", L[ I "limits.h"; I "stdlib.h"; S "realpath"; ]; "SIGNALFD", L[ 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"; ]; "STRTIME", L[ I "time.h"; S"strptime"; S"strftime"; S"asctime_r"; S"tzname"; ]; "PTS", L[ I "fcntl.h"; I "stdlib.h"; S "posix_openpt"; S "grantpt"; S "unlockpt"; S "ptsname"; ]; "FCNTL", L[ I"unistd.h"; I"fcntl.h"; S"fcntl"; V"F_GETFL"; ]; "TCPGRP", L[ I"unistd.h"; S"tcgetpgrp"; S"tcsetpgrp"; ]; "EXECINFO", L[ I"execinfo.h"; S"backtrace"; S"backtrace_symbols"; ]; "SETENV", L[ I"stdlib.h"; S"setenv"; S"unsetenv"; ]; "CLEARENV", L[ I"stdlib.h"; S"clearenv"; ]; "MKDTEMP", L[ I"stdlib.h"; S"mkdtemp"; ]; "TIMEGM", L[ I"time.h"; S"timegm"; ]; "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", L[ 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"; ]; "READ_CREDENTIALS", L[ I"sys/types.h"; I"sys/socket.h"; D"SO_PEERCRED"; ]; "FEXECVE", L[ I "unistd.h"; S"fexecve"; ]; "SENDMSG", ANY[ [ I"sys/types.h"; I"sys/socket.h"; S"sendmsg"; S"recvmsg"; D"CMSG_SPACE"; ]; [ I"sys/types.h"; I"sys/socket.h"; S"sendmsg"; S"recvmsg"; F("msghdr","msg_accrights"); ]; ]; "PREAD", L[ I "unistd.h"; S"pread"; ]; "PWRITE", L[ I "unistd.h"; S"pwrite"; ]; "READ", L[ I "unistd.h"; S"read"; ]; "WRITE", L[ I "unistd.h"; S"write"; ]; "MKSTEMPS", L[ I "stdlib.h"; S"mkstemps"; ]; "MKOSTEMPS", L[ I "stdlib.h"; S"mkostemps"; ]; "SETRESUID", L[ I"sys/types.h"; I"unistd.h"; S"setresuid"; S"setresgid" ]; ] let () = let args0 = [ "-ocamlc", Arg.Set_string ocamlc, " ocamlc"; "-ext_obj", Arg.Set_string ext_obj, " C object files extension"; "-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 name, Arg.Unit (fun () -> disabled := name :: !disabled), " disable " ^ name) features in let args = Arg.align (args0 @ args1) in Arg.parse args failwith ("Options are:"); main features ocaml-extunix-0.0.6/src/endian.c000066400000000000000000000104471212637106200165110ustar00rootroot00000000000000#define EXTUNIX_WANT_ENDIAN #include "config.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) { \ 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) { \ char *str = String_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) #include #include /* 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.0.6/src/endianba.c000066400000000000000000000051441212637106200170120ustar00rootroot00000000000000#define EXTUNIX_WANT_ENDIAN #include "config.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) #include #include /* 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.0.6/src/eventfd.c000066400000000000000000000013071212637106200167010ustar00rootroot00000000000000 #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.0.6/src/execinfo.c000066400000000000000000000010241212637106200170420ustar00rootroot00000000000000 #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.0.6/src/extUnix.ml000066400000000000000000000003761212637106200171050ustar00rootroot00000000000000(** ExtUnix *) (** Only functions available on this platform *) module Specific = ExtUnixSpecific (** All functions, those not available on this platform will raise [Not_available] with function name as an argument *) module All = ExtUnixAll ocaml-extunix-0.0.6/src/extUnix.mlpp000066400000000000000000002744251212637106200174550ustar00rootroot00000000000000(** ExtUnix *) (** [Not_available "func"] may be raised by [ExtUnix.All.func] if the wrapped C function is not available on this platform *) exception Not_available of string (** type of buffer used by BA submodules *) type buffer = (int, 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 *) HAVE FSYNC external fsync : Unix.file_descr -> unit = "caml_extunix_fsync" END HAVE FDATASYNC external fdatasync : Unix.file_descr -> unit = "caml_extunix_fdatasync" END 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" END HAVE DIRFD external dirfd : Unix.dir_handle -> Unix.file_descr = "caml_extunix_dirfd" END HAVE STATVFS 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 *) f_namemax : int; (** maximum filename length *) } external statvfs : string -> statvfs = "caml_extunix_statvfs" external fstatvfs : Unix.file_descr -> statvfs = "caml_extunix_fstatvfs" END 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" END HAVE UNAME (** uname {b Author:} Sylvain Le Gall [sylvain\@le-gall.net] *) 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" END HAVE FADVISE (** {2 posix_fadvise} {b 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" END HAVE FALLOCATE (** {2 posix_fallocate} *) (** Allocate disk space for file {b 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" END HAVE PREAD (** {2 pread} {b 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 -> string -> int -> int -> int = "caml_extunix_all_pread" let all_pread fd off buf ofs len = if off < 0 || ofs < 0 || len < 0 || ofs > String.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 -> string -> int -> int -> int = "caml_extunix_single_pread" let single_pread fd off buf ofs len = if off < 0 || ofs < 0 || len < 0 || ofs > String.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 -> string -> int -> int -> int = "caml_extunix_pread" let pread fd off buf ofs len = if off < 0 || ofs < 0 || len < 0 || ofs > String.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 -> string -> int -> int -> int = "caml_extunix_intr_pread" let intr_pread fd off buf ofs len = if off < 0 || ofs < 0 || len < 0 || ofs > String.length buf - len then invalid_arg "ExtUnix.intr_pread" else unsafe_intr_pread fd off buf ofs len END HAVE PWRITE (** {2 pwrite} {b 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 END HAVE READ (** {2 read} {b 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 -> string -> int -> int -> int = "caml_extunix_all_read" let all_read fd buf ofs len = if ofs < 0 || len < 0 || ofs > String.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 -> string -> int -> int -> int = "caml_extunix_single_read" let single_read fd buf ofs len = if ofs < 0 || len < 0 || ofs > String.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 -> string -> int -> int -> int = "caml_extunix_read" let read fd buf ofs len = if ofs < 0 || len < 0 || ofs > String.length buf - len then invalid_arg "ExtUnix.pread" 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 -> string -> int -> int -> int = "caml_extunix_intr_read" let intr_read fd buf ofs len = if ofs < 0 || len < 0 || ofs > String.length buf - len then invalid_arg "ExtUnix.intr_read" else unsafe_intr_read fd buf ofs len END HAVE WRITE (** {2 write} {b 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.pwrite" 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 END (** {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" END HAVE FALLOCATE external fallocate: Unix.file_descr -> int64 -> int64 -> unit = "caml_extunix_fallocate64" END HAVE PREAD external unsafe_all_pread: Unix.file_descr -> int64 -> string -> 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 -> string -> 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 -> string -> 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 -> string -> 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 END 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 END (** {2 Bigarray variants} *) (** *) module BA = struct HAVE PREAD external unsafe_all_pread: Unix.file_descr -> int64 -> buffer -> 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 -> buffer -> 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 -> buffer -> 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 -> buffer -> 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 END HAVE PWRITE external unsafe_all_pwrite: Unix.file_descr -> int64 -> buffer -> 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 -> buffer -> 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 -> buffer -> 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 -> buffer -> 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 end (* module BA *) end (* module LargeFile *) (** {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" END 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 end (* module Ioctl *) (** {2 Miscellaneous} *) HAVE TTYNAME (** @return name of terminal *) external ttyname : Unix.file_descr -> string = "caml_extunix_ttyname" END HAVE CTERMID (** Get controlling terminal name *) external ctermid : unit -> string = "caml_extunix_ctermid" END 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" END 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. @see "setreuid(2)" manual *) 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. @see "setregid(2)" manual *) external setregid : int -> int -> unit = "caml_extunix_setregid" END 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. @see "setresuid(2)" manual *) 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. @see "setresgid(2)" manual *) external setresgid: int -> int -> int -> unit = "caml_extunix_setresgid" END HAVE REALPATH (** [realpath path] @return the canonicalized absolute pathname of [path] @see "realpath(2)" manual *) external realpath : string -> string = "caml_extunix_realpath" END HAVE FCNTL (** @return whether file desctiptor is open *) external is_open_descr : Unix.file_descr -> bool = "caml_extunix_is_open_descr" END HAVE IFADDRS (** @return the list of [PF_INET] interfaces and corresponding addresses ({b may change}) *) external getifaddrs : unit -> (string * string) list = "caml_extunix_getifaddrs" END HAVE TCPGRP external tcgetpgrp : Unix.file_descr -> int = "caml_extunix_tcgetpgrp" external tcsetpgrp : Unix.file_descr -> int -> unit = "caml_extunix_tcsetpgrp" END (** @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 (** Exit process without running any [at_exit] hooks (implemented in Pervasives) *) external sys_exit : int -> 'a = "caml_sys_exit" HAVE SIGNALFD (** {2 signalfd} *) (** OCaml bindings for signalfd(2) and related functions {b 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. @see "signalfd(2)" manual *) 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" (** {6 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" END HAVE RESOURCE (** {2 POSIX resource operations} {b 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]. *) END (** {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" END 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) {b Author:} Goswin von Brederlow *) external memalign: int -> int -> buffer = "caml_extunix_memalign" END (** {2 Time conversion} *) HAVE STRTIME (** 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" (** 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] convert a 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" END HAVE TIMEGM (** Inverse of [Unix.gmtime] *) external timegm : Unix.tm -> float = "caml_extunix_timegm" END HAVE PTS (** {2 Pseudo terminal management} {b 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" END (** {2 Application self-debugging and diagnostics} *) HAVE EXECINFO (** @return a backtrace for the calling program *) external backtrace : unit -> string array = "caml_extunix_backtrace" END HAVE MALLOC_STATS (** Print brief heap summary statistics on stderr *) external malloc_stats : unit -> unit = "caml_extunix_malloc_stats" END HAVE MALLOC_INFO (** @return the information about state of allocator *) external malloc_info : unit -> string = "caml_extunix_malloc_info" END 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" END (** {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" END HAVE CLEARENV (** Clear the environment of all name-value pairs *) external clearenv : unit -> unit = "caml_extunix_clearenv" END (** {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" END HAVE MKSTEMPS (**/**) (** internal use only *) external internal_mkstemps : string -> 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 prefixlen = String.length prefix in let suffixlen = String.length suffix in let len = prefixlen + 6 + suffixlen in let s = String.create len in String.blit prefix 0 s 0 prefixlen; String.blit "XXXXXX" 0 s prefixlen 6; String.blit suffix 0 s (prefixlen + 6) suffixlen; let fd = internal_mkstemps s suffixlen in (fd, s) END HAVE MKOSTEMPS (**/**) (** internal use only *) external internal_mkostemps : string -> 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 prefixlen = String.length prefix in let suffixlen = String.length suffix in let len = prefixlen + 6 + suffixlen in let s = String.create len in String.blit prefix 0 s 0 prefixlen; String.blit "XXXXXX" 0 s prefixlen 6; String.blit suffix 0 s (prefixlen + 6) suffixlen; let fd = internal_mkostemps s suffixlen flags in (fd, s) END (** {2 Byte order conversion} *) (** {2 big endian functions} {b 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 str off v] stores the integer [v] as type [X] in string [str] 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 : string -> int -> int -> unit = "caml_extunix_set_8" "noalloc" external unsafe_set_int8 : string -> int -> int -> unit = "caml_extunix_set_8" "noalloc" external unsafe_set_uint16 : string -> int -> int -> unit = "caml_extunix_set_b16" "noalloc" external unsafe_set_int16 : string -> int -> int -> unit = "caml_extunix_set_b16" "noalloc" external unsafe_set_uint31 : string -> int -> int -> unit = "caml_extunix_set_b31" "noalloc" external unsafe_set_int31 : string -> int -> int -> unit = "caml_extunix_set_b31" "noalloc" external unsafe_set_int32 : string -> int -> int32 -> unit = "caml_extunix_set_b32" "noalloc" external unsafe_set_uint63 : string -> int -> int -> unit = "caml_extunix_set_b63" "noalloc" external unsafe_set_int63 : string -> int -> int -> unit = "caml_extunix_set_b63" "noalloc" external unsafe_set_int64 : string -> int -> int64 -> unit = "caml_extunix_set_b64" "noalloc" (** [set_X str off v] same as [unsafe_set_X] but with bounds checking. *) let set_uint8 str off v = if off < 0 || off >= String.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 >= String.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 > String.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 > String.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 > String.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 > String.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 > String.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 > String.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 > String.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 > String.length str - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int64 str off v END end (** {2 little endian functions} {b 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 str off v] stores the integer [v] as type [X] in string [str] 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 : string -> int -> int -> unit = "caml_extunix_set_8" "noalloc" external unsafe_set_int8 : string -> int -> int -> unit = "caml_extunix_set_8" "noalloc" external unsafe_set_uint16 : string -> int -> int -> unit = "caml_extunix_set_l16" "noalloc" external unsafe_set_int16 : string -> int -> int -> unit = "caml_extunix_set_l16" "noalloc" external unsafe_set_uint31 : string -> int -> int -> unit = "caml_extunix_set_l31" "noalloc" external unsafe_set_int31 : string -> int -> int -> unit = "caml_extunix_set_l31" "noalloc" external unsafe_set_int32 : string -> int -> int32 -> unit = "caml_extunix_set_l32" "noalloc" external unsafe_set_uint63 : string -> int -> int -> unit = "caml_extunix_set_l63" "noalloc" external unsafe_set_int63 : string -> int -> int -> unit = "caml_extunix_set_l63" "noalloc" external unsafe_set_int64 : string -> int -> int64 -> unit = "caml_extunix_set_l64" "noalloc" (** [set_X str off v] same as [unsafe_set_X] but with bounds checking. *) let set_uint8 str off v = if off < 0 || off >= String.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 >= String.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 > String.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 > String.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 > String.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 > String.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 > String.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 > String.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 > String.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 > String.length str - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int64 str off v END end (** {2 host endian functions} {b 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 str off v] stores the integer [v] as type [X] in string [str] 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 : string -> int -> int -> unit = "caml_extunix_set_8" "noalloc" external unsafe_set_int8 : string -> int -> int -> unit = "caml_extunix_set_8" "noalloc" external unsafe_set_uint16 : string -> int -> int -> unit = "caml_extunix_set_h16" "noalloc" external unsafe_set_int16 : string -> int -> int -> unit = "caml_extunix_set_h16" "noalloc" external unsafe_set_uint31 : string -> int -> int -> unit = "caml_extunix_set_h31" "noalloc" external unsafe_set_int31 : string -> int -> int -> unit = "caml_extunix_set_h31" "noalloc" external unsafe_set_int32 : string -> int -> int32 -> unit = "caml_extunix_set_h32" "noalloc" external unsafe_set_uint63 : string -> int -> int -> unit = "caml_extunix_set_h63" "noalloc" external unsafe_set_int63 : string -> int -> int -> unit = "caml_extunix_set_h63" "noalloc" external unsafe_set_int64 : string -> int -> int64 -> unit = "caml_extunix_set_h64" "noalloc" (** [set_X str off v] same as [unsafe_set_X] but with bounds checking. *) let set_uint8 str off v = if off < 0 || off >= String.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 >= String.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 > String.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 > String.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 > String.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 > String.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 > String.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 > String.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 > String.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 > String.length str - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int64 str off v end HAVE READ_CREDENTIALS (** {2 read_credentials } {b 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" END HAVE FEXECVE (** {2 fexecve } {b 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" END HAVE SENDMSG (** {2 sendmsg / recvmsg } {b Author:} Andre Nathan *) (** Send a message and optionally a file descriptor through a socket. Passing file descriptors requires UNIX domain sockets. *) 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" (** Send a file descriptor through a UNIX domain socket. *) let sendfd conn_fd fd_to_send = sendmsg conn_fd ~sendfd:fd_to_send "" (** Receive a file descriptor sent through a UNIX domain socket. *) 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 END (** {2 Bigarray variants} *) (** *) module BA = struct HAVE PREAD (** {2 pread} {b 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 -> buffer -> 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 -> buffer -> 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 -> buffer -> 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 -> buffer -> 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 END HAVE PWRITE (** {2 pwrite} {b 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 -> buffer -> 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 -> buffer -> 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 -> buffer -> 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 -> buffer -> 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 END HAVE READ (** {2 read} {b 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 -> buffer -> 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 -> buffer -> 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 -> buffer -> 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 -> buffer -> int = "caml_extunixba_intr_read" END HAVE WRITE (** {2 write} {b 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 -> buffer -> 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 -> buffer -> 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 -> buffer -> 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 -> buffer -> int = "caml_extunixba_intr_write" END (** {2 Byte order conversion} *) (** {2 big endian functions} {b 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 : buffer -> int -> int = "caml_extunixba_get_u8" "noalloc" external unsafe_get_int8 : buffer -> int -> int = "caml_extunixba_get_s8" "noalloc" external unsafe_get_uint16 : buffer -> int -> int = "caml_extunixba_get_bu16" "noalloc" external unsafe_get_int16 : buffer -> int -> int = "caml_extunixba_get_bs16" "noalloc" external unsafe_get_uint31 : buffer -> int -> int = "caml_extunixba_get_bu31" "noalloc" external unsafe_get_int31 : buffer -> int -> int = "caml_extunixba_get_bs31" "noalloc" external unsafe_get_int32 : buffer -> int -> int32 = "caml_extunixba_get_bs32" external unsafe_get_uint63 : buffer -> int -> int = "caml_extunixba_get_bu63" "noalloc" external unsafe_get_int63 : buffer -> int -> int = "caml_extunixba_get_bs63" "noalloc" external unsafe_get_int64 : buffer -> 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 : buffer -> int -> int -> unit = "caml_extunixba_set_8" "noalloc" external unsafe_set_int8 : buffer -> int -> int -> unit = "caml_extunixba_set_8" "noalloc" external unsafe_set_uint16 : buffer -> int -> int -> unit = "caml_extunixba_set_b16" "noalloc" external unsafe_set_int16 : buffer -> int -> int -> unit = "caml_extunixba_set_b16" "noalloc" external unsafe_set_uint31 : buffer -> int -> int -> unit = "caml_extunixba_set_b31" "noalloc" external unsafe_set_int31 : buffer -> int -> int -> unit = "caml_extunixba_set_b31" "noalloc" external unsafe_set_int32 : buffer -> int -> int32 -> unit = "caml_extunixba_set_b32" "noalloc" external unsafe_set_uint63 : buffer -> int -> int -> unit = "caml_extunixba_set_b63" "noalloc" external unsafe_set_int63 : buffer -> int -> int -> unit = "caml_extunixba_set_b63" "noalloc" external unsafe_set_int64 : buffer -> 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 end (** {2 little endian functions} {b 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 : buffer -> int -> int = "caml_extunixba_get_u8" "noalloc" external unsafe_get_int8 : buffer -> int -> int = "caml_extunixba_get_s8" "noalloc" external unsafe_get_uint16 : buffer -> int -> int = "caml_extunixba_get_lu16" "noalloc" external unsafe_get_int16 : buffer -> int -> int = "caml_extunixba_get_ls16" "noalloc" external unsafe_get_uint31 : buffer -> int -> int = "caml_extunixba_get_lu31" "noalloc" external unsafe_get_int31 : buffer -> int -> int = "caml_extunixba_get_ls31" "noalloc" external unsafe_get_int32 : buffer -> int -> int32 = "caml_extunixba_get_ls32" external unsafe_get_uint63 : buffer -> int -> int = "caml_extunixba_get_lu63" "noalloc" external unsafe_get_int63 : buffer -> int -> int = "caml_extunixba_get_ls63" "noalloc" external unsafe_get_int64 : buffer -> 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 : buffer -> int -> int -> unit = "caml_extunixba_set_8" "noalloc" external unsafe_set_int8 : buffer -> int -> int -> unit = "caml_extunixba_set_8" "noalloc" external unsafe_set_uint16 : buffer -> int -> int -> unit = "caml_extunixba_set_l16" "noalloc" external unsafe_set_int16 : buffer -> int -> int -> unit = "caml_extunixba_set_l16" "noalloc" external unsafe_set_uint31 : buffer -> int -> int -> unit = "caml_extunixba_set_l31" "noalloc" external unsafe_set_int31 : buffer -> int -> int -> unit = "caml_extunixba_set_l31" "noalloc" external unsafe_set_int32 : buffer -> int -> int32 -> unit = "caml_extunixba_set_l32" "noalloc" external unsafe_set_uint63 : buffer -> int -> int -> unit = "caml_extunixba_set_l63" "noalloc" external unsafe_set_int63 : buffer -> int -> int -> unit = "caml_extunixba_set_l63" "noalloc" external unsafe_set_int64 : buffer -> 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 end (** {2 host endian functions} {b 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 : buffer -> int -> int = "caml_extunixba_get_u8" "noalloc" external unsafe_get_int8 : buffer -> int -> int = "caml_extunixba_get_s8" "noalloc" external unsafe_get_uint16 : buffer -> int -> int = "caml_extunixba_get_hu16" "noalloc" external unsafe_get_int16 : buffer -> int -> int = "caml_extunixba_get_hs16" "noalloc" external unsafe_get_uint31 : buffer -> int -> int = "caml_extunixba_get_hu31" "noalloc" external unsafe_get_int31 : buffer -> int -> int = "caml_extunixba_get_hs31" "noalloc" external unsafe_get_int32 : buffer -> int -> int32 = "caml_extunixba_get_hs32" external unsafe_get_uint63 : buffer -> int -> int = "caml_extunixba_get_hu63" "noalloc" external unsafe_get_int63 : buffer -> int -> int = "caml_extunixba_get_hs63" "noalloc" external unsafe_get_int64 : buffer -> 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 : buffer -> int -> int -> unit = "caml_extunixba_set_8" "noalloc" external unsafe_set_int8 : buffer -> int -> int -> unit = "caml_extunixba_set_8" "noalloc" external unsafe_set_uint16 : buffer -> int -> int -> unit = "caml_extunixba_set_h16" "noalloc" external unsafe_set_int16 : buffer -> int -> int -> unit = "caml_extunixba_set_h16" "noalloc" external unsafe_set_uint31 : buffer -> int -> int -> unit = "caml_extunixba_set_h31" "noalloc" external unsafe_set_int31 : buffer -> int -> int -> unit = "caml_extunixba_set_h31" "noalloc" external unsafe_set_int32 : buffer -> int -> int32 -> unit = "caml_extunixba_set_h32" "noalloc" external unsafe_set_uint63 : buffer -> int -> int -> unit = "caml_extunixba_set_h63" "noalloc" external unsafe_set_int63 : buffer -> int -> int -> unit = "caml_extunixba_set_h63" "noalloc" external unsafe_set_int64 : buffer -> 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 (** [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 : buffer -> 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 : buffer -> 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 end (* module BA *) (* NB Should be after all 'external' definitions *) (** {2 Meta} *) (** [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"] *) SHOW ME THE MONEY ocaml-extunix-0.0.6/src/extunix.mllib000066400000000000000000000001671212637106200176320ustar00rootroot00000000000000# OASIS_START # DO NOT EDIT (digest: fd350374146f855460acaec852f4e088) ExtUnix ExtUnixAll ExtUnixSpecific # OASIS_STOP ocaml-extunix-0.0.6/src/fadvise.c000066400000000000000000000027221212637106200166710ustar00rootroot00000000000000/* * 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.0.6/src/fallocate.c000066400000000000000000000055261212637106200172070ustar00rootroot00000000000000/* * 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.0.6/src/fexecve.c000066400000000000000000000015471212637106200167010ustar00rootroot00000000000000#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] = 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.0.6/src/fsync.c000066400000000000000000000024621212637106200163730ustar00rootroot00000000000000 #define EXTUNIX_WANT_FSYNC #define EXTUNIX_WANT_FDATASYNC #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 #endif /* WIN32 */ ocaml-extunix-0.0.6/src/ioctl_siocgifconf.c000066400000000000000000000037551212637106200207420ustar00rootroot00000000000000 #define EXTUNIX_WANT_SIOCGIFCONF #define EXTUNIX_WANT_INET_NTOA #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; 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 && iter->ifa_addr->sa_family == AF_INET) { cons = caml_alloc(2, 0); item = caml_alloc(2, 0); Store_field(item, 0, caml_copy_string(iter->ifa_name)); Store_field(item, 1, caml_copy_string(inet_ntoa(((struct sockaddr_in *)iter->ifa_addr)->sin_addr))); 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.0.6/src/libextunix_stubs.clib000066400000000000000000000005751212637106200213560ustar00rootroot00000000000000# OASIS_START # DO NOT EDIT (digest: 6b53d87ae3b32291883dafc0e4541bad) eventfd.o dirfd.o fsync.o statvfs.o atfile.o ioctl_siocgifconf.o uname.o fadvise.o fallocate.o tty_ioctl.o unistd.o stdlib.o signalfd.o ptrace.o resource.o mman.o time.o pts.o execinfo.o malloc.o endian.o read_cred.o fexecve.o sendmsg.o memalign.o endianba.o pread_pwrite_ba.o bigarray.o common.o # OASIS_STOP ocaml-extunix-0.0.6/src/malloc.c000066400000000000000000000014351212637106200165170ustar00rootroot00000000000000 #define EXTUNIX_WANT_MALLOC_INFO #define EXTUNIX_WANT_MALLOC_STATS #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 #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 ocaml-extunix-0.0.6/src/memalign.c000066400000000000000000000015011212637106200170330ustar00rootroot00000000000000 #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.0.6/src/mman.c000066400000000000000000000013361212637106200162000ustar00rootroot00000000000000 #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.0.6/src/pa_have.ml000066400000000000000000000052531212637106200170430ustar00rootroot00000000000000(** New toplevel statement (structure item): HAVE END if (Config.have "") is true then enclosed structure items are left as is, otherwise: if -gen-all was specified then external structure items are rewritten to raise exception when called, otherwise they are dropped altogether *) module Have(Syntax : Camlp4.Sig.Camlp4Syntax) = struct open Camlp4.PreCast include Syntax let all = ref false let verbose = ref false let funcs = Hashtbl.create 16 let rec make_dummy_f body = function | <:ctyp@loc< ~ $s$ : $t$ -> $tl$ >> -> <:expr@loc< fun ~ $s$:(_:$t$) -> $make_dummy_f body tl$ >> | <:ctyp@loc< ? $s$ : $t$ -> $tl$ >> -> <:expr@loc< fun ? $s$:(_:option $t$) -> $make_dummy_f body tl$ >> | <:ctyp@loc< $t$ -> $tl$ >> -> <:expr@loc< fun (_:$t$) -> $make_dummy_f body tl$ >> | <:ctyp< $t$ >> -> let loc = Loc.ghost in <:expr@loc< ($body$ : $t$) >> let invalid_external = function | <:str_item@_loc< external $i$ : $t$ = $sl$ >> -> <:str_item< value $lid:i$ = $make_dummy_f <:expr< raise (Not_available $str:i$) >> t$; >> | e -> e let record_external have si = begin match si with | <:str_item@_loc< external $i$ : $t$ = $sl$ >> -> (* if Hashtbl.mem funcs i then failwith (Printf.sprintf "duplicate external %s" i); *) Hashtbl.replace funcs i have | _ -> () end; si let map_str_item f e = (Ast.map_str_item f)#str_item e let make_have loc = Hashtbl.fold (fun func have acc -> <:match_case@loc< $`str:func$ -> Some ($`bool:have$) | $acc$ >>) funcs <:match_case@loc< _ -> None >> let show name s = if !verbose then Printf.eprintf "%-20s %s\n%!" name s EXTEND Gram GLOBAL: str_item; str_item: [ [ "HAVE"; name=UIDENT; si=str_items; "END" -> match Config.have name with | None -> failwith ("Unregistered feature : " ^ name) | Some have -> let _ = map_str_item (record_external have) <:str_item< $si$ >> in match have, !all with | true, _ -> show name "ok"; si | false, true -> show name "rewrite"; map_str_item invalid_external <:str_item< $si$ >> | false, false -> show name "drop"; <:str_item<>> ] | [ "SHOW"; "ME"; "THE"; "MONEY" -> if !all then <:str_item< value have = fun [ $make_have _loc$ ] >> else <:str_item<>> ] ] ; END ;; Camlp4.Options.add "-gen-all" (Arg.Set all) " generate values from all HAVE sections";; Camlp4.Options.add "-gen-verbose" (Arg.Set verbose) " verbose mode";; end module Id = struct let version = "0" let name = "Have" end module M = Camlp4.Register.OCamlSyntaxExtension(Id)(Have) ocaml-extunix-0.0.6/src/pread_pwrite_ba.c000066400000000000000000000166331212637106200204050ustar00rootroot00000000000000 #define EXTUNIX_WANT_PREAD #define EXTUNIX_WANT_PWRITE #include "config.h" enum mode_bits { BIT_ONCE, BIT_NOERROR, BIT_NOINTR }; #define ONCE (1 << BIT_ONCE) #define NOERROR (1 << BIT_NOERROR) #define NOINTR (1 << BIT_NOINTR) #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_array_val(v_buf)->dim[0]; 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 & NOINTR)) continue; if (processed > 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (mode & NOERROR) break; } uerror("pread", Nothing); } processed += ret; buf += ret; off += ret; len -= ret; if (mode & 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, 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, 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, NOINTR | 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, 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, 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, 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, NOINTR | 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, 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_array_val(v_buf)->dim[0]; 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 & NOINTR)) continue; if (processed > 0){ if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (mode & NOERROR) break; } uerror("pwrite", Nothing); } processed += ret; buf += ret; off += ret; len -= ret; if (mode & 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, 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, 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, NOINTR | 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, 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, 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, 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, NOINTR | 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, 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_array_val(v_buf)->dim[0]; 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 & NOINTR)) continue; if (processed > 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (mode & NOERROR) break; } uerror("read", Nothing); } processed += ret; buf += ret; len -= ret; if (mode & 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, NOINTR); } value caml_extunixba_single_read(value v_fd, value v_buf) { return caml_extunixba_read_common(v_fd, v_buf, ONCE); } value caml_extunixba_read(value v_fd, value v_buf) { return caml_extunixba_read_common(v_fd, v_buf, NOINTR | NOERROR); } value caml_extunixba_intr_read(value v_fd, value v_buf) { return caml_extunixba_read_common(v_fd, v_buf, 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_array_val(v_buf)->dim[0]; 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 & NOINTR)) continue; if (processed > 0){ if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (mode & NOERROR) break; } uerror("write", Nothing); } processed += ret; buf += ret; len -= ret; if (mode & 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, NOINTR); } value caml_extunixba_single_write(value v_fd, value v_buf) { return caml_extunixba_write_common(v_fd, v_buf, ONCE); } value caml_extunixba_write(value v_fd, value v_buf) { return caml_extunixba_write_common(v_fd, v_buf, NOINTR | NOERROR); } value caml_extunixba_intr_write(value v_fd, value v_buf) { return caml_extunixba_write_common(v_fd, v_buf, NOERROR); } #endif ocaml-extunix-0.0.6/src/ptrace.c000066400000000000000000000023601212637106200165240ustar00rootroot00000000000000 #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.0.6/src/pts.c000066400000000000000000000015771212637106200160650ustar00rootroot00000000000000 #define EXTUNIX_WANT_PTS #include "config.h" #if defined(EXTUNIX_HAVE_PTS) #include "common.h" 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.0.6/src/read_cred.c000066400000000000000000000012501212637106200171530ustar00rootroot00000000000000#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.0.6/src/resource.c000066400000000000000000000110221212637106200170700ustar00rootroot00000000000000/******************************************************************************/ /* 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) #include 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.0.6/src/sendmsg.c000066400000000000000000000071251212637106200167120ustar00rootroot00000000000000#define EXTUNIX_WANT_SENDMSG #include "config.h" #if defined(EXTUNIX_HAVE_SENDMSG) /* 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 Val_none Val_int(0) #define Some_val(v) Field(v,0) 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; memset(&msg, 0, sizeof msg); if (sendfd_val != Val_none) { int sendfd = Int_val(Some_val(sendfd_val)); #if defined(CMSG_SPACE) union { struct cmsghdr cmsg; /* for alignment */ char control[CMSG_SPACE(sizeof sendfd)]; } control_un; 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+1); memcpy(buf, String_val(data_val), datalen); buf[datalen] = '\0'; iov[0].iov_base = buf; iov[0].iov_len = strlen(buf); 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 buf[len] = '\0'; Store_field(res, 1, caml_copy_string(buf)); CAMLreturn (res); } #endif /* EXTUNIX_HAVE_SENDMSG */ ocaml-extunix-0.0.6/src/signalfd.c000066400000000000000000000076241212637106200170450ustar00rootroot00000000000000/******************************************************************************/ /* signalfd stubs */ /* */ /* NO COPYRIGHT -- RELEASED INTO THE PUBLIC DOMAIN */ /* */ /* Author: Kaustuv Chaudhuri */ /******************************************************************************/ #define EXTUNIX_WANT_SIGNALFD #include "config.h" #define Some_val(v) Field(v,0) #define Val_none Val_int(0) #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 }; #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.0.6/src/statvfs.c000066400000000000000000000021301212637106200167330ustar00rootroot00000000000000 #define EXTUNIX_WANT_STATVFS #include "config.h" #if defined(EXTUNIX_HAVE_STATVFS) static value convert(struct statvfs* s) { CAMLparam0(); CAMLlocal1(v_s); v_s = caml_alloc(10,0); Store_field(v_s,0,Val_int(s->f_bsize)); 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,Val_int(s->f_namemax)); CAMLreturn(v_s); } 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)); } 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 ocaml-extunix-0.0.6/src/stdlib.c000066400000000000000000000063621212637106200165350ustar00rootroot00000000000000 #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) { 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 #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); char *template = String_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) #include "common.h" /* 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); char *template = String_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.0.6/src/time.c000066400000000000000000000044321212637106200162060ustar00rootroot00000000000000 #define EXTUNIX_WANT_STRTIME #define EXTUNIX_WANT_TIMEGM #include "config.h" #if defined(EXTUNIX_HAVE_STRTIME) /* * 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; } 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 */ } #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 CAMLprim value caml_extunix_asctime(value v_t) { struct tm tm; char buf[32]; /* user-supplied buffer which should have room for at least 26 bytes */ fill_tm(&tm, v_t); if (NULL == asctime_r(&tm,buf)) unix_error(EINVAL, "asctime", Nothing); return caml_copy_string(buf); } CAMLprim value caml_extunix_strftime(value v_fmt, value v_t) { struct tm tm; char buf[256]; fill_tm(&tm, v_t); if (0 == strftime(buf,sizeof(buf),String_val(v_fmt),&tm)) unix_error(EINVAL, "strftime", v_fmt); return caml_copy_string(buf); } CAMLprim value caml_extunix_tzname(value v_isdst) { int i = Bool_val(v_isdst) ? 1 : 0; return caml_copy_string(tzname[i]); } #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); t = timegm(&tm); CAMLreturn(caml_copy_double(t)); } #endif ocaml-extunix-0.0.6/src/tty_ioctl.c000066400000000000000000000021351212637106200172600ustar00rootroot00000000000000/* * 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.0.6/src/uname.c000066400000000000000000000013761212637106200163610ustar00rootroot00000000000000 #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.0.6/src/unistd.c000066400000000000000000000277611212637106200165700ustar00rootroot00000000000000 #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 #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_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, BIT_NOERROR, BIT_NOINTR }; #define ONCE (1 << BIT_ONCE) #define NOERROR (1 << BIT_NOERROR) #define NOINTR (1 << BIT_NOINTR) #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 & NOINTR)) continue; if (processed > 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (mode & NOERROR) break; } uerror("pread", Nothing); } memcpy(&Byte(v_buf, ofs), iobuf, ret); processed += ret; off += ret; ofs += ret; len -= ret; if (mode & 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, 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, 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, NOINTR | 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, 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, 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, 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, NOINTR | 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, 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 & NOINTR)) continue; if (processed > 0){ if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (mode & NOERROR) break; } uerror("pwrite", Nothing); } processed += ret; off += ret; ofs += ret; len -= ret; if (mode & 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, 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, 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, NOINTR | 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, 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, 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, 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, NOINTR | 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, 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 & NOINTR)) continue; if (processed > 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (mode & NOERROR) break; } uerror("read", Nothing); } memcpy(&Byte(v_buf, ofs), iobuf, ret); processed += ret; ofs += ret; len -= ret; if (mode & 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, 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, 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, NOINTR | 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, 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 & NOINTR)) continue; if (processed > 0){ if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (mode & NOERROR) break; } uerror("write", Nothing); } processed += ret; ofs += ret; len -= ret; if (mode & 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, 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, 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, NOINTR | 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, NOERROR); } #endif ocaml-extunix-0.0.6/test/000077500000000000000000000000001212637106200152715ustar00rootroot00000000000000ocaml-extunix-0.0.6/test/test.ml000066400000000000000000000425401212637106200166070ustar00rootroot00000000000000 open OUnit open ExtUnix.All let with_unix_error f () = try f () with Unix.Unix_error(e,f,a) -> assert_failure (Printf.sprintf "Unix_error : %s(%s) : %s" f a (Unix.error_message e)) let require feature = match 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_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; 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) = match r with | RLIMIT_NOFILE -> (* kernel may have lower limits on open files (fs.nr_open or kern.maxfilesperproc) than rlimit. In such situation setrlimit may either silently adjust rlimits to lower values (BSD) or fail with EPERM (Linux) *) let (soft,hard) = getrlimit r in begin try setrlimit r ~soft ~hard with Unix.Unix_error (Unix.EPERM,_,_) -> skip_if true "setrlimit NOFILE EPERM" end; getrlimit r | _ -> 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 = posix_openpt [Unix.O_RDWR] in 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 slave test 0 (String.length test) in let str = String.create len in ignore (Unix.read master str 0 len); assert_equal str test; () let test_execinfo () = require "backtrace"; (* backtrace may not work out of the box on all archs, see PR#5334 *) (* assert_bool "backtrace" ([||] <> backtrace ()) *) let (_:string array) = backtrace () in () let test_statvfs () = require "statvfs"; let st = statvfs "." 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 tmpl = Filename.concat Filename.temp_dir_name "extunix_test_XXXXXX" 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); if Sys.word_size = 64 then begin assert_equal (B.get_uint31 src 6) 0xFEDCBA98; assert_equal (B.get_int31 src 6) 0x7FFFFFFFFEDCBA98; assert_equal (B.get_int31 src 6) (-0x1234568); assert_equal (B.get_uint63 src 10) 0x7EDCBA9876543210; assert_equal (B.get_int63 src 10) 0x7EDCBA9876543210; assert_equal (B.get_int63 src 10) (-0x123456789ABCDF0); assert_equal (L.get_uint31 src 6) 0x98BADCFE; assert_equal (L.get_int31 src 6) 0x7FFFFFFF98BADCFE; assert_equal (L.get_int31 src 6) (-0x67452302); assert_equal (L.get_uint63 src 10) 0x1032547698BADCFE; assert_equal (L.get_int63 src 10) 0x1032547698BADCFE; assert_equal (L.get_int63 src 10) (-0x6FCDAB8967452302); end; let b = " " 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 = " " 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 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 = String.create 7 in ignore (Unix.read s1 str 0 7); 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 (Printf.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_str str c text = for i = 0 to String.length str - 1 do if 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 fd s 0 size) size; let t = String.make size ' ' in assert_equal (pread fd 0 t 0 size) size; cmp_str t 'x' "pread read bad data"; ignore (single_pread fd 0 t 0 size); let t = String.make size ' ' in assert_equal (LargeFile.pread fd Int64.zero t 0 size) size; cmp_str t 'x' "Largefile.pread read bad data"; ignore (LargeFile.single_pread fd Int64.zero t 0 size); 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 (String.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 = String.make size ' ' in read t; cmp_str t 'x' "pwrite wrote bad data"; ignore (single_pwrite fd 0 s 0 size); let s = String.make size 'y' in assert_equal (LargeFile.pwrite fd Int64.zero s 0 size) size; read t; cmp_str t 'y' "Largefile.pwrite wrote bad data"; ignore (LargeFile.single_pwrite fd Int64.zero s 0 size); 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 fd s 0 size) size; let t = String.make size ' ' in assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0; assert_equal (read fd t 0 size) size; cmp_str t 'x' "read read bad data"; assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0; ignore (single_read fd t 0 size); 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 (String.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 = String.make size ' ' in read t; cmp_str t 'x' "write wrote bad data"; ignore (single_write fd s 0 size); 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 () = 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; ]) in ignore (run_test_tt_main (test_decorate wrap tests)) ocaml-extunix-0.0.6/test/testba.ml000066400000000000000000000173611212637106200171150ustar00rootroot00000000000000 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) -> assert_failure (Printf.sprintf "Unix_error : %s(%s) : %s" f a (Unix.error_message e)) 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); if Sys.word_size = 64 then begin assert_equal (B.get_uint31 src 6) 0xFEDCBA98; assert_equal (B.get_int31 src 6) 0x7FFFFFFFFEDCBA98; assert_equal (B.get_int31 src 6) (-0x1234568); assert_equal (B.get_uint63 src 10) 0x7EDCBA9876543210; assert_equal (B.get_int63 src 10) 0x7EDCBA9876543210; assert_equal (B.get_int63 src 10) (-0x123456789ABCDF0); assert_equal (L.get_uint31 src 6) 0x98BADCFE; assert_equal (L.get_int31 src 6) 0x7FFFFFFF98BADCFE; assert_equal (L.get_int31 src 6) (-0x67452302); assert_equal (L.get_uint63 src 10) 0x1032547698BADCFE; assert_equal (L.get_int63 src 10) 0x1032547698BADCFE; assert_equal (L.get_int63 src 10) (-0x6FCDAB8967452302); end; 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 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"; ignore (single_pread fd 0 t); 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"; ignore (LargeFile.single_pread fd Int64.zero t); Unix.close fd; Unix.unlink name with exn -> Unix.close fd; Unix.unlink name; raise exn let cmp_str str c text = for i = 0 to String.length str - 1 do if 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 (String.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 = String.make size ' ' in read t; cmp_str t 'x' "pwrite wrote bad data"; ignore (single_pwrite fd 0 s); 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_str t 'y' "Largefile.pwrite wrote bad data"; ignore (LargeFile.single_pwrite fd Int64.zero s); 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 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; ignore (single_read fd t); 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 (String.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 = String.make size ' ' in read t; cmp_str t 'x' "write wrote bad data"; ignore (single_write fd s); 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))