pax_global_header00006660000000000000000000000064132512007050014505gustar00rootroot0000000000000052 comment=d6be6e3049dd6971aa891b59ef12f7758288d282 ocaml-extunix-0.1.6/000077500000000000000000000000001325120070500143065ustar00rootroot00000000000000ocaml-extunix-0.1.6/.gitignore000066400000000000000000000001671325120070500163020ustar00rootroot00000000000000_build *.native *.byte *.docdir setup.data setup.log src/config.h src/extUnixConfig.ml web/index.html *~ /userns_test/ ocaml-extunix-0.1.6/.merlin000066400000000000000000000000471325120070500155760ustar00rootroot00000000000000S src S test B _build/src B _build/testocaml-extunix-0.1.6/.travis.yml000066400000000000000000000004501325120070500164160ustar00rootroot00000000000000language: c sudo: required install: wget https://raw.githubusercontent.com/ocaml/ocaml-ci-scripts/master/.travis-opam.sh script: bash -ex .travis-opam.sh env: - OCAML_VERSION=4.02 - OCAML_VERSION=4.03 - OCAML_VERSION=4.04 - OCAML_VERSION=4.05 - OCAML_VERSION=4.06 os: - linux - osx ocaml-extunix-0.1.6/CHANGES.txt000066400000000000000000000075431325120070500161300ustar00rootroot000000000000000.1.6 - 11 Mar 2018 * OCaml 4.05 compatibility (O_KEEPEXEC) * sockopt: add BPF options * make tests less fragile * New bindings: * syslog 0.1.5 - 28 Jun 2017 * build with -safe-string 0.1.4 - 11 Nov 2016 + SO_REUSEPORT * fix sendmsg bug * fix build on mingw 0.1.3 - 24 Nov 2015 * New bindings : * fchmodat * fchownat + ExtUnix.Config * fix sysconf detection wrt non-standard options 0.1.2 - 24 Jul 2015 * New bindings : * sysinfo uptime * mtrace muntrace * mount umount2 * unshare * chroot + U.Poll.is_inter inter * TCP_KEEPCNT TCP_KEEPIDLE TCP_KEEPINTLV are now detected one by one and can be available or not available independently. Extunix currently doesn't have a mechanism to expose only selected variants from a single type in module [Specific], hence one should use [have_sockopt] function to check for options presence at runtime. 0.1.1 - 18 May 2014 * New bindings : * gettid * poll * OCaml 4.02 compatibility (install all .cmi) * sendmsg/sendfd : fix sending binary data 0.1.0 - 8 Oct 2013 * statvfs: add f_flags - decoded f_flag field * New bindings : * sysconf * splice tee vmsplice * setsockopt_int getsockopt_int (TCP keepalive) * sync syncfs * timezone * OCaml 4.01 compatibility (Unix.open_flag) * relax restrictions on bigarray types 0.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.1.6/Makefile000066400000000000000000000017171325120070500157540ustar00rootroot00000000000000# OASIS_START # DO NOT EDIT (digest: a3c674b4239234cbbe53afe090018954) 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) configure: $(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.1.6/README.md000066400000000000000000000114521325120070500155700ustar00rootroot00000000000000 ExtUnix OCaml library ===================== [![Build Status](https://travis-ci.org/ygrek/extunix.svg?branch=master)](https://travis-ci.org/ygrek/extunix) [![Build status](https://ci.appveyor.com/api/projects/status/66fpgc2qol5fu30g?svg=true)](https://ci.appveyor.com/project/ygrek/extunix/branch/master) A collection of thin bindings to various low-level system API. Our motto: "Be to Unix, what extlib is to stdlib" * Implement thin C bindings that directly map to underlying system API. * Provide common consistent ocaml interface: naming convention, exceptions. * Simple to build - no extra dependencies. Homepage: 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 do `oasis setup` * Commit * `make release` * Upload tarball and update download links on web page * Update opam Development ----------- Many people contribute to extunix. Please submit your patches and/or feature requests to project bugtracker at https://github.com/ygrek/extunix/issues Current maintainer is reachable at : * mailto:ygrek@autistici.org * xmpp:ygrek@jabber.kiev.ua ---- ocaml-extunix-0.1.6/TODO000066400000000000000000000013631325120070500150010ustar00rootroot00000000000000TODO ==== * comments: mark "emulated" (windows) functions * unsetenv winapi? see http://old.nabble.com/-patch--(msvc)-use-more-modern-facilities-for-setenv()-unsetenv()-td15877005.html * investigate F_FULLFSYNC fcntl and fsync on Mac OS * nanosleep * fdtruncate win32 * waitid DONE ==== * INRIA request for extended UNIX: http://caml.inria.fr/mantis/view.php?id=5063 http://caml.inria.fr/mantis/view.php?id=2533 http://caml.inria.fr/mantis/view.php?id=3851 http://caml.inria.fr/mantis/view.php?id=480 * mkdtemp (see Jane Street Core) * sysconf: get system configuration constants. In particular, PAGESIZE, _SC_PHYS_PAGES, _SC_AVPHYS_PAGES, _SC_NPROCESSORS_CONF, _SC_NPROCESSORS_ONLN (see Jane Street Core) * sysinfo (see Jane Street Core) ocaml-extunix-0.1.6/_oasis000066400000000000000000000070301325120070500155060ustar00rootroot00000000000000OASISFormat: 0.4 Name: extunix Version: 0.1.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, Mehdi Dogguy, Roman Vorobets, Pierre Chambart, Dmitry Grebeniuk, François Bobot, Markus W. Weissmann 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, (C) 2013 Mehdi Dogguy, (C) 2013 Roman Vorobets, (C) 2013 Pierre Chambart, (C) 2013 Dmitry Grebeniuk, (C) 2015 François Bobot, (C) 2018 Markus W. Weissmann 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, ExtUnixAll, ExtUnixSpecific, ExtUnixConfig if flag(strict) && ccomp_type(cc) CCOpt: -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, mktemp.c, memalign.c, endianba.c, pread_pwrite_ba.c, bigarray.c, splice.c, sysconf.c, common.c, common.h, sockopt.c, poll.c, sysinfo.c, mount.c, unshare.c, syslog.c BuildDepends: unix, bigarray, bytes 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) Executable test_user_namespace Path: test/ Install: false Build$: flag(tests) Custom: true CompiledObject: best MainIs: test_user_namespace.ml BuildDepends: str, extunix, oUnit (>= 1.0.3) Test main Command: $test && $testba TestTools: test, testba, test_user_namespace 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, Mehdi Dogguy, Roman Vorobets, Pierre Chambart, Dmitry Grebeniuk BuildTools: ocamldoc Format: HTML Index: index.html XOCamlbuildPath: src/ XOCamlbuildLibraries: extunix #Document changelog # Title: Changelog # Path: CHANGES.txt ocaml-extunix-0.1.6/_tags000066400000000000000000000153361325120070500153360ustar00rootroot00000000000000# OASIS_START # DO NOT EDIT (digest: 58715019d15d2563e3e94e29e14f8469) # 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 true: annot, bin_annot <**/.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/mktemp.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/splice.c": oasis_library_extunix_ccopt "src/sysconf.c": oasis_library_extunix_ccopt "src/common.c": oasis_library_extunix_ccopt "src/sockopt.c": oasis_library_extunix_ccopt "src/poll.c": oasis_library_extunix_ccopt "src/sysinfo.c": oasis_library_extunix_ccopt "src/mount.c": oasis_library_extunix_ccopt "src/unshare.c": oasis_library_extunix_ccopt "src/syslog.c": oasis_library_extunix_ccopt : use_libextunix_stubs : pkg_bigarray : pkg_bytes : pkg_unix "src/eventfd.c": pkg_bigarray "src/eventfd.c": pkg_bytes "src/eventfd.c": pkg_unix "src/dirfd.c": pkg_bigarray "src/dirfd.c": pkg_bytes "src/dirfd.c": pkg_unix "src/fsync.c": pkg_bigarray "src/fsync.c": pkg_bytes "src/fsync.c": pkg_unix "src/statvfs.c": pkg_bigarray "src/statvfs.c": pkg_bytes "src/statvfs.c": pkg_unix "src/atfile.c": pkg_bigarray "src/atfile.c": pkg_bytes "src/atfile.c": pkg_unix "src/ioctl_siocgifconf.c": pkg_bigarray "src/ioctl_siocgifconf.c": pkg_bytes "src/ioctl_siocgifconf.c": pkg_unix "src/uname.c": pkg_bigarray "src/uname.c": pkg_bytes "src/uname.c": pkg_unix "src/fadvise.c": pkg_bigarray "src/fadvise.c": pkg_bytes "src/fadvise.c": pkg_unix "src/fallocate.c": pkg_bigarray "src/fallocate.c": pkg_bytes "src/fallocate.c": pkg_unix "src/tty_ioctl.c": pkg_bigarray "src/tty_ioctl.c": pkg_bytes "src/tty_ioctl.c": pkg_unix "src/unistd.c": pkg_bigarray "src/unistd.c": pkg_bytes "src/unistd.c": pkg_unix "src/stdlib.c": pkg_bigarray "src/stdlib.c": pkg_bytes "src/stdlib.c": pkg_unix "src/signalfd.c": pkg_bigarray "src/signalfd.c": pkg_bytes "src/signalfd.c": pkg_unix "src/ptrace.c": pkg_bigarray "src/ptrace.c": pkg_bytes "src/ptrace.c": pkg_unix "src/resource.c": pkg_bigarray "src/resource.c": pkg_bytes "src/resource.c": pkg_unix "src/mman.c": pkg_bigarray "src/mman.c": pkg_bytes "src/mman.c": pkg_unix "src/time.c": pkg_bigarray "src/time.c": pkg_bytes "src/time.c": pkg_unix "src/pts.c": pkg_bigarray "src/pts.c": pkg_bytes "src/pts.c": pkg_unix "src/execinfo.c": pkg_bigarray "src/execinfo.c": pkg_bytes "src/execinfo.c": pkg_unix "src/malloc.c": pkg_bigarray "src/malloc.c": pkg_bytes "src/malloc.c": pkg_unix "src/endian.c": pkg_bigarray "src/endian.c": pkg_bytes "src/endian.c": pkg_unix "src/read_cred.c": pkg_bigarray "src/read_cred.c": pkg_bytes "src/read_cred.c": pkg_unix "src/fexecve.c": pkg_bigarray "src/fexecve.c": pkg_bytes "src/fexecve.c": pkg_unix "src/sendmsg.c": pkg_bigarray "src/sendmsg.c": pkg_bytes "src/sendmsg.c": pkg_unix "src/mktemp.c": pkg_bigarray "src/mktemp.c": pkg_bytes "src/mktemp.c": pkg_unix "src/memalign.c": pkg_bigarray "src/memalign.c": pkg_bytes "src/memalign.c": pkg_unix "src/endianba.c": pkg_bigarray "src/endianba.c": pkg_bytes "src/endianba.c": pkg_unix "src/pread_pwrite_ba.c": pkg_bigarray "src/pread_pwrite_ba.c": pkg_bytes "src/pread_pwrite_ba.c": pkg_unix "src/bigarray.c": pkg_bigarray "src/bigarray.c": pkg_bytes "src/bigarray.c": pkg_unix "src/splice.c": pkg_bigarray "src/splice.c": pkg_bytes "src/splice.c": pkg_unix "src/sysconf.c": pkg_bigarray "src/sysconf.c": pkg_bytes "src/sysconf.c": pkg_unix "src/common.c": pkg_bigarray "src/common.c": pkg_bytes "src/common.c": pkg_unix "src/sockopt.c": pkg_bigarray "src/sockopt.c": pkg_bytes "src/sockopt.c": pkg_unix "src/poll.c": pkg_bigarray "src/poll.c": pkg_bytes "src/poll.c": pkg_unix "src/sysinfo.c": pkg_bigarray "src/sysinfo.c": pkg_bytes "src/sysinfo.c": pkg_unix "src/mount.c": pkg_bigarray "src/mount.c": pkg_bytes "src/mount.c": pkg_unix "src/unshare.c": pkg_bigarray "src/unshare.c": pkg_bytes "src/unshare.c": pkg_unix "src/syslog.c": pkg_bigarray "src/syslog.c": pkg_bytes "src/syslog.c": pkg_unix # Executable test : pkg_bigarray : pkg_bytes : pkg_oUnit : pkg_unix : use_extunix : custom # Executable testba : pkg_bigarray : pkg_bytes : pkg_oUnit : pkg_unix : use_extunix : custom # Executable test_user_namespace : pkg_bigarray : pkg_bytes : pkg_oUnit : pkg_str : pkg_unix : use_extunix : pkg_bigarray : pkg_bytes : pkg_oUnit : pkg_str : pkg_unix : use_extunix : custom # OASIS_STOP true: my_warnings, safe_string "test/test.ml": warn_d "src/pa_have.ml": pkg_camlp4.quotations.r, pkg_camlp4.extend, syntax_camlp4o <**/rootfs*>: -traverse <**/rootfs*>: not_hygienic "userns_test/": -traverse "userns_test/": not_hygienic ocaml-extunix-0.1.6/appveyor.yml000066400000000000000000000005521325120070500167000ustar00rootroot00000000000000platform: - x86 environment: FORK_USER: ocaml FORK_BRANCH: master CYG_ROOT: C:\cygwin64 install: - ps: iex ((new-object net.webclient).DownloadString("https://raw.githubusercontent.com/$env:FORK_USER/ocaml-ci-scripts/$env:FORK_BRANCH/appveyor-install.ps1")) build_script: - call %CYG_ROOT%\bin\bash.exe -l %APPVEYOR_BUILD_FOLDER%\appveyor-opam.sh ocaml-extunix-0.1.6/configure000077500000000000000000000005531325120070500162200ustar00rootroot00000000000000#!/bin/sh # OASIS_START # DO NOT EDIT (digest: dc86c2ad450f91ca10c931b6045d0499) 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.1.6/myocamlbuild.ml000066400000000000000000000612561325120070500173330ustar00rootroot00000000000000(* OASIS_START *) (* DO NOT EDIT (digest: 9c5952fbe06f80244c5abc5dc76890aa) *) module OASISGettext = struct (* # 22 "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 OASISString = struct (* # 22 "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; !what_idx = String.length what 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; !what_idx = -1 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 = Buffer.create (String.length s) in String.iter (fun c -> Buffer.add_char buf (f c)) s; Buffer.contents buf let lowercase_ascii = replace_chars (fun c -> if (c >= 'A' && c <= 'Z') then Char.chr (Char.code c + 32) else c) let uncapitalize_ascii s = if s <> "" then (lowercase_ascii (String.sub s 0 1)) ^ (String.sub s 1 ((String.length s) - 1)) else s let uppercase_ascii = replace_chars (fun c -> if (c >= 'a' && c <= 'z') then Char.chr (Char.code c - 32) else c) let capitalize_ascii s = if s <> "" then (uppercase_ascii (String.sub s 0 1)) ^ (String.sub s 1 ((String.length s) - 1)) else s end module OASISUtils = struct (* # 22 "src/oasis/OASISUtils.ml" *) open OASISGettext module MapExt = struct module type S = sig include Map.S val add_list: 'a t -> (key * 'a) list -> 'a t val of_list: (key * 'a) list -> 'a t val to_list: 'a t -> (key * 'a) list end module Make (Ord: Map.OrderedType) = struct include Map.Make(Ord) let rec add_list t = function | (k, v) :: tl -> add_list (add k v t) tl | [] -> t let of_list lst = add_list empty lst let to_list t = fold (fun k v acc -> (k, v) :: acc) t [] end end module MapString = MapExt.Make(String) module SetExt = struct module type S = sig include Set.S val add_list: t -> elt list -> t val of_list: elt list -> t val to_list: t -> elt list end module Make (Ord: Set.OrderedType) = struct include Set.Make(Ord) let rec add_list t = function | e :: tl -> add_list (add e t) tl | [] -> t let of_list lst = add_list empty lst let to_list = elements end end module SetString = SetExt.Make(String) let compare_csl s1 s2 = String.compare (OASISString.lowercase_ascii s1) (OASISString.lowercase_ascii s2) module HashStringCsl = Hashtbl.Make (struct type t = string let equal s1 s2 = (compare_csl s1 s2) = 0 let hash s = Hashtbl.hash (OASISString.lowercase_ascii s) end) module SetStringCsl = SetExt.Make (struct type t = string let compare = compare_csl 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 OASISString.lowercase_ascii 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 let rec file_location ?pos1 ?pos2 ?lexbuf () = match pos1, pos2, lexbuf with | Some p, None, _ | None, Some p, _ -> file_location ~pos1:p ~pos2:p ?lexbuf () | Some p1, Some p2, _ -> let open Lexing in let fn, lineno = p1.pos_fname, p1.pos_lnum in let c1 = p1.pos_cnum - p1.pos_bol in let c2 = c1 + (p2.pos_cnum - p1.pos_cnum) in Printf.sprintf (f_ "file %S, line %d, characters %d-%d") fn lineno c1 c2 | _, _, Some lexbuf -> file_location ~pos1:(Lexing.lexeme_start_p lexbuf) ~pos2:(Lexing.lexeme_end_p lexbuf) () | None, None, None -> s_ "" let failwithpf ?pos1 ?pos2 ?lexbuf fmt = let loc = file_location ?pos1 ?pos2 ?lexbuf () in Printf.ksprintf (fun s -> failwith (Printf.sprintf "%s: %s" loc s)) fmt end module OASISExpr = struct (* # 22 "src/oasis/OASISExpr.ml" *) open OASISGettext open OASISUtils 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 # 437 "myocamlbuild.ml" module BaseEnvLight = struct (* # 22 "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) ?stream () = let line = ref 1 in let lexer st = 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 Genlex.make_lexer ["="] st_line in let rec read_file lxr mp = match Stream.npeek 3 lxr with | [Genlex.Ident nm; Genlex.Kwd "="; Genlex.String value] -> Stream.junk lxr; Stream.junk lxr; Stream.junk lxr; read_file lxr (MapString.add nm value mp) | [] -> mp | _ -> failwith (Printf.sprintf "Malformed data file '%s' line %d" filename !line) in match stream with | Some st -> read_file (lexer st) MapString.empty | None -> if Sys.file_exists filename then begin let chn = open_in_bin filename in let st = Stream.of_channel chn in try let mp = read_file (lexer st) MapString.empty in close_in chn; mp with e -> close_in chn; raise e 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 rec var_expand str env = let buff = Buffer.create ((String.length str) * 2) in Buffer.add_substitute buff (fun var -> try var_expand (MapString.find var env) env with Not_found -> failwith (Printf.sprintf "No variable %s defined when trying to expand %S." var str)) str; Buffer.contents buff let var_get name env = var_expand (MapString.find name env) env let var_choose lst env = OASISExpr.choose (fun nm -> var_get nm env) lst end # 517 "myocamlbuild.ml" module MyOCamlbuildFindlib = struct (* # 22 "src/plugins/ocamlbuild/MyOCamlbuildFindlib.ml" *) (** OCamlbuild extension, copied from * https://ocaml.org/learn/tutorials/ocamlbuild/Using_ocamlfind_with_ocamlbuild.html * by N. Pouillard and others * * Updated on 2016-06-02 * * Modified by Sylvain Le Gall *) open Ocamlbuild_plugin type conf = {no_automatic_syntax: bool} let run_and_read = Ocamlbuild_pack.My_unix.run_and_read let blank_sep_strings = Ocamlbuild_pack.Lexers.blank_sep_strings let exec_from_conf exec = let exec = let env = BaseEnvLight.load ~allow_empty:true () in try BaseEnvLight.var_get exec env with Not_found -> Printf.eprintf "W: Cannot get variable %s\n" exec; exec in let fix_win32 str = if Sys.os_type = "Win32" then begin let buff = Buffer.create (String.length str) in (* Adapt for windowsi, ocamlbuild + win32 has a hard time to handle '\\'. *) String.iter (fun c -> Buffer.add_char buff (if c = '\\' then '/' else c)) str; Buffer.contents buff end else begin str end in fix_win32 exec let split s ch = let buf = Buffer.create 13 in let x = ref [] in let flush () = x := (Buffer.contents buf) :: !x; Buffer.clear buf in String.iter (fun c -> if c = ch then flush () else Buffer.add_char buf c) s; flush (); List.rev !x let split_nl s = split s '\n' let before_space s = try String.before s (String.index s ' ') with Not_found -> s (* ocamlfind command *) let ocamlfind x = S[Sh (exec_from_conf "ocamlfind"); x] (* This lists all supported packages. *) let find_packages () = List.map before_space (split_nl & run_and_read (exec_from_conf "ocamlfind" ^ " list")) (* Mock to list available syntaxes. *) let find_syntaxes () = ["camlp4o"; "camlp4r"] let well_known_syntax = [ "camlp4.quotations.o"; "camlp4.quotations.r"; "camlp4.exceptiontracer"; "camlp4.extend"; "camlp4.foldgenerator"; "camlp4.listcomprehension"; "camlp4.locationstripper"; "camlp4.macro"; "camlp4.mapgenerator"; "camlp4.metagenerator"; "camlp4.profiler"; "camlp4.tracer" ] let dispatch conf = function | After_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"; Options.ocamlmklib := ocamlfind & A"ocamlmklib" | After_rules -> (* Avoid warnings for unused tag *) flag ["tests"] N; (* 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 -> let base_args = [A"-package"; A pkg] in (* TODO: consider how to really choose camlp4o or camlp4r. *) let syn_args = [A"-syntax"; A "camlp4o"] in let (args, pargs) = (* Heuristic to identify syntax extensions: whether they end in ".syntax"; some might not. *) if not (conf.no_automatic_syntax) && (Filename.check_suffix pkg "syntax" || List.mem pkg well_known_syntax) then (syn_args @ base_args, syn_args) else (base_args, []) in flag ["ocaml"; "compile"; "pkg_"^pkg] & S args; flag ["ocaml"; "ocamldep"; "pkg_"^pkg] & S args; flag ["ocaml"; "doc"; "pkg_"^pkg] & S args; flag ["ocaml"; "link"; "pkg_"^pkg] & S base_args; flag ["ocaml"; "infer_interface"; "pkg_"^pkg] & S args; (* TODO: Check if this is allowed for OCaml < 3.12.1 *) flag ["ocaml"; "compile"; "package("^pkg^")"] & S pargs; flag ["ocaml"; "ocamldep"; "package("^pkg^")"] & S pargs; flag ["ocaml"; "doc"; "package("^pkg^")"] & S pargs; flag ["ocaml"; "infer_interface"; "package("^pkg^")"] & S pargs; 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"]); flag ["c"; "pkg_threads"; "compile"] (S[A "-thread"]); flag ["ocaml"; "package(threads)"; "compile"] (S[A "-thread"]); flag ["ocaml"; "package(threads)"; "doc"] (S[A "-I"; A "+threads"]); flag ["ocaml"; "package(threads)"; "link"] (S[A "-thread"]); flag ["ocaml"; "package(threads)"; "infer_interface"] (S[A "-thread"]); flag ["c"; "package(threads)"; "compile"] (S[A "-thread"]); | _ -> () end module MyOCamlbuildBase = struct (* # 22 "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 type t = { lib_ocaml: (name * dir list * string 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; } (* # 110 "src/plugins/ocamlbuild/MyOCamlbuildBase.ml" *) 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 ~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\n" 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, [], intf_modules -> ocaml_lib nm; let cmis = List.map (fun m -> (OASISString.uncapitalize_ascii m) ^ ".cmi") intf_modules in dep ["ocaml"; "link"; "library"; "file:"^nm^".cma"] cmis | nm, dir :: tl, intf_modules -> 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; let cmis = List.map (fun m -> dir^"/"^(OASISString.uncapitalize_ascii m)^".cmi") intf_modules in dep ["ocaml"; "link"; "library"; "file:"^dir^"/"^nm^".cma"] cmis) 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))]); if bool_of_string (BaseEnvLight.var_get "native_dynlink" env) then 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. This holds both for programs and for libraries. *) dep ["link"; "ocaml"; tag_libstubs lib] [dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)]; dep ["compile"; "ocaml"; 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 let rec eval_specs = function | S lst -> S (List.map eval_specs lst) | A str -> A (BaseEnvLight.var_expand str env) | spec -> spec in flag tags & (eval_specs spec)) t.flags | _ -> () let dispatch_default conf t = dispatch_combine [ dispatch t; MyOCamlbuildFindlib.dispatch conf; ] end # 878 "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 "-pedantic"; A "-ccopt"; A "-Wno-long-long"; A "-ccopt"; A "-Wextra" ]) ]) ]; includes = [("test", ["src"])] } ;; let conf = {MyOCamlbuildFindlib.no_automatic_syntax = false} let dispatch_default = MyOCamlbuildBase.dispatch_default conf package_default;; # 912 "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/extUnixConfig.cmo"] ~prod (fun _ _ -> Cmd (S([P"camlp4o"; T (tags_of_pathname "src/extUnix.mlpp"++"ocaml"++"pp"); A "src/extUnixConfig.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";; flag ["compile"; "ocaml"; "my_warnings"] (S[A "-w"; A"+A-e-3-44-48-50"]);; Ocamlbuild_plugin.dispatch dispatch_default;; ocaml-extunix-0.1.6/opam000066400000000000000000000025001325120070500151620ustar00rootroot00000000000000opam-version: "1.2" maintainer: "ygrek@autistici.org" homepage: "http://ygrek.org.ua/p/extunix" dev-repo: "git://github.com/ygrek/extunix.git" bug-reports: "https://github.com/ygrek/extunix/issues" doc: "http://ygrek.org.ua/p/ocaml-extunix/api/index.html" 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" "Mehdi Dogguy" "Roman Vorobets" "Pierre Chambart" "Dmitry Grebeniuk" "François Bobot" "Markus W. Weissmann" ] build: [ ["ocaml" "setup.ml" "-configure" "--%{ounit:enable}%-tests" "--prefix" prefix] {ocaml-version >= "4.02.0"} ["ocaml" "setup.ml" "-configure" "--prefix" prefix] {ocaml-version < "4.02.0"} ["ocaml" "setup.ml" "-build"] ] install: [ ["ocaml" "setup.ml" "-install"] ] build-doc: [ ["ocaml" "setup.ml" "-doc"] ] build-test: [ ["ocaml" "setup.ml" "-test"] ] remove: [ ["ocamlfind" "remove" "extunix"] ] depends: [ "ocamlfind" {build} "camlp4" {build} "ounit" {test & >= "1.0.3"} "base-bytes" "base-bigarray" "base-unix" "ocamlbuild" {build} ] ocaml-extunix-0.1.6/setup.ml000066400000000000000000006727201325120070500160160ustar00rootroot00000000000000(* setup.ml generated for the first time by OASIS v0.2.0~alpha1 *) (* OASIS_START *) (* DO NOT EDIT (digest: 785c6cea5580bb5e674fa24c3fe39b21) *) (* Regenerated by OASIS v0.4.10 Visit http://oasis.forge.ocamlcore.org for more information and documentation about functions used in this file. *) module OASISGettext = struct (* # 22 "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 OASISString = struct (* # 22 "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; !what_idx = String.length what 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; !what_idx = -1 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 = Buffer.create (String.length s) in String.iter (fun c -> Buffer.add_char buf (f c)) s; Buffer.contents buf let lowercase_ascii = replace_chars (fun c -> if (c >= 'A' && c <= 'Z') then Char.chr (Char.code c + 32) else c) let uncapitalize_ascii s = if s <> "" then (lowercase_ascii (String.sub s 0 1)) ^ (String.sub s 1 ((String.length s) - 1)) else s let uppercase_ascii = replace_chars (fun c -> if (c >= 'a' && c <= 'z') then Char.chr (Char.code c - 32) else c) let capitalize_ascii s = if s <> "" then (uppercase_ascii (String.sub s 0 1)) ^ (String.sub s 1 ((String.length s) - 1)) else s end module OASISUtils = struct (* # 22 "src/oasis/OASISUtils.ml" *) open OASISGettext module MapExt = struct module type S = sig include Map.S val add_list: 'a t -> (key * 'a) list -> 'a t val of_list: (key * 'a) list -> 'a t val to_list: 'a t -> (key * 'a) list end module Make (Ord: Map.OrderedType) = struct include Map.Make(Ord) let rec add_list t = function | (k, v) :: tl -> add_list (add k v t) tl | [] -> t let of_list lst = add_list empty lst let to_list t = fold (fun k v acc -> (k, v) :: acc) t [] end end module MapString = MapExt.Make(String) module SetExt = struct module type S = sig include Set.S val add_list: t -> elt list -> t val of_list: elt list -> t val to_list: t -> elt list end module Make (Ord: Set.OrderedType) = struct include Set.Make(Ord) let rec add_list t = function | e :: tl -> add_list (add e t) tl | [] -> t let of_list lst = add_list empty lst let to_list = elements end end module SetString = SetExt.Make(String) let compare_csl s1 s2 = String.compare (OASISString.lowercase_ascii s1) (OASISString.lowercase_ascii s2) module HashStringCsl = Hashtbl.Make (struct type t = string let equal s1 s2 = (compare_csl s1 s2) = 0 let hash s = Hashtbl.hash (OASISString.lowercase_ascii s) end) module SetStringCsl = SetExt.Make (struct type t = string let compare = compare_csl 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 OASISString.lowercase_ascii 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 let rec file_location ?pos1 ?pos2 ?lexbuf () = match pos1, pos2, lexbuf with | Some p, None, _ | None, Some p, _ -> file_location ~pos1:p ~pos2:p ?lexbuf () | Some p1, Some p2, _ -> let open Lexing in let fn, lineno = p1.pos_fname, p1.pos_lnum in let c1 = p1.pos_cnum - p1.pos_bol in let c2 = c1 + (p2.pos_cnum - p1.pos_cnum) in Printf.sprintf (f_ "file %S, line %d, characters %d-%d") fn lineno c1 c2 | _, _, Some lexbuf -> file_location ~pos1:(Lexing.lexeme_start_p lexbuf) ~pos2:(Lexing.lexeme_end_p lexbuf) () | None, None, None -> s_ "" let failwithpf ?pos1 ?pos2 ?lexbuf fmt = let loc = file_location ?pos1 ?pos2 ?lexbuf () in Printf.ksprintf (fun s -> failwith (Printf.sprintf "%s: %s" loc s)) fmt end module OASISUnixPath = struct (* # 22 "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 (OASISString.capitalize_ascii base) let uncapitalize_file f = let dir = dirname f in let base = basename f in concat dir (OASISString.uncapitalize_ascii base) end module OASISHostPath = struct (* # 22 "src/oasis/OASISHostPath.ml" *) open Filename open OASISGettext module Unix = OASISUnixPath let make = function | [] -> invalid_arg "OASISHostPath.make" | hd :: tl -> List.fold_left Filename.concat hd tl let of_unix ufn = match Sys.os_type with | "Unix" | "Cygwin" -> ufn | "Win32" -> 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 '/')) | os_type -> OASISUtils.failwithf (f_ "Don't know the path format of os_type %S when translating unix \ filename. %S") os_type ufn end module OASISFileSystem = struct (* # 22 "src/oasis/OASISFileSystem.ml" *) (** File System functions @author Sylvain Le Gall *) type 'a filename = string class type closer = object method close: unit end class type reader = object inherit closer method input: Buffer.t -> int -> unit end class type writer = object inherit closer method output: Buffer.t -> unit end class type ['a] fs = object method string_of_filename: 'a filename -> string method open_out: ?mode:(open_flag list) -> ?perm:int -> 'a filename -> writer method open_in: ?mode:(open_flag list) -> ?perm:int -> 'a filename -> reader method file_exists: 'a filename -> bool method remove: 'a filename -> unit end module Mode = struct let default_in = [Open_rdonly] let default_out = [Open_wronly; Open_creat; Open_trunc] let text_in = Open_text :: default_in let text_out = Open_text :: default_out let binary_in = Open_binary :: default_in let binary_out = Open_binary :: default_out end let std_length = 4096 (* Standard buffer/read length. *) let binary_out = Mode.binary_out let binary_in = Mode.binary_in let of_unix_filename ufn = (ufn: 'a filename) let to_unix_filename fn = (fn: string) let defer_close o f = try let r = f o in o#close; r with e -> o#close; raise e let stream_of_reader rdr = let buf = Buffer.create std_length in let pos = ref 0 in let eof = ref false in let rec next idx = let bpos = idx - !pos in if !eof then begin None end else if bpos < Buffer.length buf then begin Some (Buffer.nth buf bpos) end else begin pos := !pos + Buffer.length buf; Buffer.clear buf; begin try rdr#input buf std_length; with End_of_file -> if Buffer.length buf = 0 then eof := true end; next idx end in Stream.from next let read_all buf rdr = try while true do rdr#input buf std_length done with End_of_file -> () class ['a] host_fs rootdir : ['a] fs = object (self) method private host_filename fn = Filename.concat rootdir fn method string_of_filename = self#host_filename method open_out ?(mode=Mode.text_out) ?(perm=0o666) fn = let chn = open_out_gen mode perm (self#host_filename fn) in object method close = close_out chn method output buf = Buffer.output_buffer chn buf end method open_in ?(mode=Mode.text_in) ?(perm=0o666) fn = (* TODO: use Buffer.add_channel when minimal version of OCaml will * be >= 4.03.0 (previous version was discarding last chars). *) let chn = open_in_gen mode perm (self#host_filename fn) in let strm = Stream.of_channel chn in object method close = close_in chn method input buf len = let read = ref 0 in try for _i = 0 to len do Buffer.add_char buf (Stream.next strm); incr read done with Stream.Failure -> if !read = 0 then raise End_of_file end method file_exists fn = Sys.file_exists (self#host_filename fn) method remove fn = Sys.remove (self#host_filename fn) end end module OASISContext = struct (* # 22 "src/oasis/OASISContext.ml" *) open OASISGettext type level = [ `Debug | `Info | `Warning | `Error] type source type source_filename = source OASISFileSystem.filename let in_srcdir ufn = OASISFileSystem.of_unix_filename ufn type t = { (* TODO: replace this by a proplist. *) quiet: bool; info: bool; debug: bool; ignore_plugins: bool; ignore_unknown_fields: bool; printf: level -> string -> unit; srcfs: source OASISFileSystem.fs; load_oasis_plugin: string -> bool; } 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; srcfs = new OASISFileSystem.host_fs(Sys.getcwd ()); load_oasis_plugin = (fun _ -> false); } let quiet = {!default with quiet = true} let fspecs () = (* TODO: don't act on default. *) let ignore_plugins = ref false in ["-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"; "-ignore-plugins", Arg.Set ignore_plugins, s_ " Ignore plugin's field."; "-C", Arg.String (fun str -> Sys.chdir str; default := {!default with srcfs = new OASISFileSystem.host_fs str}), s_ "dir Change directory before running (affects setup.{data,log})."], fun () -> {!default with ignore_plugins = !ignore_plugins} end module PropList = struct (* # 22 "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 (* # 77 "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 OASISString.lowercase_ascii 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 (* # 22 "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 (* # 22 "src/oasis/OASISVersion.ml" *) open OASISGettext 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) end module OASISLicense = struct (* # 22 "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 (* # 22 "src/oasis/OASISExpr.ml" *) open OASISGettext open OASISUtils 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 OASISText = struct (* # 22 "src/oasis/OASISText.ml" *) type elt = | Para of string | Verbatim of string | BlankLine type t = elt list end module OASISSourcePatterns = struct (* # 22 "src/oasis/OASISSourcePatterns.ml" *) open OASISUtils open OASISGettext module Templater = struct (* TODO: use this module in BaseEnv.var_expand and BaseFileAB, at least. *) type t = { atoms: atom list; origin: string } and atom = | Text of string | Expr of expr and expr = | Ident of string | String of string | Call of string * expr type env = { variables: string MapString.t; functions: (string -> string) MapString.t; } let eval env t = let rec eval_expr env = function | String str -> str | Ident nm -> begin try MapString.find nm env.variables with Not_found -> (* TODO: add error location within the string. *) failwithf (f_ "Unable to find variable %S in source pattern %S") nm t.origin end | Call (fn, expr) -> begin try (MapString.find fn env.functions) (eval_expr env expr) with Not_found -> (* TODO: add error location within the string. *) failwithf (f_ "Unable to find function %S in source pattern %S") fn t.origin end in String.concat "" (List.map (function | Text str -> str | Expr expr -> eval_expr env expr) t.atoms) let parse env s = let lxr = Genlex.make_lexer [] in let parse_expr s = let st = lxr (Stream.of_string s) in match Stream.npeek 3 st with | [Genlex.Ident fn; Genlex.Ident nm] -> Call(fn, Ident nm) | [Genlex.Ident fn; Genlex.String str] -> Call(fn, String str) | [Genlex.String str] -> String str | [Genlex.Ident nm] -> Ident nm (* TODO: add error location within the string. *) | _ -> failwithf (f_ "Unable to parse expression %S") s in let parse s = let lst_exprs = ref [] in let ss = let buff = Buffer.create (String.length s) in Buffer.add_substitute buff (fun s -> lst_exprs := (parse_expr s) :: !lst_exprs; "\000") s; Buffer.contents buff in let rec join = function | hd1 :: tl1, hd2 :: tl2 -> Text hd1 :: Expr hd2 :: join (tl1, tl2) | [], tl -> List.map (fun e -> Expr e) tl | tl, [] -> List.map (fun e -> Text e) tl in join (OASISString.nsplit ss '\000', List.rev (!lst_exprs)) in let t = {atoms = parse s; origin = s} in (* We rely on a simple evaluation for checking variables/functions. It works because there is no if/loop statement. *) let _s : string = eval env t in t (* # 144 "src/oasis/OASISSourcePatterns.ml" *) end type t = Templater.t let env ~modul () = { Templater. variables = MapString.of_list ["module", modul]; functions = MapString.of_list [ "capitalize_file", OASISUnixPath.capitalize_file; "uncapitalize_file", OASISUnixPath.uncapitalize_file; ]; } let all_possible_files lst ~path ~modul = let eval = Templater.eval (env ~modul ()) in List.fold_left (fun acc pat -> OASISUnixPath.concat path (eval pat) :: acc) [] lst let to_string t = t.Templater.origin end module OASISTypes = struct (* # 22 "src/oasis/OASISTypes.ml" *) type name = string type package_name = string type url = string type unix_dirname = string type unix_filename = string (* TODO: replace everywhere. *) type host_dirname = string (* TODO: replace everywhere. *) type host_filename = string (* TODO: replace everywhere. *) 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 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_interface_patterns: OASISSourcePatterns.t list; bs_implementation_patterns: OASISSourcePatterns.t list; bs_c_sources: unix_filename list; bs_data_files: (unix_filename * unix_filename option) list; bs_findlib_extra_files: unix_filename 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_directory: unix_dirname option; lib_findlib_containers: findlib_name list; } type object_ = { obj_modules: string list; obj_findlib_fullname: findlib_name list option; obj_findlib_directory: unix_dirname option; } 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 (* TODO: source filename. *) | DocText | PDF | PostScript | Info of unix_filename (* TODO: source 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; (* TODO: dest filename ?. *) doc_title: string; doc_authors: string list; doc_abstract: string option; doc_format: doc_format; (* TODO: src filename. *) doc_data_files: (unix_filename * unix_filename option) list; doc_build_tools: tool list; } type section = | Library of common_section * build_section * library | Object of common_section * build_section * object_ | 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 | `Object | `Executable | `Flag | `SrcRepo | `Test | `Doc ] type package = { oasis_version: OASISVersion.t; ocaml_version: OASISVersion.comparator option; findlib_version: OASISVersion.comparator option; alpha_features: string list; beta_features: string list; name: package_name; version: OASISVersion.t; license: OASISLicense.t; license_file: unix_filename option; (* TODO: source filename. *) copyrights: string list; maintainers: string list; authors: string list; homepage: url option; bugreports: url option; synopsis: string; description: OASISText.t option; tags: string list; 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; (* TODO: source filename. *) sections: section list; plugins: [`Extra] plugin list; disable_oasis_section: unix_filename list; (* TODO: source filename. *) schema_data: PropList.Data.t; plugin_data: plugin_data; } end module OASISFeatures = struct (* # 22 "src/oasis/OASISFeatures.ml" *) open OASISTypes open OASISUtils open OASISGettext open OASISVersion module MapPlugin = Map.Make (struct type t = plugin_kind * name let compare = Pervasives.compare end) module Data = struct type t = { oasis_version: OASISVersion.t; plugin_versions: OASISVersion.t option MapPlugin.t; alpha_features: string list; beta_features: string list; } let create oasis_version alpha_features beta_features = { oasis_version = oasis_version; plugin_versions = MapPlugin.empty; alpha_features = alpha_features; beta_features = beta_features } let of_package pkg = create pkg.OASISTypes.oasis_version pkg.OASISTypes.alpha_features pkg.OASISTypes.beta_features let add_plugin (plugin_kind, plugin_name, plugin_version) t = {t with plugin_versions = MapPlugin.add (plugin_kind, plugin_name) plugin_version t.plugin_versions} let plugin_version plugin_kind plugin_name t = MapPlugin.find (plugin_kind, plugin_name) t.plugin_versions let to_string t = Printf.sprintf "oasis_version: %s; alpha_features: %s; beta_features: %s; \ plugins_version: %s" (OASISVersion.string_of_version (t:t).oasis_version) (String.concat ", " t.alpha_features) (String.concat ", " t.beta_features) (String.concat ", " (MapPlugin.fold (fun (_, plg) ver_opt acc -> (plg^ (match ver_opt with | Some v -> " "^(OASISVersion.string_of_version v) | None -> "")) :: acc) t.plugin_versions [])) end type origin = | Field of string * string | Section of string | NoOrigin type stage = Alpha | Beta let string_of_stage = function | Alpha -> "alpha" | Beta -> "beta" let field_of_stage = function | Alpha -> "AlphaFeatures" | Beta -> "BetaFeatures" type publication = InDev of stage | SinceVersion of OASISVersion.t type t = { name: string; plugin: all_plugin option; publication: publication; description: unit -> string; } (* TODO: mutex protect this. *) let all_features = Hashtbl.create 13 let since_version ver_str = SinceVersion (version_of_string ver_str) let alpha = InDev Alpha let beta = InDev Beta let to_string t = Printf.sprintf "feature: %s; plugin: %s; publication: %s" (t:t).name (match t.plugin with | None -> "" | Some (_, nm, _) -> nm) (match t.publication with | InDev stage -> string_of_stage stage | SinceVersion ver -> ">= "^(OASISVersion.string_of_version ver)) let data_check t data origin = let no_message = "no message" in let check_feature features stage = let has_feature = List.mem (t:t).name features in if not has_feature then match (origin:origin) with | Field (fld, where) -> Some (Printf.sprintf (f_ "Field %s in %s is only available when feature %s \ is in field %s.") fld where t.name (field_of_stage stage)) | Section sct -> Some (Printf.sprintf (f_ "Section %s is only available when features %s \ is in field %s.") sct t.name (field_of_stage stage)) | NoOrigin -> Some no_message else None in let version_is_good ~min_version version fmt = let version_is_good = OASISVersion.comparator_apply version (OASISVersion.VGreaterEqual min_version) in Printf.ksprintf (fun str -> if version_is_good then None else Some str) fmt in match origin, t.plugin, t.publication with | _, _, InDev Alpha -> check_feature data.Data.alpha_features Alpha | _, _, InDev Beta -> check_feature data.Data.beta_features Beta | Field(fld, where), None, SinceVersion min_version -> version_is_good ~min_version data.Data.oasis_version (f_ "Field %s in %s is only valid since OASIS v%s, update \ OASISFormat field from '%s' to '%s' after checking \ OASIS changelog.") fld where (string_of_version min_version) (string_of_version data.Data.oasis_version) (string_of_version min_version) | Field(fld, where), Some(plugin_knd, plugin_name, _), SinceVersion min_version -> begin try let plugin_version_current = try match Data.plugin_version plugin_knd plugin_name data with | Some ver -> ver | None -> failwithf (f_ "Field %s in %s is only valid for the OASIS \ plugin %s since v%s, but no plugin version is \ defined in the _oasis file, change '%s' to \ '%s (%s)' in your _oasis file.") fld where plugin_name (string_of_version min_version) plugin_name plugin_name (string_of_version min_version) with Not_found -> failwithf (f_ "Field %s in %s is only valid when the OASIS plugin %s \ is defined.") fld where plugin_name in version_is_good ~min_version plugin_version_current (f_ "Field %s in %s is only valid for the OASIS plugin %s \ since v%s, update your plugin from '%s (%s)' to \ '%s (%s)' after checking the plugin's changelog.") fld where plugin_name (string_of_version min_version) plugin_name (string_of_version plugin_version_current) plugin_name (string_of_version min_version) with Failure msg -> Some msg end | Section sct, None, SinceVersion min_version -> version_is_good ~min_version data.Data.oasis_version (f_ "Section %s is only valid for since OASIS v%s, update \ OASISFormat field from '%s' to '%s' after checking OASIS \ changelog.") sct (string_of_version min_version) (string_of_version data.Data.oasis_version) (string_of_version min_version) | Section sct, Some(plugin_knd, plugin_name, _), SinceVersion min_version -> begin try let plugin_version_current = try match Data.plugin_version plugin_knd plugin_name data with | Some ver -> ver | None -> failwithf (f_ "Section %s is only valid for the OASIS \ plugin %s since v%s, but no plugin version is \ defined in the _oasis file, change '%s' to \ '%s (%s)' in your _oasis file.") sct plugin_name (string_of_version min_version) plugin_name plugin_name (string_of_version min_version) with Not_found -> failwithf (f_ "Section %s is only valid when the OASIS plugin %s \ is defined.") sct plugin_name in version_is_good ~min_version plugin_version_current (f_ "Section %s is only valid for the OASIS plugin %s \ since v%s, update your plugin from '%s (%s)' to \ '%s (%s)' after checking the plugin's changelog.") sct plugin_name (string_of_version min_version) plugin_name (string_of_version plugin_version_current) plugin_name (string_of_version min_version) with Failure msg -> Some msg end | NoOrigin, None, SinceVersion min_version -> version_is_good ~min_version data.Data.oasis_version "%s" no_message | NoOrigin, Some(plugin_knd, plugin_name, _), SinceVersion min_version -> begin try let plugin_version_current = match Data.plugin_version plugin_knd plugin_name data with | Some ver -> ver | None -> raise Not_found in version_is_good ~min_version plugin_version_current "%s" no_message with Not_found -> Some no_message end let data_assert t data origin = match data_check t data origin with | None -> () | Some str -> failwith str let data_test t data = match data_check t data NoOrigin with | None -> true | Some _ -> false let package_test t pkg = data_test t (Data.of_package pkg) let create ?plugin name publication description = let () = if Hashtbl.mem all_features name then failwithf "Feature '%s' is already declared." name in let t = { name = name; plugin = plugin; publication = publication; description = description; } in Hashtbl.add all_features name t; t let get_stage name = try (Hashtbl.find all_features name).publication with Not_found -> failwithf (f_ "Feature %s doesn't exist.") name let list () = Hashtbl.fold (fun _ v acc -> v :: acc) all_features [] (* * Real flags. *) let features = create "features_fields" (since_version "0.4") (fun () -> s_ "Enable to experiment not yet official features.") let flag_docs = create "flag_docs" (since_version "0.3") (fun () -> s_ "Make building docs require '-docs' flag at configure.") let flag_tests = create "flag_tests" (since_version "0.3") (fun () -> s_ "Make running tests require '-tests' flag at configure.") let pack = create "pack" (since_version "0.3") (fun () -> s_ "Allow to create packed library.") let section_object = create "section_object" beta (fun () -> s_ "Implement an object section.") let dynrun_for_release = create "dynrun_for_release" alpha (fun () -> s_ "Make '-setup-update dynamic' suitable for releasing project.") let compiled_setup_ml = create "compiled_setup_ml" alpha (fun () -> s_ "Compile the setup.ml and speed-up actions done with it.") let disable_oasis_section = create "disable_oasis_section" alpha (fun () -> s_ "Allow the OASIS section comments and digests to be omitted in \ generated files.") let no_automatic_syntax = create "no_automatic_syntax" alpha (fun () -> s_ "Disable the automatic inclusion of -syntax camlp4o for packages \ that matches the internal heuristic (if a dependency ends with \ a .syntax or is a well known syntax).") let findlib_directory = create "findlib_directory" beta (fun () -> s_ "Allow to install findlib libraries in sub-directories of the target \ findlib directory.") let findlib_extra_files = create "findlib_extra_files" beta (fun () -> s_ "Allow to install extra files for findlib libraries.") let source_patterns = create "source_patterns" alpha (fun () -> s_ "Customize mapping between module name and source file.") end module OASISSection = struct (* # 22 "src/oasis/OASISSection.ml" *) open OASISTypes let section_kind_common = function | Library (cs, _, _) -> `Library, cs | Object (cs, _, _) -> `Object, 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) | Object (_, bs, obj) -> Object (cs, bs, obj) | 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_kind = function | `Library -> "library" | `Object -> "object" | `Executable -> "executable" | `Flag -> "flag" | `SrcRepo -> "src repository" | `Test -> "test" | `Doc -> "doc" let string_of_section sct = let k, nm = section_id sct in (string_of_section_kind k)^" "^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 (* # 22 "src/oasis/OASISBuildSection.ml" *) open OASISTypes (* Look for a module file, considering capitalization or not. *) let find_module source_file_exists bs modul = let possible_lst = OASISSourcePatterns.all_possible_files (bs.bs_interface_patterns @ bs.bs_implementation_patterns) ~path:bs.bs_path ~modul in match List.filter source_file_exists possible_lst with | (fn :: _) as fn_lst -> `Sources (OASISUnixPath.chop_extension fn, fn_lst) | [] -> let open OASISUtils in let _, rev_lst = List.fold_left (fun (set, acc) fn -> let base_fn = OASISUnixPath.chop_extension fn in if SetString.mem base_fn set then set, acc else SetString.add base_fn set, base_fn :: acc) (SetString.empty, []) possible_lst in `No_sources (List.rev rev_lst) end module OASISExecutable = struct (* # 22 "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 (* # 22 "src/oasis/OASISLibrary.ml" *) open OASISTypes open OASISGettext let find_module ~ctxt source_file_exists cs bs modul = match OASISBuildSection.find_module source_file_exists bs modul with | `Sources _ as res -> res | `No_sources _ as res -> OASISMessage.warning ~ctxt (f_ "Cannot find source file matching module '%s' in library %s.") modul cs.cs_name; OASISMessage.warning ~ctxt (f_ "Use InterfacePatterns or ImplementationPatterns to define \ this file with feature %S.") (OASISFeatures.source_patterns.OASISFeatures.name); res let source_unix_files ~ctxt (cs, bs, lib) source_file_exists = List.fold_left (fun acc modul -> match find_module ~ctxt source_file_exists cs bs modul with | `Sources (base_fn, lst) -> (base_fn, lst) :: acc | `No_sources _ -> 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 ~ctxt source_file_exists cs bs modul with | `Sources (_, [fn]) when ext <> "cmi" && Filename.check_suffix fn ".mli" -> None (* No implementation files for pure interface. *) | `Sources (base_fn, _) -> Some [base_fn] | `No_sources lst -> Some lst in List.fold_left (fun acc nm -> match find_module nm with | None -> acc | Some base_fns -> List.map (fun base_fn -> base_fn ^"."^ext) base_fns :: acc) [] lst in (* The .cmx that be compiled along *) let cmxs = let should_be_built = match bs.bs_compiled_object with | Native -> true | Best -> is_native | Byte -> false in if should_be_built then if lib.lib_pack then find_modules [cs.cs_name] "cmx" else find_modules (lib.lib_modules @ lib.lib_internal_modules) "cmx" else [] in let acc_nopath = [] in (* The headers and annot/cmt files that should be compiled along *) let headers = let sufx = if lib.lib_pack then [".cmti"; ".cmt"; ".annot"] else [".cmi"; ".cmti"; ".cmt"; ".annot"] in List.map (List.fold_left (fun accu s -> let dot = String.rindex s '.' in let base = String.sub s 0 dot in List.map ((^) base) sufx @ accu) []) (find_modules lib.lib_modules "cmi") 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"; cs.cs_name^".cmti"; cs.cs_name^".cmt"] :: 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] :: if has_native_dynlink then ["dll"^cs.cs_name^"_stubs"^ext_dll] :: acc_nopath else acc_nopath end else begin acc_nopath end in (* All the files generated *) List.rev_append (List.rev_map (List.rev_map (OASISUnixPath.concat bs.bs_path)) acc_nopath) (headers @ cmxs) end module OASISObject = struct (* # 22 "src/oasis/OASISObject.ml" *) open OASISTypes open OASISGettext let find_module ~ctxt source_file_exists cs bs modul = match OASISBuildSection.find_module source_file_exists bs modul with | `Sources _ as res -> res | `No_sources _ as res -> OASISMessage.warning ~ctxt (f_ "Cannot find source file matching module '%s' in object %s.") modul cs.cs_name; OASISMessage.warning ~ctxt (f_ "Use InterfacePatterns or ImplementationPatterns to define \ this file with feature %S.") (OASISFeatures.source_patterns.OASISFeatures.name); res let source_unix_files ~ctxt (cs, bs, obj) source_file_exists = List.fold_left (fun acc modul -> match find_module ~ctxt source_file_exists cs bs modul with | `Sources (base_fn, lst) -> (base_fn, lst) :: acc | `No_sources _ -> acc) [] obj.obj_modules let generated_unix_files ~ctxt ~is_native ~source_file_exists (cs, bs, obj) = let find_module ext modul = match find_module ~ctxt source_file_exists cs bs modul with | `Sources (base_fn, _) -> [base_fn ^ ext] | `No_sources lst -> lst in let header, byte, native, c_object, f = match obj.obj_modules with | [ m ] -> (find_module ".cmi" m, find_module ".cmo" m, find_module ".cmx" m, find_module ".o" m, fun x -> x) | _ -> ([cs.cs_name ^ ".cmi"], [cs.cs_name ^ ".cmo"], [cs.cs_name ^ ".cmx"], [cs.cs_name ^ ".o"], OASISUnixPath.concat bs.bs_path) in List.map (List.map f) ( match bs.bs_compiled_object with | Native -> native :: c_object :: byte :: header :: [] | Best when is_native -> native :: c_object :: byte :: header :: [] | Byte | Best -> byte :: header :: []) end module OASISFindlib = struct (* # 22 "src/oasis/OASISFindlib.ml" *) open OASISTypes open OASISUtils open OASISGettext 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 of library | `Object of object_] * unix_dirname option * group_t list) type data = common_section * build_section * [`Library of library | `Object of object_] 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 | Object (cs, _, obj) -> begin let obj_name = cs.cs_name in if MapString.mem obj_name mp then failwithf (f_ "The object name '%s' is used more than once.") obj_name; let findlib_full_name = match obj.obj_findlib_fullname with | Some ns -> String.concat "." ns | None -> obj_name in MapString.add obj_name (`Solved findlib_full_name) 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 unix_directory dn lib = let directory = match lib with | `Library lib -> lib.lib_findlib_directory | `Object obj -> obj.obj_findlib_directory in match dn, directory with | None, None -> None | None, Some dn | Some dn, None -> Some dn | Some dn1, Some dn2 -> Some (OASISUnixPath.concat dn1 dn2) in let rec group_of_tree dn mp = MapString.fold (fun nm node acc -> let cur = match node with | Node (Some (cs, bs, lib), children) -> let current_dn = unix_directory dn lib in Package (nm, cs, bs, lib, current_dn, group_of_tree current_dn children) | Node (None, children) -> Container (nm, group_of_tree dn children) | Leaf (cs, bs, lib) -> let current_dn = unix_directory dn lib in Package (nm, cs, bs, lib, current_dn, []) in cur :: acc) mp [] in let group_mp = List.fold_left (fun mp -> function | Library (cs, bs, lib) -> add (cs, bs, `Library lib) mp | Object (cs, bs, obj) -> add (cs, bs, `Object obj) mp | _ -> mp) MapString.empty pkg.sections in let groups = group_of_tree None group_mp in let library_name_of_findlib_name = lazy begin (* Revert findlib_name_of_library_name. *) MapString.fold (fun k v mp -> MapString.add v k mp) fndlb_name_of_lib_name MapString.empty end 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 (* # 22 "src/oasis/OASISFlag.ml" *) end module OASISPackage = struct (* # 22 "src/oasis/OASISPackage.ml" *) end module OASISSourceRepository = struct (* # 22 "src/oasis/OASISSourceRepository.ml" *) end module OASISTest = struct (* # 22 "src/oasis/OASISTest.ml" *) end module OASISDocument = struct (* # 22 "src/oasis/OASISDocument.ml" *) end module OASISExec = struct (* # 22 "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 (* # 22 "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 (fun file -> (if case_sensitive then file_exists_case file else Sys.file_exists file) && not (Sys.is_directory file) ) 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 else begin OASISMessage.error ~ctxt (f_ "Cannot remove directory '%s': not empty.") 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 # 3159 "setup.ml" module BaseEnvLight = struct (* # 22 "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) ?stream () = let line = ref 1 in let lexer st = 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 Genlex.make_lexer ["="] st_line in let rec read_file lxr mp = match Stream.npeek 3 lxr with | [Genlex.Ident nm; Genlex.Kwd "="; Genlex.String value] -> Stream.junk lxr; Stream.junk lxr; Stream.junk lxr; read_file lxr (MapString.add nm value mp) | [] -> mp | _ -> failwith (Printf.sprintf "Malformed data file '%s' line %d" filename !line) in match stream with | Some st -> read_file (lexer st) MapString.empty | None -> if Sys.file_exists filename then begin let chn = open_in_bin filename in let st = Stream.of_channel chn in try let mp = read_file (lexer st) MapString.empty in close_in chn; mp with e -> close_in chn; raise e 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 rec var_expand str env = let buff = Buffer.create ((String.length str) * 2) in Buffer.add_substitute buff (fun var -> try var_expand (MapString.find var env) env with Not_found -> failwith (Printf.sprintf "No variable %s defined when trying to expand %S." var str)) str; Buffer.contents buff let var_get name env = var_expand (MapString.find name env) env let var_choose lst env = OASISExpr.choose (fun nm -> var_get nm env) lst end # 3239 "setup.ml" module BaseContext = struct (* # 22 "src/base/BaseContext.ml" *) (* TODO: get rid of this module. *) open OASISContext let args () = fst (fspecs ()) let default = default end module BaseMessage = struct (* # 22 "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 (* # 22 "src/base/BaseEnv.ml" *) open OASISGettext open OASISUtils open OASISContext 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) (_, 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 (_: 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 = in_srcdir "setup.data" let load ~ctxt ?(allow_empty=false) ?(filename=default_filename) () = let open OASISFileSystem in env_from_file := let repr_filename = ctxt.srcfs#string_of_filename filename in if ctxt.srcfs#file_exists filename then begin let buf = Buffer.create 13 in defer_close (ctxt.srcfs#open_in ~mode:binary_in filename) (read_all buf); defer_close (ctxt.srcfs#open_in ~mode:binary_in filename) (fun rdr -> OASISMessage.info ~ctxt "Loading environment from %S." repr_filename; BaseEnvLight.load ~allow_empty ~filename:(repr_filename) ~stream:(stream_of_reader rdr) ()) end else if allow_empty then begin BaseEnvLight.MapString.empty end else begin failwith (Printf.sprintf (f_ "Unable to load environment, the file '%s' doesn't exist.") repr_filename) end let unload () = env_from_file := MapString.empty; Data.clear env let dump ~ctxt ?(filename=default_filename) () = let open OASISFileSystem in defer_close (ctxt.OASISContext.srcfs#open_out ~mode:binary_out filename) (fun wrtr -> let buf = Buffer.create 63 in let output nm value = Buffer.add_string buf (Printf.sprintf "%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 output nm (Schema.get schema env nm) 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; wrtr#output buf) 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" name (dot_pad name); if value = "" then Printf.printf "\n" else Printf.printf " %s\n" 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 (* # 22 "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 (* # 22 "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 (* # 22 "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 (* # 22 "src/base/BaseStandardVar.ml" *) open OASISGettext open OASISTypes 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" || os_type () = "Cygwin" 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" | "Cygwin" -> ".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 (* # 22 "src/base/BaseFileAB.ml" *) open BaseEnv open OASISGettext open BaseMessage open OASISContext let to_filename fn = if not (Filename.check_suffix fn ".ab") then warning (f_ "File '%s' doesn't have '.ab' extension") fn; OASISFileSystem.of_unix_filename (Filename.chop_extension fn) let replace ~ctxt fn_lst = let open OASISFileSystem in let ibuf, obuf = Buffer.create 13, Buffer.create 13 in List.iter (fun fn -> Buffer.clear ibuf; Buffer.clear obuf; defer_close (ctxt.srcfs#open_in (of_unix_filename fn)) (read_all ibuf); Buffer.add_string obuf (var_expand (Buffer.contents ibuf)); defer_close (ctxt.srcfs#open_out (to_filename fn)) (fun wrtr -> wrtr#output obuf)) fn_lst end module BaseLog = struct (* # 22 "src/base/BaseLog.ml" *) open OASISUtils open OASISContext open OASISGettext open OASISFileSystem let default_filename = in_srcdir "setup.log" let load ~ctxt () = let 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) in if ctxt.srcfs#file_exists default_filename then begin defer_close (ctxt.srcfs#open_in default_filename) (fun rdr -> let line = ref 1 in let lxr = Genlex.make_lexer [] (stream_of_reader rdr) in let rec read_aux (st, lst) = match Stream.npeek 2 lxr with | [Genlex.String e; Genlex.String d] -> let t = e, d in Stream.junk lxr; Stream.junk lxr; if SetTupleString.mem t st then read_aux (st, lst) else read_aux (SetTupleString.add t st, t :: lst) | [] -> List.rev lst | _ -> failwithf (f_ "Malformed log file '%s' at line %d") (ctxt.srcfs#string_of_filename default_filename) !line in read_aux (SetTupleString.empty, [])) end else begin [] end let register ~ctxt event data = defer_close (ctxt.srcfs#open_out ~mode:[Open_append; Open_creat; Open_text] ~perm:0o644 default_filename) (fun wrtr -> let buf = Buffer.create 13 in Printf.bprintf buf "%S %S\n" event data; wrtr#output buf) let unregister ~ctxt event data = let lst = load ~ctxt () in let buf = Buffer.create 13 in List.iter (fun (e, d) -> if e <> event || d <> data then Printf.bprintf buf "%S %S\n" e d) lst; if Buffer.length buf > 0 then defer_close (ctxt.srcfs#open_out default_filename) (fun wrtr -> wrtr#output buf) else ctxt.srcfs#remove default_filename let filter ~ctxt events = let st_events = SetString.of_list events in List.filter (fun (e, _) -> SetString.mem e st_events) (load ~ctxt ()) let exists ~ctxt event data = List.exists (fun v -> (event, data) = v) (load ~ctxt ()) end module BaseBuilt = struct (* # 22 "src/base/BaseBuilt.ml" *) open OASISTypes open OASISGettext open BaseStandardVar open BaseMessage type t = | BExec (* Executable *) | BExecLib (* Library coming with executable *) | BLib (* Library *) | BObj (* Library *) | BDoc (* Document *) let to_log_event_file t nm = "built_"^ (match t with | BExec -> "exec" | BExecLib -> "exec_lib" | BLib -> "lib" | BObj -> "obj" | BDoc -> "doc")^ "_"^nm let to_log_event_done t nm = "is_"^(to_log_event_file t nm) let register ~ctxt t nm lst = BaseLog.register ~ctxt (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 ~ctxt (to_log_event_file t nm) (if Filename.is_relative fn then Filename.concat (Sys.getcwd ()) fn else fn); true end else begin registered end) false alt in if not registered then warning (f_ "Cannot find an existing alternative files among: %s") (String.concat (s_ ", ") alt)) lst let unregister ~ctxt t nm = List.iter (fun (e, d) -> BaseLog.unregister ~ctxt e d) (BaseLog.filter ~ctxt [to_log_event_file t nm; to_log_event_done t nm]) let fold ~ctxt 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") | BObj -> (f_ "object %s") | BDoc -> (f_ "documentation %s")) nm); acc end) acc (BaseLog.filter ~ctxt [to_log_event_file t nm]) let is_built ~ctxt t nm = List.fold_left (fun _ (_, d) -> try bool_of_string d with _ -> false) false (BaseLog.filter ~ctxt [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 let of_object ffn (cs, bs, obj) = let unix_lst = OASISObject.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 ())) (cs, bs, obj) in let evs = [BObj, cs.cs_name, List.map (List.map ffn) unix_lst] in evs, unix_lst end module BaseCustom = struct (* # 22 "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 (* # 22 "src/base/BaseDynVar.ml" *) open OASISTypes open OASISGettext open BaseEnv open BaseBuilt let init ~ctxt 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, _) -> 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 ~ctxt 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 _ | Object _ | Flag _ | Test _ | SrcRepo _ | Doc _ -> ()) pkg.sections end module BaseTest = struct (* # 22 "src/base/BaseTest.ml" *) open BaseEnv open BaseMessage open OASISTypes open OASISGettext let test ~ctxt 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 ~ctxt 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 OASISFeatures.package_test OASISFeatures.flag_tests pkg && 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 (* # 22 "src/base/BaseDoc.ml" *) open BaseEnv open BaseMessage open OASISTypes open OASISGettext let doc ~ctxt 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 ~ctxt pkg (cs, doc)) extra_args end in List.iter one_doc lst; if OASISFeatures.package_test OASISFeatures.flag_docs pkg && 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 (* # 22 "src/base/BaseSetup.ml" *) open OASISContext open BaseEnv open BaseMessage open OASISTypes open OASISGettext open OASISUtils type std_args_fun = ctxt:OASISContext.t -> package -> string array -> unit type ('a, 'b) section_args_fun = name * (ctxt:OASISContext.t -> 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 ~ctxt t args = (* Run configure *) BaseCustom.hook t.package.conf_custom (fun () -> (* Reload if preconf has changed it *) begin try unload (); load ~ctxt (); with _ -> () end; (* Run plugin's configure *) t.configure ~ctxt t.package args; (* Dump to allow postconf to change it *) dump ~ctxt ()) (); (* Reload environment *) unload (); load ~ctxt (); (* Save environment *) print (); (* Replace data in file *) BaseFileAB.replace ~ctxt t.package.files_ab let build ~ctxt t args = BaseCustom.hook t.package.build_custom (t.build ~ctxt t.package) args let doc ~ctxt t args = BaseDoc.doc ~ctxt (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 ~ctxt t args = BaseTest.test ~ctxt (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 ~ctxt t args = let rno_doc = ref false in let rno_test = ref false in let arg_rest = ref [] 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"; "--", Arg.Rest (fun arg -> arg_rest := arg :: !arg_rest), s_ "All arguments for configure."; ] (failwithf (f_ "Don't know what to do with '%s'")) ""; info "Running configure step"; configure ~ctxt t (Array.of_list (List.rev !arg_rest)); info "Running build step"; build ~ctxt t [||]; (* Load setup.log dynamic variables *) BaseDynVar.init ~ctxt t.package; if not !rno_doc then begin info "Running doc step"; doc ~ctxt t [||] end else begin info "Skipping doc step" end; if not !rno_test then begin info "Running test step"; test ~ctxt t [||] end else begin info "Skipping test step" end let install ~ctxt t args = BaseCustom.hook t.package.install_custom (t.install ~ctxt t.package) args let uninstall ~ctxt t args = BaseCustom.hook t.package.uninstall_custom (t.uninstall ~ctxt t.package) args let reinstall ~ctxt t args = uninstall ~ctxt t args; install ~ctxt 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 ~ctxt 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 ~ctxt:_ _ _ _ -> () in failsafe (f ~ctxt t.package (cs, test)) args | Doc (cs, doc) -> let f = try List.assoc cs.cs_name docs with Not_found -> fun ~ctxt:_ _ _ _ -> () in failsafe (f ~ctxt t.package (cs, doc)) args | Library _ | Object _ | Executable _ | Flag _ | SrcRepo _ -> ()) t.package.sections; (* Clean whole package *) List.iter (fun f -> failsafe (f ~ctxt t.package) args) mains) () in let clean ~ctxt t args = generic_clean ~ctxt t t.package.clean_custom t.clean t.clean_doc t.clean_test args in let distclean ~ctxt t args = (* Call clean *) clean ~ctxt t args; (* Call distclean code *) generic_clean ~ctxt t t.package.distclean_custom t.distclean t.distclean_doc t.distclean_test args; (* Remove generated source files. *) List.iter (fun fn -> if ctxt.srcfs#file_exists fn then begin info (f_ "Remove '%s'") (ctxt.srcfs#string_of_filename fn); ctxt.srcfs#remove fn end) ([BaseEnv.default_filename; BaseLog.default_filename] @ (List.rev_map BaseFileAB.to_filename t.package.files_ab)) in clean, distclean let version ~ctxt:_ (t: 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.") (* TODO: srcfs *) let default_oasis_fn = "_oasis" let update_setup_ml t = let oasis_fn = match t.oasis_fn with | Some fn -> fn | None -> default_oasis_fn 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: (fun n -> if n <> 0 then 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 default_oasis_fn 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 let act_ref = ref (fun ~ctxt:_ _ -> 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 try let () = 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") in (* Instantiate the context. *) let ctxt = !BaseContext.default in (* Build initial environment *) load ~ctxt ~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 ~ctxt t.package; if not (t.setup_update && update_setup_ml t) then !act_ref ~ctxt t (Array.of_list (List.rev !extra_args_ref)) with e when !catch_exn -> error "%s" (Printexc.to_string e); exit 1 end module BaseCompat = struct (* # 22 "src/base/BaseCompat.ml" *) (** Compatibility layer to provide a stable API inside setup.ml. This layer allows OASIS to change in between minor versions (e.g. 0.4.6 -> 0.4.7) but still provides a stable API inside setup.ml. This enables to write functions that manipulate setup_t inside setup.ml. See deps.ml for an example. The module opened by default will depend on the version of the _oasis. E.g. if we have "OASISFormat: 0.3", the module Compat_0_3 will be opened and the function Compat_0_3 will be called. If setup.ml is generated with the -nocompat, no module will be opened. @author Sylvain Le Gall *) module Compat_0_4 = struct let rctxt = ref !BaseContext.default module BaseSetup = struct module Original = BaseSetup open OASISTypes 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; } let setup t = let mk_std_args_fun f = fun ~ctxt pkg args -> rctxt := ctxt; f pkg args in let mk_section_args_fun l = List.map (fun (nm, f) -> nm, (fun ~ctxt pkg sct args -> rctxt := ctxt; f pkg sct args)) l in let t' = { Original. configure = mk_std_args_fun t.configure; build = mk_std_args_fun t.build; doc = mk_section_args_fun t.doc; test = mk_section_args_fun t.test; install = mk_std_args_fun t.install; uninstall = mk_std_args_fun t.uninstall; clean = List.map mk_std_args_fun t.clean; clean_doc = mk_section_args_fun t.clean_doc; clean_test = mk_section_args_fun t.clean_test; distclean = List.map mk_std_args_fun t.distclean; distclean_doc = mk_section_args_fun t.distclean_doc; distclean_test = mk_section_args_fun t.distclean_test; package = t.package; oasis_fn = t.oasis_fn; oasis_version = t.oasis_version; oasis_digest = t.oasis_digest; oasis_exec = t.oasis_exec; oasis_setup_args = t.oasis_setup_args; setup_update = t.setup_update; } in Original.setup t' end let adapt_setup_t setup_t = let module O = BaseSetup.Original in let mk_std_args_fun f = fun pkg args -> f ~ctxt:!rctxt pkg args in let mk_section_args_fun l = List.map (fun (nm, f) -> nm, (fun pkg sct args -> f ~ctxt:!rctxt pkg sct args)) l in { BaseSetup. configure = mk_std_args_fun setup_t.O.configure; build = mk_std_args_fun setup_t.O.build; doc = mk_section_args_fun setup_t.O.doc; test = mk_section_args_fun setup_t.O.test; install = mk_std_args_fun setup_t.O.install; uninstall = mk_std_args_fun setup_t.O.uninstall; clean = List.map mk_std_args_fun setup_t.O.clean; clean_doc = mk_section_args_fun setup_t.O.clean_doc; clean_test = mk_section_args_fun setup_t.O.clean_test; distclean = List.map mk_std_args_fun setup_t.O.distclean; distclean_doc = mk_section_args_fun setup_t.O.distclean_doc; distclean_test = mk_section_args_fun setup_t.O.distclean_test; package = setup_t.O.package; oasis_fn = setup_t.O.oasis_fn; oasis_version = setup_t.O.oasis_version; oasis_digest = setup_t.O.oasis_digest; oasis_exec = setup_t.O.oasis_exec; oasis_setup_args = setup_t.O.oasis_setup_args; setup_update = setup_t.O.setup_update; } end module Compat_0_3 = struct include Compat_0_4 end end # 5662 "setup.ml" module InternalConfigurePlugin = struct (* # 22 "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 ~ctxt:_ 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; (* Make sure the findlib version is fine for the OCaml compiler. *) begin let ocaml_ge4 = OASISVersion.version_compare (OASISVersion.version_of_string (BaseStandardVar.ocaml_version ())) (OASISVersion.version_of_string "4.0.0") >= 0 in if ocaml_ge4 then let findlib_lt132 = OASISVersion.version_compare (OASISVersion.version_of_string (BaseStandardVar.findlib_version())) (OASISVersion.version_of_string "1.3.2") < 0 in if findlib_lt132 then add_errors "OCaml >= 4.0.0 requires Findlib version >= 1.3.2" 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 (* # 22 "src/plugins/internal/InternalInstallPlugin.ml" *) (** Install using internal scheme @author Sylvain Le Gall *) (* TODO: rewrite this module with OASISFileSystem. *) open BaseEnv open BaseStandardVar open BaseMessage open OASISTypes open OASISFindlib open OASISGettext open OASISUtils let exec_hook = ref (fun (cs, bs, exec) -> cs, bs, exec) let lib_hook = ref (fun (cs, bs, dn, lib) -> cs, bs, dn, lib, []) let obj_hook = ref (fun (cs, bs, dn, obj) -> cs, bs, dn, obj, []) 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" (* TODO: this can be more generic and used elsewhere. *) 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 = let in_destdir fn = try (* Practically speaking destdir is prepended at the beginning of the target filename *) (destdir ())^fn with PropList.Not_set _ -> fn in let install_file ~ctxt ?(prepend_destdir=true) ?tgt_fn src_file envdir = let tgt_dir = if prepend_destdir then in_destdir (envdir ()) else 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 (fun dn -> info (f_ "Creating directory '%s'") dn; BaseLog.register ~ctxt install_dir_ev dn) (Filename.dirname tgt_file); (* Really install files *) info (f_ "Copying file '%s' to '%s'") src_file tgt_file; OASISFileUtil.cp ~ctxt src_file tgt_file; BaseLog.register ~ctxt install_file_ev tgt_file in (* Install the files for a library. *) let install_lib_files ~ctxt findlib_name files = let findlib_dir = let dn = let findlib_destdir = OASISExec.run_read_one_line ~ctxt (ocamlfind ()) ["printconf" ; "destdir"] in Filename.concat findlib_destdir findlib_name in fun () -> dn in let () = if not (OASISFileUtil.file_exists_case (findlib_dir ())) then failwithf (f_ "Directory '%s' doesn't exist for findlib library %s") (findlib_dir ()) findlib_name in let f dir file = let basename = Filename.basename file in let tgt_fn = Filename.concat dir basename in (* Destdir is already include in printconf. *) install_file ~ctxt ~prepend_destdir:false ~tgt_fn file findlib_dir in List.iter (fun (dir, files) -> List.iter (f dir) files) files ; in (* Install data into defined directory *) let install_data ~ctxt 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 ~ctxt fn (fun () -> match tgt_opt with | Some s -> OASISHostPath.of_unix (var_expand s) | None -> tgtdir)) real_srcs) lst in let make_fnames modul sufx = List.fold_right begin fun sufx accu -> (OASISString.capitalize_ascii modul ^ sufx) :: (OASISString.uncapitalize_ascii modul ^ sufx) :: accu end sufx [] in (** Install all libraries *) let install_libs ~ctxt pkg = let find_first_existing_files_in_path bs lst = let path = OASISHostPath.of_unix bs.bs_path in List.find OASISFileUtil.file_exists_case (List.map (Filename.concat path) lst) in let files_of_modules new_files typ cs bs modules = List.fold_left (fun acc modul -> begin try (* Add uncompiled header from the source tree *) [find_first_existing_files_in_path bs (make_fnames modul [".mli"; ".ml"])] with Not_found -> warning (f_ "Cannot find source header for module %s \ in %s %s") typ modul cs.cs_name; [] end @ List.fold_left (fun acc fn -> try find_first_existing_files_in_path bs [fn] :: acc with Not_found -> acc) acc (make_fnames modul [".annot";".cmti";".cmt"])) new_files modules in let files_of_build_section (f_data, new_files) typ cs bs = let extra_files = List.map (fun fn -> try find_first_existing_files_in_path bs [fn] with Not_found -> failwithf (f_ "Cannot find extra findlib file %S in %s %s ") fn typ cs.cs_name) bs.bs_findlib_extra_files in let f_data () = (* Install data associated with the library *) install_data ~ctxt bs.bs_path bs.bs_data_files (Filename.concat (datarootdir ()) pkg.name); f_data () in f_data, new_files @ extra_files in let files_of_library (f_data, acc) data_lib = let cs, bs, lib, dn, lib_extra = !lib_hook data_lib in if var_choose bs.bs_install && BaseBuilt.is_built ~ctxt BaseBuilt.BLib cs.cs_name then begin (* Start with lib_extra *) let new_files = lib_extra in let new_files = files_of_modules new_files "library" cs bs lib.lib_modules in let f_data, new_files = files_of_build_section (f_data, new_files) "library" cs bs in let new_files = (* Get generated files *) BaseBuilt.fold ~ctxt BaseBuilt.BLib cs.cs_name (fun acc fn -> fn :: acc) new_files in let acc = (dn, new_files) :: acc in let f_data () = (* Install data associated with the library *) install_data ~ctxt 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 and files_of_object (f_data, acc) data_obj = let cs, bs, obj, dn, obj_extra = !obj_hook data_obj in if var_choose bs.bs_install && BaseBuilt.is_built ~ctxt BaseBuilt.BObj cs.cs_name then begin (* Start with obj_extra *) let new_files = obj_extra in let new_files = files_of_modules new_files "object" cs bs obj.obj_modules in let f_data, new_files = files_of_build_section (f_data, new_files) "object" cs bs in let new_files = (* Get generated files *) BaseBuilt.fold ~ctxt BaseBuilt.BObj cs.cs_name (fun acc fn -> fn :: acc) new_files in let acc = (dn, new_files) :: acc in let f_data () = (* Install data associated with the object *) install_data ~ctxt 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, `Library lib, dn, children) -> files_of_library data_and_files (cs, bs, lib, dn), children | Package (_, cs, bs, `Object obj, dn, children) -> files_of_object data_and_files (cs, bs, obj, dn), 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. *) (* TODO: move to OASISHostPath as make_relative. *) 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 begin n end in List.map (fun (dir, fn) -> (dir, List.map (remove_prefix (Sys.getcwd ())) fn)) files in let ocamlfind = ocamlfind () in let nodir_files, dir_files = List.fold_left (fun (nodir, dir) (dn, lst) -> match dn with | Some dn -> nodir, (dn, lst) :: dir | None -> lst @ nodir, dir) ([], []) (List.rev files) in info (f_ "Installing findlib library '%s'") findlib_name; List.iter (OASISExec.run ~ctxt ocamlfind) (split_install_command ocamlfind findlib_name meta nodir_files); install_lib_files ~ctxt findlib_name dir_files; BaseLog.register ~ctxt 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 ~ctxt pkg = let install_exec data_exec = let cs, bs, _ = !exec_hook data_exec in if var_choose bs.bs_install && BaseBuilt.is_built ~ctxt BaseBuilt.BExec cs.cs_name then begin let exec_libdir () = Filename.concat (libdir ()) pkg.name in BaseBuilt.fold ~ctxt BaseBuilt.BExec cs.cs_name (fun () fn -> install_file ~ctxt ~tgt_fn:(cs.cs_name ^ ext_program ()) fn bindir) (); BaseBuilt.fold ~ctxt BaseBuilt.BExecLib cs.cs_name (fun () fn -> install_file ~ctxt fn exec_libdir) (); install_data ~ctxt 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 ~ctxt pkg = let install_doc data = let cs, doc = !doc_hook data in if var_choose doc.doc_install && BaseBuilt.is_built ~ctxt BaseBuilt.BDoc cs.cs_name then begin let tgt_dir = OASISHostPath.of_unix (var_expand doc.doc_install_dir) in BaseBuilt.fold ~ctxt BaseBuilt.BDoc cs.cs_name (fun () fn -> install_file ~ctxt fn (fun () -> tgt_dir)) (); install_data ~ctxt 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 fun ~ctxt pkg _ -> install_libs ~ctxt pkg; install_execs ~ctxt pkg; install_docs ~ctxt pkg (* Uninstall already installed data *) let uninstall ~ctxt _ _ = let uninstall_aux (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 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 (ocamlfind ()) ["remove"; data] end else begin failwithf (f_ "Unknown log event '%s'") ev; end; BaseLog.unregister ~ctxt ev data in (* We process event in reverse order *) List.iter uninstall_aux (List.rev (BaseLog.filter ~ctxt [install_file_ev; install_dir_ev])); List.iter uninstall_aux (List.rev (BaseLog.filter ~ctxt [install_findlib_ev])) end # 6465 "setup.ml" module OCamlbuildCommon = struct (* # 22 "src/plugins/ocamlbuild/OCamlbuildCommon.ml" *) (** Functions common to OCamlbuild build and doc plugin *) open OASISGettext open BaseEnv open BaseStandardVar open OASISTypes type extra_args = string list 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"; ] else []; if OASISVersion.comparator_apply (OASISVersion.version_of_string (ocaml_version ())) (OASISVersion.VLesser (OASISVersion.version_of_string "3.11.1")) then [ "-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 (tests ()) then ["-tag"; "tests"] 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 ~ctxt extra_argv = let extra_cli = String.concat " " (Array.to_list extra_argv) in (* Run if never called with these args *) if not (BaseLog.exists ~ctxt ocamlbuild_clean_ev extra_cli) then begin OASISExec.run ~ctxt (ocamlbuild ()) (fix_args ["-clean"] extra_argv); BaseLog.register ~ctxt ocamlbuild_clean_ev extra_cli; at_exit (fun () -> try BaseLog.unregister ~ctxt ocamlbuild_clean_ev extra_cli with _ -> ()) end (** Run ocamlbuild, unregister all clean events *) let run_ocamlbuild ~ctxt args extra_argv = (* TODO: enforce that target in args must be UNIX encoded i.e. toto/index.html *) OASISExec.run ~ctxt (ocamlbuild ()) (fix_args args extra_argv); (* Remove any clean event, we must run it again *) List.iter (fun (e, d) -> BaseLog.unregister ~ctxt e d) (BaseLog.filter ~ctxt [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 (* # 22 "src/plugins/ocamlbuild/OCamlbuildPlugin.ml" *) (** Build using ocamlbuild @author Sylvain Le Gall *) open OASISTypes open OASISGettext open OASISUtils open OASISString open BaseEnv open OCamlbuildCommon open BaseStandardVar let cond_targets_hook = ref (fun lst -> lst) let build ~ctxt extra_args 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 tgts = List.flatten (List.filter (fun l -> l <> []) (List.map (List.filter (fun fn -> ends_with ~what:".cma" fn || ends_with ~what:".cmxs" fn || ends_with ~what:".cmxa" fn || ends_with ~what:(ext_lib ()) fn || ends_with ~what:(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 | Object (cs, bs, obj) when var_choose bs.bs_build -> begin let evs, unix_files = BaseBuilt.of_object in_build_dir_of_unix (cs, bs, obj) in let tgts = List.flatten (List.filter (fun l -> l <> []) (List.map (List.filter (fun fn -> ends_with ~what:".cmo" fn || ends_with ~what:".cmx" fn)) unix_files)) in match tgts with | _ :: _ -> (evs, tgts) :: acc | [] -> failwithf (f_ "No possible ocamlbuild targets for object %s") cs.cs_name end | Executable (cs, bs, exec) when var_choose bs.bs_build -> begin let evs, _, _ = 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, _ 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 _ | Object _ | 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 (fn_ "Expected built file %s doesn't exist." "None of expected built files %s exists." (List.length fns)) (String.concat (s_ " or ") (List.map (Printf.sprintf "'%s'") fns))) lst; (BaseBuilt.register ~ctxt bt bnm lst) in (* Run the hook *) let cond_targets = !cond_targets_hook cond_targets in (* Run a list of target... *) run_ocamlbuild ~ctxt (List.flatten (List.map snd cond_targets) @ extra_args) argv; (* ... and register events *) List.iter check_and_register (List.flatten (List.map fst cond_targets)) let clean ~ctxt pkg extra_args = run_clean ~ctxt extra_args; List.iter (function | Library (cs, _, _) -> BaseBuilt.unregister ~ctxt BaseBuilt.BLib cs.cs_name | Executable (cs, _, _) -> BaseBuilt.unregister ~ctxt BaseBuilt.BExec cs.cs_name; BaseBuilt.unregister ~ctxt BaseBuilt.BExecLib cs.cs_name | _ -> ()) pkg.sections end module OCamlbuildDocPlugin = struct (* # 22 "src/plugins/ocamlbuild/OCamlbuildDocPlugin.ml" *) (* Create documentation using ocamlbuild .odocl files @author Sylvain Le Gall *) open OASISTypes open OASISGettext open OCamlbuildCommon type run_t = { extra_args: string list; run_path: unix_filename; } let doc_build ~ctxt run _ (cs, _) argv = let index_html = OASISUnixPath.make [ run.run_path; cs.cs_name^".docdir"; "index.html"; ] in let tgt_dir = OASISHostPath.make [ build_dir argv; OASISHostPath.of_unix run.run_path; cs.cs_name^".docdir"; ] in run_ocamlbuild ~ctxt (index_html :: run.extra_args) argv; List.iter (fun glb -> match OASISFileUtil.glob ~ctxt (Filename.concat tgt_dir glb) with | (_ :: _) as filenames -> BaseBuilt.register ~ctxt BaseBuilt.BDoc cs.cs_name [filenames] | [] -> ()) ["*.html"; "*.css"] let doc_clean ~ctxt _ _ (cs, _) argv = run_clean ~ctxt argv; BaseBuilt.unregister ~ctxt BaseBuilt.BDoc cs.cs_name end # 6837 "setup.ml" module CustomPlugin = struct (* # 22 "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 ~ctxt:_ t _ extra_args = let cmd, args = var_choose ~name:(s_ "main command") t.cmd_main in run cmd args extra_args let clean ~ctxt:_ t _ extra_args = match var_choose t.cmd_clean with | Some (cmd, args) -> run cmd args extra_args | _ -> () let distclean ~ctxt:_ t _ extra_args = match var_choose t.cmd_distclean with | Some (cmd, args) -> run cmd args extra_args | _ -> () module Build = struct let main ~ctxt t pkg extra_args = main ~ctxt 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 ~ctxt bt bnm lst) evs) pkg.sections let clean ~ctxt t pkg extra_args = clean ~ctxt 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 ~ctxt BaseBuilt.BLib cs.cs_name | Executable (cs, _, _) -> BaseBuilt.unregister ~ctxt BaseBuilt.BExec cs.cs_name; BaseBuilt.unregister ~ctxt BaseBuilt.BExecLib cs.cs_name | _ -> ()) pkg.sections let distclean ~ctxt t pkg extra_args = distclean ~ctxt t pkg extra_args end module Test = struct let main ~ctxt t pkg (cs, _) extra_args = try main ~ctxt t pkg extra_args; 0.0 with Failure s -> BaseMessage.warning (f_ "Test '%s' fails: %s") cs.cs_name s; 1.0 let clean ~ctxt t pkg _ extra_args = clean ~ctxt t pkg extra_args let distclean ~ctxt t pkg _ extra_args = distclean ~ctxt t pkg extra_args end module Doc = struct let main ~ctxt t pkg (cs, _) extra_args = main ~ctxt t pkg extra_args; BaseBuilt.register ~ctxt BaseBuilt.BDoc cs.cs_name [] let clean ~ctxt t pkg (cs, _) extra_args = clean ~ctxt t pkg extra_args; BaseBuilt.unregister ~ctxt BaseBuilt.BDoc cs.cs_name let distclean ~ctxt t pkg _ extra_args = distclean ~ctxt t pkg extra_args end end # 6969 "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 {OCamlbuildDocPlugin.extra_args = []; run_path = "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 {OCamlbuildDocPlugin.extra_args = []; run_path = "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.4"; ocaml_version = None; version = "0.1.6"; license = OASISLicense.DEP5License (OASISLicense.DEP5Unit { OASISLicense.license = "LGPL"; excption = Some "OCaml linking"; version = OASISLicense.Version "2.1" }); findlib_version = None; alpha_features = []; beta_features = []; name = "extunix"; 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"; "(C) 2013 Mehdi Dogguy"; "(C) 2013 Roman Vorobets"; "(C) 2013 Pierre Chambart"; "(C) 2013 Dmitry Grebeniuk"; "(C) 2015 Fran\195\167ois Bobot"; "(C) 2018 Markus W. Weissmann" ]; 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"; "Mehdi Dogguy"; "Roman Vorobets"; "Pierre Chambart"; "Dmitry Grebeniuk"; "Fran\195\167ois Bobot"; "Markus W. Weissmann" ]; homepage = Some "http://extunix.forge.ocamlcore.org/"; bugreports = None; synopsis = "Extended functions for OCaml Unix module"; description = Some [ OASISText.Para "Thin bindings to various low-level system APIs (often non-portable) which are not covered by Unix module."; OASISText.Para "Some of the implemented functions : uname, statvfs, fsync, fadvise,"; OASISText.Verbatim " fallocate, openat, dirfd, eventfd, signalfd, setrlimit, mlockall, etc" ]; tags = []; categories = []; 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); FindlibPackage ("bytes", None) ]; bs_build_tools = [ExternalTool "ocamlbuild"; ExternalTool "camlp4"]; bs_interface_patterns = [ { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mli" ]; origin = "${capitalize_file module}.mli" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mli" ]; origin = "${uncapitalize_file module}.mli" } ]; bs_implementation_patterns = [ { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".ml" ]; origin = "${capitalize_file module}.ml" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".ml" ]; origin = "${uncapitalize_file module}.ml" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mll" ]; origin = "${capitalize_file module}.mll" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mll" ]; origin = "${uncapitalize_file module}.mll" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mly" ]; origin = "${capitalize_file module}.mly" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mly" ]; origin = "${uncapitalize_file module}.mly" } ]; 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"; "mktemp.c"; "memalign.c"; "endianba.c"; "pread_pwrite_ba.c"; "bigarray.c"; "splice.c"; "sysconf.c"; "common.c"; "common.h"; "sockopt.c"; "poll.c"; "sysinfo.c"; "mount.c"; "unshare.c"; "syslog.c" ]; bs_data_files = []; bs_findlib_extra_files = []; bs_ccopt = [ (OASISExpr.EBool true, []); (OASISExpr.EAnd (OASISExpr.EFlag "strict", OASISExpr.ETest ("ccomp_type", "cc")), ["-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"; "ExtUnixAll"; "ExtUnixSpecific"; "ExtUnixConfig" ]; lib_pack = false; lib_internal_modules = []; lib_findlib_parent = None; lib_findlib_name = None; lib_findlib_directory = 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_interface_patterns = [ { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mli" ]; origin = "${capitalize_file module}.mli" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mli" ]; origin = "${uncapitalize_file module}.mli" } ]; bs_implementation_patterns = [ { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".ml" ]; origin = "${capitalize_file module}.ml" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".ml" ]; origin = "${uncapitalize_file module}.ml" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mll" ]; origin = "${capitalize_file module}.mll" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mll" ]; origin = "${uncapitalize_file module}.mll" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mly" ]; origin = "${capitalize_file module}.mly" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mly" ]; origin = "${uncapitalize_file module}.mly" } ]; bs_c_sources = []; bs_data_files = []; bs_findlib_extra_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_interface_patterns = [ { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mli" ]; origin = "${capitalize_file module}.mli" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mli" ]; origin = "${uncapitalize_file module}.mli" } ]; bs_implementation_patterns = [ { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".ml" ]; origin = "${capitalize_file module}.ml" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".ml" ]; origin = "${uncapitalize_file module}.ml" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mll" ]; origin = "${capitalize_file module}.mll" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mll" ]; origin = "${uncapitalize_file module}.mll" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mly" ]; origin = "${capitalize_file module}.mly" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mly" ]; origin = "${uncapitalize_file module}.mly" } ]; bs_c_sources = []; bs_data_files = []; bs_findlib_extra_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"}); Executable ({ cs_name = "test_user_namespace"; 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 = [ FindlibPackage ("str", None); InternalLibrary "extunix"; FindlibPackage ("oUnit", Some (OASISVersion.VGreaterEqual "1.0.3")) ]; bs_build_tools = [ExternalTool "ocamlbuild"; ExternalTool "camlp4"]; bs_interface_patterns = [ { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mli" ]; origin = "${capitalize_file module}.mli" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mli" ]; origin = "${uncapitalize_file module}.mli" } ]; bs_implementation_patterns = [ { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".ml" ]; origin = "${capitalize_file module}.ml" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".ml" ]; origin = "${uncapitalize_file module}.ml" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mll" ]; origin = "${capitalize_file module}.mll" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mll" ]; origin = "${uncapitalize_file module}.mll" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("capitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mly" ]; origin = "${capitalize_file module}.mly" }; { OASISSourcePatterns.Templater.atoms = [ OASISSourcePatterns.Templater.Text ""; OASISSourcePatterns.Templater.Expr (OASISSourcePatterns.Templater.Call ("uncapitalize_file", OASISSourcePatterns.Templater.Ident "module")); OASISSourcePatterns.Templater.Text ".mly" ]; origin = "${uncapitalize_file module}.mly" } ]; bs_c_sources = []; bs_data_files = []; bs_findlib_extra_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_user_namespace.ml" }); Test ({ cs_name = "main"; cs_data = PropList.Data.create (); cs_plugin_data = [] }, { test_type = (`Test, "custom", Some "0.4"); 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"; InternalExecutable "test_user_namespace" ] }); 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"; "Mehdi Dogguy"; "Roman Vorobets"; "Pierre Chambart"; "Dmitry Grebeniuk" ]; doc_abstract = None; doc_format = HTML "index.html"; doc_data_files = []; doc_build_tools = [ ExternalTool "ocamlbuild"; ExternalTool "camlp4"; ExternalTool "ocamldoc" ] }) ]; disable_oasis_section = []; conf_type = (`Configure, "internal", Some "0.4"); 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.4"); build_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)] }; install_type = (`Install, "internal", Some "0.4"); 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\")"]))) ] }; 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.4.10"; oasis_digest = Some "\158W\132\158\196\198T\029\205\252|\012^\1983\217"; oasis_exec = None; oasis_setup_args = []; setup_update = false };; let setup () = BaseSetup.setup setup_t;; # 7903 "setup.ml" let setup_t = BaseCompat.Compat_0_4.adapt_setup_t setup_t open BaseCompat.Compat_0_4 (* OASIS_STOP *) let () = setup ();; ocaml-extunix-0.1.6/src/000077500000000000000000000000001325120070500150755ustar00rootroot00000000000000ocaml-extunix-0.1.6/src/META000066400000000000000000000005511325120070500155470ustar00rootroot00000000000000# OASIS_START # DO NOT EDIT (digest: d6921a7b0d01cc37e6653d1891207aa5) version = "0.1.6" description = "Extended functions for OCaml Unix module" requires = "unix bigarray bytes" 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.1.6/src/TODO/000077500000000000000000000000001325120070500156425ustar00rootroot00000000000000ocaml-extunix-0.1.6/src/TODO/ftruncate/000077500000000000000000000000001325120070500176355ustar00rootroot00000000000000ocaml-extunix-0.1.6/src/TODO/ftruncate/ftruncate.ml000066400000000000000000000010321325120070500221560ustar00rootroot00000000000000 (** 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.1.6/src/TODO/ftruncate/ftruncateC.c000066400000000000000000000036131325120070500221020ustar00rootroot00000000000000 /* * 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.1.6/src/api.odocl000066400000000000000000000002051325120070500166650ustar00rootroot00000000000000# OASIS_START # DO NOT EDIT (digest: 92366bf0d417174534c0e4b99a4b4a1b) ExtUnix ExtUnixAll ExtUnixSpecific ExtUnixConfig # OASIS_STOP ocaml-extunix-0.1.6/src/atfile.c000066400000000000000000000147341325120070500165160ustar00rootroot00000000000000 #define EXTUNIX_WANT_ATFILE #include "config.h" #if defined(EXTUNIX_HAVE_ATFILE) /* otherlibs/unix/cst2constr.h */ extern value cst_to_constr(int n, int * tbl, int size, int deflt); static int file_kind_table[] = { S_IFREG, S_IFDIR, S_IFCHR, S_IFBLK, S_IFLNK, S_IFIFO, S_IFSOCK }; #ifndef AT_EACCESS #define AT_EACCESS 0 #endif #ifndef AT_SYMLINK_NOFOLLOW #define AT_SYMLINK_NOFOLLOW 0 #endif #ifndef AT_SYMLINK_FOLLOW #define AT_SYMLINK_FOLLOW 0 #endif #ifndef AT_NO_AUTOMOUNT #define AT_NO_AUTOMOUNT 0 #endif static int at_flags_table[] = { AT_EACCESS, AT_SYMLINK_NOFOLLOW, AT_REMOVEDIR, AT_SYMLINK_FOLLOW, AT_NO_AUTOMOUNT, }; static value stat_aux(/*int use_64,*/ struct stat *buf) { CAMLparam0(); CAMLlocal5(atime, mtime, ctime, offset, v); atime = caml_copy_double((double) buf->st_atime); mtime = caml_copy_double((double) buf->st_mtime); ctime = caml_copy_double((double) buf->st_ctime); offset = /*use_64 ? Val_file_offset(buf->st_size) :*/ Val_int (buf->st_size); v = caml_alloc_small(12, 0); Field (v, 0) = Val_int (buf->st_dev); Field (v, 1) = Val_int (buf->st_ino); Field (v, 2) = cst_to_constr(buf->st_mode & S_IFMT, file_kind_table, sizeof(file_kind_table) / sizeof(int), 0); Field (v, 3) = Val_int (buf->st_mode & 07777); Field (v, 4) = Val_int (buf->st_nlink); Field (v, 5) = Val_int (buf->st_uid); Field (v, 6) = Val_int (buf->st_gid); Field (v, 7) = Val_int (buf->st_rdev); Field (v, 8) = offset; Field (v, 9) = atime; Field (v, 10) = mtime; Field (v, 11) = ctime; CAMLreturn(v); } CAMLprim value caml_extunix_fstatat(value v_dirfd, value v_name, value v_flags) { CAMLparam3(v_dirfd, v_name, v_flags); int ret; struct stat buf; char* p = strdup(String_val(v_name)); int flags = caml_convert_flag_list(v_flags, at_flags_table); flags &= (AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT); /* only allowed flags here */ caml_enter_blocking_section(); ret = fstatat(Int_val(v_dirfd), p, &buf, flags); caml_leave_blocking_section(); free(p); if (ret != 0) uerror("fstatat", v_name); if (buf.st_size > Max_long && (buf.st_mode & S_IFMT) == S_IFREG) unix_error(EOVERFLOW, "fstatat", v_name); CAMLreturn(stat_aux(/*0,*/ &buf)); } CAMLprim value caml_extunix_unlinkat(value v_dirfd, value v_name, value v_flags) { CAMLparam3(v_dirfd, v_name, v_flags); char* p = strdup(String_val(v_name)); int ret = 0; int flags = caml_convert_flag_list(v_flags, at_flags_table); flags &= AT_REMOVEDIR; /* only allowed flag here */ caml_enter_blocking_section(); ret = unlinkat(Int_val(v_dirfd), p, flags); caml_leave_blocking_section(); free(p); if (ret != 0) uerror("unlinkat", v_name); CAMLreturn(Val_unit); } CAMLprim value caml_extunix_renameat(value v_oldfd, value v_oldname, value v_newfd, value v_newname) { CAMLparam4(v_oldfd, v_oldname, v_newfd, v_newname); int ret = renameat(Int_val(v_oldfd), String_val(v_oldname), Int_val(v_newfd), String_val(v_newname)); if (ret != 0) uerror("renameat", v_oldname); CAMLreturn(Val_unit); } CAMLprim value caml_extunix_mkdirat(value v_dirfd, value v_name, value v_mode) { CAMLparam3(v_dirfd, v_name, v_mode); int ret = mkdirat(Int_val(v_dirfd), String_val(v_name), Int_val(v_mode)); if (ret != 0) uerror("mkdirat", v_name); CAMLreturn(Val_unit); } CAMLprim value caml_extunix_linkat(value v_olddirfd, value v_oldname, value v_newdirfd, value v_newname, value v_flags) { CAMLparam5(v_olddirfd, v_oldname, v_newdirfd, v_newname, v_flags); int ret = 0; int flags = caml_convert_flag_list(v_flags, at_flags_table); flags &= AT_SYMLINK_FOLLOW; /* only allowed flag here */ ret = linkat(Int_val(v_olddirfd), String_val(v_oldname), Int_val(v_newdirfd), String_val(v_newname), flags); if (ret != 0) uerror("linkat", v_oldname); CAMLreturn(Val_unit); } CAMLprim value caml_extunix_fchownat(value v_dirfd, value v_name, value v_owner, value v_group, value v_flags) { CAMLparam5(v_dirfd, v_name, v_owner, v_group, v_flags); int ret = 0; int flags = caml_convert_flag_list(v_flags, at_flags_table); flags &= (AT_SYMLINK_NOFOLLOW /* | AT_EMPTY_PATH */); /* only allowed flag here */ ret = fchownat(Int_val(v_dirfd), String_val(v_name), Int_val(v_owner), Int_val(v_group), flags); if (ret != 0) uerror("fchownat", v_name); CAMLreturn(Val_unit); } CAMLprim value caml_extunix_fchmodat(value v_dirfd, value v_name, value v_mode, value v_flags) { CAMLparam4(v_dirfd, v_name, v_mode, v_flags); int ret = 0; int flags = caml_convert_flag_list(v_flags, at_flags_table); flags &= AT_SYMLINK_NOFOLLOW; /* only allowed flag here */ ret = fchmodat(Int_val(v_dirfd), String_val(v_name), Int_val(v_mode), flags); if (ret != 0) uerror("fchmodat", v_name); CAMLreturn(Val_unit); } CAMLprim value caml_extunix_symlinkat(value v_path, value v_newdirfd, value v_newname) { CAMLparam3(v_path, v_newdirfd, v_newname); int ret = symlinkat(String_val(v_path), Int_val(v_newdirfd), String_val(v_newname)); if (ret != 0) uerror("symlinkat", v_path); CAMLreturn(Val_unit); } CAMLprim value caml_extunix_openat(value v_dirfd, value path, value flags, value perm) { CAMLparam4(v_dirfd, path, flags, perm); int ret, cv_flags; char * p; cv_flags = extunix_open_flags(flags); p = strdup(String_val(path)); /* open on a named FIFO can block (PR#1533) */ caml_enter_blocking_section(); ret = openat(Int_val(v_dirfd), p, cv_flags, Int_val(perm)); caml_leave_blocking_section(); free(p); if (ret == -1) uerror("openat", path); CAMLreturn (Val_int(ret)); } char *readlinkat_malloc (int dirfd, const char *filename) { int size = 100; int nchars; char *buffer = NULL; char *tmp; while (1) { tmp = (char *) realloc (buffer, size); if (tmp == NULL) { free(buffer); /* if failed, dealloc is not performed */ return NULL; } buffer = tmp; nchars = readlinkat (dirfd, filename, buffer, size); if (nchars < 0) { free (buffer); return NULL; } if (nchars < size) { buffer[nchars] = '\0'; return buffer; } size *= 2; } } CAMLprim value caml_extunix_readlinkat(value v_dirfd, value v_name) { CAMLparam2(v_dirfd, v_name); CAMLlocal1(v_link); char* res; char* p = strdup(String_val(v_name)); caml_enter_blocking_section(); res = readlinkat_malloc(Int_val(v_dirfd), p); caml_leave_blocking_section(); free(p); if (res == NULL) uerror("readlinkat", v_name); v_link = caml_copy_string(res); free(res); CAMLreturn(v_link); } #endif ocaml-extunix-0.1.6/src/bigarray.c000066400000000000000000000014741325120070500170470ustar00rootroot00000000000000#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.1.6/src/common.c000066400000000000000000000017471325120070500165420ustar00rootroot00000000000000 #include "config.h" #include /* otherlibs/unix/open.c */ #ifndef O_NONBLOCK #ifdef __MINGW32__ #define O_NONBLOCK 0 /* no O_NONBLOCK on mingw */ #else #define O_NONBLOCK O_NDELAY #endif #endif #ifndef O_NOCTTY #define O_NOCTTY 0 #endif #ifndef O_DSYNC #define O_DSYNC 0 #endif #ifndef O_SYNC #define O_SYNC 0 #endif #ifndef O_RSYNC #define O_RSYNC 0 #endif #ifndef O_CLOEXEC #define O_CLOEXEC 0 #endif #ifndef O_KEEPEXEC #define O_KEEPEXEC 0 #endif static int open_flag_table[] = { O_RDONLY, O_WRONLY, O_RDWR, O_NONBLOCK, O_APPEND, O_CREAT, O_TRUNC, O_EXCL, O_NOCTTY, O_DSYNC, O_SYNC, O_RSYNC, 0 /* O_SHARE_DELETE */, O_CLOEXEC, O_KEEPEXEC, }; int extunix_open_flags(value list) { int res; int flag; res = 0; while (list != Val_int(0)) { flag = Int_val(Field(list, 0)); if (flag >= 0 && (size_t)flag < sizeof(open_flag_table)/sizeof(open_flag_table[0])) /* new flags - ignore */ res |= open_flag_table[flag]; list = Field(list, 1); } return res; } ocaml-extunix-0.1.6/src/common.h000066400000000000000000000001711325120070500165350ustar00rootroot00000000000000 #define UNUSED(x) (void)(x) #define Val_none Val_int(0) #define Some_val(v) Field(v,0) int extunix_open_flags(value); ocaml-extunix-0.1.6/src/dirfd.c000066400000000000000000000005451325120070500163350ustar00rootroot00000000000000 #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.1.6/src/discover.ml000066400000000000000000000310031325120070500172420ustar00rootroot00000000000000(** Discover features available on this platform. There are two stages: actual discover by means of trying to compile snippets of test code and generation of config file listing all the discovered features *) #warnings "+a-4" open Printf type arg = | I of string (* check header file (#include) available (promoted to config) *) | T of string (* check type available *) | DEFINE of string (* define symbol prior to including header files (promoted to config) *) | Z of string (* define symbol to zero if not defined after the includes (promoted to config) *) | S of string (* check symbol available (e.g. function name) *) | V of string (* check value available (e.g. enum member) *) | D of string (* check symbol defined *) | 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 print_zdefine b s = bprintf b "#ifndef %s\n#define %s 0\n#endif\n" s s let filter_map f l = List.rev (List.fold_left (fun acc x -> match f x with Some s -> s::acc | None -> acc) [] l) let get_defines = filter_map (function DEFINE s -> Some s | _ -> None) let get_zdefines = filter_map (function Z s -> Some s | _ -> None) let get_includes = filter_map (function I s -> Some s | _ -> None) let config_defines = [ "_POSIX_C_SOURCE 200809L"; "_XOPEN_SOURCE 700"; "_BSD_SOURCE"; "_DEFAULT_SOURCE"; "_DARWIN_C_SOURCE"; "_LARGEFILE64_SOURCE"; "WIN32_LEAN_AND_MEAN"; "_WIN32_WINNT 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"; "assert.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 _ -> () | T s -> pr "%s var_%d;" s (fresh ()) | DEFINE _ -> () | Z _ -> () (* no test required *) | 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 ""; List.iter (print_define b) config_defines; List.iter begin function | NO _ -> (); | YES (name,args) -> match get_defines args with | [] -> () | l -> pr ""; pr "#if defined(EXTUNIX_WANT_%s)" name; List.iter (print_define b) l; pr "#endif"; end result; pr ""; List.iter (print_include b) config_includes; pr "#include \"common.h\""; List.iter begin function | NO name -> pr ""; pr "#undef EXTUNIX_HAVE_%s" name; | YES (name,args) -> pr ""; pr "#define EXTUNIX_HAVE_%s" name; match get_includes args, get_zdefines args with | [],[] -> () | includes,zdefines -> pr "#if defined(EXTUNIX_WANT_%s)" name; List.iter (print_include b) includes; List.iter (print_zdefine b) zdefines; pr "#endif"; end result; pr ""; let ch = open_out file in Buffer.output_buffer ch b; close_out ch let show_ml file result = let ch = open_out file in let pr fmt = ksprintf (fun s -> output_string ch (s^"\n")) fmt in pr "(** @return whether feature is available *)"; pr "let feature = function"; List.iter (function | YES (name,_) -> pr "| %S -> Some true" name | NO name -> pr "| %S -> Some false" name) result; pr "| _ -> None"; pr ""; pr "(** @return whether feature is available *)"; pr "let have = function"; List.iter (function | YES (name,_) -> pr "| `%s -> true" name | NO name -> pr "| `%s -> false" name) result; close_out ch let main config = let result = List.map discover config in show_c "src/config.h" result; show_ml "src/extUnixConfig.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"; S "fchownat"; S "fchmodat"; ]; "DIRFD", L[ I "sys/types.h"; I "dirent.h"; S "dirfd"; ]; "STATVFS", L[ I "sys/statvfs.h"; T "struct statvfs"; S "statvfs"; S "fstatvfs"; D "ST_RDONLY"; D "ST_NOSUID"; Z "ST_NODEV"; Z "ST_NOEXEC"; Z "ST_SYNCHRONOUS"; Z "ST_MANDLOCK"; Z "ST_WRITE"; Z "ST_APPEND"; Z "ST_IMMUTABLE"; Z "ST_NOATIME"; Z "ST_NODIRATIME"; Z "ST_RELATIME"; ]; "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"; ]; "GETTID", L[ I "sys/syscall.h"; S "syscall"; V "SYS_gettid"; ]; "PGID", L[ I "unistd.h"; S "getpgid"; S "setpgid"; S "getsid"; ]; "SETREUID", L[ I "sys/types.h"; I "unistd.h"; S "setreuid"; S "setregid" ]; "FSYNC", ANY[ [I "unistd.h"; S "fsync";]; [D "WIN32"; S "FlushFileBuffers"; ]; ]; "FDATASYNC", ANY[ [I "unistd.h"; S "fdatasync";]; [D "WIN32"; S "FlushFileBuffers"; ]; ]; "SYNC", L[ I "unistd.h"; S "sync"]; "SYNCFS", ANY[ [I "unistd.h"; S "syncfs"]; [DEFINE "EXTUNIX_USE_SYS_SYNCFS"; I "unistd.h"; I "sys/syscall.h"; S"syscall"; V"SYS_syncfs"]; ]; "REALPATH", L[ I "limits.h"; I "stdlib.h"; S "realpath"; ]; "SIGNALFD", L[ 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"tzset"; S"tzname"; ]; "TIMEZONE", L[ I "time.h"; S"tzset"; S"timezone"; S"daylight" ]; "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"; I"unistd.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"; I "unistd.h"; S"mkstemps"; ]; "MKOSTEMPS", L[ I "stdlib.h"; I "unistd.h"; S"mkostemps"; ]; "SETRESUID", L[ I"sys/types.h"; I"unistd.h"; S"setresuid"; S"setresgid" ]; "SYSCONF", L[ I "unistd.h"; S "sysconf"; (* check for standard values and extensions *) D "_SC_VERSION"; D "_SC_2_VERSION"; ]; "SPLICE", L[ I "fcntl.h"; S"splice"; ]; "TEE", L[ I "fcntl.h"; S"tee"; ]; "VMSPLICE", L[ I "fcntl.h"; S"vmsplice"; ]; "SOCKOPT", L[ I "sys/socket.h"; I "netinet/in.h"; I"netinet/tcp.h"; S"setsockopt"; S"getsockopt"; ]; "TCP_KEEPCNT", L[I"netinet/in.h"; I"netinet/tcp.h";V"TCP_KEEPCNT"]; "TCP_KEEPIDLE", L[I"netinet/in.h"; I"netinet/tcp.h";V"TCP_KEEPIDLE"]; "TCP_KEEPINTVL", L[I"netinet/in.h"; I"netinet/tcp.h";V"TCP_KEEPINTVL"]; "SO_REUSEPORT", L[I"sys/socket.h"; V"SO_REUSEPORT"]; "POLL", L[ I "poll.h"; S "poll"; D "POLLIN"; D "POLLOUT"; Z "POLLRDHUP" ]; "SYSINFO", L[ I"sys/sysinfo.h"; S"sysinfo"; F ("sysinfo","mem_unit")]; "MCHECK", L[ I"mcheck.h"; S"mtrace"; S"muntrace" ]; "MOUNT", L[ I"sys/mount.h"; S "mount"; S "umount2"; D "MS_REC" ]; "UNSHARE", L[ I"sched.h"; S "unshare"; D "CLONE_NEWPID"; D "CLONE_NEWUSER"]; "CHROOT", L[ I"unistd.h"; S "chroot"; ]; "SYSLOG", L[I"syslog.h"; S "syslog"; S "openlog"; S "closelog"; S "setlogmask"; D "LOG_PID"; D "LOG_CONS"; D "LOG_NDELAY"; D "LOG_ODELAY"; D "LOG_NOWAIT"; D "LOG_EMERG"; D "LOG_ALERT"; D "LOG_CRIT"; D "LOG_ERR"; D "LOG_WARNING"; D "LOG_NOTICE"; D "LOG_INFO"; D "LOG_DEBUG"]; ] let () = let args0 = [ "-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.1.6/src/endian.c000066400000000000000000000104471325120070500165050ustar00rootroot00000000000000#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.1.6/src/endianba.c000066400000000000000000000051441325120070500170060ustar00rootroot00000000000000#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.1.6/src/eventfd.c000066400000000000000000000013071325120070500166750ustar00rootroot00000000000000 #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.1.6/src/execinfo.c000066400000000000000000000010241325120070500170360ustar00rootroot00000000000000 #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.1.6/src/extUnix.ml000066400000000000000000000005111325120070500170700ustar00rootroot00000000000000(** 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 (** Compile-time configuration information *) module Config = ExtUnixConfig ocaml-extunix-0.1.6/src/extUnix.mlpp000066400000000000000000003416271325120070500174500ustar00rootroot00000000000000(** ExtUnix These functions are thin wrappers for underlying system API, consult the corresponding man pages and/or system documentation for details. *) (** [Not_available "symbol"] may be raised by [ExtUnix.All.func] if the wrapped C function or constant is not available on this platform. [ExtUnix.Specific] includes only functions available on the current platform and will not raise [Not_available]. Note that libc wrappers underlying [ExtUnix.Specific] functions may still raise [ENOSYS] (Not implemented) error even though the function is available. *) exception Not_available of string (** type of bigarray used by BA submodules that read from files into bigarrays or write bigarrays into files. The only constraint here is [Bigarray.c_layout]. Naming: "bigarray with C layout" -> "carray". *) type ('a, 'b) carray = ('a, 'b, Bigarray.c_layout) Bigarray.Array1.t (** type of bigarray used by BA submodules that work with endianness and memory. Constraints are: 1. [Bigarray.c_layout], 2. bigarray contains 8-bit integers. Naming: "bigarray with C layout and 8-bit elements" -> "carray8". *) type 'a carray8 = ('a, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t type open_flag = Unix.open_flag (* = O_RDONLY | O_WRONLY | O_RDWR | O_NONBLOCK | O_APPEND | O_CREAT | O_TRUNC | O_EXCL | O_NOCTTY | O_DSYNC | O_SYNC | O_RSYNC | O_SHARE_DELETE | O_CLOEXEC *) HAVE EVENTFD external eventfd : int -> Unix.file_descr = "caml_extunix_eventfd" external eventfd_read : Unix.file_descr -> int64 = "caml_extunix_eventfd_read" external eventfd_write : Unix.file_descr -> int64 -> unit = "caml_extunix_eventfd_write" END HAVE SYSLOG module Syslog : sig type options = LOG_PID | LOG_CONS | LOG_NDELAY | LOG_ODELAY | LOG_NOWAIT type facility = LOG_KERN | LOG_USER | LOG_MAIL | LOG_NEWS | LOG_UUCP | LOG_DAEMON | LOG_AUTH | LOG_CRON | LOG_LPR | LOG_LOCAL0 | LOG_LOCAL1 | LOG_LOCAL2 | LOG_LOCAL3 | LOG_LOCAL4 | LOG_LOCAL5 | LOG_LOCAL6 | LOG_LOCAL7 type level = LOG_EMERG | LOG_ALERT | LOG_CRIT | LOG_ERR | LOG_WARNING | LOG_NOTICE | LOG_INFO | LOG_DEBUG val setlogmask : level list -> level list val openlog : ?ident:string -> options list -> facility -> unit val closelog : unit -> unit val syslog : ?facility:facility -> level -> ('a, unit, string, unit) format4 -> 'a val log_upto : level -> level list end = struct type options = LOG_PID | LOG_CONS | LOG_NDELAY | LOG_ODELAY | LOG_NOWAIT type facility = LOG_KERN | LOG_USER | LOG_MAIL | LOG_NEWS | LOG_UUCP | LOG_DAEMON | LOG_AUTH | LOG_CRON | LOG_LPR | LOG_LOCAL0 | LOG_LOCAL1 | LOG_LOCAL2 | LOG_LOCAL3 | LOG_LOCAL4 | LOG_LOCAL5 | LOG_LOCAL6 | LOG_LOCAL7 type level = LOG_EMERG | LOG_ALERT | LOG_CRIT | LOG_ERR | LOG_WARNING | LOG_NOTICE | LOG_INFO | LOG_DEBUG external setlogmask : level list -> level list = "caml_extunix_setlogmask" external openlog : ?ident:string -> options list -> facility -> unit = "caml_extunix_openlog" external closelog : unit -> unit = "caml_extunix_closelog" external ext_syslog : facility option -> level -> string -> unit = "caml_extunix_syslog" let syslog ?facility lvl = Printf.ksprintf (ext_syslog facility lvl) let log_upto lvl = let rec f = function | [] -> assert false | x::xs -> if x=lvl then x::xs else f xs in f [LOG_DEBUG; LOG_INFO; LOG_NOTICE; LOG_WARNING; LOG_ERR; LOG_CRIT; LOG_ALERT; LOG_EMERG] end END HAVE 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 (** {2 Filesystem} *) HAVE FSYNC (** synchronize a file's in-core state with storage device *) external fsync : Unix.file_descr -> unit = "caml_extunix_fsync" END HAVE FDATASYNC external fdatasync : Unix.file_descr -> unit = "caml_extunix_fdatasync" END HAVE SYNC (** causes all buffered modifications to file metadata and data to be written to the underlying file systems *) external sync : unit -> unit = "caml_extunix_sync" END HAVE SYNCFS (** like {!sync}, but synchronizes just the file system containing file referred to by the open file descriptor [fd] *) external syncfs : Unix.file_descr -> unit = "caml_extunix_syncfs" END HAVE DIRFD external dirfd : Unix.dir_handle -> Unix.file_descr = "caml_extunix_dirfd" END HAVE STATVFS (** file system flags *) type st_flag = | ST_RDONLY (** Mount read-only. *) | ST_NOSUID (** Ignore suid and sgid bits. *) | ST_NODEV (** Disallow access to device special files. *) | ST_NOEXEC (** Disallow program execution. *) | ST_SYNCHRONOUS (** Writes are synced at once. *) | ST_MANDLOCK (** Allow mandatory locks on an FS. *) | ST_WRITE (** Write on file/directory/symlink. *) | ST_APPEND (** Append-only file. *) | ST_IMMUTABLE (** Immutable file. *) | ST_NOATIME (** Do not update access times. *) | ST_NODIRATIME (** Do not update directory access times. *) | ST_RELATIME (** Update atime relative to mtime/ctime. *) type statvfs = { f_bsize : int; (** file system block size *) f_blocks : int64; (** size of file system in blocks *) f_bfree : int64; (** free blocks *) f_bavail : int64; (** free blocks for unprivileged users *) f_files : int64; (** inodes *) f_ffree : int64; (** free inodes *) f_favail : int64; (** free inodes for unprivileged users *) f_fsid : int64; (** file system ID *) f_flag : int; (** mount flags (raw value) *) f_flags : st_flag list; (** mount flags (decoded) *) f_namemax : int; (** maximum filename length *) } 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" external fchownat : Unix.file_descr -> string -> int -> int -> at_flag list -> unit = "caml_extunix_fchownat" external fchmodat : Unix.file_descr -> string -> int -> at_flag list -> unit = "caml_extunix_fchmodat" 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 HAVE FCNTL (** @return whether file descriptor is open *) external is_open_descr : Unix.file_descr -> bool = "caml_extunix_is_open_descr" END HAVE REALPATH (** [realpath path] @return the canonicalized absolute pathname of [path] *) external realpath : string -> string = "caml_extunix_realpath" END HAVE FADVISE (** {3 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 (** {3 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 (** {3 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 -> Bytes.t -> int -> int -> int = "caml_extunix_all_pread" let all_pread fd off buf ofs len = if off < 0 || ofs < 0 || len < 0 || ofs > Bytes.length buf - len then invalid_arg "ExtUnix.all_pread" else unsafe_all_pread fd off buf ofs len (** [single_pread fd off buf ifs len] reads up to [len] bytes from file descriptor [fd] at offset [off] (from the start of the file) into the string [buf] at offset [ofs]. The file offset is not changed. [single_pread] attempts to read only once. Returns the number of characters read or raises an Unix.Unix_error exception. *) external unsafe_single_pread: Unix.file_descr -> int -> Bytes.t -> int -> int -> int = "caml_extunix_single_pread" let single_pread fd off buf ofs len = if off < 0 || ofs < 0 || len < 0 || ofs > Bytes.length buf - len then invalid_arg "ExtUnix.single_pread" else unsafe_single_pread fd off buf ofs len (** [pread fd off buf ofs len] reads up to [len] bytes from file descriptor [fd] at offset [off] (from the start of the file) into the string [buf] at offset [ofs]. The file offset is not changed. [pread] repeats the read operation until all characters have been read or an error occurs. Raises an Unix.Unix_error exception if 0 characters could be read before an error occurs. Continues the read operation on EINTR. Returns the number of characters written in all other cases. *) external unsafe_pread: Unix.file_descr -> int -> Bytes.t -> int -> int -> int = "caml_extunix_pread" let pread fd off buf ofs len = if off < 0 || ofs < 0 || len < 0 || ofs > Bytes.length buf - len then invalid_arg "ExtUnix.pread" else unsafe_pread fd off buf ofs len (** [intr_pread fd off buf ofs len] reads up to [len] bytes from file descriptor [fd] at offset [off] (from the start of the file) into the string [buf] at offset [ofs]. The file offset is not changed. [intr_pread] repeats the read operation until all characters have been read or an error occurs. Raises an Unix.Unix_error exception if 0 characters could be read before an error occurs. Does NOT continue on EINTR. Returns the number of characters written in all other cases. *) external unsafe_intr_pread: Unix.file_descr -> int -> Bytes.t -> int -> int -> int = "caml_extunix_intr_pread" let intr_pread fd off buf ofs len = if off < 0 || ofs < 0 || len < 0 || ofs > Bytes.length buf - len then invalid_arg "ExtUnix.intr_pread" else unsafe_intr_pread fd off buf ofs len END HAVE PWRITE (** {3 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 (** {3 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 -> Bytes.t -> int -> int -> int = "caml_extunix_all_read" let all_read fd buf ofs len = if ofs < 0 || len < 0 || ofs > Bytes.length buf - len then invalid_arg "ExtUnix.all_read" else unsafe_all_read fd buf ofs len (** [single_read fd buf ifs len] reads up to [len] bytes from file descriptor [fd] into the string [buf] at offset [ofs]. [single_read] attempts to read only once. Returns the number of characters read or raises an Unix.Unix_error exception. *) external unsafe_single_read: Unix.file_descr -> Bytes.t -> int -> int -> int = "caml_extunix_single_read" let single_read fd buf ofs len = if ofs < 0 || len < 0 || ofs > Bytes.length buf - len then invalid_arg "ExtUnix.single_read" else unsafe_single_read fd buf ofs len (** [read fd buf ofs len] reads up to [len] bytes from file descriptor [fd] into the string [buf] at offset [ofs]. [read] repeats the read operation until all characters have been read or an error occurs. Raises an Unix.Unix_error exception if 0 characters could be read before an error occurs. Continues the read operation on EINTR. Returns the number of characters written in all other cases. *) external unsafe_read: Unix.file_descr -> Bytes.t -> int -> int -> int = "caml_extunix_read" let read fd buf ofs len = if ofs < 0 || len < 0 || ofs > Bytes.length buf - len then invalid_arg "ExtUnix.read" else unsafe_read fd buf ofs len (** [intr_read fd buf ofs len] reads up to [len] bytes from file descriptor [fd] into the string [buf] at offset [ofs]. [intr_read] repeats the read operation until all characters have been read or an error occurs. Raises an Unix.Unix_error exception if 0 characters could be read before an error occurs. Does NOT continue on EINTR. Returns the number of characters written in all other cases. *) external unsafe_intr_read: Unix.file_descr -> Bytes.t -> int -> int -> int = "caml_extunix_intr_read" let intr_read fd buf ofs len = if ofs < 0 || len < 0 || ofs > Bytes.length buf - len then invalid_arg "ExtUnix.intr_read" else unsafe_intr_read fd buf ofs len END HAVE WRITE (** {3 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.write" else unsafe_write fd buf ofs len (** [intr_write fd buf ofs len] writes up to [len] bytes from file descriptor [fd] into the string [buf] at offset [ofs]. [intr_write] repeats the write operation until all characters have been written or an error occurs. Raises an Unix.Unix_error exception if 0 characters could be written before an error occurs. Does NOT continue on EINTR. Returns the number of characters written in all other cases. *) external unsafe_intr_write: Unix.file_descr -> string -> int -> int -> int = "caml_extunix_intr_write" let intr_write fd buf ofs len = if ofs < 0 || len < 0 || ofs > String.length buf - len then invalid_arg "ExtUnix.intr_write" else unsafe_intr_write fd buf ofs len 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 -> Bytes.t -> int -> int -> int = "caml_extunix_all_pread64" let all_pread fd off buf ofs len = if off < Int64.zero then invalid_arg "ExtUnix.LargeFile.all_pread" else unsafe_all_pread fd off buf ofs len external unsafe_single_pread: Unix.file_descr -> int64 -> Bytes.t -> int -> int -> int = "caml_extunix_single_pread64" let single_pread fd off buf ofs len = if off < Int64.zero then invalid_arg "ExtUnix.LargeFile.single_pread" else unsafe_single_pread fd off buf ofs len external unsafe_pread: Unix.file_descr -> int64 -> Bytes.t -> int -> int -> int = "caml_extunix_pread64" let pread fd off buf ofs len = if off < Int64.zero then invalid_arg "ExtUnix.LargeFile.pread" else unsafe_pread fd off buf ofs len external unsafe_intr_pread: Unix.file_descr -> int64 -> Bytes.t -> int -> int -> int = "caml_extunix_intr_pread64" let intr_pread fd off buf ofs len = if off < Int64.zero then invalid_arg "ExtUnix.LargeFile.intr_pread" else unsafe_intr_pread fd off buf ofs len 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 -> ('a, 'b) carray -> int = "caml_extunixba_all_pread64" let all_pread fd off buf = if off < Int64.zero then invalid_arg "ExtUnix.LargeFile.all_pread" else unsafe_all_pread fd off buf external unsafe_single_pread: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_single_pread64" let single_pread fd off buf = if off < Int64.zero then invalid_arg "ExtUnix.LargeFile.single_pread" else unsafe_single_pread fd off buf external unsafe_pread: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_pread64" let pread fd off buf = if off < Int64.zero then invalid_arg "ExtUnix.LargeFile.pread" else unsafe_pread fd off buf external unsafe_intr_pread: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_intr_pread64" let intr_pread fd off buf = if off < Int64.zero then invalid_arg "ExtUnix.LargeFile.intr_pread" else unsafe_intr_pread fd off buf END HAVE PWRITE external unsafe_all_pwrite: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_all_pwrite64" let all_pwrite fd off buf = if off < Int64.zero then invalid_arg "ExtUnix.LargeFile.all_pwrite" else unsafe_all_pwrite fd off buf external unsafe_single_pwrite: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_single_pwrite64" let single_pwrite fd off buf = if off < Int64.zero then invalid_arg "ExtUnix.LargeFile.single_pwrite" else unsafe_single_pwrite fd off buf external unsafe_pwrite: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_pwrite64" let pwrite fd off buf = if off < Int64.zero then invalid_arg "ExtUnix.LargeFile.pwrite" else unsafe_pwrite fd off buf external unsafe_intr_pwrite: Unix.file_descr -> int64 -> ('a, 'b) carray -> int = "caml_extunixba_intr_pwrite64" let intr_pwrite fd off buf = if off < Int64.zero then invalid_arg "ExtUnix.LargeFile.intr_pwrite" else unsafe_intr_pwrite fd off buf END end (* module BA *) end (* module LargeFile *) HAVE MOUNT (** {3 mount system call} *) type mount_flag = | MS_RDONLY | MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_SYNCHRONOUS | MS_REMOUNT | MS_MANDLOCK | MS_DIRSYNC | MS_NOATIME | MS_NODIRATIME | MS_BIND | MS_MOVE | MS_REC | MS_SILENT | MS_POSIXACL | MS_UNBINDABLE | MS_PRIVATE | MS_SLAVE | MS_SHARED | MS_RELATIME | MS_KERNMOUNT | MS_I_VERSION | MS_STRICTATIME | MS_NOUSER external mount: source:string -> target:string -> fstype:string -> mount_flag list -> data:string -> unit = "caml_extunix_mount" type umount2_flag = | MNT_FORCE | MNT_DETACH | MNT_EXPIRE | UMOUNT_NOFOLLOW external umount2: string -> umount2_flag list -> unit = "caml_extunix_umount2" END HAVE CHROOT (** {3 chroot system call} *) external chroot: string -> unit = "caml_extunix_chroot" END (** {2 namespace} *) HAVE UNSHARE type clone_flag = | CLONE_FS | CLONE_FILES | CLONE_NEWNS | CLONE_SYSVSEM | CLONE_NEWUTS | CLONE_NEWIPC | CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNET external unshare: clone_flag list -> unit = "caml_extunix_unshare" END (** {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 GETTID (** @return thread id *) external gettid : unit -> int = "caml_extunix_gettid" 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. *) external setreuid : int -> int -> unit = "caml_extunix_setreuid" (** [setregid rgid egid] sets real and effective group IDs of the calling process. Supplying a value of -1 for either the real or effective group ID forces the system to leave that ID unchanged. *) external setregid : int -> int -> unit = "caml_extunix_setregid" 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. *) external setresuid: int -> int -> int -> unit = "caml_extunix_setresuid" (** [setresgid rgid egid sgid] sets real, effective and saved group IDs of the calling process. Supplying a value of -1 for either the real or effective group ID forces the system to leave that ID unchanged. *) external setresgid: int -> int -> int -> unit = "caml_extunix_setresgid" END HAVE TCPGRP external tcgetpgrp : Unix.file_descr -> int = "caml_extunix_tcgetpgrp" external tcsetpgrp : Unix.file_descr -> int -> unit = "caml_extunix_tcsetpgrp" END (** Exit process without running any [at_exit] hooks (implemented in Pervasives) *) external sys_exit : int -> 'a = "caml_sys_exit" HAVE SYSINFO (** NB all memory fields in this structure are the multiplies of [mem_unit] bytes *) type sysinfo = { uptime : int; (** Seconds since boot *) loads : (float * float * float); (** 1, 5, and 15 minute load averages *) totalram : int; (** Total usable main memory size *) freeram : int; (** Available memory size *) sharedram : int; (** Amount of shared memory *) bufferram : int; (** Memory used by buffers *) totalswap : int; (** Total swap space size *) freeswap : int; (** swap space still available *) procs : int; (** Number of current processes *) totalhigh : int; (** Total high memory size *) freehigh : int; (** Available high memory size *) mem_unit : int; (** Memory unit size in bytes *) } (** @return overall system statistics *) external sysinfo : unit -> sysinfo = "caml_extunix_sysinfo" (** @return seconds since boot *) external uptime : unit -> int = "caml_extunix_uptime" END (** {2 Network} *) 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 SOCKOPT type socket_int_option_ = | TCP_KEEPCNT_ | TCP_KEEPIDLE_ | TCP_KEEPINTVL_ | SO_REUSEPORT_ | SO_ATTACH_BPF_ | SO_ATTACH_REUSEPORT_EBPF_ | SO_DETACH_FILTER_ | SO_DETACH_BPF_ | SO_LOCK_FILTER_ let string_of_socket_int_option_ = function | TCP_KEEPCNT_ -> "TCP_KEEPCNT" | TCP_KEEPIDLE_ -> "TCP_KEEPIDLE" | TCP_KEEPINTVL_ -> "TCP_KEEPINTVL" | SO_REUSEPORT_ -> "SO_REUSEPORT" | SO_ATTACH_BPF_ -> "SO_ATTACH_BPF" | SO_ATTACH_REUSEPORT_EBPF_ -> "SO_ATTACH_REUSEPORT_EBPF" | SO_DETACH_FILTER_ -> "SO_DETACH_FILTER" | SO_DETACH_BPF_ -> "SO_DETACH_BPF" | SO_LOCK_FILTER_ -> "SO_LOCK_FILTER" external setsockopt_int : Unix.file_descr -> socket_int_option_ -> int -> unit = "caml_extunix_setsockopt_int" external getsockopt_int : Unix.file_descr -> socket_int_option_ -> int = "caml_extunix_getsockopt_int" external have_sockopt_int : socket_int_option_ -> bool = "caml_extunix_have_sockopt" (** Extra socket options with integer value not covered in {!Unix} module. NB Not all options available on all platforms, use {!have_sockopt} to check at runtime (even when function is defined in [Specific] module) *) type socket_int_option = | TCP_KEEPCNT (** The maximum number of keepalive probes TCP should send before dropping the connection *) | TCP_KEEPIDLE (** The time (in seconds) the connection needs to remain idle before TCP starts sending keepalive probes, if the socket option SO_KEEPALIVE has been set on this socket *) | TCP_KEEPINTVL (** The time (in seconds) between individual keepalive probes *) | SO_ATTACH_BPF (** file descriptor returned by the bpf(2), with program of type [BPF_PROG_TYPE_SOCKET_FILTER] *) | SO_ATTACH_REUSEPORT_EBPF (** same as for SO_ATTACH_BPF *) type socket_bool_option = | SO_REUSEPORT (** Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. *) | SO_LOCK_FILTER (** Prevent changing the filters associated with the socket *) type socket_unit_option = | SO_DETACH_FILTER (** Remove classic or extended BPF program attached to a socket *) | SO_DETACH_BPF (** same *) let make_socket_int_option = function | TCP_KEEPCNT -> TCP_KEEPCNT_ | TCP_KEEPIDLE -> TCP_KEEPIDLE_ | TCP_KEEPINTVL -> TCP_KEEPINTVL_ | SO_ATTACH_BPF -> SO_ATTACH_BPF_ | SO_ATTACH_REUSEPORT_EBPF -> SO_ATTACH_REUSEPORT_EBPF_ let make_socket_bool_option = function | SO_REUSEPORT -> SO_REUSEPORT_ | SO_LOCK_FILTER -> SO_LOCK_FILTER_ let make_socket_unit_option = function | SO_DETACH_FILTER -> SO_DETACH_FILTER_ | SO_DETACH_BPF -> SO_DETACH_BPF_ let have_sockopt_unit x = have_sockopt_int (make_socket_unit_option x) let have_sockopt_bool x = have_sockopt_int (make_socket_bool_option x) let have_sockopt_int x = have_sockopt_int (make_socket_int_option x) (** obsolete, compatibility *) let have_sockopt = have_sockopt_int let setsockopt_int sock opt v = try setsockopt_int sock opt v with Not_found -> raise (Not_available ("setsockopt " ^ string_of_socket_int_option_ opt)) let getsockopt_int sock opt = try getsockopt_int sock opt with Not_found -> raise (Not_available ("getsockopt " ^ string_of_socket_int_option_ opt)) (** Set the option without value on the given socket *) let setsockopt_unit sock opt = setsockopt_int sock (make_socket_unit_option opt) 0 (** Set a boolean-valued option in the given socket *) let setsockopt sock opt v = setsockopt_int sock (make_socket_bool_option opt) (if v then 1 else 0) (** Get the current value for the boolean-valued option in the given socket *) let getsockopt sock opt = 0 <> getsockopt_int sock (make_socket_bool_option opt) (** Set an integer-valued option in the given socket *) let setsockopt_int sock opt v = setsockopt_int sock (make_socket_int_option opt) v (** Get the current value for the integer-valued option in the given socket *) let getsockopt_int sock opt = getsockopt_int sock (make_socket_int_option opt) END HAVE POLL module Poll : sig type t = private int (** [is_set flags flag] @return whether [flag] is set in [flags] *) val is_set : t -> t -> bool (** [is_inter flags1 flags2] @return whether [flags1] and [flags2] have non-empty intersection *) val is_inter : t -> t -> bool (** @return intersection of two flags (AND) *) val inter : t -> t -> t (** @return union of two flags (OR) *) val union : t -> t -> t (** @return union of several flags (OR) *) val join : t list -> t (** equivalent to [union] *) val (+) : t -> t -> t val pollin : t val pollpri : t val pollout : t val pollerr : t val pollhup : t val pollnval : t (** may not be present on all platforms (=0) *) val pollrdhup : t (** no poll flags (=0) *) val none : t end = struct type t = int external poll_constants : unit -> (int*int*int*int*int*int*int) = "caml_extunix_poll_constants" let (pollin,pollpri,pollout,pollerr,pollhup,pollnval,pollrdhup) = try poll_constants () with Not_available _ -> (0,0,0,0,0,0,0) let none = 0 let is_set xs x = xs land x = x let inter x y = x land y let is_inter x y = x land y <> 0 let union a b = a lor b let (+) = union let join = List.fold_left (lor) 0 end external poll : (Unix.file_descr * Poll.t) array -> int -> float -> (Unix.file_descr * Poll.t) list = "caml_extunix_poll" let poll a ?(n=Array.length a) t = poll a n t END 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. *) 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 -> Bigarray.int8_unsigned_elt carray8 = "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 TIMEZONE (** @return timezone (seconds West of UTC) and daylight (whether there is time during the year when daylight saving time applies in this timezone) *) external timezone : unit -> int * bool = "caml_extunix_timezone" 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 {b NB} native function [backtrace] may fail to unwind the OCaml callstack correctly or even segfault. Do not use lightly. See {{:https://forge.ocamlcore.org/tracker/index.php?func=detail&aid=1290}bug #1290}, {{:http://caml.inria.fr/mantis/view.php?id=5334}PR#5344} and {{:http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=637360}Debian bug #637380} for details. *) external backtrace : unit -> string array = "caml_extunix_backtrace" 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 MCHECK external mtrace : unit -> unit = "caml_extunix_mtrace" external muntrace : unit -> unit = "caml_extunix_muntrace" 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 s = prefix ^ "XXXXXX" ^ suffix in let fd = internal_mkstemps s (String.length suffix) 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 s = prefix ^ "XXXXXX" ^ suffix in let fd = internal_mkostemps s (String.length suffix) 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 buf off v] stores the integer [v] as type [X] in the buffer [buf] starting at offset [off]. Bounds checking is not performed. Use with caution and only when the program logic guarantees that the access is within bounds. Note: The 31bit functions store an ocaml int as 32bit integer. On 32bit platforms ocaml integers are 31bit signed and will be sign extended to 32bit first. Use with care. Note: The same applies to 63bit functions. *) external unsafe_set_uint8 : Bytes.t -> int -> int -> unit = "caml_extunix_set_8" "noalloc" external unsafe_set_int8 : Bytes.t -> int -> int -> unit = "caml_extunix_set_8" "noalloc" external unsafe_set_uint16 : Bytes.t -> int -> int -> unit = "caml_extunix_set_b16" "noalloc" external unsafe_set_int16 : Bytes.t -> int -> int -> unit = "caml_extunix_set_b16" "noalloc" external unsafe_set_uint31 : Bytes.t -> int -> int -> unit = "caml_extunix_set_b31" "noalloc" external unsafe_set_int31 : Bytes.t -> int -> int -> unit = "caml_extunix_set_b31" "noalloc" external unsafe_set_int32 : Bytes.t -> int -> int32 -> unit = "caml_extunix_set_b32" "noalloc" external unsafe_set_uint63 : Bytes.t -> int -> int -> unit = "caml_extunix_set_b63" "noalloc" external unsafe_set_int63 : Bytes.t -> int -> int -> unit = "caml_extunix_set_b63" "noalloc" external unsafe_set_int64 : Bytes.t -> int -> int64 -> unit = "caml_extunix_set_b64" "noalloc" (** [set_X buf off v] same as [unsafe_set_X] but with bounds checking. *) let set_uint8 str off v = if off < 0 || off >= Bytes.length str then raise (Invalid_argument "index out of bounds"); unsafe_set_uint8 str off v let set_int8 str off v = if off < 0 || off >= Bytes.length str then raise (Invalid_argument "index out of bounds"); unsafe_set_int8 str off v let set_uint16 str off v = if off < 0 || off > Bytes.length str - 2 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint16 str off v let set_int16 str off v = if off < 0 || off > Bytes.length str - 2 then raise (Invalid_argument "index out of bounds"); unsafe_set_int16 str off v let set_uint31 str off v = if off < 0 || off > Bytes.length str - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint31 str off v let set_int31 str off v = if off < 0 || off > Bytes.length str - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_int31 str off v let set_int32 str off v = if off < 0 || off > Bytes.length str - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_int32 str off v let set_uint63 str off v = if off < 0 || off > Bytes.length str - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint63 str off v let set_int63 str off v = if off < 0 || off > Bytes.length str - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int63 str off v let set_int64 str off v = if off < 0 || off > Bytes.length str - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int64 str off v END 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 buf off v] stores the integer [v] as type [X] in the buffer [buf] starting at offset [off]. Bounds checking is not performed. Use with caution and only when the program logic guarantees that the access is within bounds. Note: The 31bit functions store an ocaml int as 32bit integer. On 32bit platforms ocaml integers are 31bit signed and will be sign extended to 32bit first. Use with care. *) external unsafe_set_uint8 : Bytes.t -> int -> int -> unit = "caml_extunix_set_8" "noalloc" external unsafe_set_int8 : Bytes.t -> int -> int -> unit = "caml_extunix_set_8" "noalloc" external unsafe_set_uint16 : Bytes.t -> int -> int -> unit = "caml_extunix_set_l16" "noalloc" external unsafe_set_int16 : Bytes.t -> int -> int -> unit = "caml_extunix_set_l16" "noalloc" external unsafe_set_uint31 : Bytes.t -> int -> int -> unit = "caml_extunix_set_l31" "noalloc" external unsafe_set_int31 : Bytes.t -> int -> int -> unit = "caml_extunix_set_l31" "noalloc" external unsafe_set_int32 : Bytes.t -> int -> int32 -> unit = "caml_extunix_set_l32" "noalloc" external unsafe_set_uint63 : Bytes.t -> int -> int -> unit = "caml_extunix_set_l63" "noalloc" external unsafe_set_int63 : Bytes.t -> int -> int -> unit = "caml_extunix_set_l63" "noalloc" external unsafe_set_int64 : Bytes.t -> int -> int64 -> unit = "caml_extunix_set_l64" "noalloc" (** [set_X buf off v] same as [unsafe_set_X] but with bounds checking. *) let set_uint8 str off v = if off < 0 || off >= Bytes.length str then raise (Invalid_argument "index out of bounds"); unsafe_set_uint8 str off v let set_int8 str off v = if off < 0 || off >= Bytes.length str then raise (Invalid_argument "index out of bounds"); unsafe_set_int8 str off v let set_uint16 str off v = if off < 0 || off > Bytes.length str - 2 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint16 str off v let set_int16 str off v = if off < 0 || off > Bytes.length str - 2 then raise (Invalid_argument "index out of bounds"); unsafe_set_int16 str off v let set_uint31 str off v = if off < 0 || off > Bytes.length str - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint31 str off v let set_int31 str off v = if off < 0 || off > Bytes.length str - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_int31 str off v let set_int32 str off v = if off < 0 || off > Bytes.length str - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_int32 str off v let set_uint63 str off v = if off < 0 || off > Bytes.length str - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint63 str off v let set_int63 str off v = if off < 0 || off > Bytes.length str - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int63 str off v let set_int64 str off v = if off < 0 || off > Bytes.length str - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int64 str off v END 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 buf off v] stores the integer [v] as type [X] in the buffer [buf] starting at offset [off]. Bounds checking is not performed. Use with caution and only when the program logic guarantees that the access is within bounds. Note: The 31bit functions store an ocaml int as 32bit integer. On 32bit platforms ocaml integers are 31bit signed and will be sign extended to 32bit first. Use with care. Note: The same applies to 63bit functions. *) external unsafe_set_uint8 : Bytes.t -> int -> int -> unit = "caml_extunix_set_8" "noalloc" external unsafe_set_int8 : Bytes.t -> int -> int -> unit = "caml_extunix_set_8" "noalloc" external unsafe_set_uint16 : Bytes.t -> int -> int -> unit = "caml_extunix_set_h16" "noalloc" external unsafe_set_int16 : Bytes.t -> int -> int -> unit = "caml_extunix_set_h16" "noalloc" external unsafe_set_uint31 : Bytes.t -> int -> int -> unit = "caml_extunix_set_h31" "noalloc" external unsafe_set_int31 : Bytes.t -> int -> int -> unit = "caml_extunix_set_h31" "noalloc" external unsafe_set_int32 : Bytes.t -> int -> int32 -> unit = "caml_extunix_set_h32" "noalloc" external unsafe_set_uint63 : Bytes.t -> int -> int -> unit = "caml_extunix_set_h63" "noalloc" external unsafe_set_int63 : Bytes.t -> int -> int -> unit = "caml_extunix_set_h63" "noalloc" external unsafe_set_int64 : Bytes.t -> int -> int64 -> unit = "caml_extunix_set_h64" "noalloc" (** [set_X buf off v] same as [unsafe_set_X] but with bounds checking. *) let set_uint8 str off v = if off < 0 || off >= Bytes.length str then raise (Invalid_argument "index out of bounds"); unsafe_set_uint8 str off v let set_int8 str off v = if off < 0 || off >= Bytes.length str then raise (Invalid_argument "index out of bounds"); unsafe_set_int8 str off v let set_uint16 str off v = if off < 0 || off > Bytes.length str - 2 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint16 str off v let set_int16 str off v = if off < 0 || off > Bytes.length str - 2 then raise (Invalid_argument "index out of bounds"); unsafe_set_int16 str off v let set_uint31 str off v = if off < 0 || off > Bytes.length str - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint31 str off v let set_int31 str off v = if off < 0 || off > Bytes.length str - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_int31 str off v let set_int32 str off v = if off < 0 || off > Bytes.length str - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_int32 str off v let set_uint63 str off v = if off < 0 || off > Bytes.length str - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint63 str off v let set_int63 str off v = if off < 0 || off > Bytes.length str - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int63 str off v let set_int64 str off v = if off < 0 || off > Bytes.length str - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int64 str off v end HAVE READ_CREDENTIALS (** {2 read_credentials } {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 and a non-empty message. *) external sendmsg: Unix.file_descr -> ?sendfd:Unix.file_descr -> string -> unit = "caml_extunix_sendmsg" (** Recieve a message and possibly a file descriptor from a socket. *) external recvmsg_fd: Unix.file_descr -> Unix.file_descr option * string = "caml_extunix_recvmsg" (** [sendfd sock fd] sends a file descriptor [fd] through a UNIX domain socket [sock]. This will send a sentinel message at the same time, otherwise {!sendmsg} will not pass the file descriptor. *) let sendfd ~sock ~fd = sendmsg sock ~sendfd:fd "\001" (** Receive a file descriptor sent through a UNIX domain socket, ignoring the message. *) let recvfd fd = match recvmsg_fd fd with | (Some recvfd, _) -> recvfd | _ -> raise (Unix.Unix_error (Unix.EINVAL, "recvfd", "no descriptor")) (** Receive a message sent through a UNIX domain socket. Raises Recvfd(fd, msg) if a file descriptor is recieved. *) exception Recvfd of Unix.file_descr * string let recvmsg fd = match recvmsg_fd fd with | (None, msg) -> msg | (Some fd, msg) -> raise (Recvfd (fd, msg)) (** Receive a message sent through a UNIX domain socket. Closes and ignores file descriptors. *) let recvmsg_nofd fd = match recvmsg_fd fd with | (Some fd, msg) -> Unix.close fd; msg | (None, msg) -> msg END HAVE SYSCONF (** {2 sysconf} {b Author:} Roman Vorobets *) (** name of the variable *) type sysconf_name = | ARG_MAX (** The maximum length of the arguments to the exec(3) family of functions. *) | CHILD_MAX (** The max number of simultaneous processes per user ID. *) | HOST_NAME_MAX (** Max length of a hostname, not including the terminating null byte, as returned by gethostname(2). *) | LOGIN_NAME_MAX (** Maximum length of a login name, including the terminating null byte. *) | CLK_TCK (** The number of clock ticks per second. *) | OPEN_MAX (** The maximum number of files that a process can have open at any time. *) | PAGESIZE (** Size of a page in bytes. *) | RE_DUP_MAX (** The number of repeated occurrences of a BRE permitted by regexec(3) and regcomp(3). *) | STREAM_MAX (** The maximum number of streams that a process can have open at any time. *) | SYMLOOP_MAX (** The maximum number of symbolic links seen in a pathname before resolution returns ELOOP. *) | TTY_NAME_MAX (** The maximum length of terminal device name, including the terminating null byte. *) | TZNAME_MAX (** The maximum number of bytes in a timezone name. *) | POSIX_VERSION (** Indicates the year and month the POSIX.1 standard was approved in the format YYYYMML; the value 199009L indicates the Sept. 1990 revision. *) | LINE_MAX (** The maximum length of a utility's input line, either from standard input or from a file. This includes space for a trailing newline. *) | POSIX2_VERSION (** Indicates the version of the POSIX.2 standard in the format of YYYYMML. *) | PHYS_PAGES (** The number of pages of physical memory. Note that it is possible for the product of this value and the value of [PAGE_SIZE] to overflow. Non-standard, may be not available *) | AVPHYS_PAGES (** The number of currently available pages of physical memory. Non-standard, may be not available *) | NPROCESSORS_CONF (** The number of processors configured. Non-standard, may be not available *) | NPROCESSORS_ONLN (** The number of processors currently online (available). Non-standard, may be not available *) external sysconf: sysconf_name -> int64 = "caml_extunix_sysconf" (** get configuration information at runtime, may raise [Not_available] for non-standard options (see above) even in [Specific] module *) let sysconf sc = try sysconf sc with Not_found -> raise (Not_available "sysconf") END HAVE SPLICE OR TEE OR VMSPLICE (** {2 splice} {b Author:} Pierre Chambart *) (** splice functions flags *) type splice_flag = | SPLICE_F_MOVE (** Attempt to move pages instead of copying. Only a hint to the kernel *) | SPLICE_F_NONBLOCK (** Do not block on I/O *) | SPLICE_F_MORE (** Announce that more data will be coming. Hint used by sockets *) | SPLICE_F_GIFT (** The user pages are a gift to the kernel. The application may not modify this memory ever, or page cache and on-disk data may differ. Gifting pages to the kernel means that a subsequent splice(2) SPLICE_F_MOVE can successfully move the pages; if this flag is not specified, then a subsequent splice(2) SPLICE_F_MOVE must copy the pages. Data must also be properly page aligned, both in memory and length. Only use for [vmsplice]. *) END HAVE SPLICE (** [splice fd_in off_in fd_out off_out len flags] moves data between two file descriptors without copying between kernel address space and user address space. It transfers up to [len] bytes of data from the file descriptor [fd_in] to the file descriptor [fd_out], where one of the descriptors must refer to a pipe. If [fd_in] refers to a pipe, then [off_in] must be [None]. If [fd_in] does not refer to a pipe and [off_in] is [None], then bytes are read from [fd_in] starting from the current file offset, and the current file offset is adjusted appropriately. If [fd_in] does not refer to a pipe and [off_in] is [Some n], then [n] mspecifies the starting offset from which bytes will be read from [fd_in]; in this case, the current file offset of [fd_in] is not changed. Analogous statements apply for [fd_out] and [off_out]. @return the number of bytes spliced to or from the pipe. A return value of 0 means that there was no data to transfer, and it would not make sense to block, because there are no writers connected to the write end of the pipe referred to by fd_in. *) external splice : Unix.file_descr -> int option -> Unix.file_descr -> int option -> int -> splice_flag list -> int = "caml_extunix_splice_bytecode" "caml_extunix_splice" END HAVE TEE (** [tee fd_in fd_out len flags] duplicates up to [len] bytes of data from the pipe [fd_in] to the pipe [fd_out]. It does not consume the data that is duplicated from [fd_in]; therefore, that data can be copied by a subsequent splice. @return the number of bytes that were duplicated between the input and output. A return value of 0 means that there was no data to transfer, and it would not make sense to block, because there are no writers connected to the write end of the pipe referred to by fd_in. *) external tee : Unix.file_descr -> Unix.file_descr -> int -> splice_flag list -> int = "caml_extunix_tee" 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 -> ('a, 'b) carray -> int = "caml_extunixba_all_pread" let all_pread fd off buf = if off < 0 then invalid_arg "ExtUnix.all_pread" else unsafe_all_pread fd off buf (** [single_pread fd off buf] reads up to [size of buf] bytes from file descriptor [fd] at offset [off] (from the start of the file) into the buffer [buf]. The file offset is not changed. [single_pread] attempts to read only once. Returns the number of characters read or raises an Unix.Unix_error exception. Unlike the string variant of the same name there is no limit on the number of characters read. *) external unsafe_single_pread: Unix.file_descr -> int -> ('a, 'b) carray -> int = "caml_extunixba_single_pread" let single_pread fd off buf = if off < 0 then invalid_arg "ExtUnix.single_pread" else unsafe_single_pread fd off buf (** [pread fd off buf] reads up to [size of buf] bytes from file descriptor [fd] at offset [off] (from the start of the file) into the buffer [buf]. The file offset is not changed. [pread] repeats the read operation until all characters have been read or an error occurs. Raises an Unix.Unix_error exception if 0 characters could be read before an error occurs. Continues the read operation on EINTR. Returns the number of characters written in all other cases. *) external unsafe_pread: Unix.file_descr -> int -> ('a, 'b) carray -> int = "caml_extunixba_pread" let pread fd off buf = if off < 0 then invalid_arg "ExtUnix.pread" else unsafe_pread fd off buf (** [intr_pread fd off buf] reads up to [size of buf] bytes from file descriptor [fd] at offset [off] (from the start of the file) into the buffer [buf]. The file offset is not changed. [intr_pread] repeats the read operation until all characters have been read or an error occurs. Raises an Unix.Unix_error exception if 0 characters could be read before an error occurs. Does NOT continue on EINTR. Returns the number of characters written in all other cases. *) external unsafe_intr_pread: Unix.file_descr -> int -> ('a, 'b) carray -> int = "caml_extunixba_intr_pread" let intr_pread fd off buf = if off < 0 then invalid_arg "ExtUnix.intr_pread" else unsafe_intr_pread fd off buf 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 -> ('a, 'b) carray -> int = "caml_extunixba_all_pwrite" let all_pwrite fd off buf = if off < 0 then invalid_arg "ExtUnix.all_pwrite" else unsafe_all_pwrite fd off buf (** [single_pwrite fd off buf] writes up to [size of buf] bytes from file descriptor [fd] at offset [off] (from the start of the file) into the buffer [buf]. The file offset is not changed. [single_pwrite] attempts to write only once. Returns the number of characters written or raises an Unix.Unix_error exception. Unlike the string variant of the same name there is no limit on the number of characters written. *) external unsafe_single_pwrite: Unix.file_descr -> int -> ('a, 'b) carray -> int = "caml_extunixba_single_pwrite" let single_pwrite fd off buf = if off < 0 then invalid_arg "ExtUnix.single_pwrite" else unsafe_single_pwrite fd off buf (** [pwrite fd off buf] writes up to [size of buf] bytes from file descriptor [fd] at offset [off] (from the start of the file) into the buffer [buf]. The file offset is not changed. [pwrite] repeats the write operation until all characters have been written or an error occurs. Raises an Unix.Unix_error exception if 0 characters could be written before an error occurs. Continues the write operation on EINTR. Returns the number of characters written in all other cases. *) external unsafe_pwrite: Unix.file_descr -> int -> ('a, 'b) carray -> int = "caml_extunixba_pwrite" let pwrite fd off buf = if off < 0 then invalid_arg "ExtUnix.pwrite" else unsafe_pwrite fd off buf (** [intr_pwrite fd off buf] writes up to [size of buf] bytes from file descriptor [fd] at offset [off] (from the start of the file) into the buffer [buf]. The file offset is not changed. [intr_pwrite] repeats the write operation until all characters have been written or an error occurs. Raises an Unix.Unix_error exception if 0 characters could be written before an error occurs. Does NOT continue on EINTR. Returns the number of characters written in all other cases. *) external unsafe_intr_pwrite: Unix.file_descr -> int -> ('a, 'b) carray -> int = "caml_extunixba_intr_pwrite" let intr_pwrite fd off buf = if off < 0 then invalid_arg "ExtUnix.intr_pwrite" else unsafe_intr_pwrite fd off buf 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 -> ('a, 'b) carray -> int = "caml_extunixba_all_read" (** [single_read fd buf] reads up to [size of buf] bytes from file descriptor [fd] into the buffer [buf]. [single_read] attempts to read only once. Returns the number of characters read or raises an Unix.Unix_error exception. Unlike the string variant of the same name there is no limit on the number of characters read. *) external single_read: Unix.file_descr -> ('a, 'b) carray -> int = "caml_extunixba_single_read" (** [read fd buf] reads up to [size of buf] bytes from file descriptor [fd] into the buffer [buf]. [read] repeats the read operation until all characters have been read or an error occurs. Raises an Unix.Unix_error exception if 0 characters could be read before an error occurs. Continues the read operation on EINTR. Returns the number of characters written in all other cases. *) external read: Unix.file_descr -> ('a, 'b) carray -> int = "caml_extunixba_read" (** [intr_read fd buf] reads up to [size of buf] bytes from file descriptor [fd] into the buffer [buf]. [intr_read] repeats the read operation until all characters have been read or an error occurs. Raises an Unix.Unix_error exception if 0 characters could be read before an error occurs. Does NOT continue on EINTR. Returns the number of characters written in all other cases. *) external intr_read: Unix.file_descr -> ('a, 'b) carray -> int = "caml_extunixba_intr_read" 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 -> ('a, 'b) carray -> int = "caml_extunixba_all_write" (** [single_write fd buf] writes up to [size of buf] bytes from file descriptor [fd] into the buffer [buf]. [single_write] attempts to write only once. Returns the number of characters written or raises an Unix.Unix_error exception. Unlike the string variant of the same name there is no limit on the number of characters written. *) external single_write: Unix.file_descr -> ('a, 'b) carray -> int = "caml_extunixba_single_write" (** [write fd buf] writes up to [size of buf] bytes from file descriptor [fd] into the buffer [buf]. [write] repeats the write operation until all characters have been written or an error occurs. Raises an Unix.Unix_error exception if 0 characters could be written before an error occurs. Continues the write operation on EINTR. Returns the number of characters written in all other cases. *) external write: Unix.file_descr -> ('a, 'b) carray -> int = "caml_extunixba_write" (** [intr_write fd buf] writes up to [size of buf] bytes from file descriptor [fd] into the buffer [buf]. [intr_write] repeats the write operation until all characters have been written or an error occurs. Raises an Unix.Unix_error exception if 0 characters could be written before an error occurs. Does NOT continue on EINTR. Returns the number of characters written in all other cases. *) external intr_write: Unix.file_descr -> ('a, 'b) carray -> int = "caml_extunixba_intr_write" 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 : 'a carray8 -> int -> int = "caml_extunixba_get_u8" "noalloc" external unsafe_get_int8 : 'a carray8 -> int -> int = "caml_extunixba_get_s8" "noalloc" external unsafe_get_uint16 : 'a carray8 -> int -> int = "caml_extunixba_get_bu16" "noalloc" external unsafe_get_int16 : 'a carray8 -> int -> int = "caml_extunixba_get_bs16" "noalloc" external unsafe_get_uint31 : 'a carray8 -> int -> int = "caml_extunixba_get_bu31" "noalloc" external unsafe_get_int31 : 'a carray8 -> int -> int = "caml_extunixba_get_bs31" "noalloc" external unsafe_get_int32 : 'a carray8 -> int -> int32 = "caml_extunixba_get_bs32" external unsafe_get_uint63 : 'a carray8 -> int -> int = "caml_extunixba_get_bu63" "noalloc" external unsafe_get_int63 : 'a carray8 -> int -> int = "caml_extunixba_get_bs63" "noalloc" external unsafe_get_int64 : 'a carray8 -> int -> int64 = "caml_extunixba_get_bs64" (** [get_X buf off] same as [unsafe_get_X] but with bounds checking. *) let get_uint8 buf off = if off < 0 || off >= Bigarray.Array1.dim buf then raise (Invalid_argument "index out of bounds"); unsafe_get_uint8 buf off let get_int8 buf off = if off < 0 || off >= Bigarray.Array1.dim buf then raise (Invalid_argument "index out of bounds"); unsafe_get_int8 buf off let get_uint16 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 2 then raise (Invalid_argument "index out of bounds"); unsafe_get_uint16 buf off let get_int16 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 2 then raise (Invalid_argument "index out of bounds"); unsafe_get_int16 buf off let get_uint31 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_get_uint31 buf off let get_int31 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_get_int31 buf off let get_int32 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_get_int32 buf off let get_uint63 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_get_uint63 buf off let get_int63 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_get_int63 buf off let get_int64 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_get_int64 buf off (** [unsafe_set_X buf off v] stores the integer [v] as type [X] in a buffer [buf] starting at offset [off]. Bounds checking is not performed. Use with caution and only when the program logic guarantees that the access is within bounds. Note: The 31bit functions store an ocaml int as 32bit integer. On 32bit platforms ocaml integers are 31bit signed and will be sign extended to 32bit first. Use with care. Note: The same applies to 63bit function. *) external unsafe_set_uint8 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_8" "noalloc" external unsafe_set_int8 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_8" "noalloc" external unsafe_set_uint16 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_b16" "noalloc" external unsafe_set_int16 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_b16" "noalloc" external unsafe_set_uint31 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_b31" "noalloc" external unsafe_set_int31 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_b31" "noalloc" external unsafe_set_int32 : 'a carray8 -> int -> int32 -> unit = "caml_extunixba_set_b32" "noalloc" external unsafe_set_uint63 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_b63" "noalloc" external unsafe_set_int63 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_b63" "noalloc" external unsafe_set_int64 : 'a carray8 -> int -> int64 -> unit = "caml_extunixba_set_b64" "noalloc" (** [set_X buf off v] same as [unsafe_set_X] but with bounds checking. *) let set_uint8 buf off v = if off < 0 || off >= Bigarray.Array1.dim buf then raise (Invalid_argument "index out of bounds"); unsafe_set_uint8 buf off v let set_int8 buf off v = if off < 0 || off >= Bigarray.Array1.dim buf then raise (Invalid_argument "index out of bounds"); unsafe_set_int8 buf off v let set_uint16 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 2 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint16 buf off v let set_int16 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 2 then raise (Invalid_argument "index out of bounds"); unsafe_set_int16 buf off v let set_uint31 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint31 buf off v let set_int31 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_int31 buf off v let set_int32 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_int32 buf off v let set_uint63 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint63 buf off v let set_int63 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int63 buf off v let set_int64 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int64 buf off v END end (* module BigEndian *) (** {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 : 'a carray8 -> int -> int = "caml_extunixba_get_u8" "noalloc" external unsafe_get_int8 : 'a carray8 -> int -> int = "caml_extunixba_get_s8" "noalloc" external unsafe_get_uint16 : 'a carray8 -> int -> int = "caml_extunixba_get_lu16" "noalloc" external unsafe_get_int16 : 'a carray8 -> int -> int = "caml_extunixba_get_ls16" "noalloc" external unsafe_get_uint31 : 'a carray8 -> int -> int = "caml_extunixba_get_lu31" "noalloc" external unsafe_get_int31 : 'a carray8 -> int -> int = "caml_extunixba_get_ls31" "noalloc" external unsafe_get_int32 : 'a carray8 -> int -> int32 = "caml_extunixba_get_ls32" external unsafe_get_uint63 : 'a carray8 -> int -> int = "caml_extunixba_get_lu63" "noalloc" external unsafe_get_int63 : 'a carray8 -> int -> int = "caml_extunixba_get_ls63" "noalloc" external unsafe_get_int64 : 'a carray8 -> int -> int64 = "caml_extunixba_get_ls64" (** [get_X buf off] same as [unsafe_get_X] but with bounds checking. *) let get_uint8 buf off = if off < 0 || off >= Bigarray.Array1.dim buf then raise (Invalid_argument "index out of bounds"); unsafe_get_uint8 buf off let get_int8 buf off = if off < 0 || off >= Bigarray.Array1.dim buf then raise (Invalid_argument "index out of bounds"); unsafe_get_int8 buf off let get_uint16 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 2 then raise (Invalid_argument "index out of bounds"); unsafe_get_uint16 buf off let get_int16 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 2 then raise (Invalid_argument "index out of bounds"); unsafe_get_int16 buf off let get_uint31 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_get_uint31 buf off let get_int31 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_get_int31 buf off let get_int32 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_get_int32 buf off let get_uint63 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_get_uint63 buf off let get_int63 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_get_int63 buf off let get_int64 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_get_int64 buf off (** [unsafe_set_X buf off v] stores the integer [v] as type [X] in a buffer [buf] starting at offset [off]. Bounds checking is not performed. Use with caution and only when the program logic guarantees that the access is within bounds. Note: The 31bit functions store an ocaml int as 32bit integer. On 32bit platforms ocaml integers are 31bit signed and will be sign extended to 32bit first. Use with care. Note: The same applies to 63bit functions. *) external unsafe_set_uint8 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_8" "noalloc" external unsafe_set_int8 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_8" "noalloc" external unsafe_set_uint16 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_l16" "noalloc" external unsafe_set_int16 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_l16" "noalloc" external unsafe_set_uint31 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_l31" "noalloc" external unsafe_set_int31 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_l31" "noalloc" external unsafe_set_int32 : 'a carray8 -> int -> int32 -> unit = "caml_extunixba_set_l32" "noalloc" external unsafe_set_uint63 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_l63" "noalloc" external unsafe_set_int63 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_l63" "noalloc" external unsafe_set_int64 : 'a carray8 -> int -> int64 -> unit = "caml_extunixba_set_l64" "noalloc" (** [set_X buf off v] same as [unsafe_set_X] but with bounds checking. *) let set_uint8 buf off v = if off < 0 || off >= Bigarray.Array1.dim buf then raise (Invalid_argument "index out of bounds"); unsafe_set_uint8 buf off v let set_int8 buf off v = if off < 0 || off >= Bigarray.Array1.dim buf then raise (Invalid_argument "index out of bounds"); unsafe_set_int8 buf off v let set_uint16 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 2 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint16 buf off v let set_int16 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 2 then raise (Invalid_argument "index out of bounds"); unsafe_set_int16 buf off v let set_uint31 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint31 buf off v let set_int31 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_int31 buf off v let set_int32 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_int32 buf off v let set_uint63 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint63 buf off v let set_int63 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int63 buf off v let set_int64 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int64 buf off v END end (* module LittleEndian *) (** {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 : 'a carray8 -> int -> int = "caml_extunixba_get_u8" "noalloc" external unsafe_get_int8 : 'a carray8 -> int -> int = "caml_extunixba_get_s8" "noalloc" external unsafe_get_uint16 : 'a carray8 -> int -> int = "caml_extunixba_get_hu16" "noalloc" external unsafe_get_int16 : 'a carray8 -> int -> int = "caml_extunixba_get_hs16" "noalloc" external unsafe_get_uint31 : 'a carray8 -> int -> int = "caml_extunixba_get_hu31" "noalloc" external unsafe_get_int31 : 'a carray8 -> int -> int = "caml_extunixba_get_hs31" "noalloc" external unsafe_get_int32 : 'a carray8 -> int -> int32 = "caml_extunixba_get_hs32" external unsafe_get_uint63 : 'a carray8 -> int -> int = "caml_extunixba_get_hu63" "noalloc" external unsafe_get_int63 : 'a carray8 -> int -> int = "caml_extunixba_get_hs63" "noalloc" external unsafe_get_int64 : 'a carray8 -> int -> int64 = "caml_extunixba_get_hs64" (** [get_X buf off] same as [unsafe_get_X] but with bounds checking. *) let get_uint8 buf off = if off < 0 || off >= Bigarray.Array1.dim buf then raise (Invalid_argument "index out of bounds"); unsafe_get_uint8 buf off let get_int8 buf off = if off < 0 || off >= Bigarray.Array1.dim buf then raise (Invalid_argument "index out of bounds"); unsafe_get_int8 buf off let get_uint16 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 2 then raise (Invalid_argument "index out of bounds"); unsafe_get_uint16 buf off let get_int16 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 2 then raise (Invalid_argument "index out of bounds"); unsafe_get_int16 buf off let get_uint31 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_get_uint31 buf off let get_int31 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_get_int31 buf off let get_int32 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_get_int32 buf off let get_uint63 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_get_uint63 buf off let get_int63 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_get_int63 buf off let get_int64 buf off = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_get_int64 buf off (** [unsafe_set_X buf off v] stores the integer [v] as type [X] in a buffer [buf] starting at offset [off]. Bounds checking is not performed. Use with caution and only when the program logic guarantees that the access is within bounds. Note: The 31bit functions store an ocaml int as 32bit integer. On 32bit platforms ocaml integers are 31bit signed and will be sign extended to 32bit first. Use with care. Note: The same applies to 63bit functions. *) external unsafe_set_uint8 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_8" "noalloc" external unsafe_set_int8 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_8" "noalloc" external unsafe_set_uint16 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_h16" "noalloc" external unsafe_set_int16 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_h16" "noalloc" external unsafe_set_uint31 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_h31" "noalloc" external unsafe_set_int31 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_h31" "noalloc" external unsafe_set_int32 : 'a carray8 -> int -> int32 -> unit = "caml_extunixba_set_h32" "noalloc" external unsafe_set_uint63 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_h63" "noalloc" external unsafe_set_int63 : 'a carray8 -> int -> int -> unit = "caml_extunixba_set_h63" "noalloc" external unsafe_set_int64 : 'a carray8 -> int -> int64 -> unit = "caml_extunixba_set_h64" "noalloc" (** [set_X buf off v] same as [unsafe_set_X] but with bounds checking. *) let set_uint8 buf off v = if off < 0 || off >= Bigarray.Array1.dim buf then raise (Invalid_argument "index out of bounds"); unsafe_set_uint8 buf off v let set_int8 buf off v = if off < 0 || off >= Bigarray.Array1.dim buf then raise (Invalid_argument "index out of bounds"); unsafe_set_int8 buf off v let set_uint16 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 2 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint16 buf off v let set_int16 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 2 then raise (Invalid_argument "index out of bounds"); unsafe_set_int16 buf off v let set_uint31 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint31 buf off v let set_int31 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_int31 buf off v let set_int32 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 4 then raise (Invalid_argument "index out of bounds"); unsafe_set_int32 buf off v let set_uint63 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_uint63 buf off v let set_int63 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int63 buf off v let set_int64 buf off v = if off < 0 || off > Bigarray.Array1.dim buf - 8 then raise (Invalid_argument "index out of bounds"); unsafe_set_int64 buf off v end (* module HostEndian *) (** [unsafe_get_substr buf off len] extracts the substring from buffer [buf] starting at offset [off] and length [len]. Bounds checking is not performed. Use with caution and only when the program logic guarantees that the access is within bounds.*) external unsafe_get_substr : 'a carray8 -> int -> int -> string = "caml_extunixba_get_substr" (** [get_substr buf off len] same as [unsafe_get_substr] but with bounds checking. *) let get_substr buf off len = if off < 0 || len < 0 || off > Bigarray.Array1.dim buf - len then raise (Invalid_argument "index out of bounds"); unsafe_get_substr buf off len (** [unsafe_set_substr buf off str] stores the string in buffer [buf] starting at offset [off]. Bounds checking is not performed. Use with caution and only when the program logic guarantees that the access is within bounds.*) external unsafe_set_substr : 'a carray8 -> int -> string -> unit = "caml_extunixba_set_substr" (** [set_substr buf off str] same as [unsafe_set_substr] but with bounds checking. *) let set_substr buf off str = if off < 0 || off > Bigarray.Array1.dim buf - String.length str then raise (Invalid_argument "index out of bounds"); unsafe_set_substr buf off str HAVE VMSPLICE (** {2 splice} {b Author:} Pierre Chambart *) (** I/O vector. Used to send multiple data using a single system call *) type 'a iov = { iov_buf : 'a carray8; iov_off : int; iov_len : int; } (** [vmsplice fd iovs flags] sends the data described by [iovs] to the pipe [fd] @return the number of bytes transferred to the pipe. *) external vmsplice : Unix.file_descr -> 'a iov array -> splice_flag list -> int = "caml_extunixba_vmsplice" END 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 (* vim: ft=ocaml *) ocaml-extunix-0.1.6/src/extunix.mldylib000066400000000000000000000002051325120070500201540ustar00rootroot00000000000000# OASIS_START # DO NOT EDIT (digest: 92366bf0d417174534c0e4b99a4b4a1b) ExtUnix ExtUnixAll ExtUnixSpecific ExtUnixConfig # OASIS_STOP ocaml-extunix-0.1.6/src/extunix.mllib000066400000000000000000000002051325120070500176170ustar00rootroot00000000000000# OASIS_START # DO NOT EDIT (digest: 92366bf0d417174534c0e4b99a4b4a1b) ExtUnix ExtUnixAll ExtUnixSpecific ExtUnixConfig # OASIS_STOP ocaml-extunix-0.1.6/src/fadvise.c000066400000000000000000000027221325120070500166650ustar00rootroot00000000000000/* * 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.1.6/src/fallocate.c000066400000000000000000000055261325120070500172030ustar00rootroot00000000000000/* * 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.1.6/src/fexecve.c000066400000000000000000000015471325120070500166750ustar00rootroot00000000000000#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.1.6/src/fsync.c000066400000000000000000000037101325120070500163640ustar00rootroot00000000000000 #define EXTUNIX_WANT_FSYNC #define EXTUNIX_WANT_FDATASYNC #define EXTUNIX_WANT_SYNC #define EXTUNIX_WANT_SYNCFS #include "config.h" #if defined(WIN32) #if defined(EXTUNIX_HAVE_FSYNC) CAMLprim value caml_extunix_fsync(value v) { CAMLparam1(v); HANDLE h = INVALID_HANDLE_VALUE; int r = 0; if (KIND_HANDLE != Descr_kind_val(v)) caml_invalid_argument("fsync"); h = Handle_val(v); caml_enter_blocking_section(); r = FlushFileBuffers(h); caml_leave_blocking_section(); if (0 == r) uerror("fsync",Nothing); CAMLreturn(Val_unit); } #if defined(EXTUNIX_HAVE_FDATASYNC) CAMLprim value caml_extunix_fdatasync(value v) { return caml_extunix_fsync(v); } #endif #endif /* EXTUNIX_HAVE_FSYNC */ #else /* WIN32 */ #if defined(EXTUNIX_HAVE_FSYNC) CAMLprim value caml_extunix_fsync(value v_fd) { CAMLparam1(v_fd); int r = 0; caml_enter_blocking_section(); r = fsync(Int_val(v_fd)); caml_leave_blocking_section(); if (0 != r) uerror("fsync",Nothing); CAMLreturn(Val_unit); } #endif #if defined(EXTUNIX_HAVE_FDATASYNC) CAMLprim value caml_extunix_fdatasync(value v_fd) { CAMLparam1(v_fd); int r = 0; caml_enter_blocking_section(); r = fdatasync(Int_val(v_fd)); caml_leave_blocking_section(); if (0 != r) uerror("fdatasync",Nothing); CAMLreturn(Val_unit); } #endif #if defined(EXTUNIX_HAVE_SYNC) CAMLprim value caml_extunix_sync(value v_unit) { (void)v_unit; caml_enter_blocking_section(); sync(); caml_leave_blocking_section(); return Val_unit; } #endif #if defined(EXTUNIX_HAVE_SYNCFS) CAMLprim value caml_extunix_syncfs(value v_fd) { CAMLparam1(v_fd); int r = 0; caml_enter_blocking_section(); #if defined(EXTUNIX_USE_SYS_SYNCFS) r = syscall(SYS_syncfs, Int_val(v_fd)); #else r = syncfs(Int_val(v_fd)); #endif caml_leave_blocking_section(); if (0 != r) uerror("syncfs",Nothing); CAMLreturn(Val_unit); } #endif #endif /* !WIN32 */ ocaml-extunix-0.1.6/src/ioctl_siocgifconf.c000066400000000000000000000037551325120070500207360ustar00rootroot00000000000000 #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.1.6/src/libextunix_stubs.clib000066400000000000000000000007171325120070500213500ustar00rootroot00000000000000# OASIS_START # DO NOT EDIT (digest: 1f2c4d204075363a78b566c842c05cca) 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 mktemp.o memalign.o endianba.o pread_pwrite_ba.o bigarray.o splice.o sysconf.o common.o sockopt.o poll.o sysinfo.o mount.o unshare.o syslog.o # OASIS_STOP ocaml-extunix-0.1.6/src/malloc.c000066400000000000000000000020401325120070500165040ustar00rootroot00000000000000 #define EXTUNIX_WANT_MALLOC_INFO #define EXTUNIX_WANT_MALLOC_STATS #define EXTUNIX_WANT_MCHECK #include "config.h" #if defined(EXTUNIX_HAVE_MALLOC_STATS) CAMLprim value caml_extunix_malloc_stats(value v_unit) { UNUSED(v_unit); malloc_stats(); return Val_unit; } #endif #if defined(EXTUNIX_HAVE_MALLOC_INFO) #include #include CAMLprim value caml_extunix_malloc_info(value v_unit) { CAMLparam0(); CAMLlocal1(v_s); char* buf = NULL; size_t size; int r; FILE* f = open_memstream(&buf,&size); UNUSED(v_unit); if (NULL == f) uerror("malloc_info", Nothing); r = malloc_info(0,f); fclose(f); if (0 != r) { free(buf); uerror("malloc_info", Nothing); } v_s = caml_alloc_string(size); memcpy(Bp_val(v_s), buf, size); free(buf); CAMLreturn(v_s); } #endif #if defined(EXTUNIX_HAVE_MCHECK) CAMLprim value caml_extunix_mtrace(value v) { UNUSED(v); mtrace(); return Val_unit; } CAMLprim value caml_extunix_muntrace(value v) { UNUSED(v); muntrace(); return Val_unit; } #endif ocaml-extunix-0.1.6/src/memalign.c000066400000000000000000000015011325120070500170270ustar00rootroot00000000000000 #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.1.6/src/mktemp.c000066400000000000000000000027541325120070500165460ustar00rootroot00000000000000#define EXTUNIX_WANT_MKDTEMP #define EXTUNIX_WANT_MKSTEMPS #define EXTUNIX_WANT_MKOSTEMPS #include "config.h" #if defined(EXTUNIX_HAVE_MKDTEMP) CAMLprim value caml_extunix_mkdtemp(value v_path) { CAMLparam1(v_path); char* path = strdup(String_val(v_path)); char *ret; caml_enter_blocking_section(); ret = mkdtemp(path); caml_leave_blocking_section(); if (NULL == ret) { free(path); uerror("mkdtemp", v_path); } v_path = caml_copy_string(ret); free(path); CAMLreturn(v_path); } #endif #if defined(EXTUNIX_HAVE_MKSTEMPS) CAMLprim value caml_extunix_internal_mkstemps(value v_template, value v_suffixlen) { CAMLparam2(v_template, v_suffixlen); 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) /* 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.1.6/src/mman.c000066400000000000000000000013361325120070500161740ustar00rootroot00000000000000 #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.1.6/src/mount.c000066400000000000000000000033711325120070500164070ustar00rootroot00000000000000 #define EXTUNIX_WANT_MOUNT #include "config.h" #if defined(EXTUNIX_HAVE_MOUNT) static int mountflags_table[] = { MS_RDONLY, MS_NOSUID, MS_NODEV, MS_NOEXEC, MS_SYNCHRONOUS, MS_REMOUNT, MS_MANDLOCK, MS_DIRSYNC, MS_NOATIME, MS_NODIRATIME, MS_BIND, MS_MOVE, MS_REC, MS_SILENT, MS_POSIXACL, MS_UNBINDABLE, MS_PRIVATE, MS_SLAVE, MS_SHARED, MS_RELATIME, MS_KERNMOUNT, MS_I_VERSION, MS_STRICTATIME, MS_NOUSER }; CAMLprim value caml_extunix_mount(value v_source, value v_target, value v_fstype, value v_mountflags, value v_data) { CAMLparam5(v_source, v_target, v_fstype, v_mountflags, v_data); int ret; char* p_source = strdup(String_val(v_source)); char* p_target = strdup(String_val(v_target)); char* p_fstype = strdup(String_val(v_fstype)); char* p_data = strdup(String_val(v_data)); int p_mountflags = caml_convert_flag_list(v_mountflags, mountflags_table); caml_enter_blocking_section(); ret = mount(p_source, p_target, p_fstype, p_mountflags, p_data); caml_leave_blocking_section(); free(p_source); free(p_target); free(p_fstype); free(p_data); if (ret != 0) uerror("mount", v_target); CAMLreturn(Val_unit); } static int umountflags_table[] = { MNT_FORCE, MNT_DETACH, MNT_EXPIRE, UMOUNT_NOFOLLOW, }; CAMLprim value caml_extunix_umount2(value v_target,value v_umountflags) { CAMLparam2(v_target, v_umountflags); int ret; char* p_target = strdup(String_val(v_target)); int p_umountflags = caml_convert_flag_list(v_umountflags, umountflags_table); caml_enter_blocking_section(); ret = umount2(p_target, p_umountflags); caml_leave_blocking_section(); free(p_target); if (ret != 0) uerror("umount", v_target); CAMLreturn(Val_unit); } #endif ocaml-extunix-0.1.6/src/pa_have.ml000066400000000000000000000060111325120070500170300ustar00rootroot00000000000000(** New toplevel statement (structure item): HAVE { OR }* END if (ExtUnixConfig.have "") is true (for any of the uident's provided) then enclosed structure items are left as is, otherwise: if -gen-all was specified then external declarations in the scope are rewritten to raise exception when called, otherwise all contents is 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 let check name = match ExtUnixConfig.feature name with | None -> failwith ("Unregistered feature : " ^ name) | Some have -> have EXTEND Gram GLOBAL: str_item; str_item: [ [ "HAVE"; names=alternatives_list; si=str_items; "END" -> let have = List.for_all check names in let name = String.concat " or " names in 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<>> ] ]; alternatives_list: [ [ name=UIDENT -> [ name ] ] | [ rest=alternatives_list; "OR"; name=UIDENT -> name :: rest ] ] ; 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.1.6/src/poll.c000066400000000000000000000031511325120070500162070ustar00rootroot00000000000000 #define EXTUNIX_WANT_POLL #include "config.h" #if defined(EXTUNIX_HAVE_POLL) CAMLprim value caml_extunix_poll_constants(value v_unit) { value v = caml_alloc_tuple(7); UNUSED(v_unit); Field(v,0) = Val_int(POLLIN); Field(v,1) = Val_int(POLLPRI); Field(v,2) = Val_int(POLLOUT); Field(v,3) = Val_int(POLLERR); Field(v,4) = Val_int(POLLHUP); Field(v,5) = Val_int(POLLNVAL); Field(v,6) = Val_int(POLLRDHUP); return v; } CAMLprim value caml_extunix_poll(value v_fds, value v_n, value v_ms) { CAMLparam3(v_fds, v_n, v_ms); CAMLlocal3(v_l,v_tuple,v_cons); struct pollfd* fd = NULL; size_t n = Int_val(v_n); size_t i = 0; int result; int timeout = Double_val(v_ms) * 1000.f; if (Wosize_val(v_fds) < n) caml_invalid_argument("poll"); if (0 == n) CAMLreturn(Val_emptylist); fd = malloc(n * sizeof(struct pollfd)); if (NULL == fd) uerror("malloc",Nothing); for (i = 0; i < n; i++) { fd[i].fd = Int_val(Field(Field(v_fds,i),0)); fd[i].events = Int_val(Field(Field(v_fds,i),1)); fd[i].revents = 0; } caml_enter_blocking_section(); result = poll(fd, n, timeout); caml_leave_blocking_section(); if (result < 0) { free(fd); uerror("poll",Nothing); } v_l = Val_emptylist; for (i = 0; i < n; i++) { if (fd[i].revents != 0) { v_tuple = caml_alloc_tuple(2); Store_field(v_tuple,0,Val_int(fd[i].fd)); Store_field(v_tuple,1,Val_int(fd[i].revents)); v_cons = caml_alloc_tuple(2); Store_field(v_cons,0,v_tuple); Store_field(v_cons,1,v_l); v_l = v_cons; } } free(fd); CAMLreturn(v_l); } #endif ocaml-extunix-0.1.6/src/pread_pwrite_ba.c000066400000000000000000000167071325120070500204030ustar00rootroot00000000000000 #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_byte_size(Caml_ba_array_val(v_buf)); size_t processed = 0; char *buf = (char*)Caml_ba_data_val(v_buf); while(len > 0) { caml_enter_blocking_section(); ret = pread(fd, buf, len, off); caml_leave_blocking_section(); if (ret == 0) break; if (ret == -1) { if (errno == EINTR && (mode & 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_byte_size(Caml_ba_array_val(v_buf)); size_t processed = 0; char *buf = (char*)Caml_ba_data_val(v_buf); while(len > 0) { caml_enter_blocking_section(); ret = pwrite(fd, buf, len, off); caml_leave_blocking_section(); if (ret == 0) break; if (ret == -1) { if (errno == EINTR && (mode & 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_byte_size(Caml_ba_array_val(v_buf)); size_t processed = 0; char *buf = (char*)Caml_ba_data_val(v_buf); while(len > 0) { caml_enter_blocking_section(); ret = read(fd, buf, len); caml_leave_blocking_section(); if (ret == 0) break; if (ret == -1) { if (errno == EINTR && (mode & 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_byte_size(Caml_ba_array_val(v_buf)); size_t processed = 0; char *buf = (char*)Caml_ba_data_val(v_buf); while(len > 0) { caml_enter_blocking_section(); ret = write(fd, buf, len); caml_leave_blocking_section(); if (ret == 0) break; if (ret == -1) { if (errno == EINTR && (mode & 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.1.6/src/ptrace.c000066400000000000000000000023601325120070500165200ustar00rootroot00000000000000 #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.1.6/src/pts.c000066400000000000000000000015521325120070500160520ustar00rootroot00000000000000 #define EXTUNIX_WANT_PTS #include "config.h" #if defined(EXTUNIX_HAVE_PTS) CAMLprim value caml_extunix_posix_openpt(value flags) { CAMLparam1(flags); int ret, cv_flags; cv_flags = extunix_open_flags(flags); ret = posix_openpt(cv_flags); if(ret == -1) uerror("posix_openpt", Nothing); CAMLreturn(Val_int(ret)); } CAMLprim value caml_extunix_grantpt(value fd) { CAMLparam1(fd); if(grantpt(Int_val(fd)) == -1) uerror("grantpt", Nothing); CAMLreturn(Val_unit); } CAMLprim value caml_extunix_unlockpt(value fd) { CAMLparam1(fd); if(unlockpt(Int_val(fd)) == -1) uerror("unlockpt", Nothing); CAMLreturn(Val_unit); } CAMLprim value caml_extunix_ptsname(value fd) { CAMLparam1(fd); CAMLlocal1(ret); char *name = ptsname(Int_val(fd)); if(name == 0) uerror("ptsname", Nothing); ret = caml_copy_string(name); CAMLreturn(ret); } #endif /* HAVE_PTS */ ocaml-extunix-0.1.6/src/read_cred.c000066400000000000000000000012501325120070500171470ustar00rootroot00000000000000#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.1.6/src/resource.c000066400000000000000000000110221325120070500170640ustar00rootroot00000000000000/******************************************************************************/ /* 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.1.6/src/sendmsg.c000066400000000000000000000071761325120070500167140ustar00rootroot00000000000000/* Copyright © 2012 Andre Nathan */ /* * These functions are adapted from Stevens, Fenner and Rudoff, UNIX Network * Programming, Volume 1, Third Edition. We use CMSG_LEN instead of CMSG_SPACE * for the msg_controllen field of struct msghdr to avoid breaking LP64 * systems (cf. Postfix source code). */ #define EXTUNIX_WANT_SENDMSG #include "config.h" #if defined(EXTUNIX_HAVE_SENDMSG) CAMLprim value caml_extunix_sendmsg(value fd_val, value sendfd_val, value data_val) { CAMLparam3(fd_val, sendfd_val, data_val); CAMLlocal1(data); size_t datalen; struct msghdr msg; struct iovec iov[1]; int fd = Int_val(fd_val); ssize_t ret; char *buf; #if defined(CMSG_SPACE) union { struct cmsghdr cmsg; /* for alignment */ char control[CMSG_SPACE(sizeof(int))]; /* sizeof sendfd */ } control_un; #endif memset(&msg, 0, sizeof msg); if (sendfd_val != Val_none) { int sendfd = Int_val(Some_val(sendfd_val)); #if defined(CMSG_SPACE) struct cmsghdr *cmsgp; msg.msg_control = control_un.control; msg.msg_controllen = CMSG_LEN(sizeof sendfd); cmsgp = CMSG_FIRSTHDR(&msg); cmsgp->cmsg_len = CMSG_LEN(sizeof sendfd); cmsgp->cmsg_level = SOL_SOCKET; cmsgp->cmsg_type = SCM_RIGHTS; *(int *)CMSG_DATA(cmsgp) = sendfd; #else msg.msg_accrights = (caddr_t)&sendfd; msg.msg_accrightslen = sizeof sendfd; #endif } datalen = caml_string_length(data_val); buf = malloc(datalen); if (NULL == buf) uerror("sendmsg", Nothing); memcpy(buf, String_val(data_val), datalen); iov[0].iov_base = buf; iov[0].iov_len = datalen; msg.msg_iov = iov; msg.msg_iovlen = 1; caml_enter_blocking_section(); ret = sendmsg(fd, &msg, 0); caml_leave_blocking_section(); free(buf); if (ret == -1) uerror("sendmsg", Nothing); CAMLreturn (Val_unit); } CAMLprim value caml_extunix_recvmsg(value fd_val) { CAMLparam1(fd_val); CAMLlocal2(data, res); struct msghdr msg; int fd = Int_val(fd_val); int recvfd; ssize_t len; struct iovec iov[1]; char buf[4096]; #if defined(CMSG_SPACE) union { struct cmsghdr cmsg; /* just for alignment */ char control[CMSG_SPACE(sizeof recvfd)]; } control_un; struct cmsghdr *cmsgp; memset(&msg, 0, sizeof msg); msg.msg_control = control_un.control; msg.msg_controllen = CMSG_LEN(sizeof recvfd); #else msg.msg_accrights = (caddr_t)&recvfd; msg.msg_accrightslen = sizeof recvfd; #endif iov[0].iov_base = buf; iov[0].iov_len = sizeof buf; msg.msg_iov = iov; msg.msg_iovlen = 1; caml_enter_blocking_section(); len = recvmsg(fd, &msg, 0); caml_leave_blocking_section(); if (len == -1) uerror("recvmsg", Nothing); res = caml_alloc(2, 0); #if defined(CMSG_SPACE) cmsgp = CMSG_FIRSTHDR(&msg); if (cmsgp == NULL) { Store_field(res, 0, Val_none); } else { CAMLlocal1(some_fd); if (cmsgp->cmsg_len != CMSG_LEN(sizeof recvfd)) unix_error(EINVAL, "recvmsg", caml_copy_string("wrong descriptor size")); if (cmsgp->cmsg_level != SOL_SOCKET || cmsgp->cmsg_type != SCM_RIGHTS) unix_error(EINVAL, "recvmsg", caml_copy_string("invalid protocol")); some_fd = caml_alloc(1, 0); Store_field(some_fd, 0, Val_int(*(int *)CMSG_DATA(cmsgp))); Store_field(res, 0, some_fd); } #else if (msg.msg_accrightslen != sizeof recvfd) { Store_field(res, 0, Val_none); } else { CAMLlocal1(some_fd); some_fd = caml_alloc(1, 0); Store_field(some_fd, 0, Val_int(recvfd)); Store_field(res, 0, some_fd); } #endif data = caml_alloc_string(len); memcpy(String_val(data), buf, len); Store_field(res, 1, data); CAMLreturn (res); } #endif /* EXTUNIX_HAVE_SENDMSG */ ocaml-extunix-0.1.6/src/signalfd.c000066400000000000000000000075301325120070500170350ustar00rootroot00000000000000/******************************************************************************/ /* signalfd stubs */ /* */ /* NO COPYRIGHT -- RELEASED INTO THE PUBLIC DOMAIN */ /* */ /* Author: Kaustuv Chaudhuri */ /******************************************************************************/ #define EXTUNIX_WANT_SIGNALFD #include "config.h" #if defined(EXTUNIX_HAVE_SIGNALFD) extern int caml_convert_signal_number(int signo); extern int caml_rev_convert_signal_number(int signo); CAMLprim value caml_extunix_signalfd(value vfd, value vsigs, value vflags, value v_unit) { CAMLparam4(vfd, vsigs, vflags, v_unit); int fd = ((Val_none == vfd) ? -1 : Int_val(Some_val(vfd))); int flags = 0; int ret = 0; sigset_t ss; sigemptyset (&ss); while (!Is_long (vsigs)) { int sig = caml_convert_signal_number (Int_val (Field (vsigs, 0))); if (sigaddset (&ss, sig) < 0) uerror ("sigaddset", Nothing); vsigs = Field (vsigs, 1); } while (!Is_long (vflags)) { int f = Int_val (Field (vflags, 0)); if (SFD_NONBLOCK == f) flags |= SFD_NONBLOCK; if (SFD_CLOEXEC == f) flags |= SFD_CLOEXEC; vflags = Field (vflags, 1); } ret = signalfd (fd, &ss, flags); if (ret < 0) uerror ("signalfd", Nothing); CAMLreturn (Val_int (ret)); } /* [HACK] improve these -- bytestream representation is OK */ static struct custom_operations ssi_ops = { "signalfd.signalfd_siginfo", custom_finalize_default, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default, #if defined(custom_compare_ext_default) custom_compare_ext_default, #endif }; #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.1.6/src/sockopt.c000066400000000000000000000045701325120070500167310ustar00rootroot00000000000000 #define EXTUNIX_WANT_SOCKOPT #include "config.h" #if defined(EXTUNIX_HAVE_SOCKOPT) #include #ifndef TCP_KEEPCNT #define TCP_KEEPCNT (-1) #endif #ifndef TCP_KEEPIDLE #define TCP_KEEPIDLE (-1) #endif #ifndef TCP_KEEPINTVL #define TCP_KEEPINTVL (-1) #endif #ifndef SO_REUSEPORT #define SO_REUSEPORT (-1) #endif #ifndef SO_ATTACH_BPF #define SO_ATTACH_BPF (-1) #endif #ifndef SO_ATTACH_REUSEPORT_EBPF #define SO_ATTACH_REUSEPORT_EBPF (-1) #endif #ifndef SO_DETACH_FILTER #define SO_DETACH_FILTER (-1) #endif #ifndef SO_DETACH_BPF #define SO_DETACH_BPF (-1) #endif #ifndef SO_LOCK_FILTER #define SO_LOCK_FILTER (-1) #endif struct option { int opt; int level; }; static struct option tcp_options[] = { { TCP_KEEPCNT, IPPROTO_TCP }, { TCP_KEEPIDLE, IPPROTO_TCP }, { TCP_KEEPINTVL, IPPROTO_TCP }, { SO_REUSEPORT, SOL_SOCKET }, { SO_ATTACH_BPF, SOL_SOCKET }, { SO_ATTACH_REUSEPORT_EBPF, SOL_SOCKET }, { SO_DETACH_FILTER, SOL_SOCKET }, { SO_DETACH_BPF, SOL_SOCKET }, { SO_LOCK_FILTER, SOL_SOCKET }, }; CAMLprim value caml_extunix_have_sockopt(value k) { if (Int_val(k) < 0 || (unsigned int)Int_val(k) >= sizeof(tcp_options) / sizeof(tcp_options[0])) { caml_invalid_argument("have_sockopt"); } return Val_bool(tcp_options[Int_val(k)].opt != -1); } CAMLprim value caml_extunix_setsockopt_int(value fd, value k, value v) { int optval = Int_val(v); socklen_t optlen = sizeof(optval); if (Int_val(k) < 0 || (unsigned int)Int_val(k) >= sizeof(tcp_options) / sizeof(tcp_options[0])) { caml_invalid_argument("setsockopt_int"); } if (tcp_options[Int_val(k)].opt == -1) { caml_raise_not_found(); assert(0); } if (0 != setsockopt(Int_val(fd), tcp_options[Int_val(k)].level, tcp_options[Int_val(k)].opt, &optval, optlen)) { uerror("setsockopt_int", Nothing); } return Val_unit; } CAMLprim value caml_extunix_getsockopt_int(value fd, value k) { int optval; socklen_t optlen = sizeof(optval); if (Int_val(k) < 0 || (unsigned int)Int_val(k) >= sizeof(tcp_options) / sizeof(tcp_options[0])) { caml_invalid_argument("getsockopt_int"); } if (tcp_options[Int_val(k)].opt == -1) { caml_raise_not_found(); assert(0); } if (0 != getsockopt(Int_val(fd), tcp_options[Int_val(k)].level, tcp_options[Int_val(k)].opt, &optval, &optlen)) { uerror("getsockopt_int", Nothing); } return Val_int(optval); } #endif ocaml-extunix-0.1.6/src/splice.c000066400000000000000000000057161325120070500165310ustar00rootroot00000000000000 #define EXTUNIX_WANT_VMSPLICE #define EXTUNIX_WANT_SPLICE #define EXTUNIX_WANT_TEE #include "config.h" #if defined(EXTUNIX_HAVE_SPLICE) | defined(EXTUNIX_HAVE_TEE) | defined(EXTUNIX_HAVE_VMSPLICE) static int splice_flags[] = { SPLICE_F_MOVE, SPLICE_F_NONBLOCK, SPLICE_F_MORE, SPLICE_F_GIFT }; #endif #if defined(EXTUNIX_HAVE_SPLICE) static loff_t* get_offset(value v_off) { return (Is_long(v_off) ? NULL : &(Field(v_off, 0))); } CAMLprim value caml_extunix_splice(value v_fd_in, value v_off_in, value v_fd_out, value v_off_out, value v_len, value v_flags) { CAMLparam5(v_fd_in, v_off_in, v_fd_out, v_off_out, v_len); CAMLxparam1(v_flags); unsigned int flags = caml_convert_flag_list(v_flags, splice_flags); int fd_in = Int_val(v_fd_in); int fd_out = Int_val(v_fd_out); loff_t* off_in = get_offset(v_off_in); loff_t* off_out = get_offset(v_off_out); size_t len = Int_val(v_len); ssize_t ret; caml_enter_blocking_section(); ret = splice(fd_in, off_in, fd_out, off_out, len, flags); caml_leave_blocking_section(); if (ret == -1) uerror("splice", Nothing); CAMLreturn(Val_long(ret)); } CAMLprim value caml_extunix_splice_bytecode(value * argv, int argn) { (void)argn; return caml_extunix_splice(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]); } #endif #if defined(EXTUNIX_HAVE_TEE) CAMLprim value caml_extunix_tee(value v_fd_in, value v_fd_out, value v_len, value v_flags) { CAMLparam4(v_fd_in, v_fd_out, v_len, v_flags); unsigned int flags = caml_convert_flag_list(v_flags, splice_flags); int fd_in = Int_val(v_fd_in); int fd_out = Int_val(v_fd_out); size_t len = Int_val(v_len); ssize_t ret; caml_enter_blocking_section(); ret = tee(fd_in, fd_out, len, flags); caml_leave_blocking_section(); if (ret == -1) uerror("tee", Nothing); CAMLreturn(Val_long(ret)); } #endif #if defined(EXTUNIX_HAVE_VMSPLICE) CAMLprim value caml_extunixba_vmsplice(value v_fd_out, value v_iov, value v_flags) { CAMLparam3(v_fd_out, v_iov, v_flags); unsigned int flags = caml_convert_flag_list(v_flags, splice_flags); int fd_out = Int_val(v_fd_out); int size = Wosize_val(v_iov); struct iovec* iov = alloca(sizeof(struct iovec) * size); ssize_t ret; int i; value tmp; struct caml_ba_array* ba; int offset, length; for (i = 0; i < size; i++) { tmp = Field(v_iov,i); /* field 0 is a 'a carray8 (bigarray of 8-bit elements) field 1 is the offset in the bigarray field 2 is the length */ ba = Caml_ba_array_val(Field(tmp,0)); offset = Int_val(Field(tmp,1)); length = Int_val(Field(tmp,2)); if(offset + length > ba->dim[0]) caml_invalid_argument("vmsplice"); iov[i].iov_base = (char *) ba->data + offset; iov[i].iov_len = length; } caml_enter_blocking_section(); ret = vmsplice(fd_out, iov, size, flags); caml_leave_blocking_section(); if (ret == -1) uerror("vmsplice", Nothing); CAMLreturn(Val_long(ret)); } #endif ocaml-extunix-0.1.6/src/statvfs.c000066400000000000000000000034471325120070500167430ustar00rootroot00000000000000 #define EXTUNIX_WANT_STATVFS #include "config.h" #if defined(EXTUNIX_HAVE_STATVFS) static int st_flags_table[] = { ST_RDONLY, ST_NOSUID, ST_NODEV, ST_NOEXEC, ST_SYNCHRONOUS, ST_MANDLOCK, ST_WRITE, ST_APPEND, ST_IMMUTABLE, ST_NOATIME, ST_NODIRATIME, ST_RELATIME }; static const int st_flags_table_size = sizeof(st_flags_table) / sizeof(st_flags_table[0]); static value convert_st_flags(unsigned long int f_flag) { CAMLparam0(); CAMLlocal2(list, tmp); int i; list = Val_emptylist; for (i = st_flags_table_size - 1; i >= 0; i--) { if (f_flag & st_flags_table[i]) { tmp = caml_alloc(2, Tag_cons); Store_field(tmp,0,Val_int(i)); Store_field(tmp,1,list); list = tmp; } } CAMLreturn(list); } static value convert(struct statvfs* s) { CAMLparam0(); CAMLlocal1(v_s); v_s = caml_alloc(11,0); Store_field(v_s,0,Val_int(s->f_bsize)); Store_field(v_s,1,caml_copy_int64(s->f_blocks)); Store_field(v_s,2,caml_copy_int64(s->f_bfree)); Store_field(v_s,3,caml_copy_int64(s->f_bavail)); Store_field(v_s,4,caml_copy_int64(s->f_files)); Store_field(v_s,5,caml_copy_int64(s->f_ffree)); Store_field(v_s,6,caml_copy_int64(s->f_favail)); Store_field(v_s,7,caml_copy_int64(s->f_fsid)); Store_field(v_s,8,Val_int(s->f_flag)); Store_field(v_s,9,convert_st_flags(s->f_flag)); Store_field(v_s,10,Val_int(s->f_namemax)); CAMLreturn(v_s); } 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.1.6/src/stdlib.c000066400000000000000000000035331325120070500165260ustar00rootroot00000000000000 #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 ocaml-extunix-0.1.6/src/sysconf.c000066400000000000000000000023241325120070500167260ustar00rootroot00000000000000/* * Binding to sysconf * * Copyright 2013 * * License LGPL-2.1 with OCaml linking static exception * * author: Roman Vorobets * */ #define EXTUNIX_WANT_SYSCONF #include "config.h" #if defined(EXTUNIX_HAVE_SYSCONF) #ifndef _SC_PHYS_PAGES #define _SC_PHYS_PAGES (-1) #endif #ifndef _SC_AVPHYS_PAGES #define _SC_AVPHYS_PAGES (-1) #endif #ifndef _SC_NPROCESSORS_CONF #define _SC_NPROCESSORS_CONF (-1) #endif #ifndef _SC_NPROCESSORS_ONLN #define _SC_NPROCESSORS_ONLN (-1) #endif static int caml_conf_table[] = { _SC_ARG_MAX, _SC_CHILD_MAX, _SC_HOST_NAME_MAX, _SC_LOGIN_NAME_MAX, _SC_CLK_TCK, _SC_OPEN_MAX, _SC_PAGESIZE, _SC_RE_DUP_MAX, _SC_STREAM_MAX, _SC_SYMLOOP_MAX, _SC_TTY_NAME_MAX, _SC_TZNAME_MAX, _SC_VERSION, _SC_LINE_MAX, _SC_2_VERSION, _SC_PHYS_PAGES, _SC_AVPHYS_PAGES, _SC_NPROCESSORS_CONF, _SC_NPROCESSORS_ONLN }; CAMLprim value caml_extunix_sysconf(value name) { CAMLparam1(name); long r = -1; int sc = caml_conf_table[Int_val(name)]; if (-1 == sc) { caml_raise_not_found(); assert(0); } r = sysconf(sc); if (-1 == r) { uerror("sysconf", Nothing); } CAMLreturn(caml_copy_int64(r)); } #endif ocaml-extunix-0.1.6/src/sysinfo.c000066400000000000000000000026041325120070500167350ustar00rootroot00000000000000 #define EXTUNIX_WANT_SYSINFO #include "config.h" #if defined(EXTUNIX_HAVE_SYSINFO) static value convert(struct sysinfo* s) { CAMLparam0(); CAMLlocal2(v,v_loads); v_loads = caml_alloc_tuple(3); Store_field(v_loads, 0, caml_copy_double(s->loads[0] / (float)(1 << SI_LOAD_SHIFT))); Store_field(v_loads, 1, caml_copy_double(s->loads[1] / (float)(1 << SI_LOAD_SHIFT))); Store_field(v_loads, 2, caml_copy_double(s->loads[2] / (float)(1 << SI_LOAD_SHIFT))); v = caml_alloc_tuple(12); Store_field(v, 0, Val_long(s->uptime)); Store_field(v, 1, v_loads); Store_field(v, 2, Val_long(s->totalram)); Store_field(v, 3, Val_long(s->freeram)); Store_field(v, 4, Val_long(s->sharedram)); Store_field(v, 5, Val_long(s->bufferram)); Store_field(v, 6, Val_long(s->totalswap)); Store_field(v, 7, Val_long(s->freeswap)); Store_field(v, 8, Val_int(s->procs)); Store_field(v, 9, Val_long(s->totalhigh)); Store_field(v, 10, Val_long(s->freehigh)); Store_field(v, 11, Val_int(s->mem_unit)); CAMLreturn(v); } CAMLprim value caml_extunix_sysinfo(value v_unit) { CAMLparam1(v_unit); struct sysinfo s; if (0 != sysinfo(&s)) { uerror("sysinfo",Nothing); } CAMLreturn(convert(&s)); } CAMLprim value caml_extunix_uptime(value v_unit) { struct sysinfo s; UNUSED(v_unit); if (0 != sysinfo(&s)) { uerror("sysinfo",Nothing); } return Val_int(s.uptime); } #endif ocaml-extunix-0.1.6/src/syslog.c000066400000000000000000000055411325120070500165660ustar00rootroot00000000000000 #define EXTUNIX_WANT_SYSLOG #include "config.h" #if defined(EXTUNIX_HAVE_SYSLOG) #include static int mask_table[] = { LOG_MASK(LOG_EMERG), LOG_MASK(LOG_ALERT), LOG_MASK(LOG_CRIT), LOG_MASK(LOG_ERR), LOG_MASK(LOG_WARNING), LOG_MASK(LOG_NOTICE), LOG_MASK(LOG_INFO), LOG_MASK(LOG_DEBUG) }; CAMLprim value caml_extunix_setlogmask(value v_level) { CAMLparam1(v_level); CAMLlocal2(cli, cons); int mask, nmask; size_t i; mask = caml_convert_flag_list(v_level, mask_table); caml_enter_blocking_section(); nmask = setlogmask(mask); caml_leave_blocking_section(); // generate list from mask (invers of "caml_convert_flag_list") cli = Val_emptylist; for (i = 0; i < (sizeof(mask_table) / sizeof(int)); i++) { if ((mask_table[i] & nmask) == mask_table[i]) { cons = caml_alloc(2, 0); Store_field(cons, 0, Val_int(i)); Store_field(cons, 1, cli); cli = cons; } } CAMLreturn(cli); } static int option_table[] = { LOG_PID, LOG_CONS, LOG_NDELAY, LOG_ODELAY, LOG_NOWAIT }; static int facility_table[] = { LOG_KERN, LOG_USER, LOG_MAIL, LOG_NEWS, LOG_UUCP, LOG_DAEMON, LOG_AUTH, LOG_CRON, LOG_LPR, LOG_LOCAL0, LOG_LOCAL1, LOG_LOCAL2, LOG_LOCAL3, LOG_LOCAL4, LOG_LOCAL5, LOG_LOCAL6, LOG_LOCAL7 }; CAMLprim value caml_extunix_openlog(value v_ident, value v_option, value v_facility) { CAMLparam3(v_ident, v_option, v_facility); int option, facility; size_t index_facility; char *ident; ident = (Val_none == v_ident) ? NULL : strdup(String_val(Some_val(v_ident))); option = caml_convert_flag_list(v_option, option_table); index_facility = Int_val(v_facility); assert(index_facility < (sizeof(facility_table) / sizeof(int))); facility = facility_table[index_facility]; caml_enter_blocking_section(); openlog(ident, option, facility); if (NULL != ident) { free(ident); } caml_leave_blocking_section(); CAMLreturn(Val_unit); } CAMLprim value caml_extunix_closelog(void) { CAMLparam0(); closelog(); CAMLreturn(Val_unit); } static int level_table[] = { LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG }; CAMLprim value caml_extunix_syslog(value v_facility, value v_level, value v_string) { CAMLparam3(v_facility, v_level, v_string); int facility, level; size_t index_level, index_facility; char *str; facility = 0; if (Val_none != v_facility) { index_facility = Int_val(Some_val(v_facility)); assert(index_facility < (sizeof(facility_table) / sizeof(int))); facility = facility_table[index_facility]; } index_level = Int_val(v_level); assert(index_level < (sizeof(level_table) / sizeof(int))); level = level_table[index_level]; str = strdup(String_val(v_string)); caml_enter_blocking_section(); syslog(level | facility, "%s", str); caml_leave_blocking_section(); free(str); CAMLreturn(Val_unit); } #endif ocaml-extunix-0.1.6/src/time.c000066400000000000000000000051331325120070500162010ustar00rootroot00000000000000 #define EXTUNIX_WANT_STRTIME #define EXTUNIX_WANT_TIMEZONE #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; tzset(); return caml_copy_string(tzname[i]); } #endif #if defined(EXTUNIX_HAVE_TIMEZONE) CAMLprim value caml_extunix_timezone(value v_unit) { CAMLparam1(v_unit); CAMLlocal1(v); tzset(); v = caml_alloc_tuple(2); Store_field(v, 0, Val_int(timezone)); Store_field(v, 1, Val_bool(daylight != 0)); CAMLreturn(v); } #endif #if defined(EXTUNIX_HAVE_TIMEGM) CAMLprim value caml_extunix_timegm(value v_t) { CAMLparam1(v_t); struct tm tm; time_t t; fill_tm(&tm, v_t); t = timegm(&tm); CAMLreturn(caml_copy_double(t)); } #endif ocaml-extunix-0.1.6/src/tty_ioctl.c000066400000000000000000000021351325120070500172540ustar00rootroot00000000000000/* * 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.1.6/src/uname.c000066400000000000000000000013761325120070500163550ustar00rootroot00000000000000 #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.1.6/src/unistd.c000066400000000000000000000310351325120070500165510ustar00rootroot00000000000000 #define EXTUNIX_WANT_TTYNAME #define EXTUNIX_WANT_CTERMID #define EXTUNIX_WANT_PGID #define EXTUNIX_WANT_SETREUID #define EXTUNIX_WANT_SETRESUID #define EXTUNIX_WANT_FCNTL #define EXTUNIX_WANT_TCPGRP #define EXTUNIX_WANT_PREAD #define EXTUNIX_WANT_PWRITE #define EXTUNIX_WANT_READ #define EXTUNIX_WANT_WRITE #define EXTUNIX_WANT_GETTID #define EXTUNIX_WANT_CHROOT #include "config.h" #if defined(EXTUNIX_HAVE_TTYNAME) /* Copyright © 2010 Stéphane Glondu */ CAMLprim value caml_extunix_ttyname(value v_fd) { CAMLparam1(v_fd); char *r = ttyname(Int_val(v_fd)); if (r) { CAMLreturn(caml_copy_string(r)); } else { uerror("ttyname", Nothing); } } #endif #if defined(EXTUNIX_HAVE_CTERMID) CAMLprim value caml_extunix_ctermid(value v_unit) { char buf[L_ctermid + 1]; UNUSED(v_unit); return caml_copy_string(ctermid(buf)); } #endif #if defined(EXTUNIX_HAVE_GETTID) CAMLprim value caml_extunix_gettid(value v_unit) { UNUSED(v_unit); return Val_int(syscall(SYS_gettid)); } #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 #if defined(EXTUNIX_HAVE_CHROOT) CAMLprim value caml_extunix_chroot(value v_path) { CAMLparam1(v_path); int ret; char* p_path = strdup(String_val(v_path)); caml_enter_blocking_section(); ret = chroot(p_path); caml_leave_blocking_section(); free(p_path); if (ret != 0) uerror("chroot", v_path); CAMLreturn(Val_unit); } #endif ocaml-extunix-0.1.6/src/unshare.c000066400000000000000000000011351325120070500167060ustar00rootroot00000000000000 #define EXTUNIX_WANT_UNSHARE #include "config.h" #if defined(EXTUNIX_HAVE_UNSHARE) static int umountflags_table[] = { CLONE_FS, CLONE_FILES, CLONE_NEWNS, CLONE_SYSVSEM, CLONE_NEWUTS, CLONE_NEWIPC, CLONE_NEWUSER, CLONE_NEWPID, CLONE_NEWNET }; CAMLprim value caml_extunix_unshare(value v_cloneflags) { CAMLparam1(v_cloneflags); int ret; int p_cloneflags = caml_convert_flag_list(v_cloneflags, umountflags_table); caml_enter_blocking_section(); ret = unshare(p_cloneflags); caml_leave_blocking_section(); if (ret != 0) uerror("unshare", Nothing); CAMLreturn(Val_unit); } #endif ocaml-extunix-0.1.6/test/000077500000000000000000000000001325120070500152655ustar00rootroot00000000000000ocaml-extunix-0.1.6/test/test.ml000066400000000000000000000461161325120070500166060ustar00rootroot00000000000000 open Printf open OUnit open ExtUnix.All let with_unix_error f () = try f () with | Unix.Unix_error(e,f,a) -> let message = sprintf "Unix_error : %s(%s) : %s" f a (Unix.error_message e) in skip_if (e = Unix.ENOSYS) message; (* libc may raise Not implemented, not an error in extunix *) assert_failure message let require feature = match have feature with | None -> assert false | Some present -> skip_if (not present) (sprintf "%S is not available" feature) let printer x = x let test_eventfd () = require "eventfd"; let e = eventfd 2 in assert_equal 2L (eventfd_read e); eventfd_write e 3L; assert_equal 3L (eventfd_read e) let test_uname () = require "uname"; let t = uname () in let _s: string = Uname.to_string t in () let test_fadvise () = require "fadvise"; let (name,ch) = Filename.open_temp_file "extunix" "test" in try fadvise (Unix.descr_of_out_channel ch) 0 0 POSIX_FADV_NORMAL; LargeFile.fadvise (Unix.descr_of_out_channel ch) 0L 0L POSIX_FADV_SEQUENTIAL; close_out ch; Unix.unlink name with exn -> close_out_noerr ch; Unix.unlink name; raise exn let test_fallocate () = require "fallocate"; let (name,ch) = Filename.open_temp_file "extunix" "test" in try let fd = Unix.descr_of_out_channel ch in fallocate fd 0 1; LargeFile.fallocate fd 1L 1L; assert_equal (Unix.fstat fd).Unix.st_size 2; close_out_noerr ch; Unix.unlink name with exn -> close_out_noerr ch; Unix.unlink name; raise exn (* Copied from oUnit.ml *) (* Utility function to manipulate test *) let rec test_decorate g tst = match tst with | TestCase f -> TestCase (g f) | TestList tst_lst -> TestList (List.map (test_decorate g) tst_lst) | TestLabel (str, tst) -> TestLabel (str, test_decorate g tst) let test_unistd = [ "ttyname" >:: begin fun () -> require "ttyname"; if Unix.isatty Unix.stdin then ignore (ttyname Unix.stdin); if Unix.isatty Unix.stdout then ignore (ttyname Unix.stdout); end; "ctermid" >:: (fun () -> require "ctermid"; ignore (ctermid ())); "pgid" >:: begin fun () -> require "getpgid"; assert_equal (getsid 0) (getsid (Unix.getpid ())); let pgid = getpgid 0 in setpgid 0 0; assert_equal (getpgid 0) (Unix.getpid ()); setpgid 0 pgid; assert_equal (getpgid 0) pgid; end; "fcntl" >:: begin fun () -> require "is_open_descr"; assert (is_open_descr Unix.stdin); assert (is_open_descr Unix.stdout); end; "int_of_file_descr" >:: begin fun () -> try assert (Unix.stdout = (file_descr_of_int (int_of_file_descr Unix.stdout))) with Not_available _ -> skip_if true "int_of_file_descr" end ] let test_realpath () = require "realpath"; assert_equal ~printer (Unix.getcwd ()) (realpath "."); assert_equal ~printer (Unix.getcwd ()) (realpath "./././/./"); assert_equal ~printer "/" (realpath "///"); assert_equal ~printer "/" (realpath "/../../"); () let test_signalfd () = require "signalfd"; let pid = Unix.getpid () in let (_:int list) = Unix.sigprocmask Unix.SIG_BLOCK [Sys.sigusr1; Sys.sigusr2] in let fd = signalfd ~sigs:[Sys.sigusr1] ~flags:[] () in Unix.kill pid Sys.sigusr1; let fd = signalfd ~fd ~sigs:[Sys.sigusr1; Sys.sigusr2] ~flags:[] () in Unix.set_nonblock fd; let printer = string_of_int in assert_equal ~printer Sys.sigusr1 (ssi_signo_sys (signalfd_read fd)); Unix.kill pid Sys.sigusr2; assert_equal ~printer Sys.sigusr2 (ssi_signo_sys (signalfd_read fd)); Unix.close fd let test_resource = let all_resources = [ RLIMIT_CORE; RLIMIT_CPU; RLIMIT_DATA; RLIMIT_FSIZE; (* RLIMIT_NOFILE; *) (* too fragile to test on CI *) RLIMIT_STACK; RLIMIT_AS; ] in let test_setrlimit r = require "setrlimit"; let test soft hard = setrlimit r ~soft ~hard; let (soft',hard') = getrlimit r in assert_equal ~printer:Rlimit.to_string ~msg:"soft limit" ~cmp:Rlimit.eq soft soft'; assert_equal ~printer:Rlimit.to_string ~msg:"hard limit" ~cmp:Rlimit.eq hard hard'; in let (soft,hard) = getrlimit r in assert_bool "soft <= hard" (Rlimit.le soft hard); test hard hard; test soft hard; match hard with | Some 0L -> () | None -> test soft soft | Some n -> let lim = Some (Int64.pred n) in test lim lim in let test_setrlimit r = (string_of_resource r) >:: (fun () -> test_setrlimit r) in [ "setrlimit" >::: (List.rev_map test_setrlimit all_resources); "getpriority" >:: (fun () -> require "getpriority"; let (_:int) = getpriority (PRIO_PROCESS (Unix.getpid ())) in ()); "setpriority" >:: (fun () -> require "setpriority"; let me = PRIO_PROCESS (Unix.getpid ()) in let prio = getpriority me in setpriority me (prio + 1); assert_equal ~printer:string_of_int (prio + 1) (getpriority me)); ] let test_strtime () = require "strptime"; assert_equal ~printer "2010/12/14" (strftime "%Y/%m/%d" (strptime "%Y-%m-%d" "2010-12-14")); let tm = Unix.localtime (Unix.gettimeofday ()) in let (_:string) = asctime tm in let (_:string) = tzname tm.Unix.tm_isdst in () let test_pts () = require "posix_openpt"; let master = 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_substring slave test 0 (String.length test) in let str = let b = Bytes.create len in assert_equal (Unix.read master b 0 len) len; Bytes.unsafe_to_string b in assert_equal str test; () let test_execinfo () = require "backtrace"; (* Disabled - may not work out of the box on all archs or even segfault *) (* assert_bool "backtrace" ([||] <> backtrace ()) *) (* let (_:string array) = backtrace () in *) () let test_statvfs () = require "statvfs"; let st = statvfs "." 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); assert_equal (B.get_uint31 src 6) (Int64.to_int 0xFEDCBA98L); assert_equal (B.get_int31 src 6) (Int64.to_int 0x7FFFFFFFFEDCBA98L); assert_equal (B.get_int31 src 6) (-0x1234568); assert_equal (B.get_uint63 src 10) (Int64.to_int 0x7EDCBA9876543210L); assert_equal (B.get_int63 src 10) (Int64.to_int 0x7EDCBA9876543210L); assert_equal (B.get_int63 src 10) (Int64.to_int (-0x123456789ABCDF0L)); assert_equal (L.get_uint31 src 6) (Int64.to_int 0x98BADCFEL); assert_equal (L.get_int31 src 6) (Int64.to_int 0x7FFFFFFF98BADCFEL); assert_equal (L.get_int31 src 6) (-0x67452302); assert_equal (L.get_uint63 src 10) (Int64.to_int 0x1032547698BADCFEL); assert_equal (L.get_int63 src 10) (Int64.to_int 0x1032547698BADCFEL); assert_equal (L.get_int63 src 10) (Int64.to_int (-0x6FCDAB8967452302L)); let b = Bytes.create 18 in B.set_uint8 b 0 0xFF; B.set_int8 b 1 (-0x01); B.set_uint16 b 2 0xFEDC; B.set_uint16 b 4 (-0x0124); B.set_int32 b 6 (0xFEDCBA98l); B.set_int64 b 10 (0xFEDCBA9876543210L); assert_equal (Bytes.unsafe_to_string b) src; let l = Bytes.create 18 in L.set_uint8 l 0 0xFF; L.set_int8 l 1 (-0x01); L.set_uint16 l 2 0xDCFE; L.set_uint16 l 4 (-0x2302); L.set_int32 l 6 (0x98BADCFEl); L.set_int64 l 10 (0x1032547698BADCFEL); assert_equal (Bytes.unsafe_to_string l) src let test_read_credentials () = require "read_credentials"; let (_fd1, fd2) = Unix.socketpair Unix.PF_UNIX Unix.SOCK_STREAM 0 in let (pid, uid, gid) = Unix.getpid (), Unix.getuid (), Unix.getgid () in assert_equal (read_credentials fd2) (pid, uid, gid) let test_fexecve () = require "fexecve"; let s1, s2 = Unix.socketpair Unix.PF_UNIX Unix.SOCK_STREAM 0 in match Unix.fork () with | 0 -> Unix.dup2 s2 Unix.stdout; Unix.close s1; Unix.close s2; let fd = Unix.openfile "/bin/echo" [Unix.O_RDONLY] 0 in fexecve fd [| "/bin/echo"; "-n"; "fexecve" |] [| |] | pid -> Unix.close s2; let wpid, _ = Unix.wait () in assert_equal wpid pid; let str = let b = Bytes.create 7 in assert_equal (Unix.read s1 b 0 7) 7; Bytes.unsafe_to_string b in assert_equal "fexecve" str; Unix.close s1 let test_sendmsg () = require "sendmsg"; let (s1, s2) = Unix.socketpair Unix.PF_UNIX Unix.SOCK_STREAM 0 in match Unix.fork () with | 0 -> Unix.close s1; let fd = Unix.openfile "/bin/ls" [Unix.O_RDONLY] 0 in let st = Unix.fstat fd in sendmsg s2 ~sendfd:fd (sprintf "%d" st.Unix.st_ino); Unix.close fd; Unix.close s2; | _pid -> Unix.close s2; let (some_fd, msg) = recvmsg_fd s1 in Unix.close s1; match some_fd with | None -> assert_failure "no fd" | Some fd -> let st = Unix.fstat fd in assert_equal (int_of_string msg) st.Unix.st_ino; Unix.close fd let cmp_bytes str c text = for i = 0 to Bytes.length str - 1 do if Bytes.get str i <> c then assert_failure text; done let test_pread () = require "unsafe_pread"; let name = Filename.temp_file "extunix" "pread" in let fd = Unix.openfile name [Unix.O_RDWR] 0 in try let size = 65536 in (* Must be larger than UNIX_BUFFER_SIZE (16384) *) let s = String.make size 'x' in assert_equal (Unix.write_substring fd s 0 size) size; let t = Bytes.make size ' ' in assert_equal (pread fd 0 t 0 size) size; cmp_bytes t 'x' "pread read bad data"; assert_equal (single_pread fd 0 t 0 size) size; cmp_bytes t 'x' "single_pread read bad data"; let t = Bytes.make size ' ' in assert_equal (LargeFile.pread fd Int64.zero t 0 size) size; cmp_bytes t 'x' "Largefile.pread read bad data"; assert_equal (LargeFile.single_pread fd Int64.zero t 0 size) size; cmp_bytes t 'x' "Largefile.single_pread read bad data"; Unix.close fd; Unix.unlink name with exn -> Unix.close fd; Unix.unlink name; raise exn let test_pwrite () = require "unsafe_pwrite"; let name = Filename.temp_file "extunix" "pwrite" in let fd = Unix.openfile name [Unix.O_RDWR] 0 in let read dst = assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0; let rec loop off = function | 0 -> () | size -> let len = Unix.read fd dst off size in loop (off + len) (size - len) in loop 0 (Bytes.length dst) in try let size = 65536 in (* Must be larger than UNIX_BUFFER_SIZE (16384) *) let s = String.make size 'x' in assert_equal (pwrite fd 0 s 0 size) size; let t = Bytes.make size ' ' in read t; cmp_bytes t 'x' "pwrite wrote bad data"; assert_equal (single_pwrite fd 0 s 0 size) size; read t; cmp_bytes t 'x' "single_pwrite wrote bad data"; let s = String.make size 'y' in assert_equal (LargeFile.pwrite fd Int64.zero s 0 size) size; let t = Bytes.make size ' ' in read t; cmp_bytes t 'y' "Largefile.pwrite wrote bad data"; assert_equal (LargeFile.single_pwrite fd Int64.zero s 0 size) size; read t; cmp_bytes t 'y' "Largefile.single_pwrite wrote bad data"; Unix.close fd; Unix.unlink name with exn -> Unix.close fd; Unix.unlink name; raise exn let test_read () = require "unsafe_read"; let name = Filename.temp_file "extunix" "read" in let fd = Unix.openfile name [Unix.O_RDWR] 0 in try let size = 65536 in (* Must be larger than UNIX_BUFFER_SIZE (16384) *) let s = String.make size 'x' in assert_equal (Unix.write_substring fd s 0 size) size; let t = Bytes.make size ' ' in assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0; assert_equal (read fd t 0 size) size; cmp_bytes t 'x' "read read bad data"; assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0; assert_equal (single_read fd t 0 size) size; cmp_bytes t 'x' "single_read read bad data"; Unix.close fd; Unix.unlink name with exn -> Unix.close fd; Unix.unlink name; raise exn let test_write () = require "unsafe_write"; let name = Filename.temp_file "extunix" "write" in let fd = Unix.openfile name [Unix.O_RDWR] 0 in let read dst = assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0; let rec loop off = function | 0 -> () | size -> let len = Unix.read fd dst off size in loop (off + len) (size - len) in loop 0 (Bytes.length dst) in try let size = 65536 in (* Must be larger than UNIX_BUFFER_SIZE (16384) *) let s = String.make size 'x' in assert_equal (write fd s 0 size) size; let t = Bytes.make size ' ' in read t; cmp_bytes t 'x' "write wrote bad data"; assert_equal (single_write fd s 0 size) size; read t; cmp_bytes t 'x' "single_write wrote bad data"; Unix.close fd; Unix.unlink name with exn -> Unix.close fd; Unix.unlink name; raise exn let test_mkstemp () = require "internal_mkstemps"; let (_fd, name) = mkstemp ~suffix:"mkstemp" "extunix" in Unix.unlink name let test_mkostemp () = require "internal_mkostemps"; let (_fd, name) = mkostemp ~suffix:"mkstemp" ~flags:[Unix.O_APPEND] "extunix" in Unix.unlink name let test_memalign () = require "memalign"; ignore (memalign 512 512); ignore (memalign 1024 2048); ignore (memalign 2048 16384); ignore (memalign 4096 65536) let test_sockopt () = require "setsockopt_int"; require "getsockopt_int"; let fd = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in let test msg opt v = try setsockopt_int fd opt v; assert_equal ~printer:string_of_int ~msg v (getsockopt_int fd opt) with Not_available _ -> skip_if true msg in Unix.setsockopt fd Unix.SO_KEEPALIVE true; test "TCP_KEEPCNT" TCP_KEEPCNT 5; test "TCP_KEEPIDLE" TCP_KEEPIDLE 30; test "TCP_KEEPINTVL" TCP_KEEPINTVL 10; Unix.close fd let test_sendmsg_bin () = require "sendmsg"; let test_msg = "test\x00message\x01" in let (s,s') = Unix.socketpair Unix.PF_UNIX Unix.SOCK_STREAM 0 in match Unix.fork () with | 0 -> Unix.close s'; sendmsg s ~sendfd:Unix.stdout test_msg; sendfd ~sock:s ~fd:Unix.stdout | _ -> Unix.close s; let (fd1,msg) = recvmsg_fd s' in assert_equal ~printer:(sprintf "%S") test_msg msg; match fd1 with | None -> assert_failure "expected fd, got nothing" | Some fd1 -> Unix.close fd1; let fd2 = recvfd s' in Unix.close fd2 let test_sysinfo () = require "sysinfo"; let t = sysinfo () in let (_:int) = t.uptime in () let () = let wrap test = with_unix_error (fun () -> test (); Gc.compact ()) in let tests = ("tests" >::: [ "eventfd" >:: test_eventfd; "uname" >:: test_uname; "fadvise" >:: test_fadvise; "fallocate" >:: test_fallocate; "unistd" >::: test_unistd; "realpath" >:: test_realpath; "signalfd" >:: test_signalfd; "resource" >::: test_resource; "strtime" >:: test_strtime; "pts" >:: test_pts; "execinfo" >:: test_execinfo; "statvfs" >:: test_statvfs; "setenv" >:: test_setenv; "mkdtemp" >:: test_mkdtemp; "endian" >:: test_endian; "endian_string" >:: test_endian_string; "read_credentials" >:: test_read_credentials; "fexecve" >:: test_fexecve; "sendmsg" >:: test_sendmsg; "pread" >:: test_pread; "pwrite" >:: test_pwrite; "read" >:: test_read; "write" >:: test_write; "mkstemp" >:: test_mkstemp; "mkostemp" >:: test_mkostemp; "memalign" >:: test_memalign; "sockopt" >:: test_sockopt; "sendmsg_bin" >:: test_sendmsg_bin; "sysinfo" >:: test_sysinfo; ]) in ignore (run_test_tt_main (test_decorate wrap tests)) ocaml-extunix-0.1.6/test/test_user_namespace.ml000066400000000000000000000326371325120070500216630ustar00rootroot00000000000000 open ExtUnix.All let mkdir ?(perm=0o750) dir = if not (Sys.file_exists dir) then Unix.mkdir dir perm let mount_inside ~dir ~src ~tgt ?(fstype="") ~flags ?(data="") () = let tgt = Filename.concat dir tgt in mkdir tgt; mount ~source:src ~target:tgt ~fstype flags ~data let mount_base dir = mount_inside ~dir ~src:"proc" ~tgt:"proc" ~fstype:"proc" ~flags:[MS_NOSUID; MS_NOEXEC; MS_NODEV] (); mount_inside ~dir ~src:"/sys" ~tgt:"sys" ~flags:[MS_BIND; MS_REC] (); mount_inside ~dir ~src:"/dev" ~tgt:"dev" ~flags:[MS_BIND; MS_REC] (); mount_inside ~dir ~src:"tmpfs" ~tgt:"dev/shm" ~fstype:"tmpfs" ~flags:[MS_NOSUID; MS_STRICTATIME; MS_NODEV] ~data:"mode=1777" (); mount_inside ~dir ~src:"tmpfs" ~tgt:"run" ~fstype:"tmpfs" ~flags:[MS_NOSUID; MS_STRICTATIME; MS_NODEV] ~data:"mode=755" (); (** for aptitude *) mkdir (Filename.concat dir "/run/lock") let do_chroot dest = Sys.chdir dest; chroot "."; Sys.chdir "/" let read_in_file fmt = Printf.ksprintf (fun file -> let c = open_in file in let v = input_line c in close_in c; v ) fmt let test_userns_availability () = let unpriviledge_userns_clone = "/proc/sys/kernel/unprivileged_userns_clone" in if Sys.file_exists unpriviledge_userns_clone then begin let v = read_in_file "%s" unpriviledge_userns_clone in if v <> "1" then begin Printf.eprintf "This kernel is configured to disable unpriviledge user\ namespace: %s must be 1\n" unpriviledge_userns_clone; exit 1 end end let write_in_file fmt = Printf.ksprintf (fun file -> Printf.ksprintf (fun towrite -> try let cout = open_out file in output_string cout towrite; close_out cout with _ -> Printf.eprintf "Error during write of %s in %s\n" towrite file; exit 1 ) ) fmt let command fmt = Printf.ksprintf (fun cmd -> Sys.command cmd = 0) fmt let command_no_fail ?(error=(fun () -> ())) fmt = Printf.ksprintf (fun cmd -> let c = Sys.command cmd in if c <> 0 then begin Printf.eprintf "Error during: %s\n%!" cmd; error (); exit 1; end ) fmt (** {2 GPG} *) let download_keyid = "0xBAEFF88C22F6E216" let download_keyserver = "hkp://pool.sks-keyservers.net" type gpg_t = | GPGNotAvailable | GPGAvailable of string let gpg_setup ~dir = let command_raise fmt = Printf.ksprintf (fun cmd -> Printf.ksprintf (fun msg -> let c = Sys.command cmd in if c <> 0 then begin Printf.eprintf "%s\n%!" msg; raise Exit end ) ) fmt in try command_raise "which gpg >/dev/null 2>&1" "The program gpg is not present: can't validate download"; let gpg_dir = Filename.concat dir "gpg" in mkdir ~perm:0o700 gpg_dir; command_raise "GNUPGHOME=%S gpg --keyserver %s --recv-keys %s > /dev/null 2>&1;" gpg_dir download_keyserver download_keyid "Can't download gpg key data: can't validate download"; GPGAvailable gpg_dir with Exit -> GPGNotAvailable let gpg_check file = function | GPGNotAvailable -> () | GPGAvailable gpg_dir -> command_no_fail ~error:(fun () -> Printf.eprintf "Invalid signature for %s\n%!" file) "GNUPGHOME=%S gpg --verify %S > /dev/null 2>&1" gpg_dir (file^".asc") (** {2 Download image} *) (** use lxc download template facilities *) let download_compat_level=2 let download_server = "images.linuxcontainers.org" let download ?(quiet=true) fmt = Printf.ksprintf (fun src -> Printf.ksprintf (fun dst -> command "wget -T 30 %s https://%s/%s -O %S %s" (if quiet then "-q" else "") download_server src dst (if quiet then ">/dev/null 2>&1" else "") ) ) fmt let download_index ~dir ~gpg = let index = Filename.concat dir "index" in let url_index = "meta/1.0/index-user" in Printf.printf "Download the index: %!"; if not (download "%s.%i" url_index download_compat_level "%s" index && download "%s.%i.asc" url_index download_compat_level "%s.asc" index) then if not (download "%s" url_index "%s" index && download "%s.asc" url_index "%s.asc" index) then begin Printf.eprintf "error.\n%!"; exit 1; end; gpg_check index gpg; Printf.printf "done.\n%!"; index let semicomma = Str.regexp_string ";" (** return download build and directory url *) let find_image ~distr ~release ~arch index = let cin = open_in index in let rec aux () = match Str.split semicomma (input_line cin) with | [d;r;a;_;db;u] when d = distr && r = release && a = arch -> close_in cin; db,u | _ -> aux () in try aux () with End_of_file -> close_in cin; Printf.eprintf "Can't find url in index corresponding to %s %s %s\n%!" distr release arch; exit 1 let download_rootfs_meta ~dir ~gpg (build_id,url) = let build_id_file = Filename.concat dir "build_id" in let rootfs_tar = Filename.concat dir "rootfs.tar.xz" in let meta_tar = Filename.concat dir "meta.tar.xz" in if not (Sys.file_exists build_id_file) || read_in_file "%s" build_id_file <> build_id then begin if Sys.file_exists build_id_file then Unix.unlink build_id_file; Printf.printf "Downloading rootfs.\n%!"; if not (download ~quiet:false "%s/rootfs.tar.xz" url "%s/rootfs.tar.xz" dir && download "%s/rootfs.tar.xz.asc" url "%s/rootfs.tar.xz.asc" dir && download "%s/meta.tar.xz" url "%s/meta.tar.xz" dir && download "%s/meta.tar.xz.asc" url "%s/meta.tar.xz.asc" dir) then begin Printf.printf "error.\n%!"; exit 1 end; gpg_check rootfs_tar gpg; gpg_check meta_tar gpg; write_in_file "%s" build_id_file "%s" build_id end; rootfs_tar, meta_tar (** {2 User namespace} *) type userns_idmap = | KeepUser (** Put only the current user (uid,gid) as root in the userns *) | IdMap of int * int (** IdMap(id,rangeid): Map [1;rangeid] (uid,gid) in the userns to [id,id+rangeid] (current user is root in the userns) *) let set_usermap idmap pid = let curr_uid = Unix.getuid () in let curr_gid = Unix.getgid () in (* write_in_file "/proc/%i/setgroups" pid "deny"; *) match idmap with | KeepUser -> write_in_file "/proc/%i/uid_map" pid "0 %i 1" curr_uid; write_in_file "/proc/%i/gid_map" pid "0 %i 1" curr_gid; | IdMap(id,rangeid) -> (* Printf.printf "pid: %i, mine: %i\n%!" pid (Unix.getpid ()); *) let error () = ignore (Unix.kill pid 9); exit 1 in command_no_fail ~error "newuidmap %i 0 %i 1 1 %i %i" pid curr_uid id rangeid; command_no_fail ~error "newgidmap %i 0 %i 1 1 %i %i" pid curr_gid id rangeid let goto_child ~exec_in_parent = let fin,fout = Unix.pipe () in match Unix.fork () with | -1 -> Printf.eprintf "Fork failed\n%!"; exit 1 | 0 -> (** child *) Unix.close fout; ignore (Unix.read fin (Bytes.create 1) 0 1); Unix.close fin | pid -> Unix.close fin; (exec_in_parent pid: unit); ignore (Unix.write fout (Bytes.create 1) 0 1); Unix.close fout; let _, status = Unix.waitpid [] pid in match status with | Unix.WEXITED s -> exit s | Unix.WSIGNALED s -> Unix.kill (Unix.getpid ()) s; assert false | Unix.WSTOPPED _ -> assert false let exec_in_child (type a) f = let fin,fout = Unix.pipe () in match Unix.fork () with | -1 -> Printf.eprintf "Fork failed\n%!"; exit 1 | 0 -> (** child *) Unix.close fout; let cin = Unix.in_channel_of_descr fin in let arg = (Marshal.from_channel cin : a) in close_in cin; f arg; exit 0 | pid -> Unix.close fin; let cout = Unix.out_channel_of_descr fout in let call_in_child (arg:a) = Marshal.to_channel cout arg []; close_out cout; let _, status = Unix.waitpid [] pid in match status with | Unix.WEXITED 0 -> () | Unix.WEXITED s -> exit s | Unix.WSIGNALED s -> Unix.kill (Unix.getpid ()) s; assert false | Unix.WSTOPPED _ -> assert false in call_in_child let exec_now_in_child f arg = match Unix.fork () with | -1 -> Printf.eprintf "Fork failed\n%!"; exit 1 | 0 -> (** child *) f arg; exit 0 | pid -> let _, status = Unix.waitpid [] pid in match status with | Unix.WEXITED 0 -> () | Unix.WEXITED s -> exit s | Unix.WSIGNALED s -> Unix.kill (Unix.getpid ()) s; assert false | Unix.WSTOPPED _ -> assert false let just_goto_child () = match Unix.fork () with | -1 -> Printf.eprintf "Fork failed\n%!"; exit 1 | 0 -> (** child *) () | pid -> let _, status = Unix.waitpid [] pid in match status with | Unix.WEXITED s -> exit s | Unix.WSIGNALED s -> Unix.kill (Unix.getpid ()) s; assert false | Unix.WSTOPPED _ -> assert false let go_in_userns idmap = (** the usermap can be set only completely outside the namespace, so we keep a child for doing that when we have a pid completely inside the namespace *) let call_set_usermap = exec_in_child (set_usermap idmap) in unshare [ CLONE_NEWNS; CLONE_NEWIPC; CLONE_NEWPID; CLONE_NEWUTS; CLONE_NEWUSER; ]; (** only the child will be in the new pid namespace, the parent is in an intermediary state not interesting *) goto_child ~exec_in_parent:call_set_usermap (* Printf.printf "User: %i (%i)\n%!" (Unix.getuid ()) (Unix.geteuid ()); *) (* Printf.printf "Pid: %i\n%!" (Unix.getpid ()); *) (* Printf.printf "User: %i (%i)\n%!" (Unix.getuid ()) (Unix.geteuid ()); *) let create_rootfs ~distr ~release ~arch testdir = let rootfsdir = Filename.concat testdir "rootfs" in if not (Sys.file_exists rootfsdir) then begin let gpg = gpg_setup ~dir:testdir in let index = download_index ~dir:testdir ~gpg in let url = find_image ~distr ~release ~arch index in let rootfs, meta = download_rootfs_meta ~dir:testdir ~gpg url in let metadir = Filename.concat testdir "meta" in command_no_fail "rm -rf %S" metadir; mkdir metadir; command_no_fail "tar Jxf %S -C %S" meta metadir; mkdir ~perm:0o750 rootfsdir; let error () = Printf.printf "error\n%!"; command_no_fail "rm -rf %S" rootfsdir in let exclude = Filename.concat metadir "excludes-user" in Printf.printf "Uncompressing rootfs:%!"; if Sys.file_exists exclude then command_no_fail ~error "tar Jxf %S -C %S --exclude-from %S \ --numeric-owner --preserve-permissions --preserve-order --same-owner" rootfs rootfsdir exclude else command_no_fail ~error "tar Jxf %S -C %S" rootfs rootfsdir; Printf.printf "done.\n%!"; end; rootfsdir let idmap, (cmd,arg), testdir, setuid, setgid, arch, distr, release = let open Arg in let testdir = ref "userns_test" in let idmap_id = ref (-1) in let idmap_rangeid = ref (-1) in let command = ref [] in let setuid = ref 0 in let setgid = ref 0 in let arch = ref "amd64" in let distr = ref "debian" in let release = ref "jessie" in parse (align [ "--dir", Set_string testdir, "dir Directory to use for the test \ (dir/rootfs is used for root directory)"; "--idmap", Tuple [Set_int idmap_id;Set_int idmap_rangeid], "id_range maps additionally uid/gid [1;range] to [id;id+range]\n\t\ you need a configured /etc/subuid (man subuid)"; "--uid", Set_int setuid, "uid Execute the command as this uid inside the user namespace"; "--gid", Set_int setgid, "gid Execute the command as this gid inside the user namespace"; "--arch", Set_string arch, "arch Specify the architecture of the image \ (eg. amd64, i386, armel,armhf)"; "--distr", Tuple [Set_string distr; Set_string release], "distr_release Specify the distribution and release of the image \ (eg. centos 6, debian jessie, ubuntu precise, gentoo current)"; "--", Rest (fun s -> command := s::!command), "Instead of running /bin/bash in the usernamespace, run the given command" ]) (fun _ -> raise (Bad "no anonymous option")) "Test for user-namespace: you need linux at least 3.18. \ In the user-namespace the\n\ current user is root. Use LXC download template facilities for getting\n\ the root filesystem."; let idmap = match !idmap_id, !idmap_rangeid with | (-1), _ | _, (-1) -> KeepUser | id, range -> IdMap(id,range) in let command = match List.rev !command with | [] -> "/bin/bash",[|"bash"|] | (cmd::_) as l -> cmd, Array.of_list l in idmap, command, !testdir, !setuid, !setgid, !arch, !distr, !release let () = if Unix.getuid () = 0 then begin Printf.eprintf "This program shouldn't be run as root!\n%!"; exit 1 end; Unix.handle_unix_error begin fun () -> test_userns_availability (); mkdir ~perm:0o750 testdir; go_in_userns idmap; let rootfsdir = create_rootfs ~arch ~distr ~release testdir in command_no_fail "cp /etc/resolv.conf %S" (Filename.concat rootfsdir "etc/resolv.conf"); (** make the mount private and mount basic directories *) mount_base rootfsdir; (** chroot in the directory *) do_chroot rootfsdir; (** group must be changed before uid... *) setresgid setgid setgid setgid; setresuid setuid setuid setuid; let path = (if setuid = 0 then "/usr/local/sbin:/usr/sbin:/sbin:" else "")^ "/usr/local/bin:/usr/bin:/bin" in Unix.putenv "PATH" path; Unix.execv cmd arg end () ocaml-extunix-0.1.6/test/testba.ml000066400000000000000000000206541325120070500171100ustar00rootroot00000000000000 open OUnit open ExtUnix.All.BA module LargeFile = ExtUnix.All.LargeFile.BA let with_unix_error f () = try f () with | Unix.Unix_error(e,f,a) -> let message = Printf.sprintf "Unix_error : %s(%s) : %s" f a (Unix.error_message e) in skip_if (e = Unix.ENOSYS) message; (* libc may raise Not implemented, not an error in extunix *) assert_failure message let require feature = match ExtUnix.All.have feature with | None -> assert false | Some present -> skip_if (not present) (Printf.sprintf "%S is not available" feature) let printer x = x let test_endian_bigarray () = require "unsafe_get_int8"; require "unsafe_get_int16"; require "unsafe_get_int31"; require "unsafe_get_int32"; require "unsafe_get_int64"; require "unsafe_get_uint8"; require "unsafe_get_uint16"; require "unsafe_get_uint31"; require "unsafe_get_uint63"; require "unsafe_get_int63"; require "unsafe_set_uint8"; require "unsafe_set_uint16"; require "unsafe_set_uint31"; require "unsafe_set_int8"; require "unsafe_set_int16"; require "unsafe_set_int31"; require "unsafe_set_int32"; require "unsafe_set_uint63"; require "unsafe_set_int63"; require "unsafe_set_int64"; let module B = BigEndian in let module L = LittleEndian in let src = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout 18 in ignore (List.fold_left (fun off x -> Bigarray.Array1.set src off x; off + 1) 0 [0xFF; 0xFF; 0xFE; 0xDC; 0xFE; 0xDC; 0xFE; 0xDC; 0xBA; 0x98; 0xFE; 0xDC; 0xBA; 0x98; 0x76; 0x54; 0x32; 0x10]); assert_equal (B.get_uint8 src 0) 0xFF; assert_equal (B.get_int8 src 1) (-0x01); assert_equal (B.get_uint16 src 2) 0xFEDC; assert_equal (B.get_int16 src 4) (-0x0124); assert_equal (B.get_int32 src 6) (0xFEDCBA98l); assert_equal (B.get_int64 src 10) (0xFEDCBA9876543210L); assert_equal (L.get_uint8 src 0) 0xFF; assert_equal (L.get_int8 src 1) (-0x01); assert_equal (L.get_uint16 src 2) 0xDCFE; assert_equal (L.get_int16 src 4) (-0x2302); assert_equal (L.get_int32 src 6) (0x98BADCFEl); assert_equal (L.get_int64 src 10) (0x1032547698BADCFEL); assert_equal (B.get_uint31 src 6) (Int64.to_int 0xFEDCBA98L); assert_equal (B.get_int31 src 6) (Int64.to_int 0x7FFFFFFFFEDCBA98L); assert_equal (B.get_int31 src 6) (-0x1234568); assert_equal (B.get_uint63 src 10) (Int64.to_int 0x7EDCBA9876543210L); assert_equal (B.get_int63 src 10) (Int64.to_int 0x7EDCBA9876543210L); assert_equal (B.get_int63 src 10) (Int64.to_int (-0x123456789ABCDF0L)); assert_equal (L.get_uint31 src 6) (Int64.to_int 0x98BADCFEL); assert_equal (L.get_int31 src 6) (Int64.to_int 0x7FFFFFFF98BADCFEL); assert_equal (L.get_int31 src 6) (-0x67452302); assert_equal (L.get_uint63 src 10) (Int64.to_int 0x1032547698BADCFEL); assert_equal (L.get_int63 src 10) (Int64.to_int 0x1032547698BADCFEL); assert_equal (L.get_int63 src 10) (Int64.to_int (-0x6FCDAB8967452302L)); let b = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout 18 in B.set_uint8 b 0 0xFF; B.set_int8 b 1 (-0x01); B.set_uint16 b 2 0xFEDC; B.set_uint16 b 4 (-0x0124); B.set_int32 b 6 (0xFEDCBA98l); B.set_int64 b 10 (0xFEDCBA9876543210L); assert_equal b src; let l = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout 18 in L.set_uint8 l 0 0xFF; L.set_int8 l 1 (-0x01); L.set_uint16 l 2 0xDCFE; L.set_uint16 l 4 (-0x2302); L.set_int32 l 6 (0x98BADCFEl); L.set_int64 l 10 (0x1032547698BADCFEL); assert_equal l src let cmp_buf buf c text = for i = 0 to Bigarray.Array1.dim buf - 1 do if Bigarray.Array1.get buf i <> (int_of_char c) then assert_failure text; done let test_pread_bigarray () = require "unsafe_pread"; let name = Filename.temp_file "extunix" "pread" in let fd = Unix.openfile name [Unix.O_RDWR] 0 in try let size = 65536 in let s = String.make size 'x' in assert_equal (Unix.write_substring fd s 0 size) size; let t = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout size in assert_equal (pread fd 0 t) size; cmp_buf t 'x' "pread read bad data"; assert_equal (single_pread fd 0 t) size; cmp_buf t 'x' "pread read bad data"; let t = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout size in assert_equal (LargeFile.pread fd Int64.zero t) size; cmp_buf t 'x' "Largefile.pread read bad data"; assert_equal (LargeFile.single_pread fd Int64.zero t) size; cmp_buf t 'x' "Largefile.single_pread read bad data"; Unix.close fd; Unix.unlink name with exn -> Unix.close fd; Unix.unlink name; raise exn let cmp_bytes str c text = for i = 0 to Bytes.length str - 1 do if Bytes.get str i <> c then assert_failure text; done let test_pwrite_bigarray () = require "unsafe_pwrite"; let name = Filename.temp_file "extunix" "pwrite" in let fd = Unix.openfile name [Unix.O_RDWR] 0 in let read dst = assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0; let rec loop off = function | 0 -> () | size -> let len = Unix.read fd dst off size in loop (off + len) (size - len) in loop 0 (Bytes.length dst) in try let size = 65536 in (* Must be larger than UNIX_BUFFER_SIZE (16384) *) let s = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout size in for i = 0 to size - 1 do Bigarray.Array1.set s i (int_of_char 'x'); done; assert_equal (pwrite fd 0 s) size; let t = Bytes.make size ' ' in read t; cmp_bytes t 'x' "pwrite wrote bad data"; assert_equal (single_pwrite fd 0 s) size; read t; cmp_bytes t 'x' "single_pwrite wrote bad data"; for i = 0 to size - 1 do Bigarray.Array1.set s i (int_of_char 'y'); done; assert_equal (LargeFile.pwrite fd Int64.zero s) size; read t; cmp_bytes t 'y' "Largefile.pwrite wrote bad data"; assert_equal (LargeFile.single_pwrite fd Int64.zero s) size; read t; cmp_bytes t 'y' "Largefile.single_pwrite wrote bad data"; Unix.close fd; Unix.unlink name with exn -> Unix.close fd; Unix.unlink name; raise exn let test_substr () = let arr = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout 12 in set_substr arr 0 "Hell"; set_substr arr 4 "o World!"; assert_equal (get_substr arr 0 6) "Hello "; assert_equal (get_substr arr 6 6) "World!" let test_read_bigarray () = require "read"; let name = Filename.temp_file "extunix" "read" in let fd = Unix.openfile name [Unix.O_RDWR] 0 in try let size = 65536 in let s = String.make size 'x' in assert_equal (Unix.write_substring fd s 0 size) size; let t = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout size in assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0; assert_equal (read fd t) size; cmp_buf t 'x' "read read bad data"; assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0; assert_equal (single_read fd t) size; cmp_buf t 'x' "single_read read bad data"; Unix.close fd; Unix.unlink name with exn -> Unix.close fd; Unix.unlink name; raise exn let test_write_bigarray () = require "write"; let name = Filename.temp_file "extunix" "write" in let fd = Unix.openfile name [Unix.O_RDWR] 0 in let read dst = assert_equal (Unix.lseek fd 0 Unix.SEEK_SET) 0; let rec loop off = function | 0 -> () | size -> let len = Unix.read fd dst off size in loop (off + len) (size - len) in loop 0 (Bytes.length dst) in try let size = 65536 in (* Must be larger than UNIX_BUFFER_SIZE (16384) *) let s = Bigarray.Array1.create Bigarray.int8_unsigned Bigarray.c_layout size in for i = 0 to size - 1 do Bigarray.Array1.set s i (int_of_char 'x'); done; assert_equal (write fd s) size; let t = Bytes.make size ' ' in read t; cmp_bytes t 'x' "write wrote bad data"; assert_equal (single_write fd s) size; read t; cmp_bytes t 'x' "write wrote bad data"; Unix.close fd; Unix.unlink name with exn -> Unix.close fd; Unix.unlink name; raise exn let () = let wrap test = with_unix_error (fun () -> test (); Gc.compact ()) in let tests = ("tests" >::: [ "endian_bigrray" >:: test_endian_bigarray; "pread_bigarray" >:: test_pread_bigarray; "pwrite_bigarray" >:: test_pwrite_bigarray; "substr" >:: test_substr; "read_bigarray" >:: test_read_bigarray; "write_bigarray" >:: test_write_bigarray; ]) in ignore (run_test_tt_main (test_decorate wrap tests))