From 819d1eab68f37134e7998f725e09d8cbd209fd00 Mon Sep 17 00:00:00 2001
From: Stephane Glondu <steph@glondu.net>
Date: Mon, 17 Jun 2024 15:02:51 +0200
Subject: [PATCH 1/3] Import upstream merge request #24 to add OCaml 5.x
 support

Origin: https://gitlab.com/gerdstolpmann/lib-ocamlnet3/-/merge_requests/24
---
 configure                          |  12 ++
 src/equeue/unixqueue_select.ml     |   2 +-
 src/equeue/unixqueue_util.ml       |   2 +-
 src/equeue/uq_engines.ml           |  53 +------
 src/equeue/uq_engines.mli          |  19 ---
 src/equeue/uq_engines_compat.mli   |   6 -
 src/netgss-system/META.in          |   2 +-
 src/netgss-system/gssapi.c         |  42 +++---
 src/netgss-system/reconfigure      |   2 +-
 src/nethttpd/nethttpd_services.ml  |   4 +-
 src/netplex/Makefile               |   2 +-
 src/netplex/netplex_config.ml      | 190 +++++++++++++++++++++++
 src/netplex/netplex_kit.ml         |   2 +-
 src/netplex/netplex_workload.ml    |   2 +-
 src/netshm/META.in                 |   2 +-
 src/netshm/netshm.ml               |   2 +-
 src/netstring/Makefile             |   4 +-
 src/netstring/netaccel_c.c         |  36 ++---
 src/netstring/netchannels.ml       |  58 ++++----
 src/netstring/netdate.ml           |   5 +-
 src/netstring/nethtml.ml           |   2 +-
 src/netstring/nethttp.ml           |   4 +-
 src/netstring/netmime.ml           |   2 +-
 src/netstring/netmime_string.ml    |   6 +-
 src/netstring/netstring_stream.ml  | 180 ++++++++++++++++++++++
 src/netsys/META.in                 |   2 +-
 src/netsys/netlog.ml               |   2 +-
 src/netsys/netsys_c.c              | 106 ++++++-------
 src/netsys/netsys_c.h              |  18 +--
 src/netsys/netsys_c_clock.c        |  56 +++----
 src/netsys/netsys_c_event.c        |  54 +++----
 src/netsys/netsys_c_fadvise.c      |   4 +-
 src/netsys/netsys_c_fallocate.c    |   8 +-
 src/netsys/netsys_c_ioprio.c       |  18 +--
 src/netsys/netsys_c_locale.c       |  16 +-
 src/netsys/netsys_c_mem.c          | 232 ++++++++++++++++-------------
 src/netsys/netsys_c_multicast.c    |  32 ++--
 src/netsys/netsys_c_outofheap.c    |   2 +-
 src/netsys/netsys_c_poll.c         |  58 ++++----
 src/netsys/netsys_c_sem.c          |  56 +++----
 src/netsys/netsys_c_shm.c          |  10 +-
 src/netsys/netsys_c_spawn.c        |  24 +--
 src/netsys/netsys_c_subprocess.c   |  48 +++---
 src/netsys/netsys_c_syslog.c       |  11 +-
 src/netsys/netsys_c_win32.c        | 178 +++++++++++-----------
 src/netsys/netsys_impl_util.ml     |   2 +-
 src/netsys/netsys_pollset_win32.ml |   6 +-
 src/netsys/netsys_posix.ml         |   8 +-
 src/nettls-gnutls/META.in          |   2 +-
 src/nettls-gnutls/gnutls.c         |  30 ++--
 src/nettls-gnutls/gnutls.descr     |   2 +-
 src/nettls-gnutls/nettle.c         |  12 +-
 src/nettls-gnutls/nettls_gnutls.ml |   2 +-
 src/nettls-gnutls/reconfigure      |   4 +-
 src/rpc-auth-local/rpclocal.c      |  44 +++---
 src/rpc/rpc_client.ml              |   2 +-
 src/rpc/rpc_proxy.ml               |   4 +-
 src/shell/shell.ml                 |   4 +-
 src/shell/shell.mli                |   6 +-
 src/shell/shell_sys.ml             |  27 ++--
 src/shell/shell_sys.mli            |  10 +-
 tools/stubgen.ml                   |  24 +--
 62 files changed, 1038 insertions(+), 727 deletions(-)
 create mode 100644 src/netstring/netstring_stream.ml

diff --git a/configure b/configure
index 20d1c8e..24f10e6 100755
--- a/configure
+++ b/configure
@@ -778,6 +778,18 @@ if [ $compat_pcre -gt 0 ]; then
     compat_pcre_provider="netstring-pcre"
 fi
 
+######################################################################
+# Bigarray
+
+# Since OCaml-5.0.0 "bigarray" is part of the regular stdlib
+v="$(ocamlc -version)"
+case "$v" in
+    [56789]\.*)
+        true ;;
+    *)
+        requires="$requires bigarray" ;;
+esac
+
 ######################################################################
 # Netsys
 
diff --git a/src/equeue/unixqueue_select.ml b/src/equeue/unixqueue_select.ml
index ca55735..dd21085 100644
--- a/src/equeue/unixqueue_select.ml
+++ b/src/equeue/unixqueue_select.ml
@@ -35,7 +35,7 @@ end
 module Fdescr = struct
   type t = Unix.file_descr
 
-  let compare (a:t) (b:t) = Pervasives.compare a b
+  let compare (a:t) (b:t) = compare a b
 
 end;;
 
diff --git a/src/equeue/unixqueue_util.ml b/src/equeue/unixqueue_util.ml
index 42d2f0b..acdbce1 100644
--- a/src/equeue/unixqueue_util.ml
+++ b/src/equeue/unixqueue_util.ml
@@ -179,7 +179,7 @@ let string_of_event ev =
 let fd_cmp =
   match Sys.os_type with
     | "Win32" ->
-	Pervasives.compare
+        compare
     | _ ->
 	(fun (fd1:Unix.file_descr) fd2 ->
 	   (Obj.magic fd1 : int) - (Obj.magic fd2 : int)
diff --git a/src/equeue/uq_engines.ml b/src/equeue/uq_engines.ml
index 819ba82..7e4abf9 100644
--- a/src/equeue/uq_engines.ml
+++ b/src/equeue/uq_engines.ml
@@ -121,7 +121,7 @@ module IntSet =
   Set.Make
     (struct
        type t = int
-       let compare (x:t) (y:t) = Pervasives.compare x y
+       let compare (x:t) (y:t) = compare x y
      end
     )
 
@@ -596,57 +596,6 @@ end
 
 
 
-class ['a] stream_seq_engine x0 (s : ('a -> 'a #engine) Stream.t)  esys =
-object(self)
-  inherit ['a] engine_mixin (`Working 0) esys
-
-  val mutable x = x0
-  val mutable cur_e = aborted_engine esys
-
-  initializer
-    self#next()
-
-  method private next() =
-    match Stream.peek s with
-      | None ->
-	  self # set_state (`Done x)
-      | Some f ->
-	  let _ = Stream.next s in  (* yep, it's "partial" *)
-	  let e =
-	    try (f x :> _ engine)
-	    with error -> const_engine (`Error error) esys in
-	  cur_e <- e;
-	  if is_active e#state then
-	    when_state
-	      ~is_done:(fun x1 -> 
-			  x <- x1;
-			  Unixqueue.epsilon esys self#next
-			    (* avoids stack overflow *)
-		       )
-	      ~is_error:(fun e -> self # set_state (`Error e))
-	      ~is_aborted:(fun () -> self # set_state `Aborted)
-	      ~is_progressing:(fun _ -> self # sseq_count())
-	      e
-	  else
-	    self # set_state e#state
-
-  method abort() =
-    cur_e # abort();
-    self # set_state `Aborted
-
-  method private sseq_count() =
-    match self#state with
-	`Working n ->
-	  self # set_state (`Working (n+1))
-      | _ ->
-	  ()
-end
-
-
-let stream_seq_engine = new stream_seq_engine
-
-
-
 let abort_if_working eng =
   match eng#state with
       `Working _ ->
diff --git a/src/equeue/uq_engines.mli b/src/equeue/uq_engines.mli
index daf4806..9af891a 100644
--- a/src/equeue/uq_engines.mli
+++ b/src/equeue/uq_engines.mli
@@ -354,25 +354,6 @@ val qseq_engine : 'a #engine -> ('a -> 'b #engine) -> 'b engine
       [qseq_engine] should be preferred for recursive chains of engines.
    *)
 
-class ['a] stream_seq_engine : 'a -> ('a -> 'a #engine) Stream.t -> 
-                               Unixqueue.event_system -> ['a] engine
-  (** [let se = new stream_seq_engine x0 s esys]: The constructed engine [se]
-    * fetches functions [f : 'a -> 'a #engine] from the stream [s], and
-    * runs the engines obtained by calling these functions [e = f x] one
-    * after the other. Each function call gets the result of the previous
-    * engine as argument. The first call gets [x0] as argument.
-    *
-    * If one of the engines [e] transitions into an error or aborted state,
-    * [se] will also do that. If [se] is aborted, this is passed down to
-    * the currently running engine [e].
-   *)
-
-
-val stream_seq_engine : 'a -> ('a -> 'a #engine) Stream.t -> 
-                         Unixqueue.event_system -> 'a engine
-  (** Same as function *)
-
-
 class ['a, 'b] sync_engine : 'a #engine -> 'b #engine -> ['a * 'b] engine
   (** This engine runs two engines in parallel, and waits until both
    * are [`Done] (synchronization). The product of the two [`Done] arguments 
diff --git a/src/equeue/uq_engines_compat.mli b/src/equeue/uq_engines_compat.mli
index e301273..23ce536 100644
--- a/src/equeue/uq_engines_compat.mli
+++ b/src/equeue/uq_engines_compat.mli
@@ -105,12 +105,6 @@ val seq_engine : 'a #engine -> ('a -> 'b #engine) -> 'b engine
 class ['a, 'b] qseq_engine : 'a #engine -> ('a -> 'b #engine) -> ['b] engine
 val qseq_engine : 'a #engine -> ('a -> 'b #engine) -> 'b engine
 
-class ['a] stream_seq_engine : 'a -> ('a -> 'a #engine) Stream.t -> 
-                               Unixqueue.event_system -> ['a] engine
-
-val stream_seq_engine : 'a -> ('a -> 'a #engine) Stream.t -> 
-                         Unixqueue.event_system -> 'a engine
-
 class ['a, 'b] sync_engine : 'a #engine -> 'b #engine -> ['a * 'b] engine
 
 val sync_engine : 'a #engine -> 'b #engine -> ('a * 'b) engine
diff --git a/src/netgss-system/META.in b/src/netgss-system/META.in
index 16b54c4..da3d355 100644
--- a/src/netgss-system/META.in
+++ b/src/netgss-system/META.in
@@ -1,5 +1,5 @@
 description = "Ocamlnet - GSSAPI bindings"
-requires = "unix,bigarray,netsys,netstring"
+requires = "unix,netsys,netstring"
 version = "@VERSION@"
 archive(byte) = "netgss-system.cma"
 archive(native) = "netgss-system.cmxa"
diff --git a/src/netgss-system/gssapi.c b/src/netgss-system/gssapi.c
index 62be2a1..3fb1ce9 100644
--- a/src/netgss-system/gssapi.c
+++ b/src/netgss-system/gssapi.c
@@ -59,7 +59,7 @@ static void netgss_free_buffer_contents(long tag, gss_buffer_t buf) {
                 fprintf(stderr, "Netgss: error from gss_release_buffer\n");
         } else {
             if (tag == 1) {
-                stat_free(buf->value);
+                caml_stat_free(buf->value);
             }
         }
     }
@@ -71,13 +71,13 @@ static void netgss_free_buffer_contents(long tag, gss_buffer_t buf) {
 static void netgss_free_buffer(long tag, gss_buffer_t buf) {
     netgss_free_buffer_contents(tag, buf);
     /* The descriptor is always allocated by us: */
-    stat_free(buf);
+    caml_stat_free(buf);
 }
 
 
 static gss_buffer_t netgss_alloc_buffer(void) {
     gss_buffer_t buf;
-    buf = (gss_buffer_t) stat_alloc(sizeof(gss_buffer_desc));
+    buf = (gss_buffer_t) caml_stat_alloc(sizeof(gss_buffer_desc));
     buf->value = NULL;
     buf->length = 0;
     return buf;
@@ -105,10 +105,10 @@ CAMLprim value netgss_buffer_of_string(value s, value pos, value len) {
     gss_buffer_t buf;
     if (Long_val(len) < 0 || Long_val(pos) < 0 ||
         Long_val(pos) > caml_string_length(s) - Long_val(len))
-        invalid_argument("buffer_of_string");
+        caml_invalid_argument("buffer_of_string");
     buf = netgss_alloc_buffer();
     buf->length = Long_val(len);
-    buf->value = stat_alloc(buf->length);
+    buf->value = caml_stat_alloc(buf->length);
     memcpy(buf->value, String_val(s) + Long_val(pos), buf->length);
     return twrap_gss_buffer_t(1, buf);
 }
@@ -155,14 +155,14 @@ static void netgss_free_oid(long tag, gss_OID buf) {
     if (tag == 0 || buf == GSS_C_NO_OID) {
         /* OIDs from the provider are to be considered as read-only */
     } else {
-        stat_free(buf->elements);
-        stat_free(buf);
+        caml_stat_free(buf->elements);
+        caml_stat_free(buf);
     }
 }
 
 
 static gss_OID netgss_alloc_oid(void) {
-    return (gss_OID) stat_alloc(sizeof(gss_OID_desc));
+    return (gss_OID) caml_stat_alloc(sizeof(gss_OID_desc));
 }
 
 
@@ -173,7 +173,7 @@ static gss_OID netgss_copy_oid(gss_OID buf) {
     } else {
         out = netgss_alloc_oid();
         out->length = buf->length;
-        out->elements = stat_alloc(buf->length);
+        out->elements = caml_stat_alloc(buf->length);
         memcpy(out->elements, buf->elements, buf->length);
     }
     return out;
@@ -184,7 +184,7 @@ CAMLprim value netgss_oid_of_string(value s) {
     gss_OID buf;
     buf = netgss_alloc_oid();
     buf->length = caml_string_length(s);
-    buf->elements = stat_alloc(buf->length);
+    buf->elements = caml_stat_alloc(buf->length);
     memcpy(buf->elements, String_val(s), buf->length);
     return twrap_gss_OID(1, buf);
 }
@@ -213,14 +213,14 @@ static void netgss_free_oid_set(long tag, gss_OID_set set) {
         for (k=0; k < set->count; k++) {
             netgss_free_oid(1, set->elements+k);
         }
-        stat_free(set->elements);
-        stat_free(set);
+        caml_stat_free(set->elements);
+        caml_stat_free(set);
     }
 }
 
 
 static gss_OID_set netgss_alloc_oid_set(void) {
-    return (gss_OID_set) stat_alloc(sizeof(gss_OID_set_desc));
+    return (gss_OID_set) caml_stat_alloc(sizeof(gss_OID_set_desc));
 }
 
 
@@ -254,7 +254,7 @@ CAMLprim value netgss_oid_set_of_array(value varg) {
         return twrap_gss_OID_set(1, GSS_C_NO_OID_SET);
     set = netgss_alloc_oid_set();
     set->count = Wosize_val(varg);
-    set->elements = stat_alloc(sizeof(gss_OID) * set->count);
+    set->elements = caml_stat_alloc(sizeof(gss_OID) * set->count);
     for (k=0; k<set->count; k++) {
         v1 = Field(varg, k);
         buf = unwrap_gss_OID(v1);
@@ -308,17 +308,17 @@ CAMLprim value netgss_map_cb(value iaddrty, value iaddr, value aaddrty,
     aaddr_len = caml_string_length(aaddr);
     data_len = caml_string_length(data);
     cb = (gss_channel_bindings_t)
-            stat_alloc(sizeof(struct gss_channel_bindings_struct));
+            caml_stat_alloc(sizeof(struct gss_channel_bindings_struct));
     cb->initiator_addrtype = Int_val(iaddrty);
     cb->initiator_address.length = iaddr_len;
-    cb->initiator_address.value = stat_alloc(iaddr_len);
+    cb->initiator_address.value = caml_stat_alloc(iaddr_len);
     memcpy(cb->initiator_address.value, String_val(iaddr), iaddr_len);
     cb->acceptor_addrtype = Int_val(aaddrty);
     cb->acceptor_address.length = aaddr_len;
-    cb->acceptor_address.value = stat_alloc(aaddr_len);
+    cb->acceptor_address.value = caml_stat_alloc(aaddr_len);
     memcpy(cb->acceptor_address.value, String_val(aaddr), aaddr_len);
     cb->application_data.length = data_len;
-    cb->application_data.value = stat_alloc(data_len);
+    cb->application_data.value = caml_stat_alloc(data_len);
     memcpy(cb->application_data.value, String_val(data), data_len);
     return wrap_gss_channel_bindings_t(cb);
 }
@@ -364,8 +364,8 @@ CAMLprim value netgss_no_oid_set(value dummy) {
 
 static void netgss_free_cb(gss_channel_bindings_t x) {
     if (x != NULL) {
-        stat_free(x->initiator_address.value);
-        stat_free(x->acceptor_address.value);
-        stat_free(x->application_data.value);
+        caml_stat_free(x->initiator_address.value);
+        caml_stat_free(x->acceptor_address.value);
+        caml_stat_free(x->application_data.value);
     }
 }
diff --git a/src/netgss-system/reconfigure b/src/netgss-system/reconfigure
index 66d315f..5f67287 100755
--- a/src/netgss-system/reconfigure
+++ b/src/netgss-system/reconfigure
@@ -133,7 +133,7 @@ echo "Generating stubs"
 
 rm -f config_checks.sh
 echo "$ ocaml -I ../../tools gssapi.descr" >>$log
-ocaml -I ../../tools gssapi.descr || exit 1
+ocaml -I +str -I ../../tools gssapi.descr || exit 1
 
 . ./config_checks.sh
 
diff --git a/src/nethttpd/nethttpd_services.ml b/src/nethttpd/nethttpd_services.ml
index 9a338b2..b365d33 100644
--- a/src/nethttpd/nethttpd_services.ml
+++ b/src/nethttpd/nethttpd_services.ml
@@ -107,10 +107,10 @@ object(self)
       try
 	let req_name = env # input_header_field "Host" in
 	let (req_host, req_port_opt) = split_host_port req_name in
-	let req_host = String.lowercase req_host in
+        let req_host = String.lowercase_ascii req_host in
 	let req_port = match req_port_opt with Some p -> p | None -> 80 in  (* CHECK *)
 	List.find
-	  (fun (n,p) -> (n = "*" || String.lowercase n = req_host) && 
+          (fun (n,p) -> (n = "*" || String.lowercase_ascii n = req_host) &&
 	                (p = 0 || p = req_port))
 	  host.server_names
       with
diff --git a/src/netplex/Makefile b/src/netplex/Makefile
index 1c1526e..415640b 100644
--- a/src/netplex/Makefile
+++ b/src/netplex/Makefile
@@ -36,7 +36,7 @@ include $(TOP_DIR)/Makefile.rules
 
 netplex-admin$(EXEC_SUFFIX): netplex.cma netplex_admin.cmo
 	$(OCAMLC) -o netplex-admin -custom \
-	        -package "bytes unix bigarray str" -linkpkg \
+	        -package "bytes unix str" -linkpkg \
 		netsys_oothr.cma netsys.cma netstring.cma equeue.cma \
 		rpc.cma netplex.cma netplex_admin.cmo
 
diff --git a/src/netplex/netplex_config.ml b/src/netplex/netplex_config.ml
index 9ed5460..2b2eb39 100644
--- a/src/netplex/netplex_config.ml
+++ b/src/netplex/netplex_config.ml
@@ -1,5 +1,195 @@
 (* $Id$ *)
 
+module Stream = Netstring_stream
+module Genlex = struct
+type token =
+    Kwd of string
+  | Ident of string
+  | Int of int
+  | Float of float
+  | String of string
+  | Char of char
+
+(* The string buffering machinery *)
+
+let initial_buffer = Bytes.create 32
+
+let buffer = ref initial_buffer
+let bufpos = ref 0
+
+let reset_buffer () = buffer := initial_buffer; bufpos := 0
+
+let store c =
+  if !bufpos >= Bytes.length !buffer then begin
+    let newbuffer = Bytes.create (2 * !bufpos) in
+    Bytes.blit !buffer 0 newbuffer 0 !bufpos;
+    buffer := newbuffer
+  end;
+  Bytes.set !buffer !bufpos c;
+  incr bufpos
+
+let get_string () =
+  let s = Bytes.sub_string !buffer 0 !bufpos in buffer := initial_buffer; s
+
+(* The lexer *)
+
+let make_lexer keywords =
+  let kwd_table = Hashtbl.create 17 in
+  List.iter (fun s -> Hashtbl.add kwd_table s (Kwd s)) keywords;
+  let ident_or_keyword id =
+    try Hashtbl.find kwd_table id with
+      Not_found -> Ident id
+  and keyword_or_error c =
+    let s = String.make 1 c in
+    try Hashtbl.find kwd_table s with
+      Not_found -> raise (Stream.Error ("Illegal character " ^ s))
+  in
+  let rec next_token (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some (' ' | '\010' | '\013' | '\009' | '\026' | '\012') ->
+        Stream.junk strm__; next_token strm__
+    | Some ('A'..'Z' | 'a'..'z' | '_' | '\192'..'\255' as c) ->
+        Stream.junk strm__;
+        let s = strm__ in reset_buffer (); store c; ident s
+    | Some
+        ('!' | '%' | '&' | '$' | '#' | '+' | '/' | ':' | '<' | '=' | '>' |
+         '?' | '@' | '\\' | '~' | '^' | '|' | '*' as c) ->
+        Stream.junk strm__;
+        let s = strm__ in reset_buffer (); store c; ident2 s
+    | Some ('0'..'9' as c) ->
+        Stream.junk strm__;
+        let s = strm__ in reset_buffer (); store c; number s
+    | Some '\'' ->
+        Stream.junk strm__;
+        let c =
+          try char strm__ with
+            Stream.Failure -> raise (Stream.Error "")
+        in
+        begin match Stream.peek strm__ with
+          Some '\'' -> Stream.junk strm__; Some (Char c)
+        | _ -> raise (Stream.Error "")
+        end
+    | Some '\"' ->
+        Stream.junk strm__;
+        let s = strm__ in reset_buffer (); Some (String (string s))
+    | Some '-' -> Stream.junk strm__; neg_number strm__
+    | Some '(' -> Stream.junk strm__; maybe_comment strm__
+    | Some c -> Stream.junk strm__; Some (keyword_or_error c)
+    | _ -> None
+  and ident (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some
+        ('A'..'Z' | 'a'..'z' | '\192'..'\255' | '0'..'9' | '_' | '\'' as c) ->
+        Stream.junk strm__; let s = strm__ in store c; ident s
+    | _ -> Some (ident_or_keyword (get_string ()))
+  and ident2 (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some
+        ('!' | '%' | '&' | '$' | '#' | '+' | '-' | '/' | ':' | '<' | '=' |
+         '>' | '?' | '@' | '\\' | '~' | '^' | '|' | '*' as c) ->
+        Stream.junk strm__; let s = strm__ in store c; ident2 s
+    | _ -> Some (ident_or_keyword (get_string ()))
+  and neg_number (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some ('0'..'9' as c) ->
+        Stream.junk strm__;
+        let s = strm__ in reset_buffer (); store '-'; store c; number s
+    | _ -> let s = strm__ in reset_buffer (); store '-'; ident2 s
+  and number (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some ('0'..'9' as c) ->
+        Stream.junk strm__; let s = strm__ in store c; number s
+    | Some '.' ->
+        Stream.junk strm__; let s = strm__ in store '.'; decimal_part s
+    | Some ('e' | 'E') ->
+        Stream.junk strm__; let s = strm__ in store 'E'; exponent_part s
+    | _ -> Some (Int (int_of_string (get_string ())))
+  and decimal_part (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some ('0'..'9' as c) ->
+        Stream.junk strm__; let s = strm__ in store c; decimal_part s
+    | Some ('e' | 'E') ->
+        Stream.junk strm__; let s = strm__ in store 'E'; exponent_part s
+    | _ -> Some (Float (float_of_string (get_string ())))
+  and exponent_part (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some ('+' | '-' as c) ->
+        Stream.junk strm__; let s = strm__ in store c; end_exponent_part s
+    | _ -> end_exponent_part strm__
+  and end_exponent_part (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some ('0'..'9' as c) ->
+        Stream.junk strm__; let s = strm__ in store c; end_exponent_part s
+    | _ -> Some (Float (float_of_string (get_string ())))
+  and string (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some '\"' -> Stream.junk strm__; get_string ()
+    | Some '\\' ->
+        Stream.junk strm__;
+        let c =
+          try escape strm__ with
+            Stream.Failure -> raise (Stream.Error "")
+        in
+        let s = strm__ in store c; string s
+    | Some c -> Stream.junk strm__; let s = strm__ in store c; string s
+    | _ -> raise Stream.Failure
+  and char (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some '\\' ->
+        Stream.junk strm__;
+        begin try escape strm__ with
+          Stream.Failure -> raise (Stream.Error "")
+        end
+    | Some c -> Stream.junk strm__; c
+    | _ -> raise Stream.Failure
+  and escape (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some 'n' -> Stream.junk strm__; '\n'
+    | Some 'r' -> Stream.junk strm__; '\r'
+    | Some 't' -> Stream.junk strm__; '\t'
+    | Some ('0'..'9' as c1) ->
+        Stream.junk strm__;
+        begin match Stream.peek strm__ with
+          Some ('0'..'9' as c2) ->
+            Stream.junk strm__;
+            begin match Stream.peek strm__ with
+              Some ('0'..'9' as c3) ->
+                Stream.junk strm__;
+                Char.chr
+                  ((Char.code c1 - 48) * 100 + (Char.code c2 - 48) * 10 +
+                     (Char.code c3 - 48))
+            | _ -> raise (Stream.Error "")
+            end
+        | _ -> raise (Stream.Error "")
+        end
+    | Some c -> Stream.junk strm__; c
+    | _ -> raise Stream.Failure
+  and maybe_comment (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some '*' ->
+        Stream.junk strm__; let s = strm__ in comment s; next_token s
+    | _ -> Some (keyword_or_error '(')
+  and comment (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some '(' -> Stream.junk strm__; maybe_nested_comment strm__
+    | Some '*' -> Stream.junk strm__; maybe_end_comment strm__
+    | Some _ -> Stream.junk strm__; comment strm__
+    | _ -> raise Stream.Failure
+  and maybe_nested_comment (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some '*' -> Stream.junk strm__; let s = strm__ in comment s; comment s
+    | Some _ -> Stream.junk strm__; comment strm__
+    | _ -> raise Stream.Failure
+  and maybe_end_comment (strm__ : _ Stream.t) =
+    match Stream.peek strm__ with
+      Some ')' -> Stream.junk strm__; ()
+    | Some '*' -> Stream.junk strm__; maybe_end_comment strm__
+    | Some _ -> Stream.junk strm__; comment strm__
+    | _ -> raise Stream.Failure
+  in
+  fun input -> Stream.from (fun _count -> next_token input)
+end
+
 open Netplex_types
 open Genlex
 open Printf
diff --git a/src/netplex/netplex_kit.ml b/src/netplex/netplex_kit.ml
index 87d661f..66503e2 100644
--- a/src/netplex/netplex_kit.ml
+++ b/src/netplex/netplex_kit.ml
@@ -89,7 +89,7 @@ end
 
 module PTYPE = struct
   type t = parallelization_type
-  let compare (x:t) (y:t) = Pervasives.compare x y
+  let compare (x:t) (y:t) = compare x y
 end
 
 module PSet = Set.Make(PTYPE)
diff --git a/src/netplex/netplex_workload.ml b/src/netplex/netplex_workload.ml
index 1484b92..4362128 100644
--- a/src/netplex/netplex_workload.ml
+++ b/src/netplex/netplex_workload.ml
@@ -119,7 +119,7 @@ end
 
 module ContId = struct
   type t = container_id
-  let (compare : t -> t -> int) = Pervasives.compare
+  let (compare : t -> t -> int) = compare
 end
 
 
diff --git a/src/netshm/META.in b/src/netshm/META.in
index 2bb9c2a..1d2ffad 100644
--- a/src/netshm/META.in
+++ b/src/netshm/META.in
@@ -1,6 +1,6 @@
 version = "@VERSION@"
 description = "Ocamlnet - Shared memory"
-requires = "unix netsys bigarray"
+requires = "unix netsys"
 archive(byte) = "netshm.cma"
 archive(native) = "netshm.cmxa"
 archive(native,gprof) = "netshm.p.cmxa"
diff --git a/src/netshm/netshm.ml b/src/netshm/netshm.ml
index 974e5ee..d22ad53 100644
--- a/src/netshm/netshm.ml
+++ b/src/netshm/netshm.ml
@@ -133,7 +133,7 @@ open Printf
 
 module Int = struct
   type t = int
-  let compare = (Pervasives.compare : int -> int -> int)
+  let compare = (compare : int -> int -> int)
 end
 
 module IntMap = Map.Make(Int)
diff --git a/src/netstring/Makefile b/src/netstring/Makefile
index 08b81e2..514f3cf 100644
--- a/src/netstring/Makefile
+++ b/src/netstring/Makefile
@@ -3,7 +3,7 @@ TOP_DIR=../..
 include $(TOP_DIR)/Makefile.conf
 
 OBJECTS  = netconst.cmo netstring_str.cmo netbuffer.cmo netunichar.cmo \
-	   netaux.cmo netstring_tstring.cmo \
+	   netaux.cmo netstring_tstring.cmo netstring_stream.cmo \
            netchannels.cmo netchannels_crypto.cmo netsockaddr.cmo \
 	   netdb.cmo netmappings_asn1.cmo netmappings.cmo netconversion.cmo \
            netulex.cmo netencoding.cmo netstream.cmo netdate.cmo \
@@ -28,7 +28,7 @@ OBJECTS  = netconst.cmo netstring_str.cmo netbuffer.cmo netunichar.cmo \
 
 PKGNAME  = netstring
 
-REQUIRES += $(REGEXP_PROVIDER_MAKE) bigarray
+REQUIRES += $(REGEXP_PROVIDER_MAKE)
 INCLUDES += $(INC_NETSYS)
 INCLUDES += -I ../netstring-pcre
 
diff --git a/src/netstring/netaccel_c.c b/src/netstring/netaccel_c.c
index b7c4ffd..d80d1f7 100644
--- a/src/netstring/netaccel_c.c
+++ b/src/netstring/netaccel_c.c
@@ -25,7 +25,7 @@ value netstring_int_blit_ml (value src, value srcpos,
 	srcpos_c+len_c > Wosize_val(src) ||
 	destpos_c < 0 ||
 	destpos_c+len_c > Wosize_val(dest))
-	invalid_argument("Netaccel.int_blit");
+	caml_invalid_argument("Netaccel.int_blit");
     
     if (src != dest || destpos_c <= srcpos_c) {
 	for (i=0; i<len_c; i++) {
@@ -59,7 +59,7 @@ value netstring_int_series_ml (value src, value srcpos,
 	srcpos_c+len_c > Wosize_val(src) ||
 	destpos_c < 0 ||
 	destpos_c+len_c > Wosize_val(dest))
-	invalid_argument("Netaccel.int_series");
+	caml_invalid_argument("Netaccel.int_series");
 
     s = n_c;
     for (i=0; i<len_c; i++) {
@@ -99,9 +99,9 @@ value netstring_read_iso88591_ml (value maxcode, value enc,
     slice_char_len = Wosize_val(slice_char);
 
     if (slice_char_len != Wosize_val(slice_blen)) 
-	invalid_argument("Netaccel.read_iso88591");
-    if (p_in_c < 0 || l_in_c < 0 || p_in_c + l_in_c > string_length(s_in)) 
-	invalid_argument("Netaccel.read_iso88591");
+	caml_invalid_argument("Netaccel.read_iso88591");
+    if (p_in_c < 0 || l_in_c < 0 || p_in_c + l_in_c > caml_string_length(s_in)) 
+	caml_invalid_argument("Netaccel.read_iso88591");
 
     m = l_in_c;
     if (slice_char_len < m) m = slice_char_len;
@@ -110,12 +110,12 @@ value netstring_read_iso88591_ml (value maxcode, value enc,
 	ch = Byte_u(s_in, p_in_c+k);
 	if (ch > maxcode_c) {
 	    Field(slice_char, k) = Val_long(-1);
-	    r = alloc_tuple(3);
+	    r = caml_alloc_tuple(3);
 	    Store_field(r, 0, Val_long(k));
 	    Store_field(r, 1, Val_long(k));
 	    Store_field(r, 2, enc);
-	    raise_with_arg(*caml_named_value("Netconversion.Malformed_code_read"),
-			   r);
+	    caml_raise_with_arg(*caml_named_value("Netconversion.Malformed_code_read"),
+                                r);
 	};
 	Field(slice_char, k) = Val_int((signed int) ch);
     };
@@ -124,7 +124,7 @@ value netstring_read_iso88591_ml (value maxcode, value enc,
 	Field(slice_char, m) = Val_long(-1);
     };
 
-    r = alloc_tuple(3);
+    r = caml_alloc_tuple(3);
     Store_field(r, 0, Val_long(m));
     Store_field(r, 1, Val_long(m));
     Store_field(r, 2, enc);
@@ -164,9 +164,9 @@ value netstring_read_utf8_ml (value is_java,
     slice_char_len = Wosize_val(slice_char);
 
     if (slice_char_len != Wosize_val(slice_blen)) 
-	invalid_argument("Netaccel.read_utf8");
-    if (p_in_c < 0 || l_in_c < 0 || p_in_c + l_in_c > string_length(s_in)) 
-	invalid_argument("Netaccel.read_utf8");
+	caml_invalid_argument("Netaccel.read_utf8");
+    if (p_in_c < 0 || l_in_c < 0 || p_in_c + l_in_c > caml_string_length(s_in)) 
+	caml_invalid_argument("Netaccel.read_utf8");
 
     p = p_in_c;
     p_max = p_in_c + l_in_c;
@@ -249,21 +249,21 @@ value netstring_read_utf8_ml (value is_java,
 	Field(slice_char, n_ret) = Val_long(-1);
     }
 
-    r = alloc_tuple(3);
+    r = caml_alloc_tuple(3);
     Store_field(r, 0, Val_long(n_ret));
     Store_field(r, 1, Val_long(p-p_in_c));
-    Store_field(r, 2, hash_variant("Enc_utf8"));
+    Store_field(r, 2, caml_hash_variant("Enc_utf8"));
 
     CAMLreturn(r);
 
  malformed_code:
     Field(slice_char, n) = Val_long(-1);
-    r = alloc_tuple(3);
+    r = caml_alloc_tuple(3);
     Store_field(r, 0, Val_long(n));
     Store_field(r, 1, Val_long(p-p_in_c));
-    Store_field(r, 2, hash_variant("Enc_utf8"));
-    raise_with_arg(*caml_named_value("Netconversion.Malformed_code_read"),
-		   r);
+    Store_field(r, 2, caml_hash_variant("Enc_utf8"));
+    caml_raise_with_arg(*caml_named_value("Netconversion.Malformed_code_read"),
+                        r);
 
     /* Cannot reach this point! */
     CAMLreturn(Val_unit);
diff --git a/src/netstring/netchannels.ml b/src/netstring/netchannels.ml
index e916b70..bd62390 100644
--- a/src/netstring/netchannels.ml
+++ b/src/netstring/netchannels.ml
@@ -213,45 +213,45 @@ object (self)
     if closed then self # complain_closed();
     try
       if len=0 then raise Sys_blocked_io;
-      let n = Pervasives.input ch buf pos len in
+      let n = input ch buf pos len in
       if n=0 then raise End_of_file else n
     with
 	Sys_blocked_io -> 0
 
   method really_input buf pos len = 
     if closed then self # complain_closed();
-    Pervasives.really_input ch buf pos len 
+    really_input ch buf pos len
 
   method really_input_string len = 
     if closed then self # complain_closed();
     #ifdef HAVE_BYTES
-      Pervasives.really_input_string ch len 
+      really_input_string ch len
     #else
       let buf = String.create len in
-      Pervasives.really_input ch buf 0 len;
+      really_input ch buf 0 len;
       buf
     #endif
 
   method input_char () =
     if closed then self # complain_closed();
-    Pervasives.input_char ch 
+    input_char ch
 
   method input_line () =
     if closed then self # complain_closed();
-    Pervasives.input_line ch 
+    input_line ch
 
   method input_byte () =
     if closed then self # complain_closed();
-    Pervasives.input_byte ch 
+    input_byte ch
 
   method close_in () =
     if not closed then (
-      Pervasives.close_in ch; closed <- true; onclose()
+      close_in ch; closed <- true; onclose()
     )
 
   method pos_in =
     if closed then self # complain_closed();
-    Pervasives.pos_in ch 
+    pos_in ch
 end
 ;;
 
@@ -999,17 +999,17 @@ object (self)
 
   method output buf pos len =
     if closed then self # complain_closed();
-    (* Pervasives.output does not support non-blocking I/O directly.
+    (* output does not support non-blocking I/O directly.
      * Work around it:
      *)
-    let p0 = Pervasives.pos_out ch in
+    let p0 = pos_out ch in
     try 
-      Pervasives.output ch buf pos len;
+      output ch buf pos len;
       errflag := false;
       len
     with
       | Sys_blocked_io ->
-	  let p1 = Pervasives.pos_out ch in
+	  let p1 = pos_out ch in
 	  errflag := false;
 	  p1 - p0
       | error ->
@@ -1018,35 +1018,35 @@ object (self)
 
   method really_output buf pos len =
     if closed then self # complain_closed();
-    monitored (Pervasives.output ch buf pos) len
+    monitored (output ch buf pos) len
 
   method really_output_string buf pos len =
     if closed then self # complain_closed();
     #ifdef HAVE_BYTES
-      monitored (Pervasives.output_substring ch buf pos) len
+      monitored (output_substring ch buf pos) len
     #else
-      monitored (Pervasives.output ch buf pos) len
+      monitored (output ch buf pos) len
     #endif
 
   method output_char c =
     if closed then self # complain_closed();
-    monitored (Pervasives.output_char ch) c
+    monitored (output_char ch) c
 
   method output_string s =
     if closed then self # complain_closed();
-    monitored (Pervasives.output_string ch) s
+    monitored (output_string ch) s
 
   method output_bytes s =
     if closed then self # complain_closed();
     #ifdef HAVE_BYTES
-      monitored (Pervasives.output_bytes ch) s
+      monitored (output_bytes ch) s
     #else
-      monitored (Pervasives.output_string ch) s
+      monitored (output_string ch) s
     #endif
 
   method output_byte b =
     if closed then self # complain_closed();
-    monitored (Pervasives.output_byte ch) b
+    monitored (output_byte ch) b
 
   method output_buffer b =
     if closed then self # complain_closed();
@@ -1061,7 +1061,7 @@ object (self)
 
   method flush() =
     if closed then self # complain_closed();
-    monitored Pervasives.flush ch
+    monitored flush ch
 
   method close_out() =
     if not closed then (
@@ -1071,9 +1071,9 @@ object (self)
 	     exception handler
 	   *)
 	  if !errflag then
-	    Pervasives.close_out_noerr ch
+	    close_out_noerr ch
 	  else
-	    Pervasives.close_out ch; 
+	    close_out ch; 
 	  closed <- true; 
 	with
 	  | error ->
@@ -1082,7 +1082,7 @@ object (self)
 		"Netchannels.output_channel: \
                    Suppressed error in close_out: %s - backtrace: %s"
 		(Netexn.to_string error) bt;
-	      Pervasives.close_out_noerr ch;
+	      close_out_noerr ch;
 	      closed <- true; 
       );
       onclose()
@@ -1090,7 +1090,7 @@ object (self)
 
   method pos_out = 
     if closed then self # complain_closed();
-    Pervasives.pos_out ch
+    pos_out ch
 
 end
 ;;
@@ -1844,7 +1844,7 @@ object (self)
                   Suppressed error in close_out: %s - backtrace: %s"
 		(Netexn.to_string error) bt;
       );
-      Pervasives.close_in transch_in;
+      close_in transch_in;
       trans # close_out();      (* closes transch_out *)
       out # close_out();
       closed := true
@@ -1859,7 +1859,7 @@ object (self)
     need_clear <- true;
     let len = trans # pos_out in
     trans # flush();
-    Pervasives.seek_in transch_in 0;
+    seek_in transch_in 0;
     let trans' = new input_channel transch_in in
     ( try 
         out # output_channel ~len trans';
@@ -1876,7 +1876,7 @@ object (self)
   method private clear() =
     (* delete the contents of the file *)
     (* First empty the file and reset the output channel: *)
-    Pervasives.seek_out transch_out 0;
+    seek_out transch_out 0;
     Unix.ftruncate (Unix.descr_of_out_channel transch_out) 0;
     (* Renew the input channel. We create a new channel to avoid problems
      * with the internal buffer of the channel.
diff --git a/src/netstring/netdate.ml b/src/netstring/netdate.ml
index 21a8c00..d67b95a 100644
--- a/src/netstring/netdate.ml
+++ b/src/netstring/netdate.ml
@@ -5,6 +5,7 @@
 
 (* Thanks to Nicolas George for contributing the parsing and format code *)
 
+module Stream = Netstring_stream
 open Printf
 
 (* Calculate local zone offset in minutes *)
@@ -1035,11 +1036,11 @@ let mk_date ?localzone ?zone ?nanos ~fmt t =
   format ~fmt (create ?localzone ?zone ?nanos t)
 
 let mk_mail_date ?localzone ?zone t =
-  format "%a, %d %b %Y %H:%M:%S %z" (create ?localzone ?zone t)
+  format ~fmt:"%a, %d %b %Y %H:%M:%S %z" (create ?localzone ?zone t)
 ;;
 
 let mk_usenet_date ?localzone ?zone t =
-  format "%A, %d-%b-%y %H:%M:%S %z" (create ?localzone ?zone t)
+  format ~fmt:"%A, %d-%b-%y %H:%M:%S %z" (create ?localzone ?zone t)
 ;;
 
 let mk_internet_date ?localzone ?zone ?(digits=0) t =
diff --git a/src/netstring/nethtml.ml b/src/netstring/nethtml.ml
index b79e48b..d8004dd 100644
--- a/src/netstring/nethtml.ml
+++ b/src/netstring/nethtml.ml
@@ -283,7 +283,7 @@ let hashtbl_from_alist l =
 
 module S = struct
   type t = string
-  let compare = (Pervasives.compare : string -> string -> int)
+  let compare = (compare : string -> string -> int)
 end
 
 module Strset = Set.Make(S);;
diff --git a/src/netstring/nethttp.ml b/src/netstring/nethttp.ml
index d3417a8..7ea987e 100644
--- a/src/netstring/nethttp.ml
+++ b/src/netstring/nethttp.ml
@@ -3,6 +3,8 @@
  * Nethttp: Basic definitions for the HTTP protocol
  *)
 
+module Stream = Netstring_stream
+
 type protocol_version = 
     int * int
 type protocol_attribute =
@@ -1009,7 +1011,7 @@ module Header = struct
       snd
       (List.stable_sort
 	 (fun (q1, tok_param1) (q2, tok_param2) ->
-	    Pervasives.compare q2 q1)
+           compare q2 q1)
 	 (List.filter
 	    (fun (q, tok_param) ->
 	       q > 0.0)
diff --git a/src/netstring/netmime.ml b/src/netstring/netmime.ml
index 70235f8..035c5aa 100644
--- a/src/netstring/netmime.ml
+++ b/src/netstring/netmime.ml
@@ -71,7 +71,7 @@ module CI : sig  (* case-insensitive strings *)
 end = struct
   type t = string
   let compare (a_ci:t) (b_ci:t) =
-    Pervasives.compare a_ci b_ci
+    compare a_ci b_ci
   let make s = STRING_LOWERCASE s
 end
 
diff --git a/src/netstring/netmime_string.ml b/src/netstring/netmime_string.ml
index 4f0e8b5..cdc83e1 100644
--- a/src/netstring/netmime_string.ml
+++ b/src/netstring/netmime_string.ml
@@ -979,7 +979,7 @@ let scan_structured_value s specials options =
       | _, t ->
 	  t :: collect scn
   in
-  let scn = create_mime_scanner specials options s in
+  let scn = create_mime_scanner ~specials ~scan_options:options s in
   collect scn
 ;;
 
@@ -995,7 +995,7 @@ let specials_rfc2045 =
 let scan_encoded_text_value s =
   let specials = [ ' '; '\t'; '\r'; '\n'; '('; '['; '"' ] in
   let options =  [ Recognize_encoded_words ] in
-  let scn = create_mime_scanner specials options s in
+  let scn = create_mime_scanner ~specials ~scan_options:options s in
   
   let rec collect () =
     match scan_token scn with
@@ -1955,7 +1955,7 @@ let scan_multipart_body s ~start_pos ~end_pos ~boundary =
   
 
 let scan_multipart_body_and_decode s ~start_pos:i0 ~end_pos:i1 ~boundary =
-  let parts = scan_multipart_body s i0 i1 boundary in
+  let parts = scan_multipart_body s ~start_pos:i0 ~end_pos:i1 ~boundary in
   List.map
     (fun (params, value) ->
        let encoding =
diff --git a/src/netstring/netstring_stream.ml b/src/netstring/netstring_stream.ml
new file mode 100644
index 0000000..2e1118a
--- /dev/null
+++ b/src/netstring/netstring_stream.ml
@@ -0,0 +1,180 @@
+(* The Stream module from latest OCaml-4. It is no longer available in
+     OCaml-5.
+ *)
+type 'a t = 'a cell option
+ and 'a cell = { mutable count : int; mutable data : 'a data }
+ and 'a data =
+   Sempty
+ | Scons of 'a * 'a data
+ | Sapp of 'a data * 'a data
+ | Slazy of 'a data Lazy.t
+ | Sgen of 'a gen
+ | Sbuffio : buffio -> char data
+ and 'a gen = { mutable curr : 'a option option; func : int -> 'a option }
+ and buffio =
+   { ic : in_channel; buff : bytes; mutable len : int; mutable ind : int }
+
+exception Failure
+exception Error of string
+
+let count = function
+  | None -> 0
+  | Some { count } -> count
+let data = function
+  | None -> Sempty
+  | Some { data } -> data
+
+let fill_buff b =
+  b.len <- input b.ic b.buff 0 (Bytes.length b.buff); b.ind <- 0
+
+let rec get_data : type v. int -> v data -> v data = fun count d -> match d with
+   (* Returns either Sempty or Scons(a, _) even when d is a generator
+      or a buffer. In those cases, the item a is seen as extracted from
+   the generator/buffer.
+   The count parameter is used for calling `Sgen-functions'.  *)
+   Sempty | Scons (_, _) -> d
+ | Sapp (d1, d2) ->
+     begin match get_data count d1 with
+       Scons (a, d11) -> Scons (a, Sapp (d11, d2))
+     | Sempty -> get_data count d2
+     | _ -> assert false
+     end
+ | Sgen {curr = Some None} -> Sempty
+ | Sgen ({curr = Some(Some a)} as g) ->
+     g.curr <- None; Scons(a, d)
+ | Sgen g ->
+     begin match g.func count with
+       None -> g.curr <- Some(None); Sempty
+     | Some a -> Scons(a, d)
+         (* Warning: anyone using g thinks that an item has been read *)
+     end
+ | Sbuffio b ->
+     if b.ind >= b.len then fill_buff b;
+     if b.len == 0 then Sempty else
+       let r = Bytes.unsafe_get b.buff b.ind in
+       (* Warning: anyone using g thinks that an item has been read *)
+       b.ind <- succ b.ind; Scons(r, d)
+ | Slazy f -> get_data count (Lazy.force f)
+
+
+let rec peek_data : type v. v cell -> v option = fun s ->
+ (* consult the first item of s *)
+ match s.data with
+   Sempty -> None
+ | Scons (a, _) -> Some a
+ | Sapp (_, _) ->
+     begin match get_data s.count s.data with
+       Scons(a, _) as d -> s.data <- d; Some a
+     | Sempty -> None
+     | _ -> assert false
+     end
+ | Slazy f -> s.data <- (Lazy.force f); peek_data s
+ | Sgen {curr = Some a} -> a
+ | Sgen g -> let x = g.func s.count in g.curr <- Some x; x
+ | Sbuffio b ->
+     if b.ind >= b.len then fill_buff b;
+     if b.len == 0 then begin s.data <- Sempty; None end
+     else Some (Bytes.unsafe_get b.buff b.ind)
+
+
+let peek = function
+  | None -> None
+  | Some s -> peek_data s
+
+
+let rec junk_data : type v. v cell -> unit = fun s ->
+  match s.data with
+    Scons (_, d) -> s.count <- (succ s.count); s.data <- d
+  | Sgen ({curr = Some _} as g) -> s.count <- (succ s.count); g.curr <- None
+  | Sbuffio b ->
+      if b.ind >= b.len then fill_buff b;
+      if b.len == 0 then s.data <- Sempty
+      else (s.count <- (succ s.count); b.ind <- succ b.ind)
+  | _ ->
+      match peek_data s with
+        None -> ()
+      | Some _ -> junk_data s
+
+
+let junk = function
+  | None -> ()
+  | Some data -> junk_data data
+
+let rec nget_data n s =
+  if n <= 0 then [], s.data, 0
+  else
+    match peek_data s with
+      Some a ->
+        junk_data s;
+        let (al, d, k) = nget_data (pred n) s in a :: al, Scons (a, d), succ k
+    | None -> [], s.data, 0
+
+
+let npeek_data n s =
+  let (al, d, len) = nget_data n s in
+  s.count <- (s.count - len);
+  s.data <- d;
+  al
+
+
+let npeek n = function
+  | None -> []
+  | Some d -> npeek_data n d
+
+let next s =
+  match peek s with
+    Some a -> junk s; a
+  | None -> raise Failure
+
+
+let empty s =
+  match peek s with
+    Some _ -> raise Failure
+  | None -> ()
+
+
+let iter f strm =
+  let rec do_rec () =
+    match peek strm with
+      Some a -> junk strm; ignore(f a); do_rec ()
+    | None -> ()
+  in
+  do_rec ()
+
+
+(* Stream building functions *)
+
+let from f = Some {count = 0; data = Sgen {curr = None; func = f}}
+
+let of_list l =
+  Some {count = 0; data = List.fold_right (fun x l -> Scons (x, l)) l Sempty}
+
+
+let of_string s =
+  let count = ref 0 in
+  from (fun _ ->
+    (* We cannot use the index passed by the [from] function directly
+       because it returns the current stream count, with absolutely no
+       guarantee that it will start from 0. For example, in the case
+       of [Stream.icons 'c' (Stream.from_string "ab")], the first
+       access to the string will be made with count [1] already.
+    *)
+    let c = !count in
+    if c < String.length s
+    then (incr count; Some s.[c])
+    else None)
+
+
+let of_bytes s =
+  let count = ref 0 in
+  from (fun _ ->
+    let c = !count in
+    if c < Bytes.length s
+    then (incr count; Some (Bytes.get s c))
+    else None)
+
+
+let of_channel ic =
+  Some {count = 0;
+        data = Sbuffio {ic = ic; buff = Bytes.create 4096; len = 0; ind = 0}}
+
diff --git a/src/netsys/META.in b/src/netsys/META.in
index d081348..f18ea56 100644
--- a/src/netsys/META.in
+++ b/src/netsys/META.in
@@ -1,5 +1,5 @@
 description = "Ocamlnet - OS-specific functions"
-requires = "bytes,unix,bigarray"
+requires = "bytes,unix"
 version = "@VERSION@"
 archive(byte) = "netsys_oothr.cma netsys.cma"
 archive(native) = "netsys_oothr.cmxa netsys.cmxa"
diff --git a/src/netsys/netlog.ml b/src/netsys/netlog.ml
index edb237c..de93ea2 100644
--- a/src/netsys/netlog.ml
+++ b/src/netsys/netlog.ml
@@ -129,7 +129,7 @@ let channel_logger ch max_lev lev msg =
     
 
 let current_logger =
-  ref(channel_logger Pervasives.stderr `Debug)
+  ref(channel_logger stderr `Debug)
 
 
 let log lev msg =
diff --git a/src/netsys/netsys_c.c b/src/netsys/netsys_c.c
index 31b7f5d..af89111 100644
--- a/src/netsys/netsys_c.c
+++ b/src/netsys/netsys_c.c
@@ -12,13 +12,13 @@ CAMLprim value netsys_int64_of_file_descr(value fd) {
 #ifdef _WIN32
     switch (Descr_kind_val(fd)) {
     case KIND_HANDLE:
-	return copy_int64((intnat) (Handle_val(fd)));
+	return caml_copy_int64((intnat) (Handle_val(fd)));
     case KIND_SOCKET:
-	return copy_int64((intnat) (Socket_val(fd)));
+	return caml_copy_int64((intnat) (Socket_val(fd)));
     }
-    return copy_int64(0);
+    return caml_copy_int64(0);
 #else
-    return copy_int64(Long_val(fd));
+    return caml_copy_int64(Long_val(fd));
 #endif
 }
 
@@ -45,13 +45,13 @@ CAMLprim value netsys_unix_error_of_code(value n) {
     win32_maperr(e);
     e = errno;
 #endif
-    return(unix_error_of_code(e));
+    return(caml_unix_error_of_code(e));
 }
 
 CAMLprim value netsys_get_nonblock(value fd)
 {
 #ifdef _WIN32
-    invalid_argument("Netsys_posix.get_nonblcok not avaiable");
+    caml_invalid_argument("Netsys_posix.get_nonblcok not avaiable");
 #else
     int r;
 
@@ -67,7 +67,7 @@ CAMLprim value netsys__exit (value n) {
     _exit(Int_val(n));
     return Val_int(0);
 #else
-    invalid_argument("Netsys._exit not available");
+    caml_invalid_argument("Netsys._exit not available");
 #endif
 }
 
@@ -76,7 +76,7 @@ CAMLprim value netsys_sysconf_open_max (value unit) {
 #ifdef HAVE_SYSCONF
     return Val_long(sysconf(_SC_OPEN_MAX));
 #else
-    invalid_argument("Netsys.sysconf_open_max not available");
+    caml_invalid_argument("Netsys.sysconf_open_max not available");
 #endif
 }
 
@@ -89,7 +89,7 @@ CAMLprim value netsys_getpgid (value pid) {
     if (pgid == -1) uerror("getpgid", Nothing);
     return Val_int(pgid);
 #else
-    invalid_argument("Netsys.getpgid not available");
+    caml_invalid_argument("Netsys.getpgid not available");
 #endif
 }
 
@@ -102,7 +102,7 @@ CAMLprim value netsys_setpgid (value pid, value pgid) {
     if (r == -1) uerror("setpgid", Nothing);
     return Val_int(0);
 #else
-    invalid_argument("Netsys.setpgid not available");
+    caml_invalid_argument("Netsys.setpgid not available");
 #endif
 }
 
@@ -115,7 +115,7 @@ CAMLprim value netsys_tcgetpgrp (value fd) {
     if (pgid == -1) uerror("tcgetpgrp", Nothing);
     return Val_int(pgid);
 #else
-    invalid_argument("Netsys.tcgetpgrp not available");
+    caml_invalid_argument("Netsys.tcgetpgrp not available");
 #endif
 }
 
@@ -128,7 +128,7 @@ CAMLprim value netsys_tcsetpgrp (value fd, value pgid) {
     if (r == -1) uerror("tcsetpgrp", Nothing);
     return Val_int(0);
 #else
-    invalid_argument("Netsys.tcsetpgrp not available");
+    caml_invalid_argument("Netsys.tcsetpgrp not available");
 #endif
 }
 
@@ -137,10 +137,10 @@ CAMLprim value netsys_ctermid (value unit) {
 #ifdef HAVE_POSIX_TTY
     char *s;
     s = NULL;
-    return copy_string(ctermid(s));
+    return caml_copy_string(ctermid(s));
     /* ctermid is always successful; however it can return an empty string */
 #else
-    invalid_argument("Netsys.ctermid not available");
+    caml_invalid_argument("Netsys.ctermid not available");
 #endif
 }
 
@@ -151,9 +151,9 @@ CAMLprim value netsys_ttyname (value fd) {
 
     s = ttyname(Int_val(fd));
     if ( s == NULL ) uerror("ttyname", Nothing);
-    return copy_string(s);
+    return caml_copy_string(s);
 #else
-    invalid_argument("Netsys.ttyname not available");
+    caml_invalid_argument("Netsys.ttyname not available");
 #endif
 }
 
@@ -166,7 +166,7 @@ CAMLprim value netsys_getsid (value pid) {
     if ( sid == -1 )  uerror("getsid", Nothing);
     return Val_int(sid);
 #else
-    invalid_argument("Netsys.getsid not available");
+    caml_invalid_argument("Netsys.getsid not available");
 #endif
 }
 
@@ -179,7 +179,7 @@ CAMLprim value netsys_setreuid(value ruid, value euid) {
     if (r == -1) uerror("setreuid", Nothing);
     return Val_int(0);
 #else
-    invalid_argument("Netsys.setreuid not available");
+    caml_invalid_argument("Netsys.setreuid not available");
 #endif
 }
 
@@ -192,7 +192,7 @@ CAMLprim value netsys_setregid(value rgid, value egid) {
     if (r == -1) uerror("setregid", Nothing);
     return Val_int(0);
 #else
-    invalid_argument("Netsys.setregid not available");
+    caml_invalid_argument("Netsys.setregid not available");
 #endif
 }
 
@@ -210,7 +210,7 @@ CAMLprim value netsys_initgroups(value user, value gid) {
 
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.initgroups not available");
+    caml_invalid_argument("Netsys_posix.initgroups not available");
 #endif
 }
 
@@ -223,7 +223,7 @@ CAMLprim value netsys_fsync(value fd) {
 	uerror("fsync", Nothing);
     return Val_unit;
 #else
-    invalid_argument("Netsys.fsync not available");
+    caml_invalid_argument("Netsys.fsync not available");
 #endif
 }
 
@@ -240,7 +240,7 @@ CAMLprim value netsys_fdatasync(value fd) {
 	uerror("fdatasync", Nothing);
     return Val_unit;
 #else
-    invalid_argument("Netsys.fdatasync not available");
+    caml_invalid_argument("Netsys.fdatasync not available");
 #endif
 }
 
@@ -249,7 +249,7 @@ CAMLprim value netsys_fchdir(value fd) {
     if (fchdir(Int_val(fd)) == -1) uerror("fchdir", Nothing);
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.fchdir not available");
+    caml_invalid_argument("Netsys_posix.fchdir not available");
 #endif
 }
 
@@ -260,11 +260,11 @@ CAMLprim value netsys_fdopendir(value fd)
   value res;
   d = fdopendir(Int_val(fd));
   if (d == (DIR *) NULL) uerror("fdopendir", Nothing);
-  res = alloc_small(1, Abstract_tag);
+  res = caml_alloc_small(1, Abstract_tag);
   DIR_Val(res) = d;
   return res;
 #else
-  invalid_argument("Netsys_posix.fdopendir not available");
+  caml_invalid_argument("Netsys_posix.fdopendir not available");
 #endif
 }
 
@@ -281,12 +281,12 @@ CAMLprim value netsys_realpath (value name)    /* POSIX.1-2001 */
 	uerror("realpath", Nothing);
     }
     else {
-	name_out = copy_string(name_out_s);
+	name_out = caml_copy_string(name_out_s);
 	free(name_out_s);
     }
     return name_out;
 #else
-    invalid_argument("Netsys_posix.realpath not available");
+    caml_invalid_argument("Netsys_posix.realpath not available");
 #endif
 }
 
@@ -299,7 +299,7 @@ CAMLprim value netsys_grantpt (value fd)    /* POSIX.1-2001 */
     if ( e < 0 ) uerror("grantpt", Nothing);
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.granpt not available");
+    caml_invalid_argument("Netsys_posix.granpt not available");
 #endif
 }
 
@@ -312,7 +312,7 @@ CAMLprim value netsys_unlockpt (value fd)    /* POSIX.1-2001 */
     if ( e < 0 ) uerror("unlockpt", Nothing);
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.unlockpt not available");
+    caml_invalid_argument("Netsys_posix.unlockpt not available");
 #endif
 }
 
@@ -324,9 +324,9 @@ CAMLprim value netsys_ptsname (value fd)    /* POSIX.1-2001 */
 
     s = ptsname(Int_val(fd));
     if ( s == NULL ) uerror("ptsname", Nothing);
-    return copy_string(s);
+    return caml_copy_string(s);
 #else
-    invalid_argument("Netsys_posix.ptsname not available");
+    caml_invalid_argument("Netsys_posix.ptsname not available");
 #endif
 }
 
@@ -348,7 +348,7 @@ CAMLprim value netsys_posix_openpt(value noctty)     /* POSIX.1-2001 */
     if (fd == -1) uerror("openpt", Nothing);
     return Val_int(fd);
 #else
-    invalid_argument("Netsys_posix.posix_openpt not available");
+    caml_invalid_argument("Netsys_posix.posix_openpt not available");
 #endif
 }
 
@@ -356,7 +356,7 @@ CAMLprim value netsys_posix_openpt(value noctty)     /* POSIX.1-2001 */
 CAMLprim value netsys_mknod (value name, value perm, value nt)
 {
 #ifdef _WIN32
-    invalid_argument("Netsys_posix.mknod not available");
+    caml_invalid_argument("Netsys_posix.mknod not available");
 #else
     mode_t m;
     dev_t d;
@@ -473,8 +473,8 @@ CAMLprim value netsys_openat(value dirfd, value path, value flags, value perm)
     char * p;
 
     /* shamelessly copied from ocaml distro */
-    cv_flags = convert_flag_list(flags, open_flag_table);
-    clo_flags = convert_flag_list(flags, open_cloexec_table);
+    cv_flags = caml_convert_flag_list(flags, open_flag_table);
+    clo_flags = caml_convert_flag_list(flags, open_cloexec_table);
     if (clo_flags & CLOEXEC)
         cloexec = 1;
     else if (clo_flags & KEEPEXEC)
@@ -484,12 +484,12 @@ CAMLprim value netsys_openat(value dirfd, value path, value flags, value perm)
 #if defined(O_CLOEXEC)
     if (cloexec) cv_flags |= O_CLOEXEC;
 #endif
-    p = stat_alloc(string_length(path) + 1);
+    p = caml_stat_alloc(caml_string_length(path) + 1);
     strcpy(p, String_val(path));
-    enter_blocking_section();
+    caml_enter_blocking_section();
     ret = openat(Int_val(dirfd), p, cv_flags, Int_val(perm));
-    leave_blocking_section();
-    stat_free(p);
+    caml_leave_blocking_section();
+    caml_stat_free(p);
     if (ret == -1) uerror("openat", path);
 #if !defined(O_CLOEXEC)
     {
@@ -500,7 +500,7 @@ CAMLprim value netsys_openat(value dirfd, value path, value flags, value perm)
 #endif
     CAMLreturn (Val_int(ret));
 #else
-    invalid_argument("Netsys_posix.openat not available");
+    caml_invalid_argument("Netsys_posix.openat not available");
 #endif
 }
 
@@ -517,15 +517,15 @@ CAMLprim value netsys_faccessat(value dirfd, value path, value perms,
 {
 #ifdef HAVE_AT
     int ret, cv_perms, cv_flags;
-    cv_perms = convert_flag_list(perms, access_permission_table);
-    cv_flags = convert_flag_list(flags, at_flags_table);
+    cv_perms = caml_convert_flag_list(perms, access_permission_table);
+    cv_flags = caml_convert_flag_list(flags, at_flags_table);
     cv_flags &= (AT_EACCESS | AT_SYMLINK_NOFOLLOW);
     ret = faccessat(Int_val(dirfd), String_val(path), cv_perms, cv_flags);
     if (ret == -1)
 	uerror("faccessat", path);
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.faccessat not available");
+    caml_invalid_argument("Netsys_posix.faccessat not available");
 #endif
 }
 
@@ -537,7 +537,7 @@ CAMLprim value netsys_mkdirat(value dirfd, value path, value perm)
 	uerror("mkdirat", path);
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.mkdirat not available");
+    caml_invalid_argument("Netsys_posix.mkdirat not available");
 #endif
 }
 
@@ -551,7 +551,7 @@ CAMLprim value netsys_renameat(value olddirfd, value oldpath,
 	uerror("renameat", oldpath);
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.renameat not available");
+    caml_invalid_argument("Netsys_posix.renameat not available");
 #endif
 }
 
@@ -561,14 +561,14 @@ CAMLprim value netsys_linkat(value olddirfd, value oldpath,
 {
 #ifdef HAVE_AT
     int cv_flags;
-    cv_flags = convert_flag_list(flags, at_flags_table);
+    cv_flags = caml_convert_flag_list(flags, at_flags_table);
     cv_flags &= AT_SYMLINK_FOLLOW;  /* only allowed flag here */
     if (linkat(Int_val(olddirfd), String_val(oldpath),
 	       Int_val(newdirfd), String_val(newpath), cv_flags) == -1)
 	uerror("linkat", oldpath);
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.linkat not available");
+    caml_invalid_argument("Netsys_posix.linkat not available");
 #endif
 }
 
@@ -577,13 +577,13 @@ CAMLprim value netsys_unlinkat(value dirfd, value path, value flags)
 {
 #ifdef HAVE_AT
     int cv_flags;
-    cv_flags = convert_flag_list(flags, at_flags_table);
+    cv_flags = caml_convert_flag_list(flags, at_flags_table);
     cv_flags &= AT_REMOVEDIR;  /* only allowed flag here */
     if (unlinkat(Int_val(dirfd), String_val(path), cv_flags) == -1)
 	uerror("unlinkat", path);
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.unlinkat not available");
+    caml_invalid_argument("Netsys_posix.unlinkat not available");
 #endif
 }
 
@@ -597,7 +597,7 @@ CAMLprim value netsys_symlinkat(value oldpath,
 	uerror("symlinkat", oldpath);
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.symlinkat not available");
+    caml_invalid_argument("Netsys_posix.symlinkat not available");
 #endif
 }
 
@@ -609,7 +609,7 @@ CAMLprim value netsys_mkfifoat(value dirfd, value path, value mode)
 	uerror("mkfifoat", path);
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.mkfifoat not available");
+    caml_invalid_argument("Netsys_posix.mkfifoat not available");
 #endif
 }
 
@@ -622,8 +622,8 @@ CAMLprim value netsys_readlinkat(value dirfd, value path)
   len = readlinkat(Int_val(dirfd), String_val(path), buffer, sizeof(buffer)-1);
   if (len == -1) uerror("readlinkat", path);
   buffer[len] = '\0';
-  return copy_string(buffer);
+  return caml_copy_string(buffer);
 #else
-    invalid_argument("Netsys_posix.readlinkat not available");
+    caml_invalid_argument("Netsys_posix.readlinkat not available");
 #endif
 }
diff --git a/src/netsys/netsys_c.h b/src/netsys/netsys_c.h
index d4d5a1a..cf6ff27 100644
--- a/src/netsys/netsys_c.h
+++ b/src/netsys/netsys_c.h
@@ -69,6 +69,7 @@
 #include "caml/callback.h"
 #include "caml/bigarray.h"
 #include "caml/version.h"
+#include "caml/unixsupport.h"
 
 #ifndef Bytes_val
 #define Bytes_val(x) String_val(x)
@@ -171,25 +172,8 @@ extern void caml_darken (value, value *);
 /* From unixsupport.h                                                 */
 /**********************************************************************/
 
-#define Nothing ((value) 0)
-
 #ifdef _WIN32
-#include "caml/unixsupport.h"
 #define netsysw32_win_alloc_handle win_alloc_handle
-#else
-
-/* POSIX */
-
-/* Since OCaml 3.10 there is unixsupport.h, and we could also include
-   this file.
-*/
-
-extern value unix_error_of_code (int errcode);
-extern void unix_error (int errcode, char * cmdname, value arg) Noreturn;
-extern void uerror (char * cmdname, value arg) Noreturn;
-
-#define DIR_Val(v) *((DIR **) &Field(v, 0))
-
 #endif
 
 /**********************************************************************/
diff --git a/src/netsys/netsys_c_clock.c b/src/netsys/netsys_c_clock.c
index c510928..1436aa0 100644
--- a/src/netsys/netsys_c_clock.c
+++ b/src/netsys/netsys_c_clock.c
@@ -23,10 +23,10 @@ static void make_timespec(value tspair, struct timespec *ts) {
 
     d = Double_val(Field(tspair,0));
     if (!isfinite(d) || d < 0 || d > LONG_MAX-1)
-	failwith("Netsys_posix: time value out of range");
+	caml_failwith("Netsys_posix: time value out of range");
     n = Long_val(Field(tspair,1));
     if (n < 0 || n > 999999999)
-	failwith("Netsys_posix: time value out of range");
+	caml_failwith("Netsys_posix: time value out of range");
     i = floor(d);
     r = floor((d - i) * 1E9);
     r = r + n;
@@ -44,7 +44,7 @@ static void make_timespec(value tspair, struct timespec *ts) {
 static value alloc_timespec_pair(double sec, long nsec) {
     CAMLparam0();
     CAMLlocal1(tsout);
-    tsout = alloc(2,0);
+    tsout = caml_alloc(2,0);
     Store_field(tsout, 0, caml_copy_double(sec));
     Store_field(tsout, 1, Val_long(nsec));
     CAMLreturn(tsout);
@@ -65,7 +65,7 @@ static void clockid_val(value c, clockid_t *out) {
 	    *out = CLOCK_MONOTONIC;
 	    break;
 #else
-	    failwith("Netsys_posix: CLOCK_MONOTONIC is not supported");
+	    caml_failwith("Netsys_posix: CLOCK_MONOTONIC is not supported");
 #endif
 	}
     }
@@ -98,11 +98,11 @@ CAMLprim value netsys_nanosleep(value tspair, value tsref)
     tsout = alloc_timespec_pair(t_out.tv_sec, t_out.tv_nsec);
     Store_field(tsref, 0, tsout);
 
-    if (r == -1) unix_error(e, "nanosleep", Nothing);
+    if (r == -1) caml_unix_error(e, "nanosleep", Nothing);
    
     CAMLreturn(Val_unit);
 #else
-    invalid_argument("Netsys_posix.nanosleep not available");
+    caml_invalid_argument("Netsys_posix.nanosleep not available");
 #endif
 }
 
@@ -118,13 +118,13 @@ CAMLprim value netsys_clock_gettime(value clock)
 
     clockid_val(clock, &c);
     r = clock_gettime(c, &ts);
-    if (r == -1) uerror("clock_gettime", Nothing);
+    if (r == -1) caml_uerror("clock_gettime", Nothing);
     
     tsout = alloc_timespec_pair(ts.tv_sec, ts.tv_nsec);
     
     CAMLreturn(tsout);
 #else
-    invalid_argument("Netsys_posix.clock_gettime not available");
+    caml_invalid_argument("Netsys_posix.clock_gettime not available");
 #endif
 }
 
@@ -141,11 +141,11 @@ CAMLprim value netsys_clock_settime(value clock, value tspair)
     make_timespec(tspair, &ts);
 
     r = clock_settime(c, &ts);
-    if (r == -1) uerror("clock_settime", Nothing);
+    if (r == -1) caml_uerror("clock_settime", Nothing);
     
     CAMLreturn(Val_unit);
 #else
-    invalid_argument("Netsys_posix.clock_settime not available");
+    caml_invalid_argument("Netsys_posix.clock_settime not available");
 #endif
 }
 
@@ -162,13 +162,13 @@ CAMLprim value netsys_clock_getres(value clock)
     clockid_val(clock, &c);
 
     r = clock_getres(c, &ts);
-    if (r == -1) uerror("clock_getres", Nothing);
+    if (r == -1) caml_uerror("clock_getres", Nothing);
     
     tsout = alloc_timespec_pair(ts.tv_sec, ts.tv_nsec);
     
     CAMLreturn(tsout);
 #else
-    invalid_argument("Netsys_posix.clock_getres not available");
+    caml_invalid_argument("Netsys_posix.clock_getres not available");
 #endif
 }
 
@@ -182,7 +182,7 @@ CAMLprim value netsys_clock_getcpuclockid(value pid) {
     char *s;
 
     r = clock_getcpuclockid(Long_val(pid), &c);
-    if (r != 0) unix_error(r, "clock_getcpuclockid", Nothing);
+    if (r != 0) caml_unix_error(r, "clock_getcpuclockid", Nothing);
 
     v = caml_alloc_string(sizeof(clockid_t));
     s = String_val(v);
@@ -191,7 +191,7 @@ CAMLprim value netsys_clock_getcpuclockid(value pid) {
 
     CAMLreturn(v);
 #else
-    invalid_argument("Netsys_posix.clock_getcpuclockid not available");
+    caml_invalid_argument("Netsys_posix.clock_getcpuclockid not available");
 #endif
 }
 
@@ -263,7 +263,7 @@ CAMLprim value netsys_timer_create(value clock, value texp) {
 	    sev.sigev_value.sival_ptr = ne;
 	    break;
 #else
-	    failwith("Netsys_posix.timer_create: unsupported type of timer");
+	    caml_failwith("Netsys_posix.timer_create: unsupported type of timer");
 #endif
 #endif
 	}
@@ -280,7 +280,7 @@ CAMLprim value netsys_timer_create(value clock, value texp) {
 	    sev.sigev_value.sival_ptr = ne;
 	    break;
 #else
-	    failwith("Netsys_posix.timer_create: unsupported type of timer");
+	    caml_failwith("Netsys_posix.timer_create: unsupported type of timer");
 #endif
 	case 1:
 	    /* TEXP_SIGNAL */
@@ -294,7 +294,7 @@ CAMLprim value netsys_timer_create(value clock, value texp) {
     switch (tcase) {
     case 0:
 	code = timer_create(c, &sev, &tm);
-	if (code == -1) uerror("timer_create", Nothing);
+	if (code == -1) caml_uerror("timer_create", Nothing);
 	v = caml_alloc_string(sizeof(timer_t));
 	memcpy(Bytes_val(v), (char *) &tm, sizeof(timer_t));
 	v_timer = caml_alloc(1, 0);
@@ -313,7 +313,7 @@ CAMLprim value netsys_timer_create(value clock, value texp) {
     Store_field(v, 1, v_event);
     CAMLreturn(v);
 #else
-    invalid_argument("Netsys_posix.timer_create not available");
+    caml_invalid_argument("Netsys_posix.timer_create not available");
 #endif
 }
 
@@ -346,7 +346,7 @@ CAMLprim value netsys_timer_settime(value timer, value abstime,
 			     Bool_val(abstime) ? TIMER_ABSTIME : 0,
 			     &it,
 			     NULL);
-	if (code == -1) uerror("timer_settime", Nothing);
+	if (code == -1) caml_uerror("timer_settime", Nothing);
 	break;
 #ifdef HAVE_TIMERFD
     case 1:
@@ -356,14 +356,14 @@ CAMLprim value netsys_timer_settime(value timer, value abstime,
 			       Bool_val(abstime) ? TFD_TIMER_ABSTIME : 0,
 			       &it,
 			       NULL);
-	if (code == -1) uerror("timerfd_settime", Nothing);
+	if (code == -1) caml_uerror("timerfd_settime", Nothing);
 	break;
 #endif
     };
 
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.timer_settime not available");
+    caml_invalid_argument("Netsys_posix.timer_settime not available");
 #endif
 }
 
@@ -382,14 +382,14 @@ CAMLprim value netsys_timer_gettime(value timer) {
 	/* POSIX timer */
 	extract_timer(Field(Field(timer, 0), 0), &tm);
 	code = timer_gettime(tm, &it);
-	if (code == -1) uerror("timer_gettime", Nothing);
+	if (code == -1) caml_uerror("timer_gettime", Nothing);
 	break;
 #ifdef HAVE_TIMERFD
     case 1:
 	/* TIMERFD */
 	fd = Int_val(Field(Field(timer, 0), 0));
 	code = timerfd_gettime(fd, &it);
-	if (code == -1) uerror("timerfd_gettime", Nothing);
+	if (code == -1) caml_uerror("timerfd_gettime", Nothing);
 	break;
 #endif
     };
@@ -398,7 +398,7 @@ CAMLprim value netsys_timer_gettime(value timer) {
 			    it.it_value.tv_nsec);
     return r;
 #else
-    invalid_argument("Netsys_posix.timer_gettime not available");
+    caml_invalid_argument("Netsys_posix.timer_gettime not available");
 #endif
 }
 
@@ -413,7 +413,7 @@ CAMLprim value netsys_timer_delete(value timer) {
 	/* POSIX timer */
 	extract_timer(Field(Field(timer, 0), 0), &tm);
 	code = timer_delete(tm);
-	if (code == -1) uerror("timer_delete", Nothing);
+	if (code == -1) caml_uerror("timer_delete", Nothing);
 	break;
 #ifdef HAVE_TIMERFD
     case 1:
@@ -424,7 +424,7 @@ CAMLprim value netsys_timer_delete(value timer) {
     }
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.timer_delete not available");
+    caml_invalid_argument("Netsys_posix.timer_delete not available");
 #endif
 }
 
@@ -435,9 +435,9 @@ CAMLprim value netsys_timer_event(value timer) {
 	return Field(timer,1);
     }
     else {
-	failwith("Netsys_posix.timer_event: timer is not connected with event");
+	caml_failwith("Netsys_posix.timer_event: timer is not connected with event");
     }
 #else
-    invalid_argument("Netsys_posix.timer_delete not available");
+    caml_invalid_argument("Netsys_posix.timer_delete not available");
 #endif
 }
diff --git a/src/netsys/netsys_c_event.c b/src/netsys/netsys_c_event.c
index 6a2ce45..939831d 100644
--- a/src/netsys/netsys_c_event.c
+++ b/src/netsys/netsys_c_event.c
@@ -187,24 +187,24 @@ CAMLprim value netsys_create_not_event(value allow_user_add)
     p->allow_user_add = Bool_val(allow_user_add);
 #ifdef HAVE_PTHREAD
     x = pthread_mutex_init(&(p->mutex), NULL);
-    if (x != 0) unix_error(x, "pthread_mutex_init", Nothing);
+    if (x != 0) caml_unix_error(x, "pthread_mutex_init", Nothing);
 #endif
 
 #ifdef HAVE_EVENTFD
     p->type = NE_EVENTFD;
     x = eventfd(0, 0);
-    if (x == -1) uerror("eventfd", Nothing);
+    if (x == -1) caml_uerror("eventfd", Nothing);
     p->fd1 = x;
     x = fcntl(p->fd1, F_SETFD, FD_CLOEXEC);
     if (x == -1) {
 	e = errno;
 	close(p->fd1);
-	unix_error(e, "fcntl", Nothing);
+	caml_unix_error(e, "fcntl", Nothing);
     }
 #else
     p->type = NE_PIPE;
     x = pipe(pipefd);
-    if (x == -1) uerror("pipe", Nothing);
+    if (x == -1) caml_uerror("pipe", Nothing);
     p->fd1 = pipefd[0];
     p->fd2 = pipefd[1];
     x = fcntl(p->fd1, F_SETFD, FD_CLOEXEC);
@@ -212,19 +212,19 @@ CAMLprim value netsys_create_not_event(value allow_user_add)
 	e = errno;
 	close(p->fd1);
 	close(p->fd2);
-	unix_error(e, "fcntl", Nothing);
+	caml_unix_error(e, "fcntl", Nothing);
     }
     x = fcntl(p->fd2, F_SETFD, FD_CLOEXEC);
     if (x == -1) {
 	e = errno;
 	close(p->fd1);
 	close(p->fd2);
-	unix_error(e, "fcntl", Nothing);
+	caml_unix_error(e, "fcntl", Nothing);
     }
 #endif
     return r;
 #else
-    invalid_argument("Netsys_posix.create_event not available");
+    caml_invalid_arggument("Netsys_posix.create_event not available");
 #endif
 }
 
@@ -246,13 +246,13 @@ CAMLprim value netsys_not_event_timerfd(int clockid)
 
     p->type = NE_TIMERFD;
     x = timerfd_create(clockid, 0);
-    if (x == -1) uerror("timerfd_create", Nothing);
+    if (x == -1) caml_uerror("timerfd_create", Nothing);
     p->fd1 = x;
     x = fcntl(p->fd1, F_SETFD, FD_CLOEXEC);
     if (x == -1) {
 	e = errno;
 	close(p->fd1);
-	unix_error(e, "fcntl", Nothing);
+	caml_unix_error(e, "fcntl", Nothing);
     }
     return r;
 }
@@ -268,17 +268,17 @@ CAMLprim value netsys_set_nonblock_not_event(value nev)
     ne = *(Not_event_val(nev));
 
     if (ne->fd1 == -1) 
-	failwith("Netsys_posix.set_nonblock_event: already destroyed");
+	caml_failwith("Netsys_posix.set_nonblock_event: already destroyed");
     
     x = fcntl(ne->fd1, F_GETFL, 0);
-    if (x == -1) uerror("fcntl", Nothing);
+    if (x == -1) caml_uerror("fcntl", Nothing);
 
     x = fcntl(ne->fd1, F_SETFL, x | O_NONBLOCK);
-    if (x == -1) uerror("fcntl", Nothing);
+    if (x == -1) caml_uerror("fcntl", Nothing);
 
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.set_nonblock_event not available");
+    caml_invalid_argument("Netsys_posix.set_nonblock_event not available");
 #endif
 }
 
@@ -290,10 +290,10 @@ CAMLprim value netsys_get_not_event_fd_nodup(value nev)
     int fd, code;
     ne = *(Not_event_val(nev));
     if (ne->fd1 == -1) 
-	failwith("Netsys_posix.get_event_fd_nodup: already destroyed");
+	caml_failwith("Netsys_posix.get_event_fd_nodup: already destroyed");
     return Val_int(ne->fd1);
 #else
-    invalid_argument("Netsys_posix.get_event_fd not available");
+    caml_invalid_argument("Netsys_posix.get_event_fd not available");
 #endif
 }
 
@@ -306,11 +306,11 @@ int netsys_return_not_event_fd(value nev)
     int fd;
     ne = *(Not_event_val(nev));
     if (ne->fd1 == -1) 
-	failwith("Netsys_posix.get_event_fd: already destroyed");
+	caml_failwith("Netsys_posix.get_event_fd: already destroyed");
     fd = ne->fd1;
     return fd;
 #else
-    invalid_argument("Netsys_posix.get_event_fd not available");
+    caml_invalid_argument("Netsys_posix.get_event_fd not available");
 #endif
 }
 
@@ -350,15 +350,15 @@ CAMLprim value netsys_set_not_event(value nev)
     CAMLparam1(nev);
     ne = *(Not_event_val(nev));
     if (ne->fd1 == -1) 
-	failwith("Netsys_posix.set_event: already destroyed");
+	caml_failwith("Netsys_posix.set_event: already destroyed");
     if (!ne->allow_user_add)
-	failwith("Netsys_posix.set_event: not allowed for this type of event");
+	caml_failwith("Netsys_posix.set_event: not allowed for this type of event");
     caml_enter_blocking_section();
     netsys_not_event_signal(ne);
     caml_leave_blocking_section();
     CAMLreturn(Val_unit);
 #else
-    invalid_argument("Netsys_posix.set_event not available");
+    caml_invalid_argument("Netsys_posix.set_event not available");
 #endif
 }
 
@@ -373,7 +373,7 @@ CAMLprim value netsys_wait_not_event(value nev)
     ne = *(Not_event_val(nev));
     
     if (ne->fd1 == -1) 
-	failwith("Netsys_posix.wait_event: already destroyed");
+	caml_failwith("Netsys_posix.wait_event: already destroyed");
 
     caml_enter_blocking_section();
     p.fd = ne->fd1;
@@ -383,10 +383,10 @@ CAMLprim value netsys_wait_not_event(value nev)
     e = errno;
     caml_leave_blocking_section();
 
-    if (code == -1) unix_error(e, "poll", Nothing);
+    if (code == -1) caml_unix_error(e, "poll", Nothing);
     CAMLreturn(Val_unit);
 #else
-    invalid_argument("Netsys_posix.wait_event not available");
+    caml_invalid_argument("Netsys_posix.wait_event not available");
 #endif
 }
 
@@ -402,7 +402,7 @@ CAMLprim value netsys_consume_not_event(value nev)
     ne = *(Not_event_val(nev));
     
     if (ne->fd1 == -1) 
-	failwith("Netsys_posix.consume_event: already destroyed");
+	caml_failwith("Netsys_posix.consume_event: already destroyed");
 
     caml_enter_blocking_section();
 
@@ -426,8 +426,8 @@ CAMLprim value netsys_consume_not_event(value nev)
 
     caml_leave_blocking_section();
 
-    if (code == -1) unix_error(e, "read", Nothing);
-    if (!ok) unix_error(EINVAL, "read (result invalid)", Nothing);
+    if (code == -1) caml_unix_error(e, "read", Nothing);
+    if (!ok) caml_unix_error(EINVAL, "read (result invalid)", Nothing);
 
     ne->state = 0;
     /* No need to block signals, or to use the mutex. The next signaller
@@ -436,6 +436,6 @@ CAMLprim value netsys_consume_not_event(value nev)
 
     CAMLreturn(Val_unit);
 #else
-    invalid_argument("Netsys_posix.wait_event not available");
+    caml_invalid_argument("Netsys_posix.wait_event not available");
 #endif
 }
diff --git a/src/netsys/netsys_c_fadvise.c b/src/netsys/netsys_c_fadvise.c
index a7c8067..da465e0 100644
--- a/src/netsys/netsys_c_fadvise.c
+++ b/src/netsys/netsys_c_fadvise.c
@@ -35,7 +35,7 @@ CAMLprim value netsys_fadvise(value fd, value start, value len, value adv) {
     case 3: case 9: adv_int = POSIX_FADV_NOREUSE; break;
     case 4: case 10: adv_int = POSIX_FADV_WILLNEED; break;
     case 5: case 11: adv_int = POSIX_FADV_DONTNEED; break;
-    default: invalid_argument("Netsys.fadvise");
+    default: caml_invalid_argument("Netsys.fadvise");
     };
 
     start_int = Int64_val(start);
@@ -54,7 +54,7 @@ CAMLprim value netsys_fadvise(value fd, value start, value len, value adv) {
 	uerror("posix_fadvise64", Nothing);
     return Val_unit;
 #else
-    invalid_argument("Netsys.fadvise not available");
+    caml_invalid_argument("Netsys.fadvise not available");
 #endif
 }
 
diff --git a/src/netsys/netsys_c_fallocate.c b/src/netsys/netsys_c_fallocate.c
index 9f6dca9..11a165f 100644
--- a/src/netsys/netsys_c_fallocate.c
+++ b/src/netsys/netsys_c_fallocate.c
@@ -28,9 +28,9 @@ CAMLprim value netsys_fallocate(value fd, value start, value len) {
     len_int = Int64_val(len);
 
     if ( ((int64_t) ((off_t) start_int)) != start_int )
-	failwith("Netsys.fadvise: large files not supported on this OS");
+	caml_failwith("Netsys.fadvise: large files not supported on this OS");
     if ( ((int64_t) ((off_t) len_int)) != len_int )
-	failwith("Netsys.fadvise: large files not supported on this OS");
+	caml_failwith("Netsys.fadvise: large files not supported on this OS");
 
     start_off = start_int;
     len_off = len_int;
@@ -38,10 +38,10 @@ CAMLprim value netsys_fallocate(value fd, value start, value len) {
     r = posix_fallocate(Int_val(fd), start_off, len_off);
     /* does not set errno! */
     if (r != 0) 
-	unix_error(r, "posix_fallocate64", Nothing);
+	caml_unix_error(r, "posix_fallocate64", Nothing);
     return Val_unit;
 #else
-    invalid_argument("Netsys.fallocate not available");
+    caml_invalid_argument("Netsys.fallocate not available");
 #endif
 }
 
diff --git a/src/netsys/netsys_c_ioprio.c b/src/netsys/netsys_c_ioprio.c
index 0f3e068..99c2a0f 100644
--- a/src/netsys/netsys_c_ioprio.c
+++ b/src/netsys/netsys_c_ioprio.c
@@ -89,11 +89,11 @@ CAMLprim value netsys_ioprio_get(value target) {
 	ioprio = ioprio_get(IOPRIO_WHO_USER, Int_val(Field(target, 0)));
 	break;
     default:
-	failwith("netsys_ioprio_get: internal error");
+	caml_failwith("netsys_ioprio_get: internal error");
     }
 
     if (ioprio == -1)
-	uerror("ioprio_get", Nothing);
+	caml_uerror("ioprio_get", Nothing);
 
     ioprio_class = ioprio >> IOPRIO_CLASS_SHIFT;
     ioprio_data = ioprio & IOPRIO_PRIO_MASK;
@@ -114,14 +114,14 @@ CAMLprim value netsys_ioprio_get(value target) {
 	result = Val_long(1);
 	break;
     default:
-	failwith("netsys_ioprio_get: Unexpected result");
+	caml_failwith("netsys_ioprio_get: Unexpected result");
     }
     
     return result;
 
 #else
     /* not ioprio_supported: */
-    unix_error(ENOSYS, "ioprio_get", Nothing);
+    caml_unix_error(ENOSYS, "ioprio_get", Nothing);
 #endif
     /* ioprio_supported */
 }
@@ -145,7 +145,7 @@ CAMLprim value netsys_ioprio_set(value target, value ioprio_arg) {
 	    ioprio_data = Int_val(Field(ioprio_arg, 0));
 	    break;
 	default:
-	    failwith("netsys_ioprio_set: internal error");
+	    caml_failwith("netsys_ioprio_set: internal error");
 	}
     } else {
 	switch (Long_val(ioprio_arg)) {
@@ -159,7 +159,7 @@ CAMLprim value netsys_ioprio_set(value target, value ioprio_arg) {
 	    ioprio_data = 7;
 	    break;
 	default:
-	    failwith("netsys_ioprio_set: internal error");
+	    caml_failwith("netsys_ioprio_set: internal error");
 	}
     };
 
@@ -176,16 +176,16 @@ CAMLprim value netsys_ioprio_set(value target, value ioprio_arg) {
 	sysres = ioprio_set(IOPRIO_WHO_USER, Int_val(Field(target, 0)), ioprio);
 	break;
     default:
-	failwith("netsys_ioprio_set: internal error");
+	caml_failwith("netsys_ioprio_set: internal error");
     }
 
     if (sysres == -1)
-	uerror("ioprio_set", Nothing);
+	caml_uerror("ioprio_set", Nothing);
 
     return Val_unit;
 #else
     /* not ioprio_supported: */
-    unix_error(ENOSYS, "ioprio_set", Nothing);
+    caml_unix_error(ENOSYS, "ioprio_set", Nothing);
 #endif
     /* ioprio_supported */
 }
diff --git a/src/netsys/netsys_c_locale.c b/src/netsys/netsys_c_locale.c
index f4961ab..a7ea2c5 100644
--- a/src/netsys/netsys_c_locale.c
+++ b/src/netsys/netsys_c_locale.c
@@ -39,28 +39,28 @@ CAMLprim value netsys_query_langinfo(value locale)
 
     old_locale = setlocale(LC_ALL, NULL);
     if (old_locale == NULL)
-	failwith("Netsys_posix.query_locale: no locale support");
-    oldcopy_locale = stat_alloc(strlen(old_locale) + 1);
+	caml_failwith("Netsys_posix.query_locale: no locale support");
+    oldcopy_locale = caml_stat_alloc(strlen(old_locale) + 1);
     strcpy(oldcopy_locale, old_locale);
 
     new_locale = setlocale(LC_ALL, String_val(locale));
     if (new_locale == NULL) {
-	stat_free(oldcopy_locale);
-	failwith("Netsys_posix.query_locale: cannot set this locale");
+	caml_stat_free(oldcopy_locale);
+	caml_failwith("Netsys_posix.query_locale: cannot set this locale");
     }
     
     n = sizeof(locale_items_table) / sizeof(locale_items_table[0]);
-    s = alloc(n,0);
+    s = caml_alloc(n,0);
     for (k=0; k<n; k++) {
-	Store_field(s,k,copy_string(nl_langinfo(locale_items_table[k])));
+	Store_field(s,k,caml_copy_string(nl_langinfo(locale_items_table[k])));
     };
     
     setlocale(LC_ALL, oldcopy_locale);
-    stat_free(oldcopy_locale);
+    caml_stat_free(oldcopy_locale);
 
     CAMLreturn (s);
 #else
-    invalid_argument("Netsys_posix.query_locale not available");
+    caml_invalid_argument("Netsys_posix.query_locale not available");
 #endif
 }
 
diff --git a/src/netsys/netsys_c_mem.c b/src/netsys/netsys_c_mem.c
index 0d7778e..6bdbe62 100644
--- a/src/netsys/netsys_c_mem.c
+++ b/src/netsys/netsys_c_mem.c
@@ -30,8 +30,8 @@ CAMLprim value netsys_blit_memory_to_string(value memv,
 					    value soffv,
 					    value lenv)
 {
-    struct caml_bigarray *mem = Bigarray_val(memv);
-    char * s = Bytes_val(sv);
+    struct caml_ba_array *mem = Caml_ba_array_val(memv);
+    unsigned char * s = Bytes_val(sv);
     long memoff = Long_val(memoffv);
     long soff = Long_val(soffv);
     long len = Long_val(lenv);
@@ -48,7 +48,7 @@ CAMLprim value netsys_blit_string_to_memory(value sv,
 					    value memoffv,
 					    value lenv)
 {
-    struct caml_bigarray *mem = Bigarray_val(memv);
+    struct caml_ba_array *mem = Caml_ba_array_val(memv);
     const char * s = String_val(sv);
     long memoff = Long_val(memoffv);
     long soff = Long_val(soffv);
@@ -62,7 +62,7 @@ CAMLprim value netsys_blit_string_to_memory(value sv,
 
 CAMLprim value netsys_memory_address(value memv)
 {
-    struct caml_bigarray *mem = Bigarray_val(memv);
+    struct caml_ba_array *mem = Caml_ba_array_val(memv);
     return caml_copy_nativeint((intnat) mem->data);
 }
 
@@ -72,7 +72,7 @@ CAMLprim value netsys_getpagesize(value dummy)
 #ifdef HAVE_SYSCONF
     return Val_long(sysconf(_SC_PAGESIZE));
 #else
-    invalid_argument("Netsys_mem.getpagesize not available");
+    caml_invalid_argument("Netsys_mem.getpagesize not available");
 #endif
 }
 
@@ -83,8 +83,8 @@ CAMLprim value netsys_grab(value addrv, value lenv)
 
     start = (void *) Nativeint_val(addrv);
     length = Long_val(lenv);
-    return alloc_bigarray_dims(BIGARRAY_C_LAYOUT | BIGARRAY_UINT8,
-			       1, start, length);
+    return caml_ba_alloc_dims(CAML_BA_C_LAYOUT | CAML_BA_UINT8,
+                              1, start, length);
 }
 
 
@@ -109,15 +109,15 @@ CAMLprim value netsys_alloc_memory_pages(value addrv, value pv, value execv)
 
     data = mmap(start, length, flags, 
 		MAP_PRIVATE | MAP_ANON, (-1), 0);
-    if (data == (void *) -1) uerror("mmap", Nothing);
+    if (data == (void *) -1) caml_uerror("mmap", Nothing);
 
-    r = alloc_bigarray_dims(BIGARRAY_C_LAYOUT | BIGARRAY_UINT8 | 
-			    BIGARRAY_MAPPED_FILE,
-			    1, data, length);
+    r = caml_ba_alloc_dims(CAML_BA_C_LAYOUT | CAML_BA_UINT8 | 
+                           CAML_BA_MAPPED_FILE,
+                           1, data, length);
 
     return r;
 #else
-    invalid_argument("Netsys_mem.alloc_memory_pages not available");
+    caml_invalid_argument("Netsys_mem.alloc_memory_pages not available");
 #endif
 }
 
@@ -125,7 +125,7 @@ CAMLprim value netsys_alloc_memory_pages(value addrv, value pv, value execv)
 CAMLprim value netsys_zero_pages(value memv, value offsv, value lenv)
 {
 #if defined(HAVE_MMAP) && defined(HAVE_SYSCONF) && defined(MAP_ANON) && defined (MAP_FIXED)
-    struct caml_bigarray *mem = Bigarray_val(memv);
+    struct caml_ba_array *mem = Caml_ba_array_val(memv);
     long offs = Long_val(offsv);
     long len = Long_val(lenv);
     long pgsize = sysconf(_SC_PAGESIZE);
@@ -137,17 +137,17 @@ CAMLprim value netsys_zero_pages(value memv, value offsv, value lenv)
 	    data2 = mmap(data, len, PROT_READ|PROT_WRITE, 
 			 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
 			 (-1), 0);
-	    if (data2 == (void *) -1) uerror("mmap", Nothing);
+	    if (data2 == (void *) -1) caml_uerror("mmap", Nothing);
 	    if (((void *) data) != data2)
-		failwith("Netsys_mem.zero_pages assertion failed");
+		caml_failwith("Netsys_mem.zero_pages assertion failed");
 	}
     }
     else
-	invalid_argument("Netsys_mem.zero_pages only for whole pages");
+	caml_invalid_argument("Netsys_mem.zero_pages only for whole pages");
 
     return Val_unit;
 #else
-    invalid_argument("Netsys_mem.zero_pages not available");
+    caml_invalid_argument("Netsys_mem.zero_pages not available");
 #endif
 }
 
@@ -162,14 +162,14 @@ CAMLprim value netsys_alloc_aligned_memory(value alignv, value pv)
     value r;
 
     e = posix_memalign(&addr, align, size);
-    if (e != 0) unix_error(e, "posix_memalign", Nothing);
+    if (e != 0) caml_unix_error(e, "posix_memalign", Nothing);
 
-    r = alloc_bigarray_dims(BIGARRAY_C_LAYOUT | BIGARRAY_UINT8 | 
-			    BIGARRAY_MANAGED,
-			    1, addr, size);
+    r = caml_ba_alloc_dims(CAML_BA_C_LAYOUT | CAML_BA_UINT8 | 
+                           CAML_BA_MANAGED,
+                           1, addr, size);
     return r;
 #else
-    invalid_argument("Netsys_mem.alloc_aligned_memory not available");
+    caml_invalid_argument("Netsys_mem.alloc_aligned_memory not available");
 #endif
 }
 
@@ -197,7 +197,7 @@ CAMLprim value netsys_map_file(value fdv,
     fd = Int_val(fdv);
     pos0 = Int64_val(posv);
     if (((int64_t) ((off_t) pos0)) != pos0)
-	failwith("Netsys_mem: large files not supported on this OS");
+	caml_failwith("Netsys_mem: large files not supported on this OS");
     pos = pos0;
     addr = (void *) Nativeint_val(addrv);
     if (addr == 0) addr = NULL;
@@ -206,36 +206,36 @@ CAMLprim value netsys_map_file(value fdv,
 
     pagesize = sysconf(_SC_PAGESIZE);
 
-    if (fstat(fd, &st) == -1) uerror("fstat", Nothing);
+    if (fstat(fd, &st) == -1) caml_uerror("fstat", Nothing);
     eofpos = st.st_size;
     
     if (size == -1) {
 	if (eofpos < pos) 
-	    failwith("Netsys_mem: cannot mmap - file position exceeds file size");
+	    caml_failwith("Netsys_mem: cannot mmap - file position exceeds file size");
 	basize0 = eofpos - pos;
 	if (((off_t) ((uintnat) basize0)) != basize0)
-	    failwith("Netsys_mem: cannot mmap - file too large");
+	    caml_failwith("Netsys_mem: cannot mmap - file too large");
 	basize = (uintnat) basize0;
     }
     else {
 	if (size < 0)
-	    invalid_argument("netsys_map_file");
+	    caml_invalid_argument("netsys_map_file");
 	if (eofpos - pos < size) {
 	    if (ftruncate(fd, pos + size) == -1)
-		uerror("ftruncate", Nothing);
+		caml_uerror("ftruncate", Nothing);
 	}
 	basize = size;
     }
     delta = (uintnat) (pos % pagesize);
     eff_addr = mmap(addr, basize + delta, PROT_READ | PROT_WRITE,
 		    shared, fd, pos - delta);
-    if (eff_addr == (void*) MAP_FAILED) uerror("mmap", Nothing);
+    if (eff_addr == (void*) MAP_FAILED) caml_uerror("mmap", Nothing);
     eff_addr = (void *) ((uintnat) eff_addr + delta);
 
-    return alloc_bigarray_dims(BIGARRAY_UINT8 | BIGARRAY_C_LAYOUT | 
-			       BIGARRAY_MAPPED_FILE, 1, eff_addr, basize);
+    return caml_ba_alloc_dims(CAML_BA_UINT8 | CAML_BA_C_LAYOUT | 
+                              CAML_BA_MAPPED_FILE, 1, eff_addr, basize);
 #else
-    invalid_argument("Netsys_mem.memory_map_file not available");
+    caml_invalid_argument("Netsys_mem.memory_map_file not available");
 #endif
 }
 
@@ -254,20 +254,20 @@ static void ba_unmap_file(void * addr, uintnat len)
 
 CAMLprim value netsys_memory_unmap_file(value memv) 
 {
-    struct caml_bigarray *b = Bigarray_val(memv);
-    if ((b->flags & BIGARRAY_MANAGED_MASK) == BIGARRAY_MAPPED_FILE) {
+    struct caml_ba_array *b = Caml_ba_array_val(memv);
+    if ((b->flags & CAML_BA_MANAGED_MASK) == CAML_BA_MAPPED_FILE) {
 	if (b->proxy == NULL) {
 	    ba_unmap_file(b->data, b->dim[0]);
 	    b->data = NULL;
 	    b->flags = 
-		(b->flags & ~BIGARRAY_MANAGED_MASK) | BIGARRAY_EXTERNAL;
+		(b->flags & ~CAML_BA_MANAGED_MASK) | CAML_BA_EXTERNAL;
 	}
 	else if (b->proxy->refcount == 1) {
 	    ba_unmap_file(b->proxy->data, b->dim[0]);
 	    b->proxy->data = NULL;
 	    b->data = NULL;
 	    b->flags = 
-		(b->flags & ~BIGARRAY_MANAGED_MASK) | BIGARRAY_EXTERNAL;
+		(b->flags & ~CAML_BA_MANAGED_MASK) | CAML_BA_EXTERNAL;
 	}
     }
     return Val_unit;
@@ -278,26 +278,26 @@ extern value caml_ba_reshape(value bv, value dimv);
 
 CAMLprim value netsys_reshape(value bv)
 {
-    struct caml_bigarray *b;
-    struct caml_bigarray *mem;
+    struct caml_ba_array *b;
+    struct caml_ba_array *mem;
     uintnat size;
     int i,k;
     CAMLparam1(bv);
     CAMLlocal2(memv,dimv);
 
-    b = Bigarray_val(bv);
+    b = Caml_ba_array_val(bv);
 
     /* We dont't have access to caml_ba_update_proxy. The workaround is
        to call caml_ba_reshape, and to fix the returned bigarray descriptor
        afterward.
     */
-    dimv = alloc(b->num_dims,0);
+    dimv = caml_alloc(b->num_dims,0);
     for (k=0; k < b->num_dims; k++) {
 	Store_field(dimv, k, Val_long(b->dim[k]));
     };
     
     memv = caml_ba_reshape(bv, dimv);
-    mem = Bigarray_val(memv);
+    mem = Caml_ba_array_val(memv);
 
     /* Compute the size of the data area: */
     size = caml_ba_element_size[b->flags & CAML_BA_KIND_MASK];
@@ -354,10 +354,14 @@ CAMLprim value netsys_color(value objv)
 
 CAMLprim value netsys_set_color(value objv, value colv)
 {
+#if OCAML_VERSION < 50000
     int col;
     col = Int_val(colv);
     Hd_val(objv) = Whitehd_hd(Hd_val(objv)) | (col << 8);
     return Val_unit;
+#else
+    caml_invalid_argument("Netsys_mem.set_color");
+#endif
 }
 
 /**********************************************************************/
@@ -375,20 +379,20 @@ CAMLprim value netsys_mem_read(value fdv, value memv, value offv, value lenv)
 #endif
 
     numbytes = Long_val(lenv);
-    data = ((char *) (Bigarray_val(memv)->data)) + Long_val(offv);
+    data = ((char *) (Caml_ba_array_val(memv)->data)) + Long_val(offv);
 #ifdef _WIN32
     if (Descr_kind_val(fdv) == KIND_SOCKET) {
 	SOCKET h = Socket_val(fdv);
-	enter_blocking_section();
+	caml_enter_blocking_section();
 	ret = recv(h, data, numbytes, 0);
 	if (ret == SOCKET_ERROR) err = WSAGetLastError();
-	leave_blocking_section();
+	caml_leave_blocking_section();
 	ret = n;
     } else {
 	HANDLE h = Handle_val(fdv);
-	enter_blocking_section();
+	caml_enter_blocking_section();
 	if (! ReadFile(h, data, numbytes, &n, NULL)) err = GetLastError();
-	leave_blocking_section();
+	caml_leave_blocking_section();
 	ret = n;
     }
     if (err) {
@@ -396,11 +400,11 @@ CAMLprim value netsys_mem_read(value fdv, value memv, value offv, value lenv)
 	ret = -1;
     }
 #else
-    enter_blocking_section();
+    caml_enter_blocking_section();
     ret = read(Int_val(fdv), data, (int) numbytes);
-    leave_blocking_section();   /* keeps errno intact */
+    caml_leave_blocking_section();   /* keeps errno intact */
 #endif
-    if (ret == -1) uerror("mem_read", Nothing);
+    if (ret == -1) caml_uerror("mem_read", Nothing);
     return Val_long(ret);
 }
 
@@ -416,20 +420,20 @@ CAMLprim value netsys_mem_write(value fdv, value memv, value offv, value lenv)
 #endif
 
     numbytes = Long_val(lenv);
-    data = ((char *) (Bigarray_val(memv)->data)) + Long_val(offv);
+    data = ((char *) (Caml_ba_array_val(memv)->data)) + Long_val(offv);
 #ifdef _WIN32
     if (Descr_kind_val(fdv) == KIND_SOCKET) {
 	SOCKET h = Socket_val(fdv);
-	enter_blocking_section();
+	caml_enter_blocking_section();
 	ret = send(h, data, numbytes, 0);
 	if (ret == SOCKET_ERROR) err = WSAGetLastError();
-	leave_blocking_section();
+	caml_leave_blocking_section();
 	ret = n;
     } else {
 	HANDLE h = Handle_val(fdv);
-	enter_blocking_section();
+	caml_enter_blocking_section();
 	if (! WriteFile(h, data, numbytes, &n, NULL)) err = GetLastError();
-	leave_blocking_section();
+	caml_leave_blocking_section();
 	ret = n;
     }
     if (err) {
@@ -437,11 +441,11 @@ CAMLprim value netsys_mem_write(value fdv, value memv, value offv, value lenv)
 	ret = -1;
     }
 #else
-    enter_blocking_section();
+    caml_enter_blocking_section();
     ret = write(Int_val(fdv), data, (int) numbytes);
-    leave_blocking_section();
+    caml_leave_blocking_section();
 #endif
-    if (ret == -1) uerror("mem_write", Nothing);
+    if (ret == -1) caml_uerror("mem_write", Nothing);
     return Val_long(ret);
 }
 
@@ -466,8 +470,8 @@ CAMLprim value netsys_mem_recv(value fdv, value memv, value offv, value lenv,
 #endif
 
     numbytes = Long_val(lenv);
-    data = ((char *) (Bigarray_val(memv)->data)) + Long_val(offv);
-    flags = convert_flag_list(flagsv, msg_flag_table);
+    data = ((char *) (Caml_ba_array_val(memv)->data)) + Long_val(offv);
+    flags = caml_convert_flag_list(flagsv, msg_flag_table);
 
 #ifdef _WIN32
     s = Socket_val(fdv);
@@ -475,18 +479,18 @@ CAMLprim value netsys_mem_recv(value fdv, value memv, value offv, value lenv,
     s = Int_val(fdv);
 #endif
 
-    enter_blocking_section();
+    caml_enter_blocking_section();
     ret = recv(s, data, (int) numbytes, flags);
 
 #ifdef _WIN32
     if (ret == -1) err = WSAGetLastError();
-    leave_blocking_section();
+    caml_leave_blocking_section();
     if (ret == -1) win32_maperr(err);
 #else
-    leave_blocking_section();
+    caml_leave_blocking_section();
 #endif
 
-    if (ret == -1) uerror("mem_recv", Nothing);
+    if (ret == -1) caml_uerror("mem_recv", Nothing);
     return Val_long(ret);
 }
 
@@ -506,8 +510,8 @@ CAMLprim value netsys_mem_send(value fdv, value memv, value offv, value lenv,
 #endif
 
     numbytes = Long_val(lenv);
-    data = ((char *) (Bigarray_val(memv)->data)) + Long_val(offv);
-    flags = convert_flag_list(flagsv, msg_flag_table);
+    data = ((char *) (Caml_ba_array_val(memv)->data)) + Long_val(offv);
+    flags = caml_convert_flag_list(flagsv, msg_flag_table);
 
 #ifdef _WIN32
     s = Socket_val(fdv);
@@ -515,18 +519,18 @@ CAMLprim value netsys_mem_send(value fdv, value memv, value offv, value lenv,
     s = Int_val(fdv);
 #endif
 
-    enter_blocking_section();
+    caml_enter_blocking_section();
     ret = send(s, data, (int) numbytes, flags);
 
 #ifdef _WIN32
     if (ret == -1) err = WSAGetLastError();
-    leave_blocking_section();
+    caml_leave_blocking_section();
     if (ret == -1) win32_maperr(err);
 #else
-    leave_blocking_section();
+    caml_leave_blocking_section();
 #endif
 
-    if (ret == -1) uerror("mem_send", Nothing);
+    if (ret == -1) caml_uerror("mem_send", Nothing);
     return Val_long(ret);
 }
 
@@ -537,44 +541,48 @@ CAMLprim value netsys_mem_send(value fdv, value memv, value offv, value lenv,
 
 CAMLprim value netsys_as_value(value memv, value offv) 
 {
-    struct caml_bigarray *b = Bigarray_val(memv);
+#if OCAML_VERSION < 50000
+    struct caml_ba_array *b = Caml_ba_array_val(memv);
     return (value) (b->data + Long_val(offv));
+#else
+    caml_invalid_argument("Netsys_mem.as_value");
+#endif
 }
 
 CAMLprim value netsys_value_area_add(value memv) 
 {
-#ifdef FANCY_PAGE_TABLES
-    struct caml_bigarray *b = Bigarray_val(memv);
+#if defined(FANCY_PAGE_TABLES) && OCAML_VERSION < 50000
+    struct caml_ba_array *b = Caml_ba_array_val(memv);
     int code;
     code = caml_page_table_add(In_static_data,
 			       b->data,
 			       b->data + b->dim[0]);
     if (code != 0) 
-	failwith("Netsys_mem.value_area: error");
+	caml_failwith("Netsys_mem.value_area: error");
     return Val_unit;
 #else
-    invalid_argument("Netsys_mem.value_area");
+    caml_invalid_argument("Netsys_mem.value_area");
 #endif
 }
 
 CAMLprim value netsys_value_area_remove(value memv) 
 {
-#ifdef FANCY_PAGE_TABLES
-    struct caml_bigarray *b = Bigarray_val(memv);
+#if defined(FANCY_PAGE_TABLES) && OCAML_VERSION < 50000
+    struct caml_ba_array *b = Caml_ba_array_val(memv);
     caml_page_table_remove(In_static_data,
                            b->data,
                            b->data + b->dim[0]);
     /* Silently ignore errors... */
     return Val_unit;
 #else
-    invalid_argument("Netsys_mem.value_area");
+    caml_invalid_argument("Netsys_mem.value_area");
 #endif
 }
 
 CAMLprim value netsys_init_header(value memv, value offv, value tagv,
 				  value sizev)
 {
-    struct caml_bigarray *b = Bigarray_val(memv);
+    struct caml_ba_array *b = Caml_ba_array_val(memv);
     intnat off = Long_val(offv);
     intnat size = Long_val(sizev);
     int tag = Int_val(tagv);
@@ -582,10 +590,10 @@ CAMLprim value netsys_init_header(value memv, value offv, value tagv,
 
 #ifdef ARCH_SIXTYFOUR
     if (off % 8 != 0)
-	invalid_argument("Netsys_mem.init_header");
+	caml_invalid_argument("Netsys_mem.init_header");
 #else
     if (off % 4 != 0)
-	invalid_argument("Netsys_mem.init_header");
+	caml_invalid_argument("Netsys_mem.init_header");
 #endif
 
     m = (value *) (((char *) b->data) + off);
@@ -619,7 +627,7 @@ CAMLprim value netsys_cmp_string(value s1, value s2)
 
 CAMLprim value netsys_init_string(value memv, value offv, value lenv) 
 {
-    struct caml_bigarray *b = Bigarray_val(memv);
+    struct caml_ba_array *b = Caml_ba_array_val(memv);
     intnat off = Long_val(offv);
     intnat len = Long_val(lenv);
     value *m;
@@ -629,10 +637,10 @@ CAMLprim value netsys_init_string(value memv, value offv, value lenv)
 
 #ifdef ARCH_SIXTYFOUR
     if (off % 8 != 0)
-	invalid_argument("Netsys_mem.init_string");
+	caml_invalid_argument("Netsys_mem.init_string");
 #else
     if (off % 4 != 0)
-	invalid_argument("Netsys_mem.init_string");
+	caml_invalid_argument("Netsys_mem.init_string");
 #endif
 
     m = (value *) (((char *) b->data) + off);
@@ -650,6 +658,8 @@ CAMLprim value netsys_init_string(value memv, value offv, value lenv)
 }
 
 
+#if OCAML_VERSION < 50000
+
 struct named_custom_ops {
     char *name;
     void *ops;
@@ -999,14 +1009,14 @@ int netsys_init_value_1(struct htab *t,
 		    size_t size = 1;
 		    size_t size_aligned;
 		    size_t size_words;
-		    b_work = Bigarray_val(work);
-		    b_copy = Bigarray_val(copy);
+		    b_work = Caml_ba_array_val(work);
+		    b_copy = Caml_ba_array_val(copy);
 		    for (i = 0; i < b_work->num_dims; i++) {
 			size = size * b_work->dim[i];
 		    };
 		    size = 
 			size * 
-			caml_ba_element_size[b_work->flags & BIGARRAY_KIND_MASK];
+			caml_ba_element_size[b_work->flags & CAML_BA_KIND_MASK];
 
 		    size_aligned = size;
 		    if (size%sizeof(void *) != 0)
@@ -1035,7 +1045,7 @@ int netsys_init_value_1(struct htab *t,
 			dest_cur += size_aligned;
 		    } else if (!simulation) {
 			data_header = NULL;
-			data_copy = stat_alloc(size_aligned);
+			data_copy = caml_stat_alloc(size_aligned);
 		    };
 
 		    if (!simulation) {
@@ -1197,7 +1207,7 @@ static void unprep_stat_queue(void)
     if (netsys_queue_size(stat_queue) > 256)
 	netsys_queue_free(stat_queue);
 }
-
+#endif
 
 value netsys_init_value(value memv, 
 			value offv, 
@@ -1208,6 +1218,7 @@ value netsys_init_value(value memv,
                         value cc
 			)
 {
+#if OCAML_VERSION < 50000
     int code;
     value r;
     intnat start_offset, bytelen;
@@ -1254,16 +1265,16 @@ value netsys_init_value(value memv,
 	old_ops = ops;
 	pair = Field(target_custom_ops,0);
 	ops = (struct named_custom_ops*) 
-	          stat_alloc(sizeof(struct named_custom_ops));
-	ops->name = stat_alloc(caml_string_length(Field(pair,0))+1);
+	          caml_stat_alloc(sizeof(struct named_custom_ops));
+	ops->name = caml_stat_alloc(caml_string_length(Field(pair,0))+1);
 	strcmp(ops->name, String_val(Field(pair,0)));
 	ops->ops = (void *) Nativeint_val(Field(pair,1));
 	ops->next = old_ops;
 	target_custom_ops = Field(target_custom_ops,1);
     };
 
-    mem_data = ((char *) Bigarray_val(memv)->data) + off;
-    mem_end = mem_data + Bigarray_val(memv)->dim[0];
+    mem_data = ((char *) Caml_ba_array_val(memv)->data) + off;
+    mem_end = mem_data + Caml_ba_array_val(memv)->dim[0];
 
     /* note: the color of the new values does not matter because bigarrays
        are ignored by the GC. So we pass 0 (white).
@@ -1287,8 +1298,8 @@ value netsys_init_value(value memv,
 
     while (ops != NULL) {
 	next_ops = ops->next;
-	stat_free(ops->name);
-	stat_free(ops);
+	caml_stat_free(ops->name);
+	caml_stat_free(ops);
 	ops = next_ops;
     };
     
@@ -1304,17 +1315,20 @@ value netsys_init_value(value memv,
 
     switch(code) {
     case (-1):
-	unix_error(errno, "netsys_init_value", Nothing);
+	caml_unix_error(errno, "netsys_init_value", Nothing);
     case (-2):
 #ifdef DEBUG
         fprintf(stderr, "Lib err\n");
 #endif
-	failwith("Netsys_mem.init_value: Library error");
+	caml_failwith("Netsys_mem.init_value: Library error");
     case (-4):
 	caml_raise_constant(*caml_named_value("Netsys_mem.Out_of_space"));
     default:
-	failwith("Netsys_mem.init_value: Unknown error");
+	caml_failwith("Netsys_mem.init_value: Unknown error");
     }
+#else
+    caml_invalid_argument("Netsys_mem.init_value");
+#endif
 }
 
 
@@ -1344,6 +1358,7 @@ value netsys_init_value_bc(value * argv, int argn)
 
 value netsys_copy_value(value flags, value orig)
 {
+#if OCAML_VERSION < 50000
     int code;
     int cflags;
     intnat start_offset, bytelen;
@@ -1389,8 +1404,8 @@ value netsys_copy_value(value flags, value orig)
     */
     bigarray_ops.name = BIGARRAY_MARSHAL_ID;
     bigarray_ops.ops = 
-	Custom_ops_val(alloc_bigarray_dims(CAML_BA_UINT8 | BIGARRAY_C_LAYOUT, 
-					   1, NULL, 1));
+	Custom_ops_val(caml_ba_alloc_dims(CAML_BA_UINT8 | CAML_BA_C_LAYOUT, 
+                                          1, NULL, 1));
     bigarray_ops.next = &int32_ops;
 
     int32_ops.name = "_i";
@@ -1490,38 +1505,45 @@ value netsys_copy_value(value flags, value orig)
 
     switch(code) {
     case (-1):
-	unix_error(errno, "netsys_copy_value", Nothing);
+	caml_unix_error(errno, "netsys_copy_value", Nothing);
     case (-2):
-	failwith("Netsys_mem.copy_value: Library error");
+	caml_failwith("Netsys_mem.copy_value: Library error");
     case (-4):
 	caml_raise_constant(*caml_named_value("Netsys_mem.Out_of_space"));
     default:
-	failwith("Netsys_mem.copy_value: Unknown error");
+	caml_failwith("Netsys_mem.copy_value: Unknown error");
     }
+#else
+    caml_invalid_argument("Netsys_mem.copy_value");
+#endif
 }
 
 
 value netsys_get_custom_ops (value v) 
 {
+#if OCAML_VERSION < 50000
     struct custom_operations *custom_ops;
     CAMLparam1(v);
     CAMLlocal1(r);
 
     if (Is_block(v) && Tag_val(v) == Custom_tag) {
 	custom_ops = Custom_ops_val(v);
-	r = alloc_small(2,0);
+	r = caml_alloc_small(2,0);
 	Field(r,0) = caml_copy_string(custom_ops->identifier);
 	Field(r,1) = caml_copy_nativeint((intnat) custom_ops);
     }
     else 
-	invalid_argument("Netsys_mem.get_custom_ops");
+	caml_invalid_argument("Netsys_mem.get_custom_ops");
 
     CAMLreturn(r);
+#else
+    caml_invalid_argument("Netsys_mem.get_custom_ops");
+#endif
 }
 
 
 value netsys_is_bigarray(value v) {
-    struct custom_operations *custom_ops;
+    const struct custom_operations *custom_ops;
     CAMLparam1(v);
     CAMLlocal1(r);
 
diff --git a/src/netsys/netsys_c_multicast.c b/src/netsys/netsys_c_multicast.c
index 26c19bb..7f9c885 100644
--- a/src/netsys/netsys_c_multicast.c
+++ b/src/netsys/netsys_c_multicast.c
@@ -43,7 +43,7 @@ static int socket_domain(int fd) {
         return PF_INET6;
 #endif
     default:
-	invalid_argument("Not an Internet socket");
+	caml_invalid_argument("Not an Internet socket");
     }
 
     return 0;
@@ -77,7 +77,7 @@ CAMLprim value netsys_mcast_set_loop(value fd, value flag) {
 #endif
 #endif
     default:
-	invalid_argument("Netsys.mcast_set_loop");
+	caml_invalid_argument("Netsys.mcast_set_loop");
     };
 
     if (r == -1)
@@ -93,7 +93,7 @@ CAMLprim value netsys_mcast_set_ttl(value fd, value ttl) {
 
 #ifdef _WIN32
     if (Descr_kind_val(fd) != KIND_SOCKET)
-	invalid_argument("Netsys.mcast_set_ttl");
+	caml_invalid_argument("Netsys.mcast_set_ttl");
     fd_sock = Socket_val(fd);
 #else
     fd_sock = Int_val(fd);
@@ -123,7 +123,7 @@ CAMLprim value netsys_mcast_set_ttl(value fd, value ttl) {
 #endif
 #endif
     default:
-	invalid_argument("Netsys.mcast_set_ttl");
+	caml_invalid_argument("Netsys.mcast_set_ttl");
     };
 
     if (r == -1)
@@ -141,7 +141,7 @@ CAMLprim value netsys_mcast_add_membership(value fd,
 
 #ifdef _WIN32
     if (Descr_kind_val(fd) != KIND_SOCKET)
-	invalid_argument("Netsys.mcast_add_membership");
+	caml_invalid_argument("Netsys.mcast_add_membership");
     fd_sock = Socket_val(fd);
 #else
     fd_sock = Int_val(fd);
@@ -154,8 +154,8 @@ CAMLprim value netsys_mcast_add_membership(value fd,
 #ifdef IP_ADD_MEMBERSHIP
     case PF_INET: {
         struct ip_mreq mreq;
-        if (string_length(group_addr) != 4 || string_length(if_addr) != 4 )
-            invalid_argument("Netsys.mcast_add_membership: Not an IPV4 address");
+        if (caml_string_length(group_addr) != 4 || caml_string_length(if_addr) != 4 )
+            caml_invalid_argument("Netsys.mcast_add_membership: Not an IPV4 address");
         memcpy(&mreq.imr_multiaddr,
                &GET_INET_ADDR(group_addr),
                4);
@@ -173,8 +173,8 @@ CAMLprim value netsys_mcast_add_membership(value fd,
 #ifdef IPV6_ADD_MEMBERSHIP
     case PF_INET6: {
         struct ipv6_mreq mreq;
-        if (string_length(group_addr) != 16 || string_length(if_addr) != 16 )
-            invalid_argument("Netsys.mcast_add_membership: Not an IPV6 address");
+        if (caml_string_length(group_addr) != 16 || caml_string_length(if_addr) != 16 )
+            caml_invalid_argument("Netsys.mcast_add_membership: Not an IPV6 address");
         memcpy(&mreq.ipv6mr_multiaddr,
                &GET_INET6_ADDR(group_addr),
                16);
@@ -193,7 +193,7 @@ CAMLprim value netsys_mcast_add_membership(value fd,
 #endif
 #endif
     default:
-	invalid_argument("Netsys.mcast_add_membership");
+	caml_invalid_argument("Netsys.mcast_add_membership");
     };
     if (r == -1)
         uerror("setsockopt",Nothing);
@@ -210,7 +210,7 @@ CAMLprim value netsys_mcast_drop_membership(value fd,
 
 #ifdef _WIN32
     if (Descr_kind_val(fd) != KIND_SOCKET)
-	invalid_argument("Netsys.mcast_drop_membership");
+	caml_invalid_argument("Netsys.mcast_drop_membership");
     fd_sock = Socket_val(fd);
 #else
     fd_sock = Int_val(fd);
@@ -223,8 +223,8 @@ CAMLprim value netsys_mcast_drop_membership(value fd,
 #ifdef IP_DROP_MEMBERSHIP
     case PF_INET: {
         struct ip_mreq mreq;
-        if (string_length(group_addr) != 4 || string_length(if_addr) != 4 )
-            invalid_argument("Netsys.mcast_drop_membership: Not an IPV4 address");
+        if (caml_string_length(group_addr) != 4 || caml_string_length(if_addr) != 4 )
+            caml_invalid_argument("Netsys.mcast_drop_membership: Not an IPV4 address");
         memcpy(&mreq.imr_multiaddr,
                &GET_INET_ADDR(group_addr),
                4);
@@ -242,8 +242,8 @@ CAMLprim value netsys_mcast_drop_membership(value fd,
 #ifdef IPV6_DROP_MEMBERSHIP
     case PF_INET6: {
         struct ipv6_mreq mreq;
-        if (string_length(group_addr) != 16 || string_length(if_addr) != 16 )
-            invalid_argument("Netsys.mcast_drop_membership: Not an IPV6 address");
+        if (caml_string_length(group_addr) != 16 || caml_string_length(if_addr) != 16 )
+            caml_invalid_argument("Netsys.mcast_drop_membership: Not an IPV6 address");
         memcpy(&mreq.ipv6mr_multiaddr,
                &GET_INET6_ADDR(group_addr),
                16);
@@ -262,7 +262,7 @@ CAMLprim value netsys_mcast_drop_membership(value fd,
 #endif
 #endif
     default:
-	invalid_argument("Netsys.mcast_drop_membership");
+	caml_invalid_argument("Netsys.mcast_drop_membership");
     };
 
     if (r == -1)
diff --git a/src/netsys/netsys_c_outofheap.c b/src/netsys/netsys_c_outofheap.c
index 55f2f61..5a5fb1b 100644
--- a/src/netsys/netsys_c_outofheap.c
+++ b/src/netsys/netsys_c_outofheap.c
@@ -9,7 +9,7 @@
 
 #include "netsys_c.h"
 
-#ifdef HAVE_NEW_MODIFY
+#if defined(HAVE_NEW_MODIFY) && OCAML_VERSION < 50000
 /* implies FANCY_PAGE_TABLES */
 
 
diff --git a/src/netsys/netsys_c_poll.c b/src/netsys/netsys_c_poll.c
index 61c3f38..8e38683 100644
--- a/src/netsys/netsys_c_poll.c
+++ b/src/netsys/netsys_c_poll.c
@@ -75,7 +75,7 @@ CAMLprim value netsys_mk_poll_mem(value n) {
     };
     return s;
 #else
-    invalid_argument("netsys_mk_poll_mem");
+    caml_invalid_argument("netsys_mk_poll_mem");
 #endif
 }
 
@@ -89,7 +89,7 @@ CAMLprim value netsys_set_poll_mem(value s, value k, value fd, value ev, value r
     (*(Poll_mem_val(s)))[Int_val(k)] = p;
     return Val_unit;
 #else
-    invalid_argument("netsys_set_poll_mem");
+    caml_invalid_argument("netsys_set_poll_mem");
 #endif
 
 }
@@ -106,7 +106,7 @@ CAMLprim value netsys_get_poll_mem(value s, value k) {
     Store_field(triple, 2, Val_int(p.revents));
     return triple;
 #else
-    invalid_argument("netsys_get_poll_mem");
+    caml_invalid_argument("netsys_get_poll_mem");
 #endif
 }
 
@@ -120,7 +120,7 @@ CAMLprim value netsys_blit_poll_mem(value s1, value k1, value s2, value k2, valu
     memmove(p2 + Int_val(k2), p1 + Int_val(k1), l*sizeof(struct pollfd));
     return Val_unit;
 #else
-    invalid_argument("netsys_blit_poll_mem");
+    caml_invalid_argument("netsys_blit_poll_mem");
 #endif
 };
 
@@ -148,15 +148,15 @@ CAMLprim value netsys_poll(value s, value nv, value tv) {
     n = Int_val(nv);
     tmo = Long_val(tv);
     
-    enter_blocking_section();
+    caml_enter_blocking_section();
     r = poll(p, n, tmo);
-    leave_blocking_section();
+    caml_leave_blocking_section();
 
-    if (r == -1) uerror("poll", Nothing);
+    if (r == -1) caml_uerror("poll", Nothing);
     
     return Val_int(r);
 #else
-     invalid_argument("netsys_poll");
+     caml_invalid_argument("netsys_poll");
 #endif
 }
 
@@ -224,12 +224,12 @@ CAMLprim value netsys_create_event_aggreg(value cancelv)
 
 #ifdef USABLE_EPOLL
     fd = epoll_create(128);
-    if (fd == -1) uerror("epoll_create", Nothing);
+    if (fd == -1) caml_uerror("epoll_create", Nothing);
     code = fcntl(fd, F_SETFD, FD_CLOEXEC);
     if (code == -1) {
 	e = errno;
 	close(fd);
-	unix_error(e, "fcntl", Nothing);
+	caml_unix_error(e, "fcntl", Nothing);
     };
     r = alloc_poll_aggreg();
     pa = *(Poll_aggreg_val(r));
@@ -243,14 +243,14 @@ CAMLprim value netsys_create_event_aggreg(value cancelv)
 	if (cancel_fd == -1) {
 	    e = errno;
 	    close(fd);
-	    unix_error(e, "eventfd", Nothing);
+	    caml_unix_error(e, "eventfd", Nothing);
 	};
 	code = fcntl(cancel_fd, F_SETFD, FD_CLOEXEC);
 	if (code == -1) {
 	    e = errno;
 	    close(fd);
 	    close(cancel_fd);
-	    unix_error(e, "fcntl", Nothing);
+	    caml_unix_error(e, "fcntl", Nothing);
 	};
 	ee.events = EPOLLIN;  /* not oneshot! */
 	ee.data.u64 = 1;  /* reserved value */
@@ -259,14 +259,14 @@ CAMLprim value netsys_create_event_aggreg(value cancelv)
 	    e = errno;
 	    close(fd);
 	    close(cancel_fd);
-	    unix_error(e, "epoll_ctl (ADD)", Nothing);
+	    caml_unix_error(e, "epoll_ctl (ADD)", Nothing);
 	};
 	pa->cancel_fd = cancel_fd;
     };
 #endif
     return r;
 #else
-    invalid_argument("Netsys_posix.create_event_aggregator not available");
+    caml_invalid_argument("Netsys_posix.create_event_aggregator not available");
 #endif
 }
 
@@ -279,14 +279,14 @@ CAMLprim value netsys_destroy_event_aggreg(value pav)
 
     pa = *(Poll_aggreg_val(pav));
     code = close(pa->fd);
-    if (code == -1) uerror("close", Nothing);
+    if (code == -1) caml_uerror("close", Nothing);
     if (pa->cancel_fd >= 0) {
 	code = close(pa->cancel_fd);
-	if (code == -1) uerror("close", Nothing);
+	if (code == -1) caml_uerror("close", Nothing);
     };
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.destroy_event_aggregator not available");
+    caml_invalid_argument("Netsys_posix.destroy_event_aggregator not available");
 #endif
 }
 
@@ -299,7 +299,7 @@ CAMLprim value netsys_event_aggreg_fd(value pav)
     pa = *(Poll_aggreg_val(pav));
     return Val_int(pa->fd);
 #else
-    invalid_argument("Netsys_posix.event_aggregator_fd not available");
+    caml_invalid_argument("Netsys_posix.event_aggregator_fd not available");
 #endif
 }
 
@@ -348,12 +348,12 @@ CAMLprim value netsys_add_event_source(value pav, value pushv)
 	translate_to_epoll_events(Int_val(Field(pushv, 2))) | EPOLLONESHOT;
     ee.data.u64 = Long_val(Field(pushv, 0)) << 1;
     code = epoll_ctl(pa->fd, EPOLL_CTL_ADD, fd, &ee);
-    if (code == -1) uerror("epoll_ctl (ADD)", Nothing);
+    if (code == -1) caml_uerror("epoll_ctl (ADD)", Nothing);
 #endif
 
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.add_event_source not available");
+    caml_invalid_argument("Netsys_posix.add_event_source not available");
 #endif
 }
 
@@ -373,12 +373,12 @@ CAMLprim value netsys_del_event_source(value pav, value idv, value tagv)
 
 #ifdef USABLE_EPOLL
     code = epoll_ctl(pa->fd, EPOLL_CTL_DEL, fd, &ee);
-    if (code == -1) uerror("epoll_ctl (DEL)", Nothing);
+    if (code == -1) caml_uerror("epoll_ctl (DEL)", Nothing);
 #endif
 
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.del_event_source not available");
+    caml_invalid_argument("Netsys_posix.del_event_source not available");
 #endif
 }
 
@@ -394,11 +394,11 @@ CAMLprim value netsys_interrupt_aggreg(value pav)
         int n;
 	buf = 1;
 	n = write(pa->cancel_fd, (char *) &buf, 8);
-        if (n == -1) uerror("write", Nothing);
+        if (n == -1) caml_uerror("write", Nothing);
     };
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.interrupt_event_aggregator not available");
+    caml_invalid_argument("Netsys_posix.interrupt_event_aggregator not available");
 #endif
 }
 
@@ -427,12 +427,12 @@ CAMLprim value netsys_push_event_sources(value pav, value pushlistv)
 	    EPOLLONESHOT;
 	ee.data.u64 = Long_val(Field(v_pushlist_hd, 0)) << 1;
 	code = epoll_ctl(pa->fd, EPOLL_CTL_MOD, fd, &ee);
-	if (code == -1) uerror("epoll_ctl (MOD)", Nothing);
+	if (code == -1) caml_uerror("epoll_ctl (MOD)", Nothing);
 #endif
     };
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.push_event_sources not available");
+    caml_invalid_argument("Netsys_posix.push_event_sources not available");
 #endif
 }
 
@@ -459,7 +459,7 @@ CAMLprim value netsys_poll_event_sources(value pav, value tmov)
     code = epoll_wait(pa->fd, ee, EPOLL_NUM, tmo);
     e = errno;
     caml_leave_blocking_section();
-    if (code == -1) unix_error(e, "epoll_wait", Nothing);
+    if (code == -1) caml_unix_error(e, "epoll_wait", Nothing);
 
     r = Val_int(0);
     for (k=0; k<code; k++) {
@@ -467,7 +467,7 @@ CAMLprim value netsys_poll_event_sources(value pav, value tmov)
 	    uint64_t buf;
             int n;
 	    n = read(pa->cancel_fd, (char *) &buf, 8);
-            if (n == -1) unix_error(errno, "read", Nothing);
+            if (n == -1) caml_unix_error(errno, "read", Nothing);
 	}
 	else {
 	    r_item = caml_alloc(3,0);
@@ -486,6 +486,6 @@ CAMLprim value netsys_poll_event_sources(value pav, value tmov)
 
     CAMLreturn(r);
 #else
-    invalid_argument("Netsys_posix.pull_event_sources not available");
+    caml_invalid_argument("Netsys_posix.pull_event_sources not available");
 #endif
 }
diff --git a/src/netsys/netsys_c_sem.c b/src/netsys/netsys_c_sem.c
index 97c68fb..9295b23 100644
--- a/src/netsys/netsys_c_sem.c
+++ b/src/netsys/netsys_c_sem.c
@@ -120,16 +120,16 @@ CAMLprim value netsys_sem_open(value namev,
     int flags;
 
     init = Long_val(initv);
-    flags = convert_flag_list(flagsv, sem_open_flag_table);
+    flags = caml_convert_flag_list(flagsv, sem_open_flag_table);
     s = sem_open(String_val(namev),
 		 flags,
 		 Int_val(modev),
 		 init);
-    if (s == (sem_t *) SEM_FAILED) uerror("sem_open", namev);
+    if (s == (sem_t *) SEM_FAILED) caml_uerror("sem_open", namev);
     r = alloc_sem_block(s, 1);
     return r;
 #else
-    invalid_argument("Netsys.sem_open not available");
+    caml_invalid_argument("Netsys.sem_open not available");
 #endif
 }
 
@@ -141,13 +141,13 @@ CAMLprim value netsys_sem_close(value srv)
 
     sb = Sem_block_val(srv);
     if (sb->sem_ptr == NULL)
-	invalid_argument ("Netsys.sem_close: stale semaphore");
+	caml_invalid_argument ("Netsys.sem_close: stale semaphore");
     code = sem_close(sb->sem_ptr);
-    if (code == -1) uerror("sem_close", Nothing);
+    if (code == -1) caml_uerror("sem_close", Nothing);
     sb->sem_ptr = NULL;
     return Val_unit;
 #else
-    invalid_argument("Netsys.sem_close not available");
+    caml_invalid_argument("Netsys.sem_close not available");
 #endif
 }
 
@@ -156,10 +156,10 @@ CAMLprim value netsys_sem_unlink(value namev)
 #ifdef HAVE_POSIX_SEM_NAMED
     int code;
     code = sem_unlink(String_val(namev));
-    if (code == -1) uerror("sem_unlink", Nothing);
+    if (code == -1) caml_uerror("sem_unlink", Nothing);
     return Val_unit;
 #else
-    invalid_argument("Netsys.sem_unlink not available");
+    caml_invalid_argument("Netsys.sem_unlink not available");
 #endif
 }
 
@@ -175,13 +175,13 @@ CAMLprim value netsys_sem_init(value memv,
     value r;
 
     init = Long_val(initv);
-    s = (sem_t *) (((char *) Bigarray_val(memv)->data) + Long_val(posv));
+    s = (sem_t *) (((char *) Caml_ba_array_val(memv)->data) + Long_val(posv));
     code = sem_init(s, Bool_val(psharedv), init);
-    if (code == -1) uerror("sem_init", Nothing);
+    if (code == -1) caml_uerror("sem_init", Nothing);
     r = alloc_sem_block(s, 0);
     return r;
 #else
-    invalid_argument("Netsys.sem_init not available");
+    caml_invalid_argument("Netsys.sem_init not available");
 #endif
 }
 
@@ -192,11 +192,11 @@ CAMLprim value netsys_as_sem(value memv,
     sem_t *s;
     value r;
 
-    s = (sem_t *) (((char *) Bigarray_val(memv)->data) + Long_val(posv));
+    s = (sem_t *) (((char *) Caml_ba_array_val(memv)->data) + Long_val(posv));
     r = alloc_sem_block(s, 0);
     return r;
 #else
-    invalid_argument("Netsys.as_sem not available");
+    caml_invalid_argument("Netsys.as_sem not available");
 #endif
 }
 
@@ -209,13 +209,13 @@ CAMLprim value netsys_sem_destroy(value srv)
 
     sb = Sem_block_val(srv);
     if (sb->sem_ptr == NULL)
-	invalid_argument ("Netsys.sem_destroy: stale semaphore");
+	caml_invalid_argument ("Netsys.sem_destroy: stale semaphore");
     code = sem_destroy(sb->sem_ptr);
-    if (code == -1) uerror("sem_destroy", Nothing);
+    if (code == -1) caml_uerror("sem_destroy", Nothing);
     sb->sem_ptr = NULL;
     return Val_unit;
 #else
-    invalid_argument("Netsys.sem_destroy not available");
+    caml_invalid_argument("Netsys.sem_destroy not available");
 #endif
 }
 
@@ -229,16 +229,16 @@ CAMLprim value netsys_sem_getvalue(value srv)
 
     sb = Sem_block_val(srv);
     if (sb->sem_ptr == NULL)
-	invalid_argument ("Netsys.sem_getvalue: stale semaphore");
+	caml_invalid_argument ("Netsys.sem_getvalue: stale semaphore");
     code = sem_getvalue(sb->sem_ptr, &sval);
-    if (code == -1) uerror("sem_getvalue", Nothing);
+    if (code == -1) caml_uerror("sem_getvalue", Nothing);
     if (sval < 0) sval = 0;
 #ifndef ARCH_SIXTYFOUR
-    if (sval > 1073741823) unix_error(EINVAL, "sem_getvalue", Nothing);
+    if (sval > 1073741823) caml_unix_error(EINVAL, "sem_getvalue", Nothing);
 #endif
     return Val_int(sval);
 #else
-    invalid_argument("Netsys.sem_getvalue not available");
+    caml_invalid_argument("Netsys.sem_getvalue not available");
 #endif
 }
 
@@ -250,12 +250,12 @@ CAMLprim value netsys_sem_post(value srv)
 
     sb = Sem_block_val(srv);
     if (sb->sem_ptr == NULL)
-	invalid_argument ("Netsys.sem_post: stale semaphore");
+	caml_invalid_argument ("Netsys.sem_post: stale semaphore");
     code = sem_post(sb->sem_ptr);
-    if (code == -1) uerror("sem_post", Nothing);
+    if (code == -1) caml_uerror("sem_post", Nothing);
     return Val_unit;
 #else
-    invalid_argument("Netsys.sem_post not available");
+    caml_invalid_argument("Netsys.sem_post not available");
 #endif
 }
 
@@ -270,19 +270,19 @@ CAMLprim value netsys_sem_wait(value srv, value bv)
 
     sb = Sem_block_val(srv);
     if (sb->sem_ptr == NULL)
-	invalid_argument ("Netsys.sem_wait: stale semaphore");
+	caml_invalid_argument ("Netsys.sem_wait: stale semaphore");
     tag = Int_val(bv);
     s = sb->sem_ptr;
-    enter_blocking_section();
+    caml_enter_blocking_section();
     if (tag == 0)
 	code = sem_wait(s);
     else
 	code = sem_trywait(s);
-    leave_blocking_section();
-    if (code == -1) uerror("sem_wait", Nothing);
+    caml_leave_blocking_section();
+    if (code == -1) caml_uerror("sem_wait", Nothing);
     return Val_unit;
 #else
-    invalid_argument("Netsys.sem_wait not available");
+    caml_invalid_argument("Netsys.sem_wait not available");
 #endif
 }
 
diff --git a/src/netsys/netsys_c_shm.c b/src/netsys/netsys_c_shm.c
index e65f99f..3356e2a 100644
--- a/src/netsys/netsys_c_shm.c
+++ b/src/netsys/netsys_c_shm.c
@@ -36,15 +36,15 @@ CAMLprim value netsys_shm_open(value path, value flags, value perm)
     int ret, cv_flags;
     char * p;
 
-    cv_flags = convert_flag_list(flags, shm_open_flag_table);
-    p = stat_alloc(string_length(path) + 1);
+    cv_flags = caml_convert_flag_list(flags, shm_open_flag_table);
+    p = caml_stat_alloc(caml_string_length(path) + 1);
     strcpy(p, String_val(path));
     ret = shm_open(p, cv_flags, Int_val(perm));
-    stat_free(p);
+    caml_stat_free(p);
     if (ret == -1) uerror("shm_open", path);
     CAMLreturn (Val_int(ret));
 #else
-    invalid_argument("Netsys.shm_open not available");
+    caml_invalid_argument("Netsys.shm_open not available");
 #endif
 }
 
@@ -58,7 +58,7 @@ CAMLprim value netsys_shm_unlink(value path)
     if (ret == -1) uerror("shm_unlink", path);
     return Val_unit;
 #else
-    invalid_argument("Netsys.shm_unlink not available");
+    caml_invalid_argument("Netsys.shm_unlink not available");
 #endif
 }
 
diff --git a/src/netsys/netsys_c_spawn.c b/src/netsys/netsys_c_spawn.c
index 7ead37d..e8396ee 100644
--- a/src/netsys/netsys_c_spawn.c
+++ b/src/netsys/netsys_c_spawn.c
@@ -112,15 +112,15 @@ CAMLprim value netsys_spawn_nat(value v_chdir,
        In the calling process, the mask is reset below at [exit].
     */
     code = sigfillset(&mask);
-    if (code == -1) unix_error(EINVAL, "netsys_spawn/sigfillset [000]", 
+    if (code == -1) caml_unix_error(EINVAL, "netsys_spawn/sigfillset [000]", 
 			       Nothing);
 #ifdef HAVE_PTHREAD
     code = pthread_sigmask(SIG_SETMASK, &mask, &save_mask);
-    if (code != 0) unix_error(code, "netsys_spawn/pthread_sigmask [001]", 
+    if (code != 0) caml_unix_error(code, "netsys_spawn/pthread_sigmask [001]", 
 			      Nothing);
 #else
     code = sigprocmask(SIG_SETMASK, &mask, &save_mask);
-    if (code == -1) uerror("netsys_spawn/sigprocmask [002]", Nothing);
+    if (code == -1) caml_uerror("netsys_spawn/sigprocmask [002]", Nothing);
 #endif
     memcpy(&spawn_mask, &save_mask, sizeof(sigset_t));
 
@@ -357,8 +357,8 @@ CAMLprim value netsys_spawn_nat(value v_chdir,
 
     /* exec the new program: */
     code = execve(String_val(v_cmd),
-		  sub_argv,
-		  sub_env);
+		  (char * const *) sub_argv,
+		  (char * const *) sub_env);
     if (code == -1) SUB_ERROR(errno, "netsys_spawn/execve [290]");
 
     SUB_ERROR(EINVAL, "netsys_spawn/assert_execve [291]");
@@ -473,11 +473,11 @@ main_exit:
     }
 
     if (uerror_errno != 0)
-	unix_error(uerror_errno, uerror_function, Nothing);
+	caml_unix_error(uerror_errno, uerror_function, Nothing);
 
     return return_value;
 #else
-     invalid_argument("netsys_spawn");
+     caml_invalid_argument("netsys_spawn");
 #endif
 }
 
@@ -614,7 +614,7 @@ CAMLprim value netsys_posix_spawn_nat(value v_pg,
 	    flags |= POSIX_SPAWN_SETPGROUP;
 	    break;
 	case 2: /* Pg_new_fg_group */
-	    invalid_argument
+	    caml_invalid_argument
 		("Netsys_posix.posix_spawn: Pg_new_fg_group not supported");
 	    break;
 	default:
@@ -638,7 +638,7 @@ CAMLprim value netsys_posix_spawn_nat(value v_pg,
 	    flags |= POSIX_SPAWN_SETSIGDEF;
 	    break;
 	case 1: /* Sig_ignore */
-	    invalid_argument
+	    caml_invalid_argument
 		("Netsys_posix.posix_spawn: Sig_ignore not supported");
 	    break;
 	case 2: /* Sig_mask */
@@ -800,15 +800,15 @@ main_exit:
     };
 
     if (uerror_errno != 0)
-	unix_error(uerror_errno, uerror_function, Nothing);
+	caml_unix_error(uerror_errno, uerror_function, Nothing);
 
     if (use_fork_exec != 0)
-	failwith("USE_FORK_EXEC");
+	caml_failwith("USE_FORK_EXEC");
 
     return return_value;
 
 #else
-     invalid_argument("netsys_posix_spawn not available");
+     caml_invalid_argument("netsys_posix_spawn not available");
 #endif
 }
 
diff --git a/src/netsys/netsys_c_subprocess.c b/src/netsys/netsys_c_subprocess.c
index a940175..a3cf4b1 100644
--- a/src/netsys/netsys_c_subprocess.c
+++ b/src/netsys/netsys_c_subprocess.c
@@ -282,7 +282,7 @@ CAMLprim value netsys_install_sigchld_handler(value dummy) {
 	    (struct sigchld_atom *) malloc(sigchld_list_len * 
 					   sizeof(struct sigchld_atom));
 	if (sigchld_list == NULL) 
-	    failwith("Cannot allocate memory");
+	    caml_failwith("Cannot allocate memory");
 
 	for (k=0; k<sigchld_list_len; k++)
 	    sigchld_list[k].pid = 0;
@@ -295,14 +295,14 @@ CAMLprim value netsys_install_sigchld_handler(value dummy) {
 	code = errno;
 	sigchld_unlock(1);
 	errno = code;
-	uerror("sigaction", Nothing);
+	caml_uerror("sigaction", Nothing);
     };
 
     sigchld_unlock(1);
 
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.install_subprocess_handler not available");
+    caml_invalid_argument("Netsys_posix.install_subprocess_handler not available");
 #endif
 }
 
@@ -349,17 +349,17 @@ CAMLprim value netsys_watch_subprocess(value pid_v, value pgid_v,
     int status, code, kill_flag;
     
     if (sigchld_list == NULL)
-	failwith("Netsys_posix.watch_subprocess: uninitialized");
+	caml_failwith("Netsys_posix.watch_subprocess: uninitialized");
 
     if (pipe(pfd) == -1)
-	uerror("pipe", Nothing);
+	caml_uerror("pipe", Nothing);
 
     if (fcntl(pfd[0], F_SETFD, FD_CLOEXEC) == -1) {
 	code = errno;
 	close(pfd[0]);
 	close(pfd[1]);
 	errno = code;
-	uerror("set_close_on_exec", Nothing);
+	caml_uerror("set_close_on_exec", Nothing);
     };
 
     if (fcntl(pfd[1], F_SETFD, FD_CLOEXEC) == -1) {
@@ -367,7 +367,7 @@ CAMLprim value netsys_watch_subprocess(value pid_v, value pgid_v,
 	close(pfd[0]);
 	close(pfd[1]);
 	errno = code;
-	uerror("set_close_on_exec", Nothing);
+	caml_uerror("set_close_on_exec", Nothing);
     };
 
     pid = Int_val(pid_v);
@@ -391,7 +391,7 @@ CAMLprim value netsys_watch_subprocess(value pid_v, value pgid_v,
 	if (sigchld_init_mt() == -1) {
 	    int saved_errno = errno;
 	    sigchld_unlock(1);
-	    unix_error(saved_errno,
+	    caml_unix_error(saved_errno,
 		       "netsys_watch_subprocess [delayed init]",
 		       Nothing);
 	}
@@ -425,7 +425,7 @@ CAMLprim value netsys_watch_subprocess(value pid_v, value pgid_v,
 	    sigchld_unlock(1);
 	    close(pfd[0]);
 	    close(pfd[1]);
-	    failwith("Cannot allocate memory");
+	    caml_failwith("Cannot allocate memory");
 	};
 
 	for (k=old_size; k<sigchld_list_len; k++)
@@ -444,7 +444,7 @@ CAMLprim value netsys_watch_subprocess(value pid_v, value pgid_v,
 	close(pfd[0]);
 	close(pfd[1]);
 	errno = code;
-	uerror("waitpid", Nothing);
+	caml_uerror("waitpid", Nothing);
     };
 
     if (code == 0) {  /* not yet terminated */
@@ -469,13 +469,13 @@ CAMLprim value netsys_watch_subprocess(value pid_v, value pgid_v,
 
     sigchld_unlock(1);
 
-    r = alloc(2,0);
+    r = caml_alloc(2,0);
     Field(r,0) = Val_int(pfd[0]);
     Field(r,1) = Val_int(atom_idx);
     
     return r;
 #else
-    invalid_argument("Netsys_posix.watch_subprocess not available");
+    caml_invalid_argument("Netsys_posix.watch_subprocess not available");
 #endif
 }
 
@@ -498,7 +498,7 @@ CAMLprim value netsys_ignore_subprocess(value atom_idx_v) {
 
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.ignore_subprocess not available");
+    caml_invalid_argument("Netsys_posix.ignore_subprocess not available");
 #endif
 }
 
@@ -521,7 +521,7 @@ CAMLprim value netsys_forget_subprocess(value atom_idx_v) {
 
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.forget_subprocess not available");
+    caml_invalid_argument("Netsys_posix.forget_subprocess not available");
 #endif
 }
 
@@ -554,15 +554,15 @@ CAMLprim value netsys_get_subprocess_status(value atom_idx_v) {
 
     if (copy.terminated) {
 	if (WIFEXITED(copy.status)) {
-	    st = alloc_small(1, TAG_WEXITED);
+	    st = caml_alloc_small(1, TAG_WEXITED);
 	    Field(st, 0) = Val_int(WEXITSTATUS(copy.status));
 	}
 	else {
-	    st = alloc_small(1, TAG_WSIGNALED);
+	    st = caml_alloc_small(1, TAG_WSIGNALED);
 	    Field(st, 0) = 
 		Val_int(caml_rev_convert_signal_number(WTERMSIG(copy.status)));
 	};
-	r = alloc(1,0);
+	r = caml_alloc(1,0);
 	Field(r, 0) = st;
     }
     else {
@@ -571,7 +571,7 @@ CAMLprim value netsys_get_subprocess_status(value atom_idx_v) {
 
     return r;
 #else
-    invalid_argument("Netsys_posix.forget_subprocess not available");
+    caml_invalid_argument("Netsys_posix.forget_subprocess not available");
 #endif
 }
 
@@ -597,7 +597,7 @@ CAMLprim value netsys_kill_subprocess(value sig_v, value atom_idx_v) {
     return Val_unit;
 
 #else
-    invalid_argument("Netsys_posix.kill_subprocess not available");
+    caml_invalid_argument("Netsys_posix.kill_subprocess not available");
 #endif
 }
 
@@ -634,7 +634,7 @@ CAMLprim value netsys_killpg_subprocess(value sig_v, value atom_idx_v) {
     return Val_unit;
 
 #else
-    invalid_argument("Netsys_posix.killpg_subprocess not available");
+    caml_invalid_argument("Netsys_posix.killpg_subprocess not available");
 #endif
 }
 
@@ -648,7 +648,7 @@ CAMLprim value netsys_kill_all_subprocesses(value sig_v, value o_flag_v,
     int k;
 
     if (sigchld_list == NULL)
-	failwith("Netsys_posix.watch_subprocess: uninitialized");
+	caml_failwith("Netsys_posix.watch_subprocess: uninitialized");
 
     sig = caml_convert_signal_number(Int_val(sig_v));
     o_flag = Bool_val(o_flag_v);
@@ -672,7 +672,7 @@ CAMLprim value netsys_kill_all_subprocesses(value sig_v, value o_flag_v,
     return Val_unit;
 
 #else
-    invalid_argument("Netsys_posix.kill_all_subprocesses not available");
+    caml_invalid_argument("Netsys_posix.kill_all_subprocesses not available");
 #endif
 }
 
@@ -686,7 +686,7 @@ CAMLprim value netsys_killpg_all_subprocesses(value sig_v, value o_flag_v) {
     pid_t pgid;
 
     if (sigchld_list == NULL)
-	failwith("Netsys_posix.watch_subprocess: uninitialized");
+	caml_failwith("Netsys_posix.watch_subprocess: uninitialized");
 
     sig = caml_convert_signal_number(Int_val(sig_v));
     o_flag = Bool_val(o_flag_v);
@@ -722,7 +722,7 @@ CAMLprim value netsys_killpg_all_subprocesses(value sig_v, value o_flag_v) {
     return Val_unit;
 
 #else
-    invalid_argument("Netsys_posix.killpg_all_subprocesses not available");
+    caml_invalid_argument("Netsys_posix.killpg_all_subprocesses not available");
 #endif
 }
 
diff --git a/src/netsys/netsys_c_syslog.c b/src/netsys/netsys_c_syslog.c
index 4552fe7..8876284 100644
--- a/src/netsys/netsys_c_syslog.c
+++ b/src/netsys/netsys_c_syslog.c
@@ -68,6 +68,7 @@ static int syslog_opt_flags[] = {
     LOG_CONS, LOG_NDELAY, LOG_ODELAY, LOG_NOWAIT, LOG_PID
 };
 
+// FIXME DOMAINS
 static char *ident_buf = NULL;
 #define IDENT_BUF_LEN 256
 #endif
@@ -86,7 +87,7 @@ CAMLprim value netsys_openlog(value ident,
     id=NULL;
     if (Is_block(ident)) {
 	if (ident_buf == NULL) {
-	    ident_buf = stat_alloc(IDENT_BUF_LEN);
+	    ident_buf = caml_stat_alloc(IDENT_BUF_LEN);
 	};
 	strncpy(ident_buf, 
 		String_val(Field(ident, 0)),
@@ -94,12 +95,12 @@ CAMLprim value netsys_openlog(value ident,
 	ident_buf[IDENT_BUF_LEN-1] = 0;
 	id=ident_buf;
     };
-    options = convert_flag_list(opts, syslog_opt_flags);
+    options = caml_convert_flag_list(opts, syslog_opt_flags);
     facility = syslog_fac_flags[Int_val(fac)];
     openlog(id, options, facility);
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.openlog not available");
+    caml_invalid_argument("Netsys_posix.openlog not available");
 #endif
 }
 
@@ -114,7 +115,7 @@ CAMLprim value netsys_syslog(value fac, value lev, value msg)
     syslog(facility | level, "%s", String_val(msg));
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.syslog not available");
+    caml_invalid_argument("Netsys_posix.syslog not available");
 #endif
 }
 
@@ -125,7 +126,7 @@ CAMLprim value netsys_closelog(value dummy)
     closelog();
     return Val_unit;
 #else
-    invalid_argument("Netsys_posix.closelog not available");
+    caml_invalid_argument("Netsys_posix.closelog not available");
 #endif
 }
 
diff --git a/src/netsys/netsys_c_win32.c b/src/netsys/netsys_c_win32.c
index 0043336..69015a8 100644
--- a/src/netsys/netsys_c_win32.c
+++ b/src/netsys/netsys_c_win32.c
@@ -57,7 +57,7 @@ CAMLprim value netsys_fill_random (value s) {
     };
     return Val_unit;
 #else
-    invalid_argument("netsys_fill_random");
+    caml_invalid_argument("netsys_fill_random");
 #endif
 }
 
@@ -76,7 +76,7 @@ CAMLprim value netsys_get_full_path_name(value path) {
     };
     return caml_copy_string(buffer);
 #else
-    invalid_argument("netsys_get_full_path_name");
+    caml_invalid_argument("netsys_get_full_path_name");
 #endif
 }
 
@@ -94,7 +94,7 @@ CAMLprim value netsys_get_long_path_name(value path) {
     };
     return caml_copy_string(buffer);
 #else
-    invalid_argument("netsys_get_long_path_name");
+    caml_invalid_argument("netsys_get_long_path_name");
 #endif
 }
 
@@ -112,7 +112,7 @@ CAMLprim value netsys_modify_close_on_exec (value fd, value new_val) {
     }
     return Val_unit;
 #else
-    invalid_argument("netsys_modify_close_on_exec");
+    caml_invalid_argument("netsys_modify_close_on_exec");
 #endif
 }
 
@@ -131,7 +131,7 @@ CAMLprim value netsys_test_close_on_exec (value fd) {
 	    Handle_val(fd), r ? "true" : "false");
     return Val_bool(r);
 #else
-    invalid_argument("netsys_test_close_on_exec");
+    caml_invalid_argument("netsys_test_close_on_exec");
 #endif
 }
 
@@ -145,7 +145,7 @@ CAMLprim value netsys_is_crt_fd (value fd, value crt_fd) {
     else
 	return Val_bool(fd1 == Int_val(crt_fd));
 #else
-    invalid_argument("netsys_is_crt_fd");
+    caml_invalid_argument("netsys_is_crt_fd");
 #endif
 }
 
@@ -224,7 +224,7 @@ CAMLprim value netsys_create_event(value dummy) {
 
     return alloc_event(e);
 #else
-    invalid_argument("netsys_create_event");
+    caml_invalid_argument("netsys_create_event");
 #endif
 }
 
@@ -246,7 +246,7 @@ CAMLprim value netsys_close_event(value ev) {
 
     return Val_unit;
 #else
-    invalid_argument("netsys_close_event");
+    caml_invalid_argument("netsys_close_event");
 #endif
 }
 
@@ -259,7 +259,7 @@ CAMLprim value netsys_set_auto_close_event_proxy(value ev, value flag) {
     e->auto_close = Bool_val(flag);
     return Val_unit;
 #else
-    invalid_argument("netsys_set_auto_close_event_proxy");
+    caml_invalid_argument("netsys_set_auto_close_event_proxy");
 #endif
 }
 
@@ -276,7 +276,7 @@ CAMLprim value netsys_set_event(value ev) {
 
     return Val_unit;
 #else
-    invalid_argument("netsys_set_event");
+    caml_invalid_argument("netsys_set_event");
 #endif
 }
 
@@ -292,7 +292,7 @@ CAMLprim value netsys_reset_event(value ev) {
 
     return Val_unit;
 #else
-    invalid_argument("netsys_reset_event");
+    caml_invalid_argument("netsys_reset_event");
 #endif
 }
 
@@ -312,7 +312,7 @@ CAMLprim value netsys_test_event(value ev) {
 
     return Val_bool(n == WAIT_OBJECT_0);
 #else
-    invalid_argument("netsys_test_event");
+    caml_invalid_argument("netsys_test_event");
 #endif
 }
 
@@ -331,10 +331,10 @@ CAMLprim value netsys_event_wait(value ev, value tmo) {
     };
 
     e = event_val(ev);
-    enter_blocking_section();
+    caml_enter_blocking_section();
     n = WaitForSingleObject(e->ev, wtmo);
     err = GetLastError();
-    leave_blocking_section();
+    caml_leave_blocking_section();
     if (n == WAIT_FAILED) {
 	win32_maperr(err);
 	uerror("netsys_event_wait/WaitForSingleObject", Nothing);
@@ -342,7 +342,7 @@ CAMLprim value netsys_event_wait(value ev, value tmo) {
 
     return Val_bool(n == WAIT_OBJECT_0);
 #else
-    invalid_argument("netsys_event_wait");
+    caml_invalid_argument("netsys_event_wait");
 #endif
 }
 
@@ -353,7 +353,7 @@ CAMLprim value netsys_event_descr(value ev) {
     e = event_val(ev);
     return netsysw32_win_alloc_handle(e->ev_proxy);
 #else
-    invalid_argument("netsys_event_descr");
+    caml_invalid_argument("netsys_event_descr");
 #endif
 }
 
@@ -383,7 +383,7 @@ CAMLprim value netsys_wsa_event_select(value ev, value fdv, value evmaskv) {
 
     return Val_unit;
 #else
-    invalid_argument("netsys_wsa_event_select");
+    caml_invalid_argument("netsys_wsa_event_select");
 #endif
 }
 
@@ -391,7 +391,7 @@ CAMLprim value netsys_wsa_maximum_wait_events(value dummy) {
 #ifdef _WIN32
     return Val_int(WSA_MAXIMUM_WAIT_EVENTS);
 #else
-    invalid_argument("netsys_wsa_maximum_wait_events");
+    caml_invalid_argument("netsys_wsa_maximum_wait_events");
 #endif
 }
 
@@ -428,9 +428,9 @@ CAMLprim value netsys_wsa_wait_for_multiple_events(value fdarray, value tmov) {
 	    tmo = tmo0;
 	else
 	    tmo = INFINITE;
-	enter_blocking_section();
+	caml_enter_blocking_section();
 	r = SleepEx(tmo, 1);
-	leave_blocking_section();
+	caml_leave_blocking_section();
 	
 	if (r == WAIT_IO_COMPLETION) {
 	    win32_maperr(EINTR);
@@ -445,10 +445,10 @@ CAMLprim value netsys_wsa_wait_for_multiple_events(value fdarray, value tmov) {
 	else
 	    tmo = INFINITE;
 	dprintf("WSAWaitForMultipleEvents start tmo=%u\n", tmo);
-	enter_blocking_section();
+	caml_enter_blocking_section();
 	r = WSAWaitForMultipleEvents(n, earray, 0, tmo, 1);
 	err = WSAGetLastError();
-	leave_blocking_section();
+	caml_leave_blocking_section();
 	dprintf("WSAWaitForMultipleEvents end code=%u\n", r);
     
 	if (r == WSA_WAIT_FAILED) {
@@ -476,9 +476,9 @@ CAMLprim value netsys_wsa_wait_for_multiple_events(value fdarray, value tmov) {
 	}
     }
     
-    invalid_argument("netsys_wsa_wait_for_multiple_events: bad return value from Win32");
+    caml_invalid_argument("netsys_wsa_wait_for_multiple_events: bad return value from Win32");
 #else
-    invalid_argument("netsys_wsa_wait_for_multiple_events");
+    caml_invalid_argument("netsys_wsa_wait_for_multiple_events");
 #endif
 }
 
@@ -538,7 +538,7 @@ CAMLprim value netsys_wsa_enum_network_events(value fdv, value ev) {
 
     return Val_int(r);
 #else
-    invalid_argument("netsys_wsa_enum_network_events");
+    caml_invalid_argument("netsys_wsa_enum_network_events");
 #endif
 }
 
@@ -626,20 +626,20 @@ static struct pipe_helper * alloc_pipe_helper (HANDLE h, HANDLE cn_ev) {
 	uerror("alloc_pipe_helper/CreateEvent", Nothing);
     };
 
-    rd_ovrlp = stat_alloc(sizeof(OVERLAPPED));
+    rd_ovrlp = caml_stat_alloc(sizeof(OVERLAPPED));
     ZeroMemory(rd_ovrlp, sizeof(OVERLAPPED));
     rd_ovrlp->hEvent = rd_ev;
 
-    wr_ovrlp = stat_alloc(sizeof(OVERLAPPED));
+    wr_ovrlp = caml_stat_alloc(sizeof(OVERLAPPED));
     ZeroMemory(wr_ovrlp, sizeof(OVERLAPPED));
     wr_ovrlp->hEvent = wr_ev;
 
-    cn_ovrlp = stat_alloc(sizeof(OVERLAPPED));
+    cn_ovrlp = caml_stat_alloc(sizeof(OVERLAPPED));
     ZeroMemory(cn_ovrlp, sizeof(OVERLAPPED));
     if (cn_ev != INVALID_HANDLE_VALUE)
 	cn_ovrlp->hEvent = cn_ev;
 
-    ph = stat_alloc(sizeof(struct pipe_helper));
+    ph = caml_stat_alloc(sizeof(struct pipe_helper));
     ph->pipe_handle = h;
     ph->pipe_is_open = 1;
     ph->pipe_is_server = 0;
@@ -680,10 +680,10 @@ static void free_pipe_helper(struct pipe_helper *ph) {
     if (ph->pipe_cn_ev != INVALID_HANDLE_VALUE)
 	CloseHandle(ph->pipe_cn_ev);
     /* do nothing about pipe_signal */
-    stat_free(ph->pipe_rd_ovrlp);
-    stat_free(ph->pipe_wr_ovrlp);
-    stat_free(ph->pipe_cn_ovrlp);
-    stat_free(ph);
+    caml_stat_free(ph->pipe_rd_ovrlp);
+    caml_stat_free(ph->pipe_wr_ovrlp);
+    caml_stat_free(ph->pipe_cn_ovrlp);
+    caml_stat_free(ph);
 }
 
 
@@ -1032,7 +1032,7 @@ CAMLprim value netsys_create_local_named_pipe(value name, value mode,
 	    ph->pipe_handle);
     return r;
 #else
-    invalid_argument("netsys_create_local_named_pipe");
+    caml_invalid_argument("netsys_create_local_named_pipe");
 #endif
 }
 
@@ -1130,7 +1130,7 @@ CAMLprim value netsys_pipe_listen(value phv) {
 
     return Val_unit;
 #else
-    invalid_argument("netsys_pipe_listen");
+    caml_invalid_argument("netsys_pipe_listen");
 #endif
 }
 
@@ -1175,13 +1175,13 @@ CAMLprim value netsys_pipe_deafen(value phv) {
     /* Check whether the overlapped ops are done: */
     check_for_pending_operations(ph);
     if (ph->pipe_cn_ovrlp_started) {
-	failwith("netsys_pipe_unlisten: cannot stop pending ConnectNamedPipe");
+	caml_failwith("netsys_pipe_unlisten: cannot stop pending ConnectNamedPipe");
     };
     if (ph->pipe_rd_ovrlp_started) {
-	failwith("netsys_pipe_unlisten: cannot stop pending ReadFile");
+	caml_failwith("netsys_pipe_unlisten: cannot stop pending ReadFile");
     };
     if (ph->pipe_wr_ovrlp_started) {
-	failwith("netsys_pipe_unlisten: cannot stop pending WriteFile");
+	caml_failwith("netsys_pipe_unlisten: cannot stop pending WriteFile");
     };
 
     dprintf("PIPE deafen %u successful\n",
@@ -1202,7 +1202,7 @@ CAMLprim value netsys_pipe_deafen(value phv) {
     return Val_unit;
 
 #else
-    invalid_argument("netsys_pipe_unlisten");
+    caml_invalid_argument("netsys_pipe_unlisten");
 #endif
 }
 
@@ -1272,7 +1272,7 @@ CAMLprim value netsys_pipe_connect(value name, value mode) {
     return r;
 
 #else
-    invalid_argument("netsys_pipe_connect");
+    caml_invalid_argument("netsys_pipe_connect");
 #endif
 }
 
@@ -1333,7 +1333,7 @@ CAMLprim value netsys_pipe_read(value phv, value s, value pos, value len) {
 
     return Val_int(l);
 #else
-    invalid_argument("netsys_pipe_read");
+    caml_invalid_argument("netsys_pipe_read");
 #endif
 }
 
@@ -1400,7 +1400,7 @@ CAMLprim value netsys_pipe_write(value phv, value s, value pos, value len) {
 
     return Val_int(l);
 #else
-    invalid_argument("netsys_pipe_write");
+    caml_invalid_argument("netsys_pipe_write");
 #endif
 }
 
@@ -1438,7 +1438,7 @@ CAMLprim value netsys_pipe_shutdown(value phv) {
 
     return Val_unit;
 #else
-    invalid_argument("netsys_pipe_shutdown");
+    caml_invalid_argument("netsys_pipe_shutdown");
 #endif
 }
 
@@ -1453,7 +1453,7 @@ CAMLprim value netsys_pipe_free(value phv) {
 
     return Val_unit;
 #else
-    invalid_argument("netsys_pipe_free");
+    caml_invalid_argument("netsys_pipe_free");
 #endif
 }
 
@@ -1469,7 +1469,7 @@ CAMLprim value netsys_pipe_conn_state(value phv) {
 
     return Val_int(ph->pipe_conn_state);
 #else
-    invalid_argument("netsys_pipe_conn_state");
+    caml_invalid_argument("netsys_pipe_conn_state");
 #endif
 }
 
@@ -1487,7 +1487,7 @@ CAMLprim value netsys_pipe_rd_event(value phv) {
 
     return alloc_event(ph->pipe_rd_ev);
 #else
-    invalid_argument("netsys_pipe_rd_event");
+    caml_invalid_argument("netsys_pipe_rd_event");
 #endif
 }
 
@@ -1505,7 +1505,7 @@ CAMLprim value netsys_pipe_wr_event(value phv) {
 
     return alloc_event(ph->pipe_wr_ev);
 #else
-    invalid_argument("netsys_pipe_wr_event");
+    caml_invalid_argument("netsys_pipe_wr_event");
 #endif
 }
 
@@ -1518,7 +1518,7 @@ CAMLprim value netsys_pipe_descr(value phv) {
 
     return netsysw32_win_alloc_handle(ph->pipe_descr);
 #else
-    invalid_argument("netsys_pipe_descr");
+    caml_invalid_argument("netsys_pipe_descr");
 #endif
 }
 
@@ -1530,7 +1530,7 @@ CAMLprim value netsys_set_auto_close_pipe_proxy(value phv, value flag) {
     ph->pipe_descr_auto_close = Bool_val(flag);
     return Val_unit;
 #else
-    invalid_argument("netsys_set_auto_close_pipe_proxy");
+    caml_invalid_argument("netsys_set_auto_close_pipe_proxy");
 #endif
 }
 
@@ -1546,7 +1546,7 @@ CAMLprim value netsys_pipe_signal(value phv, value ev) {
 
     return Val_unit;
 #else
-    invalid_argument("netsys_pipe_signal");
+    caml_invalid_argument("netsys_pipe_signal");
 #endif
 }
 
@@ -1658,7 +1658,7 @@ CAMLprim value netsys_create_process(value cmd,
 	      pass_std_handles = 1;
 	      break;
 	  default:
-	      invalid_argument("netsys_create_process [1]");
+	      caml_invalid_argument("netsys_create_process [1]");
 	  }
       }
       else {
@@ -1687,7 +1687,7 @@ CAMLprim value netsys_create_process(value cmd,
 	      pg_flags = 0;
 	      break;
 	  default:
-	      invalid_argument("netsys_create_process [2]");
+	      caml_invalid_argument("netsys_create_process [2]");
 	  }
       };
       opts_hd = Field(opts_hd,1);
@@ -1716,7 +1716,7 @@ CAMLprim value netsys_create_process(value cmd,
 	  pi.hProcess, pi.dwProcessId);
   return alloc_process(pi.hProcess, pi.dwProcessId);
 #else
-    invalid_argument("netsys_create_process");
+    caml_invalid_argument("netsys_create_process");
 #endif
 }
 
@@ -1751,7 +1751,7 @@ CAMLprim value netsys_search_path(value path_opt_v,
     if (pathlen < 256) pathlen = 256;
     cont = 1;
     while (cont) {
-	fullname = stat_alloc(pathlen);
+	fullname = caml_stat_alloc(pathlen);
 	code = SearchPath(path,
 			  file,
 			  ext,
@@ -1760,7 +1760,7 @@ CAMLprim value netsys_search_path(value path_opt_v,
 			  NULL);
 	cont = (code >= pathlen);
 	if (cont) {
-	    stat_free(fullname);
+	    caml_stat_free(fullname);
 	    pathlen = code+1;  /* space for NULL byte! */
 	}
     }
@@ -1768,16 +1768,16 @@ CAMLprim value netsys_search_path(value path_opt_v,
     caml_leave_blocking_section();
 
     if (code == 0) {
-	stat_free(fullname);
+	caml_stat_free(fullname);
 	errno = ENOENT;
 	uerror("netsys_search_path", file_v);
     };
 
     r = caml_copy_string(fullname);
-    stat_free(fullname);
+    caml_stat_free(fullname);
     return r;
 #else
-    invalid_argument("netsys_search_path");
+    caml_invalid_argument("netsys_search_path");
 #endif
 }
 
@@ -1794,7 +1794,7 @@ CAMLprim value netsys_terminate_process(value pv) {
     }
     return Val_unit;
 #else
-    invalid_argument("netsys_terminate_process");
+    caml_invalid_argument("netsys_terminate_process");
 #endif
 }
 
@@ -1807,7 +1807,7 @@ CAMLprim value netsys_process_descr(value pv) {
     p0 = process_val(pv);
     return netsysw32_win_alloc_handle(p0->proc_proxy);
 #else
-    invalid_argument("netsys_process_descr");
+    caml_invalid_argument("netsys_process_descr");
 #endif
 }
 
@@ -1819,7 +1819,7 @@ CAMLprim value netsys_set_auto_close_process_proxy(value pv, value flag) {
     p0->auto_close = Bool_val(flag);
     return Val_unit;
 #else
-    invalid_argument("netsys_set_auto_close_process_proxy");
+    caml_invalid_argument("netsys_set_auto_close_process_proxy");
 #endif
 }
 
@@ -1834,7 +1834,7 @@ CAMLprim value netsys_close_process(value pv) {
     };
     return Val_unit;
 #else
-    invalid_argument("netsys_close_process");
+    caml_invalid_argument("netsys_close_process");
 #endif
 }
 
@@ -1846,10 +1846,10 @@ CAMLprim value netsys_process_free(value pv) {
 	CloseHandle(p0->proc);
     if (p0->auto_close)
 	CloseHandle(p0->proc_proxy);
-    stat_free(p0);
+    caml_stat_free(p0);
     return Val_unit;
 #else
-    invalid_argument("netsys_close_process");
+    caml_invalid_argument("netsys_close_process");
 #endif
 }
 
@@ -1870,7 +1870,7 @@ CAMLprim value netsys_get_process_status(value pv) {
 	uerror("netsys_get_process_status/WaitForSingleObject", Nothing);
     };
     if (code != WAIT_OBJECT_0) {
-	invalid_argument("netsys_get_process_status [1]");
+	caml_invalid_argument("netsys_get_process_status [1]");
     };
     /* Now get the status: */
     code = GetExitCodeProcess(p0->proc, &status);
@@ -1882,7 +1882,7 @@ CAMLprim value netsys_get_process_status(value pv) {
     return Val_int(status);
 
 #else
-    invalid_argument("netsys_get_process_status");
+    caml_invalid_argument("netsys_get_process_status");
 #endif
 }
 
@@ -1893,7 +1893,7 @@ CAMLprim value netsys_as_process_event(value pv) {
     p0 = process_val(pv);
     return alloc_event(p0->proc);
 #else
-    invalid_argument("netsys_as_process_event");
+    caml_invalid_argument("netsys_as_process_event");
 #endif
 }
 
@@ -1915,7 +1915,7 @@ CAMLprim value netsys_emulated_pid(value pv) {
     };
     return Val_int(d);
 #else
-    invalid_argument("netsys_emulated_pid");
+    caml_invalid_argument("netsys_emulated_pid");
 #endif
 }
 
@@ -1926,7 +1926,7 @@ CAMLprim value netsys_win_pid(value pv) {
     p0 = process_val(pv);
     return Val_int(p0->win_pid);
 #else
-    invalid_argument("netsys_win_pid");
+    caml_invalid_argument("netsys_win_pid");
 #endif
 }
 
@@ -1935,7 +1935,7 @@ CAMLprim value netsys_has_console(value dummy) {
 #ifdef _WIN32
     return Val_bool(has_console());
 #else
-    invalid_argument("netsys_has_console");
+    caml_invalid_argument("netsys_has_console");
 #endif
 }
 
@@ -1950,7 +1950,7 @@ CAMLprim value netsys_is_console(value fd) {
     else
 	return Val_bool(1);
 #else
-    invalid_argument("netsys_is_console");
+    caml_invalid_argument("netsys_is_console");
 #endif
 }
 
@@ -1962,7 +1962,7 @@ CAMLprim value netsys_alloc_console(value dummy) {
     }
     return Val_unit;
 #else
-    invalid_argument("netsys_alloc_console");
+    caml_invalid_argument("netsys_alloc_console");
 #endif
 }
 
@@ -2001,7 +2001,7 @@ CAMLprim value netsys_get_console_attr(value dummy) {
 
     return r;
 #else
-    invalid_argument("netsys_get_console_attr");
+    caml_invalid_argument("netsys_get_console_attr");
 #endif
 }
 
@@ -2060,7 +2060,7 @@ CAMLprim value netsys_set_console_attr(value av) {
   
     return Val_unit;
 #else
-    invalid_argument("netsys_set_console_attr");
+    caml_invalid_argument("netsys_set_console_attr");
 #endif
 }
 
@@ -2092,7 +2092,7 @@ CAMLprim value netsys_get_console_info(value dummy) {
 
     return r;
 #else
-    invalid_argument("netsys_get_console_info");
+    caml_invalid_argument("netsys_get_console_info");
 #endif
 }
 
@@ -2146,7 +2146,7 @@ CAMLprim value netsys_get_console_mode(value dummy) {
 
     return r;
 #else
-    invalid_argument("netsys_get_console_mode");
+    caml_invalid_argument("netsys_get_console_mode");
 #endif
 }
 
@@ -2215,7 +2215,7 @@ CAMLprim value netsys_set_console_mode(value mv) {
     CloseHandle(conout);
     return Val_unit;
 #else
-    invalid_argument("netsys_set_console_mode");
+    caml_invalid_argument("netsys_set_console_mode");
 #endif
 }
 
@@ -2224,7 +2224,7 @@ CAMLprim value netsys_getacp(value dummy) {
 #ifdef _WIN32
     return Val_int(GetACP());
 #else
-    invalid_argument("netsys_getacp");
+    caml_invalid_argument("netsys_getacp");
 #endif
 }
 
@@ -2243,7 +2243,7 @@ CAMLprim value netsys_init_console_codepage(value dummy) {
     }
     return Val_unit;
 #else
-    invalid_argument("netsys_init_console_codepage");
+    caml_invalid_argument("netsys_init_console_codepage");
 #endif
 }
 
@@ -2338,7 +2338,7 @@ CAMLprim value netsys_clear_console(value mode) {
 
     return Val_unit;
 #else
-    invalid_argument("netsys_clear_console");
+    caml_invalid_argument("netsys_clear_console");
 #endif
 }
 
@@ -2347,7 +2347,7 @@ CAMLprim value netsys_get_current_thread_id(value dummy) {
 #ifdef _WIN32
     return caml_copy_int32(GetCurrentThreadId());
 #else
-    invalid_argument("netsys_get_current_thread_id");
+    caml_invalid_argument("netsys_get_current_thread_id");
 #endif
 }
 
@@ -2394,7 +2394,7 @@ CAMLprim value netsys_cancel_synchronous_io(value thread_id_val) {
 
     return Val_unit;
 #else
-    invalid_argument("netsys_cancel_synchronous_io");
+    caml_invalid_argument("netsys_cancel_synchronous_io");
 #endif
 }
 
@@ -2439,7 +2439,7 @@ static value fdset_to_fdlist(value fdlist, fd_set *fdset)
     for (/*nothing*/; fdlist != Val_int(0); fdlist = Field(fdlist, 1)) {
       s = Field(fdlist, 0);
       if (FD_ISSET(Socket_val(s), fdset)) {
-        value newres = alloc_small(2, 0);
+        value newres = caml_alloc_small(2, 0);
         Field(newres, 0) = s;
         Field(newres, 1) = res;
         res = newres;
@@ -2471,9 +2471,9 @@ CAMLprim value netsys_real_select(value readfds, value writefds,
 	&& writefds == Val_int(0)
 	&& exceptfds == Val_int(0)) {
       if ( tm > 0.0 ) {
-	enter_blocking_section();
+	caml_enter_blocking_section();
 	Sleep( (int)(tm * 1000));
-	leave_blocking_section();
+	caml_leave_blocking_section();
       }
       read_list = write_list = except_list = Val_int(0);
     } else {      
@@ -2487,10 +2487,10 @@ CAMLprim value netsys_real_select(value readfds, value writefds,
 	tv.tv_usec = (int) (1e6 * (tm - (int) tm));
 	tvp = &tv;
       }
-      enter_blocking_section();
+      caml_enter_blocking_section();
       if (select(FD_SETSIZE, &read, &write, &except, tvp) == -1)
         err = WSAGetLastError();
-      leave_blocking_section();
+      caml_leave_blocking_section();
       if (err) {
 	win32_maperr(err);
 	uerror("select", Nothing);
@@ -2499,7 +2499,7 @@ CAMLprim value netsys_real_select(value readfds, value writefds,
       write_list = fdset_to_fdlist(writefds, &write);
       except_list = fdset_to_fdlist(exceptfds, &except);
     }
-    res = alloc_small(3, 0);
+    res = caml_alloc_small(3, 0);
     Field(res, 0) = read_list;
     Field(res, 1) = write_list;
     Field(res, 2) = except_list;
@@ -2507,6 +2507,6 @@ CAMLprim value netsys_real_select(value readfds, value writefds,
   End_roots();
   return res;
 #else
-    invalid_argument("netsys_real_select");
+    caml_invalid_argument("netsys_real_select");
 #endif
 }
diff --git a/src/netsys/netsys_impl_util.ml b/src/netsys/netsys_impl_util.ml
index 561d26a..6ae9fe5 100644
--- a/src/netsys/netsys_impl_util.ml
+++ b/src/netsys/netsys_impl_util.ml
@@ -67,7 +67,7 @@ let mem_sorted_array x a =
   let rec search l h =
     if l < h then (
       let m = (l+h) / 2 in
-      let r = Pervasives.compare x a.(m) in
+      let r = compare x a.(m) in
       if r = 0 then
 	true
       else
diff --git a/src/netsys/netsys_pollset_win32.ml b/src/netsys/netsys_pollset_win32.ml
index 09b1264..dc91c50 100644
--- a/src/netsys/netsys_pollset_win32.ml
+++ b/src/netsys/netsys_pollset_win32.ml
@@ -27,9 +27,9 @@ let list_of_socket_sets ht in_set out_set pri_set =
   let in_arr  = Array.of_list in_set in
   let out_arr = Array.of_list out_set in
   let pri_arr = Array.of_list pri_set in
-  Array.sort Pervasives.compare in_arr;
-  Array.sort Pervasives.compare out_arr;
-  Array.sort Pervasives.compare pri_arr;
+  Array.sort compare in_arr;
+  Array.sort compare out_arr;
+  Array.sort compare pri_arr;
   Hashtbl.fold
     (fun fd (ev,_) l ->
        let m_in = Netsys_impl_util.mem_sorted_array fd in_arr in
diff --git a/src/netsys/netsys_posix.ml b/src/netsys/netsys_posix.ml
index 3bf3e7c..2eb32f1 100644
--- a/src/netsys/netsys_posix.ml
+++ b/src/netsys/netsys_posix.ml
@@ -337,9 +337,9 @@ let do_poll a k tmo =
 	let a_inp = Array.of_list o_inp in
 	let a_out = Array.of_list o_out in
 	let a_pri = Array.of_list o_pri in
-	Array.sort Pervasives.compare a_inp;
-	Array.sort Pervasives.compare a_out;
-	Array.sort Pervasives.compare a_pri;
+        Array.sort compare a_inp;
+        Array.sort compare a_out;
+        Array.sort compare a_pri;
 	let n = ref 0 in
 	for j = 0 to k-1 do
 	  let c = e.(j) in
@@ -679,7 +679,7 @@ end
 
 module PFH = struct
   type t = post_fork_handler
-  let compare = Pervasives.compare
+  let compare = compare
 end
 
 module PFH_Set = Set.Make(PFH)
diff --git a/src/nettls-gnutls/META.in b/src/nettls-gnutls/META.in
index feafc4e..509e7d0 100644
--- a/src/nettls-gnutls/META.in
+++ b/src/nettls-gnutls/META.in
@@ -1,5 +1,5 @@
 description = "Ocamlnet - GnuTLS bindings"
-requires = "unix,bigarray,netsys,netstring"
+requires = "unix,netsys,netstring"
 version = "@VERSION@"
 archive(byte) = "nettls-gnutls.cma"
 archive(native) = "nettls-gnutls.cmxa"
diff --git a/src/nettls-gnutls/gnutls.c b/src/nettls-gnutls/gnutls.c
index d8a0f05..90f5f5d 100644
--- a/src/nettls-gnutls/gnutls.c
+++ b/src/nettls-gnutls/gnutls.c
@@ -111,26 +111,26 @@ static value wrap_str_datum_p(const gnutls_datum_t *d) {
 static gnutls_datum_t unwrap_str_datum(value v) {
     gnutls_datum_t d;
     d.size = caml_string_length(v);
-    d.data = stat_alloc(d.size);
+    d.data = caml_stat_alloc(d.size);
     memcpy(d.data, String_val(v), d.size);
     return d;
 }
    
 static gnutls_datum_t * unwrap_str_datum_p(value v) {
     gnutls_datum_t *d;
-    d = stat_alloc(sizeof(gnutls_datum_t));
+    d = caml_stat_alloc(sizeof(gnutls_datum_t));
     *d = unwrap_str_datum(v);
     return d;
 }
    
 static void free_str_datum(gnutls_datum_t d) {
-    if (d.data != NULL) { stat_free(d.data); d.data = NULL; };
+    if (d.data != NULL) { caml_stat_free(d.data); d.data = NULL; };
 }
 
 static void free_str_datum_p(gnutls_datum_t *d) {
     if (d != NULL) {
-        if (d->data != NULL) stat_free(d->data);
-        stat_free(d);
+        if (d->data != NULL) caml_stat_free(d->data);
+        caml_stat_free(d);
     }
 }
    
@@ -405,7 +405,7 @@ static void attach_session_callbacks (gnutls_session_t s) {
     b_session_callbacks_t cb;
 
     cb = (b_session_callbacks_t) 
-            stat_alloc(sizeof(struct b_session_callbacks_st));
+            caml_stat_alloc(sizeof(struct b_session_callbacks_st));
     cb->session = s;
     cb->pull_fun = Val_int(0);
     cb->pull_timeout_fun = Val_int(0);
@@ -458,7 +458,7 @@ static void b_free_session(gnutls_session_t s) {
     caml_remove_generational_global_root(&(cb->db_store_fun));
     caml_remove_generational_global_root(&(cb->db_remove_fun));
 
-    stat_free(cb);
+    caml_stat_free(cb);
     gnutls_deinit(s);
 }
 
@@ -484,7 +484,7 @@ CAMLprim value net_b_set_pull_timeout_callback(value sv, value fun) {
     caml_modify_generational_global_root(&(cb->pull_timeout_fun), fun);
     return Val_unit;
 #else
-    invalid_argument("b_set_pull_timeout_callback");
+    caml_invalid_argument("b_set_pull_timeout_callback");
 #endif
 }
 
@@ -510,7 +510,7 @@ CAMLprim value net_b_set_verify_callback(value sv, value fun) {
     caml_modify_generational_global_root(&(cb->verify_fun), fun);
     return Val_unit;
 #else
-    invalid_argument("b_set_verify_callback");
+    caml_invalid_argument("b_set_verify_callback");
 #endif
 }
 
@@ -602,7 +602,7 @@ CAMLprim value net_gnutls_credentials_set(value sess, value creds) {
                                    );
         break;
     default:
-        failwith("net_gnutls_credentials_set");
+        caml_failwith("net_gnutls_credentials_set");
     };
     net_gnutls_error_check(error_code);
     attach_gnutls_session_t(sess, creds);
@@ -633,7 +633,7 @@ CAMLprim value net_gnutls_x509_crt_list_import(value datav, value formatv,
     code = gnutls_x509_crt_list_import(certs, &n, &data, format, 
                     flags | GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
     if (code == GNUTLS_E_SHORT_MEMORY_BUFFER) {
-        certs = (gnutls_x509_crt_t *) stat_alloc(n * sizeof(void *));
+        certs = (gnutls_x509_crt_t *) caml_stat_alloc(n * sizeof(void *));
         alloc_certs = 1;
         code = gnutls_x509_crt_list_import(certs, &n, &data, format, 
                                            flags);
@@ -646,7 +646,7 @@ CAMLprim value net_gnutls_x509_crt_list_import(value datav, value formatv,
         };
     };
     if (alloc_certs)
-        stat_free(certs);
+        caml_stat_free(certs);
     net_gnutls_error_check(code);
     CAMLreturn(array);
 }
@@ -676,7 +676,7 @@ CAMLprim value net_gnutls_x509_crl_list_import(value datav, value formatv,
     code = gnutls_x509_crl_list_import(certs, &n, &data, format, 
                     flags | GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
     if (code == GNUTLS_E_SHORT_MEMORY_BUFFER) {
-        certs = (gnutls_x509_crl_t *) stat_alloc(n * sizeof(void *));
+        certs = (gnutls_x509_crl_t *) caml_stat_alloc(n * sizeof(void *));
         alloc_certs = 1;
         code = gnutls_x509_crl_list_import(certs, &n, &data, format, 
                                            flags);
@@ -689,11 +689,11 @@ CAMLprim value net_gnutls_x509_crl_list_import(value datav, value formatv,
         };
     };
     if (alloc_certs)
-        stat_free(certs);
+        caml_stat_free(certs);
     net_gnutls_error_check(code);
     CAMLreturn(array);
 #else
-    invalid_argument("gnutls_x509_crl_list_import");
+    caml_invalid_argument("gnutls_x509_crl_list_import");
 #endif
 }
 
diff --git a/src/nettls-gnutls/gnutls.descr b/src/nettls-gnutls/gnutls.descr
index 68cd1ea..a395209 100644
--- a/src/nettls-gnutls/gnutls.descr
+++ b/src/nettls-gnutls/gnutls.descr
@@ -560,7 +560,7 @@ let functions =
       ~options: [
         `Pre("if (data_size__c < 0 || \
                   data_size__c > caml_ba_byte_size(Caml_ba_array_val(data))) \
-                      invalid_argument(\"gnutls_record_send\");"
+                      caml_invalid_argument(\"gnutls_record_send\");"
             )
       ]
       "error_code/uint gnutls_record_send \
diff --git a/src/nettls-gnutls/nettle.c b/src/nettls-gnutls/nettle.c
index 77d00ff..95ecae2 100644
--- a/src/nettls-gnutls/nettle.c
+++ b/src/nettls-gnutls/nettle.c
@@ -39,12 +39,12 @@ static void net_nettle_null_pointer(void) {
 static net_nettle_cipher_ctx_t
          net_nettle_create_cipher_ctx(net_nettle_cipher_t cipher) {
     void *p;
-    p = stat_alloc(cipher->context_size);
+    p = caml_stat_alloc(cipher->context_size);
     return p;
 }
 
 static void net_nettle_free(void *ctx) {
-    stat_free(ctx);
+    caml_stat_free(ctx);
 }
 
 static void net_nettle_destroy_cipher(net_nettle_cipher_t cipher) {
@@ -57,7 +57,7 @@ static void net_nettle_set_encrypt_key(net_nettle_cipher_t cipher,
                                        const uint8_t *key) {
 #ifdef HAVE_NETTLE_SET_KEY_WITH_TWO_ARGS
     if (length != cipher->key_size)
-        failwith("net_nettl_set_encrypt_key: key has wrong size");
+        caml_failwith("net_nettl_set_encrypt_key: key has wrong size");
     cipher->set_encrypt_key(ctx, key);
 #else
     cipher->set_encrypt_key(ctx, length, key);
@@ -71,7 +71,7 @@ static void net_nettle_set_decrypt_key(net_nettle_cipher_t cipher,
                                        const uint8_t *key) {
 #ifdef HAVE_NETTLE_SET_KEY_WITH_TWO_ARGS
     if (length != cipher->key_size)
-        failwith("net_nettl_set_decrypt_key: key has wrong size");
+        caml_failwith("net_nettl_set_decrypt_key: key has wrong size");
     cipher->set_decrypt_key(ctx, key);
 #else
     cipher->set_decrypt_key(ctx, length, key);
@@ -292,7 +292,7 @@ static void net_ext_ciphers(net_nettle_cipher_t **ciphers,
 
 static net_nettle_gcm_aes_ctx_t net_nettle_gcm_aes_init(void) {
 #ifdef HAVE_NETTLE_GCM_H
-    return stat_alloc(sizeof(struct gcm_aes_ctx));
+    return caml_stat_alloc(sizeof(struct gcm_aes_ctx));
 #else
     return NULL;
 #endif
@@ -321,7 +321,7 @@ static const char *net_nettle_hash_name(net_nettle_hash_t hash) {
 static net_nettle_hash_ctx_t
          net_nettle_create_hash_ctx(net_nettle_hash_t hash) {
     void *p;
-    p = stat_alloc(hash->context_size);
+    p = caml_stat_alloc(hash->context_size);
     return p;
 }
 
diff --git a/src/nettls-gnutls/nettls_gnutls.ml b/src/nettls-gnutls/nettls_gnutls.ml
index e916181..38ee5c9 100644
--- a/src/nettls-gnutls/nettls_gnutls.ml
+++ b/src/nettls-gnutls/nettls_gnutls.ml
@@ -4,7 +4,7 @@ open Printf
 
 module StrMap = Map.Make(String)
 module StrSet = Set.Make(String)
-module OID = struct type t = Netoid.t let compare = Pervasives.compare end
+module OID = struct type t = Netoid.t let compare = compare end
 module OIDMap = Map.Make(OID)
 
 module type GNUTLS_PROVIDER =
diff --git a/src/nettls-gnutls/reconfigure b/src/nettls-gnutls/reconfigure
index c701e7b..5b3f363 100755
--- a/src/nettls-gnutls/reconfigure
+++ b/src/nettls-gnutls/reconfigure
@@ -216,10 +216,10 @@ echo "Generating stubs"
 
 rm -f config_checks.sh
 echo "$ ocaml -I ../../tools gnutls.descr" >>$log
-ocaml -I ../../tools gnutls.descr || exit 1
+ocaml -I +str -I ../../tools gnutls.descr || exit 1
 
 echo "$ ocaml -I ../../tools nettle.descr" >>$log
-ocaml -I ../../tools nettle.descr || exit 1
+ocaml -I +str -I ../../tools nettle.descr || exit 1
 
 init_checks
 . ./config_checks.sh
diff --git a/src/rpc-auth-local/rpclocal.c b/src/rpc-auth-local/rpclocal.c
index 905eef9..0f0472d 100644
--- a/src/rpc-auth-local/rpclocal.c
+++ b/src/rpc-auth-local/rpclocal.c
@@ -12,6 +12,7 @@
 #include "caml/alloc.h"
 #include "caml/memory.h"
 #include "caml/fail.h"
+#include "caml/unixsupport.h"
 
 #ifndef _WIN32
 #include <unistd.h>
@@ -29,15 +30,6 @@
 #endif
 
 
-/**********************************************************************/
-/* From unixsupport.h                                                 */
-/**********************************************************************/
-
-#define Nothing ((value) 0)
-
-extern void unix_error (int errcode, char * cmdname, value arg) Noreturn;
-extern void uerror (char * cmdname, value arg) Noreturn;
-
 /**********************************************************************/
 
 /* Inspired by PostgreSQL's fe-connect.c */
@@ -58,7 +50,7 @@ value netsys_get_peer_credentials(value fd) {
     /* BSD, AIX, Cygwin */
     /* http://cr.yp.to/docs/secureipc.html */
     if (getpeereid(Int_val(fd), &uid, &gid) != 0) {
-	uerror("getpeereid", Nothing);
+	caml_uerror("getpeereid", Nothing);
     }
 
 #elif defined(SO_PEERCRED)
@@ -73,7 +65,7 @@ value netsys_get_peer_credentials(value fd) {
 		       SO_PEERCRED,
 		       &credentials,
 		       &len) == -1) {
-	    uerror("getsockopt",Nothing);
+	    caml_uerror("getsockopt",Nothing);
 	};
 	uid = credentials.uid;       /* Effective user ID */
 	gid = credentials.gid;       /* Effective group ID */
@@ -84,24 +76,24 @@ value netsys_get_peer_credentials(value fd) {
 	ucred_t    *ucred;
 	ucred = NULL;			/* must be initialized to NULL */
 	if (getpeerucred(Int_val(fd), &ucred) == -1) {
-	    uerror("getpeerucred",Nothing);
+	    caml_uerror("getpeerucred",Nothing);
 	};
 	if ((uid = ucred_geteuid(ucred)) == -1) {
-	    uerror("ucred_geteuid",Nothing);
+	    caml_uerror("ucred_geteuid",Nothing);
 	    ucred_free(ucred);
 	};
 	if ((gid = ucred_getegid(ucred)) == -1) {
-	    uerror("ucred_getegid",Nothing);
+	    caml_uerror("ucred_getegid",Nothing);
 	    ucred_free(ucred);
 	};
 	ucred_free(ucred);
     }
 #else
-    invalid_argument("get_peer_credentials");
+    caml_invalid_argument("get_peer_credentials");
 #endif
 
     /* Allocate a pair, and put the result into it: */
-    result = alloc_tuple(2);
+    result = caml_alloc_tuple(2);
     Store_field(result, 0, Val_int(uid));
     Store_field(result, 1, Val_int(gid));
 
@@ -140,7 +132,7 @@ value netsys_peek_peer_credentials(value fd) {
 		       SO_PASSCRED,
 		       &one,
 		       sizeof(one)) < 0) {
-	    uerror("setsockopt", Nothing);
+	    caml_uerror("setsockopt", Nothing);
 	};
 
 	memset(&msg, 0, sizeof msg);
@@ -160,7 +152,7 @@ value netsys_peek_peer_credentials(value fd) {
 	 */
 
 	if (recvmsg(Int_val(fd), &msg, MSG_PEEK) < 0) {
-	    uerror("recvmsg", Nothing);
+	    caml_uerror("recvmsg", Nothing);
 	};
 
 	if (msg.msg_controllen == 0 ||
@@ -201,12 +193,12 @@ value netsys_peek_peer_credentials(value fd) {
 		       LOCAL_CREDS,
 		       &one,
 		       sizeof(one)) < 0) {
-	    uerror("setsockopt", Nothing);
+	    caml_uerror("setsockopt", Nothing);
 	};
 
 	memset(&msg, 0, sizeof msg);
 	crmsgsize = CMSG_SPACE(SOCKCREDSIZE(NGROUPS_MAX));
-	crmsg = stat_alloc(crmsgsize);
+	crmsg = caml_stat_alloc(crmsgsize);
 
 	memset(crmsg, 0, crmsgsize);
 	msg.msg_control = crmsg;
@@ -218,19 +210,19 @@ value netsys_peek_peer_credentials(value fd) {
 	iov.iov_len = 1;
 
 	if (recvmsg(Int_val(fd), &msg, MSG_PEEK) < 0) {
-	    stat_free(crmsg);
-	    uerror("recvmsg", Nothing);
+	    caml_stat_free(crmsg);
+	    caml_uerror("recvmsg", Nothing);
 	};
 
 	if (msg.msg_controllen == 0 ||
 	    (msg.msg_flags & MSG_CTRUNC) != 0) {
-	    stat_free(crmsg);
+	    caml_stat_free(crmsg);
 	    raise_not_found();
 	};
 	cmp = CMSG_FIRSTHDR(&msg);
 	if (cmp->cmsg_level != SOL_SOCKET ||
 	    cmp->cmsg_type != SCM_CREDS) {
-	    stat_free(crmsg);
+	    caml_stat_free(crmsg);
 	    raise_not_found();
 	};
 
@@ -241,12 +233,12 @@ value netsys_peek_peer_credentials(value fd) {
 	free(crmsg);
     }
 #else
-    invalid_argument("peek_peer_credentials");
+    caml_invalid_argument("peek_peer_credentials");
 #endif
 #endif
 
     /* Allocate a pair, and put the result into it: */
-    result = alloc_tuple(2);
+    result = caml_alloc_tuple(2);
     Store_field(result, 0, Val_int(uid));
     Store_field(result, 1, Val_int(gid));
 
diff --git a/src/rpc/rpc_client.ml b/src/rpc/rpc_client.ml
index 95ec643..5805b48 100644
--- a/src/rpc/rpc_client.ml
+++ b/src/rpc/rpc_client.ml
@@ -49,7 +49,7 @@ let () =
 
 module SessionUint4 = struct
   type t = uint4
-  let compare = (Pervasives.compare : uint4 -> uint4 -> int)
+  let compare = (compare : uint4 -> uint4 -> int)
 end
 
 module SessionMap =
diff --git a/src/rpc/rpc_proxy.ml b/src/rpc/rpc_proxy.ml
index 76452a1..1de72fe 100644
--- a/src/rpc/rpc_proxy.ml
+++ b/src/rpc/rpc_proxy.ml
@@ -414,7 +414,7 @@ module ManagedClient = struct
       | `Up up -> up.serial
 
   let compare mc1 mc2 =
-    Pervasives.compare mc1.id mc2.id
+    compare mc1.id mc2.id
 
   let pending_calls mc =
     mc.pending_calls
@@ -1037,7 +1037,7 @@ module ManagedSet = struct
 	  (* Sort the services by total load first: *)
 	  Array.sort 
 	    (fun j1 j2 ->
-	       Pervasives.compare 
+               compare
 		 mset.total_load.(j1)
 		 mset.total_load.(j2)
 	    )
diff --git a/src/shell/shell.ml b/src/shell/shell.ml
index 8cd17dd..ae61a3e 100644
--- a/src/shell/shell.ml
+++ b/src/shell/shell.ml
@@ -111,8 +111,8 @@ type producer =
 let from_string ?pos ?len ?epipe s =
   P_fun (Shell_sys.from_string ?pos:pos ?len:len ?epipe:epipe s);;
 
-let from_stream ?epipe s =
-  P_fun (Shell_sys.from_stream ?epipe:epipe s);;
+let from_seq ?epipe s =
+  P_fun (Shell_sys.from_seq ?epipe:epipe s);;
 
 let from_function ~producer () =
   P_fun producer;;
diff --git a/src/shell/shell.mli b/src/shell/shell.mli
index d541078..7afa508 100644
--- a/src/shell/shell.mli
+++ b/src/shell/shell.mli
@@ -237,11 +237,11 @@ val from_string :
    *    always caught, and implicitly handled by closing the pipeline.
    *)
 
-val from_stream :
+val from_seq :
       ?epipe:(unit -> unit) ->     (* default: empty function *)
-      string Stream.t ->
+      string Seq.t ->
         producer
-  (** Creates a producer taking the data from a stream of strings.
+  (** Creates a producer taking the data from a sequence of strings.
    * After the data are sent, the pipeline is closed.
    *
    * @param epipe This function is called when the pipeline breaks
diff --git a/src/shell/shell_sys.ml b/src/shell/shell_sys.ml
index 8cd0ae1..6111ff3 100644
--- a/src/shell/shell_sys.ml
+++ b/src/shell/shell_sys.ml
@@ -82,7 +82,7 @@ let set_env_var e v x =
   try
     let k = ref 0 in
     iter_env_vars
-      (fun v' x' ->
+      ~f:(fun v' x' ->
 	 if v' = v then begin
 	   !e.(!k) <- v ^ "=" ^ x;
 	   raise Exit
@@ -100,7 +100,7 @@ let get_env_var e v =
   let x = ref "" in
   try
     iter_env_vars
-      (fun v' x' ->
+      ~f:(fun v' x' ->
 	 if v' = v then begin
 	   x := x';
 	   raise Exit
@@ -335,7 +335,7 @@ type process =
 ;;
 
 let dummy_process =
-  { p_command = command "XXX" ();
+  { p_command = command ~filename:"XXX" ();
     p_id = `Dummy;
     p_gid = 0;
     p_status = Some (Unix.WEXITED 0);
@@ -1103,7 +1103,7 @@ let from_string ?pos ?len ?epipe s =
   from_tstring ?pos ?len ?epipe (`String s)
 
 
-let from_stream
+let from_seq
       ?(epipe = fun () -> ())
       s =
   let current_el  = ref None in
@@ -1112,6 +1112,8 @@ let from_stream
   let fd_style = ref `Read_write in
   let fd_style_set = ref false in
 
+  let stream = ref s in
+
   function fd ->
     if not !fd_style_set then (
       fd_style := Netsys.get_fd_style fd;
@@ -1120,14 +1122,15 @@ let from_stream
     (* If necessary, try to get the next stream element: *)
     begin match !current_el with
 	None ->
-	  begin try
-	    let x = Stream.next s in
-	    current_el := Some x;
-	    current_pos := 0;
-	  with
-	      Stream.Failure ->
-		()
-	  end
+        begin
+          match !stream() with
+            | Seq.Nil ->
+                ()
+            | Cons(x, tail) ->
+                stream := tail;
+                current_el := Some x;
+                current_pos := 0;
+          end
       | _ ->
 	  ()
     end;
diff --git a/src/shell/shell_sys.mli b/src/shell/shell_sys.mli
index 89e9850..56521c9 100644
--- a/src/shell/shell_sys.mli
+++ b/src/shell/shell_sys.mli
@@ -417,13 +417,13 @@ val from_tstring :
         (Unix.file_descr -> bool)
   (** Same for tagged strings *)
 
-val from_stream :
+val from_seq :
       ?epipe:(unit -> unit) ->     (* default: empty function *)
-      string Stream.t ->
+      string Seq.t ->
         (Unix.file_descr -> bool)
-  (** [from_stream ?epipe s] returns a function which can be
+  (** [from_seq ?epipe s] returns a function which can be
    * used as [producer] argument for [add_producer]. The data transferred
-   * to the subprocess is taken from the string stream [s]. After these data
+   * to the subprocess is taken from the string sequence [s]. After these data
    * are sent, the pipeline is closed.
    *
    * @param epipe This function is called when the pipeline breaks
@@ -431,7 +431,7 @@ val from_stream :
    *    always caught, and implicitly handled by closing the pipeline.
    *)
 
-val add_consumer : 
+val add_consumer :
       ?descr:Unix.file_descr ->     (* default: stdout *)
       consumer:(Unix.file_descr -> bool) ->
       command ->
diff --git a/tools/stubgen.ml b/tools/stubgen.ml
index 3cd35c4..336752c 100644
--- a/tools/stubgen.ml
+++ b/tools/stubgen.ml
@@ -447,7 +447,7 @@ let gen_abstract_ptr c mli ml tyname abs ~optional =
   fprintf c "  CAMLparam0();\n";
   fprintf c "  CAMLlocal2(v,r);\n";
   if not abs.abs_nullok then
-    fprintf c "  if (x == NULL) failwith(\"wrap_%s: NULL pointer\");\n" tyname;
+    fprintf c "  if (x == NULL) caml_failwith(\"wrap_%s: NULL pointer\");\n" tyname;
   fprintf c "  v = caml_alloc_custom(&abs_%s_ops, \
                                      sizeof(struct absstruct_%s), 0, 1);\n"
          tyname tyname;
@@ -503,10 +503,10 @@ let ml_name_of_enum n0 =
   try
     let l = String.length n in
     let p = String.index n '|' in
-    String.capitalize (String.lowercase (String.sub n (p+1) (l-p-1)))
+    String.capitalize_ascii (String.lowercase_ascii (String.sub n (p+1) (l-p-1)))
   with
     | Not_found ->
-         String.capitalize (String.lowercase n)
+        String.capitalize_ascii (String.lowercase_ascii n)
 
 
 let is_opt_case n =
@@ -550,7 +550,7 @@ let gen_enum c mli ml tyname cases ~optional =
     cases;
   fprintf c "    default: break;\n";
   fprintf c "  };\n";
-  fprintf c "  failwith(\"wrap_%s: unexpected value\");\n" tyname;
+  fprintf c "  caml_failwith(\"wrap_%s: unexpected value\");\n" tyname;
   fprintf c "}\n\n";
 
   fprintf c "static %s unwrap_%s(value v) {\n" tyname tyname;
@@ -568,9 +568,9 @@ let gen_enum c mli ml tyname cases ~optional =
          fprintf c "#endif\n"
     )
     cases;
-  fprintf c "    default: invalid_argument(\"unwrap_%s\");\n" tyname;
+  fprintf c "    default: caml_invalid_argument(\"unwrap_%s\");\n" tyname;
   fprintf c "  };\n";
-  fprintf c "  failwith(\"unwrap_%s: unexpected value\");\n" tyname;
+  fprintf c "  caml_failwith(\"unwrap_%s: unexpected value\");\n" tyname;
   fprintf c "}\n";
 
   if optional then
@@ -983,7 +983,7 @@ let gen_fun c mli ml name args directives free init =
                   let i1 = new_local() in
                   c_decls := sprintf "long %s;" i1 :: !c_decls;
                   let code1 =
-                    [ sprintf "%s = (%s) stat_alloc(Wosize_val(%s)*sizeof(%s));" 
+                    [ sprintf "%s = (%s) caml_stat_alloc(Wosize_val(%s)*sizeof(%s));"
                               n1 c_ty n el_c_ty;
                       sprintf "for (%s=0; %s < Wosize_val(%s); %s++) {"
                               i1 i1 n i1;
@@ -1000,7 +1000,7 @@ let gen_fun c mli ml name args directives free init =
                          sprintf "};"
                        ]
                      else []) @
-                      [ sprintf "stat_free(%s);" n1 ] in
+                      [ sprintf "caml_stat_free(%s);" n1 ] in
                   c_code_post_prio := List.rev code2 @ !c_code_post_prio;
              | `Array_size(n_array, ty) ->
                   let code =
@@ -1358,14 +1358,14 @@ let gen_fun c mli ml name args directives free init =
       fprintf c "    long n__stub;\n";
       fprintf c "    %s__c++;\n" n_strbuf_size;
       fprintf c "    n__stub = %s__c;\n" n_strbuf_size;
-      fprintf c "    %s__c = stat_alloc(%s__c+1);\n" n_strbuf n_strbuf_size;
+      fprintf c "    %s__c = caml_stat_alloc(%s__c+1);\n" n_strbuf n_strbuf_size;
       fprintf c "    ";
       emit_call();
       fprintf c "    if (%s == 0) {\n" ret_var;
       fprintf c "      ((char *) %s__c)[n__stub] = 0;\n" n_strbuf;
       fprintf c "      %s = caml_copy_string(%s__c);\n" n_strbuf n_strbuf;
       fprintf c "    };\n";
-      fprintf c "    stat_free(%s__c);\n" n_strbuf;
+      fprintf c "    caml_stat_free(%s__c);\n" n_strbuf;
       fprintf c "  };\n";      
     )
     else (
@@ -1414,7 +1414,7 @@ let gen_fun c mli ml name args directives free init =
 
   if optional then (
     fprintf c "#else\n";
-    fprintf c "  invalid_argument(\"%s\");\n" name;
+    fprintf c "  caml_invalid_argument(\"%s\");\n" name;
     fprintf c "#endif\n";
   );
 
@@ -1483,7 +1483,7 @@ let gen_c_head c =
 
 let gen_c_head2 c =
   fprintf c "static unsigned int uint_val(value v) {\n\
-             \032   if (Int_val(v) < 0) invalid_argument(\"negative integer\");\n\
+             \032   if (Int_val(v) < 0) caml_invalid_argument(\"negative integer\");\n\
              \032   return (unsigned int) Int_val(v);\n\
              }\n\
              \n\
-- 
2.45.2

