ocaml-usb-1.3.0/0000755000000000000000000000000012005550027011557 5ustar0000000000000000ocaml-usb-1.3.0/ocaml-usb-api.odocl0000644000000000000000000000013412005550027015230 0ustar0000000000000000# OASIS_START # DO NOT EDIT (digest: 844381baf44d5bef352ba9377ceb5b75) src/USB # OASIS_STOP ocaml-usb-1.3.0/configure0000755000000000000000000000055412005550027013472 0ustar0000000000000000#!/bin/sh # OASIS_START # DO NOT EDIT (digest: 425187ed8bfdbdd207fd76392dd243a7) set -e FST=true for i in "$@"; do if $FST; then set -- FST=false fi case $i in --*=*) ARG=${i%%=*} VAL=${i##*=} set -- "$@" "$ARG" "$VAL" ;; *) set -- "$@" "$i" ;; esac done ocaml setup.ml -configure "$@" # OASIS_STOP ocaml-usb-1.3.0/Makefile0000644000000000000000000000127612005550027013225 0ustar0000000000000000# OASIS_START # DO NOT EDIT (digest: bc1e05bfc8b39b664f29dae8dbd3ebbb) SETUP = ocaml setup.ml build: setup.data $(SETUP) -build $(BUILDFLAGS) doc: setup.data build $(SETUP) -doc $(DOCFLAGS) test: setup.data build $(SETUP) -test $(TESTFLAGS) all: $(SETUP) -all $(ALLFLAGS) install: setup.data $(SETUP) -install $(INSTALLFLAGS) uninstall: setup.data $(SETUP) -uninstall $(UNINSTALLFLAGS) reinstall: setup.data $(SETUP) -reinstall $(REINSTALLFLAGS) clean: $(SETUP) -clean $(CLEANFLAGS) distclean: $(SETUP) -distclean $(DISTCLEANFLAGS) setup.data: $(SETUP) -configure $(CONFIGUREFLAGS) .PHONY: build doc test all install uninstall reinstall clean distclean configure # OASIS_STOP ocaml-usb-1.3.0/CHANGES.darcs0000644000000000000000000001720512005550027013652 0ustar0000000000000000Mon Jul 30 20:18:55 CEST 2012 Jeremie Dimino tagged 1.3.0 Mon Jul 30 20:18:50 CEST 2012 Jeremie Dimino * bump version number Mon Jul 30 20:18:43 CEST 2012 Jeremie Dimino * update CHANGES Mon Jul 30 20:17:07 CEST 2012 Jeremie Dimino * upgrade _oasis format Wed Apr 25 08:11:25 CEST 2012 Jeremie Dimino * update setup.ml for oasis 0.3.0 Thu Feb 16 12:11:21 CET 2012 Jeremie Dimino * add more device class codes Thu Jul 28 21:37:35 CEST 2011 Jeremie Dimino * add a minimal setup.ml file Sat Jul 2 18:07:57 CEST 2011 Stephane Glondu * Include stdint.h before libusb.h Fixes FTBFS on kfreebsd-*. Sat Jun 18 19:17:24 CEST 2011 Jeremie Dimino * remove oasis files Thu May 19 21:38:25 CEST 2011 Jeremie Dimino * fix initialization Wed May 18 19:21:29 CEST 2011 Jeremie Dimino tagged 1.2.0 Wed May 18 19:21:23 CEST 2011 Jeremie Dimino * version 1.2.0 Wed May 18 19:20:51 CEST 2011 Jeremie Dimino * update CHANGES Wed May 18 19:20:07 CEST 2011 Jeremie Dimino * add a boring file Thu May 19 18:32:09 CEST 2011 Jeremie Dimino * add pollfds created by libusb before the pollfds add/remove handlers are registered Thanks to Nicolas Dandrimont for the patch Wed May 18 19:18:21 CEST 2011 Jeremie Dimino * add the odocl file Wed Mar 9 23:11:47 CET 2011 Jeremie Dimino * typo Tue Feb 8 20:27:41 CET 2011 Jeremie Dimino * update for the new lwt engine system Wed Dec 29 17:36:43 CET 2010 Jeremie Dimino * execute predist.sh when creating the dist archive Wed Dec 15 21:27:07 CET 2010 Jeremie Dimino tagged 1.1.0 Wed Dec 15 21:26:57 CET 2010 Jeremie Dimino * version 1.1.0 Wed Dec 15 21:19:20 CET 2010 Jeremie Dimino * fix jobs Wed Dec 15 21:14:40 CET 2010 Jeremie Dimino * use lwt_unix_main_loop instead of NULL Wed Dec 15 21:07:57 CET 2010 Jeremie Dimino * fix ml_usb_add_watcher Wed Dec 15 20:52:40 CET 2010 Jeremie Dimino * fix dependencies Tue Dec 14 19:23:40 CET 2010 Jeremie Dimino * use lwt unix jobs Tue Dec 14 13:09:08 CET 2010 Jeremie Dimino * switch to oasis for the build system Tue Oct 26 17:55:29 CEST 2010 Jeremie Dimino * update main loop integration (use libev) Sat Sep 4 14:59:25 CEST 2010 Jeremie Dimino * repace fail by raise_lwt Fri May 28 16:57:15 CEST 2010 Jeremie Dimino * uses task instead of wait in transfers Thu Apr 29 07:43:23 CEST 2010 Stephane Glondu * Move the cmxs rule to Before_rules Move the cmxs rule to Before_rules, so that it overrides the built-in rules (which are present in OCaml 3.12). Sat Apr 17 18:59:38 CEST 2010 Jeremie Dimino tagged 1.0 Sat Apr 17 18:59:10 CEST 2010 Jeremie Dimino * version 1.0 Thu Feb 25 01:23:43 CET 2010 Jeremie Dimino * register printer for exceptions Tue Feb 16 20:11:33 CET 2010 Jeremie Dimino * ensures that device handles are closed only once Thu Jan 14 01:08:22 CET 2010 Jeremie Dimino * fix stubs Sat Nov 7 17:25:01 CET 2009 Jeremie Dimino * install usb.cmxs Sat Nov 7 17:14:55 CET 2009 Jeremie Dimino * typo Sat Nov 7 17:01:49 CET 2009 Jeremie Dimino * fix documentation generation Thu Nov 5 11:58:45 CET 2009 Jeremie Dimino tagged 1.0rc1 Thu Nov 5 11:37:04 CET 2009 Jeremie Dimino * compile stubs with -Wall Thu Nov 5 11:20:37 CET 2009 Jeremie Dimino * adding myocamlbuild and Makefile for examples Thu Nov 5 11:19:15 CET 2009 Jeremie Dimino * Prepare release 1.0rc1 Thu Nov 5 10:17:32 CET 2009 Jeremie Dimino * fixes USB.get_device_list The comparison "cnt < 0" did not returned the right result because (size_t) values are unsigned Thu Nov 5 09:47:40 CET 2009 Jeremie Dimino * typo in comments Sat Oct 24 19:11:50 CEST 2009 Jeremie Dimino * add support for isochronous transfers Fri Oct 23 22:55:48 CEST 2009 Jeremie Dimino * add README Fri Oct 23 21:05:33 CEST 2009 Jeremie Dimino * change error types Fri Oct 23 13:39:12 CEST 2009 Jeremie Dimino * changes in the build system Fri Oct 23 13:21:25 CEST 2009 Jeremie Dimino * uses default values for recipient and request_type Thu Oct 22 20:16:38 CEST 2009 Jeremie Dimino * add USB.get_string_descriptor Thu Oct 22 17:22:07 CEST 2009 Jeremie Dimino * add USB.get_*config_descriptor* Wed Oct 21 21:33:23 CEST 2009 Jeremie Dimino * add USB.get_device_descriptor Wed Oct 21 20:30:49 CEST 2009 Jeremie Dimino * add USB.set_interface_alt_setting Wed Oct 21 20:24:26 CEST 2009 Jeremie Dimino * add USB.clear_halt Wed Oct 21 20:20:06 CEST 2009 Jeremie Dimino * add the possibility to cancel transfers Wed Oct 21 17:48:52 CEST 2009 Jeremie Dimino * fixes in LICENSE Mon Oct 12 14:15:01 CEST 2009 Jeremie Dimino * add a state to device handle Wed Jun 24 12:56:21 CEST 2009 Jeremie Dimino * use the new Lwt.wait Fri Jun 5 20:03:01 CEST 2009 Jeremie Dimino * fix in control transfers Thu Jun 4 00:20:07 CEST 2009 Jeremie Dimino * update for lwt changes Tue Jun 2 23:12:04 CEST 2009 Jeremie Dimino * fix in get_max_packet_size Tue May 19 15:39:31 CEST 2009 Jeremie Dimino * use Lwt_preemptive for blocking calls Mon May 18 23:58:54 CEST 2009 Jeremie Dimino * fix error handling Mon May 18 13:57:24 CEST 2009 Jeremie Dimino * remove Lwt_pervasives Mon May 18 01:38:40 CEST 2009 Jeremie Dimino * bugfixes in C stubs Tue May 12 00:48:47 CEST 2009 Jeremie Dimino * implementation of reset_device Tue May 12 00:40:08 CEST 2009 Jeremie Dimino * do not use Lwt.preemptive for now Tue May 12 00:05:20 CEST 2009 Jeremie Dimino * implementation of control transfers Mon May 11 22:23:17 CEST 2009 Jeremie Dimino * add USB.with_device Wed May 6 22:32:26 CEST 2009 Jeremie Dimino * bugfixes Wed May 6 04:06:36 CEST 2009 Jeremie Dimino * typo Thu Apr 30 02:10:35 CEST 2009 Jeremie Dimino * more functions Wed Apr 29 13:32:15 CEST 2009 Jeremie Dimino * beginning of IOs Sat Apr 25 20:07:36 CEST 2009 Jeremie Dimino * gcc must be mad Thu Apr 23 19:19:52 CEST 2009 Jeremie Dimino * more fixes for C stubs Thu Apr 23 18:36:37 CEST 2009 Jeremie Dimino * cleaner compilation of stubs Thu Apr 23 02:30:56 CEST 2009 Jeremie Dimino * initial import ocaml-usb-1.3.0/setup.ml0000644000000000000000000045633612005550027013272 0ustar0000000000000000(* * setup.ml * -------- * Copyright : (c) 2011, Jeremie Dimino * Licence : BSD3 * * This file is a part of ocaml-usb. *) (* OASIS_START *) (* DO NOT EDIT (digest: 9c09b54e5d735cc1651b4a0c986909b1) *) (* Regenerated by OASIS v0.3.0 Visit http://oasis.forge.ocamlcore.org for more information and documentation about functions used in this file. *) module OASISGettext = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISGettext.ml" let ns_ str = str let s_ str = str let f_ (str : ('a, 'b, 'c, 'd) format4) = str let fn_ fmt1 fmt2 n = if n = 1 then fmt1^^"" else fmt2^^"" let init = [] end module OASISContext = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISContext.ml" open OASISGettext type level = [ `Debug | `Info | `Warning | `Error] type t = { quiet: bool; info: bool; debug: bool; ignore_plugins: bool; ignore_unknown_fields: bool; printf: level -> string -> unit; } let printf lvl str = let beg = match lvl with | `Error -> s_ "E: " | `Warning -> s_ "W: " | `Info -> s_ "I: " | `Debug -> s_ "D: " in prerr_endline (beg^str) let default = ref { quiet = false; info = false; debug = false; ignore_plugins = false; ignore_unknown_fields = false; printf = printf; } let quiet = {!default with quiet = true} let args () = ["-quiet", Arg.Unit (fun () -> default := {!default with quiet = true}), (s_ " Run quietly"); "-info", Arg.Unit (fun () -> default := {!default with info = true}), (s_ " Display information message"); "-debug", Arg.Unit (fun () -> default := {!default with debug = true}), (s_ " Output debug message")] end module OASISString = struct # 1 "/home/dim/sources/oasis/src/oasis/OASISString.ml" (** Various string utilities. Mostly inspired by extlib and batteries ExtString and BatString libraries. @author Sylvain Le Gall *) let nsplitf str f = if str = "" then [] else let buf = Buffer.create 13 in let lst = ref [] in let push () = lst := Buffer.contents buf :: !lst; Buffer.clear buf in let str_len = String.length str in for i = 0 to str_len - 1 do if f str.[i] then push () else Buffer.add_char buf str.[i] done; push (); List.rev !lst (** [nsplit c s] Split the string [s] at char [c]. It doesn't include the separator. *) let nsplit str c = nsplitf str ((=) c) let find ~what ?(offset=0) str = let what_idx = ref 0 in let str_idx = ref offset in while !str_idx < String.length str && !what_idx < String.length what do if str.[!str_idx] = what.[!what_idx] then incr what_idx else what_idx := 0; incr str_idx done; if !what_idx <> String.length what then raise Not_found else !str_idx - !what_idx let sub_start str len = let str_len = String.length str in if len >= str_len then "" else String.sub str len (str_len - len) let sub_end ?(offset=0) str len = let str_len = String.length str in if len >= str_len then "" else String.sub str 0 (str_len - len) let starts_with ~what ?(offset=0) str = let what_idx = ref 0 in let str_idx = ref offset in let ok = ref true in while !ok && !str_idx < String.length str && !what_idx < String.length what do if str.[!str_idx] = what.[!what_idx] then incr what_idx else ok := false; incr str_idx done; if !what_idx = String.length what then true else false let strip_starts_with ~what str = if starts_with ~what str then sub_start str (String.length what) else raise Not_found let ends_with ~what ?(offset=0) str = let what_idx = ref ((String.length what) - 1) in let str_idx = ref ((String.length str) - 1) in let ok = ref true in while !ok && offset <= !str_idx && 0 <= !what_idx do if str.[!str_idx] = what.[!what_idx] then decr what_idx else ok := false; decr str_idx done; if !what_idx = -1 then true else false let strip_ends_with ~what str = if ends_with ~what str then sub_end str (String.length what) else raise Not_found let replace_chars f s = let buf = String.make (String.length s) 'X' in for i = 0 to String.length s - 1 do buf.[i] <- f s.[i] done; buf end module OASISUtils = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISUtils.ml" open OASISGettext module MapString = Map.Make(String) let map_string_of_assoc assoc = List.fold_left (fun acc (k, v) -> MapString.add k v acc) MapString.empty assoc module SetString = Set.Make(String) let set_string_add_list st lst = List.fold_left (fun acc e -> SetString.add e acc) st lst let set_string_of_list = set_string_add_list SetString.empty let compare_csl s1 s2 = String.compare (String.lowercase s1) (String.lowercase s2) module HashStringCsl = Hashtbl.Make (struct type t = string let equal s1 s2 = (String.lowercase s1) = (String.lowercase s2) let hash s = Hashtbl.hash (String.lowercase s) end) let varname_of_string ?(hyphen='_') s = if String.length s = 0 then begin invalid_arg "varname_of_string" end else begin let buf = OASISString.replace_chars (fun c -> if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') then c else hyphen) s; in let buf = (* Start with a _ if digit *) if '0' <= s.[0] && s.[0] <= '9' then "_"^buf else buf in String.lowercase buf end let varname_concat ?(hyphen='_') p s = let what = String.make 1 hyphen in let p = try OASISString.strip_ends_with ~what p with Not_found -> p in let s = try OASISString.strip_starts_with ~what s with Not_found -> s in p^what^s let is_varname str = str = varname_of_string str let failwithf fmt = Printf.ksprintf failwith fmt end module PropList = struct # 21 "/home/dim/sources/oasis/src/oasis/PropList.ml" open OASISGettext type name = string exception Not_set of name * string option exception No_printer of name exception Unknown_field of name * name let () = Printexc.register_printer (function | Not_set (nm, Some rsn) -> Some (Printf.sprintf (f_ "Field '%s' is not set: %s") nm rsn) | Not_set (nm, None) -> Some (Printf.sprintf (f_ "Field '%s' is not set") nm) | No_printer nm -> Some (Printf.sprintf (f_ "No default printer for value %s") nm) | Unknown_field (nm, schm) -> Some (Printf.sprintf (f_ "Field %s is not defined in schema %s") nm schm) | _ -> None) module Data = struct type t = (name, unit -> unit) Hashtbl.t let create () = Hashtbl.create 13 let clear t = Hashtbl.clear t # 71 "/home/dim/sources/oasis/src/oasis/PropList.ml" end module Schema = struct type ('ctxt, 'extra) value = { get: Data.t -> string; set: Data.t -> ?context:'ctxt -> string -> unit; help: (unit -> string) option; extra: 'extra; } type ('ctxt, 'extra) t = { name: name; fields: (name, ('ctxt, 'extra) value) Hashtbl.t; order: name Queue.t; name_norm: string -> string; } let create ?(case_insensitive=false) nm = { name = nm; fields = Hashtbl.create 13; order = Queue.create (); name_norm = (if case_insensitive then String.lowercase else fun s -> s); } let add t nm set get extra help = let key = t.name_norm nm in if Hashtbl.mem t.fields key then failwith (Printf.sprintf (f_ "Field '%s' is already defined in schema '%s'") nm t.name); Hashtbl.add t.fields key { set = set; get = get; help = help; extra = extra; }; Queue.add nm t.order let mem t nm = Hashtbl.mem t.fields nm let find t nm = try Hashtbl.find t.fields (t.name_norm nm) with Not_found -> raise (Unknown_field (nm, t.name)) let get t data nm = (find t nm).get data let set t data nm ?context x = (find t nm).set data ?context x let fold f acc t = Queue.fold (fun acc k -> let v = find t k in f acc k v.extra v.help) acc t.order let iter f t = fold (fun () -> f) () t let name t = t.name end module Field = struct type ('ctxt, 'value, 'extra) t = { set: Data.t -> ?context:'ctxt -> 'value -> unit; get: Data.t -> 'value; sets: Data.t -> ?context:'ctxt -> string -> unit; gets: Data.t -> string; help: (unit -> string) option; extra: 'extra; } let new_id = let last_id = ref 0 in fun () -> incr last_id; !last_id let create ?schema ?name ?parse ?print ?default ?update ?help extra = (* Default value container *) let v = ref None in (* If name is not given, create unique one *) let nm = match name with | Some s -> s | None -> Printf.sprintf "_anon_%d" (new_id ()) in (* Last chance to get a value: the default *) let default () = match default with | Some d -> d | None -> raise (Not_set (nm, Some (s_ "no default value"))) in (* Get data *) let get data = (* Get value *) try (Hashtbl.find data nm) (); match !v with | Some x -> x | None -> default () with Not_found -> default () in (* Set data *) let set data ?context x = let x = match update with | Some f -> begin try f ?context (get data) x with Not_set _ -> x end | None -> x in Hashtbl.replace data nm (fun () -> v := Some x) in (* Parse string value, if possible *) let parse = match parse with | Some f -> f | None -> fun ?context s -> failwith (Printf.sprintf (f_ "Cannot parse field '%s' when setting value %S") nm s) in (* Set data, from string *) let sets data ?context s = set ?context data (parse ?context s) in (* Output value as string, if possible *) let print = match print with | Some f -> f | None -> fun _ -> raise (No_printer nm) in (* Get data, as a string *) let gets data = print (get data) in begin match schema with | Some t -> Schema.add t nm sets gets extra help | None -> () end; { set = set; get = get; sets = sets; gets = gets; help = help; extra = extra; } let fset data t ?context x = t.set data ?context x let fget data t = t.get data let fsets data t ?context s = t.sets data ?context s let fgets data t = t.gets data end module FieldRO = struct let create ?schema ?name ?parse ?print ?default ?update ?help extra = let fld = Field.create ?schema ?name ?parse ?print ?default ?update ?help extra in fun data -> Field.fget data fld end end module OASISMessage = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISMessage.ml" open OASISGettext open OASISContext let generic_message ~ctxt lvl fmt = let cond = if ctxt.quiet then false else match lvl with | `Debug -> ctxt.debug | `Info -> ctxt.info | _ -> true in Printf.ksprintf (fun str -> if cond then begin ctxt.printf lvl str end) fmt let debug ~ctxt fmt = generic_message ~ctxt `Debug fmt let info ~ctxt fmt = generic_message ~ctxt `Info fmt let warning ~ctxt fmt = generic_message ~ctxt `Warning fmt let error ~ctxt fmt = generic_message ~ctxt `Error fmt end module OASISVersion = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISVersion.ml" open OASISGettext type s = string type t = string type comparator = | VGreater of t | VGreaterEqual of t | VEqual of t | VLesser of t | VLesserEqual of t | VOr of comparator * comparator | VAnd of comparator * comparator (* Range of allowed characters *) let is_digit c = '0' <= c && c <= '9' let is_alpha c = ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') let is_special = function | '.' | '+' | '-' | '~' -> true | _ -> false let rec version_compare v1 v2 = if v1 <> "" || v2 <> "" then begin (* Compare ascii string, using special meaning for version * related char *) let val_ascii c = if c = '~' then -1 else if is_digit c then 0 else if c = '\000' then 0 else if is_alpha c then Char.code c else (Char.code c) + 256 in let len1 = String.length v1 in let len2 = String.length v2 in let p = ref 0 in (** Compare ascii part *) let compare_vascii () = let cmp = ref 0 in while !cmp = 0 && !p < len1 && !p < len2 && not (is_digit v1.[!p] && is_digit v2.[!p]) do cmp := (val_ascii v1.[!p]) - (val_ascii v2.[!p]); incr p done; if !cmp = 0 && !p < len1 && !p = len2 then val_ascii v1.[!p] else if !cmp = 0 && !p = len1 && !p < len2 then - (val_ascii v2.[!p]) else !cmp in (** Compare digit part *) let compare_digit () = let extract_int v p = let start_p = !p in while !p < String.length v && is_digit v.[!p] do incr p done; let substr = String.sub v !p ((String.length v) - !p) in let res = match String.sub v start_p (!p - start_p) with | "" -> 0 | s -> int_of_string s in res, substr in let i1, tl1 = extract_int v1 (ref !p) in let i2, tl2 = extract_int v2 (ref !p) in i1 - i2, tl1, tl2 in match compare_vascii () with | 0 -> begin match compare_digit () with | 0, tl1, tl2 -> if tl1 <> "" && is_digit tl1.[0] then 1 else if tl2 <> "" && is_digit tl2.[0] then -1 else version_compare tl1 tl2 | n, _, _ -> n end | n -> n end else begin 0 end let version_of_string str = str let string_of_version t = t let chop t = try let pos = String.rindex t '.' in String.sub t 0 pos with Not_found -> t let rec comparator_apply v op = match op with | VGreater cv -> (version_compare v cv) > 0 | VGreaterEqual cv -> (version_compare v cv) >= 0 | VLesser cv -> (version_compare v cv) < 0 | VLesserEqual cv -> (version_compare v cv) <= 0 | VEqual cv -> (version_compare v cv) = 0 | VOr (op1, op2) -> (comparator_apply v op1) || (comparator_apply v op2) | VAnd (op1, op2) -> (comparator_apply v op1) && (comparator_apply v op2) let rec string_of_comparator = function | VGreater v -> "> "^(string_of_version v) | VEqual v -> "= "^(string_of_version v) | VLesser v -> "< "^(string_of_version v) | VGreaterEqual v -> ">= "^(string_of_version v) | VLesserEqual v -> "<= "^(string_of_version v) | VOr (c1, c2) -> (string_of_comparator c1)^" || "^(string_of_comparator c2) | VAnd (c1, c2) -> (string_of_comparator c1)^" && "^(string_of_comparator c2) let rec varname_of_comparator = let concat p v = OASISUtils.varname_concat p (OASISUtils.varname_of_string (string_of_version v)) in function | VGreater v -> concat "gt" v | VLesser v -> concat "lt" v | VEqual v -> concat "eq" v | VGreaterEqual v -> concat "ge" v | VLesserEqual v -> concat "le" v | VOr (c1, c2) -> (varname_of_comparator c1)^"_or_"^(varname_of_comparator c2) | VAnd (c1, c2) -> (varname_of_comparator c1)^"_and_"^(varname_of_comparator c2) let version_0_3_or_after t = comparator_apply t (VGreaterEqual (string_of_version "0.3")) end module OASISLicense = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISLicense.ml" (** License for _oasis fields @author Sylvain Le Gall *) type license = string type license_exception = string type license_version = | Version of OASISVersion.t | VersionOrLater of OASISVersion.t | NoVersion type license_dep_5_unit = { license: license; excption: license_exception option; version: license_version; } type license_dep_5 = | DEP5Unit of license_dep_5_unit | DEP5Or of license_dep_5 list | DEP5And of license_dep_5 list type t = | DEP5License of license_dep_5 | OtherLicense of string (* URL *) end module OASISExpr = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISExpr.ml" open OASISGettext type test = string type flag = string type t = | EBool of bool | ENot of t | EAnd of t * t | EOr of t * t | EFlag of flag | ETest of test * string type 'a choices = (t * 'a) list let eval var_get t = let rec eval' = function | EBool b -> b | ENot e -> not (eval' e) | EAnd (e1, e2) -> (eval' e1) && (eval' e2) | EOr (e1, e2) -> (eval' e1) || (eval' e2) | EFlag nm -> let v = var_get nm in assert(v = "true" || v = "false"); (v = "true") | ETest (nm, vl) -> let v = var_get nm in (v = vl) in eval' t let choose ?printer ?name var_get lst = let rec choose_aux = function | (cond, vl) :: tl -> if eval var_get cond then vl else choose_aux tl | [] -> let str_lst = if lst = [] then s_ "" else String.concat (s_ ", ") (List.map (fun (cond, vl) -> match printer with | Some p -> p vl | None -> s_ "") lst) in match name with | Some nm -> failwith (Printf.sprintf (f_ "No result for the choice list '%s': %s") nm str_lst) | None -> failwith (Printf.sprintf (f_ "No result for a choice list: %s") str_lst) in choose_aux (List.rev lst) end module OASISTypes = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISTypes.ml" type name = string type package_name = string type url = string type unix_dirname = string type unix_filename = string type host_dirname = string type host_filename = string type prog = string type arg = string type args = string list type command_line = (prog * arg list) type findlib_name = string type findlib_full = string type compiled_object = | Byte | Native | Best type dependency = | FindlibPackage of findlib_full * OASISVersion.comparator option | InternalLibrary of name type tool = | ExternalTool of name | InternalExecutable of name type vcs = | Darcs | Git | Svn | Cvs | Hg | Bzr | Arch | Monotone | OtherVCS of url type plugin_kind = [ `Configure | `Build | `Doc | `Test | `Install | `Extra ] type plugin_data_purpose = [ `Configure | `Build | `Install | `Clean | `Distclean | `Install | `Uninstall | `Test | `Doc | `Extra | `Other of string ] type 'a plugin = 'a * name * OASISVersion.t option type all_plugin = plugin_kind plugin type plugin_data = (all_plugin * plugin_data_purpose * (unit -> unit)) list # 102 "/home/dim/sources/oasis/src/oasis/OASISTypes.ml" type 'a conditional = 'a OASISExpr.choices type custom = { pre_command: (command_line option) conditional; post_command: (command_line option) conditional; } type common_section = { cs_name: name; cs_data: PropList.Data.t; cs_plugin_data: plugin_data; } type build_section = { bs_build: bool conditional; bs_install: bool conditional; bs_path: unix_dirname; bs_compiled_object: compiled_object; bs_build_depends: dependency list; bs_build_tools: tool list; bs_c_sources: unix_filename list; bs_data_files: (unix_filename * unix_filename option) list; bs_ccopt: args conditional; bs_cclib: args conditional; bs_dlllib: args conditional; bs_dllpath: args conditional; bs_byteopt: args conditional; bs_nativeopt: args conditional; } type library = { lib_modules: string list; lib_pack: bool; lib_internal_modules: string list; lib_findlib_parent: findlib_name option; lib_findlib_name: findlib_name option; lib_findlib_containers: findlib_name list; } type executable = { exec_custom: bool; exec_main_is: unix_filename; } type flag = { flag_description: string option; flag_default: bool conditional; } type source_repository = { src_repo_type: vcs; src_repo_location: url; src_repo_browser: url option; src_repo_module: string option; src_repo_branch: string option; src_repo_tag: string option; src_repo_subdir: unix_filename option; } type test = { test_type: [`Test] plugin; test_command: command_line conditional; test_custom: custom; test_working_directory: unix_filename option; test_run: bool conditional; test_tools: tool list; } type doc_format = | HTML of unix_filename | DocText | PDF | PostScript | Info of unix_filename | DVI | OtherDoc type doc = { doc_type: [`Doc] plugin; doc_custom: custom; doc_build: bool conditional; doc_install: bool conditional; doc_install_dir: unix_filename; doc_title: string; doc_authors: string list; doc_abstract: string option; doc_format: doc_format; doc_data_files: (unix_filename * unix_filename option) list; doc_build_tools: tool list; } type section = | Library of common_section * build_section * library | Executable of common_section * build_section * executable | Flag of common_section * flag | SrcRepo of common_section * source_repository | Test of common_section * test | Doc of common_section * doc type section_kind = [ `Library | `Executable | `Flag | `SrcRepo | `Test | `Doc ] type package = { oasis_version: OASISVersion.t; ocaml_version: OASISVersion.comparator option; findlib_version: OASISVersion.comparator option; name: package_name; version: OASISVersion.t; license: OASISLicense.t; license_file: unix_filename option; copyrights: string list; maintainers: string list; authors: string list; homepage: url option; synopsis: string; description: string option; categories: url list; conf_type: [`Configure] plugin; conf_custom: custom; build_type: [`Build] plugin; build_custom: custom; install_type: [`Install] plugin; install_custom: custom; uninstall_custom: custom; clean_custom: custom; distclean_custom: custom; files_ab: unix_filename list; sections: section list; plugins: [`Extra] plugin list; schema_data: PropList.Data.t; plugin_data: plugin_data; } end module OASISUnixPath = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISUnixPath.ml" type unix_filename = string type unix_dirname = string type host_filename = string type host_dirname = string let current_dir_name = "." let parent_dir_name = ".." let is_current_dir fn = fn = current_dir_name || fn = "" let concat f1 f2 = if is_current_dir f1 then f2 else let f1' = try OASISString.strip_ends_with ~what:"/" f1 with Not_found -> f1 in f1'^"/"^f2 let make = function | hd :: tl -> List.fold_left (fun f p -> concat f p) hd tl | [] -> invalid_arg "OASISUnixPath.make" let dirname f = try String.sub f 0 (String.rindex f '/') with Not_found -> current_dir_name let basename f = try let pos_start = (String.rindex f '/') + 1 in String.sub f pos_start ((String.length f) - pos_start) with Not_found -> f let chop_extension f = try let last_dot = String.rindex f '.' in let sub = String.sub f 0 last_dot in try let last_slash = String.rindex f '/' in if last_slash < last_dot then sub else f with Not_found -> sub with Not_found -> f let capitalize_file f = let dir = dirname f in let base = basename f in concat dir (String.capitalize base) let uncapitalize_file f = let dir = dirname f in let base = basename f in concat dir (String.uncapitalize base) end module OASISHostPath = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISHostPath.ml" open Filename module Unix = OASISUnixPath let make = function | [] -> invalid_arg "OASISHostPath.make" | hd :: tl -> List.fold_left Filename.concat hd tl let of_unix ufn = if Sys.os_type = "Unix" then ufn else make (List.map (fun p -> if p = Unix.current_dir_name then current_dir_name else if p = Unix.parent_dir_name then parent_dir_name else p) (OASISString.nsplit ufn '/')) end module OASISSection = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISSection.ml" open OASISTypes let section_kind_common = function | Library (cs, _, _) -> `Library, cs | Executable (cs, _, _) -> `Executable, cs | Flag (cs, _) -> `Flag, cs | SrcRepo (cs, _) -> `SrcRepo, cs | Test (cs, _) -> `Test, cs | Doc (cs, _) -> `Doc, cs let section_common sct = snd (section_kind_common sct) let section_common_set cs = function | Library (_, bs, lib) -> Library (cs, bs, lib) | Executable (_, bs, exec) -> Executable (cs, bs, exec) | Flag (_, flg) -> Flag (cs, flg) | SrcRepo (_, src_repo) -> SrcRepo (cs, src_repo) | Test (_, tst) -> Test (cs, tst) | Doc (_, doc) -> Doc (cs, doc) (** Key used to identify section *) let section_id sct = let k, cs = section_kind_common sct in k, cs.cs_name let string_of_section sct = let k, nm = section_id sct in (match k with | `Library -> "library" | `Executable -> "executable" | `Flag -> "flag" | `SrcRepo -> "src repository" | `Test -> "test" | `Doc -> "doc") ^" "^nm let section_find id scts = List.find (fun sct -> id = section_id sct) scts module CSection = struct type t = section let id = section_id let compare t1 t2 = compare (id t1) (id t2) let equal t1 t2 = (id t1) = (id t2) let hash t = Hashtbl.hash (id t) end module MapSection = Map.Make(CSection) module SetSection = Set.Make(CSection) end module OASISBuildSection = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISBuildSection.ml" end module OASISExecutable = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISExecutable.ml" open OASISTypes let unix_exec_is (cs, bs, exec) is_native ext_dll suffix_program = let dir = OASISUnixPath.concat bs.bs_path (OASISUnixPath.dirname exec.exec_main_is) in let is_native_exec = match bs.bs_compiled_object with | Native -> true | Best -> is_native () | Byte -> false in OASISUnixPath.concat dir (cs.cs_name^(suffix_program ())), if not is_native_exec && not exec.exec_custom && bs.bs_c_sources <> [] then Some (dir^"/dll"^cs.cs_name^"_stubs"^(ext_dll ())) else None end module OASISLibrary = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISLibrary.ml" open OASISTypes open OASISUtils open OASISGettext open OASISSection type library_name = name type findlib_part_name = name type 'a map_of_findlib_part_name = 'a OASISUtils.MapString.t exception InternalLibraryNotFound of library_name exception FindlibPackageNotFound of findlib_name type group_t = | Container of findlib_name * group_t list | Package of (findlib_name * common_section * build_section * library * group_t list) (* Look for a module file, considering capitalization or not. *) let find_module source_file_exists (cs, bs, lib) modul = let possible_base_fn = List.map (OASISUnixPath.concat bs.bs_path) [modul; OASISUnixPath.uncapitalize_file modul; OASISUnixPath.capitalize_file modul] in (* TODO: we should be able to be able to determine the source for every * files. Hence we should introduce a Module(source: fn) for the fields * Modules and InternalModules *) List.fold_left (fun acc base_fn -> match acc with | `No_sources _ -> begin let file_found = List.fold_left (fun acc ext -> if source_file_exists (base_fn^ext) then (base_fn^ext) :: acc else acc) [] [".ml"; ".mli"; ".mll"; ".mly"] in match file_found with | [] -> acc | lst -> `Sources (base_fn, lst) end | `Sources _ -> acc) (`No_sources possible_base_fn) possible_base_fn let source_unix_files ~ctxt (cs, bs, lib) source_file_exists = List.fold_left (fun acc modul -> match find_module source_file_exists (cs, bs, lib) modul with | `Sources (base_fn, lst) -> (base_fn, lst) :: acc | `No_sources _ -> OASISMessage.warning ~ctxt (f_ "Cannot find source file matching \ module '%s' in library %s") modul cs.cs_name; acc) [] (lib.lib_modules @ lib.lib_internal_modules) let generated_unix_files ~ctxt ~is_native ~has_native_dynlink ~ext_lib ~ext_dll ~source_file_exists (cs, bs, lib) = let find_modules lst ext = let find_module modul = match find_module source_file_exists (cs, bs, lib) modul with | `Sources (base_fn, _) -> [base_fn] | `No_sources lst -> OASISMessage.warning ~ctxt (f_ "Cannot find source file matching \ module '%s' in library %s") modul cs.cs_name; lst in List.map (fun nm -> List.map (fun base_fn -> base_fn ^"."^ext) (find_module nm)) lst in (* The headers that should be compiled along *) let headers = if lib.lib_pack then [] else find_modules lib.lib_modules "cmi" in (* The .cmx that be compiled along *) let cmxs = let should_be_built = (not lib.lib_pack) && (* Do not install .cmx packed submodules *) match bs.bs_compiled_object with | Native -> true | Best -> is_native | Byte -> false in if should_be_built then find_modules (lib.lib_modules @ lib.lib_internal_modules) "cmx" else [] in let acc_nopath = [] in (* Compute what libraries should be built *) let acc_nopath = (* Add the packed header file if required *) let add_pack_header acc = if lib.lib_pack then [cs.cs_name^".cmi"] :: acc else acc in let byte acc = add_pack_header ([cs.cs_name^".cma"] :: acc) in let native acc = let acc = add_pack_header (if has_native_dynlink then [cs.cs_name^".cmxs"] :: acc else acc) in [cs.cs_name^".cmxa"] :: [cs.cs_name^ext_lib] :: acc in match bs.bs_compiled_object with | Native -> byte (native acc_nopath) | Best when is_native -> byte (native acc_nopath) | Byte | Best -> byte acc_nopath in (* Add C library to be built *) let acc_nopath = if bs.bs_c_sources <> [] then begin ["lib"^cs.cs_name^"_stubs"^ext_lib] :: ["dll"^cs.cs_name^"_stubs"^ext_dll] :: acc_nopath end else acc_nopath in (* All the files generated *) List.rev_append (List.rev_map (List.rev_map (OASISUnixPath.concat bs.bs_path)) acc_nopath) (headers @ cmxs) type data = common_section * build_section * library type tree = | Node of (data option) * (tree MapString.t) | Leaf of data let findlib_mapping pkg = (* Map from library name to either full findlib name or parts + parent. *) let fndlb_parts_of_lib_name = let fndlb_parts cs lib = let name = match lib.lib_findlib_name with | Some nm -> nm | None -> cs.cs_name in let name = String.concat "." (lib.lib_findlib_containers @ [name]) in name in List.fold_left (fun mp -> function | Library (cs, _, lib) -> begin let lib_name = cs.cs_name in let fndlb_parts = fndlb_parts cs lib in if MapString.mem lib_name mp then failwithf (f_ "The library name '%s' is used more than once.") lib_name; match lib.lib_findlib_parent with | Some lib_name_parent -> MapString.add lib_name (`Unsolved (lib_name_parent, fndlb_parts)) mp | None -> MapString.add lib_name (`Solved fndlb_parts) mp end | Executable _ | Test _ | Flag _ | SrcRepo _ | Doc _ -> mp) MapString.empty pkg.sections in (* Solve the above graph to be only library name to full findlib name. *) let fndlb_name_of_lib_name = let rec solve visited mp lib_name lib_name_child = if SetString.mem lib_name visited then failwithf (f_ "Library '%s' is involved in a cycle \ with regard to findlib naming.") lib_name; let visited = SetString.add lib_name visited in try match MapString.find lib_name mp with | `Solved fndlb_nm -> fndlb_nm, mp | `Unsolved (lib_nm_parent, post_fndlb_nm) -> let pre_fndlb_nm, mp = solve visited mp lib_nm_parent lib_name in let fndlb_nm = pre_fndlb_nm^"."^post_fndlb_nm in fndlb_nm, MapString.add lib_name (`Solved fndlb_nm) mp with Not_found -> failwithf (f_ "Library '%s', which is defined as the findlib parent of \ library '%s', doesn't exist.") lib_name lib_name_child in let mp = MapString.fold (fun lib_name status mp -> match status with | `Solved _ -> (* Solved initialy, no need to go further *) mp | `Unsolved _ -> let _, mp = solve SetString.empty mp lib_name "" in mp) fndlb_parts_of_lib_name fndlb_parts_of_lib_name in MapString.map (function | `Solved fndlb_nm -> fndlb_nm | `Unsolved _ -> assert false) mp in (* Convert an internal library name to a findlib name. *) let findlib_name_of_library_name lib_nm = try MapString.find lib_nm fndlb_name_of_lib_name with Not_found -> raise (InternalLibraryNotFound lib_nm) in (* Add a library to the tree. *) let add sct mp = let fndlb_fullname = let cs, _, _ = sct in let lib_name = cs.cs_name in findlib_name_of_library_name lib_name in let rec add_children nm_lst (children : tree MapString.t) = match nm_lst with | (hd :: tl) -> begin let node = try add_node tl (MapString.find hd children) with Not_found -> (* New node *) new_node tl in MapString.add hd node children end | [] -> (* Should not have a nameless library. *) assert false and add_node tl node = if tl = [] then begin match node with | Node (None, children) -> Node (Some sct, children) | Leaf (cs', _, _) | Node (Some (cs', _, _), _) -> (* TODO: allow to merge Package, i.e. * archive(byte) = "foo.cma foo_init.cmo" *) let cs, _, _ = sct in failwithf (f_ "Library '%s' and '%s' have the same findlib name '%s'") cs.cs_name cs'.cs_name fndlb_fullname end else begin match node with | Leaf data -> Node (Some data, add_children tl MapString.empty) | Node (data_opt, children) -> Node (data_opt, add_children tl children) end and new_node = function | [] -> Leaf sct | hd :: tl -> Node (None, MapString.add hd (new_node tl) MapString.empty) in add_children (OASISString.nsplit fndlb_fullname '.') mp in let rec group_of_tree mp = MapString.fold (fun nm node acc -> let cur = match node with | Node (Some (cs, bs, lib), children) -> Package (nm, cs, bs, lib, group_of_tree children) | Node (None, children) -> Container (nm, group_of_tree children) | Leaf (cs, bs, lib) -> Package (nm, cs, bs, lib, []) in cur :: acc) mp [] in let group_mp = List.fold_left (fun mp -> function | Library (cs, bs, lib) -> add (cs, bs, lib) mp | _ -> mp) MapString.empty pkg.sections in let groups = group_of_tree group_mp in let library_name_of_findlib_name = Lazy.lazy_from_fun (fun () -> (* Revert findlib_name_of_library_name. *) MapString.fold (fun k v mp -> MapString.add v k mp) fndlb_name_of_lib_name MapString.empty) in let library_name_of_findlib_name fndlb_nm = try MapString.find fndlb_nm (Lazy.force library_name_of_findlib_name) with Not_found -> raise (FindlibPackageNotFound fndlb_nm) in groups, findlib_name_of_library_name, library_name_of_findlib_name let findlib_of_group = function | Container (fndlb_nm, _) | Package (fndlb_nm, _, _, _, _) -> fndlb_nm let root_of_group grp = let rec root_lib_aux = (* We do a DFS in the group. *) function | Container (_, children) -> List.fold_left (fun res grp -> if res = None then root_lib_aux grp else res) None children | Package (_, cs, bs, lib, _) -> Some (cs, bs, lib) in match root_lib_aux grp with | Some res -> res | None -> failwithf (f_ "Unable to determine root library of findlib library '%s'") (findlib_of_group grp) end module OASISFlag = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISFlag.ml" end module OASISPackage = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISPackage.ml" end module OASISSourceRepository = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISSourceRepository.ml" end module OASISTest = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISTest.ml" end module OASISDocument = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISDocument.ml" end module OASISExec = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISExec.ml" open OASISGettext open OASISUtils open OASISMessage (* TODO: I don't like this quote, it is there because $(rm) foo expands to * 'rm -f' foo... *) let run ~ctxt ?f_exit_code ?(quote=true) cmd args = let cmd = if quote then if Sys.os_type = "Win32" then if String.contains cmd ' ' then (* Double the 1st double quote... win32... sigh *) "\""^(Filename.quote cmd) else cmd else Filename.quote cmd else cmd in let cmdline = String.concat " " (cmd :: args) in info ~ctxt (f_ "Running command '%s'") cmdline; match f_exit_code, Sys.command cmdline with | None, 0 -> () | None, i -> failwithf (f_ "Command '%s' terminated with error code %d") cmdline i | Some f, i -> f i let run_read_output ~ctxt ?f_exit_code cmd args = let fn = Filename.temp_file "oasis-" ".txt" in try begin let () = run ~ctxt ?f_exit_code cmd (args @ [">"; Filename.quote fn]) in let chn = open_in fn in let routput = ref [] in begin try while true do routput := (input_line chn) :: !routput done with End_of_file -> () end; close_in chn; Sys.remove fn; List.rev !routput end with e -> (try Sys.remove fn with _ -> ()); raise e let run_read_one_line ~ctxt ?f_exit_code cmd args = match run_read_output ~ctxt ?f_exit_code cmd args with | [fst] -> fst | lst -> failwithf (f_ "Command return unexpected output %S") (String.concat "\n" lst) end module OASISFileUtil = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISFileUtil.ml" open OASISGettext let file_exists_case fn = let dirname = Filename.dirname fn in let basename = Filename.basename fn in if Sys.file_exists dirname then if basename = Filename.current_dir_name then true else List.mem basename (Array.to_list (Sys.readdir dirname)) else false let find_file ?(case_sensitive=true) paths exts = (* Cardinal product of two list *) let ( * ) lst1 lst2 = List.flatten (List.map (fun a -> List.map (fun b -> a,b) lst2) lst1) in let rec combined_paths lst = match lst with | p1 :: p2 :: tl -> let acc = (List.map (fun (a,b) -> Filename.concat a b) (p1 * p2)) in combined_paths (acc :: tl) | [e] -> e | [] -> [] in let alternatives = List.map (fun (p,e) -> if String.length e > 0 && e.[0] <> '.' then p ^ "." ^ e else p ^ e) ((combined_paths paths) * exts) in List.find (if case_sensitive then file_exists_case else Sys.file_exists) alternatives let which ~ctxt prg = let path_sep = match Sys.os_type with | "Win32" -> ';' | _ -> ':' in let path_lst = OASISString.nsplit (Sys.getenv "PATH") path_sep in let exec_ext = match Sys.os_type with | "Win32" -> "" :: (OASISString.nsplit (Sys.getenv "PATHEXT") path_sep) | _ -> [""] in find_file ~case_sensitive:false [path_lst; [prg]] exec_ext (**/**) let rec fix_dir dn = (* Windows hack because Sys.file_exists "src\\" = false when * Sys.file_exists "src" = true *) let ln = String.length dn in if Sys.os_type = "Win32" && ln > 0 && dn.[ln - 1] = '\\' then fix_dir (String.sub dn 0 (ln - 1)) else dn let q = Filename.quote (**/**) let cp ~ctxt ?(recurse=false) src tgt = if recurse then match Sys.os_type with | "Win32" -> OASISExec.run ~ctxt "xcopy" [q src; q tgt; "/E"] | _ -> OASISExec.run ~ctxt "cp" ["-r"; q src; q tgt] else OASISExec.run ~ctxt (match Sys.os_type with | "Win32" -> "copy" | _ -> "cp") [q src; q tgt] let mkdir ~ctxt tgt = OASISExec.run ~ctxt (match Sys.os_type with | "Win32" -> "md" | _ -> "mkdir") [q tgt] let rec mkdir_parent ~ctxt f tgt = let tgt = fix_dir tgt in if Sys.file_exists tgt then begin if not (Sys.is_directory tgt) then OASISUtils.failwithf (f_ "Cannot create directory '%s', a file of the same name already \ exists") tgt end else begin mkdir_parent ~ctxt f (Filename.dirname tgt); if not (Sys.file_exists tgt) then begin f tgt; mkdir ~ctxt tgt end end let rmdir ~ctxt tgt = if Sys.readdir tgt = [||] then begin match Sys.os_type with | "Win32" -> OASISExec.run ~ctxt "rd" [q tgt] | _ -> OASISExec.run ~ctxt "rm" ["-r"; q tgt] end let glob ~ctxt fn = let basename = Filename.basename fn in if String.length basename >= 2 && basename.[0] = '*' && basename.[1] = '.' then begin let ext_len = (String.length basename) - 2 in let ext = String.sub basename 2 ext_len in let dirname = Filename.dirname fn in Array.fold_left (fun acc fn -> try let fn_ext = String.sub fn ((String.length fn) - ext_len) ext_len in if fn_ext = ext then (Filename.concat dirname fn) :: acc else acc with Invalid_argument _ -> acc) [] (Sys.readdir dirname) end else begin if file_exists_case fn then [fn] else [] end end # 2142 "setup.ml" module BaseEnvLight = struct # 21 "/home/dim/sources/oasis/src/base/BaseEnvLight.ml" module MapString = Map.Make(String) type t = string MapString.t let default_filename = Filename.concat (Sys.getcwd ()) "setup.data" let load ?(allow_empty=false) ?(filename=default_filename) () = if Sys.file_exists filename then begin let chn = open_in_bin filename in let st = Stream.of_channel chn in let line = ref 1 in let st_line = Stream.from (fun _ -> try match Stream.next st with | '\n' -> incr line; Some '\n' | c -> Some c with Stream.Failure -> None) in let lexer = Genlex.make_lexer ["="] st_line in let rec read_file mp = match Stream.npeek 3 lexer with | [Genlex.Ident nm; Genlex.Kwd "="; Genlex.String value] -> Stream.junk lexer; Stream.junk lexer; Stream.junk lexer; read_file (MapString.add nm value mp) | [] -> mp | _ -> failwith (Printf.sprintf "Malformed data file '%s' line %d" filename !line) in let mp = read_file MapString.empty in close_in chn; mp end else if allow_empty then begin MapString.empty end else begin failwith (Printf.sprintf "Unable to load environment, the file '%s' doesn't exist." filename) end let var_get name env = let rec var_expand str = let buff = Buffer.create ((String.length str) * 2) in Buffer.add_substitute buff (fun var -> try var_expand (MapString.find var env) with Not_found -> failwith (Printf.sprintf "No variable %s defined when trying to expand %S." var str)) str; Buffer.contents buff in var_expand (MapString.find name env) let var_choose lst env = OASISExpr.choose (fun nm -> var_get nm env) lst end # 2240 "setup.ml" module BaseContext = struct # 21 "/home/dim/sources/oasis/src/base/BaseContext.ml" open OASISContext let args = args let default = default end module BaseMessage = struct # 21 "/home/dim/sources/oasis/src/base/BaseMessage.ml" (** Message to user, overrid for Base @author Sylvain Le Gall *) open OASISMessage open BaseContext let debug fmt = debug ~ctxt:!default fmt let info fmt = info ~ctxt:!default fmt let warning fmt = warning ~ctxt:!default fmt let error fmt = error ~ctxt:!default fmt end module BaseEnv = struct # 21 "/home/dim/sources/oasis/src/base/BaseEnv.ml" open OASISGettext open OASISUtils open PropList module MapString = BaseEnvLight.MapString type origin_t = | ODefault | OGetEnv | OFileLoad | OCommandLine type cli_handle_t = | CLINone | CLIAuto | CLIWith | CLIEnable | CLIUser of (Arg.key * Arg.spec * Arg.doc) list type definition_t = { hide: bool; dump: bool; cli: cli_handle_t; arg_help: string option; group: string option; } let schema = Schema.create "environment" (* Environment data *) let env = Data.create () (* Environment data from file *) let env_from_file = ref MapString.empty (* Lexer for var *) let var_lxr = Genlex.make_lexer [] let rec var_expand str = let buff = Buffer.create ((String.length str) * 2) in Buffer.add_substitute buff (fun var -> try (* TODO: this is a quick hack to allow calling Test.Command * without defining executable name really. I.e. if there is * an exec Executable toto, then $(toto) should be replace * by its real name. It is however useful to have this function * for other variable that depend on the host and should be * written better than that. *) let st = var_lxr (Stream.of_string var) in match Stream.npeek 3 st with | [Genlex.Ident "utoh"; Genlex.Ident nm] -> OASISHostPath.of_unix (var_get nm) | [Genlex.Ident "utoh"; Genlex.String s] -> OASISHostPath.of_unix s | [Genlex.Ident "ocaml_escaped"; Genlex.Ident nm] -> String.escaped (var_get nm) | [Genlex.Ident "ocaml_escaped"; Genlex.String s] -> String.escaped s | [Genlex.Ident nm] -> var_get nm | _ -> failwithf (f_ "Unknown expression '%s' in variable expansion of %s.") var str with | Unknown_field (_, _) -> failwithf (f_ "No variable %s defined when trying to expand %S.") var str | Stream.Error e -> failwithf (f_ "Syntax error when parsing '%s' when trying to \ expand %S: %s") var str e) str; Buffer.contents buff and var_get name = let vl = try Schema.get schema env name with Unknown_field _ as e -> begin try MapString.find name !env_from_file with Not_found -> raise e end in var_expand vl let var_choose ?printer ?name lst = OASISExpr.choose ?printer ?name var_get lst let var_protect vl = let buff = Buffer.create (String.length vl) in String.iter (function | '$' -> Buffer.add_string buff "\\$" | c -> Buffer.add_char buff c) vl; Buffer.contents buff let var_define ?(hide=false) ?(dump=true) ?short_desc ?(cli=CLINone) ?arg_help ?group name (* TODO: type constraint on the fact that name must be a valid OCaml id *) dflt = let default = [ OFileLoad, (fun () -> MapString.find name !env_from_file); ODefault, dflt; OGetEnv, (fun () -> Sys.getenv name); ] in let extra = { hide = hide; dump = dump; cli = cli; arg_help = arg_help; group = group; } in (* Try to find a value that can be defined *) let var_get_low lst = let errors, res = List.fold_left (fun (errors, res) (o, v) -> if res = None then begin try errors, Some (v ()) with | Not_found -> errors, res | Failure rsn -> (rsn :: errors), res | e -> (Printexc.to_string e) :: errors, res end else errors, res) ([], None) (List.sort (fun (o1, _) (o2, _) -> Pervasives.compare o2 o1) lst) in match res, errors with | Some v, _ -> v | None, [] -> raise (Not_set (name, None)) | None, lst -> raise (Not_set (name, Some (String.concat (s_ ", ") lst))) in let help = match short_desc with | Some fs -> Some fs | None -> None in let var_get_lst = FieldRO.create ~schema ~name ~parse:(fun ?(context=ODefault) s -> [context, fun () -> s]) ~print:var_get_low ~default ~update:(fun ?context x old_x -> x @ old_x) ?help extra in fun () -> var_expand (var_get_low (var_get_lst env)) let var_redefine ?hide ?dump ?short_desc ?cli ?arg_help ?group name dflt = if Schema.mem schema name then begin (* TODO: look suspsicious, we want to memorize dflt not dflt () *) Schema.set schema env ~context:ODefault name (dflt ()); fun () -> var_get name end else begin var_define ?hide ?dump ?short_desc ?cli ?arg_help ?group name dflt end let var_ignore (e : unit -> string) = () let print_hidden = var_define ~hide:true ~dump:false ~cli:CLIAuto ~arg_help:"Print even non-printable variable. (debug)" "print_hidden" (fun () -> "false") let var_all () = List.rev (Schema.fold (fun acc nm def _ -> if not def.hide || bool_of_string (print_hidden ()) then nm :: acc else acc) [] schema) let default_filename = BaseEnvLight.default_filename let load ?allow_empty ?filename () = env_from_file := BaseEnvLight.load ?allow_empty ?filename () let unload () = env_from_file := MapString.empty; Data.clear env let dump ?(filename=default_filename) () = let chn = open_out_bin filename in let output nm value = Printf.fprintf chn "%s=%S\n" nm value in let mp_todo = (* Dump data from schema *) Schema.fold (fun mp_todo nm def _ -> if def.dump then begin try let value = Schema.get schema env nm in output nm value with Not_set _ -> () end; MapString.remove nm mp_todo) !env_from_file schema in (* Dump data defined outside of schema *) MapString.iter output mp_todo; (* End of the dump *) close_out chn let print () = let printable_vars = Schema.fold (fun acc nm def short_descr_opt -> if not def.hide || bool_of_string (print_hidden ()) then begin try let value = Schema.get schema env nm in let txt = match short_descr_opt with | Some s -> s () | None -> nm in (txt, value) :: acc with Not_set _ -> acc end else acc) [] schema in let max_length = List.fold_left max 0 (List.rev_map String.length (List.rev_map fst printable_vars)) in let dot_pad str = String.make ((max_length - (String.length str)) + 3) '.' in Printf.printf "\nConfiguration: \n"; List.iter (fun (name,value) -> Printf.printf "%s: %s %s\n" name (dot_pad name) value) (List.rev printable_vars); Printf.printf "\n%!" let args () = let arg_concat = OASISUtils.varname_concat ~hyphen:'-' in [ "--override", Arg.Tuple ( let rvr = ref "" in let rvl = ref "" in [ Arg.Set_string rvr; Arg.Set_string rvl; Arg.Unit (fun () -> Schema.set schema env ~context:OCommandLine !rvr !rvl) ] ), "var+val Override any configuration variable."; ] @ List.flatten (Schema.fold (fun acc name def short_descr_opt -> let var_set s = Schema.set schema env ~context:OCommandLine name s in let arg_name = OASISUtils.varname_of_string ~hyphen:'-' name in let hlp = match short_descr_opt with | Some txt -> txt () | None -> "" in let arg_hlp = match def.arg_help with | Some s -> s | None -> "str" in let default_value = try Printf.sprintf (f_ " [%s]") (Schema.get schema env name) with Not_set _ -> "" in let args = match def.cli with | CLINone -> [] | CLIAuto -> [ arg_concat "--" arg_name, Arg.String var_set, Printf.sprintf (f_ "%s %s%s") arg_hlp hlp default_value ] | CLIWith -> [ arg_concat "--with-" arg_name, Arg.String var_set, Printf.sprintf (f_ "%s %s%s") arg_hlp hlp default_value ] | CLIEnable -> let dflt = if default_value = " [true]" then s_ " [default: enabled]" else s_ " [default: disabled]" in [ arg_concat "--enable-" arg_name, Arg.Unit (fun () -> var_set "true"), Printf.sprintf (f_ " %s%s") hlp dflt; arg_concat "--disable-" arg_name, Arg.Unit (fun () -> var_set "false"), Printf.sprintf (f_ " %s%s") hlp dflt ] | CLIUser lst -> lst in args :: acc) [] schema) end module BaseArgExt = struct # 21 "/home/dim/sources/oasis/src/base/BaseArgExt.ml" open OASISUtils open OASISGettext let parse argv args = (* Simulate command line for Arg *) let current = ref 0 in try Arg.parse_argv ~current:current (Array.concat [[|"none"|]; argv]) (Arg.align args) (failwithf (f_ "Don't know what to do with arguments: '%s'")) (s_ "configure options:") with | Arg.Help txt -> print_endline txt; exit 0 | Arg.Bad txt -> prerr_endline txt; exit 1 end module BaseCheck = struct # 21 "/home/dim/sources/oasis/src/base/BaseCheck.ml" open BaseEnv open BaseMessage open OASISUtils open OASISGettext let prog_best prg prg_lst = var_redefine prg (fun () -> let alternate = List.fold_left (fun res e -> match res with | Some _ -> res | None -> try Some (OASISFileUtil.which ~ctxt:!BaseContext.default e) with Not_found -> None) None prg_lst in match alternate with | Some prg -> prg | None -> raise Not_found) let prog prg = prog_best prg [prg] let prog_opt prg = prog_best prg [prg^".opt"; prg] let ocamlfind = prog "ocamlfind" let version var_prefix cmp fversion () = (* Really compare version provided *) let var = var_prefix^"_version_"^(OASISVersion.varname_of_comparator cmp) in var_redefine ~hide:true var (fun () -> let version_str = match fversion () with | "[Distributed with OCaml]" -> begin try (var_get "ocaml_version") with Not_found -> warning (f_ "Variable ocaml_version not defined, fallback \ to default"); Sys.ocaml_version end | res -> res in let version = OASISVersion.version_of_string version_str in if OASISVersion.comparator_apply version cmp then version_str else failwithf (f_ "Cannot satisfy version constraint on %s: %s (version: %s)") var_prefix (OASISVersion.string_of_comparator cmp) version_str) () let package_version pkg = OASISExec.run_read_one_line ~ctxt:!BaseContext.default (ocamlfind ()) ["query"; "-format"; "%v"; pkg] let package ?version_comparator pkg () = let var = OASISUtils.varname_concat "pkg_" (OASISUtils.varname_of_string pkg) in let findlib_dir pkg = let dir = OASISExec.run_read_one_line ~ctxt:!BaseContext.default (ocamlfind ()) ["query"; "-format"; "%d"; pkg] in if Sys.file_exists dir && Sys.is_directory dir then dir else failwithf (f_ "When looking for findlib package %s, \ directory %s return doesn't exist") pkg dir in let vl = var_redefine var (fun () -> findlib_dir pkg) () in ( match version_comparator with | Some ver_cmp -> ignore (version var ver_cmp (fun _ -> package_version pkg) ()) | None -> () ); vl end module BaseOCamlcConfig = struct # 21 "/home/dim/sources/oasis/src/base/BaseOCamlcConfig.ml" open BaseEnv open OASISUtils open OASISGettext module SMap = Map.Make(String) let ocamlc = BaseCheck.prog_opt "ocamlc" let ocamlc_config_map = (* Map name to value for ocamlc -config output (name ^": "^value) *) let rec split_field mp lst = match lst with | line :: tl -> let mp = try let pos_semicolon = String.index line ':' in if pos_semicolon > 1 then ( let name = String.sub line 0 pos_semicolon in let linelen = String.length line in let value = if linelen > pos_semicolon + 2 then String.sub line (pos_semicolon + 2) (linelen - pos_semicolon - 2) else "" in SMap.add name value mp ) else ( mp ) with Not_found -> ( mp ) in split_field mp tl | [] -> mp in let cache = lazy (var_protect (Marshal.to_string (split_field SMap.empty (OASISExec.run_read_output ~ctxt:!BaseContext.default (ocamlc ()) ["-config"])) [])) in var_redefine "ocamlc_config_map" ~hide:true ~dump:false (fun () -> (* TODO: update if ocamlc change !!! *) Lazy.force cache) let var_define nm = (* Extract data from ocamlc -config *) let avlbl_config_get () = Marshal.from_string (ocamlc_config_map ()) 0 in let chop_version_suffix s = try String.sub s 0 (String.index s '+') with _ -> s in let nm_config, value_config = match nm with | "ocaml_version" -> "version", chop_version_suffix | _ -> nm, (fun x -> x) in var_redefine nm (fun () -> try let map = avlbl_config_get () in let value = SMap.find nm_config map in value_config value with Not_found -> failwithf (f_ "Cannot find field '%s' in '%s -config' output") nm (ocamlc ())) end module BaseStandardVar = struct # 21 "/home/dim/sources/oasis/src/base/BaseStandardVar.ml" open OASISGettext open OASISTypes open OASISExpr open BaseCheck open BaseEnv let ocamlfind = BaseCheck.ocamlfind let ocamlc = BaseOCamlcConfig.ocamlc let ocamlopt = prog_opt "ocamlopt" let ocamlbuild = prog "ocamlbuild" (**/**) let rpkg = ref None let pkg_get () = match !rpkg with | Some pkg -> pkg | None -> failwith (s_ "OASIS Package is not set") let var_cond = ref [] let var_define_cond ~since_version f dflt = let holder = ref (fun () -> dflt) in let since_version = OASISVersion.VGreaterEqual (OASISVersion.version_of_string since_version) in var_cond := (fun ver -> if OASISVersion.comparator_apply ver since_version then holder := f ()) :: !var_cond; fun () -> !holder () (**/**) let pkg_name = var_define ~short_desc:(fun () -> s_ "Package name") "pkg_name" (fun () -> (pkg_get ()).name) let pkg_version = var_define ~short_desc:(fun () -> s_ "Package version") "pkg_version" (fun () -> (OASISVersion.string_of_version (pkg_get ()).version)) let c = BaseOCamlcConfig.var_define let os_type = c "os_type" let system = c "system" let architecture = c "architecture" let ccomp_type = c "ccomp_type" let ocaml_version = c "ocaml_version" (* TODO: Check standard variable presence at runtime *) let standard_library_default = c "standard_library_default" let standard_library = c "standard_library" let standard_runtime = c "standard_runtime" let bytecomp_c_compiler = c "bytecomp_c_compiler" let native_c_compiler = c "native_c_compiler" let model = c "model" let ext_obj = c "ext_obj" let ext_asm = c "ext_asm" let ext_lib = c "ext_lib" let ext_dll = c "ext_dll" let default_executable_name = c "default_executable_name" let systhread_supported = c "systhread_supported" let flexlink = BaseCheck.prog "flexlink" let flexdll_version = var_define ~short_desc:(fun () -> "FlexDLL version (Win32)") "flexdll_version" (fun () -> let lst = OASISExec.run_read_output ~ctxt:!BaseContext.default (flexlink ()) ["-help"] in match lst with | line :: _ -> Scanf.sscanf line "FlexDLL version %s" (fun ver -> ver) | [] -> raise Not_found) (**/**) let p name hlp dflt = var_define ~short_desc:hlp ~cli:CLIAuto ~arg_help:"dir" name dflt let (/) a b = if os_type () = Sys.os_type then Filename.concat a b else if os_type () = "Unix" then OASISUnixPath.concat a b else OASISUtils.failwithf (f_ "Cannot handle os_type %s filename concat") (os_type ()) (**/**) let prefix = p "prefix" (fun () -> s_ "Install architecture-independent files dir") (fun () -> match os_type () with | "Win32" -> let program_files = Sys.getenv "PROGRAMFILES" in program_files/(pkg_name ()) | _ -> "/usr/local") let exec_prefix = p "exec_prefix" (fun () -> s_ "Install architecture-dependent files in dir") (fun () -> "$prefix") let bindir = p "bindir" (fun () -> s_ "User executables") (fun () -> "$exec_prefix"/"bin") let sbindir = p "sbindir" (fun () -> s_ "System admin executables") (fun () -> "$exec_prefix"/"sbin") let libexecdir = p "libexecdir" (fun () -> s_ "Program executables") (fun () -> "$exec_prefix"/"libexec") let sysconfdir = p "sysconfdir" (fun () -> s_ "Read-only single-machine data") (fun () -> "$prefix"/"etc") let sharedstatedir = p "sharedstatedir" (fun () -> s_ "Modifiable architecture-independent data") (fun () -> "$prefix"/"com") let localstatedir = p "localstatedir" (fun () -> s_ "Modifiable single-machine data") (fun () -> "$prefix"/"var") let libdir = p "libdir" (fun () -> s_ "Object code libraries") (fun () -> "$exec_prefix"/"lib") let datarootdir = p "datarootdir" (fun () -> s_ "Read-only arch-independent data root") (fun () -> "$prefix"/"share") let datadir = p "datadir" (fun () -> s_ "Read-only architecture-independent data") (fun () -> "$datarootdir") let infodir = p "infodir" (fun () -> s_ "Info documentation") (fun () -> "$datarootdir"/"info") let localedir = p "localedir" (fun () -> s_ "Locale-dependent data") (fun () -> "$datarootdir"/"locale") let mandir = p "mandir" (fun () -> s_ "Man documentation") (fun () -> "$datarootdir"/"man") let docdir = p "docdir" (fun () -> s_ "Documentation root") (fun () -> "$datarootdir"/"doc"/"$pkg_name") let htmldir = p "htmldir" (fun () -> s_ "HTML documentation") (fun () -> "$docdir") let dvidir = p "dvidir" (fun () -> s_ "DVI documentation") (fun () -> "$docdir") let pdfdir = p "pdfdir" (fun () -> s_ "PDF documentation") (fun () -> "$docdir") let psdir = p "psdir" (fun () -> s_ "PS documentation") (fun () -> "$docdir") let destdir = p "destdir" (fun () -> s_ "Prepend a path when installing package") (fun () -> raise (PropList.Not_set ("destdir", Some (s_ "undefined by construct")))) let findlib_version = var_define "findlib_version" (fun () -> BaseCheck.package_version "findlib") let is_native = var_define "is_native" (fun () -> try let _s : string = ocamlopt () in "true" with PropList.Not_set _ -> let _s : string = ocamlc () in "false") let ext_program = var_define "suffix_program" (fun () -> match os_type () with | "Win32" -> ".exe" | _ -> "") let rm = var_define ~short_desc:(fun () -> s_ "Remove a file.") "rm" (fun () -> match os_type () with | "Win32" -> "del" | _ -> "rm -f") let rmdir = var_define ~short_desc:(fun () -> s_ "Remove a directory.") "rmdir" (fun () -> match os_type () with | "Win32" -> "rd" | _ -> "rm -rf") let debug = var_define ~short_desc:(fun () -> s_ "Turn ocaml debug flag on") ~cli:CLIEnable "debug" (fun () -> "true") let profile = var_define ~short_desc:(fun () -> s_ "Turn ocaml profile flag on") ~cli:CLIEnable "profile" (fun () -> "false") let tests = var_define_cond ~since_version:"0.3" (fun () -> var_define ~short_desc:(fun () -> s_ "Compile tests executable and library and run them") ~cli:CLIEnable "tests" (fun () -> "false")) "true" let docs = var_define_cond ~since_version:"0.3" (fun () -> var_define ~short_desc:(fun () -> s_ "Create documentations") ~cli:CLIEnable "docs" (fun () -> "true")) "true" let native_dynlink = var_define ~short_desc:(fun () -> s_ "Compiler support generation of .cmxs.") ~cli:CLINone "native_dynlink" (fun () -> let res = let ocaml_lt_312 () = OASISVersion.comparator_apply (OASISVersion.version_of_string (ocaml_version ())) (OASISVersion.VLesser (OASISVersion.version_of_string "3.12.0")) in let flexdll_lt_030 () = OASISVersion.comparator_apply (OASISVersion.version_of_string (flexdll_version ())) (OASISVersion.VLesser (OASISVersion.version_of_string "0.30")) in let has_native_dynlink = let ocamlfind = ocamlfind () in try let fn = OASISExec.run_read_one_line ~ctxt:!BaseContext.default ocamlfind ["query"; "-predicates"; "native"; "dynlink"; "-format"; "%d/%a"] in Sys.file_exists fn with _ -> false in if not has_native_dynlink then false else if ocaml_lt_312 () then false else if (os_type () = "Win32" || os_type () = "Cygwin") && flexdll_lt_030 () then begin BaseMessage.warning (f_ ".cmxs generation disabled because FlexDLL needs to be \ at least 0.30. Please upgrade FlexDLL from %s to 0.30.") (flexdll_version ()); false end else true in string_of_bool res) let init pkg = rpkg := Some pkg; List.iter (fun f -> f pkg.oasis_version) !var_cond end module BaseFileAB = struct # 21 "/home/dim/sources/oasis/src/base/BaseFileAB.ml" open BaseEnv open OASISGettext open BaseMessage let to_filename fn = let fn = OASISHostPath.of_unix fn in if not (Filename.check_suffix fn ".ab") then warning (f_ "File '%s' doesn't have '.ab' extension") fn; Filename.chop_extension fn let replace fn_lst = let buff = Buffer.create 13 in List.iter (fun fn -> let fn = OASISHostPath.of_unix fn in let chn_in = open_in fn in let chn_out = open_out (to_filename fn) in ( try while true do Buffer.add_string buff (var_expand (input_line chn_in)); Buffer.add_char buff '\n' done with End_of_file -> () ); Buffer.output_buffer chn_out buff; Buffer.clear buff; close_in chn_in; close_out chn_out) fn_lst end module BaseLog = struct # 21 "/home/dim/sources/oasis/src/base/BaseLog.ml" open OASISUtils let default_filename = Filename.concat (Filename.dirname BaseEnv.default_filename) "setup.log" module SetTupleString = Set.Make (struct type t = string * string let compare (s11, s12) (s21, s22) = match String.compare s11 s21 with | 0 -> String.compare s12 s22 | n -> n end) let load () = if Sys.file_exists default_filename then begin let chn = open_in default_filename in let scbuf = Scanf.Scanning.from_file default_filename in let rec read_aux (st, lst) = if not (Scanf.Scanning.end_of_input scbuf) then begin let acc = try Scanf.bscanf scbuf "%S %S\n" (fun e d -> let t = e, d in if SetTupleString.mem t st then st, lst else SetTupleString.add t st, t :: lst) with Scanf.Scan_failure _ -> failwith (Scanf.bscanf scbuf "%l" (fun line -> Printf.sprintf "Malformed log file '%s' at line %d" default_filename line)) in read_aux acc end else begin close_in chn; List.rev lst end in read_aux (SetTupleString.empty, []) end else begin [] end let register event data = let chn_out = open_out_gen [Open_append; Open_creat; Open_text] 0o644 default_filename in Printf.fprintf chn_out "%S %S\n" event data; close_out chn_out let unregister event data = if Sys.file_exists default_filename then begin let lst = load () in let chn_out = open_out default_filename in let write_something = ref false in List.iter (fun (e, d) -> if e <> event || d <> data then begin write_something := true; Printf.fprintf chn_out "%S %S\n" e d end) lst; close_out chn_out; if not !write_something then Sys.remove default_filename end let filter events = let st_events = List.fold_left (fun st e -> SetString.add e st) SetString.empty events in List.filter (fun (e, _) -> SetString.mem e st_events) (load ()) let exists event data = List.exists (fun v -> (event, data) = v) (load ()) end module BaseBuilt = struct # 21 "/home/dim/sources/oasis/src/base/BaseBuilt.ml" open OASISTypes open OASISGettext open BaseStandardVar open BaseMessage type t = | BExec (* Executable *) | BExecLib (* Library coming with executable *) | BLib (* Library *) | BDoc (* Document *) let to_log_event_file t nm = "built_"^ (match t with | BExec -> "exec" | BExecLib -> "exec_lib" | BLib -> "lib" | BDoc -> "doc")^ "_"^nm let to_log_event_done t nm = "is_"^(to_log_event_file t nm) let register t nm lst = BaseLog.register (to_log_event_done t nm) "true"; List.iter (fun alt -> let registered = List.fold_left (fun registered fn -> if OASISFileUtil.file_exists_case fn then begin BaseLog.register (to_log_event_file t nm) (if Filename.is_relative fn then Filename.concat (Sys.getcwd ()) fn else fn); true end else registered) false alt in if not registered then warning (f_ "Cannot find an existing alternative files among: %s") (String.concat (s_ ", ") alt)) lst let unregister t nm = List.iter (fun (e, d) -> BaseLog.unregister e d) (BaseLog.filter [to_log_event_file t nm; to_log_event_done t nm]) let fold t nm f acc = List.fold_left (fun acc (_, fn) -> if OASISFileUtil.file_exists_case fn then begin f acc fn end else begin warning (f_ "File '%s' has been marked as built \ for %s but doesn't exist") fn (Printf.sprintf (match t with | BExec | BExecLib -> (f_ "executable %s") | BLib -> (f_ "library %s") | BDoc -> (f_ "documentation %s")) nm); acc end) acc (BaseLog.filter [to_log_event_file t nm]) let is_built t nm = List.fold_left (fun is_built (_, d) -> (try bool_of_string d with _ -> false)) false (BaseLog.filter [to_log_event_done t nm]) let of_executable ffn (cs, bs, exec) = let unix_exec_is, unix_dll_opt = OASISExecutable.unix_exec_is (cs, bs, exec) (fun () -> bool_of_string (is_native ())) ext_dll ext_program in let evs = (BExec, cs.cs_name, [[ffn unix_exec_is]]) :: (match unix_dll_opt with | Some fn -> [BExecLib, cs.cs_name, [[ffn fn]]] | None -> []) in evs, unix_exec_is, unix_dll_opt let of_library ffn (cs, bs, lib) = let unix_lst = OASISLibrary.generated_unix_files ~ctxt:!BaseContext.default ~source_file_exists:(fun fn -> OASISFileUtil.file_exists_case (OASISHostPath.of_unix fn)) ~is_native:(bool_of_string (is_native ())) ~has_native_dynlink:(bool_of_string (native_dynlink ())) ~ext_lib:(ext_lib ()) ~ext_dll:(ext_dll ()) (cs, bs, lib) in let evs = [BLib, cs.cs_name, List.map (List.map ffn) unix_lst] in evs, unix_lst end module BaseCustom = struct # 21 "/home/dim/sources/oasis/src/base/BaseCustom.ml" open BaseEnv open BaseMessage open OASISTypes open OASISGettext let run cmd args extra_args = OASISExec.run ~ctxt:!BaseContext.default ~quote:false (var_expand cmd) (List.map var_expand (args @ (Array.to_list extra_args))) let hook ?(failsafe=false) cstm f e = let optional_command lst = let printer = function | Some (cmd, args) -> String.concat " " (cmd :: args) | None -> s_ "No command" in match var_choose ~name:(s_ "Pre/Post Command") ~printer lst with | Some (cmd, args) -> begin try run cmd args [||] with e when failsafe -> warning (f_ "Command '%s' fail with error: %s") (String.concat " " (cmd :: args)) (match e with | Failure msg -> msg | e -> Printexc.to_string e) end | None -> () in let res = optional_command cstm.pre_command; f e in optional_command cstm.post_command; res end module BaseDynVar = struct # 21 "/home/dim/sources/oasis/src/base/BaseDynVar.ml" open OASISTypes open OASISGettext open BaseEnv open BaseBuilt let init pkg = (* TODO: disambiguate exec vs other variable by adding exec_VARNAME. *) (* TODO: provide compile option for library libary_byte_args_VARNAME... *) List.iter (function | Executable (cs, bs, exec) -> if var_choose bs.bs_build then var_ignore (var_redefine (* We don't save this variable *) ~dump:false ~short_desc:(fun () -> Printf.sprintf (f_ "Filename of executable '%s'") cs.cs_name) (OASISUtils.varname_of_string cs.cs_name) (fun () -> let fn_opt = fold BExec cs.cs_name (fun _ fn -> Some fn) None in match fn_opt with | Some fn -> fn | None -> raise (PropList.Not_set (cs.cs_name, Some (Printf.sprintf (f_ "Executable '%s' not yet built.") cs.cs_name))))) | Library _ | Flag _ | Test _ | SrcRepo _ | Doc _ -> ()) pkg.sections end module BaseTest = struct # 21 "/home/dim/sources/oasis/src/base/BaseTest.ml" open BaseEnv open BaseMessage open OASISTypes open OASISExpr open OASISGettext let test lst pkg extra_args = let one_test (failure, n) (test_plugin, cs, test) = if var_choose ~name:(Printf.sprintf (f_ "test %s run") cs.cs_name) ~printer:string_of_bool test.test_run then begin let () = info (f_ "Running test '%s'") cs.cs_name in let back_cwd = match test.test_working_directory with | Some dir -> let cwd = Sys.getcwd () in let chdir d = info (f_ "Changing directory to '%s'") d; Sys.chdir d in chdir dir; fun () -> chdir cwd | None -> fun () -> () in try let failure_percent = BaseCustom.hook test.test_custom (test_plugin pkg (cs, test)) extra_args in back_cwd (); (failure_percent +. failure, n + 1) with e -> begin back_cwd (); raise e end end else begin info (f_ "Skipping test '%s'") cs.cs_name; (failure, n) end in let (failed, n) = List.fold_left one_test (0.0, 0) lst in let failure_percent = if n = 0 then 0.0 else failed /. (float_of_int n) in let msg = Printf.sprintf (f_ "Tests had a %.2f%% failure rate") (100. *. failure_percent) in if failure_percent > 0.0 then failwith msg else info "%s" msg; (* Possible explanation why the tests where not run. *) if OASISVersion.version_0_3_or_after pkg.oasis_version && not (bool_of_string (BaseStandardVar.tests ())) && lst <> [] then BaseMessage.warning "Tests are turned off, consider enabling with \ 'ocaml setup.ml -configure --enable-tests'" end module BaseDoc = struct # 21 "/home/dim/sources/oasis/src/base/BaseDoc.ml" open BaseEnv open BaseMessage open OASISTypes open OASISGettext let doc lst pkg extra_args = let one_doc (doc_plugin, cs, doc) = if var_choose ~name:(Printf.sprintf (f_ "documentation %s build") cs.cs_name) ~printer:string_of_bool doc.doc_build then begin info (f_ "Building documentation '%s'") cs.cs_name; BaseCustom.hook doc.doc_custom (doc_plugin pkg (cs, doc)) extra_args end in List.iter one_doc lst; if OASISVersion.version_0_3_or_after pkg.oasis_version && not (bool_of_string (BaseStandardVar.docs ())) && lst <> [] then BaseMessage.warning "Docs are turned off, consider enabling with \ 'ocaml setup.ml -configure --enable-docs'" end module BaseSetup = struct # 21 "/home/dim/sources/oasis/src/base/BaseSetup.ml" open BaseEnv open BaseMessage open OASISTypes open OASISSection open OASISGettext open OASISUtils type std_args_fun = package -> string array -> unit type ('a, 'b) section_args_fun = name * (package -> (common_section * 'a) -> string array -> 'b) type t = { configure: std_args_fun; build: std_args_fun; doc: ((doc, unit) section_args_fun) list; test: ((test, float) section_args_fun) list; install: std_args_fun; uninstall: std_args_fun; clean: std_args_fun list; clean_doc: (doc, unit) section_args_fun list; clean_test: (test, unit) section_args_fun list; distclean: std_args_fun list; distclean_doc: (doc, unit) section_args_fun list; distclean_test: (test, unit) section_args_fun list; package: package; oasis_fn: string option; oasis_version: string; oasis_digest: Digest.t option; oasis_exec: string option; oasis_setup_args: string list; setup_update: bool; } (* Associate a plugin function with data from package *) let join_plugin_sections filter_map lst = List.rev (List.fold_left (fun acc sct -> match filter_map sct with | Some e -> e :: acc | None -> acc) [] lst) (* Search for plugin data associated with a section name *) let lookup_plugin_section plugin action nm lst = try List.assoc nm lst with Not_found -> failwithf (f_ "Cannot find plugin %s matching section %s for %s action") plugin nm action let configure t args = (* Run configure *) BaseCustom.hook t.package.conf_custom (fun () -> (* Reload if preconf has changed it *) begin try unload (); load (); with _ -> () end; (* Run plugin's configure *) t.configure t.package args; (* Dump to allow postconf to change it *) dump ()) (); (* Reload environment *) unload (); load (); (* Save environment *) print (); (* Replace data in file *) BaseFileAB.replace t.package.files_ab let build t args = BaseCustom.hook t.package.build_custom (t.build t.package) args let doc t args = BaseDoc.doc (join_plugin_sections (function | Doc (cs, e) -> Some (lookup_plugin_section "documentation" (s_ "build") cs.cs_name t.doc, cs, e) | _ -> None) t.package.sections) t.package args let test t args = BaseTest.test (join_plugin_sections (function | Test (cs, e) -> Some (lookup_plugin_section "test" (s_ "run") cs.cs_name t.test, cs, e) | _ -> None) t.package.sections) t.package args let all t args = let rno_doc = ref false in let rno_test = ref false in Arg.parse_argv ~current:(ref 0) (Array.of_list ((Sys.executable_name^" all") :: (Array.to_list args))) [ "-no-doc", Arg.Set rno_doc, s_ "Don't run doc target"; "-no-test", Arg.Set rno_test, s_ "Don't run test target"; ] (failwithf (f_ "Don't know what to do with '%s'")) ""; info "Running configure step"; configure t [||]; info "Running build step"; build t [||]; (* Load setup.log dynamic variables *) BaseDynVar.init t.package; if not !rno_doc then begin info "Running doc step"; doc t [||]; end else begin info "Skipping doc step" end; if not !rno_test then begin info "Running test step"; test t [||] end else begin info "Skipping test step" end let install t args = BaseCustom.hook t.package.install_custom (t.install t.package) args let uninstall t args = BaseCustom.hook t.package.uninstall_custom (t.uninstall t.package) args let reinstall t args = uninstall t args; install t args let clean, distclean = let failsafe f a = try f a with e -> warning (f_ "Action fail with error: %s") (match e with | Failure msg -> msg | e -> Printexc.to_string e) in let generic_clean t cstm mains docs tests args = BaseCustom.hook ~failsafe:true cstm (fun () -> (* Clean section *) List.iter (function | Test (cs, test) -> let f = try List.assoc cs.cs_name tests with Not_found -> fun _ _ _ -> () in failsafe (f t.package (cs, test)) args | Doc (cs, doc) -> let f = try List.assoc cs.cs_name docs with Not_found -> fun _ _ _ -> () in failsafe (f t.package (cs, doc)) args | Library _ | Executable _ | Flag _ | SrcRepo _ -> ()) t.package.sections; (* Clean whole package *) List.iter (fun f -> failsafe (f t.package) args) mains) () in let clean t args = generic_clean t t.package.clean_custom t.clean t.clean_doc t.clean_test args in let distclean t args = (* Call clean *) clean t args; (* Call distclean code *) generic_clean t t.package.distclean_custom t.distclean t.distclean_doc t.distclean_test args; (* Remove generated file *) List.iter (fun fn -> if Sys.file_exists fn then begin info (f_ "Remove '%s'") fn; Sys.remove fn end) (BaseEnv.default_filename :: BaseLog.default_filename :: (List.rev_map BaseFileAB.to_filename t.package.files_ab)) in clean, distclean let version t _ = print_endline t.oasis_version let update_setup_ml, no_update_setup_ml_cli = let b = ref true in b, ("-no-update-setup-ml", Arg.Clear b, s_ " Don't try to update setup.ml, even if _oasis has changed.") let update_setup_ml t = let oasis_fn = match t.oasis_fn with | Some fn -> fn | None -> "_oasis" in let oasis_exec = match t.oasis_exec with | Some fn -> fn | None -> "oasis" in let ocaml = Sys.executable_name in let setup_ml, args = match Array.to_list Sys.argv with | setup_ml :: args -> setup_ml, args | [] -> failwith (s_ "Expecting non-empty command line arguments.") in let ocaml, setup_ml = if Sys.executable_name = Sys.argv.(0) then (* We are not running in standard mode, probably the script * is precompiled. *) "ocaml", "setup.ml" else ocaml, setup_ml in let no_update_setup_ml_cli, _, _ = no_update_setup_ml_cli in let do_update () = let oasis_exec_version = OASISExec.run_read_one_line ~ctxt:!BaseContext.default ~f_exit_code: (function | 0 -> () | 1 -> failwithf (f_ "Executable '%s' is probably an old version \ of oasis (< 0.3.0), please update to version \ v%s.") oasis_exec t.oasis_version | 127 -> failwithf (f_ "Cannot find executable '%s', please install \ oasis v%s.") oasis_exec t.oasis_version | n -> failwithf (f_ "Command '%s version' exited with code %d.") oasis_exec n) oasis_exec ["version"] in if OASISVersion.comparator_apply (OASISVersion.version_of_string oasis_exec_version) (OASISVersion.VGreaterEqual (OASISVersion.version_of_string t.oasis_version)) then begin (* We have a version >= for the executable oasis, proceed with * update. *) (* TODO: delegate this check to 'oasis setup'. *) if Sys.os_type = "Win32" then failwithf (f_ "It is not possible to update the running script \ setup.ml on Windows. Please update setup.ml by \ running '%s'.") (String.concat " " (oasis_exec :: "setup" :: t.oasis_setup_args)) else begin OASISExec.run ~ctxt:!BaseContext.default ~f_exit_code: (function | 0 -> () | n -> failwithf (f_ "Unable to update setup.ml using '%s', \ please fix the problem and retry.") oasis_exec) oasis_exec ("setup" :: t.oasis_setup_args); OASISExec.run ~ctxt:!BaseContext.default ocaml (setup_ml :: args) end end else failwithf (f_ "The version of '%s' (v%s) doesn't match the version of \ oasis used to generate the %s file. Please install at \ least oasis v%s.") oasis_exec oasis_exec_version setup_ml t.oasis_version in if !update_setup_ml then begin try match t.oasis_digest with | Some dgst -> if Sys.file_exists oasis_fn && dgst <> Digest.file "_oasis" then begin do_update (); true end else false | None -> false with e -> error (f_ "Error when updating setup.ml. If you want to avoid this error, \ you can bypass the update of %s by running '%s %s %s %s'") setup_ml ocaml setup_ml no_update_setup_ml_cli (String.concat " " args); raise e end else false let setup t = let catch_exn = ref true in try let act_ref = ref (fun _ -> failwithf (f_ "No action defined, run '%s %s -help'") Sys.executable_name Sys.argv.(0)) in let extra_args_ref = ref [] in let allow_empty_env_ref = ref false in let arg_handle ?(allow_empty_env=false) act = Arg.Tuple [ Arg.Rest (fun str -> extra_args_ref := str :: !extra_args_ref); Arg.Unit (fun () -> allow_empty_env_ref := allow_empty_env; act_ref := act); ] in Arg.parse (Arg.align ([ "-configure", arg_handle ~allow_empty_env:true configure, s_ "[options*] Configure the whole build process."; "-build", arg_handle build, s_ "[options*] Build executables and libraries."; "-doc", arg_handle doc, s_ "[options*] Build documents."; "-test", arg_handle test, s_ "[options*] Run tests."; "-all", arg_handle ~allow_empty_env:true all, s_ "[options*] Run configure, build, doc and test targets."; "-install", arg_handle install, s_ "[options*] Install libraries, data, executables \ and documents."; "-uninstall", arg_handle uninstall, s_ "[options*] Uninstall libraries, data, executables \ and documents."; "-reinstall", arg_handle reinstall, s_ "[options*] Uninstall and install libraries, data, \ executables and documents."; "-clean", arg_handle ~allow_empty_env:true clean, s_ "[options*] Clean files generated by a build."; "-distclean", arg_handle ~allow_empty_env:true distclean, s_ "[options*] Clean files generated by a build and configure."; "-version", arg_handle ~allow_empty_env:true version, s_ " Display version of OASIS used to generate this setup.ml."; "-no-catch-exn", Arg.Clear catch_exn, s_ " Don't catch exception, useful for debugging."; ] @ (if t.setup_update then [no_update_setup_ml_cli] else []) @ (BaseContext.args ()))) (failwithf (f_ "Don't know what to do with '%s'")) (s_ "Setup and run build process current package\n"); (* Build initial environment *) load ~allow_empty:!allow_empty_env_ref (); (** Initialize flags *) List.iter (function | Flag (cs, {flag_description = hlp; flag_default = choices}) -> begin let apply ?short_desc () = var_ignore (var_define ~cli:CLIEnable ?short_desc (OASISUtils.varname_of_string cs.cs_name) (fun () -> string_of_bool (var_choose ~name:(Printf.sprintf (f_ "default value of flag %s") cs.cs_name) ~printer:string_of_bool choices))) in match hlp with | Some hlp -> apply ~short_desc:(fun () -> hlp) () | None -> apply () end | _ -> ()) t.package.sections; BaseStandardVar.init t.package; BaseDynVar.init t.package; if t.setup_update && update_setup_ml t then () else !act_ref t (Array.of_list (List.rev !extra_args_ref)) with e when !catch_exn -> error "%s" (Printexc.to_string e); exit 1 end # 4480 "setup.ml" module InternalConfigurePlugin = struct # 21 "/home/dim/sources/oasis/src/plugins/internal/InternalConfigurePlugin.ml" (** Configure using internal scheme @author Sylvain Le Gall *) open BaseEnv open OASISTypes open OASISUtils open OASISGettext open BaseMessage (** Configure build using provided series of check to be done * and then output corresponding file. *) let configure pkg argv = let var_ignore_eval var = let _s : string = var () in () in let errors = ref SetString.empty in let buff = Buffer.create 13 in let add_errors fmt = Printf.kbprintf (fun b -> errors := SetString.add (Buffer.contents b) !errors; Buffer.clear b) buff fmt in let warn_exception e = warning "%s" (Printexc.to_string e) in (* Check tools *) let check_tools lst = List.iter (function | ExternalTool tool -> begin try var_ignore_eval (BaseCheck.prog tool) with e -> warn_exception e; add_errors (f_ "Cannot find external tool '%s'") tool end | InternalExecutable nm1 -> (* Check that matching tool is built *) List.iter (function | Executable ({cs_name = nm2}, {bs_build = build}, _) when nm1 = nm2 -> if not (var_choose build) then add_errors (f_ "Cannot find buildable internal executable \ '%s' when checking build depends") nm1 | _ -> ()) pkg.sections) lst in let build_checks sct bs = if var_choose bs.bs_build then begin if bs.bs_compiled_object = Native then begin try var_ignore_eval BaseStandardVar.ocamlopt with e -> warn_exception e; add_errors (f_ "Section %s requires native compilation") (OASISSection.string_of_section sct) end; (* Check tools *) check_tools bs.bs_build_tools; (* Check depends *) List.iter (function | FindlibPackage (findlib_pkg, version_comparator) -> begin try var_ignore_eval (BaseCheck.package ?version_comparator findlib_pkg) with e -> warn_exception e; match version_comparator with | None -> add_errors (f_ "Cannot find findlib package %s") findlib_pkg | Some ver_cmp -> add_errors (f_ "Cannot find findlib package %s (%s)") findlib_pkg (OASISVersion.string_of_comparator ver_cmp) end | InternalLibrary nm1 -> (* Check that matching library is built *) List.iter (function | Library ({cs_name = nm2}, {bs_build = build}, _) when nm1 = nm2 -> if not (var_choose build) then add_errors (f_ "Cannot find buildable internal library \ '%s' when checking build depends") nm1 | _ -> ()) pkg.sections) bs.bs_build_depends end in (* Parse command line *) BaseArgExt.parse argv (BaseEnv.args ()); (* OCaml version *) begin match pkg.ocaml_version with | Some ver_cmp -> begin try var_ignore_eval (BaseCheck.version "ocaml" ver_cmp BaseStandardVar.ocaml_version) with e -> warn_exception e; add_errors (f_ "OCaml version %s doesn't match version constraint %s") (BaseStandardVar.ocaml_version ()) (OASISVersion.string_of_comparator ver_cmp) end | None -> () end; (* Findlib version *) begin match pkg.findlib_version with | Some ver_cmp -> begin try var_ignore_eval (BaseCheck.version "findlib" ver_cmp BaseStandardVar.findlib_version) with e -> warn_exception e; add_errors (f_ "Findlib version %s doesn't match version constraint %s") (BaseStandardVar.findlib_version ()) (OASISVersion.string_of_comparator ver_cmp) end | None -> () end; (* FlexDLL *) if BaseStandardVar.os_type () = "Win32" || BaseStandardVar.os_type () = "Cygwin" then begin try var_ignore_eval BaseStandardVar.flexlink with e -> warn_exception e; add_errors (f_ "Cannot find 'flexlink'") end; (* Check build depends *) List.iter (function | Executable (_, bs, _) | Library (_, bs, _) as sct -> build_checks sct bs | Doc (_, doc) -> if var_choose doc.doc_build then check_tools doc.doc_build_tools | Test (_, test) -> if var_choose test.test_run then check_tools test.test_tools | _ -> ()) pkg.sections; (* Check if we need native dynlink (presence of libraries that compile to * native) *) begin let has_cmxa = List.exists (function | Library (_, bs, _) -> var_choose bs.bs_build && (bs.bs_compiled_object = Native || (bs.bs_compiled_object = Best && bool_of_string (BaseStandardVar.is_native ()))) | _ -> false) pkg.sections in if has_cmxa then var_ignore_eval BaseStandardVar.native_dynlink end; (* Check errors *) if SetString.empty != !errors then begin List.iter (fun e -> error "%s" e) (SetString.elements !errors); failwithf (fn_ "%d configuration error" "%d configuration errors" (SetString.cardinal !errors)) (SetString.cardinal !errors) end end module InternalInstallPlugin = struct # 21 "/home/dim/sources/oasis/src/plugins/internal/InternalInstallPlugin.ml" (** Install using internal scheme @author Sylvain Le Gall *) open BaseEnv open BaseStandardVar open BaseMessage open OASISTypes open OASISLibrary open OASISGettext open OASISUtils let exec_hook = ref (fun (cs, bs, exec) -> cs, bs, exec) let lib_hook = ref (fun (cs, bs, lib) -> cs, bs, lib, []) let doc_hook = ref (fun (cs, doc) -> cs, doc) let install_file_ev = "install-file" let install_dir_ev = "install-dir" let install_findlib_ev = "install-findlib" let win32_max_command_line_length = 8000 let split_install_command ocamlfind findlib_name meta files = if Sys.os_type = "Win32" then (* Arguments for the first command: *) let first_args = ["install"; findlib_name; meta] in (* Arguments for remaining commands: *) let other_args = ["install"; findlib_name; "-add"] in (* Extract as much files as possible from [files], [len] is the current command line length: *) let rec get_files len acc files = match files with | [] -> (List.rev acc, []) | file :: rest -> let len = len + 1 + String.length file in if len > win32_max_command_line_length then (List.rev acc, files) else get_files len (file :: acc) rest in (* Split the command into several commands. *) let rec split args files = match files with | [] -> [] | _ -> (* Length of "ocamlfind install [META|-add]" *) let len = List.fold_left (fun len arg -> len + 1 (* for the space *) + String.length arg) (String.length ocamlfind) args in match get_files len [] files with | ([], _) -> failwith (s_ "Command line too long.") | (firsts, others) -> let cmd = args @ firsts in (* Use -add for remaining commands: *) let () = let findlib_ge_132 = OASISVersion.comparator_apply (OASISVersion.version_of_string (BaseStandardVar.findlib_version ())) (OASISVersion.VGreaterEqual (OASISVersion.version_of_string "1.3.2")) in if not findlib_ge_132 then failwithf (f_ "Installing the library %s require to use the flag \ '-add' of ocamlfind because the command line is too \ long. This flag is only available for findlib 1.3.2. \ Please upgrade findlib from %s to 1.3.2") findlib_name (BaseStandardVar.findlib_version ()) in let cmds = split other_args others in cmd :: cmds in (* The first command does not use -add: *) split first_args files else ["install" :: findlib_name :: meta :: files] let install pkg argv = let in_destdir = try let destdir = destdir () in (* Practically speaking destdir is prepended * at the beginning of the target filename *) fun fn -> destdir^fn with PropList.Not_set _ -> fun fn -> fn in let install_file ?tgt_fn src_file envdir = let tgt_dir = in_destdir (envdir ()) in let tgt_file = Filename.concat tgt_dir (match tgt_fn with | Some fn -> fn | None -> Filename.basename src_file) in (* Create target directory if needed *) OASISFileUtil.mkdir_parent ~ctxt:!BaseContext.default (fun dn -> info (f_ "Creating directory '%s'") dn; BaseLog.register install_dir_ev dn) tgt_dir; (* Really install files *) info (f_ "Copying file '%s' to '%s'") src_file tgt_file; OASISFileUtil.cp ~ctxt:!BaseContext.default src_file tgt_file; BaseLog.register install_file_ev tgt_file in (* Install data into defined directory *) let install_data srcdir lst tgtdir = let tgtdir = OASISHostPath.of_unix (var_expand tgtdir) in List.iter (fun (src, tgt_opt) -> let real_srcs = OASISFileUtil.glob ~ctxt:!BaseContext.default (Filename.concat srcdir src) in if real_srcs = [] then failwithf (f_ "Wildcard '%s' doesn't match any files") src; List.iter (fun fn -> install_file fn (fun () -> match tgt_opt with | Some s -> OASISHostPath.of_unix (var_expand s) | None -> tgtdir)) real_srcs) lst in (** Install all libraries *) let install_libs pkg = let files_of_library (f_data, acc) data_lib = let cs, bs, lib, lib_extra = !lib_hook data_lib in if var_choose bs.bs_install && BaseBuilt.is_built BaseBuilt.BLib cs.cs_name then begin let acc = (* Start with acc + lib_extra *) List.rev_append lib_extra acc in let acc = (* Add uncompiled header from the source tree *) let path = OASISHostPath.of_unix bs.bs_path in List.fold_left (fun acc modul -> try List.find OASISFileUtil.file_exists_case (List.map (Filename.concat path) [modul^".mli"; modul^".ml"; String.uncapitalize modul^".mli"; String.capitalize modul^".mli"; String.uncapitalize modul^".ml"; String.capitalize modul^".ml"]) :: acc with Not_found -> begin warning (f_ "Cannot find source header for module %s \ in library %s") modul cs.cs_name; acc end) acc lib.lib_modules in let acc = (* Get generated files *) BaseBuilt.fold BaseBuilt.BLib cs.cs_name (fun acc fn -> fn :: acc) acc in let f_data () = (* Install data associated with the library *) install_data bs.bs_path bs.bs_data_files (Filename.concat (datarootdir ()) pkg.name); f_data () in (f_data, acc) end else begin (f_data, acc) end in (* Install one group of library *) let install_group_lib grp = (* Iterate through all group nodes *) let rec install_group_lib_aux data_and_files grp = let data_and_files, children = match grp with | Container (_, children) -> data_and_files, children | Package (_, cs, bs, lib, children) -> files_of_library data_and_files (cs, bs, lib), children in List.fold_left install_group_lib_aux data_and_files children in (* Findlib name of the root library *) let findlib_name = findlib_of_group grp in (* Determine root library *) let root_lib = root_of_group grp in (* All files to install for this library *) let f_data, files = install_group_lib_aux (ignore, []) grp in (* Really install, if there is something to install *) if files = [] then begin warning (f_ "Nothing to install for findlib library '%s'") findlib_name end else begin let meta = (* Search META file *) let (_, bs, _) = root_lib in let res = Filename.concat bs.bs_path "META" in if not (OASISFileUtil.file_exists_case res) then failwithf (f_ "Cannot find file '%s' for findlib library %s") res findlib_name; res in let files = (* Make filename shorter to avoid hitting command max line length * too early, esp. on Windows. *) let remove_prefix p n = let plen = String.length p in let nlen = String.length n in if plen <= nlen && String.sub n 0 plen = p then begin let fn_sep = if Sys.os_type = "Win32" then '\\' else '/' in let cutpoint = plen + (if plen < nlen && n.[plen] = fn_sep then 1 else 0) in String.sub n cutpoint (nlen - cutpoint) end else n in List.map (remove_prefix (Sys.getcwd ())) files in info (f_ "Installing findlib library '%s'") findlib_name; let ocamlfind = ocamlfind () in let commands = split_install_command ocamlfind findlib_name meta files in List.iter (OASISExec.run ~ctxt:!BaseContext.default ocamlfind) commands; BaseLog.register install_findlib_ev findlib_name end; (* Install data files *) f_data (); in let group_libs, _, _ = findlib_mapping pkg in (* We install libraries in groups *) List.iter install_group_lib group_libs in let install_execs pkg = let install_exec data_exec = let (cs, bs, exec) = !exec_hook data_exec in if var_choose bs.bs_install && BaseBuilt.is_built BaseBuilt.BExec cs.cs_name then begin let exec_libdir () = Filename.concat (libdir ()) pkg.name in BaseBuilt.fold BaseBuilt.BExec cs.cs_name (fun () fn -> install_file ~tgt_fn:(cs.cs_name ^ ext_program ()) fn bindir) (); BaseBuilt.fold BaseBuilt.BExecLib cs.cs_name (fun () fn -> install_file fn exec_libdir) (); install_data bs.bs_path bs.bs_data_files (Filename.concat (datarootdir ()) pkg.name) end in List.iter (function | Executable (cs, bs, exec)-> install_exec (cs, bs, exec) | _ -> ()) pkg.sections in let install_docs pkg = let install_doc data = let (cs, doc) = !doc_hook data in if var_choose doc.doc_install && BaseBuilt.is_built BaseBuilt.BDoc cs.cs_name then begin let tgt_dir = OASISHostPath.of_unix (var_expand doc.doc_install_dir) in BaseBuilt.fold BaseBuilt.BDoc cs.cs_name (fun () fn -> install_file fn (fun () -> tgt_dir)) (); install_data Filename.current_dir_name doc.doc_data_files doc.doc_install_dir end in List.iter (function | Doc (cs, doc) -> install_doc (cs, doc) | _ -> ()) pkg.sections in install_libs pkg; install_execs pkg; install_docs pkg (* Uninstall already installed data *) let uninstall _ argv = List.iter (fun (ev, data) -> if ev = install_file_ev then begin if OASISFileUtil.file_exists_case data then begin info (f_ "Removing file '%s'") data; Sys.remove data end else begin warning (f_ "File '%s' doesn't exist anymore") data end end else if ev = install_dir_ev then begin if Sys.file_exists data && Sys.is_directory data then begin if Sys.readdir data = [||] then begin info (f_ "Removing directory '%s'") data; OASISFileUtil.rmdir ~ctxt:!BaseContext.default data end else begin warning (f_ "Directory '%s' is not empty (%s)") data (String.concat ", " (Array.to_list (Sys.readdir data))) end end else begin warning (f_ "Directory '%s' doesn't exist anymore") data end end else if ev = install_findlib_ev then begin info (f_ "Removing findlib library '%s'") data; OASISExec.run ~ctxt:!BaseContext.default (ocamlfind ()) ["remove"; data] end else failwithf (f_ "Unknown log event '%s'") ev; BaseLog.unregister ev data) (* We process event in reverse order *) (List.rev (BaseLog.filter [install_file_ev; install_dir_ev; install_findlib_ev;])) end # 5233 "setup.ml" module OCamlbuildCommon = struct # 21 "/home/dim/sources/oasis/src/plugins/ocamlbuild/OCamlbuildCommon.ml" (** Functions common to OCamlbuild build and doc plugin *) open OASISGettext open BaseEnv open BaseStandardVar let ocamlbuild_clean_ev = "ocamlbuild-clean" let ocamlbuildflags = var_define ~short_desc:(fun () -> "OCamlbuild additional flags") "ocamlbuildflags" (fun () -> "") (** Fix special arguments depending on environment *) let fix_args args extra_argv = List.flatten [ if (os_type ()) = "Win32" then [ "-classic-display"; "-no-log"; "-no-links"; "-install-lib-dir"; (Filename.concat (standard_library ()) "ocamlbuild") ] else []; if not (bool_of_string (is_native ())) || (os_type ()) = "Win32" then [ "-byte-plugin" ] else []; args; if bool_of_string (debug ()) then ["-tag"; "debug"] else []; if bool_of_string (profile ()) then ["-tag"; "profile"] else []; OASISString.nsplit (ocamlbuildflags ()) ' '; Array.to_list extra_argv; ] (** Run 'ocamlbuild -clean' if not already done *) let run_clean extra_argv = let extra_cli = String.concat " " (Array.to_list extra_argv) in (* Run if never called with these args *) if not (BaseLog.exists ocamlbuild_clean_ev extra_cli) then begin OASISExec.run ~ctxt:!BaseContext.default (ocamlbuild ()) (fix_args ["-clean"] extra_argv); BaseLog.register ocamlbuild_clean_ev extra_cli; at_exit (fun () -> try BaseLog.unregister ocamlbuild_clean_ev extra_cli with _ -> ()) end (** Run ocamlbuild, unregister all clean events *) let run_ocamlbuild args extra_argv = (* TODO: enforce that target in args must be UNIX encoded i.e. toto/index.html *) OASISExec.run ~ctxt:!BaseContext.default (ocamlbuild ()) (fix_args args extra_argv); (* Remove any clean event, we must run it again *) List.iter (fun (e, d) -> BaseLog.unregister e d) (BaseLog.filter [ocamlbuild_clean_ev]) (** Determine real build directory *) let build_dir extra_argv = let rec search_args dir = function | "-build-dir" :: dir :: tl -> search_args dir tl | _ :: tl -> search_args dir tl | [] -> dir in search_args "_build" (fix_args [] extra_argv) end module OCamlbuildPlugin = struct # 21 "/home/dim/sources/oasis/src/plugins/ocamlbuild/OCamlbuildPlugin.ml" (** Build using ocamlbuild @author Sylvain Le Gall *) open OASISTypes open OASISGettext open OASISUtils open BaseEnv open OCamlbuildCommon open BaseStandardVar open BaseMessage let cond_targets_hook = ref (fun lst -> lst) let build pkg argv = (* Return the filename in build directory *) let in_build_dir fn = Filename.concat (build_dir argv) fn in (* Return the unix filename in host build directory *) let in_build_dir_of_unix fn = in_build_dir (OASISHostPath.of_unix fn) in let cond_targets = List.fold_left (fun acc -> function | Library (cs, bs, lib) when var_choose bs.bs_build -> begin let evs, unix_files = BaseBuilt.of_library in_build_dir_of_unix (cs, bs, lib) in let ends_with nd fn = let nd_len = String.length nd in (String.length fn >= nd_len) && (String.sub fn (String.length fn - nd_len) nd_len) = nd in let tgts = List.flatten (List.filter (fun l -> l <> []) (List.map (List.filter (fun fn -> ends_with ".cma" fn || ends_with ".cmxs" fn || ends_with ".cmxa" fn || ends_with (ext_lib ()) fn || ends_with (ext_dll ()) fn)) unix_files)) in match tgts with | _ :: _ -> (evs, tgts) :: acc | [] -> failwithf (f_ "No possible ocamlbuild targets for library %s") cs.cs_name end | Executable (cs, bs, exec) when var_choose bs.bs_build -> begin let evs, unix_exec_is, unix_dll_opt = BaseBuilt.of_executable in_build_dir_of_unix (cs, bs, exec) in let target ext = let unix_tgt = (OASISUnixPath.concat bs.bs_path (OASISUnixPath.chop_extension exec.exec_main_is))^ext in let evs = (* Fix evs, we want to use the unix_tgt, without copying *) List.map (function | BaseBuilt.BExec, nm, lst when nm = cs.cs_name -> BaseBuilt.BExec, nm, [[in_build_dir_of_unix unix_tgt]] | ev -> ev) evs in evs, [unix_tgt] in (* Add executable *) let acc = match bs.bs_compiled_object with | Native -> (target ".native") :: acc | Best when bool_of_string (is_native ()) -> (target ".native") :: acc | Byte | Best -> (target ".byte") :: acc in acc end | Library _ | Executable _ | Test _ | SrcRepo _ | Flag _ | Doc _ -> acc) [] (* Keep the pkg.sections ordered *) (List.rev pkg.sections); in (* Check and register built files *) let check_and_register (bt, bnm, lst) = List.iter (fun fns -> if not (List.exists OASISFileUtil.file_exists_case fns) then failwithf (f_ "No one of expected built files %s exists") (String.concat (s_ ", ") (List.map (Printf.sprintf "'%s'") fns))) lst; (BaseBuilt.register bt bnm lst) in let cond_targets = (* Run the hook *) !cond_targets_hook cond_targets in (* Run a list of target... *) run_ocamlbuild (List.flatten (List.map snd cond_targets)) argv; (* ... and register events *) List.iter check_and_register (List.flatten (List.map fst cond_targets)) let clean pkg extra_args = run_clean extra_args; List.iter (function | Library (cs, _, _) -> BaseBuilt.unregister BaseBuilt.BLib cs.cs_name | Executable (cs, _, _) -> BaseBuilt.unregister BaseBuilt.BExec cs.cs_name; BaseBuilt.unregister BaseBuilt.BExecLib cs.cs_name | _ -> ()) pkg.sections end module OCamlbuildDocPlugin = struct # 21 "/home/dim/sources/oasis/src/plugins/ocamlbuild/OCamlbuildDocPlugin.ml" (* Create documentation using ocamlbuild .odocl files @author Sylvain Le Gall *) open OASISTypes open OASISGettext open OASISMessage open OCamlbuildCommon open BaseStandardVar let doc_build path pkg (cs, doc) argv = let index_html = OASISUnixPath.make [ path; cs.cs_name^".docdir"; "index.html"; ] in let tgt_dir = OASISHostPath.make [ build_dir argv; OASISHostPath.of_unix path; cs.cs_name^".docdir"; ] in run_ocamlbuild [index_html] argv; List.iter (fun glb -> BaseBuilt.register BaseBuilt.BDoc cs.cs_name [OASISFileUtil.glob ~ctxt:!BaseContext.default (Filename.concat tgt_dir glb)]) ["*.html"; "*.css"] let doc_clean t pkg (cs, doc) argv = run_clean argv; BaseBuilt.unregister BaseBuilt.BDoc cs.cs_name end # 5558 "setup.ml" open OASISTypes;; let setup_t = { BaseSetup.configure = InternalConfigurePlugin.configure; build = OCamlbuildPlugin.build; test = []; doc = [("ocaml-usb-api", OCamlbuildDocPlugin.doc_build "./")]; install = InternalInstallPlugin.install; uninstall = InternalInstallPlugin.uninstall; clean = [OCamlbuildPlugin.clean]; clean_test = []; clean_doc = [("ocaml-usb-api", OCamlbuildDocPlugin.doc_clean "./")]; distclean = []; distclean_test = []; distclean_doc = []; package = { oasis_version = "0.3"; ocaml_version = None; findlib_version = None; name = "ocaml-usb"; version = "1.3.0"; license = OASISLicense.DEP5License (OASISLicense.DEP5Unit { OASISLicense.license = "BSD3"; excption = None; version = OASISLicense.NoVersion; }); license_file = Some "COPYING"; copyrights = []; maintainers = []; authors = ["J\195\169r\195\169mie Dimino"]; homepage = Some "http://ocaml-usb.forge.ocamlcore.org/"; synopsis = "Bindings for libusb-1.0"; description = None; categories = []; conf_type = (`Configure, "internal", Some "0.3"); conf_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; build_type = (`Build, "ocamlbuild", Some "0.3"); build_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; install_type = (`Install, "internal", Some "0.3"); install_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; uninstall_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; clean_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; distclean_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; files_ab = []; sections = [ Library ({ cs_name = "usb"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { bs_build = [(OASISExpr.EBool true, true)]; bs_install = [(OASISExpr.EBool true, true)]; bs_path = "src"; bs_compiled_object = Best; bs_build_depends = [ FindlibPackage ("lwt.unix", None); FindlibPackage ("lwt.syntax", None) ]; bs_build_tools = [ExternalTool "ocamlbuild"]; bs_c_sources = ["usb_stubs.c"]; bs_data_files = []; bs_ccopt = [(OASISExpr.EBool true, [])]; bs_cclib = [(OASISExpr.EBool true, [])]; bs_dlllib = [(OASISExpr.EBool true, [])]; bs_dllpath = [(OASISExpr.EBool true, [])]; bs_byteopt = [(OASISExpr.EBool true, [])]; bs_nativeopt = [(OASISExpr.EBool true, [])]; }, { lib_modules = ["USB"]; lib_pack = false; lib_internal_modules = []; lib_findlib_parent = None; lib_findlib_name = Some "usb"; lib_findlib_containers = []; }); Doc ({ cs_name = "ocaml-usb-api"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { doc_type = (`Doc, "ocamlbuild", Some "0.3"); doc_custom = { pre_command = [(OASISExpr.EBool true, None)]; post_command = [(OASISExpr.EBool true, None)]; }; doc_build = [ (OASISExpr.ENot (OASISExpr.EFlag "docs"), false); (OASISExpr.EFlag "docs", true) ]; doc_install = [(OASISExpr.EBool true, true)]; doc_install_dir = "$htmldir/api"; doc_title = "API reference for ocaml-usb"; doc_authors = []; doc_abstract = None; doc_format = OtherDoc; doc_data_files = []; doc_build_tools = [ExternalTool "ocamlbuild"; ExternalTool "ocamldoc"]; }); SrcRepo ({ cs_name = "head"; cs_data = PropList.Data.create (); cs_plugin_data = []; }, { src_repo_type = Darcs; src_repo_location = "http://darcs.ocamlcore.org/repos/ocaml-usb"; src_repo_browser = Some "http://darcs.ocamlcore.org/cgi-bin/darcsweb.cgi?r=ocaml-usb;a=summary"; src_repo_module = None; src_repo_branch = None; src_repo_tag = None; src_repo_subdir = None; }) ]; plugins = [(`Extra, "DevFiles", Some "0.3"); (`Extra, "META", Some "0.3")]; schema_data = PropList.Data.create (); plugin_data = []; }; oasis_fn = Some "_oasis"; oasis_version = "0.3.0"; oasis_digest = Some "\225>7\153\168\144\147\243kq>\003\2140\221\161"; oasis_exec = None; oasis_setup_args = []; setup_update = false; };; let setup () = BaseSetup.setup setup_t;; # 5731 "setup.ml" (* OASIS_STOP *) let () = setup ();; ocaml-usb-1.3.0/myocamlbuild.ml0000644000000000000000000003620012005550027014573 0ustar0000000000000000(* * myocamlbuild.ml * --------------- * Copyright : (c) 2010, Jeremie Dimino * Licence : BSD3 * * This file is a part of ocaml-usb. *) (* OASIS_START *) (* DO NOT EDIT (digest: 86b4c0dd0ab6b20486bb406684a56c7a) *) module OASISGettext = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISGettext.ml" let ns_ str = str let s_ str = str let f_ (str : ('a, 'b, 'c, 'd) format4) = str let fn_ fmt1 fmt2 n = if n = 1 then fmt1^^"" else fmt2^^"" let init = [] end module OASISExpr = struct # 21 "/home/dim/sources/oasis/src/oasis/OASISExpr.ml" open OASISGettext type test = string type flag = string type t = | EBool of bool | ENot of t | EAnd of t * t | EOr of t * t | EFlag of flag | ETest of test * string type 'a choices = (t * 'a) list let eval var_get t = let rec eval' = function | EBool b -> b | ENot e -> not (eval' e) | EAnd (e1, e2) -> (eval' e1) && (eval' e2) | EOr (e1, e2) -> (eval' e1) || (eval' e2) | EFlag nm -> let v = var_get nm in assert(v = "true" || v = "false"); (v = "true") | ETest (nm, vl) -> let v = var_get nm in (v = vl) in eval' t let choose ?printer ?name var_get lst = let rec choose_aux = function | (cond, vl) :: tl -> if eval var_get cond then vl else choose_aux tl | [] -> let str_lst = if lst = [] then s_ "" else String.concat (s_ ", ") (List.map (fun (cond, vl) -> match printer with | Some p -> p vl | None -> s_ "") lst) in match name with | Some nm -> failwith (Printf.sprintf (f_ "No result for the choice list '%s': %s") nm str_lst) | None -> failwith (Printf.sprintf (f_ "No result for a choice list: %s") str_lst) in choose_aux (List.rev lst) end # 117 "myocamlbuild.ml" module BaseEnvLight = struct # 21 "/home/dim/sources/oasis/src/base/BaseEnvLight.ml" module MapString = Map.Make(String) type t = string MapString.t let default_filename = Filename.concat (Sys.getcwd ()) "setup.data" let load ?(allow_empty=false) ?(filename=default_filename) () = if Sys.file_exists filename then begin let chn = open_in_bin filename in let st = Stream.of_channel chn in let line = ref 1 in let st_line = Stream.from (fun _ -> try match Stream.next st with | '\n' -> incr line; Some '\n' | c -> Some c with Stream.Failure -> None) in let lexer = Genlex.make_lexer ["="] st_line in let rec read_file mp = match Stream.npeek 3 lexer with | [Genlex.Ident nm; Genlex.Kwd "="; Genlex.String value] -> Stream.junk lexer; Stream.junk lexer; Stream.junk lexer; read_file (MapString.add nm value mp) | [] -> mp | _ -> failwith (Printf.sprintf "Malformed data file '%s' line %d" filename !line) in let mp = read_file MapString.empty in close_in chn; mp end else if allow_empty then begin MapString.empty end else begin failwith (Printf.sprintf "Unable to load environment, the file '%s' doesn't exist." filename) end let var_get name env = let rec var_expand str = let buff = Buffer.create ((String.length str) * 2) in Buffer.add_substitute buff (fun var -> try var_expand (MapString.find var env) with Not_found -> failwith (Printf.sprintf "No variable %s defined when trying to expand %S." var str)) str; Buffer.contents buff in var_expand (MapString.find name env) let var_choose lst env = OASISExpr.choose (fun nm -> var_get nm env) lst end # 215 "myocamlbuild.ml" module MyOCamlbuildFindlib = struct # 21 "/home/dim/sources/oasis/src/plugins/ocamlbuild/MyOCamlbuildFindlib.ml" (** OCamlbuild extension, copied from * http://brion.inria.fr/gallium/index.php/Using_ocamlfind_with_ocamlbuild * by N. Pouillard and others * * Updated on 2009/02/28 * * Modified by Sylvain Le Gall *) open Ocamlbuild_plugin (* these functions are not really officially exported *) let run_and_read = Ocamlbuild_pack.My_unix.run_and_read let blank_sep_strings = Ocamlbuild_pack.Lexers.blank_sep_strings let split s ch = let x = ref [] in let rec go s = let pos = String.index s ch in x := (String.before s pos)::!x; go (String.after s (pos + 1)) in try go s with Not_found -> !x let split_nl s = split s '\n' let before_space s = try String.before s (String.index s ' ') with Not_found -> s (* this lists all supported packages *) let find_packages () = List.map before_space (split_nl & run_and_read "ocamlfind list") (* this is supposed to list available syntaxes, but I don't know how to do it. *) let find_syntaxes () = ["camlp4o"; "camlp4r"] (* ocamlfind command *) let ocamlfind x = S[A"ocamlfind"; x] let dispatch = function | Before_options -> (* by using Before_options one let command line options have an higher priority *) (* on the contrary using After_options will guarantee to have the higher priority *) (* override default commands by ocamlfind ones *) Options.ocamlc := ocamlfind & A"ocamlc"; Options.ocamlopt := ocamlfind & A"ocamlopt"; Options.ocamldep := ocamlfind & A"ocamldep"; Options.ocamldoc := ocamlfind & A"ocamldoc"; Options.ocamlmktop := ocamlfind & A"ocamlmktop" | After_rules -> (* When one link an OCaml library/binary/package, one should use -linkpkg *) flag ["ocaml"; "link"; "program"] & A"-linkpkg"; (* For each ocamlfind package one inject the -package option when * compiling, computing dependencies, generating documentation and * linking. *) List.iter begin fun pkg -> flag ["ocaml"; "compile"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "ocamldep"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "doc"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "link"; "pkg_"^pkg] & S[A"-package"; A pkg]; flag ["ocaml"; "infer_interface"; "pkg_"^pkg] & S[A"-package"; A pkg]; end (find_packages ()); (* Like -package but for extensions syntax. Morover -syntax is useless * when linking. *) List.iter begin fun syntax -> flag ["ocaml"; "compile"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "ocamldep"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "doc"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "infer_interface"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; end (find_syntaxes ()); (* The default "thread" tag is not compatible with ocamlfind. * Indeed, the default rules add the "threads.cma" or "threads.cmxa" * options when using this tag. When using the "-linkpkg" option with * ocamlfind, this module will then be added twice on the command line. * * To solve this, one approach is to add the "-thread" option when using * the "threads" package using the previous plugin. *) flag ["ocaml"; "pkg_threads"; "compile"] (S[A "-thread"]); flag ["ocaml"; "pkg_threads"; "doc"] (S[A "-I"; A "+threads"]); flag ["ocaml"; "pkg_threads"; "link"] (S[A "-thread"]); flag ["ocaml"; "pkg_threads"; "infer_interface"] (S[A "-thread"]) | _ -> () end module MyOCamlbuildBase = struct # 21 "/home/dim/sources/oasis/src/plugins/ocamlbuild/MyOCamlbuildBase.ml" (** Base functions for writing myocamlbuild.ml @author Sylvain Le Gall *) open Ocamlbuild_plugin module OC = Ocamlbuild_pack.Ocaml_compiler type dir = string type file = string type name = string type tag = string # 56 "/home/dim/sources/oasis/src/plugins/ocamlbuild/MyOCamlbuildBase.ml" type t = { lib_ocaml: (name * dir list) list; lib_c: (name * dir * file list) list; flags: (tag list * (spec OASISExpr.choices)) list; (* Replace the 'dir: include' from _tags by a precise interdepends in * directory. *) includes: (dir * dir list) list; } let env_filename = Pathname.basename BaseEnvLight.default_filename let dispatch_combine lst = fun e -> List.iter (fun dispatch -> dispatch e) lst let tag_libstubs nm = "use_lib"^nm^"_stubs" let nm_libstubs nm = nm^"_stubs" let dispatch t e = let env = BaseEnvLight.load ~filename:env_filename ~allow_empty:true () in match e with | Before_options -> let no_trailing_dot s = if String.length s >= 1 && s.[0] = '.' then String.sub s 1 ((String.length s) - 1) else s in List.iter (fun (opt, var) -> try opt := no_trailing_dot (BaseEnvLight.var_get var env) with Not_found -> Printf.eprintf "W: Cannot get variable %s" var) [ Options.ext_obj, "ext_obj"; Options.ext_lib, "ext_lib"; Options.ext_dll, "ext_dll"; ] | After_rules -> (* Declare OCaml libraries *) List.iter (function | nm, [] -> ocaml_lib nm | nm, dir :: tl -> ocaml_lib ~dir:dir (dir^"/"^nm); List.iter (fun dir -> List.iter (fun str -> flag ["ocaml"; "use_"^nm; str] (S[A"-I"; P dir])) ["compile"; "infer_interface"; "doc"]) tl) t.lib_ocaml; (* Declare directories dependencies, replace "include" in _tags. *) List.iter (fun (dir, include_dirs) -> Pathname.define_context dir include_dirs) t.includes; (* Declare C libraries *) List.iter (fun (lib, dir, headers) -> (* Handle C part of library *) flag ["link"; "library"; "ocaml"; "byte"; tag_libstubs lib] (S[A"-dllib"; A("-l"^(nm_libstubs lib)); A"-cclib"; A("-l"^(nm_libstubs lib))]); flag ["link"; "library"; "ocaml"; "native"; tag_libstubs lib] (S[A"-cclib"; A("-l"^(nm_libstubs lib))]); flag ["link"; "program"; "ocaml"; "byte"; tag_libstubs lib] (S[A"-dllib"; A("dll"^(nm_libstubs lib))]); (* When ocaml link something that use the C library, then one need that file to be up to date. *) dep ["link"; "ocaml"; "program"; tag_libstubs lib] [dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)]; dep ["compile"; "ocaml"; "program"; tag_libstubs lib] [dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)]; (* TODO: be more specific about what depends on headers *) (* Depends on .h files *) dep ["compile"; "c"] headers; (* Setup search path for lib *) flag ["link"; "ocaml"; "use_"^lib] (S[A"-I"; P(dir)]); ) t.lib_c; (* Add flags *) List.iter (fun (tags, cond_specs) -> let spec = BaseEnvLight.var_choose cond_specs env in flag tags & spec) t.flags | _ -> () let dispatch_default t = dispatch_combine [ dispatch t; MyOCamlbuildFindlib.dispatch; ] end # 476 "myocamlbuild.ml" open Ocamlbuild_plugin;; let package_default = { MyOCamlbuildBase.lib_ocaml = [("usb", ["src"])]; lib_c = [("usb", "src", [])]; flags = []; includes = []; } ;; let dispatch_default = MyOCamlbuildBase.dispatch_default package_default;; # 490 "myocamlbuild.ml" (* OASIS_STOP *) open Ocamlbuild_plugin let pkg_config flags package = with_temp_file "lwt" "pkg-config" (fun tmp -> Command.execute ~quiet:true & Cmd(S[A "pkg-config"; A("--" ^ flags); A package; Sh ">"; A tmp]); List.map (fun arg -> A arg) (string_list_of_file tmp)) let define_c_library ~name ~c_name = let tag = Printf.sprintf "use_%s" name in (* Get flags for using pkg-config: *) let opt = pkg_config "cflags" c_name and lib = pkg_config "libs" c_name in (* Add flags for linking with the C library: *) flag ["ocamlmklib"; "c"; tag] & S lib; (* C stubs using the C library must be compiled with the library specifics flags: *) flag ["c"; "compile"; tag] & S(List.map (fun arg -> S[A"-ccopt"; arg]) opt); (* OCaml libraries must depends on the C library: *) flag ["link"; "ocaml"; tag] & S(List.map (fun arg -> S[A"-cclib"; arg]) lib) let () = dispatch (fun hook -> dispatch_default hook; match hook with | Before_options -> Options.make_links := false | After_rules -> define_c_library ~name:"libusb" ~c_name:"libusb-1.0"; flag ["c"; "compile"; "use_libusb"] & S[A"-package"; A"lwt"] | _ -> ()) ocaml-usb-1.3.0/_tags0000644000000000000000000000131212005550027012574 0ustar0000000000000000: syntax_camlp4o : use_libusb # OASIS_START # DO NOT EDIT (digest: fd818c5a3df16d6501123bb480b69ee8) # Ignore VCS directories, you can use the same kind of rule outside # OASIS_START/STOP if you want to exclude directories that contains # useless stuff for the build process <**/.svn>: -traverse <**/.svn>: not_hygienic ".bzr": -traverse ".bzr": not_hygienic ".hg": -traverse ".hg": not_hygienic ".git": -traverse ".git": not_hygienic "_darcs": -traverse "_darcs": not_hygienic # Library usb "src/usb.cmxs": use_usb : use_libusb_stubs : pkg_lwt.unix : pkg_lwt.syntax "src/usb_stubs.c": pkg_lwt.unix "src/usb_stubs.c": pkg_lwt.syntax # OASIS_STOP ocaml-usb-1.3.0/_oasis0000644000000000000000000000146312005550027012763 0ustar0000000000000000OASISFormat: 0.3 Name: ocaml-usb Version: 1.3.0 LicenseFile: COPYING License: BSD3 Authors: Jérémie Dimino Homepage: http://ocaml-usb.forge.ocamlcore.org/ BuildTools: ocamlbuild Plugins: DevFiles (0.3), META (0.3) Synopsis: Bindings for libusb-1.0 Library "usb" FindlibName: usb Path: src Modules: USB BuildDepends: lwt.unix, lwt.syntax XMETADescription: Bindings for libusb-1.0 XMETARequires: lwt.unix CSources: usb_stubs.c Document "ocaml-usb-api" Title: API reference for ocaml-usb Type: ocamlbuild (0.3) Install: true InstallDir: $htmldir/api BuildTools: ocamldoc XOCamlbuildPath: ./ XOCamlbuildLibraries: usb SourceRepository head Type: darcs Location: http://darcs.ocamlcore.org/repos/ocaml-usb Browser: http://darcs.ocamlcore.org/cgi-bin/darcsweb.cgi?r=ocaml-usb;a=summary ocaml-usb-1.3.0/README0000644000000000000000000000143012005550027012435 0ustar0000000000000000 OCaml-USB Jeremie Dimino October 2009 url: https://forge.ocamlcore.org/projects/ocaml-usb/ * What it is ? OCaml-USB is a binding to libusb-1.0. It uses Lwt to make it easy to use asynchronous IO features of libusb-1.0. * Requirement OCaml-USB needs ocaml >= 3.11, lwt >= 2.0.0 and libusb-1.0. * Building and installation To build and install it just type: $ make all $ make install This will install the "usb" package (ocamlfind is required). * Development The last development version of ocaml-usb can always be found in the darcs repository hosted at darcs.ocamlcore.org: $ darcs get http://darcs.ocamlcore.org/repos/ocaml-usb/ocaml-usb local variables: mode: outline end: ocaml-usb-1.3.0/LICENSE0000644000000000000000000000275612005550027012576 0ustar0000000000000000Copyright (c) 2009, Jeremie Dimino All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Jeremie Dimino nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ocaml-usb-1.3.0/CHANGES0000644000000000000000000000043112005550027012550 0ustar0000000000000000===== 1.3.0 ===== * fix an initialization bug * fix build of stubs of kfreebsd * add more device classes * update oasis files ===== 1.2.0 ===== * upgrade for lwt-2.3.0 ===== 1.1.0 ===== * use oasis * upgrade for lwt-2.2.0 ===== 1.0.0 ===== * Initial release ocaml-usb-1.3.0/src/0000755000000000000000000000000012005550027012346 5ustar0000000000000000ocaml-usb-1.3.0/src/usb.mllib0000644000000000000000000000013012005550027014152 0ustar0000000000000000# OASIS_START # DO NOT EDIT (digest: 7aca5ec618f7317328dcd7014cf9bdcf) USB # OASIS_STOP ocaml-usb-1.3.0/src/libusb_stubs.clib0000644000000000000000000000014012005550027015674 0ustar0000000000000000# OASIS_START # DO NOT EDIT (digest: 0783307e545c0b6731e9c59c3d747f03) usb_stubs.o # OASIS_STOP ocaml-usb-1.3.0/src/META0000644000000000000000000000047112005550027013021 0ustar0000000000000000# OASIS_START # DO NOT EDIT (digest: b2c1dd3d44032d0ec4341cceb2232662) version = "1.3.0" description = "Bindings for libusb-1.0" requires = "lwt.unix" archive(byte) = "usb.cma" archive(byte, plugin) = "usb.cma" archive(native) = "usb.cmxa" archive(native, plugin) = "usb.cmxs" exists_if = "usb.cma" # OASIS_STOP ocaml-usb-1.3.0/src/usb_stubs.c0000644000000000000000000007633412005550027014540 0ustar0000000000000000/* * usb_stubs.c * ----------- * Copyright : (c) 2009, Jeremie Dimino * Licence : BSD3 * * This file is a part of ocaml-usb. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* +-----------------------------------------------------------------+ | Errors | +-----------------------------------------------------------------+ */ static void ml_usb_error(int code, char *fun_name) { int num; value arg[2]; switch(code) { case LIBUSB_ERROR_IO: num = Val_int(0); break; case LIBUSB_ERROR_INVALID_PARAM: num = Val_int(1); break; case LIBUSB_ERROR_ACCESS: num = Val_int(2); break; case LIBUSB_ERROR_NO_DEVICE: num = Val_int(3); break; case LIBUSB_ERROR_NOT_FOUND: num = Val_int(4); break; case LIBUSB_ERROR_BUSY: num = Val_int(5); break; case LIBUSB_ERROR_TIMEOUT: num = Val_int(6); break; case LIBUSB_ERROR_OVERFLOW: num = Val_int(7); break; case LIBUSB_ERROR_PIPE: num = Val_int(8); break; case LIBUSB_ERROR_INTERRUPTED: num = Val_int(9); break; case LIBUSB_ERROR_NO_MEM: num = Val_int(10); break; case LIBUSB_ERROR_NOT_SUPPORTED: num = Val_int(11); break; case LIBUSB_ERROR_OTHER: num = Val_int(12); break; default: { char str[512]; sprintf(str, "ocaml-usb: unknown error (%d)", code); caml_failwith(str); } } arg[0] = num; arg[1] = caml_copy_string(fun_name); caml_raise_with_args(*caml_named_value("ocaml-usb:Error"), 2, arg); } static void *ml_usb_malloc(size_t size) { void *ptr = malloc(size); if (ptr == NULL) caml_failwith("ocaml-usb: out of memory"); return ptr; } static struct libusb_transfer *ml_usb_alloc_transfer(int count) { struct libusb_transfer *transfer = libusb_alloc_transfer(count); if (transfer == NULL) caml_failwith("ocaml-usb: out of memory"); return transfer; } /* +-----------------------------------------------------------------+ | Event-loop integration | +-----------------------------------------------------------------+ */ CAMLprim value ml_usb_handle_events() { struct timeval tp = { 0, 0 }; int res = libusb_handle_events_timeout(NULL, &tp); if (res) ml_usb_error(res, "handle_event_timeout"); return Val_unit; } CAMLprim value ml_usb_get_next_timeout() { struct timeval tp; if (libusb_get_next_timeout(NULL, &tp) == 1) return caml_copy_double(tp.tv_sec + (tp.tv_usec * 1e-3)); else return caml_copy_double(-1.0); } #if defined(LWT_ON_WINDOWS) # error "ocaml-usb does not work (yet) on windows" #else static void ml_usb_add_pollfd(int fd, short events, void *user_data) { caml_callback3(*caml_named_value("ocaml-usb:insert-pollfd"), Val_int(fd), Val_bool(events & POLLIN), Val_bool(events & POLLOUT)); } static void ml_usb_remove_pollfd(int fd, void *user_data) { caml_callback(*caml_named_value("ocaml-usb:remove-pollfd"), Val_int(fd)); } #endif /* +-----------------------------------------------------------------+ | Initialization | +-----------------------------------------------------------------+ */ CAMLprim value ml_usb_init() { const struct libusb_pollfd** pollfds = NULL; int i = 0; int res = libusb_init(NULL); if (res) ml_usb_error(res, "init"); pollfds = libusb_get_pollfds(NULL); if (pollfds) { for (i = 0; pollfds[i] != NULL; i++ ) { ml_usb_add_pollfd(pollfds[i]->fd, pollfds[i]->events, NULL); } free(pollfds); } libusb_set_pollfd_notifiers(NULL, ml_usb_add_pollfd, ml_usb_remove_pollfd, NULL); return Val_unit; } CAMLprim value ml_usb_exit() { libusb_exit(NULL); return Val_unit; } CAMLprim value ml_usb_set_debug(value level) { libusb_set_debug(NULL, Int_val(level)); return Val_unit; } /* +-----------------------------------------------------------------+ | Device and enumerations | +-----------------------------------------------------------------+ */ #define Endpoint_val(endpoint, direction) (Int_val(endpoint) | (Int_val(direction) == 0 ? LIBUSB_ENDPOINT_IN : LIBUSB_ENDPOINT_OUT)) #define Ptr_val(v) ((long)(*(void**)Data_custom_val(v))) static int ml_usb_compare(value v1, value v2) { return (int)(Ptr_val(v1) - Ptr_val(v2)); } static long ml_usb_hash(value v) { return Ptr_val(v); } #define Device_val(v) *(libusb_device**)Data_custom_val(v) static void ml_usb_device_finalize(value dev) { libusb_unref_device(Device_val(dev)); } static struct custom_operations device_ops = { "usb.device", ml_usb_device_finalize, ml_usb_compare, ml_usb_hash, custom_serialize_default, custom_deserialize_default }; #define Handle_val(v) *(libusb_device_handle**)Data_custom_val(v) static void ml_usb_device_handle_finalize(value vhandle) { libusb_device_handle *handle = Handle_val(vhandle); if (handle) { Handle_val(vhandle) = NULL; libusb_close(handle); } } static struct custom_operations handle_ops = { "usb.device.handle", ml_usb_device_handle_finalize, ml_usb_compare, ml_usb_hash, custom_serialize_default, custom_deserialize_default }; static value alloc_device(libusb_device *device) { value x = caml_alloc_custom(&device_ops, sizeof(libusb_device*), 0, 1); Device_val(x) = device; return x; } static value alloc_handle(libusb_device_handle *handle) { value x = caml_alloc_custom(&handle_ops, sizeof(libusb_device_handle*), 0, 1); Handle_val(x) = handle; return x; } CAMLprim value ml_usb_get_device_list(value unit) { CAMLparam1(unit); CAMLlocal2(x, y); libusb_device **devices; size_t cnt = libusb_get_device_list(NULL, &devices); if ((int)cnt < 0) ml_usb_error(cnt, "get_device_list"); /* Convert the array to a caml list */ size_t i; x = Val_int(0); for (i = 0; i < cnt; i++) { y = caml_alloc_tuple(2); Store_field(y, 0, alloc_device(devices[i])); Store_field(y, 1, x); x = y; } /* Free the list but not the devices */ libusb_free_device_list(devices, 0); CAMLreturn(x); } CAMLprim value ml_usb_get_bus_number(value dev) { return Val_int(libusb_get_bus_number(Device_val(dev))); } CAMLprim value ml_usb_get_device_address(value dev) { return Val_int(libusb_get_device_address(Device_val(dev))); } CAMLprim value ml_usb_get_max_packet_size(value dev, value direction, value endpoint) { int res = libusb_get_max_packet_size(Device_val(dev), Endpoint_val(endpoint, direction)); if (res < 0) ml_usb_error(res, "get_max_packet_size"); return Val_int(res); } CAMLprim value ml_usb_open(value dev) { CAMLparam1(dev); libusb_device_handle *handle = NULL; int res = libusb_open(Device_val(dev), &handle); if (res) ml_usb_error(res, "open"); CAMLreturn(alloc_handle(handle)); } CAMLprim value ml_usb_open_device_with_vid_pid(value vid, value pid) { CAMLparam2(vid, pid); CAMLlocal1(some); libusb_device_handle *handle = libusb_open_device_with_vid_pid(NULL, Int_val(vid), Int_val(pid)); if (handle == NULL) CAMLreturn(Val_int(0)); else { some = caml_alloc_tuple(1); Store_field(some, 0, alloc_handle(handle)); CAMLreturn(some); } } CAMLprim value ml_usb_close(value vhandle) { libusb_device_handle *handle = Handle_val(vhandle); if (handle) { Handle_val(vhandle) = NULL; libusb_close(handle); } return Val_unit; } CAMLprim value ml_usb_get_device(value handle) { CAMLparam1(handle); libusb_device *device = libusb_get_device(Handle_val(handle)); libusb_ref_device(device); CAMLreturn(alloc_device(device)); } CAMLprim value ml_usb_kernel_driver_active(value handle, value interface) { int res = libusb_kernel_driver_active(Handle_val(handle), Int_val(interface)); switch (res) { case 0: return Val_false; case 1: return Val_true; default: ml_usb_error(res, "kernel_driver_active"); return Val_false; } } CAMLprim value ml_usb_detach_kernel_driver(value handle, value interface) { int res = libusb_detach_kernel_driver(Handle_val(handle), Int_val(interface)); if (res) ml_usb_error(res, "detach_kernel_driver"); return Val_unit; } CAMLprim value ml_usb_attach_kernel_driver(value handle, value interface) { int res = libusb_attach_kernel_driver(Handle_val(handle), Int_val(interface)); if (res) ml_usb_error(res, "attach_kernel_driver"); return Val_unit; } /* +-----------------------------------------------------------------+ | JOB: claim_interface | +-----------------------------------------------------------------+ */ struct job_claim_interface { struct lwt_unix_job job; libusb_device_handle *handle; int interface; int result; }; #define Job_claim_interface(v) *(struct job_claim_interface**)Data_custom_val(v) static void worker_claim_interface(struct job_claim_interface *job) { job->result = libusb_claim_interface(job->handle, job->interface); } CAMLprim value ml_usb_claim_interface_job(value val_handle, value val_interface) { struct job_claim_interface *job = lwt_unix_new(struct job_claim_interface); job->job.worker = (lwt_unix_job_worker)worker_claim_interface; job->handle = Handle_val(val_handle); job->interface = Int_val(val_interface); return lwt_unix_alloc_job(&(job->job)); } CAMLprim value ml_usb_claim_interface_result(value val_job) { struct job_claim_interface *job = Job_claim_interface(val_job); if (job->result) ml_usb_error(job->result, "claim_interface"); return Val_unit; } CAMLprim value ml_usb_claim_interface_free(value val_job) { struct job_claim_interface *job = Job_claim_interface(val_job); lwt_unix_free_job(&job->job); return Val_unit; } /* +-----------------------------------------------------------------+ | JOB: release_interface | +-----------------------------------------------------------------+ */ struct job_release_interface { struct lwt_unix_job job; libusb_device_handle *handle; int interface; int result; }; #define Job_release_interface(v) *(struct job_release_interface**)Data_custom_val(v) static void worker_release_interface(struct job_release_interface *job) { job->result = libusb_release_interface(job->handle, job->interface); } CAMLprim value ml_usb_release_interface_job(value val_handle, value val_interface) { struct job_release_interface *job = lwt_unix_new(struct job_release_interface); job->job.worker = (lwt_unix_job_worker)worker_release_interface; job->handle = Handle_val(val_handle); job->interface = Int_val(val_interface); return lwt_unix_alloc_job(&(job->job)); } CAMLprim value ml_usb_release_interface_result(value val_job) { struct job_release_interface *job = Job_release_interface(val_job); if (job->result) ml_usb_error(job->result, "release_interface"); return Val_unit; } CAMLprim value ml_usb_release_interface_free(value val_job) { struct job_release_interface *job = Job_release_interface(val_job); lwt_unix_free_job(&job->job); return Val_unit; } /* +-----------------------------------------------------------------+ | JOB: get_configuration | +-----------------------------------------------------------------+ */ struct job_get_configuration { struct lwt_unix_job job; libusb_device_handle *handle; int configuration; int result; }; #define Job_get_configuration(v) *(struct job_get_configuration**)Data_custom_val(v) static void worker_get_configuration(struct job_get_configuration *job) { job->result = libusb_get_configuration(job->handle, &(job->configuration)); } CAMLprim value ml_usb_get_configuration_job(value val_handle) { struct job_get_configuration *job = lwt_unix_new(struct job_get_configuration); job->job.worker = (lwt_unix_job_worker)worker_get_configuration; job->handle = Handle_val(val_handle); return lwt_unix_alloc_job(&(job->job)); } CAMLprim value ml_usb_get_configuration_result(value val_job) { struct job_get_configuration *job = Job_get_configuration(val_job); if (job->result) ml_usb_error(job->result, "get_configuration"); return Val_int(job->configuration); } CAMLprim value ml_usb_get_configuration_free(value val_job) { struct job_get_configuration *job = Job_get_configuration(val_job); lwt_unix_free_job(&job->job); return Val_unit; } /* +-----------------------------------------------------------------+ | JOB: set_configuration | +-----------------------------------------------------------------+ */ struct job_set_configuration { struct lwt_unix_job job; libusb_device_handle *handle; int configuration; int result; }; #define Job_set_configuration(v) *(struct job_set_configuration**)Data_custom_val(v) static void worker_set_configuration(struct job_set_configuration *job) { job->result = libusb_set_configuration(job->handle, job->configuration); } CAMLprim value ml_usb_set_configuration_job(value val_handle, value val_configuration) { struct job_set_configuration *job = lwt_unix_new(struct job_set_configuration); job->job.worker = (lwt_unix_job_worker)worker_set_configuration; job->handle = Handle_val(val_handle); job->configuration = Int_val(val_configuration); return lwt_unix_alloc_job(&(job->job)); } CAMLprim value ml_usb_set_configuration_result(value val_job) { struct job_set_configuration *job = Job_set_configuration(val_job); if (job->result) ml_usb_error(job->result, "set_configuration"); return Val_unit; } CAMLprim value ml_usb_set_configuration_free(value val_job) { struct job_set_configuration *job = Job_set_configuration(val_job); lwt_unix_free_job(&job->job); return Val_unit; } /* +-----------------------------------------------------------------+ | JOB: set_interface_alt_setting | +-----------------------------------------------------------------+ */ struct job_set_interface_alt_setting { struct lwt_unix_job job; libusb_device_handle *handle; int interface; int alt_setting; int result; }; #define Job_set_interface_alt_setting(v) *(struct job_set_interface_alt_setting**)Data_custom_val(v) static void worker_set_interface_alt_setting(struct job_set_interface_alt_setting *job) { job->result = libusb_set_interface_alt_setting(job->handle, job->interface, job->alt_setting); } CAMLprim value ml_usb_set_interface_alt_setting_job(value val_handle, value val_interface, value val_alt_setting) { struct job_set_interface_alt_setting *job = lwt_unix_new(struct job_set_interface_alt_setting); job->job.worker = (lwt_unix_job_worker)worker_set_interface_alt_setting; job->handle = Handle_val(val_handle); job->interface = Int_val(val_interface); job->alt_setting = Int_val(val_alt_setting); return lwt_unix_alloc_job(&(job->job)); } CAMLprim value ml_usb_set_interface_alt_setting_result(value val_job) { struct job_set_interface_alt_setting *job = Job_set_interface_alt_setting(val_job); if (job->result) ml_usb_error(job->result, "set_interface_alt_setting"); return Val_unit; } CAMLprim value ml_usb_set_interface_alt_setting_free(value val_job) { struct job_set_interface_alt_setting *job = Job_set_interface_alt_setting(val_job); lwt_unix_free_job(&job->job); return Val_unit; } /* +-----------------------------------------------------------------+ | JOB: clear_halt | +-----------------------------------------------------------------+ */ struct job_clear_halt { struct lwt_unix_job job; libusb_device_handle *handle; int endpoint; int result; }; #define Job_clear_halt(v) *(struct job_clear_halt**)Data_custom_val(v) static void worker_clear_halt(struct job_clear_halt *job) { job->result = libusb_clear_halt(job->handle, job->endpoint); } CAMLprim value ml_usb_clear_halt_job(value val_handle, value val_endpoint) { struct job_clear_halt *job = lwt_unix_new(struct job_clear_halt); job->job.worker = (lwt_unix_job_worker)worker_clear_halt; job->handle = Handle_val(val_handle); job->endpoint = Int_val(val_endpoint); return lwt_unix_alloc_job(&(job->job)); } CAMLprim value ml_usb_clear_halt_result(value val_job) { struct job_clear_halt *job = Job_clear_halt(val_job); if (job->result) ml_usb_error(job->result, "clear_halt"); return Val_unit; } CAMLprim value ml_usb_clear_halt_free(value val_job) { struct job_clear_halt *job = Job_clear_halt(val_job); lwt_unix_free_job(&job->job); return Val_unit; } /* +-----------------------------------------------------------------+ | JOB: reset_device | +-----------------------------------------------------------------+ */ struct job_reset_device { struct lwt_unix_job job; libusb_device_handle *handle; int result; }; #define Job_reset_device(v) *(struct job_reset_device**)Data_custom_val(v) static void worker_reset_device(struct job_reset_device *job) { job->result = libusb_reset_device(job->handle); } CAMLprim value ml_usb_reset_device_job(value val_handle) { struct job_reset_device *job = lwt_unix_new(struct job_reset_device); job->job.worker = (lwt_unix_job_worker)worker_reset_device; job->handle = Handle_val(val_handle); return lwt_unix_alloc_job(&(job->job)); } CAMLprim value ml_usb_reset_device_result(value val_job) { struct job_reset_device *job = Job_reset_device(val_job); if (job->result) ml_usb_error(job->result, "reset_device"); return Val_unit; } CAMLprim value ml_usb_reset_device_free(value val_job) { struct job_reset_device *job = Job_reset_device(val_job); lwt_unix_free_job(&job->job); return Val_unit; } /* +-----------------------------------------------------------------+ | USB descriptors | +-----------------------------------------------------------------+ */ CAMLprim value ml_usb_get_device_descriptor(value device) { CAMLparam1(device); CAMLlocal1(result); struct libusb_device_descriptor desc; int res = libusb_get_device_descriptor(Device_val(device), &desc); if (res) ml_usb_error(res, "get_device_descriptor"); result = caml_alloc_tuple(12); Store_field(result, 0, Val_int(desc.bcdUSB)); Store_field(result, 1, Val_int(desc.bDeviceClass)); Store_field(result, 2, Val_int(desc.bDeviceSubClass)); Store_field(result, 3, Val_int(desc.bDeviceProtocol)); Store_field(result, 4, Val_int(desc.bMaxPacketSize0)); Store_field(result, 5, Val_int(desc.idVendor)); Store_field(result, 6, Val_int(desc.idProduct)); Store_field(result, 7, Val_int(desc.bcdDevice)); Store_field(result, 8, Val_int(desc.iManufacturer)); Store_field(result, 9, Val_int(desc.iProduct)); Store_field(result, 10, Val_int(desc.iSerialNumber)); Store_field(result, 11, Val_int(desc.bNumConfigurations)); CAMLreturn(result); } static value copy_config_descriptor(struct libusb_config_descriptor *cd) { CAMLparam0(); CAMLlocal5(result, iface, ifaces, altsettings, endpoint); CAMLlocal1(endpoints); result = caml_alloc_tuple(5); Store_field(result, 0, Val_int(cd->bConfigurationValue)); Store_field(result, 1, Val_int(cd->iConfiguration)); Store_field(result, 2, Val_int(cd->bmAttributes)); Store_field(result, 3, Val_int(cd->MaxPower)); ifaces = caml_alloc_tuple(cd->bNumInterfaces); Store_field(result, 4, ifaces); int i, j, k; for (i = 0; i < cd->bNumInterfaces; i++) { altsettings = caml_alloc_tuple(cd->interface[i].num_altsetting); Store_field(ifaces, i, altsettings); for (j = 0; j < cd->interface[i].num_altsetting; j++) { iface = caml_alloc_tuple(7); Store_field(altsettings, j, iface); Store_field(iface, 0, Val_int(cd->interface[i].altsetting[j].bInterfaceNumber)); Store_field(iface, 1, Val_int(cd->interface[i].altsetting[j].bAlternateSetting)); Store_field(iface, 2, Val_int(cd->interface[i].altsetting[j].bInterfaceClass)); Store_field(iface, 3, Val_int(cd->interface[i].altsetting[j].bInterfaceSubClass)); Store_field(iface, 4, Val_int(cd->interface[i].altsetting[j].bInterfaceProtocol)); Store_field(iface, 5, Val_int(cd->interface[i].altsetting[j].iInterface)); endpoints = caml_alloc_tuple(cd->interface[i].altsetting[j].bNumEndpoints); Store_field(iface, 6, endpoints); for (k = 0; k < cd->interface[i].altsetting[j].bNumEndpoints; k++) { endpoint = caml_alloc_tuple(6); Store_field(endpoints, k, endpoint); Store_field(endpoint, 0, Val_int(cd->interface[i].altsetting[j].endpoint[k].bEndpointAddress)); Store_field(endpoint, 1, Val_int(cd->interface[i].altsetting[j].endpoint[k].bmAttributes)); Store_field(endpoint, 2, Val_int(cd->interface[i].altsetting[j].endpoint[k].wMaxPacketSize)); Store_field(endpoint, 3, Val_int(cd->interface[i].altsetting[j].endpoint[k].bInterval)); Store_field(endpoint, 4, Val_int(cd->interface[i].altsetting[j].endpoint[k].bRefresh)); Store_field(endpoint, 5, Val_int(cd->interface[i].altsetting[j].endpoint[k].bSynchAddress)); } } } libusb_free_config_descriptor(cd); CAMLreturn(result); } CAMLprim value ml_usb_get_active_config_descriptor(value device) { struct libusb_config_descriptor *cd; int res = libusb_get_active_config_descriptor(Device_val(device), &cd); if (res) ml_usb_error(res, "get_active_config_descriptor"); return copy_config_descriptor(cd); } CAMLprim value ml_usb_get_config_descriptor(value device, value index) { struct libusb_config_descriptor *cd; int res = libusb_get_config_descriptor(Device_val(device), Int_val(index), &cd); if (res) ml_usb_error(res, "get_config_descriptor"); return copy_config_descriptor(cd); } CAMLprim value ml_usb_get_config_descriptor_by_value(value device, value val) { struct libusb_config_descriptor *cd; int res = libusb_get_config_descriptor_by_value(Device_val(device), Int_val(val), &cd); if (res) ml_usb_error(res, "get_config_descriptor_by_value"); return copy_config_descriptor(cd); } /* +-----------------------------------------------------------------+ | IOs | +-----------------------------------------------------------------+ */ #define Transfer_val(v) *(struct libusb_transfer**)Data_custom_val(v) static struct custom_operations transfer_ops = { "usb.transfer", custom_finalize_default, ml_usb_compare, ml_usb_hash, custom_serialize_default, custom_deserialize_default }; static value alloc_transfer(struct libusb_transfer *transfer) { value x = caml_alloc_custom(&transfer_ops, sizeof(struct libusb_transfer*), 0, 1); Transfer_val(x) = transfer; return x; } CAMLprim value ml_usb_cancel_transfer(value transfer) { int res = libusb_cancel_transfer(Transfer_val(transfer)); if (res) ml_usb_error(res, "cancel_transfer"); return Val_unit; } /* Allocate a buffer, taking cares of remarks about overflows from the libsub documentation: */ static unsigned char *ml_usb_alloc_buffer(int length) { int rest = length % 512; if (rest) length = length - rest + 512; return (unsigned char*)ml_usb_malloc(length); } /* Convert an error transfer status to an exception */ static value ml_usb_transfer_error(enum libusb_transfer_status status) { switch(status) { case LIBUSB_TRANSFER_ERROR: return Val_int(0); case LIBUSB_TRANSFER_TIMED_OUT: return Val_int(1); case LIBUSB_TRANSFER_CANCELLED: return Val_int(2); case LIBUSB_TRANSFER_STALL: return Val_int(3); case LIBUSB_TRANSFER_NO_DEVICE: return Val_int(4); case LIBUSB_TRANSFER_OVERFLOW: return Val_int(5); default: return Val_int(0); } } /* Construct the result of an isochronous transfer: */ static value ml_usb_iso_result(struct libusb_transfer *transfer) { CAMLparam0(); CAMLlocal3(list, x, y); int i; for (i = 0; i < transfer->num_iso_packets; i++) { if (transfer->iso_packet_desc[i].status == LIBUSB_TRANSFER_COMPLETED) { x = caml_alloc(1, 0); Store_field(x, 0, Val_int(transfer->iso_packet_desc[i].actual_length)); } else { x = caml_alloc(1, 1); Store_field(x, 0, ml_usb_transfer_error(transfer->status)); } y = caml_alloc_tuple(2); Store_field(y, 0, x); Store_field(y, 1, list); list = y; } CAMLreturn(list); } /* Handler for device-to-host transfers: */ static void ml_usb_handle_recv(struct libusb_transfer *transfer) { CAMLparam0(); CAMLlocal2(meta, result); /* Metadata of the transfer: */ meta = (value)(transfer->user_data); if (transfer->status == LIBUSB_TRANSFER_COMPLETED) { /* Copy bytes from the C memory to the caml string: */ memcpy(String_val(Field(meta, 1)) + Long_val(Field(meta, 2)), transfer->buffer, transfer->actual_length); /* Returns [OK actual_length] */ result = caml_alloc(1, 0); if (transfer->num_iso_packets == 0) /* Classic transfer */ Store_field(result, 0, Val_int(transfer->actual_length)); else /* Isochronous transfer */ Store_field(result, 0, ml_usb_iso_result(transfer)); } else { /* Returns [Error status] */ result = caml_alloc(1, 1); Store_field(result, 0, ml_usb_transfer_error(transfer->status)); } /* Unregister the memory root: */ caml_remove_generational_global_root((value*)(&(transfer->user_data))); /* Cleanup allocated structures: */ free(transfer->buffer); libusb_free_transfer(transfer); /* Call the ocaml handler: */ caml_callback(Field(meta, 0), result); CAMLreturn0; } /* Handler for host-to-device transfers: */ void ml_usb_handle_send(struct libusb_transfer *transfer) { CAMLparam0(); CAMLlocal2(caml_func, result); /* Metadata contains only the caml callback: */ caml_func = (value)(transfer->user_data); if (transfer->status == LIBUSB_TRANSFER_COMPLETED) { result = caml_alloc(1, 0); if (transfer->num_iso_packets == 0) /* Classic transfer */ Store_field(result, 0, Val_int(transfer->actual_length)); else /* Isochronous transfer */ Store_field(result, 0, ml_usb_iso_result(transfer)); } else { /* Returns [Error status] */ result = caml_alloc(1, 1); Store_field(result, 0, ml_usb_transfer_error(transfer->status)); } /* Unregister the memory root: */ caml_remove_generational_global_root((value*)(&(transfer->user_data))); /* Cleanup allocated structures: */ free(transfer->buffer); libusb_free_transfer(transfer); /* Call the ocaml handler: */ caml_callback(caml_func, result); CAMLreturn0; } /* Alloc a transfer and fill it with common informations: */ struct libusb_transfer *ml_usb_transfer(value desc /* the description provided by the caml function: */, value meta /* metadata for the callback */, enum libusb_endpoint_direction direction, int num_iso_packets) { struct libusb_transfer *transfer = ml_usb_alloc_transfer(num_iso_packets); transfer->dev_handle = Handle_val(Field(desc, 0)); transfer->endpoint = Int_val(Field(desc, 1)) | direction; transfer->timeout = Int_val(Field(desc, 2)); transfer->buffer = ml_usb_alloc_buffer(Int_val(Field(desc, 5))); transfer->length = Int_val(Field(desc, 5)); transfer->user_data = (void*)meta; transfer->num_iso_packets = num_iso_packets; /* Register metadata as a memory root, because we need it for the callback which will be called later: */ caml_register_generational_global_root((value*)(&(transfer->user_data))); return transfer; } /* Device-to-host transfers, for interrupt or bulk transfers: */ CAMLprim value ml_usb_recv(value desc, enum libusb_transfer_type type, int num_iso_packets) { CAMLparam1(desc); CAMLlocal1(meta); /* Metadata for the transfer: */ meta = caml_alloc_tuple(3); /* - the caml callback: */ Store_field(meta, 0, Field(desc, 6)); /* - the caml buffer: */ Store_field(meta, 1, Field(desc, 3)); /* - the offset in the buffer: */ Store_field(meta, 2, Field(desc, 4)); struct libusb_transfer *transfer = ml_usb_transfer(desc, meta, LIBUSB_ENDPOINT_IN, num_iso_packets); transfer->callback = ml_usb_handle_recv; transfer->type = type; int res = libusb_submit_transfer(transfer); if (res) ml_usb_error(res, "submit_transfer"); CAMLreturn(alloc_transfer(transfer)); } /* Host-to-device transfers, for interrupt or bulk transfers: */ CAMLprim value ml_usb_send(value desc, enum libusb_transfer_type type, int num_iso_packets) { /* Metadata contains only the callback: */ struct libusb_transfer *transfer = ml_usb_transfer(desc, Field(desc, 6), LIBUSB_ENDPOINT_OUT, num_iso_packets); transfer->callback = ml_usb_handle_send; transfer->type = type; /* Copy data to send from the managed memory to the C memory: */ memcpy(transfer->buffer, String_val(Field(desc, 3)) + Long_val(Field(desc, 4)), Long_val(Field(desc, 5))); int res = libusb_submit_transfer(transfer); if (res) ml_usb_error(res, "submit_transfer"); return alloc_transfer(transfer); } CAMLprim value ml_usb_bulk_recv(value desc) { return ml_usb_recv(desc, LIBUSB_TRANSFER_TYPE_BULK, 0); } CAMLprim value ml_usb_bulk_send(value desc) { return ml_usb_send(desc, LIBUSB_TRANSFER_TYPE_BULK, 0); } CAMLprim value ml_usb_interrupt_recv(value desc) { return ml_usb_recv(desc, LIBUSB_TRANSFER_TYPE_INTERRUPT, 0); } CAMLprim value ml_usb_interrupt_send(value desc) { return ml_usb_send(desc, LIBUSB_TRANSFER_TYPE_INTERRUPT, 0); } /* Generic function which filling the data section of a control transfer: */ CAMLprim value ml_usb_control(value desc, enum libusb_endpoint_direction direction) { struct libusb_control_setup *control = (struct libusb_control_setup*)String_val(Field(desc,3)); control->bmRequestType = Int_val(Field(desc, 7)) | (Int_val(Field(desc, 8)) << 5) | direction; control->bRequest = Int_val(Field(desc, 9)); control->wValue = libusb_cpu_to_le16(Int_val(Field(desc, 10))); control->wIndex = libusb_cpu_to_le16(Int_val(Field(desc, 11))); int length = Int_val(Field(desc, 5)); control->wLength = libusb_cpu_to_le16(length); Field(desc, 5) = Val_int(length + LIBUSB_CONTROL_SETUP_SIZE); if (direction == LIBUSB_ENDPOINT_IN) return ml_usb_recv(desc, LIBUSB_TRANSFER_TYPE_CONTROL, 0); else return ml_usb_send(desc, LIBUSB_TRANSFER_TYPE_CONTROL, 0); } CAMLprim value ml_usb_control_recv(value desc) { return ml_usb_control(desc, LIBUSB_ENDPOINT_IN); } CAMLprim value ml_usb_control_send(value desc) { return ml_usb_control(desc, LIBUSB_ENDPOINT_OUT); } CAMLprim value ml_usb_iso(value desc, enum libusb_endpoint_direction direction) { int num_iso_packets = Int_val(Field(desc, 7)); value val_transfer; if (direction == LIBUSB_ENDPOINT_IN) val_transfer = ml_usb_recv(desc, LIBUSB_TRANSFER_TYPE_ISOCHRONOUS, num_iso_packets); else val_transfer = ml_usb_send(desc, LIBUSB_TRANSFER_TYPE_ISOCHRONOUS, num_iso_packets); struct libusb_transfer *transfer = Transfer_val(val_transfer); int i; value x = Field(desc, 8); for (i = 0; i < num_iso_packets; i++, x = Field(x, 1)) transfer->iso_packet_desc[i].length = Int_val(Field(x, 0)); return val_transfer; } CAMLprim value ml_usb_iso_recv(value desc) { return ml_usb_iso(desc, LIBUSB_ENDPOINT_IN); } CAMLprim value ml_usb_iso_send(value desc) { return ml_usb_iso(desc, LIBUSB_ENDPOINT_OUT); } ocaml-usb-1.3.0/src/USB.mli0000644000000000000000000003460712005550027013514 0ustar0000000000000000(* * USB.mli * ------- * Copyright : (c) 2009, Jeremie Dimino * Licence : BSD3 * * This file is a part of ocaml-usb. *) (** Module for USB communication *) val handle_error : ('a -> 'b) -> 'a -> 'b (** [handle_unix_error f x] applies [f] to [x] and returns the result. If the exception {!Error} or {!Transport} is raised, it prints a message describing the error and exits with code 2. *) (** {6 General errors} *) (** Any function of this module may raise one of the following errors: *) type error = | Error_io (** Error on IOs *) | Error_invalid_param (** Invalid parameter. If this error is raised, then there is a bug in ocaml-usb. Please fill a bug report in this case. *) | Error_access (** Access denied to a peripheral *) | Error_no_device (** No such device (it may have been disconnected) *) | Error_not_found (** Entity not found *) | Error_busy (** Resource busy *) | Error_timeout (** Operation timed out *) | Error_overflow (** Overflow *) | Error_pipe (** Pipe error *) | Error_interrupted (** System call interrupted (perhaps due to signal) *) | Error_no_mem (** Insufficient memory *) | Error_not_supported (** Operation not supported or unimplemented on this platform *) | Error_other (** Other error *) exception Error of error * string (** [Error(error, func_name)] is raised when libusb returns an error. [func_name] is a the name of the function which failed. *) val error_message : error -> string (** [error_message error] returns a human readable description of the error *) (** {6 Types} *) (** A USB endpoint direction *) type direction = In | Out (** A USB endpoint number *) type endpoint = int (** {6 Miscellanies} *) val init : unit Lazy.t (** When forced, [init] initialises libusb. This is automatically done so you do not need to do it manually. By the way you can do it to catch initialisation errors. *) val set_debug : [ `quiet | `error | `warning | `verbose ] -> unit (** [set_debug level] set the debug level. *) (** {6 Device informations} *) type device (** Representation of a device description *) val get_device_list : unit -> device list (** Returns a list of USB devices currently attached to the system. *) val get_bus_number : device -> int (** Get the number of the bus that a device is connected to. *) val get_device_address : device -> int (** Get the address of the device on the bus it is connected to. *) val get_max_packet_size : device : device -> direction : direction -> endpoint : endpoint -> int (** [get_max_packet_size ~device ~direction ~endpoint] Convenience function to retrieve the [wMaxPacketSize] value for a particular endpoint in the active device configuration. *) (** {6 Device use} *) type handle (** A handle allows you to perform I/O on the device in question. *) type interface = int (** An interface number on a device *) val open_device : device -> handle (** Open a device and obtain a device handle. A handle allows you to perform I/O on the device in question. *) val close : handle -> unit (** Close a previously opened device handle *) val open_device_with : vendor_id : int -> product_id : int -> handle (** [open_device_with ~vendor_id ~product_id] Convenience function for finding a device with a particular idVendor/idProduct combination. @raise Failure if the device is not found. *) val get_device : handle -> device (** Get the underlying device for a handle *) val kernel_driver_active : handle -> interface -> bool (** Determine if a kernel driver is active on an interface. If a kernel driver is active, you cannot claim the interface, and libusb will be unable to perform I/O. *) val detach_kernel_driver : handle -> interface -> unit (** Detach a kernel driver from an interface. If successful, you will then be able to claim the interface and perform I/O. *) val attach_kernel_driver : handle -> interface -> unit (** Re-attach an interface's kernel driver, which was previously detached using {!detach_kernel_driver}. *) val claim_interface : handle -> interface -> unit Lwt.t (** [claim_interface handle interface_number] Claim an interface on a given device handle. You must claim the interface you wish to use before you can perform I/O on any of its endpoints. *) val release_interface : handle -> interface -> unit Lwt.t (** Release an interface previously claimed with libusb_claim_interface(). You should release all claimed interfaces before closing a device handle. This is a blocking function. A [SET_INTERFACE] control request will be sent to the device, resetting interface state to the first alternate setting. *) type configuration = int (** A device configuration *) val get_configuration : handle -> configuration Lwt.t (** [get_configuration handle] returns the current configuration of a device *) val set_configuration : handle -> configuration -> unit Lwt.t (** [set_configuration handle conf] change the current configuration of a device *) val set_interface_alt_setting : handle -> interface -> int -> unit Lwt.t (** [set_interface_alt_setting handle interface alternate_setting] activates an alternate setting for an interface. *) val clear_halt : handle -> endpoint -> unit Lwt.t (** [clear_halt handle endpoint] clears the halt/stall condition for an endpoint. *) val reset_device : handle -> unit Lwt.t (** [reset_device handle] reset the given device *) (** {6 USB descriptors} *) (** Device class codes *) module Class : sig type t = int val per_interface : t val audio : t val communication : t val hid : t val physical : t val printer : t val image : t val mass_storage : t val hub : t val data : t val smart_card : t val content_security : t val video : t val personal_healthcare : t val diagnostic_device : t val wireless : t val application : t val vendor_specific : t val ptp : t (** Legacy name, same as {!image}. *) val to_string : t -> string (** Returns a string representation of a device class code *) end type device_descriptor = { dd_usb : int; (** USB specification release number in binary-coded decimal. A value of 0x0200 indicates USB 2.0, 0x0110 indicates USB 1.1, etc. *) dd_device_class : Class.t; (** USB-IF class code for the device. *) dd_device_sub_class : int; (** USB-IF subclass code for the device, qualified by the [dd_device_class] value. *) dd_device_protocol : int; (** USB-IF protocol code for the device, qualified by the [dd_device_class] and [dd_device_subclass] values. *) dd_max_packet_size : int; (** Maximum packet size for endpoint 0. *) dd_vendor_id : int; (** USB-IF vendor ID. *) dd_product_id : int; (** USB-IF product ID. *) dd_device : int; (** Device release number in binary-coded decimal. *) dd_index_manufacturer : int; (** Index of string descriptor describing manufacturer. *) dd_index_product : int; (** Index of string descriptor describing product. *) dd_index_serial_number : int; (** Index of string descriptor containing device serial number. *) dd_configurations : int; (** Number of possible configurations. *) } val get_device_descriptor : device -> device_descriptor (** Get the USB device descriptor for a given device. *) type endpoint_descriptor = { ed_endpoint_address : int; (** The address of the endpoint described by this descriptor. *) ed_attributes : int; (** Attributes which apply to the endpoint when it is configured using the {!cd_configuration_value}. *) ed_max_packet_size : int; (** Maximum packet size this endpoint is capable of sending/receiving. *) ed_interval : int; (** Interval for polling endpoint for data transfers. *) ed_refresh : int; (** For audio devices only: the rate at which synchronization feedback is provided. *) ed_synch_address : int; (** For audio devices only: the address if the synch endpoint. *) } type interface_descriptor = { id_interface : int; (** Number of this interface. *) id_alternate_setting : int; (** Value used to select this alternate setting for this interface. *) id_interface_class : Class.t; (** USB-IF class code for this interface. *) id_interface_sub_class : int; (** USB-IF subclass code for this interface, qualified by the [id_interface_class] value. *) id_interface_protocol : int; (** USB-IF protocol code for this interface, qualified by the [id_interface_class] and [id_interface_sub_class] values. *) id_index_interface : int; (** Index of string descriptor describing this interface. *) id_endpoints : endpoint_descriptor array; (** Array of endpoint descriptors. *) } type config_descriptor = { cd_configuration_value : int; (** Identifier value for this configuration *) cd_index_configuration : int; (** Index of string descriptor describing this configuration. *) cd_attributes : int; (** A bitmask, representing configuration characteristics. *) cd_max_power : int; (** Maximum power consumption of the USB device from this bus in this configuration when the device is fully opreation. Expressed in units of 2 mA. *) cd_interfaces : interface_descriptor array array; (** Array of interfaces supported by this configuration. [cd_interface.(iface).(altsetting)] designate the interface descriptor for interface [iface] with alternate setting [altsetting]. *) } val get_active_config_descriptor : device -> config_descriptor (** Get the USB configuration descriptor for the currently active configuration. *) val get_config_descriptor : device -> int -> config_descriptor (** Get a USB configuration descriptor based on its index. *) val get_config_descriptor_by_value : device -> int -> config_descriptor (** Get a USB configuration descriptor with a specific [cd_configuration_value]. *) (** Descriptor types *) module DT : sig type t = int val device : t val config : t val string : t val interface : t val endpoint : t val hid : t val report : t val physical : t val hub : t end val get_string_descriptor : handle -> ?timeout : float -> ?lang_id : int -> index : int -> string Lwt.t (** Retrieve a string descriptor from a device. *) (** {6 IOs} *) (** {8 Errors} *) (** Transfers may fails with any of the following error: *) type transfer_error = | Transfer_error (** Transfer failed *) | Transfer_timed_out (** Transfer timed out *) | Transfer_cancelled (** Transfer was cancelled *) | Transfer_stall (** For bulk/interrupt endpoints: halt condition detected (endpoint stalled). For control endpoints: control request not supported. *) | Transfer_no_device (** Device was disconnected *) | Transfer_overflow (** Device sent more data than requested *) exception Transfer of transfer_error * string (** [Transfer(error, func_name)] Exception raised when a transfer fail. *) val transfer_error_message : transfer_error -> string (** [transfer_error_message error] *) (** {8 Bulk transfers} *) val bulk_recv : handle : handle -> endpoint : endpoint -> ?timeout : float -> string -> int -> int -> int Lwt.t (** [bulk_recv ~handle ~endpoint ?timeout buffer offset length] *) val bulk_send : handle : handle -> endpoint : endpoint -> ?timeout : float -> string -> int -> int -> int Lwt.t (** [bulk_send ~handle ~endpoint ?timeout buffer offset length] *) (** {8 Interrupt transfers} *) val interrupt_recv : handle : handle -> endpoint : endpoint -> ?timeout : float -> string -> int -> int -> int Lwt.t (** [interrupt_recv ~handle ~endpoint ?timeout buffer offset length] *) val interrupt_send : handle : handle -> endpoint : endpoint -> ?timeout : float -> string -> int -> int -> int Lwt.t (** [interrupt_send ~handle ~endpoint ?timeout buffer offset length] *) (** {8 Isochronous transfers} *) (** Result of the transfer of one packet in an isochronous transfer: *) type iso_result = | Iso_ok of int (** The packet has been transfered successfully *) | Iso_error of transfer_error * string (** [Iso_error(error, func_name)] An error occured *) val iso_recv : handle : handle -> endpoint : endpoint -> ?timeout : float -> string -> int -> int list -> iso_result list Lwt.t val iso_send : handle : handle -> endpoint : endpoint -> ?timeout : float -> string -> int -> int list -> iso_result list Lwt.t (** {8 Control transfers} *) type recipient = | Device | Interface | Endpoint | Other type request_type = | Standard | Class | Vendor | Reserved type request = int val control_send : handle : handle -> endpoint : endpoint -> ?timeout : float -> ?recipient : recipient -> ?request_type : request_type -> request : request -> value : int -> index : int -> string -> int -> int -> int Lwt.t (** Sends a control packet. @param recipient defaults to {!Device} @param request_type defaults to {!Standard} *) val control_recv : handle : handle -> endpoint : endpoint -> ?timeout : float -> ?recipient : recipient -> ?request_type : request_type -> request : request -> value : int -> index : int -> string -> int -> int -> int Lwt.t (** Receives a control packet. @param recipient defaults to {!Device} @param request_type defaults to {!Standard} *) (** Standard requests *) module Request : sig type t = request val get_status : t (** Request status of the specific recipient *) val clear_feature : t (** Clear or disable a specific feature *) val set_feature : t (** Set or enable a specific feature *) val set_address : t (** Set device address for all future accesses *) val get_descriptor : t (** Get the specified descriptor *) val set_descriptor : t (** Used to update existing descriptors or add new descriptors *) val get_configuration : t (** Get the current device configuration value *) val set_configuration : t (** Set device configuration *) val get_interface : t (** Return the selected alternate setting for the specified interface *) val set_interface : t (** Select an alternate interface for the specified interface *) val synch_frame : t (** Set then report an endpoint's synchronization frame *) end ocaml-usb-1.3.0/src/USB.ml0000644000000000000000000005331512005550027013340 0ustar0000000000000000(* * USB.ml * ------ * Copyright : (c) 2009, Jeremie Dimino * Licence : BSD3 * * This file is a part of ocaml-usb. *) open Lwt_unix open Lwt (* +-----------------------------------------------------------------+ | Errors | +-----------------------------------------------------------------+ *) type error = | Error_io | Error_invalid_param | Error_access | Error_no_device | Error_not_found | Error_busy | Error_timeout | Error_overflow | Error_pipe | Error_interrupted | Error_no_mem | Error_not_supported | Error_other exception Error of error * string let _ = Callback.register_exception "ocaml-usb:Error" (Error(Error_access, "")) type transfer_error = | Transfer_error | Transfer_timed_out | Transfer_cancelled | Transfer_stall | Transfer_no_device | Transfer_overflow exception Transfer of transfer_error * string let error_message = function | Error_io -> "Input/output error" | Error_invalid_param -> "Invalid parameter" | Error_access -> "Access denied" | Error_no_device -> "No such device" | Error_not_found -> "Entity not found" | Error_busy -> "Resource busy" | Error_timeout -> "Operation timed out" | Error_overflow -> "Overflow" | Error_pipe -> "Pipe error" | Error_interrupted -> "System call interrupted" | Error_no_mem -> "Insufficient memory" | Error_not_supported -> "Operation not supported or unimplemented on this platform" | Error_other -> "Other error" let transfer_error_message = function | Transfer_error -> "Transfer failed" | Transfer_timed_out -> "Transfer timed out" | Transfer_cancelled -> "Transfer was cancelled" | Transfer_stall -> "Transfer stalled" | Transfer_no_device -> "Device was disconnected" | Transfer_overflow -> "Device sent more data than requested" let () = Printexc.register_printer (function | Error(err, fun_name) -> Some(Printf.sprintf "USB error: '%s' failed: %s" fun_name (error_message err)) | Transfer(err, fun_name) -> Some(Printf.sprintf "USB transfer error: '%s' failed: %s" fun_name (transfer_error_message err)) | exn -> None) let handle_error f arg = try f arg with | Error(err, fun_name) -> Printf.eprintf "%s: %s failed: %s\n%!" Sys.argv.(0) fun_name (error_message err); exit 2 | Transfer(err, fun_name) -> Printf.eprintf "%s: %s failed: %s\n%!" Sys.argv.(0) fun_name (transfer_error_message err); exit 2 (* +-----------------------------------------------------------------+ | Types | +-----------------------------------------------------------------+ *) type device type device_handle type transfer type handle_state = | State_closed | State_detach (* A detached operation is being performed on the device. *) | State_ok type handle = { handle : device_handle; mutable state : handle_state; mutex : Lwt_mutex.t; } type direction = In | Out type endpoint = int type interface = int type recipient = | Device | Interface | Endpoint | Other type request_type = | Standard | Class | Vendor | Reserved type request = int type configuration = int type iso_result = | Iso_ok of int | Iso_error of transfer_error * string (* +-----------------------------------------------------------------+ | Stub functions | +-----------------------------------------------------------------+ *) (* Result of a transfer: *) type 'a result = | OK of 'a | Error of transfer_error external ml_usb_init : unit -> unit = "ml_usb_init" external ml_usb_exit : unit -> unit = "ml_usb_exit" external ml_usb_set_debug : int -> unit = "ml_usb_set_debug" external ml_usb_get_next_timeout : unit -> float = "ml_usb_get_next_timeout" external ml_usb_handle_events : unit -> unit = "ml_usb_handle_events" external ml_usb_get_device_list : unit -> device list = "ml_usb_get_device_list" external ml_usb_get_bus_number : device -> int = "ml_usb_get_bus_number" external ml_usb_get_device_address : device -> int = "ml_usb_get_device_address" external ml_usb_get_max_packet_size : device -> direction -> endpoint -> int = "ml_usb_get_max_packet_size" external ml_usb_open : device -> device_handle = "ml_usb_open" external ml_usb_open_device_with_vid_pid : int -> int -> device_handle option = "ml_usb_open_device_with_vid_pid" external ml_usb_close : device_handle -> unit = "ml_usb_close" external ml_usb_get_device : device_handle -> device = "ml_usb_get_device" external ml_usb_kernel_driver_active : device_handle -> interface -> bool = "ml_usb_kernel_driver_active" external ml_usb_detach_kernel_driver : device_handle -> interface -> unit = "ml_usb_detach_kernel_driver" external ml_usb_attach_kernel_driver : device_handle -> interface -> unit = "ml_usb_attach_kernel_driver" external ml_usb_bulk_recv : device_handle * endpoint * int * string * int * int * (int result -> unit) -> transfer = "ml_usb_bulk_recv" external ml_usb_bulk_send : device_handle * endpoint * int * string * int * int * (int result -> unit) -> transfer = "ml_usb_bulk_send" external ml_usb_interrupt_recv : device_handle * endpoint * int * string * int * int * (int result -> unit) -> transfer = "ml_usb_interrupt_recv" external ml_usb_interrupt_send : device_handle * endpoint * int * string * int * int * (int result -> unit) -> transfer = "ml_usb_interrupt_send" external ml_usb_control_recv : device_handle * endpoint * int * string * int * int * (int result -> unit) * recipient * request_type * request * int * int -> transfer = "ml_usb_control_recv" external ml_usb_control_send : device_handle * endpoint * int * string * int * int * (int result -> unit) * recipient * request_type * request * int * int -> transfer = "ml_usb_control_send" external ml_usb_iso_recv : device_handle * endpoint * int * string * int * int * (int result list result -> unit) * int * int list -> transfer = "ml_usb_iso_recv" external ml_usb_iso_send : device_handle * endpoint * int * string * int * int * (int result list result -> unit) * int * int list -> transfer = "ml_usb_iso_send" external ml_usb_cancel_transfer : transfer -> unit = "ml_usb_cancel_transfer" external ml_usb_claim_interface_job : device_handle -> interface -> [ `claim_interface ] job = "ml_usb_claim_interface_job" external ml_usb_claim_interface_result : [ `claim_interface ] job -> unit = "ml_usb_claim_interface_result" external ml_usb_claim_interface_free : [ `claim_interface ] job -> unit = "ml_usb_claim_interface_free" external ml_usb_release_interface_job : device_handle -> interface -> [ `release_interface ] job = "ml_usb_release_interface_job" external ml_usb_release_interface_result : [ `release_interface ] job -> unit = "ml_usb_release_interface_result" external ml_usb_release_interface_free : [ `release_interface ] job -> unit = "ml_usb_release_interface_free" external ml_usb_get_configuration_job : device_handle -> [ `get_configuration ] job = "ml_usb_get_configuration_job" external ml_usb_get_configuration_result : [ `get_configuration ] job -> configuration = "ml_usb_get_configuration_result" external ml_usb_get_configuration_free : [ `get_configuration ] job -> unit = "ml_usb_get_configuration_free" external ml_usb_set_configuration_job : device_handle -> configuration -> [ `set_configuration ] job = "ml_usb_set_configuration_job" external ml_usb_set_configuration_result : [ `set_configuration ] job -> unit = "ml_usb_set_configuration_result" external ml_usb_set_configuration_free : [ `set_configuration ] job -> unit = "ml_usb_set_configuration_free" external ml_usb_set_interface_alt_setting_job : device_handle -> interface -> int -> [ `set_interface_alt_setting ] job = "ml_usb_set_interface_alt_setting_job" external ml_usb_set_interface_alt_setting_result : [ `set_interface_alt_setting ] job -> unit = "ml_usb_set_interface_alt_setting_result" external ml_usb_set_interface_alt_setting_free : [ `set_interface_alt_setting ] job -> unit = "ml_usb_set_interface_alt_setting_free" external ml_usb_clear_halt_job : device_handle -> endpoint -> [ `clear_halt ] job = "ml_usb_clear_halt_job" external ml_usb_clear_halt_result : [ `clear_halt ] job -> unit = "ml_usb_clear_halt_result" external ml_usb_clear_halt_free : [ `clear_halt ] job -> unit = "ml_usb_clear_halt_free" external ml_usb_reset_device_job : device_handle -> [ `reset_device ] job = "ml_usb_reset_device_job" external ml_usb_reset_device_result : [ `reset_device ] job -> unit = "ml_usb_reset_device_result" external ml_usb_reset_device_free : [ `reset_device ] job -> unit = "ml_usb_reset_device_free" (* +-----------------------------------------------------------------+ | Lwt integration | +-----------------------------------------------------------------+ *) let timeout_fired = ref false let timeout_event = ref Lwt_engine.fake_event let enter_iter () = timeout_fired := false; let timeout = ml_usb_get_next_timeout () in if timeout >= 0. then timeout_event := Lwt_engine.on_timer timeout false (fun _ -> timeout_fired := true) let leave_iter () = Lwt_engine.stop_event !timeout_event; if !timeout_fired then ml_usb_handle_events () let events = Hashtbl.create 42 let insert_pollfd fd check_readable check_writable = let acc = [] in let acc = if check_readable then Lwt_engine.on_readable fd (fun _ -> ml_usb_handle_events ()) :: acc else acc in let acc = if check_writable then Lwt_engine.on_writable fd (fun _ -> ml_usb_handle_events ()) :: acc else acc in Hashtbl.add events fd acc let remove_pollfd fd = List.iter Lwt_engine.stop_event (Hashtbl.find events fd); Hashtbl.remove events fd let () = Callback.register "ocaml-usb:insert-pollfd" insert_pollfd; Callback.register "ocaml-usb:remove-pollfd" remove_pollfd (* +-----------------------------------------------------------------+ | Initialization | +-----------------------------------------------------------------+ *) (* Every function of this module must take care of forcing this before doing anything: *) let init = lazy( (* Initializes libusb. *) ml_usb_init (); (* Integrate libusb timoeuts into lwt. *) ignore (Lwt_sequence.add_r enter_iter Lwt_main.enter_iter_hooks); ignore (Lwt_sequence.add_r leave_iter Lwt_main.leave_iter_hooks); (* Cleanup libusb on exit. *) let exit = lazy(ml_usb_exit ()) in at_exit (fun _ -> Lazy.force exit) ) let set_debug level = Lazy.force init; ml_usb_set_debug (match level with | `quiet -> 0 | `error -> 1 | `warning -> 2 | `verbose -> 3) (* +-----------------------------------------------------------------+ | Device handling and enumeration | +-----------------------------------------------------------------+ *) let get_device_list () = Lazy.force init; ml_usb_get_device_list () let make_handle device_handle = { handle = device_handle; state = State_ok; mutex = Lwt_mutex.create (); } (* Check that a handle is valid. It must be called before using a handle. *) let check_handle handle = if handle.state = State_closed then failwith "device handle closed" let detach handle job result free = Lwt_mutex.with_lock handle.mutex (fun () -> check_handle handle; handle.state <- State_detach; try_lwt execute_job (job ()) result free finally if handle.state = State_detach then handle.state <- State_ok; return ()) let get_bus_number = ml_usb_get_bus_number let get_device_address = ml_usb_get_device_address let get_max_packet_size ~device ~direction ~endpoint = ml_usb_get_max_packet_size device direction endpoint let open_device device = make_handle (ml_usb_open device) let close handle = if handle.state <> State_closed then begin handle.state <- State_closed; ml_usb_close handle.handle end let get_device handle = ml_usb_get_device handle.handle let claim_interface handle interface = detach handle (fun () -> ml_usb_claim_interface_job handle.handle interface) ml_usb_claim_interface_result ml_usb_claim_interface_free let release_interface handle interface = detach handle (fun () -> ml_usb_release_interface_job handle.handle interface) ml_usb_release_interface_result ml_usb_release_interface_free let kernel_driver_active handle = check_handle handle; ml_usb_kernel_driver_active handle.handle let detach_kernel_driver handle = check_handle handle; ml_usb_detach_kernel_driver handle.handle let attach_kernel_driver handle = check_handle handle; ml_usb_attach_kernel_driver handle.handle let get_configuration handle = detach handle (fun () -> ml_usb_get_configuration_job handle.handle) ml_usb_get_configuration_result ml_usb_get_configuration_free let set_configuration handle configuration = detach handle (fun () -> ml_usb_set_configuration_job handle.handle configuration) ml_usb_set_configuration_result ml_usb_set_configuration_free let set_interface_alt_setting handle interface alt_setting = detach handle (fun () -> ml_usb_set_interface_alt_setting_job handle.handle interface alt_setting) ml_usb_set_interface_alt_setting_result ml_usb_set_interface_alt_setting_free let clear_halt handle endpoint = detach handle (fun () -> ml_usb_clear_halt_job handle.handle endpoint) ml_usb_clear_halt_result ml_usb_clear_halt_free let reset_device handle = detach handle (fun () -> ml_usb_reset_device_job handle.handle) ml_usb_reset_device_result ml_usb_reset_device_free let open_device_with ~vendor_id ~product_id = Lazy.force init; match ml_usb_open_device_with_vid_pid vendor_id product_id with | Some device_handle -> make_handle device_handle | None -> failwith (Printf.sprintf "no such usb device (vendor-id=0x%04x, product-id=0x%04x)" vendor_id product_id) (* +-----------------------------------------------------------------+ | USB descriptors | +-----------------------------------------------------------------+ *) module Class = struct type t = int let per_interface = 0 let audio = 1 let communication = 2 let hid = 3 let physical = 5 let printer = 7 let ptp = 6 let image = 6 let mass_storage = 8 let hub = 9 let data = 10 let smart_card = 0x0b let content_security = 0x0d let video = 0x0e let personal_healthcare = 0x0f let diagnostic_device = 0xdc let wireless = 0xe0 let application = 0xfe let vendor_specific = 0xff let to_string n = try List.assoc n [(per_interface, "per interface"); (audio, "audio"); (communication, "communication"); (hid, "HID"); (physical, "physical"); (printer, "printer"); (image, "image"); (mass_storage, "mass storage"); (hub, "HUB"); (data, "data"); (smart_card, "smart card"); (content_security, "content security"); (video, "video"); (personal_healthcare, "personal healthcare"); (diagnostic_device, "diagnostic device"); (wireless, "wireless"); (application, "application"); (vendor_specific, "vendor specific")] with Not_found -> Printf.sprintf "0x%x02x" n end type device_descriptor = { dd_usb : int; dd_device_class : Class.t; dd_device_sub_class : int; dd_device_protocol : int; dd_max_packet_size : int; dd_vendor_id : int; dd_product_id : int; dd_device : int; dd_index_manufacturer : int; dd_index_product : int; dd_index_serial_number : int; dd_configurations : int; } type endpoint_descriptor = { ed_endpoint_address : int; ed_attributes : int; ed_max_packet_size : int; ed_interval : int; ed_refresh : int; ed_synch_address : int; } type interface_descriptor = { id_interface : int; id_alternate_setting : int; id_interface_class : Class.t; id_interface_sub_class : int; id_interface_protocol : int; id_index_interface : int; id_endpoints : endpoint_descriptor array; } type config_descriptor = { cd_configuration_value : int; cd_index_configuration : int; cd_attributes : int; cd_max_power : int; cd_interfaces : interface_descriptor array array; } external get_device_descriptor : device -> device_descriptor = "ml_usb_get_device_descriptor" external get_active_config_descriptor : device -> config_descriptor = "ml_usb_get_active_config_descriptor" external get_config_descriptor : device -> int -> config_descriptor = "ml_usb_get_config_descriptor" external get_config_descriptor_by_value : device -> int -> config_descriptor = "ml_usb_get_config_descriptor_by_value" module DT = struct type t = int let device = 0x01 let config = 0x02 let string = 0x03 let interface = 0x04 let endpoint = 0x05 let hid = 0x21 let report = 0x22 let physical = 0x23 let hub = 0x2 end (* +-----------------------------------------------------------------+ | IOs | +-----------------------------------------------------------------+ *) (* Handle the result of a transfer *) let handle_result func_name w = function | OK x -> Lwt.wakeup w x | Error error -> Lwt.wakeup_exn w (Transfer(error, func_name)) let make_timeout = function | None -> 0 | Some t -> Pervasives.truncate (t *. 1000.0) let transfer name func ~handle ~endpoint ?timeout buffer offset length = check_handle handle; if offset < 0 || length < 0 || offset > String.length buffer - length then invalid_arg ("USB." ^ name); let waiter, wakener = Lwt.task () in let transfer = func (handle.handle, endpoint, make_timeout timeout, buffer, offset, length, handle_result name wakener) in Lwt.on_cancel waiter (fun () -> ml_usb_cancel_transfer transfer); waiter let bulk_recv = transfer "bulk_recv" ml_usb_bulk_recv let bulk_send = transfer "bulk_send" ml_usb_bulk_send let interrupt_recv = transfer "interrupt_recv" ml_usb_interrupt_recv let interrupt_send = transfer "interrupt_send" ml_usb_interrupt_send let control_transfer name func ~handle ~endpoint ?timeout ?(recipient=Device) ?(request_type=Standard) ~request ~value ~index buffer offset length = check_handle handle; if offset < 0 || length < 0 || offset > String.length buffer - length then invalid_arg ("USB." ^ name); let waiter, wakener = Lwt.task () in let transfer = func (handle.handle, endpoint, make_timeout timeout, buffer, offset, length, handle_result name wakener, recipient, request_type, request, value, index) in Lwt.on_cancel waiter (fun () -> ml_usb_cancel_transfer transfer); waiter let control_recv = control_transfer "control_recv" ml_usb_control_recv let control_send = control_transfer "control_send" ml_usb_control_send let handle_iso_result func_name w = function | OK l -> Lwt.wakeup w (List.rev_map (function | OK x -> Iso_ok x | Error error -> Iso_error(error, func_name)) l) | Error error -> Lwt.wakeup_exn w (Transfer(error, func_name)) let iso_transfer name func ~handle ~endpoint ?timeout buffer offset lengths = check_handle handle; if lengths = [] then return [] else begin List.iter (fun length -> if length < 0 then invalid_arg ("USB." ^ name)) lengths; let length = List.fold_left (+) 0 lengths in if offset < 0 || offset > String.length buffer - length then invalid_arg ("USB." ^ name); let waiter, wakener = Lwt.task () in let transfer = func (handle.handle, endpoint, make_timeout timeout, buffer, offset, length, handle_iso_result name wakener, List.length lengths, lengths) in Lwt.on_cancel waiter (fun () -> ml_usb_cancel_transfer transfer); waiter end let iso_recv = iso_transfer "iso_recv" ml_usb_iso_recv let iso_send = iso_transfer "iso_send" ml_usb_iso_send (* +-----------------------------------------------------------------+ | Standard request | +-----------------------------------------------------------------+ *) module Request = struct type t = request let get_status = 0x00 let clear_feature = 0x01 let set_feature = 0x03 let set_address = 0x05 let get_descriptor = 0x06 let set_descriptor = 0x07 let get_configuration = 0x08 let set_configuration = 0x09 let get_interface = 0x0a let set_interface = 0x0b let synch_frame = 0x0c end (* +-----------------------------------------------------------------+ | Helpers | +-----------------------------------------------------------------+ *) let get_string_descriptor handle ?timeout ?lang_id ~index = let data = String.create 255 in lwt lang_id = match lang_id with | Some lang_id -> return lang_id | None -> (* Guess the default language id *) lwt n = control_recv ~handle ~endpoint:0 ?timeout ~request:Request.get_descriptor ~value:(DT.string lsl 8) ~index:0 data 0 (String.length data) in if n < 4 then raise_lwt (Failure "USB.get_string_descriptor: cannot retreive default lang id") else return (Char.code data.[2] lor (Char.code data.[3] lsl 8)) in lwt n = control_recv ~handle ~endpoint:0 ?timeout ~request:Request.get_descriptor ~value:(DT.string lsl 8 lor index) ~index:lang_id data 0 (String.length data) in let len = Char.code data.[0] in if Char.code data.[1] <> DT.string || len > n then raise_lwt (Failure "USB.get_string_descriptor: invalid control packet") else return (String.sub data 2 (len - 2)) ocaml-usb-1.3.0/examples/0000755000000000000000000000000012005550027013375 5ustar0000000000000000ocaml-usb-1.3.0/examples/myocamlbuild.ml0000644000000000000000000000732012005550027016412 0ustar0000000000000000(* * myocamlbuild.ml * --------------- * Copyright : (c) 2009, Jeremie Dimino * Licence : BSD3 * * This file is a part of ocaml-usb. *) open Printf open Ocamlbuild_plugin (* +-----------------------------------------------------------------+ | Configuration | +-----------------------------------------------------------------+ *) let try_exec command = try let _ = run_and_read command in true with _ -> false let () = if not (try_exec "ocamlfind printconf") then begin prerr_endline "ocamlfind is not available, please install it"; exit 1 end let have_native = try_exec "ocamlfind ocamlopt -version" (* +-----------------------------------------------------------------+ | Ocamlfind | +-----------------------------------------------------------------+ *) (* Packages we want to use: *) let packages = [ "lwt"; "lwt.preemptive"; "lwt.extra"; "lwt.ssl"; "lwt.glib"; "lwt.text"; "lwt.unix"; "usb"; (* Syntax extensions: *) "camlp4"; "lwt.syntax"; ] (* List of syntaxes: *) let syntaxes = [ "camlp4o"; "camlp4r" ] (* +-----------------------------------------------------------------+ | Utils | +-----------------------------------------------------------------+ *) (* Given the tag [tag] add the command line options [f] to all stages of compilatiopn but linking *) let flag_all_stages_except_link tag f = flag ["ocaml"; "compile"; tag] f; flag ["ocaml"; "ocamldep"; tag] f; flag ["ocaml"; "doc"; tag] f (* Same as [flag_all_stages_except_link] but also flag the linking stage *) let flag_all_stages tag f = flag_all_stages_except_link tag f; flag ["ocaml"; "link"; tag] f let _ = dispatch begin function | Before_options -> (* override default commands by ocamlfind ones *) let ocamlfind x = S[A"ocamlfind"; A x] in Options.ocamlc := ocamlfind "ocamlc"; Options.ocamlopt := ocamlfind "ocamlopt"; Options.ocamldep := ocamlfind "ocamldep"; Options.ocamldoc := ocamlfind "ocamldoc" | After_rules -> (* +---------------------------------------------------------+ | Virtual targets | +---------------------------------------------------------+ *) let examples = ["list_devices"] in let byte = List.map (sprintf "%s.byte") examples and native = List.map (sprintf "%s.native") examples in let virtual_rule name deps = rule name ~stamp:name ~deps (fun _ _ -> Nop) in virtual_rule "best" & if have_native then native else byte; virtual_rule "byte" & byte; virtual_rule "native" & native; (* +---------------------------------------------------------+ | Ocamlfind stuff | +---------------------------------------------------------+ *) (* When one link an OCaml binary, one should use -linkpkg *) flag ["ocaml"; "link"; "program"] & A"-linkpkg"; (* For each ocamlfind package one inject the -package option when compiling, computing dependencies, generating documentation and linking. *) List.iter (fun package -> flag_all_stages ("pkg_" ^ package) (S[A"-package"; A package])) packages; (* Like -package but for extensions syntax. Morover -syntax is useless when linking. *) List.iter (fun syntax -> flag_all_stages_except_link ("syntax_" ^ syntax) (S[A"-syntax"; A syntax])) syntaxes; | _ -> () end ocaml-usb-1.3.0/examples/list_devices.ml0000644000000000000000000000052712005550027016410 0ustar0000000000000000(* * list_devices.ml * --------------- * Copyright : (c) 2009, Jeremie Dimino * Licence : BSD3 * * This file is a part of ocaml-usb. *) open Lwt let _ = List.iter (fun dev -> Printf.printf "Bus %03d Device %03d\n" (USB.get_bus_number dev) (USB.get_device_address dev)) (USB.get_device_list ()) ocaml-usb-1.3.0/examples/_tags0000644000000000000000000000004512005550027014414 0ustar0000000000000000# -*- conf -*- <*>: thread, pkg_usb ocaml-usb-1.3.0/examples/Makefile0000644000000000000000000000077612005550027015047 0ustar0000000000000000# Makefile # -------- # Copyright : (c) 2009, Jeremie Dimino # Licence : BSD3 # # This file is a part of ocaml-usb. # Tools OCAMLFIND := ocamlfind OCAMLBUILD := ocamlbuild # Use classic-display when compiling under a terminal which does not # support ANSI sequence: ifeq ($(TERM),dumb) OCAMLBUILD += -classic-display endif all: best best: $(OCAMLBUILD) best byte: $(OCAMLBUILD) byte native: $(OCAMLBUILD) native clean: $(OCAMLBUILD) -clean .PHONY: best all byte native clean