language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
TOML | hhvm/hphp/hack/src/utils/rust/relative_path/Cargo.toml | # @generated by autocargo
[package]
name = "relative_path"
version = "0.0.0"
edition = "2021"
[lib]
path = "../relative_path.rs"
[dependencies]
arena_trait = { version = "0.0.0", path = "../../../arena_trait" }
eq_modulo_pos = { version = "0.0.0", path = "../../eq_modulo_pos" }
no_pos_hash = { version = "0.0.0", path = "../../no_pos_hash" }
ocamlrep = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" }
serde = { version = "1.0.176", features = ["derive", "rc"] }
[dev-dependencies]
pretty_assertions = { version = "1.2", features = ["alloc"], default-features = false } |
TOML | hhvm/hphp/hack/src/utils/rust/relative_path_utils/Cargo.toml | # @generated by autocargo
[package]
name = "relative_path_utils"
version = "0.0.0"
edition = "2021"
[lib]
path = "../relative_path_utils.rs"
[dependencies]
anyhow = "1.0.71"
relative_path = { version = "0.0.0", path = "../relative_path" }
[dev-dependencies]
tempfile = "3.5" |
TOML | hhvm/hphp/hack/src/utils/rust/signed_source/Cargo.toml | # @generated by autocargo
[package]
name = "signed_source"
version = "0.0.0"
edition = "2021"
[lib]
path = "../signed_source.rs"
[dependencies]
bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] }
hex = "0.4.3"
md-5 = "0.10"
once_cell = "1.12"
regex = "1.9.2"
thiserror = "1.0.43" |
OCaml | hhvm/hphp/hack/src/utils/sqlite/sqlite_utils.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Core
(* Check a sqlite result, and crash if it is invalid *)
let check_rc (db : Sqlite3.db) (rc : Sqlite3.Rc.t) : unit =
match rc with
| Sqlite3.Rc.OK
| Sqlite3.Rc.DONE ->
()
| _ ->
failwith
(Printf.sprintf
"SQLite operation failed: %s (%s)"
(Sqlite3.Rc.to_string rc)
(Sqlite3.errmsg db))
(* Gather a database and prepared statement into a tuple *)
let prepare_or_reset_statement
(db_opt_ref : Sqlite3.db option ref)
(stmt_ref : Sqlite3.stmt option ref)
(sql_command_text : string) : Sqlite3.stmt =
let db = Option.value_exn !db_opt_ref in
let stmt =
match !stmt_ref with
| Some s ->
Sqlite3.reset s |> check_rc db;
s
| None ->
let s = Sqlite3.prepare db sql_command_text in
stmt_ref := Some s;
s
in
stmt
let to_str_exn (value : Sqlite3.Data.t) : string =
match value with
| Sqlite3.Data.TEXT s -> s
| _ ->
raise
(Invalid_argument
(Printf.sprintf
"Expected a string, but was %s"
(Sqlite3.Data.to_string_debug value)))
let to_blob_exn (value : Sqlite3.Data.t) : string =
match value with
| Sqlite3.Data.BLOB s -> s
| _ ->
raise
(Invalid_argument
(Printf.sprintf
"Expected a blob, but was %s"
(Sqlite3.Data.to_string_debug value)))
(* Convert a sqlite data value to an Int64, or raise an exception *)
let to_int64_exn (value : Sqlite3.Data.t) : int64 =
match value with
| Sqlite3.Data.INT (i : int64) -> i
| _ ->
raise
(Invalid_argument
(Printf.sprintf
"Expected an int, but was %s"
(Sqlite3.Data.to_string_debug value)))
(* Coerce a value to an Int64, and ignore errors *)
let to_int64 (value : Sqlite3.Data.t) : int64 =
try to_int64_exn value with
| Invalid_argument _ -> 0L
(* Convert a sqlite data value to an ocaml int, or raise an exception *)
let to_int_exn (value : Sqlite3.Data.t) : int =
match value with
| Sqlite3.Data.INT i -> begin
match Int64.to_int i with
| Some num -> num
| None ->
raise (Invalid_argument "Attempt to coerce sqlite value to ocaml int")
end
| _ -> raise (Invalid_argument "Attempt to coerce sqlite value to ocaml int")
(* Convert a sqlite data value to an ocaml int, and ignore errors *)
let to_int (value : Sqlite3.Data.t) : int =
try to_int_exn value with
| Invalid_argument _ -> 0
(* To save a bool to sqlite have to convert it to int64 *)
let bool_to_sqlite (value : bool) : Sqlite3.Data.t =
match value with
| true -> Sqlite3.Data.INT 1L
| false -> Sqlite3.Data.INT 0L
(* Convert a sqlite value to a bool *)
let to_bool_exn (value : Sqlite3.Data.t) : bool =
match value with
| Sqlite3.Data.INT 0L -> false
| Sqlite3.Data.INT 1L -> true
| _ -> raise (Invalid_argument "Attempt to coerce sqlite value to ocaml bool")
(* Convert a sqlite data value to an ocaml int, and ignore errors *)
let to_bool (value : Sqlite3.Data.t) : bool =
try to_bool_exn value with
| Invalid_argument _ -> false
let column_str stmt idx = to_str_exn (Sqlite3.column stmt idx)
let column_blob stmt idx = to_blob_exn (Sqlite3.column stmt idx)
let column_int64 stmt idx = to_int64_exn (Sqlite3.column stmt idx)
let optional f g stmt idx =
let data = f stmt idx in
match data with
| Sqlite3.Data.NULL -> None
| _ -> Some (g data)
let column_str_option = optional Sqlite3.column to_str_exn
let column_blob_option = optional Sqlite3.column to_blob_exn
let column_int64_option = optional Sqlite3.column to_int64_exn
module StatementCache = struct
type t = {
db: Sqlite3.db;
statements: (string, Sqlite3.stmt) Hashtbl.t;
}
let make ~db = { db; statements = Hashtbl.Poly.create () }
(** Prepared statements must be finalized before we can close the database
connection, or else an exception is thrown. Call this function before
attempting `Sqlite3.close_db`. *)
let close t =
Hashtbl.iter t.statements ~f:(fun stmt ->
Sqlite3.finalize stmt |> check_rc t.db);
Hashtbl.clear t.statements
let make_stmt t query =
let stmt =
Hashtbl.find_or_add t.statements query ~default:(fun () ->
Sqlite3.prepare t.db query)
in
(* Clear any previous bindings for prepared statement parameters. *)
Sqlite3.reset stmt |> check_rc t.db;
stmt
end
module Data_shorthands = struct
let opt_text = Sqlite3.Data.opt_text
let opt_int = Sqlite3.Data.opt_int
let opt_bool = Sqlite3.Data.opt_bool
let text s = opt_text (Some s)
let int i = opt_int (Some i)
let bool b = opt_bool (Some b)
end |
TOML | hhvm/hphp/hack/src/utils/stack_limit/Cargo.toml | # @generated by autocargo
[package]
name = "stack_limit"
version = "0.0.0"
edition = "2021"
[lib]
path = "lib.rs"
[dependencies]
psm = "0.1.17"
stacker = "0.1.14" |
Rust | hhvm/hphp/hack/src/utils/stack_limit/lib.rs | // Copyright (c) 2019, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
/// Use a large enough redzone value to avoid stack overflow between
/// calls to stack_limit::maybe_grow(). This can be adjusted but
/// should be big enough to accommodate debug builds. HHVM's equivalent
/// value is RequestInfo::StackSlack, currently set to 1MiB.
const RED_ZONE: usize = 128 * 1024; // 128KiB
/// When the stack grows, allocate a new stack segment of this size.
const STACK_SIZE: usize = 16 * RED_ZONE; // 2MiB
/// Lightweight stack size tracking facility
///
/// # Usage:
/// ```
/// {
/// // casual recursion: no checks needed within RED_ZONE.
/// // Can also reset & check peak stack depth.
/// stack_limit::reset();
/// let x = stack_limit::maybe_grow(move || {
/// // fearless recursion: stack will be at least STACK_SIZE
/// // if remaining space is below RED_ZONE bytes.
/// });
/// println!("max depth {}", stack_limit::peak());
/// x
/// }
///
/// Call stack_limit::maybe_grow() along recursive paths that may otherwise
/// overflow. The called lambda continues to run on the same thread even
/// when the stack is grown.
/// ```
///
pub fn maybe_grow<T>(f: impl FnOnce() -> T) -> T {
let sp = psm::stack_pointer();
match stacker::remaining_stack() {
Some(r) if r < RED_ZONE => {
// Save old base & depth values before growing stack, and update peak.
let old = TRACKER.with(|t| {
let old = t.get();
let depth = old.depth(sp);
t.replace(Tracker {
depth,
peak: std::cmp::max(old.peak, depth),
..old
})
});
let x = stacker::grow(STACK_SIZE, || {
// Get the new base stack pointer.
TRACKER.with(|t| {
t.set(Tracker {
base: psm::stack_pointer(),
..t.get()
})
});
f()
});
TRACKER.with(|t| {
// Restore old tracker but preserve peak.
t.set(Tracker {
peak: t.get().peak,
..old
})
});
return x;
}
Some(_) => {
// No need to grow, just update peak.
TRACKER.with(|t| {
let old = t.get();
t.set(Tracker {
peak: std::cmp::max(old.peak, old.depth(sp)),
..old
})
});
}
None => {}
}
f()
}
#[derive(Debug, Clone, Copy)]
struct Tracker {
/// Highest address in current stack segment.
base: *const u8,
/// Maximum stack depth since last reset().
peak: usize,
/// Stack depth just before most recent grow().
depth: usize,
}
impl Default for Tracker {
fn default() -> Self {
Self {
base: std::ptr::null(),
peak: 0,
depth: 0,
}
}
}
impl Tracker {
fn depth(&self, sp: *const u8) -> usize {
self.depth + (self.base as usize).abs_diff(sp as usize)
}
}
pub fn reset() {
let base = psm::stack_pointer();
TRACKER.with(|t| {
t.set(Tracker {
base,
..Default::default()
});
});
}
pub fn peak() -> usize {
TRACKER.with(|t| t.get().peak)
}
thread_local! {
static TRACKER: std::cell::Cell<Tracker> = Default::default();
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
fn detect_growth() -> bool {
TRACKER.with(|t| t.get().depth != 0)
}
// Ackerman function that returns a K-sized array of result values
// to consume stack space faster.
#[inline(never)]
fn ackermann<const K: usize>(m: i64, n: i64) -> ([i64; K], bool) {
let over = detect_growth();
if m == 0 {
return ([n + 1; K], over);
}
maybe_grow(|| {
if n == 0 {
let (a, inner_over) = ackermann(m - 1, 1);
(a, over | inner_over)
} else {
let (a1, over1) = ackermann::<K>(m, n - 1);
let (a2, over2) = ackermann::<K>(m - 1, a1[0]);
(a2, over | over1 | over2)
}
})
}
// Find the lowest value of n that will encroach on RED_ZONE
fn min_n_that_overflows<const K: usize>(m: i64) -> i64 {
for n in 2..8 {
eprintln!("trying ({},{})", m, n);
if let (_, true) = ackermann::<K>(m, n) {
eprintln!("overflow at n={}", n);
return n;
}
}
0
}
fn ackermann_test<const K: usize>() -> bool {
const M: i64 = 3;
let n = min_n_that_overflows::<K>(M);
if n < 4 {
eprintln!("K={} n={} rejected", K, n);
return false;
}
// Ackermann recursion depth grows ~2x when n is increased by 1 and m is fixed,
// so this should trigger stacker::grow() but not panic or crash.
assert!(matches!(ackermann::<K>(M, n + 1), (_, true)));
true
}
#[test]
fn test() {
assert!(!detect_growth());
// Try to find a good value of K (stack bloat for each stack frame)
// so the test recurses deep enough but also terminates reasonably fast.
if ackermann_test::<1000>() {
return;
}
if ackermann_test::<500>() {
return;
}
if ackermann_test::<200>() {
return;
}
if ackermann_test::<100>() {
return;
}
if ackermann_test::<50>() {
return;
}
panic!();
}
} |
hhvm/hphp/hack/src/utils/state_loader/dune | (* -*- tuareg -*- *)
let library_entry name suffix =
Printf.sprintf
"(library
(name %s)
(wrapped false)
(modules)
(libraries %s_%s))" name name suffix
let fb_entry name =
library_entry name "fb"
let stubs_entry name =
library_entry name "stubs"
let entry is_fb name =
if is_fb then
fb_entry name
else
stubs_entry name
let () =
(* test presence of fb subfolder *)
let current_dir = Sys.getcwd () in
(* we are in src/utils/state_loader, locate src/facebook *)
let src_dir = Filename.dirname @@ Filename.dirname current_dir in
let fb_dir = Filename.concat src_dir "facebook" in
(* locate src/facebook/dune *)
let fb_dune = Filename.concat fb_dir "dune" in
let is_fb = Sys.file_exists fb_dune in
let lib_entry = entry is_fb "state_loader" in
Jbuild_plugin.V1.send lib_entry |
|
OCaml | hhvm/hphp/hack/src/utils/string/string_utils.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
exception Incorrect_format
let string_before s n = String.sub s 0 n
let string_after s n = String.sub s n (String.length s - n)
(* Returns the index of the first occurrence of string `needle` in string
`haystack`. If not found, returns -1.
An implementation of the Knuth-Morris-Pratt (KMP) algorithm. *)
let substring_index needle =
(* see Wikipedia pseudocode *)
let needle_len = String.length needle in
if needle_len = 0 then raise (Invalid_argument needle);
let table = Array.make needle_len 0 in
table.(0) <- -1;
let pos = ref 2 and cnd = ref 0 in
while !pos < needle_len do
if needle.[!pos - 1] = needle.[!cnd] then (
table.(!pos) <- !cnd + 1;
incr pos;
incr cnd
) else if !cnd > 0 then
cnd := table.(!cnd)
else (
table.(!pos) <- 0;
incr pos
)
done;
fun haystack ->
let len = String.length haystack in
let p = ref 0 in
let q = ref 0 in
while !p < len && !q < needle_len do
if haystack.[!p] = needle.[!q] then (
incr p;
incr q
) else if !q = 0 then
incr p
else
q := table.(!q)
done;
if !q >= needle_len then
!p - needle_len
else
-1
(* Return a copy of the string with prefixing string removed.
* The function is a no-op if it s does not start with prefix.
* Modeled after Python's string.lstrip.
*)
let lstrip s prefix =
let prefix_length = String.length prefix in
if Core.String.is_prefix s ~prefix then
String.sub s prefix_length (String.length s - prefix_length)
else
s
let rstrip s suffix =
let result_length = String.length s - String.length suffix in
if Core.String.is_suffix s ~suffix then
String.sub s 0 result_length
else
s
let rpartition s c =
let sep_idx = String.rindex s c in
let first = String.sub s 0 sep_idx in
let second = String.sub s (sep_idx + 1) (String.length s - sep_idx - 1) in
(first, second)
(** If s is longer than length len, return a copy of s truncated to length len. *)
let truncate len s =
if String.length s <= len then
s
else
String.sub s 0 len
(** [index_not_from_opt str i chars] is like [index_from_opt], but returns the index of the first
char in [str] after position [i] that is not in [chars] if it exists, or [None] otherwise. *)
let index_not_from_opt =
let rec helper i len str chars =
if i = len then
None
else if not (String.contains chars str.[i]) then
Some i
else
helper (i + 1) len str chars
in
(fun str i chars -> helper i (String.length str) str chars)
(** [index_not_opt str chars] is like [index_opt], but returns the index of the first char in
[str] that is not in [chars] if it exists, or [None] otherwise. *)
let index_not_opt str chars = index_not_from_opt str 0 chars
let fold_left ~f ~acc str =
let acc = ref acc in
String.iter (fun c -> acc := f !acc c) str;
!acc
let split c = Str.split (Str.regexp @@ Char.escaped c)
let split2 c s =
let parts = split c s in
match parts with
| [first; second] -> Some (first, second)
| _ -> None
let split2_exn c s =
match split2 c s with
| Some s -> s
| None -> raise Incorrect_format
(* Replaces all instances of the needle character with the replacement character
*)
let replace_char needle replacement =
String.map (fun c ->
if c = needle then
replacement
else
c)
(* Splits a string into a list of strings using "\n", "\r" or "\r\n" as
* delimiters. If the string starts or ends with a delimiter, there WILL be an
* empty string at the beginning or end of the list, like Str.split_delim does
*)
let split_into_lines str =
(* To avoid unnecessary string allocations, we're going to keep a list of
* the start index of each line and how long it is. Then, at the end, we can
* use String.sub to create the actual strings. *)
let (_, (last_start, lines)) =
fold_left
~f:(fun (idx, (start, lines)) c ->
(* For \r\n, we've already processed the newline *)
if c = '\n' && idx > 0 && str.[idx - 1] = '\r' then
(idx + 1, (idx + 1, lines))
else if c = '\n' || c = '\r' then
(idx + 1, (idx + 1, (start, idx - start) :: lines))
else
(idx + 1, (start, lines)))
~acc:(0, (0, []))
str
in
(* Reverses the list of start,len and turns them into strings *)
List.fold_left
(fun lines (start, len) -> String.sub str start len :: lines)
[]
((last_start, String.length str - last_start) :: lines)
(* Splits a string into lines, indents each non-empty line, and concats with newlines *)
let indent indent_size str =
let padding = String.make indent_size ' ' in
str
|> split_into_lines
|> List.map (fun str ->
if str = "" then
""
else
padding ^ str)
|> String.concat "\n"
(* Splits a string into a list of strings using only "\n" as a delimiter.
* If the string ends with a delimiter, an empty string representing the
* contents after the final delimiter is NOT included (unlike Str.split_delim).
*)
let split_on_newlines content =
let re = Str.regexp "[\n]" in
let lines = Str.split_delim re content in
(* don't create a list entry for the line after a trailing newline *)
match List.rev lines with
| "" :: rest -> List.rev rest
| _ -> lines
module Internal = struct
let to_list s =
let rec loop acc i =
if i < 0 then
acc
else
(loop [@tailcall]) (s.[i] :: acc) (i - 1)
in
loop [] (String.length s - 1)
let of_list l =
let s = Bytes.create (List.length l) in
List.iteri (Bytes.set s) l;
Bytes.unsafe_to_string s
end
let to_list = Internal.to_list
let of_list = Internal.of_list
module CharSet = struct
include Set.Make (Char)
let of_string str = of_list (Internal.to_list str)
let to_string set = Internal.of_list (elements set)
end
(* Levenshtein distance algorithm.
Based on the public domain implementation at
https://bitbucket.org/camlspotter/ocaml_levenshtein/src/default/
*)
let levenshtein_distance ?(upper_bound = max_int) (xs : string) (ys : string) =
let xs_len = String.length xs in
let ys_len = String.length ys in
let min3 (x : int) y z =
let m' (a : int) b =
if a <= b then
a
else
b
in
m' (m' x y) z
in
let cache = Array.init (xs_len + 1) (fun _ -> Array.make (ys_len + 1) (-1)) in
let rec d i j =
match (i, j) with
| (0, _) -> j
| (_, 0) -> i
| _ ->
let i' = i - 1 in
let cache_i = Array.unsafe_get cache i' in
let j' = j - 1 in
(match Array.unsafe_get cache_i j' with
| -1 ->
let res =
let upleft = d i' j' in
if upleft >= upper_bound then
upper_bound
else
let cost = abs (compare xs.[i'] ys.[j']) in
let upleft' = upleft + cost in
if upleft' >= upper_bound then
upper_bound
else
(* This is not tail recursive *)
min3 (d i' j + 1) (d i j' + 1) upleft'
in
Array.unsafe_set cache_i j' res;
res
| res -> res)
in
let res = min (d xs_len ys_len) upper_bound in
res |
OCaml Interface | hhvm/hphp/hack/src/utils/string/string_utils.mli | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* This `.mli` file was generated automatically. It may include extra
definitions that should not actually be exposed to the caller. If you notice
that this interface file is a poor interface, please take a few minutes to
clean it up manually, and then delete this comment once the interface is in
shape. *)
exception Incorrect_format
val string_before : string -> int -> string
val string_after : string -> int -> string
val substring_index : string -> string -> int
val lstrip : string -> string -> string
val rstrip : string -> string -> string
val rpartition : string -> char -> string * string
val truncate : int -> string -> string
val index_not_opt : string -> string -> int option
val split : char -> string -> string list
val split2 : char -> string -> (string * string) option
val split2_exn : char -> string -> string * string
val replace_char : char -> char -> string -> string
val split_into_lines : string -> string list
val indent : int -> string -> string
val split_on_newlines : string -> string list
module Internal : sig
val to_list : string -> char list
val of_list : char list -> string
end
val to_list : string -> char list
val of_list : char list -> string
module CharSet : sig
type elt = Char.t
type t = Set.Make(Char).t
val empty : t
val is_empty : t -> bool
val mem : elt -> t -> bool
val add : elt -> t -> t
val singleton : elt -> t
val remove : elt -> t -> t
val union : t -> t -> t
val inter : t -> t -> t
val diff : t -> t -> t
val compare : t -> t -> int
val equal : t -> t -> bool
val subset : t -> t -> bool
val iter : (elt -> unit) -> t -> unit
val map : (elt -> elt) -> t -> t
val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a
val for_all : (elt -> bool) -> t -> bool
val exists : (elt -> bool) -> t -> bool
val filter : (elt -> bool) -> t -> t
val partition : (elt -> bool) -> t -> t * t
val cardinal : t -> int
val elements : t -> elt list
val min_elt : t -> elt
val min_elt_opt : t -> elt option
val max_elt : t -> elt
val max_elt_opt : t -> elt option
val choose : t -> elt
val choose_opt : t -> elt option
val split : elt -> t -> t * bool * t
val find : elt -> t -> elt
val find_opt : elt -> t -> elt option
val find_first : (elt -> bool) -> t -> elt
val find_first_opt : (elt -> bool) -> t -> elt option
val find_last : (elt -> bool) -> t -> elt
val find_last_opt : (elt -> bool) -> t -> elt option
val of_list : elt list -> t
val of_string : string -> t
val to_string : t -> string
end
val levenshtein_distance : ?upper_bound:int -> string -> string -> int |
OCaml | hhvm/hphp/hack/src/utils/sys/daemon.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
external disable_ASLR : string array -> unit = "caml_disable_ASLR"
module Option = Base.Option
type 'a in_channel = Timeout.in_channel
type 'a out_channel = Stdlib.out_channel
type ('in_, 'out) channel_pair = 'in_ in_channel * 'out out_channel
type ('in_, 'out) handle = {
channels: ('in_, 'out) channel_pair;
pid: int;
}
(* Windows: ensure that the serialize/deserialize functions
for the custom block of "Unix.file_descr" are registred. *)
let () = Lazy.force Handle.init
let to_channel :
'a out_channel ->
?flags:Marshal.extern_flags list ->
?flush:bool ->
'a ->
unit =
fun oc ?(flags = []) ?flush:(should_flush = true) v ->
Marshal.to_channel oc v flags;
if should_flush then flush oc
let from_channel : ?timeout:Timeout.t -> 'a in_channel -> 'a =
(fun ?timeout ic -> Timeout.input_value ?timeout ic)
let flush : 'a out_channel -> unit = Stdlib.flush
let descr_of_in_channel : 'a in_channel -> Unix.file_descr =
Timeout.descr_of_in_channel
let descr_of_out_channel : 'a out_channel -> Unix.file_descr =
Unix.descr_of_out_channel
let cast_in ic = ic
let cast_out oc = oc
(* We cannot fork() on Windows, so in order to emulate this in a
* cross-platform way, we use create_process() and set the HH_SERVER_DAEMON
* environment variable to indicate which function the child should
* execute. On Unix, create_process() does fork + exec, so global state is
* not copied; in particular, if you have set a mutable reference the
* daemon will not see it. All state must be explicitly passed via
* environment variables; see set/get_context() below.
*
* With some factoring we could make the daemons into separate binaries
* altogether and dispense with this emulation. *)
module Entry : sig
(* All the 'untyped' operations---that are required for the
entry-points hashtable and the parameters stored in env
variable---are hidden in this sub-module, behind a 'type-safe'
interface. *)
type ('param, 'input, 'output) t
val name_of_entry : ('param, 'input, 'output) t -> string
val register :
string ->
('param -> ('input, 'output) channel_pair -> unit) ->
('param, 'input, 'output) t
val find :
('param, 'input, 'output) t ->
'param ->
('input, 'output) channel_pair ->
unit
val set_context :
('param, 'input, 'output) t ->
name:string ->
'param ->
Unix.file_descr * Unix.file_descr ->
unit
(* Note: the Entry module is not public, so this exception can only
* be used in this file.
*)
exception Context_not_found
(* Might raise {!Context_not_found} *)
val get_context :
unit ->
('param, 'input, 'output) t * 'param * ('input, 'output) channel_pair
val clear_context : unit -> unit
end = struct
type ('param, 'input, 'output) t = string
let name_of_entry name = name
(* Store functions as 'Obj.t' *)
let entry_points : (string, Obj.t) Hashtbl.t = Hashtbl.create 23
let register name f =
if Hashtbl.mem entry_points name then
Printf.ksprintf
failwith
"Daemon.register_entry_point: duplicate entry point %S."
name;
Hashtbl.add entry_points name (Obj.repr f);
name
let find name =
match Hashtbl.find_opt entry_points name with
| Some entry -> Obj.obj entry
| None -> Printf.ksprintf failwith "Unknown entry point %S" name
(** If OCAML_LANDMARKS is set, then set output file for Landmarks to a file specific to
the process which is about to be spawned. *)
let set_ocaml_landmarks process_name =
let var_name = "OCAML_LANDMARKS" in
try
let value = Unix.getenv var_name in
let landmarks_file =
let profiling_dir_name =
Filename.concat Tmp.hh_server_tmp_dir "profiling"
in
Sys_utils.mkdir_no_fail profiling_dir_name;
Filename.temp_file
~temp_dir:profiling_dir_name
(Printf.sprintf "%s." process_name)
".landmarks"
in
Unix.putenv var_name (Printf.sprintf "%s,output=%s" value landmarks_file)
with
| Not_found -> ()
let set_context entry ~name param (ic, oc) =
Unix.putenv "HH_SERVER_DAEMON" entry;
let (file, param_oc) =
Filename.open_temp_file
~mode:[Open_binary]
~temp_dir:Sys_utils.temp_dir_name
"daemon_param"
".bin"
in
Marshal.to_channel param_oc (ic, oc, param) [Marshal.Closures];
close_out param_oc;
Unix.putenv "HH_SERVER_DAEMON_PARAM" file;
set_ocaml_landmarks name;
()
exception Context_not_found
(* How this works on Unix: It may appear like we are passing file descriptors
* from one process to another here, but in_handle / out_handle are actually
* file descriptors that are already open in the current process -- they were
* created by the parent process before it did fork + exec. However, since
* exec causes the child to "forget" everything, we have to pass the numbers
* of these file descriptors as arguments.
*
* I'm not entirely sure what this does on Windows.
*
* Might raise {!Context_not_found} *)
let get_context () =
let entry =
try Unix.getenv "HH_SERVER_DAEMON" with
| Caml.Not_found -> raise Context_not_found
in
if String.equal entry "" then raise Context_not_found;
let (in_handle, out_handle, param) =
try
let file = Sys.getenv "HH_SERVER_DAEMON_PARAM" in
if String.equal file "" then raise Context_not_found;
let ic = Sys_utils.open_in_bin_no_fail file in
let res = Marshal.from_channel ic in
Sys_utils.close_in_no_fail "Daemon.get_context" ic;
Sys.remove file;
res
with
| exn ->
failwith ("Can't find daemon parameters: " ^ Printexc.to_string exn)
in
( entry,
param,
( Timeout.in_channel_of_descr in_handle,
Unix.out_channel_of_descr out_handle ) )
let clear_context () =
Unix.putenv "HH_SERVER_DAEMON" "";
Unix.putenv "HH_SERVER_DAEMON_PARAM" ""
end
type ('param, 'input, 'output) entry = ('param, 'input, 'output) Entry.t
let exec entry param ic oc =
(*
* The name "exec" is a bit of a misnomer. By the time we
* get here, the "exec" syscall has already finished and the
* process image has been replaced. We're using "exec" here to mean
* running the proper entry.
*
* Since Linux's "exec" has already completed, we can actaully set
* FD_CLOEXEC on the opened channels.
*)
let () = Unix.set_close_on_exec (descr_of_in_channel ic) in
let () = Unix.set_close_on_exec (descr_of_out_channel oc) in
let f = Entry.find entry in
try
f param (ic, oc);
exit 0
with
| e ->
prerr_endline (Printexc.to_string e);
Printexc.print_backtrace stderr;
exit 2
let register_entry_point = Entry.register
let name_of_entry = Entry.name_of_entry
let fd_of_path path =
Sys_utils.with_umask 0o111 (fun () ->
Sys_utils.mkdir_no_fail (Filename.dirname path);
Unix.openfile path [Unix.O_RDWR; Unix.O_CREAT; Unix.O_TRUNC] 0o666)
let null_fd () = fd_of_path Sys_utils.null_path
let setup_channels channel_mode =
let mk =
match channel_mode with
| `pipe -> (fun () -> Unix.pipe ())
| `socket -> (fun () -> Unix.socketpair Unix.PF_UNIX Unix.SOCK_STREAM 0)
in
let (parent_in, child_out) = mk () in
let (child_in, parent_out) = mk () in
Unix.set_close_on_exec parent_in;
Unix.set_close_on_exec parent_out;
((parent_in, child_out), (child_in, parent_out))
let descr_as_channels (descr_in, descr_out) =
let ic = Timeout.in_channel_of_descr descr_in in
let oc = Unix.out_channel_of_descr descr_out in
(ic, oc)
(* This only works on Unix, and should be avoided as far as possible. Use
* Daemon.spawn instead. *)
let fork_FOR_TESTING_ON_UNIX_ONLY
?(channel_mode = `pipe)
(type param)
(log_stdout, log_stderr)
(f : param -> ('a, 'b) channel_pair -> unit)
(param : param) : ('b, 'a) handle =
let ((parent_in, child_out), (child_in, parent_out)) =
setup_channels channel_mode
in
(* Since don't use exec, we can actually set CLOEXEC before the fork. *)
Unix.set_close_on_exec child_in;
Unix.set_close_on_exec child_out;
let (parent_in, child_out) = descr_as_channels (parent_in, child_out) in
let (child_in, parent_out) = descr_as_channels (child_in, parent_out) in
match Fork.fork () with
| -1 -> failwith "Go get yourself a real computer"
| 0 ->
(* child *)
(try
ignore (Unix.setsid ());
Timeout.close_in parent_in;
close_out parent_out;
Sys_utils.with_umask 0o111 (fun () ->
let fd = null_fd () in
Unix.dup2 fd Unix.stdin;
Unix.close fd);
Unix.dup2 log_stdout Unix.stdout;
Unix.dup2 log_stderr Unix.stderr;
if log_stdout <> Unix.stdout then Unix.close log_stdout;
if log_stderr <> Unix.stderr && log_stderr <> log_stdout then
Unix.close log_stderr;
f param (child_in, child_out);
exit 0
with
| e ->
prerr_endline (Printexc.to_string e);
Printexc.print_backtrace stderr;
exit 1)
| pid ->
(* parent *)
Timeout.close_in child_in;
close_out child_out;
{ channels = (parent_in, parent_out); pid }
let spawn
(type param input output)
?(channel_mode = `pipe)
?name
(stdin, stdout, stderr)
(entry : (param, input, output) entry)
(param : param) : (output, input) handle =
let ((parent_in, child_out), (child_in, parent_out)) =
setup_channels channel_mode
in
let name = Option.value ~default:(Entry.name_of_entry entry) name in
Entry.set_context entry ~name param (child_in, child_out);
let exe = Sys_utils.executable_path () in
let pid = Unix.create_process exe [| exe; name |] stdin stdout stderr in
Entry.clear_context ();
Unix.close child_in;
Unix.close child_out;
let close_if_open fd =
try Unix.close fd with
| Unix.Unix_error (Unix.EBADF, _, _) -> ()
in
if stdin <> Unix.stdin then close_if_open stdin;
if stdout <> Unix.stdout then close_if_open stdout;
if stderr <> Unix.stderr && stderr <> stdout then close_if_open stderr;
PidLog.log ~reason:(Entry.name_of_entry entry) ~no_fail:true pid;
{
channels =
( Timeout.in_channel_of_descr parent_in,
Unix.out_channel_of_descr parent_out );
pid;
}
(* for testing code *)
let devnull () =
let ic = Timeout.open_in "/dev/null" in
let oc = open_out "/dev/null" in
{ channels = (ic, oc); pid = 0 }
(**
* In order for the Daemon infrastructure to work, the beginning of your
* program (or very close to the beginning) must start with a call to
* check_entry_point.
*
* Details: Daemon.spawn essentially does a fork then exec of the currently
* running program. Thus, the child process will just end up running the exact
* same program as the parent if you forgot to start with a check_entry_point.
* The parent process sees this as a NOOP when its program starts, but a
* child process (from Daemon.spawn) will use this as a GOTO to its entry
* point.
*)
let check_entry_point () =
disable_ASLR Sys.argv;
try
let (entry, param, (ic, oc)) = Entry.get_context () in
Entry.clear_context ();
exec entry param ic oc
with
| Entry.Context_not_found -> ()
let close { channels = (ic, oc); _ } =
Timeout.close_in ic;
close_out oc
let force_quit h =
close h;
Sys_utils.terminate_process h.pid
let close_out = close_out
let output_string = output_string
let flush = flush
let close_in = Timeout.close_in
let input_char ic = Timeout.input_char ic
let input_value ic = Timeout.input_value ic
let start_memtracing filename =
let _tracer : Memtrace.tracer =
Memtrace.start_tracing
~context:None
~sampling_rate:Memtrace.default_sampling_rate
~filename
in
() |
OCaml Interface | hhvm/hphp/hack/src/utils/sys/daemon.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** Type-safe version of the in channel in Stdlib. *)
type 'a in_channel
(** Type-safe version of the out channel in Stdlib. *)
type 'a out_channel
type ('in_, 'out) channel_pair = 'in_ in_channel * 'out out_channel
val to_channel :
'a out_channel ->
?flags:Marshal.extern_flags list ->
?flush:bool ->
'a ->
unit
val from_channel : ?timeout:Timeout.t -> 'a in_channel -> 'a
val flush : 'a out_channel -> unit
(* This breaks the type safety, but is necessary in order to allow select() *)
val descr_of_in_channel : 'a in_channel -> Unix.file_descr
val descr_of_out_channel : 'a out_channel -> Unix.file_descr
val cast_in : 'a in_channel -> Timeout.in_channel
val cast_out : 'a out_channel -> Stdlib.out_channel
val close_out : 'a out_channel -> unit
val output_string : 'a out_channel -> string -> unit
val close_in : 'a in_channel -> unit
val input_char : 'a in_channel -> char
val input_value : 'a in_channel -> 'b
(* Spawning new process *)
(* In the absence of 'fork' on Windows, its usage must be restricted
to Unix specifics parts.
This module provides a mechanism to "spawn" new instance of the
current program, but with a custom entry point (e.g. workers,
DfindServer, ...). Then, alternate entry points should not depend
on global references that may not have been (re)initialised in the
new process.
All required data must be passed through the typed channels.
associated to the spawned process.
*)
(** Alternate entry points *)
type ('param, 'input, 'output) entry
(** Alternate entry points must be registered at toplevel, i.e.
every call to `Daemon.register_entry_point` must have been
evaluated when `Daemon.check_entry_point` is called at the
beginning of `ServerMain.start`. *)
val register_entry_point :
string ->
('param -> ('input, 'output) channel_pair -> unit) ->
('param, 'input, 'output) entry
val name_of_entry : ('param, 'input, 'output) entry -> string
(** Handler upon spawn and forked process. *)
type ('in_, 'out) handle = {
channels: ('in_, 'out) channel_pair;
pid: int;
}
(** for unit tests *)
val devnull : unit -> ('a, 'b) handle
val fd_of_path : string -> Unix.file_descr
val null_fd : unit -> Unix.file_descr
(** Fork and run a function that communicates via the typed channels. Doesn't work with start_memtracing. *)
val fork_FOR_TESTING_ON_UNIX_ONLY :
?channel_mode:[ `pipe | `socket ] ->
(* Where the daemon's output should go *)
Unix.file_descr * Unix.file_descr ->
('param -> ('input, 'output) channel_pair -> unit) ->
'param ->
('output, 'input) handle
(** Spawn a new instance of the current process, and execute the
alternate entry point. *)
val spawn :
?channel_mode:[ `pipe | `socket ] ->
?name:string ->
(* Where the daemon's input and output should go *)
Unix.file_descr * Unix.file_descr * Unix.file_descr ->
('param, 'input, 'output) entry ->
'param ->
('output, 'input) handle
(** Close the typed channels associated to a 'spawned' child. *)
val close : ('a, 'b) handle -> unit
(** Force quit the spawned child process and close the associated typed channels. *)
val force_quit : ('a, 'b) handle -> unit
(** This will start the current process memtracing to the named file. It is suggested
that any process which is interesting to trace should call this function near the start
of its lifetime, so long as `--config memtrace_dir` is set. Callers are responsible
for constructing a filename that's in that directory and is unique with respect to
all other filenames used by the hh_server instance. The conventional suffix is ".ctf".
Recent versions of the memtrace library will suppress tracing after fork, but in
case we don't have the most recent version, then better not to fork!
However, it's okay to call Daemon.spawn while memtracing. *)
val start_memtracing : string -> unit
(** Main function, that executes an alternate entry point.
It should be called only once, just before the main entry point.
This function does not return when a custom entry point is selected. *)
val check_entry_point : unit -> unit |
C | hhvm/hphp/hack/src/utils/sys/daemon_stubs.c | /* Copyright (c) 2021, Meta Inc. All rights reserved. */
#include <caml/mlvalues.h>
#include <caml/memory.h>
#if defined(__linux__)
# include <sys/personality.h>
# include <unistd.h>
#endif
/* Programs using the Daemon module tend to rely heavily on the
ability to pass closures to the instances of themselves that they
spawn. Unfortunately, this technique is unstable in the presence of
ASLR (address space layout randomization) (when unmarshaling
closures doesn't work e.g. for this reason or another, you'll see
it manifest as an exception along the lines of
```
(Failure
"Can't find daemon parameters: (Failure \"input_value: unknown code module <DIGEST>\")")
```
where <DIGEST> is a SHA-1 hash value).
This function, if necessary, replaces the current process in which
ASLR is enabled with a new instance of itself in which ASLR is
disabled. */
CAMLprim value caml_disable_ASLR(value args) {
CAMLparam1(args);
#if defined(__linux__)
/* Allow users to opt out of this behavior in restricted environments, e.g.
docker with default seccomp profile */
if (getenv("HHVM_DISABLE_PERSONALITY")) {
CAMLreturn(Val_unit);
}
int res = personality((unsigned long)0xffffffff);
if (res == -1) {
fprintf(stderr, "error: daemon_stubs.c: caml_disable_ASLR: failed to get personality\n");
exit(1);
}
if (! (res & ADDR_NO_RANDOMIZE)) {
res = personality((unsigned long)(res | ADDR_NO_RANDOMIZE));
if(res == -1) {
fprintf(stderr, "error: daemon_stubs.c: caml_disable_ASLR: failed to set personality\n");
exit(1);
}
int i, argc = Wosize_val(args);
char const** argv = (char const**)(malloc ((argc + 1) * sizeof(char const*)));
for (i = 0; i < argc; ++i) {
argv[i] = String_val(Field(args, i));
}
argv[argc] = (char const*)0;
(void)execv(argv[0], (char *const *)argv); /* Usually no return. */
}
#endif
/* Reachable on MacOS, or if the execv fails. */
CAMLreturn(Val_unit);
} |
hhvm/hphp/hack/src/utils/sys/dune | (library
(name sys_utils)
(wrapped false)
(flags
(:standard -safe-string))
(libraries collections disk exec_command memtrace str unix utils_core)
(foreign_stubs
(language c)
(names
daemon_stubs
files
gc_profiling
getrusage
handle_stubs
priorities
processor_info
realpath
sysinfo))
(preprocess
(pps lwt_ppx ppx_deriving.std))) |
|
C | hhvm/hphp/hack/src/utils/sys/files.c | /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*/
#define CAML_NAME_SPACE
#include <caml/fail.h>
#include <caml/memory.h>
#include <caml/unixsupport.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#ifndef _WIN32
#include <sys/time.h>
#endif
#ifdef __linux__
#include <linux/magic.h>
#include <sys/vfs.h>
#endif
void hh_lutimes(value filename_v) {
CAMLparam1(filename_v);
#ifdef _WIN32
/* Not implemented */
CAMLreturn0;
#else
const char* filename = String_val(filename_v);
int success = lutimes(filename, NULL);
if (success != 0) {
caml_failwith("lutimes failed");
}
#endif
CAMLreturn0;
}
value hh_is_nfs(value filename_v) {
CAMLparam1(filename_v);
#ifdef __linux__
struct statfs buf;
const char* filename = String_val(filename_v);
int success = statfs(filename, &buf);
if (success != 0) {
caml_failwith("statfs failed");
}
switch (buf.f_type) {
#ifdef CIFS_MAGIC_NUMBER
case CIFS_MAGIC_NUMBER:
#endif
case NFS_SUPER_MAGIC:
case SMB_SUPER_MAGIC:
CAMLreturn(Val_bool(1));
default:
CAMLreturn(Val_bool(0));
}
#endif
CAMLreturn(Val_bool(0));
}
// C89 spec: "The primary use of the freopen function is to change the file associated
// with a standard text stream (stderr, stdin, or stdout)" e.g. freopen("newout.txt", "a", stdout)
// It returns NULL upon failure, or the third parameter upon success.
// The right way to use freopen is to ignore the returned value in success case:
// https://stackoverflow.com/questions/584868/rerouting-stdin-and-stdout-from-c/586416#586416
void hh_freopen(value filename_v, value mode_v, value fd_v) {
CAMLparam3(filename_v, mode_v, fd_v);
const char *filename = String_val(filename_v);
const char *mode = String_val(mode_v);
int fd = Int_val(fd_v);
FILE *fp = fdopen(fd, mode);
if (fp == NULL) {
unix_error(errno, "fdopen", filename_v); // raises Unix.error
}
FILE *r = freopen(filename, mode, fp);
if (r == NULL) {
unix_error(errno, "freopen", filename_v); // raises Unix.error
}
CAMLreturn0;
}
// This is like Unix.openfile https://github.com/ocaml/ocaml/blob/trunk/otherlibs/unix/open_unix.c
// except it passes flag O_TMPFILE creates an inode without a filename.
// (there's no way to pass O_TMPFILE into Unix.openfile).
CAMLprim value hh_open_tmpfile(value rd_v, value wr_v, value dir_v, value file_perm_v) {
CAMLparam4(rd_v, wr_v, dir_v, file_perm_v);
const int file_perm = Int_val(file_perm_v);
const int rd = Bool_val(rd_v);
const int wr = Bool_val(wr_v);
int flags = __O_TMPFILE | ((rd && wr) ? O_RDWR : rd ? O_RDONLY : wr ? O_WRONLY : 0);
// Unix.openfile also uses caml_{enter,leave}_blocking_section to allow domain
// concurrency while this blocking operation is underway. That's not needed for
// correctness, so I'll skip it.
// The following line checks that it's a c-safe string. Because it's what Unix.openfile does.
// Implementation at https://github.com/ocaml/ocaml/blob/trunk/otherlibs/unix/unixsupport_unix.c
caml_unix_check_path(dir_v, "hh_open_tmpfile");
const char *dir = String_val(dir_v);
int fd = open(dir, flags, file_perm);
if (fd == -1) uerror("hh_open_tmpfile", dir_v);
CAMLreturn (Val_int(fd));
} |
OCaml | hhvm/hphp/hack/src/utils/sys/fork.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
(* Forking duplicates data in all buffers, so we flush them beforehand to avoid
* writing the same thing twice.
*
* Note: by default, this only clears ocaml's internal buffers (via flush_all).
* If your process has its own buffers in the program state, those must be
* cleared by registering a callback with `on_fork` below to reliably avoid
* writing those buffers twice as well. *)
let pre_fork_callbacks : (unit -> unit) list ref = ref [Stdlib.flush_all]
(** Sometimes it is more convenient to clear buffers in the children (to
* avoid the double writing of data) instead of the parent on a successful
* fork. We store those callbacks here. *)
let post_fork_child_callbacks : (unit -> unit) list ref = ref []
let on_fork f = pre_fork_callbacks := f :: !pre_fork_callbacks
let post_fork_child f =
post_fork_child_callbacks := f :: !post_fork_child_callbacks
(* You should always use this instead of Unix.fork, so that the callbacks get
* invoked *)
let fork () =
List.iter !pre_fork_callbacks ~f:(fun f -> f ());
match Unix.fork () with
| 0 ->
List.iter !post_fork_child_callbacks ~f:(fun f -> f ());
0
| i -> i
(* should only be called from hh_server, which initializes the PidLog *)
let fork_and_log ?reason () =
let result = fork () in
(match result with
| -1 -> ()
| 0 -> PidLog.close ()
| pid -> PidLog.log ?reason pid);
result
let fork_and_may_log ?reason () =
match reason with
| None -> fork ()
| Some _ -> fork_and_log ?reason () |
C | hhvm/hphp/hack/src/utils/sys/gc_profiling.c | /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the "hack" directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#define CAML_NAME_SPACE
#include <caml/alloc.h>
#include <caml/callback.h>
#include <caml/memory.h>
#include <caml/misc.h>
#include <caml/mlvalues.h>
#include <stdio.h>
#include <sys/time.h>
static double minor_start_time = 0.0;
static double major_start_time = 0.0;
static double minor_time = 0.0;
static double major_time = 0.0;
void minor_begin() {
struct timeval time;
gettimeofday(&time, NULL);
minor_start_time = time.tv_sec + ((double)time.tv_usec / 1000000);
}
void major_begin() {
struct timeval time;
gettimeofday(&time, NULL);
major_start_time = time.tv_sec + ((double)time.tv_usec / 1000000);
}
void minor_end() {
struct timeval time;
gettimeofday(&time, NULL);
minor_time +=
time.tv_sec + ((double)time.tv_usec / 1000000) - minor_start_time;
}
/**
* This seems to be called every time that caml_major_collection_slice is
* called, which is quite often. I don't 100% understand the major collection,
* but it seems to have phases and is executed over multiple calls. If I run
* `bin/flow check .`, this will be called around 579 times totaling 0.0028s
* (compared to 291 minor collections totaling 0.057s), though the gc stats will
* claim only a single major collection happened. If I use caml_gc_phase to only
* fire the callback when it equals 2 (Phase_sweep, the last phase), it is
* called 3 times for 0.0008s.
*/
void major_end() {
struct timeval time;
gettimeofday(&time, NULL);
major_time +=
time.tv_sec + ((double)time.tv_usec / 1000000) - major_start_time;
}
void hh_start_gc_profiling() {
major_time = 0.0;
minor_time = 0.0;
caml_minor_gc_begin_hook = minor_begin;
caml_minor_gc_end_hook = minor_end;
caml_major_slice_begin_hook = major_begin;
caml_major_slice_end_hook = major_end;
}
/**
* I (glevi) originally used to allow more complicated callbacks for the end of
* GC. However, I was observing weird crashes (including marshal'ing things
* outside of the heap), so I switched to super simple callbacks which
* definitely don't allocate anything during GC
*/
value hh_get_gc_time() {
caml_minor_gc_begin_hook = NULL;
caml_minor_gc_end_hook = NULL;
caml_major_slice_begin_hook = NULL;
caml_major_slice_end_hook = NULL;
CAMLparam0();
CAMLlocal1(ret);
ret = caml_alloc_tuple(2);
Store_field(ret, 0, caml_copy_double(major_time));
Store_field(ret, 1, caml_copy_double(minor_time));
CAMLreturn(ret);
} |
C | hhvm/hphp/hack/src/utils/sys/getrusage.c | /**
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*/
#include <caml/alloc.h>
#include <caml/memory.h>
#ifdef _WIN32
#include <caml/fail.h>
#include <windows.h>
value hh_getrusage(void) {
caml_failwith("getrusage is unimplemented for Windows");
}
#else
#include <sys/resource.h>
value hh_getrusage(void) {
CAMLparam0();
CAMLlocal1(result);
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
result = caml_alloc_tuple(14);
/* maximum resident set size */
Store_field(result, 0, Val_long(ru.ru_maxrss));
/* integral shared memory size */
Store_field(result, 1, Val_long(ru.ru_ixrss));
/* integral unshared data size */
Store_field(result, 2, Val_long(ru.ru_idrss));
/* integral unshared stack size */
Store_field(result, 3, Val_long(ru.ru_isrss));
/* page reclaims (soft page faults) */
Store_field(result, 4, Val_long(ru.ru_minflt));
/* page faults (hard page faults) */
Store_field(result, 5, Val_long(ru.ru_majflt));
/* swaps */
Store_field(result, 6, Val_long(ru.ru_nswap));
/* block input operations */
Store_field(result, 7, Val_long(ru.ru_inblock));
/* block output operations */
Store_field(result, 8, Val_long(ru.ru_oublock));
/* IPC messages sent */
Store_field(result, 9, Val_long(ru.ru_msgsnd));
/* IPC messages received */
Store_field(result, 10, Val_long(ru.ru_msgrcv));
/* signals received */
Store_field(result, 11, Val_long(ru.ru_nsignals));
/* voluntary context switches */
Store_field(result, 12, Val_long(ru.ru_nvcsw));
/* involuntary context switches */
Store_field(result, 13, Val_long(ru.ru_nivcsw));
CAMLreturn(result);
}
#endif |
OCaml | hhvm/hphp/hack/src/utils/sys/handle.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* On Win32, unwrap the handle from the 'abstract block' representing
the file descriptor otherwise it can't be marshalled or passed as
an integer command-line argument. *)
type handle = int
external raw_get_handle : Unix.file_descr -> handle
= "caml_hh_worker_get_handle"
[@@noalloc]
external raw_wrap_handle : handle -> Unix.file_descr
= "caml_hh_worker_create_handle"
external win_setup_handle_serialization : unit -> unit
= "win_setup_handle_serialization"
let init =
(* Windows: register the serialize/desarialize functions
for the custom block of "Unix.file_descr". *)
lazy (win_setup_handle_serialization ())
let () = Lazy.force init
let () = assert (Sys.win32 || Obj.is_int (Obj.repr Unix.stdin))
let get_handle =
if Sys.win32 then
raw_get_handle
else
Obj.magic
let wrap_handle =
if Sys.win32 then
raw_wrap_handle
else
Obj.magic
let to_in_channel h = wrap_handle h |> Unix.in_channel_of_descr
let to_out_channel h = wrap_handle h |> Unix.out_channel_of_descr |
C | hhvm/hphp/hack/src/utils/sys/handle_stubs.c | /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*/
#define CAML_NAME_SPACE
#include <caml/mlvalues.h>
#include <caml/unixsupport.h>
#include <caml/intext.h>
#include <caml/custom.h>
#include <stdio.h>
// Ideally these would live in a handle.h file but our internal build system
// can't support that at the moment. These are shared with hh_shared.c
#ifdef _WIN32
#define Val_handle(fd) (win_alloc_handle(fd))
#else
#define Handle_val(fd) (Long_val(fd))
#define Val_handle(fd) (Val_long(fd))
#endif
value caml_hh_worker_get_handle(value x) {
return Val_long(Handle_val(x));
}
value caml_hh_worker_create_handle(value x) {
#ifdef _WIN32
return Val_handle((HANDLE)Long_val(x));
#else
return Val_handle(Long_val(x));
#endif
}
#ifdef _WIN32
static void win_handle_serialize(value h, uintnat *wsize_32, uintnat *wsize_64) {
caml_serialize_int_8((int64_t)Handle_val(h));
caml_serialize_int_1(Descr_kind_val(h));
caml_serialize_int_1(CRT_fd_val(h));
caml_serialize_int_1(Flags_fd_val(h));
*wsize_32 = sizeof(struct filedescr);
*wsize_64 = sizeof(struct filedescr);
}
static uintnat win_handle_deserialize(void * dst) {
struct filedescr *h= (struct filedescr *)dst;
h->fd.handle = (HANDLE)caml_deserialize_sint_8();
h->kind = caml_deserialize_uint_1();
h->crt_fd = caml_deserialize_sint_1();
h->flags_fd = caml_deserialize_uint_1();
return sizeof(struct filedescr);
}
#endif
value win_setup_handle_serialization(value unit) {
(void)unit; // Dear compiler, please ignore this param
#ifdef _WIN32
value handle = win_alloc_handle((HANDLE)0); // Dummy handle
struct custom_operations *win_handle_ops = (struct custom_operations *)Field(handle, 0);
win_handle_ops->serialize = win_handle_serialize;
win_handle_ops->deserialize = win_handle_deserialize;
caml_register_custom_operations(win_handle_ops);
#endif
return Val_unit;
} |
OCaml | hhvm/hphp/hack/src/utils/sys/lock.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
let lock_fds = ref SMap.empty
(**
* Basic lock operations.
*
* We use these for two reasons:
* 1. making sure we are only running one instance of hh_server per person on a given dev box
* 2. giving a way to hh_client to check if a server is running.
*)
let register_lock lock_file =
let _ = Sys_utils.mkdir_no_fail (Filename.dirname lock_file) in
Sys_utils.with_umask 0o111 (fun () ->
let fd = Unix.descr_of_out_channel (open_out lock_file) in
let st = Unix.fstat fd in
lock_fds := SMap.add lock_file (fd, st) !lock_fds;
fd)
(**
* Grab or check if a file lock is available.
*
* Returns true if the lock is/was available, false otherwise.
*)
let _operations lock_file op : bool =
try
let fd =
match SMap.find_opt lock_file !lock_fds with
| None -> register_lock lock_file
| Some (fd, st) ->
let identical_file =
try
(* Note: I'm carefully avoiding opening another fd to the
* lock_file when doing this check, because closing any file
* descriptor to a given file will release the locks on *all*
* file descriptors that point to that file. Fortunately, stat()
* gets us our information without opening a fd *)
let current_st = Unix.stat lock_file in
Unix.(
st.st_dev = current_st.st_dev && st.st_ino = current_st.st_ino)
with
| _ -> false
in
if not (Sys.win32 || identical_file) then
(* Looks like someone (tmpwatch?) deleted the lock file; don't
* create another one, because our socket is probably gone too.
* We are dead in the water. *)
raise Exit
else
fd
in
let _ =
try Unix.lockf fd op 1 with
| _ when Sys.win32 && (op = Unix.F_TLOCK || op = Unix.F_TEST) ->
(* On Windows, F_TLOCK and F_TEST fail if we have the lock ourself *)
(* However, we then are the only one to be able to write there. *)
ignore (Unix.lseek fd 0 Unix.SEEK_SET : int);
(* If we don't have the lock, the following 'write' will
throw an exception. *)
let wb = Unix.write fd (Bytes.make 1 ' ') 0 1 in
(* When not throwing an exception, the current
implementation of `Unix.write` always return `1`. But let's
be protective against semantic changes, and better fails
than wrongly assume that we own a lock. *)
assert (wb = 1)
in
true
with
| _ -> false
(**
* Grabs the file lock and returns true if it the lock was grabbed
*)
let grab lock_file : bool = _operations lock_file Unix.F_TLOCK
(**
* Releases a file lock.
*)
let release lock_file : bool = _operations lock_file Unix.F_ULOCK
let blocking_grab_then_release lock_file =
ignore (_operations lock_file Unix.F_LOCK);
ignore (release lock_file)
(**
* Gets the server instance-unique integral fd for a given lock file.
*)
let fd_of lock_file : int =
match SMap.find_opt lock_file !lock_fds with
| None -> -1
| Some fd -> Obj.magic fd
(**
* Check if the file lock is available without grabbing it.
* Returns true if the lock is free.
*)
let check lock_file : bool = _operations lock_file Unix.F_TEST |
OCaml Interface | hhvm/hphp/hack/src/utils/sys/lock.mli | (*
* Copyright (c) 2017, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val grab : string -> bool
val release : string -> bool
val blocking_grab_then_release : string -> unit
val fd_of : string -> int
val check : string -> bool |
OCaml | hhvm/hphp/hack/src/utils/sys/path.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Reordered_argument_collections
include Stdlib.Sys
module S = struct
type t = string [@@deriving show]
let equal = String.equal
let compare = String.compare
let to_string x = x
end
type t = S.t [@@deriving show]
let dummy_path : t = ""
let cat = Sys_utils.cat
let equal = S.equal
let compare = S.compare
let dirname = Filename.dirname
let basename = Filename.basename
(**
* Resolves a path (using realpath)
*
* The advantage of using a path instead of strings is that you
* don't need to care about symlinks or trailing slashes: each
* path gets normalized by calling realpath.
*
* A few things to keep in mind:
* - paths are always absolute. So the empty string "" becomes
* the current directory (in absolute)
*)
let make path =
match Sys_utils.realpath path with
| Some path -> path
| None -> (* assert false? *) path
(**
* Creates a Path without running it through `realpath`. This is unsafe because
* it doesn't normalize symlinks, trailing slashes, or relative paths. The path
* you pass here must be absolute, and free of symlinks (including ../).
*)
let make_unsafe path = path
let to_string path = path
let concat path more = make (Filename.concat path more)
let parent path =
if is_directory path then
make (concat path Filename.parent_dir_name)
else
make (Filename.dirname path)
let output = Stdlib.output_string
let slash_escaped_string_of_path path =
let buf = Buffer.create (String.length path) in
String.iter
~f:(fun ch ->
match ch with
| '\\' -> Buffer.add_string buf "zB"
| ':' -> Buffer.add_string buf "zC"
| '/' -> Buffer.add_string buf "zS"
| '\x00' -> Buffer.add_string buf "z0"
| 'z' -> Buffer.add_string buf "zZ"
| _ -> Buffer.add_char buf ch)
path;
Buffer.contents buf
let path_of_slash_escaped_string str =
let length = String.length str in
let buf = Buffer.create length in
let rec consume i =
if i >= length then
()
else
let replacement =
if i < length - 1 && Char.equal str.[i] 'z' then
match str.[i + 1] with
| 'B' -> Some '\\'
| 'C' -> Some ':'
| 'S' -> Some '/'
| '0' -> Some '\x00'
| 'Z' -> Some 'z'
| _ -> None
else
None
in
let (c, next_i) =
match replacement with
| Some r -> (r, i + 2)
| None -> (str.[i], i + 1)
in
Buffer.add_char buf c;
consume next_i
in
consume 0;
make (Buffer.contents buf)
module Set = Reordered_argument_set (Caml.Set.Make (S)) |
OCaml Interface | hhvm/hphp/hack/src/utils/sys/path.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Reordered_argument_collections
module S : sig
type t = private string [@@deriving show]
val equal : t -> t -> bool
val compare : t -> t -> int
val to_string : t -> string
end
type t = S.t [@@deriving show]
val dummy_path : t
val make : string -> t
val make_unsafe : string -> t
val to_string : t -> string
val file_exists : t -> bool
val is_directory : t -> bool
val equal : t -> t -> bool
val compare : t -> t -> int
val concat : t -> string -> t
val chdir : t -> unit
val dirname : t -> t
val basename : t -> string
val getcwd : unit -> t
val output : out_channel -> t -> unit
val remove : t -> unit
val parent : t -> t
val executable_name : t
val cat : t -> string
val slash_escaped_string_of_path : t -> string
val path_of_slash_escaped_string : string -> t
module Set : module type of Reordered_argument_set (Set.Make (S)) |
OCaml | hhvm/hphp/hack/src/utils/sys/pidLog.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Core
module Unix = Caml_unix
let log_oc = ref None
let enabled = ref true
let disable () = enabled := false
let init pids_file =
assert (Option.is_none !log_oc);
Sys_utils.with_umask 0o111 (fun () ->
Sys_utils.mkdir_no_fail (Filename.dirname pids_file);
let oc = Out_channel.create pids_file in
log_oc := Some oc;
Unix.(set_close_on_exec (descr_of_out_channel oc)))
let log ?reason ?(no_fail = false) pid =
if !enabled then
let pid = Sys_utils.pid_of_handle pid in
let reason =
match reason with
| None -> "unknown"
| Some s -> s
in
match !log_oc with
| None when no_fail -> ()
| None -> failwith "Can't write pid to uninitialized pids log"
| Some oc -> Printf.fprintf oc "%d\t%s\n%!" pid reason
exception FailedToGetPids
let get_pids pids_file =
try
let ic = In_channel.create pids_file in
let results = ref [] in
begin
try
while true do
let row = In_channel.input_line ic in
match row with
| None -> raise End_of_file
| Some row ->
if Str.string_match (Str.regexp "^\\([0-9]+\\)\t\\(.+\\)") row 0
then
let pid = int_of_string (Str.matched_group 1 row) in
let reason = Str.matched_group 2 row in
results := (pid, reason) :: !results
done
with
| End_of_file -> ()
end;
In_channel.close ic;
List.rev !results
with
| Sys_error _ -> raise FailedToGetPids
let close () =
Option.iter !log_oc ~f:Out_channel.close;
log_oc := None |
OCaml | hhvm/hphp/hack/src/utils/sys/printSignal.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
let string_of_signal n =
match n with
| _ when n = Sys.sigabrt -> "sigabrt"
| _ when n = Sys.sigalrm -> "sigalrm"
| _ when n = Sys.sigfpe -> "sigfpe"
| _ when n = Sys.sighup -> "sighup"
| _ when n = Sys.sigill -> "sigill"
| _ when n = Sys.sigint -> "sigint"
| _ when n = Sys.sigkill -> "sigkill"
| _ when n = Sys.sigpipe -> "sigpipe"
| _ when n = Sys.sigquit -> "sigquit"
| _ when n = Sys.sigsegv -> "sigsegv"
| _ when n = Sys.sigterm -> "sigterm"
| _ when n = Sys.sigusr1 -> "sigusr1"
| _ when n = Sys.sigusr2 -> "sigusr2"
| _ when n = Sys.sigchld -> "sigchld"
| _ when n = Sys.sigcont -> "sigcont"
| _ when n = Sys.sigstop -> "sigstop"
| _ when n = Sys.sigtstp -> "sigtstp"
| _ when n = Sys.sigttin -> "sigttin"
| _ when n = Sys.sigttou -> "sigttou"
| _ when n = Sys.sigvtalrm -> "sigvtalrm"
| _ when n = Sys.sigprof -> "sigprof"
(**** Signals added in 4.03 ****)
| _ when n = Sys.sigbus -> "sigbus"
| _ when n = Sys.sigpoll -> "sigpoll"
| _ when n = Sys.sigsys -> "sigsys"
| _ when n = Sys.sigtrap -> "sigtrap"
| _ when n = Sys.sigurg -> "sigurg"
| _ when n = Sys.sigxcpu -> "sigxcpu"
| _ when n = Sys.sigxfsz -> "sigxfsz" (*******************************)
(* The integer value in the OCaml signal Sys.sigkill is -7. In POSIX, sigkill is 9. This
* illustrates that it's generally a bad idea to interact with the integer values inside of
* OCaml's signals. To be honest, I'm not sure why OCaml doesn't just use some abstract type for
* its signals, since you generally can't use the integer values directly *)
| _ -> Printf.sprintf "unknown signal %d" n |
C | hhvm/hphp/hack/src/utils/sys/priorities.c | /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*/
#define CAML_NAME_SPACE
#include <caml/mlvalues.h>
#include <caml/unixsupport.h>
#include <caml/memory.h>
#include <caml/alloc.h>
#include <caml/fail.h>
#undef CAML_NAME_SPACE
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#endif
/*****************************************************************************/
/* Sets CPU and IO priorities. */
/*****************************************************************************/
// glibc refused to add ioprio_set, sigh.
// https://sourceware.org/bugzilla/show_bug.cgi?id=4464
#define IOPRIO_CLASS_SHIFT 13
#define IOPRIO_PRIO_VALUE(cl, dat) (((cl) << IOPRIO_CLASS_SHIFT) | (dat))
#define IOPRIO_WHO_PROCESS 1
#define IOPRIO_CLASS_BE 2
value hh_set_priorities(value cpu_prio_val, value io_prio_val) {
CAMLparam2(cpu_prio_val, io_prio_val);
int cpu_prio = Long_val(cpu_prio_val);
int io_prio = Long_val(io_prio_val);
// No need to check the return value, if we failed then whatever.
#ifdef __linux__
syscall(
SYS_ioprio_set,
IOPRIO_WHO_PROCESS,
getpid(),
IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, io_prio)
);
#endif
#ifdef _WIN32
SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
// One might also try: PROCESS_MODE_BACKGROUND_BEGIN
#else
int dummy = nice(cpu_prio);
(void)dummy; // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509
#endif
CAMLreturn(Val_unit);
} |
OCaml | hhvm/hphp/hack/src/utils/sys/proc.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type proc_stat = {
cmdline: string;
ppid: int;
}
let cmdline_delimiter_re = Str.regexp "\x00"
(* Takes a PID and returns the full command line the process was started with *)
let get_cmdline (pid : int) : (string, string) result =
(* NOTE: Linux's OS type is Unix *)
if not Sys.unix then
Error "Getting cmdline is not implemented for non-Unix OS types"
else
let cmdline_path = Printf.sprintf "/proc/%d/cmdline" pid in
try
let line =
Str.global_replace cmdline_delimiter_re " " (Disk.cat cmdline_path)
in
Ok line
with
| e ->
let error =
Printf.sprintf
"No 'cmdline' file found for PID %d: '%s'"
pid
(Exn.to_string e)
in
Error error
(* Takes a PID and returns the information about the process, including
the name and the PID of the parent process (PPID) *)
let get_proc_stat (pid : int) : (proc_stat, string) result =
(* NOTE: Linux's OS type is Unix *)
if not Sys.unix then
Error "Getting cmdline is not implemented for non-Unix OS types"
else
let stat_path = Printf.sprintf "/proc/%d/stat" pid in
try
let stat = Scanf.Scanning.from_string (Disk.cat stat_path) in
try
let record =
Scanf.bscanf
stat
"%d (%s@) %c %d"
(fun _my_pid _comm _state ppid : (proc_stat, string) result ->
match get_cmdline pid with
| Ok cmdline -> Ok { cmdline; ppid }
| Error err -> Error err)
in
record
with
| e ->
let error =
Printf.sprintf
"Error reading 'stat' for PID %d: %s"
pid
(Exn.to_string e)
in
Error error
with
| e ->
let error =
Printf.sprintf
"No 'stat' file found for PID %d: '%s'"
pid
(Exn.to_string e)
in
Error error
(** This returns the cmdlines of all callers in the PPID stack, with the ancestor caller at head
e.g. "/usr/lib/systemd/systemd --system" and the cmdline of the [pid] parameter at the tail.
There's the theoretical possibility of failng to read a /proc/{PID}/stat
or /proc/{PID}/cmdline on linux, and the real eventuality that it doesn't work
outside linux -- in these cases the returned string list contains strings that start with
the word "ERROR". *)
let get_proc_stack
?(max_depth : int = -1) ?(max_length : int = Int.max_value) (pid : int) :
string list =
let prepare_cmdline (cmdline : string) : string =
let cmdline = Caml.String.trim cmdline in
if max_length >= String.length cmdline then
cmdline
else
Caml.String.trim (String.sub cmdline ~pos:0 ~len:max_length) ^ "..."
in
(* We could have max_depth as optional, but then everybody would have to pass in None *)
(* let max_depth = match max_depth with | None -> -1 | Some max_depth -> max_depth in *)
let rec build_proc_stack (curr_pid : int) (acc : string list) (counter : int)
: string list =
if curr_pid = 0 then
acc
else if counter = max_depth then
acc
else
match get_proc_stat curr_pid with
| Ok stat ->
build_proc_stack
stat.ppid
(prepare_cmdline stat.cmdline :: acc)
(counter + 1)
| Error e -> ["ERROR " ^ e]
in
build_proc_stack pid [] 0
(** This heuristic function judges whether [init_proc_stack] indicates an hh binary
that was invoked from an interactive shell, rather than from some script/tool. *)
let is_likely_from_interactive_shell (init_proc_stack : string list) : bool =
(* Things at the bottom of the stack like "/usr/local/bin/hh_client" indicate
the actual binary, or "/bin/bash /usr/local/bin/hh" a trivial wrapper around it.
We will ignore these. *)
let is_skippable_hh_cmdline (cmdline : string) : bool =
match String.split cmdline ~on:' ' with
| [] -> false
| "/bin/bash" :: cmd :: _
| cmd :: _ ->
List.mem
["hh"; "hh_client"; "hh_server"]
(Filename.basename cmd)
~equal:String.equal
in
(* After stripping binary/wrapper, if what's left has the form "-bash" or "/usr/bin/bash --init-file ..."
then that shows it's an interactive shell. However "bash -c cmd" is not. *)
let is_interactive_shell_cmdline (cmdline : string) : bool =
match String.split cmdline ~on:' ' with
| [] -> false
| cmd :: [] when String.is_suffix cmd ~suffix:"sh" -> true
| cmd :: arg :: _ when String.is_suffix cmd ~suffix:"sh" ->
String.is_prefix arg ~prefix:"-"
&& not (String.is_prefix arg ~prefix:"-c")
| _ -> false
in
let rec loop stack =
match stack with
| [] -> false
| cmdline :: rest when is_skippable_hh_cmdline cmdline -> loop rest
| cmdline :: _ when is_interactive_shell_cmdline cmdline -> true
| _ -> false
in
loop (List.rev init_proc_stack)
(** There's no reliable way to tell whether an arbitrary PID is still alive.
That's because after the process has long since died, its PID might be recycled
for use by another process. This routine makes a best-effort attempt:
1. Can we read /proc/<pid>/cmdline? - yes if it's alive or still being held onto.
2. Is "expected" a substring of cmdline? - this is our best-effort protection
against pid recyling, since the chance that it gets recycled *and* the recycled one
has the process-name we were expecting just seems pretty low. Note that cmdline
will be empty if the process has been zombified. Also that if a process modifies
its argv then the cmdline will reflect that. In effect, cmdline is the command-line
that the process wants you to see.
3. Can we send SIGKILL 0 to it? If this succeeds without throwing an exception,
then the process is alive. *)
let is_alive ~(pid : int) ~(expected : string) : bool =
if not Sys.unix then
failwith "is_alive only implemented on Linux"
else begin
(* 1. Can we fetch /proc/<pid>/cmdline ? *)
match get_cmdline pid with
| Error _ -> false
| Ok cmdline ->
(* 2. Is /proc/<pid>/cmdline the process-name that we expected? *)
(* To consider: it would be more accurate, but less usable, to test whether /proc/stat
records the same starttime as expected. See 'man proc' for more details. *)
if String.is_substring cmdline ~substring:expected then
try
(* 3. Does "SIGKILL <pid> 0" succeed to send a message to the process? *)
Unix.kill pid 0;
true
with
| _ -> false
else
false
end |
C | hhvm/hphp/hack/src/utils/sys/processor_info.c | /**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*/
#define CAML_NAME_SPACE
#include <caml/alloc.h>
#include <caml/fail.h>
#include <caml/memory.h>
#include <stdio.h>
#define CPU_INFO_USER 0
#define CPU_INFO_USER_NICE 1
#define CPU_INFO_SYSTEM 2
#define CPU_INFO_IDLE 3
#define PROCESSOR_INFO_PROC_TOTALS 0
#define PROCESSOR_INFO_PROC_PER_CPU 1
#ifdef _WIN32
// TODO if we every start profiling Windows
// Rather than crash, we'll just return empty info
value hh_processor_info(void) {
CAMLparam0();
CAMLlocal3(result, array, info);
// Empty array of cpu info
array = caml_alloc_tuple(0);
// Empty total cpu info
info = caml_alloc(4, Double_array_tag);
Store_double_field(info, CPU_INFO_USER, 0);
Store_double_field(info, CPU_INFO_USER_NICE, 0);
Store_double_field(info, CPU_INFO_SYSTEM, 0);
Store_double_field(info, CPU_INFO_IDLE, 0);
result = caml_alloc_tuple(2);
Store_field(result, PROCESSOR_INFO_PROC_TOTALS, info);
Store_field(result, PROCESSOR_INFO_PROC_PER_CPU, array);
CAMLreturn(result);
}
#elif defined(__APPLE__)
#include <mach/mach_error.h>
#include <mach/mach_host.h>
#include <mach/processor_info.h>
#include <unistd.h>
value hh_processor_info(void) {
CAMLparam0();
CAMLlocal3(result, array, info);
processor_cpu_load_info_t cpu_load_info;
mach_msg_type_number_t msg_count;
char buf[256];
double total_user = 0, total_nice = 0, total_system = 0, total_idle = 0;
int i;
long ticks_per_second = sysconf(_SC_CLK_TCK);
natural_t num_cpus;
kern_return_t ret = host_processor_info(
mach_host_self(),
PROCESSOR_CPU_LOAD_INFO,
&num_cpus,
(processor_info_array_t *)&cpu_load_info,
&msg_count);
if (ret) {
snprintf(buf, 256, "host_processor_info error: %s", mach_error_string(ret));
caml_failwith(buf);
}
array = caml_alloc_tuple(num_cpus);
for (i = 0; i < num_cpus; i++) {
info = caml_alloc(4, Double_array_tag);
Store_double_field(
info,
CPU_INFO_USER,
cpu_load_info[i].cpu_ticks[CPU_STATE_USER] / ticks_per_second);
Store_double_field(
info,
CPU_INFO_USER_NICE,
cpu_load_info[i].cpu_ticks[CPU_STATE_NICE] / ticks_per_second);
Store_double_field(
info,
CPU_INFO_SYSTEM,
cpu_load_info[i].cpu_ticks[CPU_STATE_SYSTEM] / ticks_per_second);
Store_double_field(
info,
CPU_INFO_IDLE,
cpu_load_info[i].cpu_ticks[CPU_STATE_IDLE] / ticks_per_second);
Store_field(array, i, info);
total_user += cpu_load_info[i].cpu_ticks[CPU_STATE_USER];
total_nice += cpu_load_info[i].cpu_ticks[CPU_STATE_NICE];
total_system += cpu_load_info[i].cpu_ticks[CPU_STATE_SYSTEM];
total_idle += cpu_load_info[i].cpu_ticks[CPU_STATE_IDLE];
}
info = caml_alloc(4, Double_array_tag);
Store_double_field(info, CPU_INFO_USER, total_user / ticks_per_second);
Store_double_field(info, CPU_INFO_USER_NICE, total_nice / ticks_per_second);
Store_double_field(info, CPU_INFO_SYSTEM, total_system / ticks_per_second);
Store_double_field(info, CPU_INFO_IDLE, total_idle / ticks_per_second);
result = caml_alloc_tuple(2);
Store_field(result, PROCESSOR_INFO_PROC_TOTALS, info);
Store_field(result, PROCESSOR_INFO_PROC_PER_CPU, array);
CAMLreturn(result);
}
#else // Not Windows and not OS X means Linux
#include <unistd.h> // nolint (linter thinks this is a duplicate include)
value scan_line(FILE *fp, long ticks_per_second) {
CAMLparam0();
CAMLlocal1(cpu_info);
double user = 0.0;
double nice = 0.0;
double sys = 0.0;
double idle = 0.0;
fscanf(fp, "%*s %lf %lf %lf %lf %*[^\n]", &user, &nice, &sys, &idle);
// Usually, ocaml will box the float type. However, arrays and records that
// only contain floats get their own special representation which is unboxed
cpu_info = caml_alloc(4, Double_array_tag);
// The numbers in /proc/stat represent clock ticks, so convert to seconds.
Store_double_field(cpu_info, CPU_INFO_USER, user / ticks_per_second);
Store_double_field(cpu_info, CPU_INFO_USER_NICE, nice / ticks_per_second);
Store_double_field(cpu_info, CPU_INFO_SYSTEM, sys / ticks_per_second);
Store_double_field(cpu_info, CPU_INFO_IDLE, idle / ticks_per_second);
CAMLreturn(cpu_info);
}
value hh_processor_info(void) {
CAMLparam0();
CAMLlocal2(result, array);
FILE *fp = fopen("/proc/stat", "r");
long num_cpus = sysconf(_SC_NPROCESSORS_ONLN);
int i;
long ticks_per_second = sysconf(_SC_CLK_TCK);
if (fp == NULL) {
caml_failwith("Failed to open /proc/stat");
}
result = caml_alloc_tuple(2);
if (fp != NULL) {
Store_field(
result,
PROCESSOR_INFO_PROC_TOTALS,
scan_line(fp, ticks_per_second));
array = caml_alloc_tuple(num_cpus);
Store_field(result, PROCESSOR_INFO_PROC_PER_CPU, array);
// For each CPU, scan in the line
for (i = 0; i < num_cpus; i++) {
Store_field(array, i, scan_line(fp, ticks_per_second));
}
fclose(fp);
}
CAMLreturn(result);
}
#endif |
C | hhvm/hphp/hack/src/utils/sys/realpath.c | /**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*/
#define CAML_NAME_SPACE
#include <caml/mlvalues.h>
#include <caml/memory.h>
#include <caml/alloc.h>
#include <limits.h>
#include <stdlib.h>
#define Val_none Val_int(0)
static value
Val_some( value v )
{
CAMLparam1( v );
CAMLlocal1( some );
some = caml_alloc(1, 0);
Store_field( some, 0, v );
CAMLreturn( some );
}
CAMLprim value
hh_realpath(value v) {
const char *input;
#ifndef _WIN32
char output[PATH_MAX];
#else
char output[_MAX_PATH];
#endif
char *result;
CAMLparam1(v);
input = String_val(v);
#ifndef _WIN32
result = realpath(input, output);
#else
result = _fullpath(output, input, _MAX_PATH);
#endif
if (result == NULL) {
CAMLreturn(Val_none);
} else {
CAMLreturn(Val_some(caml_copy_string(output)));
}
} |
C | hhvm/hphp/hack/src/utils/sys/sysinfo.c | /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*/
#define CAML_NAME_SPACE
#include <caml/alloc.h>
#include <caml/fail.h>
#include <caml/memory.h>
#include <caml/mlvalues.h>
#include <assert.h>
#ifdef __linux__
#include <sys/sysinfo.h>
#endif
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
// This function returns an option of a 9-int-member struct
value hh_sysinfo(void) {
CAMLparam0();
#ifdef __linux__
CAMLlocal2(result, some);
result = caml_alloc_tuple(9);
struct sysinfo info = {0}; // this initializes all members to 0
if (sysinfo(&info) != 0) {
caml_failwith("Failed to sysinfo()");
}
Store_field(result, 0, Val_long(info.uptime));
Store_field(result, 1, Val_long(info.totalram * info.mem_unit));
Store_field(result, 2, Val_long(info.freeram * info.mem_unit));
Store_field(result, 3, Val_long(info.sharedram * info.mem_unit));
Store_field(result, 4, Val_long(info.bufferram * info.mem_unit));
Store_field(result, 5, Val_long(info.totalswap * info.mem_unit));
Store_field(result, 6, Val_long(info.freeswap * info.mem_unit));
Store_field(result, 7, Val_long(info.totalhigh * info.mem_unit));
Store_field(result, 8, Val_long(info.freehigh * info.mem_unit));
some = caml_alloc(1, 0);
Store_field(some, 0, result);
CAMLreturn(some);
#else
CAMLreturn(Val_int(0)); // None
#endif
}
CAMLprim value hh_sysinfo_is_apple_os(void) {
CAMLparam0();
#ifdef __APPLE__
return Val_bool(1);
#else
return Val_bool(0);
#endif
}
value hh_nproc(void) {
CAMLparam0();
CAMLlocal1(result);
#ifdef _WIN32
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
result = Val_long(sysinfo.dwNumberOfProcessors);
#else
result = Val_long(sysconf(_SC_NPROCESSORS_ONLN));
#endif
CAMLreturn(result);
}
/**
* There are a bunch of functions that you expect to return a pid,
* like Unix.getpid() and Unix.create_process(). However, on
* Windows, instead of returning the process ID, they return a
* process handle.
*
* Process handles seem act like pointers to a process. You can have
* more than one handle that points to a single process (unlike
* pids, where there is a single pid for a process).
*
* This isn't a problem normally, since functons like Unix.waitpid()
* will take the process handle on Windows. But if you want to print
* or log the pid, then you need to dereference the handle and get
* the pid. And that's what this function does.
*/
value pid_of_handle(value handle) {
CAMLparam1(handle);
#ifdef _WIN32
CAMLreturn(Val_int(GetProcessId((HANDLE)Long_val(handle))));
#else
CAMLreturn(handle);
#endif
}
value handle_of_pid_for_termination(value pid) {
CAMLparam1(pid);
#ifdef _WIN32
CAMLreturn(Val_int(OpenProcess(PROCESS_TERMINATE, FALSE, Int_val(pid))));
#else
CAMLreturn(pid);
#endif
} |
OCaml | hhvm/hphp/hack/src/utils/sys/sys_utils.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module Printexc = Stdlib.Printexc
external realpath : string -> string option = "hh_realpath"
external is_nfs : string -> bool = "hh_is_nfs"
external is_apple_os : unit -> bool = "hh_sysinfo_is_apple_os"
external freopen : string -> string -> Unix.file_descr -> unit = "hh_freopen"
external open_tmpfile :
rd:bool -> wr:bool -> dir:string -> file_perm:int -> Unix.file_descr
= "hh_open_tmpfile"
let get_env name =
try Some (Sys.getenv name) with
| Caml.Not_found -> None
let getenv_user () =
let user_var =
if Sys.win32 then
"USERNAME"
else
"USER"
in
let logname_var = "LOGNAME" in
let user = get_env user_var in
let logname = get_env logname_var in
Option.first_some user logname
let getenv_home () =
let home_var =
if Sys.win32 then
"APPDATA"
else
"HOME"
in
get_env home_var
let getenv_term () =
let term_var = "TERM" in
(* This variable does not exist on windows. *)
get_env term_var
let path_sep =
if Sys.win32 then
";"
else
":"
let null_path =
if Sys.win32 then
"nul"
else
"/dev/null"
let temp_dir_name =
if Sys.win32 then
Stdlib.Filename.get_temp_dir_name ()
else
"/tmp"
let getenv_path () =
let path_var = "PATH" in
(* Same variable on windows *)
get_env path_var
let open_in_no_fail fn =
try In_channel.create fn with
| e ->
let e = Printexc.to_string e in
Printf.fprintf stderr "Could not In_channel.create: '%s' (%s)\n" fn e;
exit 3
let open_in_bin_no_fail fn =
try In_channel.create ~binary:true fn with
| e ->
let e = Printexc.to_string e in
Printf.fprintf
stderr
"Could not In_channel.create ~binary:true: '%s' (%s)\n"
fn
e;
exit 3
let close_in_no_fail fn ic =
try In_channel.close ic with
| e ->
let e = Printexc.to_string e in
Printf.fprintf stderr "Could not close: '%s' (%s)\n" fn e;
exit 3
let open_out_no_fail fn =
try Out_channel.create fn with
| e ->
let e = Printexc.to_string e in
Printf.fprintf stderr "Could not Out_channel.create: '%s' (%s)\n" fn e;
exit 3
let open_out_bin_no_fail fn =
try Out_channel.create ~binary:true fn with
| e ->
let e = Printexc.to_string e in
Printf.fprintf
stderr
"Could not Out_channel.create ~binary:true: '%s' (%s)\n"
fn
e;
exit 3
let close_out_no_fail fn oc =
try Out_channel.close oc with
| e ->
let e = Printexc.to_string e in
Printf.fprintf stderr "Could not close: '%s' (%s)\n" fn e;
exit 3
let file_exists = Disk.file_exists
let cat = Disk.cat
let cat_or_failed file =
try Some (Disk.cat file) with
| TestDisk.No_such_file_or_directory _
| Sys_error _
| Failure _ ->
None
let cat_no_fail filename =
let ic = open_in_bin_no_fail filename in
let len = Int64.to_int @@ In_channel.length ic in
let len = Option.value_exn len in
let buf = Buffer.create len in
Caml.Buffer.add_channel buf ic len;
let content = Buffer.contents buf in
close_in_no_fail filename ic;
content
let nl_regexp = Str.regexp "[\r\n]"
let split_lines = Str.split nl_regexp
let string_contains str substring =
(* regexp_string matches only this string and nothing else. *)
let re = Str.regexp_string substring in
try Str.search_forward re str 0 >= 0 with
| Caml.Not_found -> false
let exec_read cmd =
let ic = Unix.open_process_in cmd in
let result = In_channel.input_line ic in
assert (Poly.(Unix.close_process_in ic = Unix.WEXITED 0));
result
let exec_try_read cmd =
let ic = Unix.open_process_in cmd in
let out = In_channel.input_line ic in
let status = Unix.close_process_in ic in
match (out, status) with
| (Some _, Unix.WEXITED 0) -> out
| _ -> None
let exec_read_lines ?(reverse = false) cmd =
let ic = Unix.open_process_in cmd in
let result = ref [] in
(try
while true do
match In_channel.input_line ic with
| Some line -> result := line :: !result
| None -> raise End_of_file
done
with
| End_of_file -> ());
assert (Poly.(Unix.close_process_in ic = Unix.WEXITED 0));
if not reverse then
List.rev !result
else
!result
(**
* Collects paths that satisfy a predicate, recursively traversing directories.
*)
let rec collect_paths path_predicate path =
if Sys.is_directory path then
path
|> Sys.readdir
|> Array.to_list
|> List.map ~f:(Filename.concat path)
|> List.concat_map ~f:(collect_paths path_predicate)
else
Utils.singleton_if (path_predicate path) path
let parse_path_list (paths : string list) : string list =
List.concat_map paths ~f:(fun path ->
if String.is_prefix path ~prefix:"@" then
let path = String_utils.lstrip path "@" in
cat path |> split_lines
else
[path])
let rm_dir_tree ?(skip_mocking = false) =
if skip_mocking then
RealDisk.rm_dir_tree
else
Disk.rm_dir_tree
let restart () =
let cmd = Sys.argv.(0) in
let argv = Sys.argv in
Unix.execv cmd argv
let logname_impl () =
match getenv_user () with
| Some user -> user
| None ->
(try Utils.unsafe_opt (exec_try_read "logname") with
| Invalid_argument _ ->
(try Utils.unsafe_opt (exec_try_read "id -un") with
| Invalid_argument _ -> "[unknown]"))
let logname_lazy = lazy (logname_impl ())
let logname () = Lazy.force logname_lazy
let get_primary_owner () =
let owners_file = "/etc/devserver.owners" in
let logged_in_user = logname () in
if not (Disk.file_exists owners_file) then
logged_in_user
else
let lines = Core.String.split_lines (Disk.cat owners_file) in
if List.mem lines logged_in_user ~equal:String.( = ) then
logged_in_user
else
lines |> List.last |> Option.value ~default:logged_in_user
let with_umask umask f =
let old_umask = ref 0 in
Utils.with_context
~enter:(fun () -> old_umask := Unix.umask umask)
~exit:(fun () ->
let _ = Unix.umask !old_umask in
())
~do_:f
let with_umask umask f =
if Sys.win32 then
f ()
else
with_umask umask f
let read_stdin_to_string () =
let buf = Buffer.create 4096 in
try
while true do
match In_channel.input_line In_channel.stdin with
| Some line ->
Buffer.add_string buf line;
Buffer.add_char buf '\n'
| None -> raise End_of_file
done;
assert false
with
| End_of_file -> Buffer.contents buf
let read_all ?(buf_size = 4096) ic =
let buf = Buffer.create buf_size in
(try
while true do
let data = Bytes.create buf_size in
let bytes_read = In_channel.input ic ~buf:data ~pos:0 ~len:buf_size in
if bytes_read = 0 then raise Exit;
Buffer.add_subbytes buf data ~pos:0 ~len:bytes_read
done
with
| Exit -> ());
Buffer.contents buf
let expanduser path =
Str.substitute_first
(Str.regexp "^~\\([^/]*\\)")
begin
fun s ->
match Str.matched_group 1 s with
| "" -> begin
match getenv_home () with
| None -> (Unix.getpwuid (Unix.getuid ())).Unix.pw_dir
| Some home -> home
end
| unixname ->
(try (Unix.getpwnam unixname).Unix.pw_dir with
| Caml.Not_found -> Str.matched_string s)
end
path
let executable_path : unit -> string =
let executable_path_ = ref None in
let dir_sep = Filename.dir_sep.[0] in
let search_path path =
let paths =
match getenv_path () with
| None -> failwith "Unable to determine executable path"
| Some paths -> Str.split (Str.regexp_string path_sep) paths
in
let path =
List.fold_left
paths
~f:
begin
fun acc p ->
match acc with
| Some _ -> acc
| None -> realpath (expanduser (Filename.concat p path))
end
~init:None
in
match path with
| Some path -> path
| None -> failwith "Unable to determine executable path"
in
fun () ->
match !executable_path_ with
| Some path -> path
| None ->
let path = Sys.executable_name in
let path =
if String.contains path dir_sep then
match realpath path with
| Some path -> path
| None -> failwith "Unable to determine executable path"
else
search_path path
in
executable_path_ := Some path;
path
let lines_of_in_channel ic =
let rec loop accum =
match In_channel.input_line ic with
| None -> List.rev accum
| Some line -> loop (line :: accum)
in
loop []
let lines_of_file filename =
let ic = In_channel.create filename in
try
let result = lines_of_in_channel ic in
let () = In_channel.close ic in
result
with
| _ ->
In_channel.close ic;
[]
let read_file file =
let ic = In_channel.create ~binary:true file in
let size = Int64.to_int @@ In_channel.length ic in
let size = Option.value_exn size in
let buf = Bytes.create size in
Option.value_exn (In_channel.really_input ic ~buf ~pos:0 ~len:size);
In_channel.close ic;
buf
let write_file ~file s = Disk.write_file ~file ~contents:s
let append_file ~file s =
let chan = Out_channel.create ~append:true ~perm:0o666 file in
Out_channel.output_string chan s;
Out_channel.close chan
let write_strings_to_file ~file (ss : string list) =
let chan = Out_channel.create ~perm:0o666 file in
List.iter ~f:(Out_channel.output_string chan) ss;
Out_channel.close chan
(* could be in control section too *)
let mkdir_p ?(skip_mocking = false) =
if skip_mocking then
RealDisk.mkdir_p
else
Disk.mkdir_p
let mkdir_no_fail dir =
with_umask 0 (fun () ->
(* Don't set sticky bit since the socket opening code wants to remove any
* old sockets it finds, which may be owned by a different user. *)
try Unix.mkdir dir 0o777 with
| Unix.Unix_error (Unix.EEXIST, _, _) -> ())
let unlink_no_fail fn =
try Unix.unlink fn with
| Unix.Unix_error (Unix.ENOENT, _, _) -> ()
let readlink_no_fail fn =
if Sys.win32 && Sys.file_exists fn then
cat fn
else
try Unix.readlink fn with
| _ -> fn
let filemtime file = (Unix.stat file).Unix.st_mtime
external lutimes : string -> unit = "hh_lutimes"
type touch_mode =
| Touch_existing of { follow_symlinks: bool }
(** This won't open/close fds, which is important for some callers. *)
| Touch_existing_or_create_new of {
mkdir_if_new: bool;
perm_if_new: Unix.file_perm;
}
let touch mode file =
match mode with
| Touch_existing { follow_symlinks = true } -> Unix.utimes file 0. 0.
| Touch_existing { follow_symlinks = false } -> lutimes file
| Touch_existing_or_create_new { mkdir_if_new; perm_if_new } ->
with_umask 0o000 (fun () ->
if mkdir_if_new then mkdir_no_fail (Filename.dirname file);
let oc =
Out_channel.create ~append:true ~binary:true ~perm:perm_if_new file
in
Out_channel.close oc)
let try_touch mode file =
try touch mode file with
| _ -> ()
let splitext filename =
let root = Filename.chop_extension filename in
let root_length = String.length root in
(* -1 because the extension includes the period, e.g. ".foo" *)
let ext_length = String.length filename - root_length - 1 in
let ext = String.sub filename ~pos:(root_length + 1) ~len:ext_length in
(root, ext)
let enable_telemetry () =
(* The production builds where we want telemetry all have both build_mode and build-revision set. *)
let is_production_build =
(not (String.is_empty Build_id.build_mode))
&& not (String.is_empty Build_id.build_revision)
in
(* There are some cases where we want telemetry even from a non-production build,
so achieve that by setting HH_TEST_MODE=0.
There are other cases where we want to disable telemetry even in a production build,
so achieve that by setting HH_TEST_MODE=1 (or indeed anything other than 0). *)
match Sys.getenv_opt "HH_TEST_MODE" with
| Some "0" -> true
| Some _ -> false
| None -> is_production_build
let deterministic_behavior_for_tests () =
(* The only time we want A/B experiments is if we get telemetry on their outcomes!
That's why we use the same logic. *)
not (enable_telemetry ())
let sleep ~seconds = ignore @@ Unix.select [] [] [] seconds
let symlink =
(* Dummy implementation of `symlink` on Windows: we create a text
file containing the targeted-file's path. Symlink are available
on Windows since Vista, but until Seven (included), one should
have administratrive rights in order to create symlink. *)
let win32_symlink source dest = write_file ~file:dest source in
if Sys.win32 then
win32_symlink
else
(* 4.03 adds an optional argument to Unix.symlink that we want to ignore
*)
fun source dest ->
Unix.symlink source dest
let make_link_of_timestamped linkname =
Unix.(
let dir = Filename.dirname linkname in
mkdir_p dir;
let base = Filename.basename linkname in
let (base, ext) = splitext base in
let dir = Filename.concat dir (Printf.sprintf "%ss" ext) in
mkdir_p dir;
let tm = localtime (time ()) in
let year = tm.tm_year + 1900 in
let time_str =
Printf.sprintf
"%d-%02d-%02d-%02d-%02d-%02d"
year
(tm.tm_mon + 1)
tm.tm_mday
tm.tm_hour
tm.tm_min
tm.tm_sec
in
let filename =
Filename.concat dir (Printf.sprintf "%s-%s.%s" base time_str ext)
in
unlink_no_fail linkname;
symlink filename linkname;
filename)
let setsid =
(* Not implemented on Windows. Let's just return the pid *)
if Sys.win32 then
Unix.getpid
else
Unix.setsid
let set_signal =
if not Sys.win32 then
Sys.set_signal
else
fun _ _ ->
()
let signal =
if not Sys.win32 then
fun a b ->
ignore (Sys.signal a b)
else
fun _ _ ->
()
type sysinfo = {
uptime: int;
totalram: int;
freeram: int;
sharedram: int;
bufferram: int;
totalswap: int;
freeswap: int;
totalhigh: int;
freehigh: int;
}
external sysinfo : unit -> sysinfo option = "hh_sysinfo"
external nprocs : unit -> int = "hh_nproc"
let nbr_procs = nprocs ()
let total_ram =
Option.value_map (sysinfo ()) ~default:0 ~f:(fun si -> si.totalram)
let uptime () =
Option.value_map (sysinfo ()) ~default:0 ~f:(fun si -> si.uptime)
external set_priorities : cpu_priority:int -> io_priority:int -> unit
= "hh_set_priorities"
external pid_of_handle : int -> int = "pid_of_handle"
external handle_of_pid_for_termination : int -> int
= "handle_of_pid_for_termination"
let terminate_process pid = Unix.kill pid Sys.sigkill
let lstat path =
(* WTF, on Windows `lstat` fails if a directory path ends with an
'/' (or a '\', whatever) *)
Unix.lstat
@@
if Sys.win32 && String.is_suffix path ~suffix:Filename.dir_sep then
String.sub path ~pos:0 ~len:(String.length path - 1)
else
path
let normalize_filename_dir_sep =
let dir_sep_char = Filename.dir_sep.[0] in
String.map ~f:(fun c ->
if Char.equal c dir_sep_char then
'/'
else
c)
let name_of_signal = function
| s when s = Sys.sigabrt -> "SIGABRT (Abnormal termination)"
| s when s = Sys.sigalrm -> "SIGALRM (Timeout)"
| s when s = Sys.sigfpe -> "SIGFPE (Arithmetic exception)"
| s when s = Sys.sighup -> "SIGHUP (Hangup on controlling terminal)"
| s when s = Sys.sigill -> "SIGILL (Invalid hardware instruction)"
| s when s = Sys.sigint -> "SIGINT (Interactive interrupt (ctrl-C))"
| s when s = Sys.sigkill -> "SIGKILL (Termination)"
| s when s = Sys.sigpipe -> "SIGPIPE (Broken pipe)"
| s when s = Sys.sigquit -> "SIGQUIT (Interactive termination)"
| s when s = Sys.sigsegv -> "SIGSEGV (Invalid memory reference)"
| s when s = Sys.sigterm -> "SIGTERM (Termination)"
| s when s = Sys.sigusr1 -> "SIGUSR1 (Application-defined signal 1)"
| s when s = Sys.sigusr2 -> "SIGUSR2 (Application-defined signal 2)"
| s when s = Sys.sigchld -> "SIGCHLD (Child process terminated)"
| s when s = Sys.sigcont -> "SIGCONT (Continue)"
| s when s = Sys.sigstop -> "SIGSTOP (Stop)"
| s when s = Sys.sigtstp -> "SIGTSTP (Interactive stop)"
| s when s = Sys.sigttin -> "SIGTTIN (Terminal read from background process)"
| s when s = Sys.sigttou -> "SIGTTOU (Terminal write from background process)"
| s when s = Sys.sigvtalrm -> "SIGVTALRM (Timeout in virtual time)"
| s when s = Sys.sigprof -> "SIGPROF (Profiling interrupt)"
| s when s = Sys.sigbus -> "SIGBUS (Bus error)"
| s when s = Sys.sigpoll -> "SIGPOLL (Pollable event)"
| s when s = Sys.sigsys -> "SIGSYS (Bad argument to routine)"
| s when s = Sys.sigtrap -> "SIGTRAP (Trace/breakpoint trap)"
| s when s = Sys.sigurg -> "SIGURG (Urgent condition on socket)"
| s when s = Sys.sigxcpu -> "SIGXCPU (Timeout in cpu time)"
| s when s = Sys.sigxfsz -> "SIGXFSZ (File size limit exceeded)"
| other -> string_of_int other
type cpu_info = {
cpu_user: float;
cpu_nice_user: float;
cpu_system: float;
cpu_idle: float;
}
type processor_info = {
proc_totals: cpu_info;
proc_per_cpu: cpu_info array;
}
external processor_info : unit -> processor_info = "hh_processor_info"
let string_of_fd (fd : Unix.file_descr) : string = string_of_int (Obj.magic fd)
let show_inode (fd : Unix.file_descr) : string =
let stat = Unix.fstat fd in
Printf.sprintf "inode#%d:%d" stat.Unix.st_dev stat.Unix.st_ino
let rec select_non_intr read write exn timeout =
let start_time = Unix.gettimeofday () in
try Unix.select read write exn timeout with
| Unix.Unix_error (Unix.EINTR, _, _) ->
(* Negative timeouts mean no timeout *)
let timeout =
if Float.(timeout < 0.0) then
(* A negative timeout means no timeout, i.e. unbounded wait. *)
timeout
else
Float.(max 0.0 (timeout -. (Unix.gettimeofday () -. start_time)))
in
select_non_intr read write exn timeout
| Unix.Unix_error (Unix.EINVAL, fun_name, "") ->
(* There are suspicions that we are receiving this exception because we are
* leaking file descriptors and end up using fds beyond the allowable
* range of 1024, so this intends to log all of the file descriptors that
* we call select on to verify those suspicions.
*)
let fdl_to_str fdl =
(* Using `Obj.magic` to convert file descriptors to ints because there is no
* library function to do so. See (https://github.com/ocaml/ocaml/pull/1990)
*)
"["
^ List.fold_left
~f:(fun init fd -> init ^ string_of_fd fd ^ ", ")
~init:""
fdl
^ "]"
in
let fun_params =
Printf.sprintf
"%s %s %s %f"
(fdl_to_str read)
(fdl_to_str write)
(fdl_to_str exn)
timeout
in
raise (Unix.Unix_error (Unix.EINVAL, fun_name, fun_params))
let rec restart_on_EINTR f x =
try f x with
| Unix.Unix_error (Unix.EINTR, _, _) -> restart_on_EINTR f x
let write_non_intr (fd : Unix.file_descr) (buf : bytes) (pos : int) (len : int)
: unit =
let pos = ref pos in
while !pos < len do
(* must use Unix.single_write, not Unix.write, because the latter does arbitrarily
many OS calls and we don't know which one got the EINTR *)
let n = restart_on_EINTR (Unix.single_write fd buf !pos) (len - !pos) in
pos := !pos + n
done
let read_non_intr (fd : Unix.file_descr) (len : int) : bytes option =
let buf = Bytes.create len in
let pos = ref 0 in
let is_eof = ref false in
while !pos < len && not !is_eof do
let n = restart_on_EINTR (Unix.read fd buf !pos) (len - !pos) in
pos := !pos + n;
if n = 0 then is_eof := true
done;
if !is_eof then
None
else
Some buf
let rec waitpid_non_intr flags pid =
try Unix.waitpid flags pid with
| Unix.Unix_error (Unix.EINTR, _, _) -> waitpid_non_intr flags pid
let find_oom_in_dmesg_output pid name lines =
(* oomd: "Memory cgroup out of memory: Killed process 4083583 (hh_server)" (https://facebookmicrosites.github.io/oomd/)
oomkiller: "Out of memory: Kill process 4083583 (hh_server)" *)
let re =
Str.regexp
(Printf.sprintf
"[Oo]ut of memory: Kill\\(ed\\)? process \\([0-9]+\\) (%s)"
name)
in
let pid = string_of_int pid in
List.exists lines ~f:(fun line ->
try
ignore @@ Str.search_forward re line 0;
let pid_s = Str.matched_group 2 line in
String.equal pid_s pid
with
| Caml.Not_found -> false)
let check_dmesg_for_oom pid name =
let dmesg = exec_read_lines ~reverse:true "dmesg" in
find_oom_in_dmesg_output pid name dmesg
(* Be careful modifying the rusage type! Like other types that interact with C, the order matters!
* If you change things here you must update hh_getrusage too! *)
type rusage = {
ru_maxrss: int;
(* maximum resident set size *)
ru_ixrss: int;
(* integral shared memory size *)
ru_idrss: int;
(* integral unshared data size *)
ru_isrss: int;
(* integral unshared stack size *)
ru_minflt: int;
(* page reclaims (soft page faults) *)
ru_majflt: int;
(* page faults (hard page faults) *)
ru_nswap: int;
(* swaps *)
ru_inblock: int;
(* block input operations *)
ru_oublock: int;
(* block output operations *)
ru_msgsnd: int;
(* IPC messages sent *)
ru_msgrcv: int;
(* IPC messages received *)
ru_nsignals: int;
(* signals received *)
ru_nvcsw: int;
(* voluntary context switches *)
ru_nivcsw: int; (* involuntary context switches *)
}
external getrusage : unit -> rusage = "hh_getrusage"
external start_gc_profiling : unit -> unit = "hh_start_gc_profiling" [@@noalloc]
external get_gc_time : unit -> float * float = "hh_get_gc_time"
module For_test = struct
let find_oom_in_dmesg_output = find_oom_in_dmesg_output
end
let atomically_create_and_init_file
(path : string)
~(rd : bool)
~(wr : bool)
(file_perm : Unix.file_perm)
~(init : Unix.file_descr -> unit) : Unix.file_descr option =
if not Sys.unix then
failwith "O_TMPFILE, linkat and /proc/fd all require linux";
(* There's no way to pass O_TMPFILE to Unix.openfile. So, we need our own version... *)
let fd = open_tmpfile ~rd ~wr ~dir:(Filename.dirname path) ~file_perm in
try
init fd;
(* If the user's callback worked, we can proceed to atomically move the file into place.
If this fails due to pre-existing, then we'll return None.
Implementation of Unix.link is at
https://github.com/ocaml/ocaml/blob/trunk/otherlibs/unix/link_unix.c.
The ~follow:true flag makes it do
linkat(AT_FDCWD, "/proc/self/fd/<fd>", AT_FDCWD, filename, AT_SYMLINK_FOLLOW) *)
(* Here is documentation from "man 2 open": https://man7.org/linux/man-pages/man2/open.2.html
Note that it only exists on linux (since 2013) and not on other unix platforms.
O_TMPFILE must be specified with one of O_RDWR or O_WRONLY and, optionally, O_EXCL. If O_EXCL
is not specified, then linkat(2) can be used to link the temporary file into the filesystem,
making it permanent, using code like the following:
char path[PATH_MAX];
fd = open("/path/to/dir", O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR);
/* File I/O on 'fd'... */
snprintf(path, PATH_MAX, "/proc/self/fd/%d", fd);
linkat(AT_FDCWD, path, AT_FDCWD, "/path/for/file", AT_SYMLINK_FOLLOW);
There are two main use cases for O_TMPFILE:
* Improved tmpfile(3) functionality: race-free creation of temporary files that (1) are
automatically deleted when closed; (2) can never be reached via any pathname; (3) are not
subject to symlink attacks; and (4) do not require the caller to devise unique names.
* Creating a file that is initially invisible, which is then populated with data and adjusted to
have appropriate filesystem attributes (fchown(2), fchmod(2), fsetxattr(2), etc.) before being
atomically linked into the filesystem in a fully formed state (using linkat(2) as described above)
*)
begin
try
Unix.link
~follow:true
(Printf.sprintf "/proc/self/fd/%s" (string_of_fd fd))
path;
Some fd
with
| Unix.Unix_error (Unix.EEXIST, _, _) ->
Unix.close fd;
None
end
with
| exn ->
let e = Exception.wrap exn in
Unix.close fd;
Exception.reraise e
let protected_read_exn (filename : string) : string =
(* TODO(ljw): this function is vulnerable to EINTR. Although we only hit it about once a month. *)
(* TODO(ljw): we should use atomic-create for this! *)
(* We can't use the standard Disk.cat because we need to read from an existing (locked)
fd for the file; not open the file a second time and read from that. *)
let cat_from_fd (fd : Unix.file_descr) : string =
let total = Unix.lseek fd 0 Unix.SEEK_END in
let _0 = Unix.lseek fd 0 Unix.SEEK_SET in
let buf = Bytes.create total in
let rec rec_read offset =
if offset = total then
()
else
let bytes_read = Unix.read fd buf offset (total - offset) in
if bytes_read = 0 then raise End_of_file;
rec_read (offset + bytes_read)
in
rec_read 0;
Bytes.to_string buf
in
(* Unix has no way to atomically create a file and lock it; fnctl inherently
only works on an existing file. There's therefore a race where the writer
might create the file before locking it, but we get our read lock in first.
We'll work around this with a hacky sleep+retry. Other solutions would be
to have the file always exist, or to use a separate .lock file. *)
let rec retry_if_empty () =
let fd = Unix.openfile filename [Unix.O_RDONLY] 0o666 in
let content =
Utils.try_finally
~f:(fun () ->
Unix.lockf fd Unix.F_RLOCK 0;
cat_from_fd fd)
~finally:(fun () -> Unix.close fd)
in
if String.is_empty content then
let () = Unix.sleepf 0.001 in
retry_if_empty ()
else
content
in
retry_if_empty ()
let protected_write_exn (filename : string) (content : string) : unit =
if String.is_empty content then failwith "Empty content not supported.";
with_umask 0o000 (fun () ->
let fd = Unix.openfile filename [Unix.O_RDWR; Unix.O_CREAT] 0o666 in
Utils.try_finally
~f:(fun () ->
Unix.lockf fd Unix.F_LOCK 0;
let _written =
Unix.write_substring fd content 0 (String.length content)
in
Unix.ftruncate fd (String.length content))
~finally:(fun () -> Unix.close fd))
let with_lock
(fd : Unix.file_descr) (lock_command : Unix.lock_command) ~(f : unit -> 'a)
=
(* helper function to set current file position to 0, then do "f",
then restore it to what it was before *)
let with_pos0 ~f =
let pos = Unix.lseek fd 0 Unix.SEEK_CUR in
let _ = Unix.lseek fd 0 Unix.SEEK_SET in
let result = f () in
let _ = Unix.lseek fd pos Unix.SEEK_SET in
result
in
Utils.try_finally
~f:(fun () ->
(* lockf is applied starting at the file-descriptors current position.
We use "with_pos0" so that when we acquire or release the lock,
we're locking from the start of the file through to (len=0) the end. *)
with_pos0 ~f:(fun () -> restart_on_EINTR (Unix.lockf fd lock_command) 0);
f ())
~finally:(fun () ->
with_pos0 ~f:(fun () -> restart_on_EINTR (Unix.lockf fd Unix.F_ULOCK) 0);
())
let redirect_stdout_and_stderr_to_file (filename : string) : unit =
let old_stdout = Unix.dup Unix.stdout in
let old_stderr = Unix.dup Unix.stderr in
Utils.try_finally
~finally:(fun () ->
(* Those two old_* handles must be closed so as not to have dangling FDs.
Neither success nor failure path holds onto them: the success path ignores
then, and the failure path dups them. That's why we can close them here. *)
(try Unix.close old_stdout with
| _ -> ());
(try Unix.close old_stderr with
| _ -> ());
())
~f:(fun () ->
try
(* We want both stdout and stderr to be redirected to the same file.
Do not attempt to open a file that's already open:
https://wiki.sei.cmu.edu/confluence/display/c/FIO24-C.+Do+not+open+a+file+that+is+already+open
Use dup for this scenario instead:
https://stackoverflow.com/questions/15155314/redirect-stdout-and-stderr-to-the-same-file-and-restore-it *)
freopen filename "w" Unix.stdout;
Unix.dup2 Unix.stdout Unix.stderr;
()
with
| exn ->
let e = Exception.wrap exn in
(try Unix.dup2 old_stdout Unix.stdout with
| _ -> ());
(try Unix.dup2 old_stderr Unix.stderr with
| _ -> ());
Exception.reraise e) |
OCaml Interface | hhvm/hphp/hack/src/utils/sys/sys_utils.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
external realpath : string -> string option = "hh_realpath"
external is_nfs : string -> bool = "hh_is_nfs"
external is_apple_os : unit -> bool = "hh_sysinfo_is_apple_os"
(** E.g. freopen "file.txt" "a" Unix.stdout will redirect stdout to the file. *)
external freopen : string -> string -> Unix.file_descr -> unit = "hh_freopen"
(** Option type intead of exception throwing. *)
val get_env : string -> string option
val getenv_user : unit -> string option
val getenv_home : unit -> string option
val getenv_term : unit -> string option
val path_sep : string
val null_path : string
val temp_dir_name : string
val getenv_path : unit -> string option
(** This is a string "fd123:456" which uniquely identifies this file's inode *)
val show_inode : Unix.file_descr -> string
val open_in_no_fail : string -> in_channel
val open_in_bin_no_fail : string -> in_channel
val close_in_no_fail : string -> in_channel -> unit
val open_out_no_fail : string -> out_channel
val open_out_bin_no_fail : string -> out_channel
val close_out_no_fail : string -> out_channel -> unit
val file_exists : string -> bool
val cat : string -> string
val cat_or_failed : string -> string option
val cat_no_fail : string -> string
val nl_regexp : Str.regexp
val split_lines : string -> string list
(** Returns true if substring occurs somewhere inside str. *)
val string_contains : string -> string -> bool
val exec_read : string -> string option
val exec_try_read : string -> string option
val exec_read_lines : ?reverse:bool -> string -> string list
val collect_paths : (string -> bool) -> string -> string list
(**
* Sometimes the user wants to pass a list of paths on the command-line.
* However, we have enough files in the codebase that sometimes that list
* exceeds the maximum number of arguments that can be passed on the
* command-line. To work around this, we can use the convention that some Unix
* tools use: a `@` before a path name represents a file that should be read
* to get the necessary information (in this case, containing a list of files,
* one per line).
*)
val parse_path_list : string list -> string list
val rm_dir_tree : ?skip_mocking:bool -> string -> unit
val restart : unit -> 'a
val logname_impl : unit -> string
val logname : unit -> string
val get_primary_owner : unit -> string
val with_umask : int -> (unit -> 'a) -> 'a
val read_stdin_to_string : unit -> string
val read_all : ?buf_size:int -> in_channel -> string
(** Like Python's os.path.expanduser, though probably doesn't cover some
cases. Roughly follow's bash's tilde expansion:
http://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html
~/foo -> /home/bob/foo if $HOME = "/home/bob"
~joe/foo -> /home/joe/foo if joe's home is /home/joe
*)
val expanduser : string -> string
(** Turns out it's surprisingly complex to figure out the path to the current
executable, which we need in order to extract its embedded libraries. If
argv[0] is a path, then we can use that; sometimes it's just the exe name, so
we have to search $PATH for it the same way shells do. for example:
https://www.gnu.org/software/bash/manual/html_node/Command-Search-and-Execution.html
There are other options which might be more reliable when they exist, like
using the `_` env var set by bash, or /proc/self/exe on Linux, but they are
not portable. *)
val executable_path : unit -> string
val lines_of_in_channel : in_channel -> string list
val lines_of_file : string -> string list
val read_file : string -> bytes
val write_file : file:string -> string -> unit
val append_file : file:string -> string -> unit
val write_strings_to_file : file:string -> string list -> unit
val mkdir_p : ?skip_mocking:bool -> string -> unit
(** Emulate "mkdir -p", i.e., no error if already exists. *)
val mkdir_no_fail : string -> unit
val unlink_no_fail : string -> unit
val readlink_no_fail : string -> string
val filemtime : string -> float
external lutimes : string -> unit = "hh_lutimes"
type touch_mode =
| Touch_existing of { follow_symlinks: bool }
| Touch_existing_or_create_new of {
mkdir_if_new: bool;
perm_if_new: Unix.file_perm;
}
val touch : touch_mode -> string -> unit
val try_touch : touch_mode -> string -> unit
val splitext : string -> string * string
(** Do we want HackEventLogger to work? *)
val enable_telemetry : unit -> bool
(** This flag controls whether at runtime we pick A/B experiments to test;
if not, then the output behavior will be solely a function of the inputs
(environment variables, hh.conf, .hhconfig, command-line arguments, repository).
It also controls whether certain key lines out output e.g. times or upload URLs,
which tests can't avoid looking at, will print fixed outputs. *)
val deterministic_behavior_for_tests : unit -> bool
val sleep : seconds:float -> unit
val symlink : string -> string -> unit
(** Creates a symlink at `<dir>/<linkname.ext>` to
`<dir>/<pluralized ext>/<linkname>-<timestamp>.<ext>` *)
val make_link_of_timestamped : string -> string
val setsid : unit -> int
val set_signal : int -> Sys.signal_behavior -> unit
val signal : int -> Sys.signal_behavior -> unit
(** as reported by sysinfo().uptime. Is 0 if not on linux. *)
val uptime : unit -> int
(** in bytes, as reported by sysinfo().totalram. Is 0 if not on linux. *)
val total_ram : int
(** returns the number of processors (which includes hyperthreads),
as reported by sysconf(_SC_NPROCESSORS_ONLN) *)
val nbr_procs : int
external set_priorities : cpu_priority:int -> io_priority:int -> unit
= "hh_set_priorities"
external pid_of_handle : int -> int = "pid_of_handle"
external handle_of_pid_for_termination : int -> int
= "handle_of_pid_for_termination"
val terminate_process : int -> unit
val lstat : string -> Unix.stats
val normalize_filename_dir_sep : string -> string
val name_of_signal : int -> string
(** The units for each of these fields is seconds, similar to Unix.times().
`cpu_info` and `processor_info` are constructed by c code (see
`processor_info.c`) so be very careful modifying these types! *)
type cpu_info = {
cpu_user: float;
cpu_nice_user: float;
cpu_system: float;
cpu_idle: float;
}
type processor_info = {
proc_totals: cpu_info;
proc_per_cpu: cpu_info array;
}
external processor_info : unit -> processor_info = "hh_processor_info"
type sysinfo = {
uptime: int;
totalram: int;
freeram: int;
sharedram: int;
bufferram: int;
totalswap: int;
freeswap: int;
totalhigh: int;
freehigh: int;
}
(** returns None if not on linux. *)
external sysinfo : unit -> sysinfo option = "hh_sysinfo"
(** Calls Unix.select but ignores EINTR, i.e. retries select with
an adjusted timout upon EINTR.
We implement timers using sigalarm which means selects can be
interrupted. This is a wrapper around EINTR which continues the select if it
gets interrupted by a signal *)
val select_non_intr :
Unix.file_descr list ->
Unix.file_descr list ->
Unix.file_descr list ->
float ->
Unix.file_descr list * Unix.file_descr list * Unix.file_descr list
(** "restart_on_EINTR f x" will do "f x", but if it throws EINTR then it will retry.
See https://ocaml.github.io/ocamlunix/ocamlunix.html#sec88 for explanation. *)
val restart_on_EINTR : ('a -> 'b) -> 'a -> 'b
(** Like Unix.write, but ignores EINTR. *)
val write_non_intr : Unix.file_descr -> bytes -> int -> int -> unit
(** Reads specified number of bytes from the file descriptor through repeated calls to Unix.read.
Ignores EINTR. If ever a call to Unix.read returns 0 bytes (e.g. end of file),
then this function will return None. *)
val read_non_intr : Unix.file_descr -> int -> bytes option
(** Flow uses lwt, which installs a sigchld handler. So the old pattern of
fork & waitpid will hit an EINTR when the forked process dies and the parent
gets a sigchld signal.
Note: this is only a problem if you're not using the WNOHANG flag, since
EINTR isn't thrown for WNOHANG *)
val waitpid_non_intr : Unix.wait_flag list -> int -> int * Unix.process_status
val check_dmesg_for_oom : int -> string -> bool
type rusage = {
ru_maxrss: int;
ru_ixrss: int;
ru_idrss: int;
ru_isrss: int;
ru_minflt: int;
ru_majflt: int;
ru_nswap: int;
ru_inblock: int;
ru_oublock: int;
ru_msgsnd: int;
ru_msgrcv: int;
ru_nsignals: int;
ru_nvcsw: int;
ru_nivcsw: int;
}
external getrusage : unit -> rusage = "hh_getrusage"
external start_gc_profiling : unit -> unit = "hh_start_gc_profiling" [@@noalloc]
external get_gc_time : unit -> float * float = "hh_get_gc_time"
module For_test : sig
val find_oom_in_dmesg_output : int -> string -> string list -> bool
end
(** [atomically_create_and_init_file file ~rd ~wr perm ~init] will
(1) create an anomymous FD using [rd], [wr] and [perm],
(2) call the [init] callback allowing you to write contents or lock that FD,
(3) attempt to atomically place that FD at the specified filename [file].
If this third step fails because a file already exists there, the function
will return None. Otherwise, it will return Some fd. *)
val atomically_create_and_init_file :
string ->
rd:bool ->
wr:bool ->
Unix.file_perm ->
init:(Unix.file_descr -> unit) ->
Unix.file_descr option
(** This will acquire a reader-lock on the file then read its content.
Locks in unix are advisory, so this only works if writing is done by
[protected_write_exn]. If the file doesn't exist, Unix.Unix_error(ENOENT). *)
val protected_read_exn : string -> string
(** [protected_write_exn file content] will acquire a writer-lock on the file
then write content. Locks in unix are advisory, so this only works if reading is
done by [protected_read_exn]. Empty content isn't supported and will fail. *)
val protected_write_exn : string -> string -> unit
(** This is a primitive API for atomic locks. It is robust against EINTR. *)
val with_lock : Unix.file_descr -> Unix.lock_command -> f:(unit -> 'a) -> 'a
(** As it says, redirects stdout and stderr to this file, which it will
open in "w" mode. If redirection fails then stdout+stderr are left unchanged.*)
val redirect_stdout_and_stderr_to_file : string -> unit |
OCaml | hhvm/hphp/hack/src/utils/sys/timeout.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Core
module Unix = Caml_unix
type timings = {
start_time: float;
deadline_time: float; (** caller-supplied deadline *)
timeout_time: float; (** actual time we raised the timeout *)
}
let show_timings (t : timings) : string =
Printf.sprintf
"{start=%s deadline=%s timeout=%s}"
(Utils.timestring t.start_time)
(Utils.timestring t.deadline_time)
(Utils.timestring t.timeout_time)
let pp_timings fmt t = Format.fprintf fmt "Timeout.timings%s" (show_timings t)
exception
Timeout of {
exn_id: int;
timeout_time: float;
deadline_time: float;
}
let () =
Caml.Printexc.register_printer (fun exn ->
match exn with
| Timeout t ->
Some
(Printf.sprintf
"Timeout.Timeout(id=%d timeout=%s deadline=%s)"
t.exn_id
(Utils.timestring t.timeout_time)
(Utils.timestring t.deadline_time))
| _ -> None)
(* The IDs are used to tell the difference between timeout A timing out and timeout B timing out.
* So they only really need to be unique between any two active timeouts in the same process. *)
let id_counter = ref 0
let mk_id () =
incr id_counter;
!id_counter
module Alarm_timeout = struct
(** Timeout *)
type t = int
let with_timeout ~timeout ~on_timeout ~do_ =
let start_time = Unix.gettimeofday () in
let id = mk_id () in
let callback () =
raise
(Timeout
{
exn_id = id;
timeout_time = Unix.gettimeofday ();
deadline_time = start_time +. float_of_int timeout;
})
in
try
let timer = Timer.set_timer ~interval:(float_of_int timeout) ~callback in
let ret =
try do_ id with
| exn ->
let e = Exception.wrap exn in
(* Any uncaught exception will cancel the timeout *)
Timer.cancel_timer timer;
Exception.reraise e
in
Timer.cancel_timer timer;
ret
with
| Timeout { exn_id; timeout_time; deadline_time } when exn_id = id ->
on_timeout { start_time; timeout_time; deadline_time }
let check_timeout _ = ()
let select ?timeout:_ = Sys_utils.select_non_intr
(** Channel *)
type in_channel = Stdlib.in_channel * int option
let ignore_timeout f ?timeout:_ (ic, _pid) = f ic
let input = ignore_timeout Stdlib.input
let really_input = ignore_timeout Stdlib.really_input
let input_char = ignore_timeout Stdlib.input_char
let input_line = ignore_timeout Stdlib.input_line
let input_value_with_workaround ic =
(* OCaml 4.03.0 changed the behavior of input_value to no longer
* throw End_of_file when the pipe has closed. We can simulate that
* behavior, however, by trying to read a byte afterwards, which WILL
* raise End_of_file if the pipe has closed
* http://caml.inria.fr/mantis/view.php?id=7142 *)
try Stdlib.input_value ic with
| Failure msg as exn ->
let e = Exception.wrap exn in
if String.equal msg "input_value: truncated object" then
Stdlib.input_char ic |> ignore;
Exception.reraise e
let input_value = ignore_timeout input_value_with_workaround
let open_in name = (Stdlib.open_in name, None)
let close_in (ic, _) = Stdlib.close_in ic
let close_in_noerr (ic, _) = Stdlib.close_in_noerr ic
let in_channel_of_descr fd = (Unix.in_channel_of_descr fd, None)
let descr_of_in_channel (ic, _) = Unix.descr_of_in_channel ic
let open_process cmd args =
let (child_in_fd, out_fd) = Unix.pipe () in
let (in_fd, child_out_fd) = Unix.pipe () in
Unix.set_close_on_exec in_fd;
Unix.set_close_on_exec out_fd;
let pid =
Unix.(
create_process
(Exec_command.to_string cmd)
args
child_in_fd
child_out_fd
stderr)
in
Unix.close child_out_fd;
Unix.close child_in_fd;
let ic = (Unix.in_channel_of_descr in_fd, Some pid) in
let oc = Unix.out_channel_of_descr out_fd in
(ic, oc)
let open_process_in cmd args =
let (child_in_fd, out_fd) = Unix.pipe () in
let (in_fd, child_out_fd) = Unix.pipe () in
Unix.set_close_on_exec in_fd;
Unix.set_close_on_exec out_fd;
Unix.close out_fd;
let pid =
Unix.(
create_process
(Exec_command.to_string cmd)
args
child_in_fd
child_out_fd
stderr)
in
Unix.close child_out_fd;
Unix.close child_in_fd;
let ic = (Unix.in_channel_of_descr in_fd, Some pid) in
ic
let close_process_in (ic, pid) =
match pid with
| None -> invalid_arg "Timeout.close_process_in"
| Some pid ->
Stdlib.close_in ic;
snd (Sys_utils.waitpid_non_intr [] pid)
let read_process ~timeout ~on_timeout ~reader cmd args =
let (ic, oc) = open_process cmd args in
with_timeout ~timeout ~on_timeout ~do_:(fun timeout ->
try reader timeout ic oc with
| exn ->
let e = Exception.wrap exn in
close_in ic;
Out_channel.close oc;
Exception.reraise e)
let open_connection ?timeout:_ sockaddr =
(* timeout isn't used in this Alarm_timeout implementation, but is used in Select_timeout *)
let (ic, oc) = Unix.open_connection sockaddr in
((ic, None), oc)
let shutdown_connection (ic, _) = Unix.shutdown_connection ic
let is_timeout_exn id = function
| Timeout { exn_id; _ } -> exn_id = id
| _ -> false
end
module Select_timeout = struct
(** Timeout *)
type t = {
timeout: float;
id: int;
}
let create timeout =
{ timeout = Unix.gettimeofday () +. timeout; id = mk_id () }
let with_timeout ~timeout ~on_timeout ~do_ =
let start_time = Unix.gettimeofday () in
let t = create (float timeout) in
try do_ t with
| Timeout { exn_id; timeout_time; deadline_time } when exn_id = t.id ->
on_timeout { start_time; timeout_time; deadline_time }
let check_timeout t =
let timeout_time = Unix.gettimeofday () in
if Float.(timeout_time > t.timeout) then
raise (Timeout { exn_id = t.id; timeout_time; deadline_time = t.timeout })
(** Channel *)
type channel = {
fd: Unix.file_descr;
buf: Bytes.t;
mutable curr: int;
mutable max: int;
mutable pid: int option;
}
type in_channel = channel
let buffer_size = 65536 - 9 (* From ocaml/byterun/io.h *)
let in_channel_of_descr fd =
let buf = Bytes.create buffer_size in
{ fd; buf; curr = 0; max = 0; pid = None }
let descr_of_in_channel { fd; _ } = fd
let open_in name =
let fd = Unix.openfile name [Unix.O_RDONLY; Unix.O_NONBLOCK] 0o640 in
in_channel_of_descr fd
let close_in tic = Unix.close tic.fd
let close_in_noerr tic =
try Unix.close tic.fd with
| _ -> ()
let close_process_in tic =
match tic.pid with
| None -> invalid_arg "Timeout.close_process_in"
| Some pid ->
close_in tic;
snd (Sys_utils.waitpid_non_intr [] pid)
(* A negative timeout for select means block until a fd is ready *)
let no_select_timeout = ~-.1.0
let select ?timeout rfds wfds xfds select_timeout =
(* A wrapper around Sys_utils.select_non_intr. If timeout would fire before the select's timeout,
* then change the select's timeout and throw an exception when it fires *)
match timeout with
(* No timeout set, fallback to Sys_utils.select_non_intr *)
| None -> Sys_utils.select_non_intr rfds wfds xfds select_timeout
| Some { timeout = deadline_time; id } ->
let now = Unix.gettimeofday () in
let remaining_time = deadline_time -. now in
(* Whoops, timeout already fired, throw right away! *)
if Float.(remaining_time < 0.) then
raise (Timeout { exn_id = id; timeout_time = now; deadline_time });
(* A negative select_timeout would mean wait forever *)
if
Float.(select_timeout >= 0.0 && select_timeout < remaining_time)
(* The select's timeout is smaller than our timeout, so leave it alone *)
then
Sys_utils.select_non_intr rfds wfds xfds select_timeout
else (
(* Our timeout is smaller, so use that *)
match Sys_utils.select_non_intr rfds wfds xfds remaining_time with
(* Timeout hit! Throw an exception! *)
| ([], [], []) ->
raise
(Timeout
{
exn_id = id;
timeout_time = Unix.gettimeofday ();
deadline_time;
})
(* Got a result before the timeout fired, so just return that *)
| ret -> ret
)
let do_read ?timeout tic =
match select ?timeout [tic.fd] [] [] no_select_timeout with
| ([], _, _) ->
failwith
"This should be unreachable. How did select return with no fd when there is no timeout?"
| ([_], _, _) ->
let read =
try Unix.read tic.fd tic.buf tic.max (buffer_size - tic.max) with
| Unix.Unix_error (Unix.EPIPE, _, _) -> raise End_of_file
in
tic.max <- tic.max + read;
read
| (_ :: _, _, _) -> assert false
(* Should never happen *)
let refill ?timeout tic =
tic.curr <- 0;
tic.max <- 0;
let nread = do_read ?timeout tic in
if nread = 0 then raise End_of_file;
nread
let unsafe_input ?timeout tic s ofs len =
let n =
if len > Int.max_value then
Int.max_value
else
len
in
let avail = tic.max - tic.curr in
if n <= avail then (
(* There is enough to read in the buffer. *)
Bytes.blit ~src:tic.buf ~src_pos:tic.curr ~dst:s ~dst_pos:ofs ~len:n;
tic.curr <- tic.curr + n;
n
) else if avail > 0 then (
(* Read the rest of the buffer. *)
Bytes.blit ~src:tic.buf ~src_pos:tic.curr ~dst:s ~dst_pos:ofs ~len:avail;
tic.curr <- tic.curr + avail;
avail
) else
(* No input to read, refill buffer. *)
let nread = refill ?timeout tic in
let n = min nread n in
Bytes.blit ~src:tic.buf ~src_pos:tic.curr ~dst:s ~dst_pos:ofs ~len:n;
tic.curr <- tic.curr + n;
n
let input ?timeout tic s ofs len =
if ofs < 0 || len < 0 || ofs > Bytes.length s - len then
invalid_arg "input"
else
unsafe_input ?timeout tic s ofs len
let input_char ?timeout tic =
if tic.curr = tic.max then ignore (refill ?timeout tic);
tic.curr <- tic.curr + 1;
Bytes.get tic.buf (tic.curr - 1)
(* Read in channel until we discover a '\n' *)
let input_scan_line ?timeout tic =
let rec scan_line tic pos =
if pos < tic.max then
if Char.equal (Bytes.get tic.buf pos) '\n' then
pos - tic.curr + 1
else
scan_line tic (pos + 1)
else
let pos =
if tic.curr <> 0 then (
tic.max <- tic.max - tic.curr;
Bytes.blit
~src:tic.buf
~src_pos:tic.curr
~dst:tic.buf
~dst_pos:0
~len:tic.max;
tic.curr <- 0;
tic.max
) else
pos
in
if tic.max = buffer_size then
-(tic.max - tic.curr)
else
let nread = do_read ?timeout tic in
if nread = 0 then
-(tic.max - tic.curr)
else
scan_line tic pos
in
scan_line tic tic.curr
let input_line ?timeout tic =
let rec build_result buf pos = function
| [] -> buf
| hd :: tl ->
let len = Bytes.length hd in
Bytes.blit ~src:hd ~src_pos:0 ~dst:buf ~dst_pos:(pos - len) ~len;
build_result buf (pos - len) tl
in
let rec scan accu len =
let n = input_scan_line ?timeout tic in
(* End of file, if accu is not empty, return the last line. *)
if n = 0 then
match accu with
| [] -> raise End_of_file
| _ -> build_result (Bytes.create len) len accu
(* New line found in the buffer. *)
else if n > 0 then (
let result = Bytes.create (n - 1) in
(* No need to keep '\n' *)
ignore (unsafe_input tic result 0 (n - 1));
ignore (input_char tic);
(* Skip newline *)
match accu with
| [] -> result
| _ ->
let len = len + n - 1 in
build_result (Bytes.create len) len (result :: accu)
(* New line not found in the buffer *)
) else
let ofs = Bytes.create (-n) in
ignore (unsafe_input tic ofs 0 (-n));
scan (ofs :: accu) (len - n)
in
Bytes.unsafe_to_string ~no_mutation_while_string_reachable:(scan [] 0)
let rec unsafe_really_input ?timeout tic buf ofs len =
if len = 0 then
()
else
let r = unsafe_input ?timeout tic buf ofs len in
if r = 0 then
raise End_of_file
else
unsafe_really_input ?timeout tic buf (ofs + r) (len - r)
let really_input ?timeout tic buf ofs len =
if ofs < 0 || len < 0 || ofs > Bytes.length buf - len then
invalid_arg "really_input"
else
unsafe_really_input ?timeout tic buf ofs len
(** Marshal *)
let marshal_magic = Bytes.of_string "\x84\x95\xA6\xBE"
let input_value ?timeout tic =
let magic = Bytes.create 4 in
Bytes.set magic 0 (input_char ?timeout tic);
Bytes.set magic 1 (input_char ?timeout tic);
Bytes.set magic 2 (input_char ?timeout tic);
Bytes.set magic 3 (input_char ?timeout tic);
if Bytes.(magic <> marshal_magic) then
failwith "Select.input_value: bad object.";
let b1 = int_of_char (input_char ?timeout tic) in
let b2 = int_of_char (input_char ?timeout tic) in
let b3 = int_of_char (input_char ?timeout tic) in
let b4 = int_of_char (input_char ?timeout tic) in
let len = ((b1 lsl 24) lor (b2 lsl 16) lor (b3 lsl 8) lor b4) + 12 in
let data = Bytes.create (len + 8) in
Bytes.blit ~src:magic ~src_pos:0 ~dst:data ~dst_pos:0 ~len:4;
Bytes.set data 4 (char_of_int b1);
Bytes.set data 5 (char_of_int b2);
Bytes.set data 6 (char_of_int b3);
Bytes.set data 7 (char_of_int b4);
begin
try unsafe_really_input ?timeout tic data 8 len with
| End_of_file -> failwith "Select.input_value: truncated object."
end;
Marshal.from_bytes data 0
(** Process *)
let open_process cmd args =
let (child_in_fd, out_fd) = Unix.pipe () in
let (in_fd, child_out_fd) = Unix.pipe () in
Unix.set_close_on_exec in_fd;
Unix.set_close_on_exec out_fd;
let pid =
Unix.(
create_process
(Exec_command.to_string cmd)
args
child_in_fd
child_out_fd
stderr)
in
Unix.close child_out_fd;
Unix.close child_in_fd;
let tic = in_channel_of_descr in_fd in
tic.pid <- Some pid;
let oc = Unix.out_channel_of_descr out_fd in
(tic, oc)
let open_process_in cmd args =
let (child_in_fd, out_fd) = Unix.pipe () in
let (in_fd, child_out_fd) = Unix.pipe () in
Unix.set_close_on_exec in_fd;
Unix.set_close_on_exec out_fd;
Unix.close out_fd;
let pid =
Unix.(
create_process
(Exec_command.to_string cmd)
args
child_in_fd
child_out_fd
stderr)
in
Unix.close child_out_fd;
Unix.close child_in_fd;
let tic = in_channel_of_descr in_fd in
tic.pid <- Some pid;
tic
let read_process ~timeout ~on_timeout ~reader cmd args =
let (tic, oc) = open_process cmd args in
let on_timeout timings =
Option.iter ~f:Sys_utils.terminate_process tic.pid;
tic.pid <- None;
on_timeout timings
in
with_timeout ~timeout ~on_timeout ~do_:(fun timeout ->
try reader timeout tic oc with
| exn ->
let e = Exception.wrap exn in
Option.iter ~f:Sys_utils.terminate_process tic.pid;
tic.pid <- None;
close_in tic;
Out_channel.close oc;
Exception.reraise e)
(** Socket *)
let open_connection ?timeout sockaddr =
let connect sock sockaddr =
(* connect binds the fd sock to the socket at sockaddr. If sock is nonblocking, and the
* connect call would block, it errors. You can then use select to wait for the connect
* to finish.
*
* On Windows, if the connect succeeds, sock will be returned in the writable fd set.
* If the connect fails, the sock will be returned in the exception fd set.
* https://msdn.microsoft.com/en-us/library/windows/desktop/ms737625(v=vs.85).aspx
*
* On Linux, the sock will always be returned in the writable fd set, and you're supposed
* to use getsockopt to read the SO_ERROR option at level SOL_SOCKET to figure out if the
* connect worked. However, this code is only used on Windows, so that's fine *)
try Unix.connect sock sockaddr with
| Unix.Unix_error ((Unix.EINPROGRESS | Unix.EWOULDBLOCK), _, _) -> begin
match select ?timeout [] [sock] [] no_select_timeout with
| (_, [], [exn_sock]) when Poly.(exn_sock = sock) ->
failwith "Failed to connect to socket"
| (_, [], _) ->
failwith
"This should be unreachable. How did select return with no fd when there is no timeout?"
| (_, [_sock], _) -> ()
| (_, _, _) -> assert false
end
| exn ->
let e = Exception.wrap exn in
Unix.close sock;
Exception.reraise e
in
let sock =
Unix.socket (Unix.domain_of_sockaddr sockaddr) Unix.SOCK_STREAM 0
in
Unix.set_nonblock sock;
connect sock sockaddr;
Unix.clear_nonblock sock;
Unix.set_close_on_exec sock;
let tic = in_channel_of_descr sock in
let oc = Unix.out_channel_of_descr sock in
(tic, oc)
let shutdown_connection { fd; _ } = Unix.(shutdown fd SHUTDOWN_SEND)
let is_timeout_exn { id; timeout = _ } = function
| Timeout { exn_id; _ } -> exn_id = id
| _ -> false
end
module type S = sig
type t
val with_timeout :
timeout:int -> on_timeout:(timings -> 'a) -> do_:(t -> 'a) -> 'a
val check_timeout : t -> unit
type in_channel
val in_channel_of_descr : Unix.file_descr -> in_channel
val descr_of_in_channel : in_channel -> Unix.file_descr
val open_in : string -> in_channel
val close_in : in_channel -> unit
val close_in_noerr : in_channel -> unit
val select :
?timeout:t ->
Unix.file_descr list ->
Unix.file_descr list ->
Unix.file_descr list ->
float ->
Unix.file_descr list * Unix.file_descr list * Unix.file_descr list
val input : ?timeout:t -> in_channel -> Bytes.t -> int -> int -> int
val really_input : ?timeout:t -> in_channel -> Bytes.t -> int -> int -> unit
val input_char : ?timeout:t -> in_channel -> char
val input_line : ?timeout:t -> in_channel -> string
val input_value : ?timeout:t -> in_channel -> 'a
val open_process :
Exec_command.t -> string array -> in_channel * Out_channel.t
val open_process_in : Exec_command.t -> string array -> in_channel
val close_process_in : in_channel -> Unix.process_status
val read_process :
timeout:int ->
on_timeout:(timings -> 'a) ->
reader:(t -> in_channel -> Out_channel.t -> 'a) ->
Exec_command.t ->
string array ->
'a
val open_connection :
?timeout:t -> Unix.sockaddr -> in_channel * Out_channel.t
val shutdown_connection : in_channel -> unit
val is_timeout_exn : t -> exn -> bool
end
let select = (module Select_timeout : S)
let alarm = (module Alarm_timeout : S)
include
(val if Sys.win32 then
select
else
alarm)
let read_connection ~timeout ~on_timeout ~reader sockaddr =
with_timeout ~timeout ~on_timeout ~do_:(fun timeout ->
let (tic, oc) = open_connection ~timeout sockaddr in
try reader timeout tic oc with
| exn ->
let e = Exception.wrap exn in
Out_channel.close oc;
Exception.reraise e) |
OCaml Interface | hhvm/hphp/hack/src/utils/sys/timeout.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** Helpers for handling timeout, in particular input timeout. *)
type timings = {
start_time: float;
deadline_time: float; (** caller-supplied deadline *)
timeout_time: float; (** actual time, after deadline, when we fired *)
}
[@@deriving show]
type t
(** The function `with_timeout` executes 'do_' for at most 'timeout'
seconds. If the `timeout` is reached, the `on_timeout` is executed
if available, otherwise the `Timeout` exception is raised.
On Unix platform, this function is based on interval timer ITIMER_REAL
which sends SIGALRM upon completion, and setting a signal handler for SIGALRM.
On Windows platform, this is based on the equivalent of `select`.
Hence, this module exports variant of basic input functions, adding
them a `timeout` parameter. It should correspond to the parameter of the
`do_` function.
For `do_` function based only on computation (and not I/O), you
should call the `check_timeout` function on a regular
basis. Otherwise, on Windows, the timeout will never be detected.
On Unix, the function `check_timeout` is no-op.
On Unix, the type `in_channel` is in fact an alias for
`Stdlib.in_channel`. *)
val with_timeout :
timeout:int -> on_timeout:(timings -> 'a) -> do_:(t -> 'a) -> 'a
val check_timeout : t -> unit
type in_channel
val open_in : string -> in_channel
val close_in : in_channel -> unit
val close_in_noerr : in_channel -> unit
val in_channel_of_descr : Unix.file_descr -> in_channel
val descr_of_in_channel : in_channel -> Unix.file_descr
(** Selects ready file descriptor. Based on Unix.select in Unix.
[timeout] is only there to achieve a similar effect as Unix interval
timers on Windows, but is ignored on Unix. On Windows,
[select ~timeout read write exn select_timeout] runs with a timeout
that is the minimum of [timeout and select_timeout] and throws
a Timeout exception on timeout.*)
val select :
?timeout:t ->
Unix.file_descr list ->
Unix.file_descr list ->
Unix.file_descr list ->
float ->
Unix.file_descr list * Unix.file_descr list * Unix.file_descr list
val input : ?timeout:t -> in_channel -> Bytes.t -> int -> int -> int
val really_input : ?timeout:t -> in_channel -> Bytes.t -> int -> int -> unit
val input_char : ?timeout:t -> in_channel -> char
val input_line : ?timeout:t -> in_channel -> string
val input_value : ?timeout:t -> in_channel -> 'a
val open_process : Exec_command.t -> string array -> in_channel * out_channel
val open_process_in : Exec_command.t -> string array -> in_channel
val close_process_in : in_channel -> Unix.process_status
val read_process :
timeout:int ->
on_timeout:(timings -> 'a) ->
reader:(t -> in_channel -> out_channel -> 'a) ->
Exec_command.t ->
string array ->
'a
val open_connection : ?timeout:t -> Unix.sockaddr -> in_channel * out_channel
val read_connection :
timeout:int ->
on_timeout:(timings -> 'a) ->
reader:(t -> in_channel -> out_channel -> 'a) ->
Unix.sockaddr ->
'a
val shutdown_connection : in_channel -> unit
(* Some silly people like to catch all exceptions. This means they need to explicitly detect and
* reraise the timeout exn. *)
val is_timeout_exn : t -> exn -> bool |
OCaml | hhvm/hphp/hack/src/utils/sys/timer.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* Warning: This is the ONLY code that should be using sigalrm. Any code using it should use Timer
* instead.
*
* This is a timer which lets you schedule callbacks to be invoked later. There are a few things
* you should know:
*
* 1. Timer will not work on Windows, since Unix.setitimer is not implemented there. If you are
* building a cross-platform feature, you'll need a Windows-specific implementation. For example,
* Timeout uses select instead of timers to implement timeouts on Windows.
* 2. Timer is built using signals, which can cause your Unix calls to error with EINTR, since
* you are interupting them. Not a huge deal, just worth being aware of.
*
* The Timer implementation generally works as follows:
*
* 1. We keep a priority queue of timers, where the shortest timer is at the front
* 2. The shortest timer is popped off the priority queue and put in current_timer
* 3. We set a Unix timer to fire when current_timer is due
* 4. When the Unix timer fires, we execute the current timer's callback and schedule the next timer
*)
open Base
module Sys = Stdlib.Sys
type t = int
type timer = {
target_time: float;
callback: unit -> unit;
id: int;
}
module TimerKey = struct
type t = timer
let compare a b = Float.compare a.target_time b.target_time
end
(** Mutable priority queue, ordered by target time, with O(log(n)) pushes and pops *)
module TimerQueue = PriorityQueue.Make (TimerKey)
let next_id = ref 1
let queue : TimerQueue.t = TimerQueue.make_empty 8
let current_timer : timer option ref = ref None
let cancelled : ISet.t ref = ref ISet.empty
(** Gets the next ongoing timer. Any expired timers have their callbacks invoked *)
let rec get_next_timer ~exns =
if TimerQueue.is_empty queue then
(None, List.rev exns)
else
let timer = TimerQueue.pop queue in
(* Skip cancelled timers *)
if ISet.mem timer.id !cancelled then begin
cancelled := ISet.remove timer.id !cancelled;
get_next_timer ~exns
end else
let interval = timer.target_time -. Unix.gettimeofday () in
if Float.(interval <= 0.0) then
let exns =
try
timer.callback ();
exns
with
| exn -> exn :: exns
in
get_next_timer ~exns
else
(Some timer, List.rev exns)
(** [schedule_non_recurring interval] sets the Unix ITIMER_REAL interval timer
for [interval] seconds, which will deliver signal SIGALRM upon completion. *)
let schedule_non_recurring interval =
Unix.(
let interval_timer =
{
it_interval = 0.0;
(* Don't restart timer when it finishes *)
it_value = interval (* How long to wait *);
}
in
ignore (setitimer ITIMER_REAL interval_timer))
external reraise : exn -> 'a = "%reraise"
(** Calls the callback of the current timer and schedule next timer if any. *)
let rec ding_fries_are_done _ =
let exns =
try
Option.iter !current_timer ~f:(fun timer -> timer.callback ());
[]
with
| exn -> [exn]
in
current_timer := None;
schedule ~exns ()
(** Pop timer queue to get the current timer and schedule its callback by setting the Unix
ITIMER_REAL interval timer and setting a signal handler for SIGALRM. *)
and schedule ?(exns = []) () =
(* Stop the current timer, if there is one, to avoid races *)
schedule_non_recurring 0.0;
(* If there's a current timer, requeue it *)
Option.iter !current_timer ~f:(TimerQueue.push queue);
let (timer, exns) = get_next_timer ~exns in
current_timer := timer;
ignore (Sys.signal Sys.sigalrm (Sys.Signal_handle ding_fries_are_done));
(* Start the timer back up *)
Option.iter timer ~f:(fun t ->
schedule_non_recurring (t.target_time -. Unix.gettimeofday ()));
(* If we executed more than one callback this time and more than one callback threw an
* exception, then we just arbitrarily choose one to throw. Oh well :/ *)
match exns with
| exn :: _ -> reraise exn
| _ -> ()
(** Will invoke [callback ()] after [interval] seconds *)
let set_timer ~interval ~callback =
let target_time = Unix.gettimeofday () +. interval in
let id = !next_id in
Int.incr next_id;
TimerQueue.push queue { target_time; callback; id };
(match !current_timer with
| Some current_timer when Float.(target_time >= current_timer.target_time) ->
(* There's currently a timer and the new timer will fire after it. As an optimization we can
skip scheduling *)
()
| _ ->
(* There's currently a timer, but the new timer will fire first or there is no current timer *)
schedule ());
id
let cancel_timer id =
cancelled := ISet.add id !cancelled;
match !current_timer with
| Some timer when timer.id = id ->
current_timer := None;
schedule ()
| _ -> () |
OCaml Interface | hhvm/hphp/hack/src/utils/sys/timer.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* Warning: This is the ONLY code that should be using sigalrm. Any code using it should use Timer
* instead.
*
* This is a timer which lets you schedule callbacks to be invoked later. There are a few things
* you should know:
*
* 1. Timer will not work on Windows, since Unix.setitimer is not implemented there. If you are
* building a cross-platform feature, you'll need a Windows-specific implementation. For example,
* Timeout uses select instead of timers to implement timeouts on Windows.
* 2. Timer is built using signals, which can cause your Unix calls to error with EINTR, since
* you are interupting them. Not a huge deal, just worth being aware of.
*)
type t
(** Will invoke [callback ()] after [interval] seconds.
Based on Unix interval timer ITIMER_REAL which sends SIGALRM upon completion,
and setting a signal handler for SIGALRM which invokes [callback]. *)
val set_timer : interval:float -> callback:(unit -> unit) -> t
(** Will prevent a future timer from firing *)
val cancel_timer : t -> unit |
OCaml | hhvm/hphp/hack/src/utils/sys/tmp.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(*****************************************************************************)
(* Handling where our temporary files go *)
(*****************************************************************************)
let temp_dir parent_dir prefix =
Sys_utils.mkdir_no_fail parent_dir;
let tmpdir =
Filename.concat
parent_dir
(Printf.sprintf "%s_%06x" prefix (Random.bits ()))
in
Sys_utils.mkdir_no_fail tmpdir;
tmpdir
let hh_server_tmp_dir =
try Sys.getenv "HH_TMPDIR" with
| _ ->
Path.to_string
@@ Path.concat (Path.make Sys_utils.temp_dir_name) "hh_server"
let ( // ) = Filename.concat
let make_dir_in_tmp ~description_what_for ~root =
let tmp = hh_server_tmp_dir in
assert (String.length description_what_for > 0);
let dir = tmp // description_what_for in
let dir =
match root with
| None -> dir
| Some root -> dir // Path.slash_escaped_string_of_path root
in
Sys_utils.mkdir_p dir;
dir |
OCaml Interface | hhvm/hphp/hack/src/utils/sys/tmp.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** [temp_dir parent_dir prefix ] creates a new temporary directory under parent_dir.
The name of that directory is made of the given prefix followed by a random integer. *)
val temp_dir : string -> string -> string
val hh_server_tmp_dir : string
(** Create subdirectory in [hh_server_tmp_dir] as [description_what_for]/zSpathzStozS[root] *)
val make_dir_in_tmp :
description_what_for:string -> root:Path.t option -> string |
OCaml | hhvm/hphp/hack/src/utils/sys/tty.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type raw_color =
| Default
| Black
| Red
| Green
| Yellow
| Blue
| Magenta
| Cyan
| White
type style =
| Normal of raw_color
| Bold of raw_color
| Dim of raw_color
| Italics of raw_color
| Underline of raw_color
| BoldDim of raw_color
| BoldItalics of raw_color
| BoldUnderline of raw_color
| DimUnderline of raw_color
| NormalWithBG of raw_color * raw_color
| BoldWithBG of raw_color * raw_color
type color_mode =
| Color_Always
| Color_Never
| Color_Auto
let text_num = function
| Default -> "39"
| Black -> "30"
| Red -> "31"
| Green -> "32"
| Yellow -> "33"
| Blue -> "34"
| Magenta -> "35"
| Cyan -> "36"
| White -> "37"
let background_num = function
| Default -> "49"
| Black -> "40"
| Red -> "41"
| Green -> "42"
| Yellow -> "43"
| Blue -> "44"
| Magenta -> "45"
| Cyan -> "46"
| White -> "47"
let color_num = function
| Default -> "0"
| x -> text_num x
let style_num = function
| Normal c -> color_num c
| Bold c -> color_num c ^ ";1"
| Dim c -> color_num c ^ ";2"
| Italics c -> color_num c ^ ";3"
| Underline c -> color_num c ^ ";4"
| BoldDim c -> color_num c ^ ";1;2"
| BoldItalics c -> color_num c ^ ";1;3"
| BoldUnderline c -> color_num c ^ ";1;4"
| DimUnderline c -> color_num c ^ ";2;4"
| NormalWithBG (text, bg) -> text_num text ^ ";" ^ background_num bg
| BoldWithBG (text, bg) -> text_num text ^ ";" ^ background_num bg ^ ";1"
let style_num_from_list color styles =
List.fold_left styles ~init:(color_num color) ~f:(fun accum style ->
match style with
| `Bold -> accum ^ ";1"
| `Dim -> accum ^ ";2"
| `Italics -> accum ^ ";3"
| `Underline -> accum ^ ";4")
let supports_color =
let memo = ref None in
fun () ->
match !memo with
| Some x -> x
| None ->
let value =
match Sys_utils.getenv_term () with
| None -> false
| Some term -> Unix.isatty Unix.stdout && not (String.equal term "dumb")
in
memo := Some value;
value
let should_color color_mode =
let force_color =
Sys_utils.get_env "FORCE_ERROR_COLOR"
|> Option.value_map ~default:false ~f:(fun s -> String.equal s "true")
in
match color_mode with
| Color_Always -> true
| Color_Never -> false
| Color_Auto -> supports_color () || force_color
(* See https://github.com/yarnpkg/yarn/issues/405. *)
let supports_emoji () =
(not (String.equal Sys.os_type "Win32")) && supports_color ()
let apply_color ?(color_mode = Color_Auto) c s : string =
if should_color color_mode then
Printf.sprintf "\x1b[%sm%s\x1b[0m" (style_num c) s
else
Printf.sprintf "%s" s
let apply_color_from_style ?(color_mode = Color_Auto) style s : string =
if should_color color_mode then
Printf.sprintf "\x1b[%sm%s\x1b[0m" style s
else
Printf.sprintf "%s" s
let print_one ?(color_mode = Color_Auto) ?(out_channel = Stdio.stdout) c s =
Stdlib.Printf.fprintf out_channel "%s" (apply_color ~color_mode c s)
let cprint ?(color_mode = Color_Auto) ?(out_channel = Stdio.stdout) strs =
List.iter strs ~f:(fun (c, s) -> print_one ~color_mode ~out_channel c s)
let cprintf ?(color_mode = Color_Auto) ?(out_channel = Stdio.stdout) c =
Printf.ksprintf (print_one ~color_mode ~out_channel c)
(* ANSI escape sequence to clear whole line *)
let clear_line_seq = "\r\x1b[0K"
let print_clear_line chan =
if Unix.isatty (Unix.descr_of_out_channel chan) then
Printf.fprintf chan "%s%!" clear_line_seq
else
()
(* Read a single char and return immediately, without waiting for a newline.
* `man termios` to see how termio works. *)
let read_char () =
let tty = Unix.(openfile "/dev/tty" [O_RDWR] 0o777) in
let termio = Unix.tcgetattr tty in
let new_termio =
{ termio with Unix.c_icanon = false; c_vmin = 1; c_vtime = 0 }
in
Unix.tcsetattr tty Unix.TCSANOW new_termio;
let buf = Bytes.create 1 in
let bytes_read = UnixLabels.read tty ~buf ~pos:0 ~len:1 in
Unix.tcsetattr tty Unix.TCSANOW termio;
assert (bytes_read = 1);
Bytes.get buf 0
(* Prompt the user to pick one character out of a given list. If other
* characters are entered, the prompt repeats indefinitely. *)
let read_choice message choices =
let rec loop () =
Stdio.printf
"%s (%s)%!"
message
(String.concat ~sep:"|" (List.map choices ~f:(String.make 1)));
let choice = read_char () in
Stdio.print_endline "";
if List.mem ~equal:Char.equal choices choice then
choice
else
loop ()
in
loop ()
let eprintf fmt =
if Unix.(isatty stderr) then
Printf.eprintf fmt
else
Printf.ifprintf stderr fmt
(* Gets the number of columns in the current terminal window through
* [`tput cols`][1]. If the command fails in any way then `None` will
* be returned.
*
* This value may change over the course of program execution if a user resizes
* their terminal.
*
* [1]: http://invisible-island.net/ncurses/man/tput.1.html
*)
let get_term_cols () =
if (not Sys.unix) || not (supports_color ()) then
None
else
Option.map ~f:int_of_string (Sys_utils.exec_read "tput cols") |
OCaml Interface | hhvm/hphp/hack/src/utils/sys/tty.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
* *)
type raw_color =
| Default
| Black
| Red
| Green
| Yellow
| Blue
| Magenta
| Cyan
| White
type style =
| Normal of raw_color
| Bold of raw_color
| Dim of raw_color
| Italics of raw_color
| Underline of raw_color
| BoldDim of raw_color
| BoldItalics of raw_color
| BoldUnderline of raw_color
| DimUnderline of raw_color
| NormalWithBG of raw_color * raw_color
| BoldWithBG of raw_color * raw_color
type color_mode =
| Color_Always
| Color_Never
| Color_Auto
val apply_color : ?color_mode:color_mode -> style -> string -> string
val style_num_from_list :
raw_color -> [< `Bold | `Dim | `Italics | `Underline ] list -> string
val apply_color_from_style :
?color_mode:color_mode -> string -> string -> string
(*
* Print a sequence of colorized strings to stdout/stderr, using ANSI color
* escapes codes.
*)
val cprint :
?color_mode:color_mode ->
?out_channel:out_channel ->
(style * string) list ->
unit
val cprintf :
?color_mode:color_mode ->
?out_channel:out_channel ->
style ->
('a, unit, string, unit) format4 ->
'a
(* Output a "clear current line" escape sequence to out_channel if it's
* a TTY and a newline otherwise *)
val print_clear_line : out_channel -> unit
(* Read a single char and return immediately, without waiting for a newline. *)
val read_char : unit -> char
(* Prompt the user to pick one character out of a given list. If other
* characters are entered, the prompt repeats indefinitely. *)
val read_choice : string -> char list -> char
(* Only print if we are attached to a tty *)
val eprintf : ('a, out_channel, unit) format -> 'a
(* Whether the terminal supports color *)
val supports_color : unit -> bool
val should_color : color_mode -> bool
(* Whether the terminal supports emoji *)
val supports_emoji : unit -> bool
(* Gets the column width of the current terminal. *)
val get_term_cols : unit -> int option |
TOML | hhvm/hphp/hack/src/utils/test/Cargo.toml | # @generated by autocargo
[package]
name = "line_break_map_tests"
version = "0.0.0"
edition = "2021"
[lib]
path = "line_break_map_tests.rs"
test = false
doctest = false
[dependencies]
line_break_map = { version = "0.0.0", path = "../line_break_map" }
ocamlrep_ocamlpool = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" } |
OCaml | hhvm/hphp/hack/src/utils/test/ffi_runner.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
external offset_to_file_pos_triple : string -> int -> int * int * int
= "offset_to_file_pos_triple"
external offset_to_file_pos_triple_with_cursor :
string -> int -> int -> int * int * int
= "offset_to_file_pos_triple_with_cursor"
external offset_to_line_start_offset : string -> int -> int
= "offset_to_line_start_offset"
external offset_to_position : string -> int -> int * int = "offset_to_position"
external position_to_offset : string -> bool -> int -> int -> int * bool
= "position_to_offset"
let all = List.for_all (fun x -> x)
let rec range a b =
if a > b then
[]
else
a :: range (a + 1) b
let rec prod l1 l2 =
match (l1, l2) with
| ([], _)
| (_, []) ->
[]
| (h1 :: t1, h2 :: t2) -> ((h1, h2) :: prod [h1] t2) @ prod t1 l2
let run_1 data =
let len = String.length data in
let lbm = Line_break_map.make data in
let inputs = range (-1) (len + 1) in
let cmp i =
Line_break_map.reset_global_state ();
let ((e1, e2, e3) as e) = Line_break_map.offset_to_file_pos_triple lbm i in
let ((a1, a2, a3) as a) = offset_to_file_pos_triple data i in
if a <> e then (
Printf.printf
"Array: %s : len: %d \n"
(Line_break_map.show lbm)
(String.length data);
Printf.printf "String: %s\nInput: %d\n" data i;
Printf.printf "Expected %d %d %d\nActual %d %d %d\n\n" e1 e2 e3 a1 a2 a3;
false
) else
true
in
List.map cmp inputs |> all
let run_2 data =
let len = String.length data in
let lbm = Line_break_map.make data in
let inputs = range (-1) (len + 1) in
let inputs = prod inputs inputs in
let cmp (i, j) =
Line_break_map.reset_global_state ();
ignore (Line_break_map.offset_to_file_pos_triple lbm j);
let ((e1, e2, e3) as e) = Line_break_map.offset_to_file_pos_triple lbm i in
let ((a1, a2, a3) as a) = offset_to_file_pos_triple_with_cursor data j i in
if a <> e then (
Printf.printf
"Array: %s : len: %d \n"
(Line_break_map.show lbm)
(String.length data);
Printf.printf "String: %s\nInput: %d\n" data i;
Printf.printf "Expected %d %d %d\nActual %d %d %d\n\n" e1 e2 e3 a1 a2 a3;
false
) else
true
in
List.map cmp inputs |> all
let run_3 data =
let len = String.length data in
let lbm = Line_break_map.make data in
let inputs = range (-1) (len + 1) in
let cmp i =
Line_break_map.reset_global_state ();
let e = Line_break_map.offset_to_line_start_offset lbm i in
let a = offset_to_line_start_offset data i in
if a <> e then (
Printf.printf
"Array: %s : len: %d \n"
(Line_break_map.show lbm)
(String.length data);
Printf.printf "String: %s\nInput: %d\n" data i;
Printf.printf "Expected %d \nActual %d \n\n" e a;
false
) else
true
in
List.map cmp inputs |> all
let run_4 data =
let len = String.length data in
let lbm = Line_break_map.make data in
let inputs = range (-1) (len + 1) in
let cmp i =
Line_break_map.reset_global_state ();
let ((e1, e2) as e) = Line_break_map.offset_to_position lbm i in
let ((a1, a2) as a) = offset_to_position data i in
if a <> e then (
Printf.printf
"Array: %s : len: %d \n"
(Line_break_map.show lbm)
(String.length data);
Printf.printf "String: %s\nInput: %d\n" data i;
Printf.printf "Expected %d %d\nActual %d %d\n\n" e1 e2 a1 a2;
false
) else
true
in
List.map cmp inputs |> all
let exception_to_bool f =
try
let x = f () in
(x, true)
with
| _ -> (0, false)
let run_5 data =
let len = String.length data in
let lbm = Line_break_map.make data in
let inputs = range (-1) (len + 1) in
let inputs = prod inputs inputs in
let inputs = prod inputs [true; false] in
let cmp ((i, j), existing) =
Line_break_map.reset_global_state ();
let ((e1, e2) as e) =
exception_to_bool (fun () ->
Line_break_map.position_to_offset ~existing lbm (i, j))
in
let ((a1, a2) as a) = position_to_offset data existing i j in
if a <> e then (
Printf.printf
"Array: %s : len: %d \n"
(Line_break_map.show lbm)
(String.length data);
Printf.printf "String: %s\nInput: %d, %d, %b\n" data i j existing;
Printf.printf "Expected %d %b\nActual %d %b\n\n" e1 e2 a1 a2;
false
) else
true
in
List.map cmp inputs |> all
let data_ =
[
"";
"\n";
"\n\n";
"12345";
"12345\n";
"123\n123";
"\n123\n123\n";
"";
"\r\n";
"\r\n\r\n";
"12345";
"12345\r\n";
"123\r\n123";
"\r\n123\r\n123\r\n";
"\r\r\n";
"\r\n\r\n";
"\n\r\n\r\n";
]
let data = String.concat "" data_ :: data_
let tests = [run_1; run_2; run_3; run_4; run_5]
let () =
let result = all (List.map (fun t -> all (List.map t data)) tests) in
if not result then failwith "Fail" |
Rust | hhvm/hphp/hack/src/utils/test/line_break_map_tests.rs | // Copyright (c) 2019, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use line_break_map::LineBreakMap;
use ocamlrep_ocamlpool::ocaml_ffi;
ocaml_ffi! {
fn offset_to_file_pos_triple(string: String, offset: isize) -> (isize, isize, isize) {
let line_break_map = LineBreakMap::new(string.as_bytes());
line_break_map.offset_to_file_pos_triple_original(offset)
}
fn offset_to_file_pos_triple_with_cursor(
string: String,
cursor_offset: isize,
offset: isize,
) -> (isize, isize, isize) {
let line_break_map = LineBreakMap::new(string.as_bytes());
line_break_map.offset_to_file_pos_triple_original(cursor_offset);
line_break_map.offset_to_file_pos_triple_original(offset)
}
fn offset_to_line_start_offset(string: String, offset: isize) -> isize {
let line_break_map = LineBreakMap::new(string.as_bytes());
line_break_map.offset_to_line_start_offset(offset)
}
fn offset_to_position(string: String, offset: isize) -> (isize, isize) {
let line_break_map = LineBreakMap::new(string.as_bytes());
line_break_map.offset_to_position(offset)
}
fn position_to_offset(string: String, existing: bool, i: isize, j: isize) -> (isize, bool) {
let line_break_map = LineBreakMap::new(string.as_bytes());
match line_break_map.position_to_offset(existing, i, j) {
Some(p) => (p, true),
None => (0, false),
}
}
} |
Rust | hhvm/hphp/hack/src/utils/test/macro_test_util.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::fmt::Display;
use proc_macro2::TokenStream;
use proc_macro2::TokenTree;
fn mismatch(ta: Option<TokenTree>, tb: Option<TokenTree>, ax: &TokenStream, bx: &TokenStream) -> ! {
panic!(
"Mismatch!\nLeft: {}\nRight: {}\nwhen comparing\nLeft: {}\nRight: {}\n",
ta.map_or("None".into(), |t| t.to_string()),
tb.map_or("None".into(), |t| t.to_string()),
ax,
bx
);
}
pub fn assert_pat_eq<E: Display>(a: Result<TokenStream, E>, b: TokenStream) {
let a = match a {
Err(err) => {
panic!("Unexpected error '{}'", err);
}
Ok(ok) => ok,
};
fn inner_cmp(a: TokenStream, b: TokenStream, ax: &TokenStream, bx: &TokenStream) {
let mut ia = a.into_iter();
let mut ib = b.into_iter();
loop {
let t_a = ia.next();
let t_b = ib.next();
let (t_a, t_b) = match (t_a, t_b) {
(None, None) => break,
(None, Some(TokenTree::Punct(t))) if t.as_char() == ',' && ib.next().is_none() => {
// Allow one side to have a trailing comma
break;
}
(Some(TokenTree::Punct(t)), None) if t.as_char() == ',' && ia.next().is_none() => {
// Allow one side to have a trailing comma
break;
}
(t_a @ Some(_), t_b @ None) | (t_a @ None, t_b @ Some(_)) => {
mismatch(t_a, t_b, ax, bx);
}
(Some(a), Some(b)) => (a, b),
};
match (&t_a, &t_b) {
(TokenTree::Ident(a), TokenTree::Ident(b)) if a == b => {}
(TokenTree::Literal(a), TokenTree::Literal(b))
if a.to_string() == b.to_string() => {}
(TokenTree::Punct(a), TokenTree::Punct(b)) if a.to_string() == b.to_string() => {}
(TokenTree::Group(ga), TokenTree::Group(gb))
if ga.delimiter() == gb.delimiter() =>
{
inner_cmp(ga.stream(), gb.stream(), ax, bx);
}
(TokenTree::Group(_), _)
| (TokenTree::Ident(_), _)
| (TokenTree::Punct(_), _)
| (TokenTree::Literal(_), _) => mismatch(Some(t_a), Some(t_b), ax, bx),
}
}
}
inner_cmp(a.clone(), b.clone(), &a, &b);
}
pub fn assert_error<E: Display>(a: Result<TokenStream, E>, b: &str) {
match a {
Ok(a) => panic!("Expected error but got:\n{}", a),
Err(e) => {
let a = format!("{}", e);
assert_eq!(a, b, "Incorrect error")
}
}
} |
TOML | hhvm/hphp/hack/src/utils/test/arena_deserializer/Cargo.toml | # @generated by autocargo
[package]
name = "arena_deserializer_tests"
version = "0.0.0"
edition = "2021"
[lib]
path = "lib.rs"
[dev-dependencies]
arena_deserializer = { version = "0.0.0", path = "../../arena_deserializer" }
bincode = "1.3.3"
bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] }
bumpalo = { version = "3.11.1", features = ["collections"] }
oxidized_by_ref = { version = "0.0.0", path = "../../../oxidized_by_ref" }
relative_path = { version = "0.0.0", path = "../../rust/relative_path" }
serde = { version = "1.0.176", features = ["derive", "rc"] }
serde_json = { version = "1.0.100", features = ["float_roundtrip", "unbounded_depth"] } |
Rust | hhvm/hphp/hack/src/utils/test/arena_deserializer/lib.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
#![cfg(test)]
use arena_deserializer::*;
use bumpalo::Bump;
use serde::Deserialize;
use serde::Serialize;
fn round_trip<'a, X: Deserialize<'a> + Serialize + Eq + std::fmt::Debug>(x: X, arena: &'a Bump) {
let se = serde_json::to_string(&x).unwrap();
let mut de = serde_json::Deserializer::from_str(&se);
let de = ArenaDeserializer::new(arena, &mut de);
let x2 = X::deserialize(de).unwrap();
assert_eq!(x, x2);
use bincode::Options;
let op = bincode::config::Options::with_native_endian(bincode::options());
let se = op.serialize(&x).unwrap();
let mut de = bincode::de::Deserializer::from_slice(se.as_slice(), op);
let de = arena_deserializer::ArenaDeserializer::new(arena, &mut de);
let x2 = X::deserialize(de).unwrap();
assert_eq!(x, x2, "Bytes: {:?}", se);
}
#[test]
fn impl_deserialize_in_arena_tests() {
#[derive(Deserialize)]
struct N;
impl_deserialize_in_arena!(N);
#[derive(Deserialize)]
struct A<'a>(std::marker::PhantomData<&'a ()>);
impl_deserialize_in_arena!(A<'arena>);
#[derive(Deserialize)]
struct B<'a, 'b>(std::marker::PhantomData<(&'a (), &'b ())>);
impl_deserialize_in_arena!(B<'arena, 'arena>);
#[derive(Deserialize)]
struct C<'a, T>(std::marker::PhantomData<(&'a (), T)>);
impl_deserialize_in_arena!(C<'arena, T>);
#[derive(Deserialize)]
struct D<T>(std::marker::PhantomData<T>);
impl_deserialize_in_arena!(D<T>);
#[derive(Deserialize)]
struct E<T, S>(std::marker::PhantomData<(T, S)>);
impl_deserialize_in_arena!(E<T, S>);
}
#[test]
fn example() {
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
struct I(isize);
impl_deserialize_in_arena!(I);
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
#[serde(bound(deserialize = "T: 'de + arena_deserializer::DeserializeInArena<'de>"))]
enum Num<'a, T> {
#[serde(deserialize_with = "arena_deserializer::arena")]
Base(&'a I),
#[serde(deserialize_with = "arena_deserializer::arena")]
Succ(&'a Num<'a, T>),
#[serde(deserialize_with = "arena_deserializer::arena")]
Sum(&'a Num<'a, T>, &'a Num<'a, T>),
#[serde(deserialize_with = "arena_deserializer::arena")]
List(&'a [&'a Num<'a, T>]),
#[serde(deserialize_with = "arena_deserializer::arena")]
ListValue(&'a [Num<'a, T>]),
#[serde(deserialize_with = "arena_deserializer::arena")]
Str(&'a str),
String(String),
#[serde(deserialize_with = "arena_deserializer::arena")]
OptRef(Option<&'a isize>),
#[serde(deserialize_with = "arena_deserializer::arena")]
Opt(Option<isize>),
#[serde(deserialize_with = "arena_deserializer::arena")]
PairRef(&'a (bool, &'a isize)),
#[serde(deserialize_with = "arena_deserializer::arena")]
Pair((&'a Num<'a, T>, &'a isize)),
#[serde(deserialize_with = "arena_deserializer::arena")]
T(T),
#[serde(deserialize_with = "arena_deserializer::arena")]
BStr(&'a bstr::BStr),
Record {
#[serde(deserialize_with = "arena_deserializer::arena")]
left: &'a Num<'a, T>,
#[serde(deserialize_with = "arena_deserializer::arena")]
right: &'a Num<'a, T>,
},
#[serde(deserialize_with = "arena_deserializer::arena")]
RP(&'a oxidized_by_ref::relative_path::RelativePath<'a>),
//#[serde(deserialize_with = "arena_deserializer::arena")]
//Cell(std::cell::Cell<&'a Num<'a, T>>),
}
impl_deserialize_in_arena!(Num<'arena, T>);
let arena = Bump::new();
let x = I(0);
round_trip(x, &arena);
let i: Num<'_, ()> = Num::Str("aa");
let x = Num::Succ(&i);
round_trip(x, &arena);
let i: Num<'_, ()> = Num::Str("aa");
let x = Num::Sum(&i, &i);
round_trip(x, &arena);
let i = I(3);
let x: Num<'_, ()> = Num::Base(&i);
round_trip(x, &arena);
let i = I(1);
let n1: Num<'_, ()> = Num::Base(&i);
let n2 = Num::Succ(&n1);
let ls = vec![&n1, &n2];
let x = Num::List(&ls);
round_trip(x, &arena);
let i = I(1);
let n1: Num<'_, ()> = Num::Base(&i);
let n2 = Num::Succ(&n1);
let n1 = Num::Base(&i);
let ls = vec![n1, n2];
let x = Num::ListValue(&ls);
round_trip(x, &arena);
let i: isize = 3;
let x: Num<'_, ()> = Num::OptRef(Some(&i));
round_trip(x, &arena);
let i: isize = 3;
let x: Num<'_, ()> = Num::Opt(Some(i));
round_trip(x, &arena);
let i: isize = 1;
let n: Num<'_, ()> = Num::Opt(Some(3));
let p = (&n, &i);
let x = Num::Pair(p);
round_trip(x, &arena);
let x = Num::T(true);
round_trip(x, &arena);
let s: &bstr::BStr = "abc".into();
let x: Num<'_, ()> = Num::BStr(s);
round_trip(x, &arena);
let s = oxidized_by_ref::relative_path::RelativePath::new(
relative_path::Prefix::Dummy,
std::path::Path::new("/tmp/foo.php"),
);
let x: Num<'_, ()> = Num::RP(&s);
round_trip(x, &arena);
}
#[test]
fn complex() {
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(bound(deserialize = "V: 'de + arena_deserializer::DeserializeInArena<'de>"))]
struct Set<'a, V>(
#[serde(deserialize_with = "arena_deserializer::arena", borrow)] Option<&'a Node<'a, V>>,
#[serde(deserialize_with = "arena_deserializer::arena", borrow)] &'a isize, // test only
);
impl_deserialize_in_arena!(Set<'arena, V>);
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(bound(deserialize = "V: 'de + arena_deserializer::DeserializeInArena<'de>"))]
struct Node<'a, V>(
#[serde(deserialize_with = "arena_deserializer::arena", borrow)] Set<'a, V>,
#[serde(deserialize_with = "arena_deserializer::arena")] V,
usize,
);
impl_deserialize_in_arena!(Node<'arena, V>);
let arena = bumpalo::Bump::new();
let dummy: &isize = &3;
let x: Set<'_, ()> = Set(None, dummy);
round_trip(x, &arena);
let v: isize = 3;
let n = Node(Set(None, dummy), &v, 1);
let x = Set(Some(&n), dummy);
round_trip(x, &arena);
let v: isize = 3;
let n = Node(Set(None, dummy), &v, 1);
let x: Set<'_, &isize> = Set(Some(&n), dummy);
let n = Node(Set(None, dummy), &x, 1);
let x: Set<'_, &Set<'_, &isize>> = Set(Some(&n), dummy);
round_trip(x, &arena);
} |
TOML | hhvm/hphp/hack/src/utils/test/macro_test_util/Cargo.toml | # @generated by autocargo
[package]
name = "macro_test_util"
version = "0.0.0"
edition = "2021"
[lib]
path = "../macro_test_util.rs"
[dependencies]
proc-macro2 = { version = "1.0.64", features = ["span-locations"] } |
TOML | hhvm/hphp/hack/src/utils/unwrap_ocaml/Cargo.toml | # @generated by autocargo
[package]
name = "unwrap_ocaml"
version = "0.0.0"
edition = "2021"
[lib]
path = "../unwrap_ocaml.rs"
test = false
doctest = false
[dependencies]
libc = "0.2.139" |
OCaml | hhvm/hphp/hack/src/utils/username/sys_username.ml | (** When sudo is used to execute a process, effective user ID is root,
* but user id will still be the original user. *)
let get_real_user_name () =
let uid = Unix.getuid () in
if uid = 1 then
None
else
let pwd_entry = Unix.getpwuid uid in
Some pwd_entry.Unix.pw_name
let get_logged_in_username () =
let name =
try Unix.getlogin () with
| Unix.Unix_error (Unix.ENOENT, m, _) when String.equal m "getlogin" ->
begin
try
(* Linux getlogin(3) man page suggests checking LOGNAME. *)
Sys.getenv "LOGNAME"
with
| Not_found -> Sys.getenv "SUDO_USER"
end
in
try
if String.equal name "root" then
get_real_user_name ()
else
Some name
with
| Not_found -> None |
OCaml Interface | hhvm/hphp/hack/src/utils/username/sys_username.mli | (*
* Tries to get the logged in username via various ways, consecutively
* as each one fails.
*)
val get_logged_in_username : unit -> string option |
OCaml | hhvm/hphp/hack/src/utils/username/sys_username_runner.ml | let () =
match Sys_username.get_logged_in_username () with
| Some name -> Printf.printf "%s\n" name
| None -> failwith "Can't get logged in username" |
Rust | hhvm/hphp/hack/src/utils/write_bytes/arguments.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::io::Result;
use std::io::Write;
use crate::BytesFormatter;
use crate::DisplayBytes;
use crate::FmtSpec;
pub fn write_bytes_fmt(w: &mut dyn Write, args: Arguments<'_>) -> Result<()> {
let (a, b) = args.literals.split_at(args.args.len());
for (literal, arg) in a.iter().zip(args.args.iter()) {
if !literal.is_empty() {
w.write_all(literal)?;
}
arg.value.fmt(&mut BytesFormatter(w, &arg.spec))?;
}
if !b.is_empty() {
w.write_all(b.first().unwrap())?;
}
Ok(())
}
pub struct Arguments<'a> {
literals: &'a [&'a [u8]],
args: &'a [Argument<'a>],
}
impl<'a> Arguments<'a> {
pub fn new(literals: &'a [&'a [u8]], args: &'a [Argument<'a>]) -> Self {
Arguments { literals, args }
}
}
pub struct Argument<'a> {
value: &'a dyn DisplayBytes,
spec: FmtSpec,
}
impl<'a> Argument<'a> {
pub fn new(value: &'a dyn DisplayBytes, spec: FmtSpec) -> Self {
Argument { value, spec }
}
} |
Rust | hhvm/hphp/hack/src/utils/write_bytes/bytes_formatter.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::io::Result;
use std::io::Write;
// Once we support fmtspec this is where the parameters (like width) will live.
pub struct FmtSpec {}
pub struct BytesFormatter<'a>(pub(crate) &'a mut dyn Write, pub(crate) &'a FmtSpec);
impl Write for BytesFormatter<'_> {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> Result<()> {
self.0.flush()
}
fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> Result<usize> {
self.0.write_vectored(bufs)
}
fn write_all(&mut self, buf: &[u8]) -> Result<()> {
self.0.write_all(buf)
}
fn write_fmt(&mut self, fmt: std::fmt::Arguments<'_>) -> Result<()> {
self.0.write_fmt(fmt)
}
} |
Rust | hhvm/hphp/hack/src/utils/write_bytes/display_bytes.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::io::Result;
use std::io::Write;
use bstr::BStr;
use bstr::BString;
use crate::BytesFormatter;
pub trait DisplayBytes {
fn fmt(&self, fmt: &mut BytesFormatter<'_>) -> Result<()>;
}
impl<T: DisplayBytes + ?Sized> DisplayBytes for &T {
fn fmt(&self, fmt: &mut BytesFormatter<'_>) -> Result<()> {
<T as DisplayBytes>::fmt(self, fmt)
}
}
#[macro_export]
macro_rules! display_bytes_using_display {
($name:ty) => {
impl $crate::DisplayBytes for $name {
fn fmt(&self, fmt: &mut $crate::BytesFormatter<'_>) -> std::io::Result<()> {
use std::io::Write;
write!(fmt, "{}", self)
}
}
};
}
display_bytes_using_display!(str);
display_bytes_using_display!(String);
display_bytes_using_display!(i32);
display_bytes_using_display!(i64);
display_bytes_using_display!(isize);
display_bytes_using_display!(u32);
display_bytes_using_display!(u64);
display_bytes_using_display!(usize);
macro_rules! display_bytes_using_as_ref {
($name:ty) => {
impl DisplayBytes for $name {
fn fmt(&self, fmt: &mut BytesFormatter<'_>) -> Result<()> {
fmt.write_all(self.as_ref())
}
}
};
}
display_bytes_using_as_ref!(&[u8]);
display_bytes_using_as_ref!(BStr);
display_bytes_using_as_ref!(BString);
display_bytes_using_as_ref!(&[u8; 0]);
display_bytes_using_as_ref!(&[u8; 1]);
display_bytes_using_as_ref!(&[u8; 2]);
display_bytes_using_as_ref!(&[u8; 3]);
display_bytes_using_as_ref!(&[u8; 4]);
display_bytes_using_as_ref!(&[u8; 5]);
display_bytes_using_as_ref!(&[u8; 6]);
display_bytes_using_as_ref!(&[u8; 7]);
display_bytes_using_as_ref!(&[u8; 8]);
display_bytes_using_as_ref!(&[u8; 9]);
display_bytes_using_as_ref!(&[u8; 10]);
display_bytes_using_as_ref!(&[u8; 11]);
display_bytes_using_as_ref!(&[u8; 12]);
display_bytes_using_as_ref!(&[u8; 13]);
display_bytes_using_as_ref!(&[u8; 14]);
display_bytes_using_as_ref!(&[u8; 15]);
display_bytes_using_as_ref!(&[u8; 16]);
impl<T> DisplayBytes for std::borrow::Cow<'_, T>
where
T: DisplayBytes + ToOwned + ?Sized,
<T as ToOwned>::Owned: DisplayBytes,
{
fn fmt(&self, fmt: &mut BytesFormatter<'_>) -> Result<()> {
self.as_ref().fmt(fmt)
}
}
impl<T: DisplayBytes + ?Sized> DisplayBytes for std::boxed::Box<T> {
fn fmt(&self, fmt: &mut BytesFormatter<'_>) -> Result<()> {
DisplayBytes::fmt(&**self, fmt)
}
} |
Rust | hhvm/hphp/hack/src/utils/write_bytes/lib.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
pub mod arguments;
pub mod bytes_formatter;
pub mod display_bytes;
#[cfg(test)]
mod test;
#[cfg(test)]
extern crate self as write_bytes;
pub use arguments::write_bytes_fmt;
pub use arguments::Argument;
pub use arguments::Arguments;
pub use bytes_formatter::BytesFormatter;
pub use bytes_formatter::FmtSpec;
pub use display_bytes::DisplayBytes;
pub use write_bytes_macro::write_bytes;
#[macro_export]
macro_rules! format_bytes {
($($toks:tt)*) => (
{
let mut tmp = Vec::new();
write_bytes!(&mut tmp, $($toks)*).unwrap();
tmp
}
)
}
#[macro_export]
macro_rules! writeln_bytes {
($stream:expr) => {
($stream).write_all(b"\n")
};
($stream:expr, $($toks:tt)*) => {{
write_bytes!($stream, $($toks)*).and_then(|()| ($stream).write_all(b"\n"))
}};
} |
Rust | hhvm/hphp/hack/src/utils/write_bytes/test.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::borrow::Cow;
use crate::format_bytes;
use crate::write_bytes;
type Result = std::io::Result<()>;
#[test]
fn test_basic() -> Result {
let mut v: Vec<u8> = Vec::new();
write_bytes!(&mut v, b"abc")?;
assert_eq!(v, b"abc");
assert_eq!(format_bytes!(b"abc"), b"abc");
Ok(())
}
#[test]
fn test_pos() -> Result {
let mut v = Vec::new();
write_bytes!(&mut v, b"abc{}def", 5)?;
assert_eq!(v, b"abc5def");
assert_eq!(format_bytes!(b"abc{}def", 5), b"abc5def");
Ok(())
}
#[test]
fn test_named() -> Result {
let mut v = Vec::new();
write_bytes!(&mut v, b"abc{foo}def", foo = 5)?;
assert_eq!(v, b"abc5def");
assert_eq!(format_bytes!(b"abc{foo}def", foo = 5), b"abc5def");
Ok(())
}
#[test]
fn test_types() -> Result {
assert_eq!(format_bytes!(b"{}", 5), b"5");
assert_eq!(format_bytes!(b"{}", "abc"), b"abc");
assert_eq!(format_bytes!(b"{}", Cow::from("abc")), b"abc");
Ok(())
} |
Rust | hhvm/hphp/hack/src/utils/write_bytes/write_bytes-macro.rs | // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
use std::borrow::Cow;
use std::collections::HashMap;
use std::collections::HashSet;
use proc_macro2::Literal;
use proc_macro2::Span;
use proc_macro2::TokenStream;
use quote::quote;
use syn::parse::Parser;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::Error;
use syn::Expr;
use syn::LitByteStr;
use syn::Token;
type Result<T> = std::result::Result<T, Error>;
/// Macro like write!() but for use with byte strings.
#[cfg(not(test))]
#[proc_macro]
pub fn write_bytes(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = TokenStream::from(input);
match write_bytes_macro(input) {
Ok(res) => res.into(),
Err(err) => err.into_compile_error().into(),
}
}
const DEBUG: bool = false;
fn write_bytes_macro(input: TokenStream) -> Result<TokenStream> {
if DEBUG {
eprintln!("INPUT: {}", input);
}
let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
let root = parser.parse2(input)?;
let mut it = root.iter();
let stream = it
.next()
.ok_or_else(|| Error::new(Span::call_site(), "missing stream argument"))?;
let format_string = read_format_string(&mut it)?;
let (named, positional) = read_args(it)?;
let mut named_used: HashSet<String> = HashSet::new();
let mut positional_used: HashSet<usize> = HashSet::new();
let this_crate = quote!(::write_bytes);
let mut args_vars = TokenStream::new();
let mut named_idx: HashMap<String, usize> = HashMap::new();
for expr in &positional {
args_vars.extend(quote!(&#expr,));
}
for (i, (name, expr)) in named.iter().enumerate() {
args_vars.extend(quote!(&#expr,));
let _i: usize = i + positional.len();
named_idx.insert(name.to_owned(), i + positional.len());
}
let mut literals = TokenStream::new();
let mut args_values = TokenStream::new();
let mut cur = Vec::new();
let mut next_pos = 0;
let mut it = format_string.value().into_iter().peekable();
let span = format_string.span();
while let Some(c) = it.next() {
if c == b'{' {
if it.peek().copied() == Some(b'{') {
it.next();
cur.push(b'{');
continue;
}
// We need to always do this - even if it's blank.
let cur_bs = LitByteStr::new(&cur, span);
literals.extend(quote!(#cur_bs,));
cur.clear();
let spec = read_fmt_spec(&mut it, span)?;
let arg_idx = match spec.name {
FmtSpecName::Unspecified => {
let pos = next_pos;
next_pos += 1;
if pos >= positional.len() {
return Err(Error::new(
span,
format!(
"{} positional arguments in format string, but there is {} argument",
pos + 1,
positional.len()
),
));
}
positional_used.insert(pos);
pos
}
FmtSpecName::Positional(pos) => {
if pos >= positional.len() {
return Err(Error::new(
span,
format!("Invalid reference to positional argument {}", pos),
));
}
positional_used.insert(pos);
pos
}
FmtSpecName::Named(name) => {
if let Some(&pos) = named_idx.get(&name) {
named_used.insert(name);
pos
} else {
return Err(Error::new(
span,
format!("there is no argument named '{}'", name),
));
}
}
};
let fmt_spec = quote!(#this_crate::FmtSpec {});
let arg_idx = Literal::usize_unsuffixed(arg_idx);
args_values.extend(quote!(#this_crate::Argument::new(_args.#arg_idx, #fmt_spec), ));
} else if c == b'}' {
if let Some(nc) = it.next() {
if nc == b'}' {
cur.push(b'}');
continue;
}
}
return Err(Error::new(span, "unmatched '}' in format string"));
} else {
cur.push(c);
}
}
if !cur.is_empty() {
let cur_bs = LitByteStr::new(&cur, format_string.span());
literals.extend(quote!(#cur_bs,));
}
if named_used.len() != named.len() {
let unused = named
.iter()
.find(|(k, _v)| !named_used.contains(k))
.unwrap();
return Err(Error::new(unused.1.span(), "named argument never used"));
}
if positional_used.len() != positional.len() {
let unused: usize = (0..positional.len())
.find(|k| !positional_used.contains(k))
.unwrap();
return Err(Error::new(positional[unused].span(), "argument never used"));
}
let result = quote!(
#this_crate::write_bytes_fmt(
#stream,
#this_crate::Arguments::new(
&[#literals],
&match (#args_vars) {
_args => [#args_values],
}
)
)
);
if DEBUG {
eprintln!("RESULT: {:?}\n{}", result, result);
}
Ok(result)
}
fn read_format_string<'a>(it: &mut impl Iterator<Item = &'a Expr>) -> Result<Cow<'a, LitByteStr>> {
let fs = it
.next()
.ok_or_else(|| Error::new(Span::call_site(), "missing format argument string"))?;
let bs = match fs {
Expr::Lit(syn::ExprLit {
attrs: _,
lit: syn::Lit::ByteStr(bs),
}) => Cow::Borrowed(bs),
Expr::Lit(syn::ExprLit {
attrs: _,
lit: syn::Lit::Str(s),
}) => Cow::Owned(LitByteStr::new(s.value().as_bytes(), s.span())),
_ => {
return Err(Error::new(
fs.span(),
"format argument must be a string literal",
));
}
};
Ok(bs)
}
fn read_args<'a>(
it: impl Iterator<Item = &'a Expr>,
) -> Result<(Vec<(String, &'a Expr)>, Vec<&'a Expr>)> {
// positional, positional, positional, ..., name = named, name = named, ...
let mut named = Vec::new();
let mut positional = Vec::new();
for expr in it {
match expr {
Expr::Assign(assign) => {
let name = match &*assign.left {
Expr::Path(path) => path.path.get_ident().map(|id| format!("{}", id)),
_ => None,
};
let name = name.ok_or_else(|| {
Error::new(expr.span(), "identifier expected for named parameter name")
})?;
named.push((name, &*assign.right));
}
_ => {
if !named.is_empty() {
return Err(Error::new(
expr.span(),
"positional arguments must be before named arguments",
));
}
positional.push(expr);
}
}
}
Ok((named, positional))
}
#[derive(Debug)]
enum FmtSpecName {
Unspecified,
Positional(usize),
Named(String),
}
#[derive(Debug)]
struct FmtSpec {
name: FmtSpecName,
}
fn read_fmt_spec<I: Iterator<Item = u8>>(
it: &mut std::iter::Peekable<I>,
span: Span,
) -> Result<FmtSpec> {
// {[integer|identifier][:[[fill]align][sign]['#']['0'][width]['.' precision]type]}
let mut spec = FmtSpec {
name: FmtSpecName::Unspecified,
};
fn is_ident(c: u8) -> bool {
c.is_ascii_alphanumeric() || c == b'_'
}
if it.peek().copied().map_or(false, is_ident) {
// integer | identifier
let mut pos = String::new();
while it.peek().copied().map_or(false, is_ident) {
pos.push(it.next().unwrap() as char);
}
if pos.chars().next().unwrap().is_ascii_digit() {
spec.name = FmtSpecName::Positional(
pos.parse::<usize>()
.map_err(|e| Error::new(span, e.to_string()))?,
);
} else {
// identifier
spec.name = FmtSpecName::Named(pos);
}
}
if it.peek().copied() == Some(b':') {
// format spec
todo!();
}
if let Some(c) = it.next() {
if c != b'}' {
return Err(Error::new(
span,
format!("Unexpected character '{}' in format string", c),
));
}
} else {
return Err(Error::new(span, "Expected '}' in format string"));
}
Ok(spec)
}
#[cfg(test)]
mod test_helpers {
use proc_macro2::TokenStream;
use proc_macro2::TokenTree;
use syn::Error;
pub(crate) fn mismatch(
ta: Option<TokenTree>,
tb: Option<TokenTree>,
ax: &TokenStream,
bx: &TokenStream,
) -> ! {
panic!(
"Mismatch!\nLeft: {}\nRight: {}\nwhen comparing\nLeft: {}\nRight: {}\n",
ta.map_or("None".into(), |t| t.to_string()),
tb.map_or("None".into(), |t| t.to_string()),
ax,
bx
);
}
pub(crate) fn assert_pat_eq(a: Result<TokenStream, Error>, b: TokenStream) {
let a = match a {
Err(err) => {
panic!("Unexpected error '{}'", err);
}
Ok(ok) => ok,
};
fn inner_cmp(a: TokenStream, b: TokenStream, ax: &TokenStream, bx: &TokenStream) {
let mut ia = a.into_iter();
let mut ib = b.into_iter();
loop {
let t_a = ia.next();
let t_b = ib.next();
if t_a.is_none() && t_b.is_none() {
break;
}
if t_a.is_none() || t_b.is_none() {
mismatch(t_a, t_b, ax, bx);
}
let t_a = t_a.unwrap();
let t_b = t_b.unwrap();
match (&t_a, &t_b) {
(TokenTree::Ident(_), TokenTree::Ident(_))
| (TokenTree::Literal(_), TokenTree::Literal(_))
| (TokenTree::Punct(_), TokenTree::Punct(_))
if t_a.to_string() == t_b.to_string() => {}
(TokenTree::Group(ga), TokenTree::Group(gb)) => {
inner_cmp(ga.stream(), gb.stream(), ax, bx);
}
(TokenTree::Group(_), _)
| (TokenTree::Ident(_), _)
| (TokenTree::Punct(_), _)
| (TokenTree::Literal(_), _) => mismatch(Some(t_a), Some(t_b), ax, bx),
}
}
}
inner_cmp(a.clone(), b.clone(), &a, &b);
}
pub(crate) fn assert_error(a: Result<TokenStream, Error>, b: &str) {
match a {
Ok(a) => panic!("Expected error but got:\n{}", a),
Err(e) => {
let a = format!("{}", e);
assert_eq!(a, b, "Incorrect error")
}
}
}
}
#[cfg(test)]
// #[rustfmt::skip] // skip rustfmt because it tends to add unwanted tokens to our quotes.
#[allow(dead_code)]
mod test {
use quote::quote;
use super::*;
use crate::test_helpers::assert_error;
use crate::test_helpers::assert_pat_eq;
#[test]
fn test_basic() {
assert_pat_eq(
write_bytes_macro(quote!(w, b"text")),
quote!(::write_bytes::write_bytes_fmt(
w,
::write_bytes::Arguments::new(
&[b"text",],
&match () {
_args => [],
}
)
)),
);
assert_pat_eq(
write_bytes_macro(quote!(w, b"text",)),
quote!(::write_bytes::write_bytes_fmt(
w,
::write_bytes::Arguments::new(
&[b"text",],
&match () {
_args => [],
}
)
)),
);
assert_pat_eq(
write_bytes_macro(quote!(w, "text")),
quote!(::write_bytes::write_bytes_fmt(
w,
::write_bytes::Arguments::new(
&[b"text",],
&match () {
_args => [],
}
)
)),
);
assert_error(write_bytes_macro(quote!()), "missing stream argument");
assert_error(
write_bytes_macro(quote!(w)),
"missing format argument string",
);
assert_error(
write_bytes_macro(quote!(w,)),
"missing format argument string",
);
assert_error(
write_bytes_macro(quote!(w, x)),
"format argument must be a string literal",
);
}
#[test]
fn test_escape() {
assert_pat_eq(
write_bytes_macro(quote!(w, b"te\nxt")),
quote!(::write_bytes::write_bytes_fmt(
w,
::write_bytes::Arguments::new(
&[b"te\nxt",],
&match () {
_args => [],
}
)
)),
);
assert_pat_eq(
write_bytes_macro(quote!(w, b"te\\xt")),
quote!(::write_bytes::write_bytes_fmt(
w,
::write_bytes::Arguments::new(
&[b"te\\xt",],
&match () {
_args => [],
}
)
)),
);
assert_pat_eq(
write_bytes_macro(quote!(w, b"te{{xt")),
quote!(::write_bytes::write_bytes_fmt(
w,
::write_bytes::Arguments::new(
&[b"te{xt",],
&match () {
_args => [],
}
)
)),
);
assert_pat_eq(
write_bytes_macro(quote!(w, b"te}}xt")),
quote!(::write_bytes::write_bytes_fmt(
w,
::write_bytes::Arguments::new(
&[b"te}xt",],
&match () {
_args => [],
}
)
)),
);
assert_error(
write_bytes_macro(quote!(w, b"abc{", arg)),
"Expected '}' in format string",
);
assert_error(
write_bytes_macro(quote!(w, b"abc}def", arg)),
"unmatched '}' in format string",
);
}
#[test]
fn test_pos() {
assert_pat_eq(
write_bytes_macro(quote!(w, b"abc{}def", arg)),
quote!(::write_bytes::write_bytes_fmt(
w,
::write_bytes::Arguments::new(
&[b"abc", b"def",],
&match (&arg,) {
_args => [::write_bytes::Argument::new(
_args.0,
::write_bytes::FmtSpec {}
),],
}
)
)),
);
assert_pat_eq(
write_bytes_macro(quote!(w, b"abc{}", arg)),
quote!(::write_bytes::write_bytes_fmt(
w,
::write_bytes::Arguments::new(
&[b"abc",],
&match (&arg,) {
_args => [::write_bytes::Argument::new(
_args.0,
::write_bytes::FmtSpec {}
),],
}
)
)),
);
assert_pat_eq(
write_bytes_macro(quote!(w, b"abc{}", 5)),
quote!(::write_bytes::write_bytes_fmt(
w,
::write_bytes::Arguments::new(
&[b"abc",],
&match (&5,) {
_args => [::write_bytes::Argument::new(
_args.0,
::write_bytes::FmtSpec {}
),],
}
)
)),
);
assert_pat_eq(
write_bytes_macro(quote!(w, b"abc{1}def{0}ghi", arg0, arg1)),
quote!(::write_bytes::write_bytes_fmt(
w,
::write_bytes::Arguments::new(
&[b"abc", b"def", b"ghi",],
&match (&arg0, &arg1,) {
_args => [
::write_bytes::Argument::new(_args.1, ::write_bytes::FmtSpec {}),
::write_bytes::Argument::new(_args.0, ::write_bytes::FmtSpec {}),
],
}
)
)),
);
assert_pat_eq(
write_bytes_macro(quote!(w, b"abc{0}{1}ghi", arg0, arg1)),
quote!(::write_bytes::write_bytes_fmt(
w,
::write_bytes::Arguments::new(
&[b"abc", b"", b"ghi",],
&match (&arg0, &arg1,) {
_args => [
::write_bytes::Argument::new(_args.0, ::write_bytes::FmtSpec {}),
::write_bytes::Argument::new(_args.1, ::write_bytes::FmtSpec {}),
],
}
)
)),
);
assert_pat_eq(
write_bytes_macro(quote!(w, b"{}abc", arg)),
quote!(::write_bytes::write_bytes_fmt(
w,
::write_bytes::Arguments::new(
&[b"", b"abc",],
&match (&arg,) {
_args => [::write_bytes::Argument::new(
_args.0,
::write_bytes::FmtSpec {}
),],
}
)
)),
);
assert_error(
write_bytes_macro(quote!(w, b"abc{1}def", arg0)),
"Invalid reference to positional argument 1",
);
assert_error(
write_bytes_macro(quote!(w, b"abc{}def", foo = bar, arg0)),
"positional arguments must be before named arguments",
);
assert_error(
write_bytes_macro(quote!(w, b"abc{}def{}ghi", arg0)),
"2 positional arguments in format string, but there is 1 argument",
);
assert_error(
write_bytes_macro(quote!(w, b"abc{}def{}ghi", arg0, arg1, arg2)),
"argument never used",
);
}
#[test]
fn test_named() {
assert_pat_eq(
write_bytes_macro(quote!(w, b"abc{foo}def", foo = arg)),
quote!(::write_bytes::write_bytes_fmt(
w,
::write_bytes::Arguments::new(
&[b"abc", b"def",],
&match (&arg,) {
_args => [::write_bytes::Argument::new(
_args.0,
::write_bytes::FmtSpec {}
),],
}
)
)),
);
assert_error(
write_bytes_macro(quote!(w, b"abc{bar}def", foo = arg)),
"there is no argument named 'bar'",
);
assert_error(
write_bytes_macro(quote!(w, b"abcdef", foo = arg)),
"named argument never used",
);
}
} |
TOML | hhvm/hphp/hack/src/utils/write_bytes/write_bytes/Cargo.toml | # @generated by autocargo
[package]
name = "write_bytes"
version = "0.0.0"
edition = "2021"
[lib]
path = "../lib.rs"
[dependencies]
bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] }
write_bytes-macro = { version = "0.0.0", path = "../write_bytes-macro" } |
TOML | hhvm/hphp/hack/src/utils/write_bytes/write_bytes-macro/Cargo.toml | # @generated by autocargo
[package]
name = "write_bytes-macro"
version = "0.0.0"
edition = "2021"
[lib]
path = "../write_bytes-macro.rs"
test = false
doctest = false
proc-macro = true
[dependencies]
proc-macro2 = { version = "1.0.64", features = ["span-locations"] }
quote = "1.0.29"
syn = { version = "1.0.109", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] } |
OCaml | hhvm/hphp/hack/src/version/hh_version.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* Monotonically increasing identifier that can be used when we introduce
* backward incompatible changes in hh_client commands, and to signal
* new capabilities to clients.
* v1 (hvvm 3.15, 11 May 2016) - persistent connection introduced
* v4 (hvvm 3.18, 7 Nov 2016) - persistent connection stable
* v5 (hvvm 3.23, 17 Nov 2017) - 'hh_client lsp' stable
*)
let api_version = 5
let version : string =
match Build_banner.banner with
| Some banner -> banner
| None -> Build_id.build_revision ^ " " ^ Build_id.build_commit_time_string
let version_json =
Hh_json.(
JSON_Object
[
("commit", JSON_String Build_id.build_revision);
("commit_time", int_ Build_id.build_commit_time);
("build_mode", JSON_String Build_id.build_mode);
("api_version", int_ api_version);
]) |
OCaml | hhvm/hphp/hack/src/version/build_banner/build_banner.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
external get_build_banner : unit -> string option = "hh_get_build_banner"
let banner = get_build_banner () |
OCaml Interface | hhvm/hphp/hack/src/version/build_banner/build_banner.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val banner : string option |
C | hhvm/hphp/hack/src/version/build_banner/build_banner_stubs.c | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*/
#define CAML_NAME_SPACE
#include <caml/alloc.h>
#include <caml/memory.h>
#include <caml/mlvalues.h>
#include <string.h>
#ifdef HH_BUILD_BANNER
#include "hphp/runtime/version.h"
#endif
#define STRINGIFY_HELPER(x) #x
#define STRINGIFY_VALUE(x) STRINGIFY_HELPER(x)
CAMLprim value hh_get_build_banner(void) {
CAMLparam0();
CAMLlocal2(result, option);
#ifdef HH_BUILD_BANNER
const char* const buf =
STRINGIFY_VALUE(HH_BUILD_BANNER) "-" HHVM_VERSION_C_STRING_LITERALS;
const size_t len = strlen(buf);
result = caml_alloc_initialized_string(len, buf);
option = caml_alloc(1, 0); // Some result
Store_field(option, 0, result);
#else
option = Val_int(0); // None
#endif
CAMLreturn(option);
} |
hhvm/hphp/hack/src/version/build_banner/dune | (library
(name build_banner)
(wrapped false)
(foreign_stubs
(language c)
(names build_banner_stubs)
(flags
(:standard
-I%{env:CMAKE_SOURCE_DIR=xxx}
(:include build-id-opt)))))
(rule
(targets build-id build-id.c)
(deps (universe))
(action
(progn
(write-file
generate-build-id.sh
"INSTALL_DIR=$PWD FBCODE_DIR=%{env:CMAKE_SOURCE_DIR=xxx} %{env:CMAKE_SOURCE_DIR=yyy}/hphp/tools/generate-build-id.sh IGNORED IGNORED hackc hphp/hack/src")
(system "chmod +x generate-build-id.sh && ./generate-build-id.sh"))))
(rule
(targets build-id-opt)
(action
(write-file build-id-opt -DHH_BUILD_BANNER=%{read:build-id}))) |
|
OCaml | hhvm/hphp/hack/src/version/compiler_id/compiler_id.ml | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
external get_compiler_id : unit -> string = "hh_get_compiler_id" |
OCaml Interface | hhvm/hphp/hack/src/version/compiler_id/compiler_id.mli | (*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
external get_compiler_id : unit -> string = "hh_get_compiler_id" |
C | hhvm/hphp/hack/src/version/compiler_id/compiler_id_impl.c | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*/
#define CAML_NAME_SPACE
#include <caml/memory.h>
#include <caml/alloc.h>
#include <string.h>
extern const char* const build_id;
value hh_get_compiler_id(void) {
CAMLparam0();
const char* const buf = build_id;
const ssize_t len = strlen(buf);
value result;
result = caml_alloc_initialized_string(len, buf);
CAMLreturn(result);
} |
hhvm/hphp/hack/src/version/compiler_id/dune | (copy_files ../build_banner/build-id.c)
(library
(name compiler_id)
(wrapped false)
(modules compiler_id)
(foreign_stubs
(language c)
(names compiler_id_impl build-id)
(flags
(:standard -I%{env:CMAKE_SOURCE_DIR=xxx})))) |
|
hhvm/hphp/hack/src/watchman/dune | (library
(name watchman)
(wrapped false)
(modules watchman watchman_sig)
(libraries
buffered_line_reader
core_kernel
hh_json
logging_common
sys_utils
utils_core)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name watchman_utils)
(wrapped false)
(modules watchman_utils)
(libraries hh_json logging utils_core)
(preprocess
(pps lwt_ppx ppx_deriving.std))) |
|
OCaml | hhvm/hphp/hack/src/watchman/watchman.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
* *)
open Hh_prelude
open Utils
(*
* Module for us to interface with Watchman, a file watching service.
* https://facebook.github.io/watchman/
*
* TODO:
* * Connect directly to the Watchman server socket instead of spawning
* a client process each time
* * Use the BSER protocol for enhanced performance
*)
(** Stuff shared between Actual and Mocked implementations. *)
module Testing_common = struct
open Watchman_sig.Types
let test_settings =
{
subscribe_mode = Some Defer_changes;
init_timeout = Watchman_sig.Types.No_timeout;
expression_terms = [];
debug_logging = false;
roots = [Path.dummy_path];
sockname = None;
subscription_prefix = "dummy_prefix";
}
end
module Watchman_process_helpers = struct
include Watchman_sig.Types
module J = Hh_json_helpers.AdhocJsonHelpers
let timeout_to_secs = function
| No_timeout -> None
| Default_timeout -> Some 1200.
| Explicit_timeout timeout -> Some timeout
let debug = false
(* Throw this exception when we know there is something to read from
* the watchman channel, but reading took too long. *)
exception Read_payload_too_long
(* Looks for common errors in watchman responses *)
let assert_no_error obj =
(try
let warning = J.get_string_val "warning" obj in
EventLogger.watchman_warning warning;
Hh_logger.log "Watchman warning: %s\n" warning
with
| J.Not_found -> ());
(try
let error = J.get_string_val "error" obj in
EventLogger.watchman_error error;
raise @@ Watchman_error error
with
| J.Not_found -> ());
try
let canceled = J.get_bool_val "canceled" obj in
if canceled then (
EventLogger.watchman_error "Subscription canceled by watchman";
raise @@ Subscription_canceled_by_watchman
) else
()
with
| J.Not_found -> ()
let max_array_elt_in_json_logging = 5
(* Verifies that a watchman response is valid JSON and free from common errors *)
let sanitize_watchman_response ~debug_logging output =
if debug_logging then Hh_logger.info "Watchman response: %s" output;
let response =
try
let response = Hh_json.json_of_string output in
(if not debug_logging then
let has_changed = ref false in
(* if debug_logging, we've already logged the full watchman response, so skip
* logging truncated one. *)
let json =
Hh_json.json_truncate
~max_array_elt_count:max_array_elt_in_json_logging
~has_changed
response
in
Hh_logger.info
"Watchman response: %s%s"
(if !has_changed then
Printf.sprintf "(truncated) "
else
"")
(Hh_json.json_to_string json));
response
with
| exn ->
let e = Exception.wrap exn in
Hh_logger.error
"Failed to parse string as JSON: %s\n%s"
output
(Exception.to_string e);
Exception.reraise e
in
assert_no_error response;
response
end
module Regular_watchman_process : sig
include Watchman_sig.WATCHMAN_PROCESS with type 'a result = 'a
val get_reader : conn -> Buffered_line_reader.t
end = struct
include Watchman_process_helpers
type 'a result = 'a
type conn = Buffered_line_reader.t * Out_channel.t
let ( >>= ) a f = f a
let ( >|= ) a f = f a
let return x = x
let catch ~f ~catch =
try f () with
| exn -> catch (Exception.wrap exn)
let list_fold_values = List.fold
(* Send a request to the watchman process *)
let send_request ~debug_logging oc json =
let json_str = Hh_json.(json_to_string json) in
if debug_logging then
Hh_logger.info "Watchman request: %s" json_str
else
let has_changed = ref false in
let json =
Hh_json.json_truncate
json
~max_array_elt_count:max_array_elt_in_json_logging
~has_changed
in
Hh_logger.info
"Watchman request: %s%s"
(if !has_changed then
"(truncated) "
else
"")
(json |> Hh_json.json_to_string);
Out_channel.output_string oc json_str;
Out_channel.output_string oc "\n";
Out_channel.flush oc
(***************************************************************************)
(* Handling requests and responses. *)
(***************************************************************************)
let has_input timeout reader =
if Buffered_line_reader.has_buffered_content reader then
true
else
(* Negative means "no timeout" to select *)
let timeout = Option.value (timeout_to_secs timeout) ~default:~-.1. in
match
Sys_utils.select_non_intr
[Buffered_line_reader.get_fd reader]
[]
[]
timeout
with
| ([], _, _) -> false
| _ -> true
let read_with_timeout timeout reader =
let start_t = Unix.time () in
if not (has_input timeout reader) then
raise Timeout
else
match timeout_to_secs timeout with
| None -> Buffered_line_reader.get_next_line reader
| Some timeout ->
let remaining = start_t +. timeout -. Unix.time () in
let timeout = int_of_float remaining in
let timeout = max timeout 10 in
Timeout.with_timeout
~do_:(fun _ -> Buffered_line_reader.get_next_line reader)
~timeout
~on_timeout:(fun (_ : Timeout.timings) ->
let () = EventLogger.watchman_timeout () in
raise Read_payload_too_long)
(* Asks watchman for the path to the socket file *)
let get_sockname timeout =
let ic =
Timeout.open_process_in
Exec_command.Watchman
[|
Exec_command.to_string Exec_command.Watchman;
"get-sockname";
"--no-pretty";
|]
in
let reader =
Buffered_line_reader.create @@ Timeout.descr_of_in_channel ic
in
let output = read_with_timeout timeout reader in
assert (
match Timeout.close_process_in ic with
| Unix.WEXITED 0 -> true
| _ -> false);
let json = Hh_json.json_of_string output in
J.get_string_val "sockname" json
(* Opens a connection to the watchman process through the socket *)
let open_connection ~timeout ~(sockname : string option) =
let sockname =
match sockname with
| Some sockname -> sockname
| None -> get_sockname timeout
in
let (tic, oc) = Timeout.open_connection (Unix.ADDR_UNIX sockname) in
let reader =
Buffered_line_reader.create @@ Timeout.descr_of_in_channel @@ tic
in
(reader, oc)
let close_connection conn =
let (reader, _) = conn in
Unix.close @@ Buffered_line_reader.get_fd reader
(** Open a connection to the watchman socket, call the continuation, then
* close. *)
let with_watchman_conn ~timeout ~(sockname : string option) f =
let conn = open_connection ~timeout ~sockname in
let result =
try f conn with
| exn ->
let e = Exception.wrap exn in
Unix.close @@ Buffered_line_reader.get_fd @@ fst conn;
Exception.reraise e
in
Unix.close @@ Buffered_line_reader.get_fd @@ fst conn;
result
(* Sends a request to watchman and returns the response. If we don't have a connection,
* a new connection will be created before the request and destroyed after the response *)
let rec request
~debug_logging
?conn
?(timeout = Default_timeout)
~(sockname : string option)
json =
match conn with
| None ->
with_watchman_conn ~timeout ~sockname (fun conn ->
request ~debug_logging ~conn ~timeout ~sockname json)
| Some (reader, oc) ->
send_request ~debug_logging oc json;
sanitize_watchman_response
~debug_logging
(read_with_timeout timeout reader)
let send_request_and_do_not_wait_for_response
~debug_logging ~conn:(_, oc) json =
send_request ~debug_logging oc json
let blocking_read ~debug_logging ?(timeout = Explicit_timeout 0.) conn =
let ready = has_input timeout @@ fst conn in
if not ready then
match timeout with
| No_timeout -> None
| Explicit_timeout timeout when Float.equal timeout 0. -> None
| _ -> raise Timeout
else
(* Use the timeout mechanism to limit maximum time to read payload (cap
* data size) so we don't freeze if watchman sends an inordinate amount of
* data, or if it is malformed (i.e. doesn't end in a newline). *)
let timeout = 40 in
let output =
Timeout.with_timeout
~do_:(fun _ -> Buffered_line_reader.get_next_line @@ fst conn)
~timeout
~on_timeout:
begin
fun (_ : Timeout.timings) ->
let () =
Hh_logger.log
"Regular_watchman_process.blocking_read timed out"
in
raise Read_payload_too_long
end
in
Some (sanitize_watchman_response ~debug_logging output)
let get_reader (reader, _) = reader
module Testing = struct
let get_test_conn () =
(Buffered_line_reader.get_null_reader (), Out_channel.create "/dev/null")
end
end
module Functor (Watchman_process : Watchman_sig.WATCHMAN_PROCESS) :
Watchman_sig.S
with type 'a result = 'a Watchman_process.result
and type conn = Watchman_process.conn = struct
let ( >>= ) = Watchman_process.( >>= )
let ( >|= ) = Watchman_process.( >|= )
type 'a result = 'a Watchman_process.result
type conn = Watchman_process.conn
(**
* Ocaml module signatures are static. This means since mocking
* functionality is exposed in the mli, it must be implemented for
* both actual builds as well as testing/mocked builds.
*
* For actual builds, we just raise exceptions for the
* setters.
*)
module Mocking = struct
exception Cannot_set_when_mocks_disabled
let print_env _ = raise Cannot_set_when_mocks_disabled
let get_changes_returns _ = raise Cannot_set_when_mocks_disabled
let init_returns _ = raise Cannot_set_when_mocks_disabled
end
(** This number is totally arbitrary. Just need some cap. *)
let max_reinit_attempts = 8
(**
* Triggers watchman to flush buffered updates on this subscription.
* See watchman/docs/cmd/flush-subscriptions.html
*)
let flush_subscriptions_cmd = "cmd-flush-subscriptions"
include Watchman_sig.Types
type dead_env = {
(* Will reuse original settings to reinitializing watchman subscription. *)
prior_settings: init_settings;
reinit_attempts: int;
dead_since: float;
prior_clockspec: string;
}
type env = {
(* See https://facebook.github.io/watchman/docs/clockspec.html
*
* This is also used to reliably detect a crashed watchman. Watchman has a
* facility to detect watchman process crashes between two "since" queries
*
* See also assert_no_fresh_instance *)
mutable clockspec: string;
conn: Watchman_process.conn;
settings: init_settings;
subscription: string;
watch_root: string;
watched_path_expression_terms: Hh_json.json option;
}
let dead_env_from_alive env =
{
prior_settings = env.settings;
dead_since = Unix.time ();
reinit_attempts = 0;
(* When we start a new watchman connection, we continue to use the prior
* clockspec. If the same watchman server is still alive, then all is
* good. If not, the clockspec allows us to detect whether a new watchman
* server had to be started. See also "is_fresh_instance" on watchman's
* "since" response. *)
prior_clockspec = env.clockspec;
}
type watchman_instance =
(* Indicates a dead watchman instance (most likely due to chef upgrading,
* reconfiguration, or a user terminating watchman, or a timeout reading
* from the connection) detected by, for example, a pipe error or a timeout.
*
* TODO: Currently fallback to a Watchman_dead is only handled in calls
* wrapped by the with_crash_record. Pipe errors elsewhere (for example
* during request) will still result in Hack exiting. Need to cover those
* cases too. *)
| Watchman_dead of dead_env
| Watchman_alive of env
module J = Hh_json_helpers.AdhocJsonHelpers
(****************************************************************************)
(* JSON methods. *)
(****************************************************************************)
let clock root = J.strlist ["clock"; root]
type watch_command =
| Subscribe
| Query
(** Conjunction of extra_expressions and expression_terms. *)
let request_json
?(extra_kv = []) ?(extra_expressions = []) watchman_command env =
Hh_json.(
let command =
match watchman_command with
| Subscribe -> "subscribe"
| Query -> "query"
in
let header =
[JSON_String command; JSON_String env.watch_root]
@
match watchman_command with
| Subscribe -> [JSON_String env.subscription]
| _ -> []
in
let expressions = extra_expressions @ env.settings.expression_terms in
let expressions =
match env.watched_path_expression_terms with
| Some terms -> terms :: expressions
| None -> expressions
in
assert (not (List.is_empty expressions));
let directives =
[
JSON_Object
(extra_kv
@ [
("fields", J.strlist ["name"]);
(* Watchman doesn't allow an empty allof expression. But expressions is never empty *)
("expression", J.pred "allof" expressions);
]);
]
in
let request = JSON_Array (header @ directives) in
request)
let all_query env =
request_json ~extra_expressions:[Hh_json.JSON_String "exists"] Query env
let get_changes_since_mergebase_query env =
let extra_kv =
[
( "since",
Hh_json.JSON_Object
[
( "scm",
Hh_json.JSON_Object
[("mergebase-with", Hh_json.JSON_String "master")] );
] );
]
in
request_json ~extra_kv Query env
let since_query env =
request_json
~extra_kv:
[
("since", Hh_json.JSON_String env.clockspec);
("empty_on_fresh_instance", Hh_json.JSON_Bool true);
]
Query
env
let subscribe ~mode env =
let (since, mode) =
match mode with
| All_changes -> (Hh_json.JSON_String env.clockspec, [])
| Defer_changes ->
( Hh_json.JSON_String env.clockspec,
[("defer", J.strlist ["hg.update"; "meerkat-build"])] )
| Scm_aware ->
Hh_logger.log "Making Scm_aware subscription";
let scm =
Hh_json.JSON_Object [("mergebase-with", Hh_json.JSON_String "master")]
in
let since =
Hh_json.JSON_Object
[("scm", scm); ("drop", J.strlist ["hg.update"; "meerkat-build"])]
in
(since, [])
in
request_json
~extra_kv:
(([("since", since)] @ mode)
@ [("empty_on_fresh_instance", Hh_json.JSON_Bool true)])
Subscribe
env
let watch_project root = J.strlist ["watch-project"; root]
(* See https://facebook.github.io/watchman/docs/cmd/version.html *)
let capability_check ?(optional = []) required =
Hh_json.(
JSON_Array
([JSON_String "version"]
@ [
JSON_Object
[
("optional", J.strlist optional);
("required", J.strlist required);
];
]))
(** We filter all responses from get_changes through this. This is to detect
* Watchman server crashes.
*
* See also Watchman docs on "since" query parameter. *)
let assert_no_fresh_instance obj =
Hh_json.Access.(
let _ =
return obj >>= get_bool "is_fresh_instance" >>= fun (is_fresh, trace) ->
if is_fresh then (
Hh_logger.log "Watchman server is fresh instance. Exiting.";
raise Exit_status.(Exit_with Watchman_fresh_instance)
) else
Ok ((), trace)
in
())
(****************************************************************************)
(* Initialization, reinitialization, and crash-tracking. *)
(****************************************************************************)
let with_crash_record_exn source f =
Watchman_process.catch ~f ~catch:(fun exn ->
Hh_logger.exception_ ~prefix:("Watchman " ^ source ^ ": ") exn;
Exception.reraise exn)
let with_crash_record_opt source f =
Watchman_process.catch
~f:(fun () -> with_crash_record_exn source f >|= fun v -> Some v)
~catch:(fun exn ->
match Exception.unwrap exn with
(* Avoid swallowing these *)
| Exit_status.Exit_with _
| Watchman_restarted ->
Exception.reraise exn
| _ -> Watchman_process.return None)
let has_capability name capabilities =
(* Projects down from the boolean error monad into booleans.
* Error states go to false, values are projected directly. *)
let project_bool m =
match m with
| Ok (v, _) -> v
| Error _ -> false
in
Hh_json.Access.(
return capabilities
>>= get_obj "capabilities"
>>= get_bool name
|> project_bool)
(* When we re-init our connection to Watchman, we use the old clockspec to get all the changes
* since our last response. However, if Watchman has restarted and the old clockspec pre-dates
* the new Watchman, then we may miss updates. It is important for Flow and Hack to restart
* in that case.
*
* Unfortunately, the response to "subscribe" doesn't have the "is_fresh_instance" field. So
* we'll instead send a small "query" request. It should always return 0 files, but it should
* tell us whether the Watchman service has restarted since clockspec.
*)
let assert_watchman_has_not_restarted_since
~debug_logging ~conn ~sockname ~watch_root ~clockspec =
let hard_to_match_name = "irrelevant.potato" in
let query =
Hh_json.(
JSON_Array
[
JSON_String "query";
JSON_String watch_root;
JSON_Object
[
("since", JSON_String clockspec);
("empty_on_fresh_instance", JSON_Bool true);
( "expression",
JSON_Array
[JSON_String "name"; JSON_String hard_to_match_name] );
];
])
in
Watchman_process.request ~debug_logging ~conn ~sockname query
>>= fun response ->
match Hh_json_helpers.Jget.bool_opt (Some response) "is_fresh_instance" with
| Some false -> Watchman_process.return ()
| Some true ->
Hh_logger.error
"Watchman server restarted so we may have missed some updates";
raise Watchman_restarted
| None ->
(* The response to this query **always** should include the `is_fresh_instance` boolean
* property. If it is missing then something has gone wrong with Watchman. Since we can't
* prove that Watchman has not restarted, we must treat this as an error. *)
Hh_logger.error
"Invalid Watchman response to `empty_on_fresh_instance` query:\n%s"
(Hh_json.json_to_string ~pretty:true response);
raise Exit_status.(Exit_with Watchman_failed)
let prepend_relative_path_term ~relative_path ~terms =
match terms with
| None -> None
| Some _ when String.equal relative_path "" ->
(* If we're watching the watch root directory, then there's no point in specifying a list of
* files and directories to watch. We're already subscribed to any change in this watch root
* anyway *)
None
| Some terms ->
(* So lets say we're being told to watch foo/bar. Is foo/bar a directory? Is it a file? If it
* is a file now, might it become a directory later? I'm not aware of aterm which will watch for either a file or a directory, so let's add two terms *)
Some
(J.strlist ["dirname"; relative_path]
:: J.strlist ["name"; relative_path]
:: terms)
let re_init
?prior_clockspec
{
init_timeout;
subscribe_mode;
expression_terms;
debug_logging;
roots;
sockname;
subscription_prefix;
} =
with_crash_record_opt "init" @@ fun () ->
Watchman_process.open_connection ~timeout:init_timeout ~sockname
>>= fun conn ->
Watchman_process.request
~debug_logging
~conn
~timeout:Default_timeout
~sockname
(capability_check ~optional:[flush_subscriptions_cmd] ["relative_root"])
>>= fun capabilities ->
let supports_flush = has_capability flush_subscriptions_cmd capabilities in
(* Disable subscribe if Watchman flush feature isn't supported. *)
let subscribe_mode =
if supports_flush then
subscribe_mode
else
None
in
Watchman_process.list_fold_values
roots
~init:(Some [], SSet.empty, SSet.empty)
~f:(fun (terms, watch_roots, failed_paths) path ->
(* Watch this root. If the path doesn't exist, watch_project will throw. In that case catch
* the error and continue for now. *)
Watchman_process.catch
~f:(fun () ->
Watchman_process.request
~debug_logging
~conn
~sockname
(watch_project (Path.to_string path))
>|= fun response -> Some response)
~catch:(fun _ -> Watchman_process.return None)
>|= fun response ->
match response with
| None ->
(terms, watch_roots, SSet.add (Path.to_string path) failed_paths)
| Some response ->
let watch_root = J.get_string_val "watch" response in
let relative_path =
J.get_string_val "relative_path" ~default:"" response
in
let terms = prepend_relative_path_term ~relative_path ~terms in
let watch_roots = SSet.add watch_root watch_roots in
(terms, watch_roots, failed_paths))
>>= fun (watched_path_expression_terms, watch_roots, failed_paths) ->
(* The failed_paths are likely includes which don't exist on the filesystem, so watch_project
* returned an error. Let's do a best effort attempt to infer the watch root and relative
* path for each bad include *)
let watched_path_expression_terms =
SSet.fold
(fun path terms ->
String_utils.(
match
SSet.find_first_opt
(fun root -> String.is_prefix path ~prefix:root)
watch_roots
with
| None -> failwith (spf "Cannot deduce watch root for path %s" path)
| Some root ->
let relative_path = lstrip (lstrip path root) Filename.dir_sep in
prepend_relative_path_term ~relative_path ~terms))
failed_paths
watched_path_expression_terms
in
(* All of our watched paths should have the same watch root. Let's assert that *)
let watch_root =
match SSet.elements watch_roots with
| [] -> failwith "Cannot run watchman with fewer than 1 root"
| [watch_root] -> watch_root
| _ ->
failwith
(spf
"Can't watch paths across multiple Watchman watch_roots. Found %d watch_roots"
(SSet.cardinal watch_roots))
in
(* If we don't have a prior clockspec, grab the current clock *)
(match prior_clockspec with
| Some clockspec ->
assert_watchman_has_not_restarted_since
~debug_logging
~conn
~sockname
~watch_root
~clockspec
>>= fun () -> Watchman_process.return clockspec
| None ->
Watchman_process.request ~debug_logging ~conn ~sockname (clock watch_root)
>|= J.get_string_val "clock")
>>= fun clockspec ->
let watched_path_expression_terms =
Option.map watched_path_expression_terms ~f:(J.pred "anyof")
in
let env =
{
settings =
{
init_timeout;
debug_logging;
subscribe_mode;
expression_terms;
roots;
sockname;
subscription_prefix;
};
conn;
watch_root;
watched_path_expression_terms;
clockspec;
subscription =
Printf.sprintf "%s.%d" subscription_prefix (Unix.getpid ());
}
in
(match subscribe_mode with
| None -> Watchman_process.return ()
| Some mode ->
Watchman_process.request
~debug_logging
~conn
~sockname
(subscribe ~mode env)
>|= ignore)
>|= fun () -> env
let init ?since_clockspec settings () =
let prior_clockspec = since_clockspec in
re_init ?prior_clockspec settings
let extract_file_names env json =
let files =
try J.get_array_val "files" json with
(* When an hg.update happens, it shows up in the watchman subscription
* as a notification with no files key present. *)
| J.Not_found -> []
in
let files =
List.map files ~f:(fun json ->
let s = Hh_json.get_string_exn json in
let abs = Filename.concat env.watch_root s in
abs)
in
files
let within_backoff_time attempts time =
let offset =
4.0
*. 2.0
** float
(if attempts > 3 then
3
else
attempts)
in
Float.(Unix.time () >= time +. offset)
let maybe_restart_instance instance =
match instance with
| Watchman_alive _ -> Watchman_process.return instance
| Watchman_dead dead_env ->
if dead_env.reinit_attempts >= max_reinit_attempts then
let () =
Hh_logger.log "Ran out of watchman reinit attempts. Exiting."
in
raise Exit_status.(Exit_with Watchman_failed)
else if within_backoff_time dead_env.reinit_attempts dead_env.dead_since
then (
let () =
Hh_logger.log "Attemping to reestablish watchman subscription"
in
re_init
~prior_clockspec:dead_env.prior_clockspec
dead_env.prior_settings
>|= function
| None ->
Hh_logger.log "Reestablishing watchman subscription failed.";
EventLogger.watchman_connection_reestablishment_failed ();
Watchman_dead
{ dead_env with reinit_attempts = dead_env.reinit_attempts + 1 }
| Some env ->
Hh_logger.log "Watchman connection reestablished.";
EventLogger.watchman_connection_reestablished ();
Watchman_alive env
) else
Watchman_process.return instance
let close env = Watchman_process.close_connection env.conn
let close_channel_on_instance env =
close env >|= fun () ->
EventLogger.watchman_died_caught ();
(Watchman_dead (dead_env_from_alive env), Watchman_unavailable)
let with_instance instance ~try_to_restart ~on_alive ~on_dead =
(if try_to_restart then
maybe_restart_instance instance
else
Watchman_process.return instance)
>>= function
| Watchman_dead dead_env -> on_dead dead_env
| Watchman_alive env -> on_alive env
(** Calls f on the instance, maybe restarting it if its dead and maybe
* reverting it to a dead state if things go south. For example, if watchman
* shuts the connection on us, or shuts down, or crashes, we revert to a dead
* instance, upon which a restart will be attempted down the road.
* Alternatively, we also proactively revert to a dead instance if it appears
* to be unresponsive (Timeout), and if reading the payload from it is
* taking too long. *)
let call_on_instance =
let on_dead dead_env =
Watchman_process.return (Watchman_dead dead_env, Watchman_unavailable)
in
let on_alive source f env =
Watchman_process.catch
~f:(fun () ->
with_crash_record_exn source (fun () -> f env)
>|= fun (env, result) -> (Watchman_alive env, result))
~catch:(fun exn ->
match Exception.unwrap exn with
| Sys_error msg when String.equal msg "Broken pipe" ->
Hh_logger.log "Watchman Pipe broken.";
close_channel_on_instance env
| Sys_error msg when String.equal msg "Connection reset by peer" ->
Hh_logger.log "Watchman connection reset by peer.";
close_channel_on_instance env
| Sys_error msg when String.equal msg "Bad file descriptor" ->
(* This happens when watchman is tearing itself down after we
* retrieved a sock address and connected to the sock address. That's
* because Unix.open_connection (via Timeout.open_connection) doesn't
* error even when the sock address is no longer valid and actually -
* it returns a channel that will error at some later time when you
* actually try to do anything with it (write to it, or even get the
* file descriptor of it). I'm pretty sure we don't need to close the
* channel when that happens since we never had a useable channel
* to start with. *)
Hh_logger.log "Watchman bad file descriptor.";
EventLogger.watchman_died_caught ();
Watchman_process.return
(Watchman_dead (dead_env_from_alive env), Watchman_unavailable)
| End_of_file ->
Hh_logger.log "Watchman connection End_of_file. Closing channel";
close_channel_on_instance env
| Watchman_process.Read_payload_too_long ->
Hh_logger.log "Watchman reading payload too long. Closing channel";
close_channel_on_instance env
| Timeout ->
Hh_logger.log "Watchman reading Timeout. Closing channel";
close_channel_on_instance env
| Watchman_error msg ->
Hh_logger.log "Watchman error: %s. Closing channel" msg;
close_channel_on_instance env
| _ ->
let msg = Exception.to_string exn in
EventLogger.watchman_uncaught_failure msg;
raise Exit_status.(Exit_with Watchman_failed))
in
fun instance source f ->
with_instance
instance
~try_to_restart:true
~on_dead
~on_alive:(on_alive source f)
(** This is a large >50MB payload, which could longer than 2 minutes for
* Watchman to generate and push down the channel. *)
let get_all_files env =
Watchman_process.catch
~f:(fun () ->
with_crash_record_exn "get_all_files" @@ fun () ->
Watchman_process.request
~debug_logging:env.settings.debug_logging
~timeout:Default_timeout
~sockname:env.settings.sockname
(all_query env)
>|= fun response ->
env.clockspec <- J.get_string_val "clock" response;
extract_file_names env response)
~catch:(fun _ -> raise Exit_status.(Exit_with Watchman_failed))
module RepoStates : sig
type state = string
val enter : state -> unit
val leave : state -> unit
val get_as_telemetry : unit -> Telemetry.t
end = struct
type state = string
type t = {
past_states: SSet.t;
current_states: state list;
}
let init : t = { past_states = SSet.empty; current_states = [] }
let states : t ref = ref init
let enter : state -> unit =
fun state ->
states :=
{ !states with current_states = state :: !states.current_states }
let rec remove_first : string list -> string -> string list =
fun list elt ->
match list with
| [] -> []
| hd :: list ->
if String.equal hd elt then
list
else
hd :: remove_first list elt
let leave : state -> unit =
fun state ->
let { current_states; past_states } = !states in
let current_states = remove_first current_states state in
let past_states = SSet.add state past_states in
states := { current_states; past_states }
let get_as_telemetry () =
let { current_states; past_states } = !states in
Telemetry.create ()
|> Telemetry.string_list ~key:"current_states" ~value:current_states
|> Telemetry.string_list
~key:"past_states"
~value:(SSet.elements past_states)
end
let make_state_change_response state name data =
let metadata = J.try_get_val "metadata" data in
match state with
| `Enter ->
RepoStates.enter name;
State_enter (name, metadata)
| `Leave ->
RepoStates.leave name;
State_leave (name, metadata)
(** returns (data.clock.scm.mergebase, data.since?.scm.mergebase).
The watchman docs explain: "The since field holds the fat clock that was returned
in the clock field from the prior subscription update. It is present as a convenience
for you; you can compare the mergebase fields between the two to determine that the
merge base changed in this update."
Edge cases: (1) when we send the first subscribe request, we get back an answer that
lacks the since property entirely, (2) the next thing we hear has an empty since.mergebase,
(3) the next thing we hear has a full since.mergebase. *)
let extract_mergebase data =
let open Hh_json.Access in
let accessor = return data in
let ret =
accessor >>= get_obj "clock" >>= get_obj "scm" >>= get_string "mergebase"
>>= fun (mergebase, _) ->
let since_mergebase =
accessor
>>= get_obj "since"
>>= get_obj "scm"
>>= get_string "mergebase"
|> to_option
in
return (mergebase, since_mergebase)
in
to_option ret
(** watchman's data.clock property is either a slim-clock "string", or a fat-clock "{clock, scm}".
This function extracts either. *)
let extract_clock data =
let open Hh_json.Access in
let fat = return data >>= get_obj "clock" >>= get_string "clock" in
let slim = return data >>= get_string "clock" in
match (fat, slim) with
| (Ok (clock, _), _)
| (_, Ok (clock, _)) ->
clock
| _ -> failwith "watchman response lacks clock"
let transform_asynchronous_get_changes_response env data =
match data with
| None -> (env, Files_changed SSet.empty)
| Some data ->
let clock = extract_clock data in
env.clockspec <- clock;
(match extract_mergebase data with
| Some (mergebase, Some since_mergebase)
when not (String.equal mergebase since_mergebase) ->
let files = set_of_list @@ extract_file_names env data in
(env, Changed_merge_base (mergebase, files, clock))
| _ ->
assert_no_fresh_instance data;
(try
( env,
make_state_change_response
`Enter
(J.get_string_val "state-enter" data)
data )
with
| J.Not_found ->
(try
( env,
make_state_change_response
`Leave
(J.get_string_val "state-leave" data)
data )
with
| J.Not_found ->
(env, Files_changed (set_of_list @@ extract_file_names env data)))))
let get_clock instance =
match instance with
| Watchman_alive { clockspec; _ } -> clockspec
| Watchman_dead { prior_clockspec; _ } -> prior_clockspec
let get_changes ?deadline instance =
call_on_instance instance "get_changes" @@ fun env ->
let timeout =
Option.map deadline ~f:(fun deadline ->
let timeout = deadline -. Unix.time () in
Explicit_timeout Float.(max timeout 0.0))
in
let debug_logging = env.settings.debug_logging in
let sockname = env.settings.sockname in
if Option.is_some env.settings.subscribe_mode then
Watchman_process.blocking_read ~debug_logging ?timeout env.conn
>|= fun response ->
let (env, result) =
transform_asynchronous_get_changes_response env response
in
(env, Watchman_pushed result)
else
let query = since_query env in
Watchman_process.request
~debug_logging
~conn:env.conn
?timeout
~sockname
query
>|= fun response ->
let (env, changes) =
transform_asynchronous_get_changes_response env (Some response)
in
(env, Watchman_synchronous [changes])
let get_changes_since_mergebase ?timeout env =
Watchman_process.request
?timeout
~debug_logging:env.settings.debug_logging
~sockname:env.settings.sockname
(get_changes_since_mergebase_query env)
>|= extract_file_names env
let get_mergebase ?timeout env =
Watchman_process.request
?timeout
~debug_logging:env.settings.debug_logging
~sockname:env.settings.sockname
(get_changes_since_mergebase_query env)
>|= fun response ->
match extract_mergebase response with
| Some (mergebase, _since_mergebase) -> mergebase
| None -> raise (Watchman_error "Failed to extract mergebase from response")
let flush_request ~(timeout : int) watch_root =
Hh_json.(
let directive =
JSON_Object
[
(* Watchman expects timeout milliseconds. *)
("sync_timeout", JSON_Number (string_of_int @@ (timeout * 1000)));
]
in
JSON_Array
[JSON_String "flush-subscriptions"; JSON_String watch_root; directive])
let rec poll_until_sync ~deadline env acc =
let is_finished_flush_response json =
match json with
| None -> false
| Some json ->
Hh_json.Access.(
let is_synced =
lazy
(return json >>= get_array "synced" |> function
| Error _ -> false
| Ok (vs, _) ->
List.exists vs ~f:(fun str ->
String.equal (Hh_json.get_string_exn str) env.subscription))
in
let is_not_needed =
lazy
(return json >>= get_array "no_sync_needed" |> function
| Error _ -> false
| Ok (vs, _) ->
List.exists vs ~f:(fun str ->
String.equal (Hh_json.get_string_exn str) env.subscription))
in
Lazy.force is_synced || Lazy.force is_not_needed)
in
let timeout =
let timeout = deadline -. Unix.time () in
if Float.(timeout <= 0.0) then
raise Timeout
else
Explicit_timeout timeout
in
let debug_logging = env.settings.debug_logging in
Watchman_process.blocking_read ~debug_logging ~timeout env.conn
>>= fun json ->
if is_finished_flush_response json then
Watchman_process.return (env, acc)
else
let (env, acc) =
match json with
| None -> (env, acc)
| Some json ->
let (env, result) =
transform_asynchronous_get_changes_response env (Some json)
in
(env, result :: acc)
in
poll_until_sync ~deadline env acc
let poll_until_sync ~deadline env = poll_until_sync ~deadline env []
let get_changes_synchronously ~(timeout : int) instance =
( call_on_instance instance "get_changes_synchronously" @@ fun env ->
if Option.is_none env.settings.subscribe_mode then
let timeout = Explicit_timeout (float timeout) in
let query = since_query env in
Watchman_process.request
~debug_logging:env.settings.debug_logging
~conn:env.conn
~timeout
~sockname:env.settings.sockname
query
>|= fun response ->
let (env, changes) =
transform_asynchronous_get_changes_response env (Some response)
in
(env, Watchman_synchronous [changes])
else
let request = flush_request ~timeout env.watch_root in
let conn = env.conn in
Watchman_process.send_request_and_do_not_wait_for_response
~debug_logging:env.settings.debug_logging
~conn
request
>>= fun () ->
let deadline = Unix.time () +. float_of_int timeout in
poll_until_sync ~deadline env >|= fun (env, changes) ->
(env, Watchman_synchronous (List.rev changes)) )
>|= function
| (_, Watchman_unavailable) ->
raise (Watchman_error "Watchman unavailable for synchronous response")
| (_, Watchman_pushed _) ->
raise (Watchman_error "Wtf? pushed response from synchronous request")
| (instance, Watchman_synchronous files) -> (instance, files)
let conn_of_instance = function
| Watchman_dead _ -> None
| Watchman_alive { conn; _ } -> Some conn
module Testing = struct
include Testing_common
let get_test_env () =
Watchman_process.Testing.get_test_conn () >|= fun conn ->
{
settings = test_settings;
conn;
watch_root = "/path/to/root";
clockspec = "";
watched_path_expression_terms =
Some
(J.pred
"anyof"
[J.strlist ["dirname"; "foo"]; J.strlist ["name"; "foo"]]);
subscription = "dummy_prefix.123456789";
}
let transform_asynchronous_get_changes_response env json =
transform_asynchronous_get_changes_response env json
end
end
module Watchman_actual = struct
include Functor (Regular_watchman_process)
let get_reader instance =
Option.map
(conn_of_instance instance)
~f:Regular_watchman_process.get_reader
end
module Watchman_mock = struct
exception Not_available_in_mocking
type 'a result = 'a
type conn
include Watchman_sig.Types
type env = string
type dead_env = unit
type watchman_instance =
| Watchman_dead of dead_env
| Watchman_alive of env
module Mocking = struct
let print_env env = env
let init = ref None
let init_returns v = init := v
let changes = ref Watchman_unavailable
let get_changes_returns v = changes := v
let changes_synchronously = ref []
let all_files = ref []
end
module Testing = struct
include Testing_common
let get_test_env () = "test_env"
let transform_asynchronous_get_changes_response _ _ =
raise Not_available_in_mocking
end
module RepoStates = struct
let get_as_telemetry () = Telemetry.create ()
end
let init ?since_clockspec:_ _ () = !Mocking.init
let get_changes ?deadline instance =
let _ = deadline in
let result = !Mocking.changes in
Mocking.changes := Watchman_unavailable;
(instance, result)
let get_changes_synchronously ~timeout instance =
let _ = timeout in
let result = !Mocking.changes_synchronously in
Mocking.changes_synchronously := [];
(instance, result)
let get_clock _instance = ""
let get_reader _ = None
let conn_of_instance _ = None
let get_all_files _ =
let result = !Mocking.all_files in
Mocking.all_files := [];
result
let get_changes_since_mergebase ?timeout:_ _ = []
let get_mergebase ?timeout:_ _ = "mergebase"
let close _ = ()
let with_instance instance ~try_to_restart:_ ~on_alive ~on_dead =
match instance with
| Watchman_dead dead_env -> on_dead dead_env
| Watchman_alive env -> on_alive env
end
module type S = sig
include Watchman_sig.S with type 'a result = 'a
val get_reader : watchman_instance -> Buffered_line_reader.t option
end
include
(val if Injector_config.use_test_stubbing then
(module Watchman_mock : S)
else
(module Watchman_actual : S)) |
OCaml Interface | hhvm/hphp/hack/src/watchman/watchman.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module Watchman_process_helpers : sig
module J = Hh_json_helpers.AdhocJsonHelpers
val debug : bool
val timeout_to_secs : Watchman_sig.Types.timeout -> float option
exception Read_payload_too_long
val assert_no_error : Hh_json.json -> unit
val sanitize_watchman_response : debug_logging:bool -> string -> Hh_json.json
end
module Functor (Watchman_process : Watchman_sig.WATCHMAN_PROCESS) :
Watchman_sig.S with type 'a result = 'a Watchman_process.result
include Watchman_sig.S with type 'a result = 'a
val get_reader : watchman_instance -> Buffered_line_reader.t option |
OCaml | hhvm/hphp/hack/src/watchman/watchman_sig.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module Types = struct
exception Timeout
exception Watchman_error of string
exception Subscription_canceled_by_watchman
exception Watchman_restarted
type subscribe_mode =
| All_changes
| Defer_changes
| Scm_aware
type timeout =
| No_timeout
| Default_timeout
| Explicit_timeout of float
type init_settings = {
(* None for query mode, otherwise specify subscriptions mode. *)
subscribe_mode: subscribe_mode option;
(* Seconds used for init timeout - will be reused for reinitialization. None -> no timeout *)
init_timeout: timeout;
(* See watchman expression terms. *)
expression_terms: Hh_json.json list;
debug_logging: bool;
roots: Path.t list;
sockname: string option;
subscription_prefix: string;
}
(** The message's clock. *)
type clock = string [@@deriving show]
type pushed_changes =
(*
* State name and metadata.
*
* For example:
* State name: "hg.update"
* Metadata:
* {
* "partial":false,
* "rev":"780dab9ff0a01691c9b18a5ee1194810e555c78b",
* "distance":2,
* "status":"ok"
* }
*
* Note: The distance is HG Revision distance, not SVN revision distance.
*)
| State_enter of string * Hh_json.json option
| State_leave of string * Hh_json.json option
| Changed_merge_base of string * SSet.t * clock
| Files_changed of SSet.t
[@@deriving show]
type changes =
| Watchman_unavailable
| Watchman_pushed of pushed_changes
| Watchman_synchronous of pushed_changes list
end
(** The abstract types, and the types that are defined in terms of
* abstract types must be split out. The reason is left as an exercise
* to the reader (i.e. try it yourself out a few ways and you'll discover the
* limitations - whether your strategy is splitting up the definitions
* into 3 modules "base types, abstract types, dependent types", or
* if you change this to a functor). *)
module Abstract_types = struct
type env
type dead_env
(* This has to be repeated because they depend on the abstract types. *)
type watchman_instance =
| Watchman_dead of dead_env
| Watchman_alive of env
end
module type WATCHMAN_PROCESS = sig
type 'a result
type conn
exception Read_payload_too_long
val ( >>= ) : 'a result -> ('a -> 'b result) -> 'b result
val ( >|= ) : 'a result -> ('a -> 'b) -> 'b result
val return : 'a -> 'a result
val catch :
f:(unit -> 'b result) -> catch:(Exception.t -> 'b result) -> 'b result
val list_fold_values :
'a list -> init:'b -> f:('b -> 'a -> 'b result) -> 'b result
val open_connection :
timeout:Types.timeout -> sockname:string option -> conn result
val request :
debug_logging:bool ->
?conn:conn ->
?timeout:Types.timeout ->
sockname:string option ->
Hh_json.json ->
Hh_json.json result
val send_request_and_do_not_wait_for_response :
debug_logging:bool -> conn:conn -> Hh_json.json -> unit result
val blocking_read :
debug_logging:bool ->
?timeout:Types.timeout ->
conn ->
Hh_json.json option result
val close_connection : conn -> unit result
module Testing : sig
val get_test_conn : unit -> conn result
end
end
module type S = sig
include module type of Types
include module type of Abstract_types
type 'a result
type conn
val init :
?since_clockspec:string -> init_settings -> unit -> env option result
val get_all_files : env -> string list result
val get_changes_since_mergebase :
?timeout:timeout -> env -> string list result
val get_mergebase : ?timeout:timeout -> env -> string result
val get_changes :
?deadline:float -> watchman_instance -> (watchman_instance * changes) result
val get_changes_synchronously :
timeout:int ->
watchman_instance ->
(watchman_instance * pushed_changes list) result
val get_clock : watchman_instance -> clock
val conn_of_instance : watchman_instance -> conn option
val close : env -> unit result
val with_instance :
watchman_instance ->
try_to_restart:bool ->
on_alive:(env -> 'a result) ->
on_dead:(dead_env -> 'a result) ->
'a result
module RepoStates : sig
val get_as_telemetry : unit -> Telemetry.t
end
(* Expose some things for testing. *)
module Testing : sig
val get_test_env : unit -> env result
val test_settings : init_settings
val transform_asynchronous_get_changes_response :
env -> Hh_json.json option -> env * pushed_changes
end
module Mocking : sig
val print_env : env -> string
val init_returns : string option -> unit
val get_changes_returns : changes -> unit
end
end |
OCaml | hhvm/hphp/hack/src/watchman/watchman_utils.ml | (** State_enter and State_leave events contains a JSON blob specifying
* the revision we are moving to. This gets it. *)
let rev_in_state_change json =
Hh_json.Access.(
return json >>= get_string "rev" |> function
| Error _ ->
let () =
Hh_logger.log
"Watchman_utils failed to get rev in json: %s"
(Hh_json.json_to_string json)
in
None
| Ok (v, _) -> Some v)
let merge_in_state_change json =
Hh_json.Access.(
return json >>= get_bool "merge" |> function
| Error _ ->
let () =
Hh_logger.log
"Watchman_utils failed to get merge in json: %s"
(Hh_json.json_to_string json)
in
None
| Ok (v, _) -> Some v) |
hhvm/hphp/hack/src/watchman_event_watcher/dune | (library
(name watchman_config)
(wrapped false)
(modules watchmanEventWatcherConfig)
(libraries injector_config server_utils))
(library
(name watchman_lib)
(wrapped false)
(modules watchmanEventWatcher)
(libraries socket watchman_config watchman_utils))
(executable
(name watcher_bin)
(modules watcher_bin)
(link_flags
(:standard
(:include ../dune_config/ld-opts.sexp)))
(modes exe byte_complete)
(libraries default_injector_config folly_stubs watchman_config watchman_lib))
(library
(name watchman_client)
(wrapped false)
(modules watchmanEventWatcherClient watchmanEventWatcherClient_sig)
(libraries socket watchman_config server_utils)) |
|
YAML | hhvm/hphp/hack/src/watchman_event_watcher/packman.yml | packages:
fb-hh-watchman-event-watcher:
packager: hack
build_architectures: [x86_64, aarch64]
summary: Watches a repo for Watchman state change events. Reports to clients the state of the repo
rules:
buck:hphp/hack/src/watchman_event_watcher:watcher_bin:
# Packman looks for the targets in buck-out/gen
# binaries are placed in buck-out/bin
../bin/hphp/hack/src/watchman_event_watcher/watcher_bin/watcher_bin.opt:
owner: 'root'
group: 'root'
mode: '0755'
path: bin/hh-watchman-event-watcher |
OCaml | hhvm/hphp/hack/src/watchman_event_watcher/watcher_bin.ml | module WEW = WatchmanEventWatcher
module Config = WatchmanEventWatcherConfig
let () = Random.self_init ()
module Args = struct
type t = {
root: Path.t;
daemonize: bool;
get_sockname: bool;
}
let usage =
Printf.sprintf "Usage: %s [--daemonize] [REPO DIRECTORY]\n" Sys.argv.(0)
let parse () =
let root = ref None in
let daemonize = ref false in
let get_sockname = ref false in
let options =
[
("--daemonize", Arg.Set daemonize, "spawn watcher daemon");
("--get-sockname", Arg.Set get_sockname, "print socket and exit");
]
in
let () = Arg.parse options (fun s -> root := Some s) usage in
match !root with
| None ->
Printf.eprintf "%s" usage;
exit 1
| Some root ->
{
root = Path.make root;
daemonize = !daemonize;
get_sockname = !get_sockname;
}
end
let () =
Daemon.check_entry_point ();
Folly.ensure_folly_init ();
let args = Args.parse () in
if args.Args.get_sockname then
Printf.printf "%s%!" (Config.socket_file args.Args.root)
else if args.Args.daemonize then
WEW.spawn_daemon args.Args.root
else
WEW.main args.Args.root |
OCaml | hhvm/hphp/hack/src/watchman_event_watcher/watchmanEventWatcher.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(***************************************************
("Who watches the Watchmen?")
****************************************************)
open Hh_prelude
(**
* Watches a repo and logs state-leave and state-enter
* events on it using a Watchman subscription.
*
* This is useful to ask the question "is this repo mid-update
* right now?", which isn't provided by the Mercurial or Watchman
* APIs.
*
* Socket can be retrieved by invoking this command with --get-sockname
*
* Clients get the status by connecting to the socket and reading
* newline-terminated messages. The message can be:
* 'unknown' - watcher doesn't know what state the repo is in
* 'mid_update' - repo is currently undergoing an update
* 'settled' - repo is settled (not undergoing an update)
*
* After sending 'settled' message, the socket is closed.
* An 'unknown' or 'mid_updat' message is eventually followed by a
* 'settled' message when the repo is settled.
*
* The Hack Monitor uses the watcher when first starting up to delay
* initialization while a repo is in the middle of an update. Initialization
* mid-update is undesirable because the wrong saved state will be loaded
* (the one corresponding to the revision we are leaving) resulting in
* a slow recheck after init.
*
* Why do we need a socket with a 'settled' notification instead of just
* having the Hack Server tail the watcher's logs? Consider the following
* race:
*
* Watcher prints 'mid_update' to logs, Watchman has sent State_leave
* event to subscribers before the Hack Monitor's subscription started,
* and the Watcher crashes before processing this State_leave.
*
*
* If the Hack Monitor just tailed the watcher logs to see the state of the
* repo, it would not start a server, would never get the State_leave watchman
* event on its subscription, and would just wait indefinitely.
*
* The watcher must also be used as the source-of-truth for the repo's
* state during startup instead of the Hack Monitor's own subscription.
* Consider the following incorrect usage of the Watcher:
*
* Hack Monitor starts up, starts a Watchman subscription, checks watcher
* for repo state and sees 'mid_update', delays starting a server.
* Waits on its Watchman subscription for a State_leave before starting a
* server.
*
*
* The Monitor could potentially wait forever in this scenario due to a
* race condition - Watchman has already sent the State_leave to all
* subscriptions before the Monitor's subscription was started, but it
* was not yet processed by the Watcher.
*
* The Hack Monitor should instead be waiting for a 'settled' from the
* Watcher.
*)
module Config = WatchmanEventWatcherConfig
module Responses = Config.Responses
type state =
| Unknown (** State_enter heading towards. *)
| Entering (** State_leave left at. *)
| Left
type env = {
watchman: Watchman.watchman_instance; (** Directory we are watching. *)
root: Path.t;
update_state: state;
transaction_state: state;
socket: Unix.file_descr;
waiting_clients: Unix.file_descr Queue.t;
}
let ignore_unix_epipe f x =
try f x with
| Unix.Unix_error (Unix.EPIPE, _, _) -> ()
(**
* This allows the repo itself to turn on-or-off this Watchman Event
* Watcher service (and send a fake Settled message instead).
*
* This service has its own deploy/release cycle independent of the
* Hack Server. Adding this toggle to the Hack Server wouldn't retroactively
* allow us to toggle off this service for older versions of the Hack Server.
* Putting it here instead allows us to turn off this service regardless of
* what version of the Hack server is running.
*)
let is_enabled env =
let enabled_file = Path.concat env.root ".hh_enable_watchman_event_watcher" in
Sys.file_exists (Path.to_string enabled_file)
let send_to_fd env v fd =
let v =
if is_enabled env then
v
else (
Hh_logger.log "Service not enabled. Sending fake Settled message instead";
Responses.Settled
)
in
let str = Printf.sprintf "%s\n" (Responses.to_string v) in
let str = Bytes.of_string str in
let str_length = Bytes.length str in
let bytes = Unix.single_write fd str 0 str_length in
if bytes = str_length then
()
else
(* We're only writing a few bytes. Not sure what to do here.
* Retry later when the pipe has been pumped? *)
Hh_logger.log "Failed to write all bytes";
match v with
| Responses.Settled -> Unix.close fd
| Responses.Unknown
| Responses.Mid_update ->
Queue.enqueue env.waiting_clients fd
type init_failure =
| Failure_daemon_already_running
| Failure_watchman_init
type daemon_init_result =
| Init_failure of init_failure
| Init_success
let process_changes changes env =
let notify_client client =
(* Notify the client that the repo has settled. *)
ignore_unix_epipe (send_to_fd env Responses.Settled) client
in
let notify_waiting_clients env =
let clients = Queue.create () in
let () = Queue.blit_transfer ~src:env.waiting_clients ~dst:clients () in
Queue.fold ~f:(fun () client -> notify_client client) ~init:() clients
in
Watchman.(
match changes with
| Watchman_unavailable ->
Hh_logger.log "Watchman unavailable. Exiting";
exit 1
| Watchman_pushed (Changed_merge_base (mergebase, changes, _)) ->
Hh_logger.log "changed mergebase: %s" mergebase;
let changes = String.concat ~sep:"\n" (SSet.elements changes) in
Hh_logger.log "changes: %s" changes;
let env = { env with update_state = Left } in
let () = notify_waiting_clients env in
env
| Watchman_pushed (State_enter (name, json))
when String.equal name "hg.update" ->
Hh_logger.log "State_enter %s" name;
let ( >>= ) = Option.( >>= ) in
let ( >>| ) = Option.( >>| ) in
ignore
( json >>= Watchman_utils.rev_in_state_change >>| fun hg_rev ->
Hh_logger.log "Revision: %s" hg_rev );
{ env with update_state = Entering }
| Watchman_pushed (State_enter (name, _json))
when String.equal name "hg.transaction" ->
{ env with transaction_state = Entering }
| Watchman_pushed (State_enter (name, _json)) ->
Hh_logger.log "Ignoring State_enter %s" name;
env
| Watchman_pushed (State_leave (name, json))
when String.equal name "hg.update" ->
Hh_logger.log "State_leave %s" name;
let ( >>= ) = Option.( >>= ) in
let ( >>| ) = Option.( >>| ) in
ignore
( json >>= Watchman_utils.rev_in_state_change >>| fun hg_rev ->
Hh_logger.log "Revision: %s" hg_rev );
let env = { env with update_state = Left } in
let () = notify_waiting_clients env in
env
| Watchman_pushed (State_leave (name, _json))
when String.equal name "hg.transaction" ->
{ env with transaction_state = Left }
| Watchman_pushed (State_leave (name, _json)) ->
Hh_logger.log "Ignoring State_leave %s" name;
env
| Watchman_pushed (Files_changed set) when SSet.is_empty set -> env
| Watchman_pushed (Files_changed set) ->
let files =
SSet.fold
(fun x acc ->
let exists = Sys.file_exists x in
acc ^ Printf.sprintf "%s: %b" x exists ^ "; ")
set
""
in
Hh_logger.log "Changes: %s" files;
env
| Watchman_synchronous _ ->
Hh_logger.log "Watchman unexpectd synchronous response. Exiting";
exit 1)
let check_subscription env =
let (w, changes) = Watchman.get_changes env.watchman in
let env = { env with watchman = w } in
let env = process_changes changes env in
env
let sleep_and_check ?(wait_time = 0.3) socket =
let (ready_socket_l, _, _) = Unix.select [socket] [] [] wait_time in
not (List.is_empty ready_socket_l)
(** Batch accept all new client connections. Return the list of them. *)
let get_new_clients socket =
let rec get_all_clients_nonblocking socket acc =
let has_client = sleep_and_check ~wait_time:0.0 socket in
if not has_client then
acc
else
let acc =
try
let (fd, _) = Unix.accept socket in
fd :: acc
with
| Unix.Unix_error _ -> acc
in
get_all_clients_nonblocking socket acc
in
let has_client = sleep_and_check socket in
if not has_client then
[]
else
get_all_clients_nonblocking socket []
let process_client_ env client =
(* We allow this to throw Unix_error - this lets us ignore broken
* clients instead of adding them to the waiting_clients queue. *)
(match (env.update_state, env.transaction_state) with
| (Unknown, _)
| (_, Unknown) ->
send_to_fd env Responses.Unknown client
| (Entering, Entering)
| (Entering, Left)
| (Left, Entering) ->
send_to_fd env Responses.Mid_update client
| (Left, Left) -> send_to_fd env Responses.Settled client);
env
let process_client env client =
try process_client_ env client with
| Unix.Unix_error _ -> env
let check_new_connections env =
let new_clients = get_new_clients env.socket in
let env = List.fold_left new_clients ~init:env ~f:process_client in
let count = List.length new_clients in
if count > 0 then HackEventLogger.processed_clients count;
env
let rec serve env =
let env = check_subscription env in
let env = check_new_connections env in
serve env
let init_watchman root =
Watchman.init
{
Watchman.subscribe_mode = Some Watchman.All_changes;
init_timeout = Watchman.Explicit_timeout 30.;
debug_logging = false;
expression_terms = FilesToIgnore.watchman_watcher_expression_terms;
sockname = None;
subscription_prefix = "hh_event_watcher";
roots = [root];
}
()
let init root =
let init_id = Random_id.short_string () in
HackEventLogger.init_watchman_event_watcher root init_id;
let lock_file = WatchmanEventWatcherConfig.lock root in
if not (Lock.grab lock_file) then (
Hh_logger.log "Can't grab lock; terminating.\n%!";
HackEventLogger.lock_stolen lock_file;
Error Failure_daemon_already_running
) else
let watchman = init_watchman root in
match watchman with
| None ->
Hh_logger.log "Error failed to initialize watchman";
Error Failure_watchman_init
| Some wenv ->
let socket = Socket.init_unix_socket (Config.socket_file root) in
Hh_logger.log "initialized and listening on %s" (Config.socket_file root);
Ok
{
watchman = Watchman.Watchman_alive wenv;
update_state = Unknown;
transaction_state = Unknown;
socket;
root;
waiting_clients = Queue.create ();
}
let to_channel_no_exn oc data =
try Daemon.to_channel oc ~flush:true data with
| exn ->
let e = Exception.wrap exn in
Hh_logger.exception_ ~prefix:"Warning: writing to channel failed" e
let main root =
Sys_utils.set_signal Sys.sigpipe Sys.Signal_ignore;
let result = init root in
match result with
| Ok env -> begin
try serve env with
| exn ->
let e = Exception.wrap exn in
let () =
Hh_logger.exception_
~prefix:"WatchmanEventWatcher uncaught exception. exiting."
e
in
Exception.reraise e
end
| Error Failure_daemon_already_running
| Error Failure_watchman_init ->
exit 1
let log_file root =
let log_link = WatchmanEventWatcherConfig.log_link root in
(try Sys.rename log_link (log_link ^ ".old") with
| _ -> ());
Sys_utils.make_link_of_timestamped log_link
let daemon_main_ root oc =
match init root with
| Ok env ->
to_channel_no_exn oc Init_success;
serve env
| Error Failure_watchman_init ->
to_channel_no_exn oc (Init_failure Failure_watchman_init);
Hh_logger.log "Watchman init failed. Exiting.";
HackEventLogger.init_watchman_failed ();
exit 1
| Error Failure_daemon_already_running ->
Hh_logger.log "Daemon already running. Exiting.";
exit 1
let daemon_main root (_ic, oc) =
Sys_utils.set_signal Sys.sigpipe Sys.Signal_ignore;
try daemon_main_ root oc with
| exn ->
let e = Exception.wrap exn in
HackEventLogger.watchman_uncaught_exception e
(** Typechecker canont infer this type since the input channel
* is never used so its phantom type is never inferred. We annotate
* the type manually to "unit" here to help it out. *)
let daemon_entry : (Path.t, unit, daemon_init_result) Daemon.entry =
Daemon.register_entry_point "Watchman_event_watcher_daemon_main" daemon_main
let spawn_daemon root =
let log_file_path = log_file root in
let in_fd = Daemon.null_fd () in
let out_fd = Daemon.fd_of_path log_file_path in
Printf.eprintf "Spawning daemon. Its logs will go to: %s\n%!" log_file_path;
let { Daemon.channels; _ } =
Daemon.spawn (in_fd, out_fd, out_fd) daemon_entry root
in
let result = Daemon.from_channel (fst channels) in
match result with
| Init_success -> ()
| Init_failure Failure_daemon_already_running ->
Printf.eprintf "No need to spawn daemon. One already running";
exit 0
| Init_failure Failure_watchman_init ->
Printf.eprintf "Daemon failed to spawn - watchman failure\n%!";
exit 1 |
OCaml | hhvm/hphp/hack/src/watchman_event_watcher/watchmanEventWatcherClient.ml | (*
* Copyright (c) 2017, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(**
* A client to get the repo state from an already-running
* server watching a repo.
*
* See .mli file for details.
*)
open Hh_prelude
module Config = WatchmanEventWatcherConfig
module Responses = WatchmanEventWatcherConfig.Responses
module Client_actual = struct
(**
* We track the last known state of the Watcher so we can return a response
* in get_status even when there's nothing to be read from the reader.
*
* This let's us differentiate between "The Watcher connection has gone down"
* (returning None) and "The Watcher has nothing to tell us right now"
* (returning the last known state).
*)
type state =
| Unknown of Buffered_line_reader.t
| Mid_update of Buffered_line_reader.t
(* Settled message has been read. No further reads from
* the File Descriptor are done (the FD is actually dropped entirely). *)
| Settled
(* Connection to the Watcher has failed. Cannot read further updates. *)
| Failed
type t_ = { state: state ref }
type t = t_ option
let ignore_unix_error f x =
try f x with
| Unix.Unix_error _ -> ()
let init root =
let socket_file = Config.socket_file root in
let sock_path = Socket.get_path socket_file in
(* Copied wholesale from MonitorConnection *)
let sockaddr =
if Sys.win32 then (
let ic = In_channel.create ~binary:true sock_path in
let port = Option.value_exn (In_channel.input_binary_int ic) in
In_channel.close ic;
Unix.(ADDR_INET (inet_addr_loopback, port))
) else
Unix.ADDR_UNIX sock_path
in
try
let (tic, _) = Timeout.open_connection sockaddr in
let reader =
Buffered_line_reader.create @@ Timeout.descr_of_in_channel @@ tic
in
Some { state = ref @@ Unknown reader }
with
| Unix.Unix_error (Unix.ENOENT, _, _) -> None
| Unix.Unix_error (Unix.ECONNREFUSED, _, _) -> None
let get_status_ instance =
match !(instance.state) with
| Failed -> None
| Settled -> Some Responses.Settled
| Mid_update reader
| Unknown reader
when Buffered_line_reader.is_readable reader -> begin
try
let msg = Buffered_line_reader.get_next_line reader in
let msg = Responses.of_string msg in
let response =
match msg with
| Responses.Unknown -> Responses.Unknown
| Responses.Mid_update ->
instance.state := Mid_update reader;
Responses.Mid_update
| Responses.Settled ->
instance.state := Settled;
ignore_unix_error Unix.close @@ Buffered_line_reader.get_fd reader;
Responses.Settled
in
Some response
with
| Unix.Unix_error (Unix.EPIPE, _, _)
| End_of_file ->
instance.state := Failed;
None
end
| Mid_update _ -> Some Responses.Mid_update
| Unknown _ -> Some Responses.Unknown
module Mocking = struct
exception Cannot_set_when_mocks_disabled
let get_status_returns _ = raise Cannot_set_when_mocks_disabled
end
let get_status t =
let ( >>= ) = Option.( >>= ) in
t >>= get_status_
end
module Client_mock = struct
type t = string option
module Mocking = struct
let status = ref None
let get_status_returns v = status := v
end
let init _ = None
let get_status _ = !Mocking.status
end
include
(val if Injector_config.use_test_stubbing then
(module Client_mock : WatchmanEventWatcherClient_sig.S)
else
(module Client_actual : WatchmanEventWatcherClient_sig.S)) |
OCaml | hhvm/hphp/hack/src/watchman_event_watcher/watchmanEventWatcherClient_sig.ml | (*
* Copyright (c) 2017, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(**
* A client to get the repo state from an already-running
* server watching a repo.
*
* Since the server sends at most 3 messages to connected clients, this client
* reads at most 3 messages (unknown, mid_update, settled).
* After reading the "settled" message, future calls to issettled
* return true immediately.
*)
module Abstract_types = struct
type t
end
module type S = sig
include module type of Abstract_types
(**
* Initiates a client.
*
* Connects to the Watcher that's watching the repo at this path.
*
* If a connection cannot be made to a Watcher, returns None.
*)
val init : Path.t -> t
(**
* Non-blocking poll on the connection - returns true if the Watcher reports
* settled state, or we have previously already read the settled message.
*
* If Watchman Event Watcher connection fails, None is returned.
*)
val get_status : t -> WatchmanEventWatcherConfig.Responses.t option
module Mocking : sig
val get_status_returns :
WatchmanEventWatcherConfig.Responses.t option -> unit
end
end |
OCaml | hhvm/hphp/hack/src/watchman_event_watcher/watchmanEventWatcherConfig.ml | let lock root = ServerFiles.path_of_root root "watchman_event_watcher_lock"
let log_link root = ServerFiles.path_of_root root "watchman_event_watcher_log"
let socket_file root =
ServerFiles.path_of_root root "watchman_event_watcher_sock"
module Responses = struct
let unknown_str = "unknown"
let mid_update_str = "mid_update"
let settled_str = "settled"
exception Invalid_response
type t =
| Unknown
| Mid_update
| Settled
let to_string = function
| Unknown -> unknown_str
| Mid_update -> mid_update_str
| Settled -> settled_str
let of_string s =
match s with
| str when String.equal str unknown_str -> Unknown
| str when String.equal str mid_update_str -> Mid_update
| str when String.equal str settled_str -> Settled
| _ -> raise Invalid_response
end |
hhvm/hphp/hack/test/.gitignore | *.diff
*.format_out
*.out
*.decl_out
*.direct_decl_out
*.reparse_out
*.tast_typecheck_out
*.type_check_out
*.php.pess
hhi/pessimised_hhi
*.hhvm_out
*.round_trip.hhas
*.hhcodegen_messages
*.hhcodegen_output.hhas
*.semdiff
*.semdiff_messages
*.hhcodegen_config.json
*.debug_out
*.type_check_raised_out
oUnit-*.cache |
|
hhvm/hphp/hack/test/dune | (env
(_
(flags
(:standard -w @a-3-4-29-32-34-35-37-41-42-44-45-48-50-60-70 \ -strict-sequence)))) |
|
Python | hhvm/hphp/hack/test/parse_errors.py | #!/usr/bin/env python3
# pyre-strict
import re
from dataclasses import dataclass
from typing import IO, List, Tuple
@dataclass
class ErrorCode:
type: str
code: int
@dataclass
class Position:
fileName: str
line: int
startColumn: int
endColumn: int
@dataclass
class PositionedMessage:
position: Position
message: str
@dataclass
class Error:
code: ErrorCode
message: PositionedMessage
reason: List[PositionedMessage]
class ParseException(Exception):
pass
def make_error(
errorCode: ErrorCode,
position: Position,
message: str,
reasons: List[PositionedMessage],
) -> Error:
return Error(errorCode, PositionedMessage(position, message), reasons)
def end_of_file(line: str) -> bool:
return line == "" or line == "\n"
def parse_errors(output_file_name: str) -> List[Error]:
with open(output_file_name) as output_file:
try:
return parse_error(output_file, True)
except ParseException:
try:
return parse_error(output_file, False)
except ParseException as ex:
raise ParseException(f"at file {output_file_name}: {ex}")
def same_error(line: str, multiple_error_file: bool) -> bool:
if multiple_error_file:
return starts_with_space(line)
else:
return not end_of_file(line)
# parse a "plain" formatted error. The expected format is emittted by
# Errors.to_string (OCaml) or Error::display_plain() (Rust).
def parse_error(output_file: IO[str], multiple_error_file: bool) -> List[Error]:
errors = []
line = output_file.readline()
while not end_of_file(line):
if line == "No errors\n":
return []
position = parse_position(line)
line = output_file.readline()
if starts_with_space(line):
# this is part of an hh_show, so ignore and continue
while starts_with_space(line):
line = output_file.readline()
continue
(message, errorCode) = parse_message_and_code(output_file, line)
line = output_file.readline()
reasons = []
while same_error(line, multiple_error_file):
reasonPos = parse_position(line)
line = output_file.readline()
(line, reasonMessage) = parse_message(output_file, line)
reason = PositionedMessage(reasonPos, reasonMessage)
reasons.append(reason)
errors.append(make_error(errorCode, position, message, reasons))
return errors
position_regex = r'^\s*File "(.*)", line (\d+), characters (\d+)-(\d+):(\[\d+\])?\n'
def parse_position(line: str) -> Position:
match = re.match(position_regex, line)
if match is None:
raise ParseException(f"Could not parse position line: {line}")
file = match.group(1)
lineNum = int(match.group(2))
startCol = int(match.group(3))
endCol = int(match.group(4))
return Position(file, lineNum, startCol, endCol)
def parse_message_and_code(file: IO[str], line: str) -> Tuple[str, ErrorCode]:
message_chunks = []
message_and_code_regex = r"^\s*(.*) \((.*)\[(\d+)\]\)\n"
match = re.match(message_and_code_regex, line)
while match is None:
match = re.match(r"^\s*(.*)\n", line)
if match is None:
raise ParseException(f"Could not parse message line: {line}")
message_line = match.group(1)
message_chunks.append(message_line)
line = file.readline()
match = re.match(message_and_code_regex, line)
assert match is not None, "should have raised exception above"
message_line = match.group(1)
type = match.group(2)
code = int(match.group(3))
message_chunks.append(message_line)
message = "".join(message_chunks)
return (message, ErrorCode(type, code))
def parse_message(file: IO[str], line: str) -> Tuple[str, str]:
message_chunks = []
message_regex = r"^\s*(.*)\n"
match = re.match(message_regex, line)
if match is None:
raise ParseException(f"Could not parse message line: {line}")
message_line = match.group(1)
message_chunks.append(message_line)
line = file.readline()
match = re.match(position_regex, line)
while match is None and not end_of_file(line):
match = re.match(message_regex, line)
if match is None:
raise ParseException(f"Could not parse message line: {line}")
message_line = match.group(1)
message_chunks.append(message_line)
line = file.readline()
match = re.match(position_regex, line)
message = "".join(message_chunks)
return (line, message)
def starts_with_space(s: str) -> bool:
return re.match(r"^\s", s) is not None
def sprint_error(error: Error) -> str:
file = error.message.position.fileName
line = error.message.position.line
startCol = error.message.position.startColumn
endCol = error.message.position.endColumn
message = error.message.message
type = error.code.type
code = error.code.code
out = [
f"\033[91m{file}:{line}:{startCol},{endCol}:\033[0m "
f"{message} ({type}[{code}])\n"
]
for reason in error.reason:
file = reason.position.fileName
line = reason.position.line
startCol = reason.position.startColumn
endCol = reason.position.endColumn
message = reason.message
out.append(f" \033[91m{file}:{line}:{startCol},{endCol}:\033[0m {message}\n")
return "".join(out)
def sprint_errors(errors: List[Error]) -> str:
if not errors:
return "No errors\n"
out = []
for error in errors:
out.append(sprint_error(error))
return "".join(out) |
Python | hhvm/hphp/hack/test/pessimise_and_single_type_check.py | #!/usr/bin/env python3
# pyre-strict
import os
import shutil
import subprocess
import sys
from typing import List
def arg_extract(args: List[str], arg: str) -> str:
index = args.index(arg)
value = args.pop(index + 1)
del args[index]
return value
if __name__ == "__main__":
# Parsing the arguments is not straightforward as pessimise_and_single_type_check
# must be aware of all the arguments supported by hh_single_type_check, but we do
# not want to duplicate the list here (which is long and moving fast).
# We thus use the following ad-hoc strategy:
#
# 1. extract the paths to hh_stc, hh_pessimisation, pessimised_hhi from the arguments
# 2. delete the binary name
# 3. extract all the *.php strings, assuming these are the files being tested
# 4. the remaining arguments are the flags to be passed to hh_single_type_checks
arguments: List[str] = sys.argv
hh_stc_path: str = arg_extract(arguments, "--hh-stc-path")
hh_pessimisation_path: str = arg_extract(arguments, "--hh-pessimisation-path")
pessimised_hhi_path: str = arg_extract(arguments, "--pessimised-hhi-path")
del arguments[0]
hh_stc_arguments: List[str] = []
files: List[str] = []
for a in arguments:
if a.endswith(".php"):
files.append(a)
else:
hh_stc_arguments.append(a)
# invoke hh_pessimise on the all the current tests (say foo.php)
for file in files:
cmd: List[str] = [
hh_pessimisation_path,
"--file=" + file,
"--update",
"--enable-multifile-support",
]
subprocess.run(cmd)
# identify the extra builtins used
extra_builtins: List[str] = []
while True:
try:
extra_builtins.append(arg_extract(hh_stc_arguments, "--extra-builtin"))
except ValueError:
break
# pessimise the extra builtins and build the cli options
# - if extra_builtin refer to <path>/<file>, the pessimised extra builtin is
# generated inside <path>/pessimised_hhi_<PID>/<file>
# - the <PID> is required to avoid a race condition when multiple instances of
# this script are invoked concurrently by buck
# - the <path>/pessimised_hhi_<PID>/ directories are deleted at the end of the script
extra_builtins_opts: List[str] = []
pessimised_extra_builtins_dirs: List[str] = []
for file in extra_builtins:
(file_dir, file_name) = os.path.split(file)
output_file = file + ".pess"
unique_pessimised_file_dir = os.path.join(
file_dir, "pessimised_hhi_" + str(os.getpid())
)
os.makedirs(unique_pessimised_file_dir, exist_ok=True)
pessimised_file = os.path.join(unique_pessimised_file_dir, file_name)
if not (os.path.exists(pessimised_file)):
cmd: List[str] = [
hh_pessimisation_path,
"--file",
file,
"--output-file",
pessimised_file,
]
subprocess.run(cmd)
extra_builtins_opts.append("--extra-builtin")
extra_builtins_opts.append(pessimised_file)
pessimised_extra_builtins_dirs.append(unique_pessimised_file_dir)
# pessimised tests have extension file+".pess"
# invoke hh_single_type_check on the pessimised tests
pessimised_files: List[str] = [file + ".pess" for file in files]
cmd: List[str] = (
[hh_stc_path]
+ hh_stc_arguments
+ extra_builtins_opts
+ [
"--enable-sound-dynamic-type",
"--like-type-hints",
"--config",
"pessimise_builtins=true",
]
+ ["--custom-hhi-path", pessimised_hhi_path]
+ pessimised_files
)
subprocess.run(cmd)
# delete the temporary directories where extra builtins files have been pessimised
for dir in pessimised_extra_builtins_dirs:
shutil.rmtree(dir)
# Remark: in batch-mode the out files will have extension ".pess.out"
# instead of ".out" |
Python | hhvm/hphp/hack/test/pessimise_targeted_and_single_type_check.py | #!/usr/bin/env python3
# pyre-strict
import io
import os
import subprocess
import sys
from typing import List
def arg_extract(args: List[str], arg: str) -> str:
index = args.index(arg)
value = args.pop(index + 1)
del args[index]
return value
if __name__ == "__main__":
# Parsing the arguments is not straightforward as pessimise_and_single_type_check
# must be aware of all the arguments supported by hh_single_type_check, but we do
# not want to duplicate the list here (which is long and moving fast).
# We thus use the following ad-hoc strategy:
#
# 1. extract the paths to hh_stc, hh_pessimisation, pessimised_hhi from the arguments
# 2. delete the binary name
# 3. extract all the *.php strings, assuming these are the files being tested
# 4. the remaining arguments are the flags to be passed to hh_single_type_checks
arguments: List[str] = sys.argv
hh_stc_path: str = arg_extract(arguments, "--hh-stc-path")
hh_pessimisation_path: str = arg_extract(arguments, "--hh-pessimisation-path")
pessimised_hhi_path: str = arg_extract(arguments, "--pessimised-hhi-path")
del arguments[0]
hh_stc_arguments: List[str] = []
files: List[str] = []
for a in arguments:
if a.endswith(".php"):
files.append(a)
else:
hh_stc_arguments.append(a)
# pessimise all the current tests
# 1. run hh_single_type_check to collect pessimisation targets
cmd: List[str] = (
[hh_stc_path]
+ hh_stc_arguments
+ ["--hh-log-level", "pessimise", "1"]
+ ["--config", "like_casts=true"]
+ ["--error-format", "plain"]
+ files
)
subprocess.call(cmd)
for file in files:
# 2. run targeted hh_pessimisation on each file
cmd: List[str] = [
hh_pessimisation_path,
"--file=" + file,
"--update",
"--forward",
"--pessimisation-targets=" + file + ".out",
"--enable-multifile-support",
]
subprocess.run(cmd)
# identify the extra builtins used
extra_builtins: List[str] = []
while True:
try:
extra_builtins.append(arg_extract(hh_stc_arguments, "--extra-builtin"))
except ValueError:
break
# pessimise the extra builtins and build the cli options
# - if extra_builtin refer to <path>/<file>, the pessimised extra builtin is
# generated inside <path>/pessimised_hhi/<file>
# - to avoid a race condition, the hhi is first pessimised into <file>.pess.<PID>,
# and then moved to <path>/pessimised_hhi/<file>
extra_builtins_opts: List[str] = []
for file in extra_builtins:
(file_dir, file_name) = os.path.split(file)
unique_output_file = file + ".pess." + str(os.getpid())
pessimised_file_dir = os.path.join(file_dir, "pessimised_hhi")
pessimised_file = os.path.join(pessimised_file_dir, file_name)
if not (os.path.exists(pessimised_file)):
cmd: List[str] = [
hh_pessimisation_path,
"--file",
file,
"--forward",
"--output-file",
unique_output_file,
]
subprocess.run(cmd)
os.makedirs(pessimised_file_dir, exist_ok=True)
# this is expected to be atomic
os.rename(unique_output_file, pessimised_file)
extra_builtins_opts.append("--extra-builtin")
extra_builtins_opts.append(pessimised_file)
# pessimised tests have extension file+".pess"
# invoke hh_single_type_check on the pessimised tests
pessimised_files: List[str] = list(map(lambda file: file + ".pess", files))
cmd: List[str] = (
[hh_stc_path]
+ ["--batch-files"]
+ hh_stc_arguments
+ extra_builtins_opts
+ ["--enable-sound-dynamic-type", "--like-type-hints"]
+ ["--custom-hhi-path", pessimised_hhi_path]
+ pessimised_files
)
subprocess.run(cmd)
# Remark: in batch-mode the out files will have extension ".pess.out"
# instead of ".out" |
Shell Script | hhvm/hphp/hack/test/review.sh | #! /usr/bin/env bash
# Usage: First do 'make -C ../src test' to generate the .out files. If there are
# failures, their test filenames will be printed to stdout. Pass these as
# arguments to this script.
# note: we don't use [ -z $FOO ] to check if FOO is unset because that is also
# true if FOO=""
if [ -z "${OUT_EXT+x}" ]; then
OUT_EXT=".out"
fi
if [ -z "${EXP_EXT+x}" ]; then
EXP_EXT=".exp"
fi
if [ -z "${UPDATE+x}" ]; then
# "always", "prompt" or "never"
UPDATE=prompt
fi
ARROW="$(tput bold)$(tput setaf 6)==>$(tput setaf 7)"
function reconstitute_full_path {
TEST_PATH=$1
ROOT=$2
if [ -n "${ROOT}" ]; then
if [[ "$TEST_PATH" = "$SOURCE_ROOT"* ]]; then
FULL_PATH="${ROOT}${TEST_PATH#"${SOURCE_ROOT}"}"
elif [[ "$TEST_PATH" = ./hphp/hack/* ]]; then
FULL_PATH="${ROOT}/${TEST_PATH#"./hphp/hack/"}"
elif [[ "$TEST_PATH" = hphp/hack/* ]]; then
FULL_PATH="${ROOT}/${TEST_PATH#"hphp/hack/"}"
fi
fi
echo "$FULL_PATH"
}
for f in "$@"; do
echo "$ARROW $f $(tput sgr0)"
# `-b a` means to number all lines; this is the same as
# --body-numbering=a, but works with both BSD and GNU `nl`
nl -b a "$(reconstitute_full_path "$f" "$SOURCE_ROOT")"
echo
if [ "$VERIFY_PESSIMISATION" = true ]; then
NAME_PESS=$f".pess"
NAME_PESS_FULL_PATH="$(reconstitute_full_path "$NAME_PESS" "$SOURCE_ROOT")"
if [ -f "$NAME_PESS_FULL_PATH" ]; then
echo "$(tput setaf 6)[pessimised into]$(tput setaf 7)$ARROW $NAME_PESS $(tput sgr0)"
nl -b a "$NAME_PESS_FULL_PATH"
fi
fi
OUT_BASE=$(reconstitute_full_path "$f" "$OUTPUT_ROOT")
EXP_BASE=$(reconstitute_full_path "$f" "$SOURCE_ROOT")
if [ -e "$OUT_BASE$OUT_EXT" ]; then
OUT="$OUT_BASE$OUT_EXT"
elif [ "$VERIFY_PESSIMISATION" = true ] && [ -e "$OUT_BASE.pess$OUT_EXT" ]; then
OUT="$OUT_BASE.pess$OUT_EXT"
else
OUT=/dev/null
fi
EXP_TO="$EXP_BASE$EXP_EXT"
if [ -e "$EXP_BASE$EXP_EXT" ]; then
EXP="$EXP_BASE$EXP_EXT"
elif [ -n "${FALLBACK_EXP_EXT+x}" ] && [ -e "$EXP_BASE$FALLBACK_EXP_EXT" ]; then
EXP="$EXP_BASE$FALLBACK_EXP_EXT"
else
EXP=/dev/null
fi
echo "$ARROW Diff between $EXP and $(basename "$OUT") $(tput sgr0)"
# Use git diff to give us color and word diffs. The patience algorithm
# produces more readable diffs in some situations.
#
# --no-index makes us ignore the git repo, if any - otherwise this only
# works in hg checkouts (i.e. fbcode)
git --no-pager diff --no-index --diff-algorithm=histogram --color=always \
--word-diff=color --word-diff-regex='[^[:space:]]+' \
$EXP "$OUT" | tail -n +5
echo
if [ "$UPDATE" = always ]; then
# UPDATE=always updates all the .exp files without prompting.
cp "$OUT" "$EXP_TO"
elif [ "$UPDATE" = never ]; then
# UPDATE=never allows users to see a diff of each .exp file with .out.
if [ "$TERM" = "dumb" ]; then
read -r -p "$(tput bold)View next file? [Y/q] $(tput sgr0)"
else
read -p "$(tput bold)View next file? [Y/q] $(tput sgr0)" -n 1 -r
fi
if [ "$REPLY" = "q" ]; then
exit 0
fi
else
# UPDATE=prompt allows users to see a diff of each .exp with
# .out, then prompts to replace the .exp file.
if [ "$TERM" = "dumb" ]; then
read -r -p "$(tput bold)Copy output to expected output? [y/q/N] $(tput sgr0)"
else
read -p "$(tput bold)Copy output to expected output? [y/q/N] $(tput sgr0)" -n 1 -r
fi
if [ "$REPLY" = "y" ]; then
cp "$OUT" "$EXP_TO"
elif [ "$REPLY" = "q" ]; then
exit 0
fi
fi
# A single blank line between loop iterations, even if the user hit enter.
if [[ "$REPLY" =~ [a-zA-Z] ]]; then
echo
fi
done |
Python | hhvm/hphp/hack/test/verify.py | #!/usr/bin/env python3
# pyre-strict
import argparse
import difflib
import os
import os.path
import re
import shlex
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from enum import Enum
from typing import Callable, Dict, List, Optional, Tuple
from hphp.hack.test.parse_errors import Error, parse_errors, sprint_errors
DEFAULT_OUT_EXT = ".out"
DEFAULT_EXP_EXT = ".exp"
flags_pessimise_unsupported = [
"--complex-coercion",
"--enable-higher-kinded-types",
"--enable-class-level-where-clauses",
"--enable-global-access-check",
]
max_workers = 48
verbose = False
dump_on_failure = False
batch_size = 500
@dataclass
class TestCase:
file_path: str
input: Optional[str]
expected: str
@dataclass
class Result:
test_case: TestCase
output: str
is_failure: bool
class VerifyPessimisationOptions(Enum):
no = "no"
all = "all"
added = "added"
removed = "removed"
full = "full"
def __str__(self) -> str:
return self.value
"""
Per-test flags passed to test executable. Expected to be in a file with
same name as test, but with .flags extension.
"""
def compare_errors_by_line_no(
errors_exp: List[Error], errors_out: List[Error]
) -> Tuple[List[Error], List[Error]]:
i_out = 0
i_exp = 0
len_out = len(errors_out)
len_exp = len(errors_exp)
errors_in_out_not_in_exp = []
errors_in_exp_not_in_out = []
while i_out < len_out and i_exp < len_exp:
err_out = errors_out[i_out]
err_exp = errors_exp[i_exp]
l_out = err_out.message.position.line
l_exp = err_exp.message.position.line
if l_out < l_exp:
errors_in_out_not_in_exp.append(err_out)
i_out += 1
elif l_exp < l_out:
errors_in_exp_not_in_out.append(err_exp)
i_exp += 1
else:
i_out += 1
i_exp += 1
if i_out >= len_out:
for i in range(i_exp, len_exp):
errors_in_exp_not_in_out.append(errors_exp[i])
elif i_exp >= len_exp:
for i in range(i_out, len_out):
errors_in_out_not_in_exp.append(errors_out[i])
return (errors_in_exp_not_in_out, errors_in_out_not_in_exp)
def compare_output_files_error_lines_only(
file_out: str, file_exp: str
) -> Tuple[bool, str]:
out = ""
failed = False
try:
errors_out = parse_errors(file_out)
errors_exp = parse_errors(file_exp)
(
errors_in_exp_not_in_out,
errors_in_out_not_in_exp,
) = compare_errors_by_line_no(errors_out=errors_out, errors_exp=errors_exp)
failed = bool(errors_in_exp_not_in_out) or bool(errors_in_out_not_in_exp)
if errors_in_exp_not_in_out:
out += f"""\033[93mExpected errors which were not produced:\033[0m
{sprint_errors(errors_in_exp_not_in_out)}
"""
if errors_in_out_not_in_exp:
out += f"""\033[93mProduced errors which were not expected:\033[0m
{sprint_errors(errors_in_out_not_in_exp)}
"""
except IOError as e:
out = f"Warning: {e}"
return (failed, out)
def check_output_error_lines_only(
test: str, out_ext: str = DEFAULT_OUT_EXT, exp_ext: str = DEFAULT_EXP_EXT
) -> Tuple[bool, str]:
file_out = test + out_ext
file_exp = test + exp_ext
return compare_output_files_error_lines_only(file_out=file_out, file_exp=file_exp)
def get_test_flags(path: str) -> List[str]:
prefix, _ext = os.path.splitext(path)
path = prefix + ".flags"
if not os.path.isfile(path):
return []
with open(path) as file:
return shlex.split(file.read().strip())
def check_output(
case: TestCase,
out_extension: str,
default_expect_regex: Optional[str],
ignore_error_text: bool,
only_compare_error_lines: bool,
verify_pessimisation: VerifyPessimisationOptions,
check_expected_included_in_actual: bool,
) -> Result:
if only_compare_error_lines:
(failed, out) = check_output_error_lines_only(case.file_path)
return Result(test_case=case, output=out, is_failure=failed)
else:
out_path = (
case.file_path + out_extension
if verify_pessimisation == VerifyPessimisationOptions.no
or verify_pessimisation == VerifyPessimisationOptions.full
or out_extension == ".pess.out"
else case.file_path + ".pess" + out_extension
)
try:
with open(out_path, "r") as f:
output: str = f.read()
except FileNotFoundError:
out_path = os.path.realpath(out_path)
output = "Output file " + out_path + " was not found!"
return check_result(
case,
default_expect_regex,
ignore_error_text,
verify_pessimisation,
check_expected_included_in_actual=check_expected_included_in_actual,
out=output,
)
def debug_cmd(cwd: str, cmd: List[str]) -> None:
if verbose:
print("From directory", os.path.realpath(cwd))
print("Executing", " ".join(cmd))
print()
def run_batch_tests(
test_cases: List[TestCase],
program: str,
default_expect_regex: Optional[str],
ignore_error_text: bool,
no_stderr: bool,
force_color: bool,
mode_flag: List[str],
get_flags: Callable[[str], List[str]],
out_extension: str,
verify_pessimisation: VerifyPessimisationOptions,
check_expected_included_in_actual: bool,
only_compare_error_lines: bool = False,
) -> List[Result]:
"""
Run the program with batches of files and return a list of results.
"""
# Each directory needs to be in a separate batch because flags are different
# for each directory.
# Compile a list of directories to test cases, and then
dirs_to_files: Dict[str, List[TestCase]] = {}
for case in test_cases:
test_dir = os.path.dirname(case.file_path)
dirs_to_files.setdefault(test_dir, []).append(case)
# run a list of test cases.
# The contract here is that the program will write to
# filename.out_extension for each file, and we read that
# for the output.
# Remark: if verify_pessimisation is set, then the result
# is in filename.pess.out_extension.
def run(test_cases: List[TestCase]) -> List[Result]:
if not test_cases:
raise AssertionError()
first_test = test_cases[0]
test_dir = os.path.dirname(first_test.file_path)
flags = get_flags(test_dir)
test_flags = get_test_flags(first_test.file_path)
if verify_pessimisation != VerifyPessimisationOptions.no:
path = os.path.join(test_dir, "NO_PESS")
if os.path.isfile(path):
return []
for flag in flags_pessimise_unsupported:
if flag in flags:
return []
cmd = [program]
cmd += mode_flag
cmd += ["--batch-files", "--out-extension", out_extension]
cmd += flags + test_flags
cmd += [os.path.basename(case.file_path) for case in test_cases]
debug_cmd(test_dir, cmd)
env = os.environ.copy()
env["FORCE_ERROR_COLOR"] = "true" if force_color else "false"
try:
return_code = subprocess.call(
cmd,
stderr=None if no_stderr else subprocess.STDOUT,
cwd=test_dir,
universal_newlines=True,
env=env,
)
except subprocess.CalledProcessError:
# we don't care about nonzero exit codes... for instance, type
# errors cause hh_single_type_check to produce them
return_code = None
if return_code == -11:
print(
"Segmentation fault while running the following command "
+ "from directory "
+ os.path.realpath(test_dir)
)
print(" ".join(cmd))
print()
results = []
for case in test_cases:
result = check_output(
case,
out_extension=out_extension,
default_expect_regex=default_expect_regex,
ignore_error_text=ignore_error_text,
only_compare_error_lines=only_compare_error_lines,
verify_pessimisation=verify_pessimisation,
check_expected_included_in_actual=check_expected_included_in_actual,
)
results.append(result)
return results
# Create a list of batched cases.
all_batched_cases: List[List[TestCase]] = []
# For each directory, we split all the test cases
# into chunks of batch_size. Then each of these lists
# is a separate job for each thread in the threadpool.
for cases in dirs_to_files.values():
batched_cases: List[List[TestCase]] = [
cases[i : i + batch_size] for i in range(0, len(cases), batch_size)
]
all_batched_cases += batched_cases
executor = ThreadPoolExecutor(max_workers=max_workers)
futures = [executor.submit(run, test_batch) for test_batch in all_batched_cases]
results = [future.result() for future in futures]
# Flatten the list
return [item for sublist in results for item in sublist]
def run_test_program(
test_cases: List[TestCase],
program: str,
default_expect_regex: Optional[str],
ignore_error_text: bool,
no_stderr: bool,
force_color: bool,
mode_flag: List[str],
get_flags: Callable[[str], List[str]],
verify_pessimisation: VerifyPessimisationOptions,
check_expected_included_in_actual: bool,
timeout: Optional[float] = None,
) -> List[Result]:
"""
Run the program and return a list of results.
"""
def run(test_case: TestCase) -> Result:
test_dir, test_name = os.path.split(test_case.file_path)
flags = get_flags(test_dir)
test_flags = get_test_flags(test_case.file_path)
cmd = [program]
cmd += mode_flag
if test_case.input is None:
cmd.append(test_name)
cmd += flags + test_flags
debug_cmd(test_dir, cmd)
env = os.environ.copy()
env["FORCE_ERROR_COLOR"] = "true" if force_color else "false"
try:
output = subprocess.check_output(
cmd,
stderr=None if no_stderr else subprocess.STDOUT,
cwd=test_dir,
universal_newlines=True,
input=test_case.input,
timeout=timeout,
errors="replace",
env=env,
)
except subprocess.TimeoutExpired as e:
output = "Timed out. " + str(e.output)
except subprocess.CalledProcessError as e:
if e.returncode == 126:
# unable to execute, typically due in buck2 to "Text file is busy" because someone still has a write handle open to it.
# https://www.internalfb.com/intern/qa/312685/text-file-is-busy---test-is-run-before-fclose-on-e
# Ugly workaround for now: just skip it
# This should be removed once T107518211 is closed.
output = "Timed out. " + str(e.output)
else:
# we don't care about nonzero exit codes... for instance, type
# errors cause hh_single_type_check to produce them
output = str(e.output)
return check_result(
test_case,
default_expect_regex,
ignore_error_text,
verify_pessimisation,
check_expected_included_in_actual=check_expected_included_in_actual,
out=output,
)
executor = ThreadPoolExecutor(max_workers=max_workers)
futures = [executor.submit(run, test_case) for test_case in test_cases]
return [future.result() for future in futures]
def filter_ocaml_stacktrace(text: str) -> str:
"""take a string and remove all the lines that look like
they're part of an OCaml stacktrace"""
assert isinstance(text, str)
it = text.splitlines()
out = []
for x in it:
drop_line = x.lstrip().startswith("Called") or x.lstrip().startswith("Raised")
if drop_line:
pass
else:
out.append(x)
return "\n".join(out)
def filter_temp_hhi_path(text: str) -> str:
"""The .hhi files are stored in a temporary directory whose name
changes every time. Normalise it.
/tmp/ASjh5RoWbb/builtins_fb.hhi -> /tmp/hhi_dir/builtins_fb.hhi
"""
return re.sub(
r"/tmp/[^/]*/([a-zA-Z0-9_]+\.hhi)",
"/tmp/hhi_dir/\\1",
text,
)
def strip_pess_suffix(text: str) -> str:
return re.sub(
r"_pess.php",
".php",
text,
)
def compare_expected(
expected: str, out: str, verify_pessimisation: VerifyPessimisationOptions
) -> bool:
if (
verify_pessimisation == VerifyPessimisationOptions.no
or verify_pessimisation == VerifyPessimisationOptions.all
or verify_pessimisation == VerifyPessimisationOptions.full
):
if expected == "No errors" or out == "No errors":
return expected == out
else:
return True
elif verify_pessimisation == VerifyPessimisationOptions.added:
return not (expected == "No errors" and out != "No errors")
elif verify_pessimisation == VerifyPessimisationOptions.removed:
return not (expected != "No errors" and out == "No errors")
else:
raise Exception(
"Cannot happen: verify_pessimisation option %s" % verify_pessimisation
)
# Strip leading and trailing whitespace from every line
def strip_lines(text: str) -> str:
return "\n".join(line.strip() for line in text.splitlines())
def check_result(
test_case: TestCase,
default_expect_regex: Optional[str],
ignore_error_messages: bool,
verify_pessimisation: VerifyPessimisationOptions,
check_expected_included_in_actual: bool,
out: str,
) -> Result:
if check_expected_included_in_actual:
return check_included(test_case, out)
else:
return check_expected_equal_actual(
test_case,
default_expect_regex,
ignore_error_messages,
verify_pessimisation,
out,
)
def check_expected_equal_actual(
test_case: TestCase,
default_expect_regex: Optional[str],
ignore_error_messages: bool,
verify_pessimisation: VerifyPessimisationOptions,
out: str,
) -> Result:
"""
Check that the output of the test in :out corresponds to the expected
output, or if a :default_expect_regex is provided,
check that the output in :out contains the provided regex.
"""
expected = filter_temp_hhi_path(strip_lines(test_case.expected))
normalized_out = (
filter_temp_hhi_path(strip_lines(out))
if verify_pessimisation == "no"
else strip_pess_suffix(filter_temp_hhi_path(strip_lines(out)))
)
is_ok = (
expected == normalized_out
or (
(
ignore_error_messages
or verify_pessimisation != VerifyPessimisationOptions.no
and verify_pessimisation != VerifyPessimisationOptions.full
)
and compare_expected(expected, normalized_out, verify_pessimisation)
)
or expected == filter_ocaml_stacktrace(normalized_out)
or (
default_expect_regex is not None
and re.search(default_expect_regex, normalized_out) is not None
and expected == ""
)
)
return Result(test_case=test_case, output=out, is_failure=not is_ok)
def check_included(test_case: TestCase, output: str) -> Result:
elts = set(output.splitlines())
expected_elts = set(test_case.expected.splitlines())
is_failure = False
for expected_elt in expected_elts:
if expected_elt not in elts:
is_failure = True
break
output = ""
if is_failure:
for elt in expected_elts.intersection(elts):
output += elt + "\n"
return Result(test_case, output, is_failure)
def record_results(results: List[Result], out_ext: str) -> None:
for result in results:
outfile = result.test_case.file_path + out_ext
with open(outfile, "wb") as f:
f.write(bytes(result.output, "UTF-8"))
def find_in_ancestors_rec(dir: str, path: str) -> str:
if path == "" or os.path.dirname(path) == path:
raise Exception("Could not find directory %s in ancestors." % dir)
if os.path.basename(path) == dir:
return path
return find_in_ancestors_rec(dir, os.path.dirname(path))
def find_in_ancestors(dir: str, path: str) -> str:
try:
return find_in_ancestors_rec(dir, path)
except Exception:
raise Exception("Could not find directory %s in ancestors of %s." % (dir, path))
def get_exp_out_dirs(test_file: str) -> Tuple[str, str]:
if (
os.environ.get("HACK_BUILD_ROOT") is not None
and os.environ.get("HACK_SOURCE_ROOT") is not None
):
exp_dir = os.environ["HACK_SOURCE_ROOT"]
out_dir = os.environ["HACK_BUILD_ROOT"]
else:
fbcode = find_in_ancestors("fbcode", test_file)
exp_dir = os.path.join(fbcode, "hphp", "hack")
out_dir = os.path.dirname(find_in_ancestors("test", test_file))
return exp_dir, out_dir
def report_failures(
total: int,
failures: List[Result],
out_extension: str,
expect_extension: str,
fallback_expect_extension: Optional[str],
verify_pessimisation: VerifyPessimisationOptions = VerifyPessimisationOptions.no,
no_copy: bool = False,
only_compare_error_lines: bool = False,
) -> None:
if only_compare_error_lines:
for failure in failures:
print(f"\033[95m{failure.test_case.file_path}\033[0m")
print(failure.output)
print()
elif failures != []:
record_results(failures, out_extension)
if dump_on_failure:
dump_failures(failures)
fnames = [failure.test_case.file_path for failure in failures]
print("To review the failures, use the following command: ")
first_test_file = os.path.realpath(failures[0].test_case.file_path)
out_dir: str # for Pyre
(exp_dir, out_dir) = get_exp_out_dirs(first_test_file)
# Get a full path to 'review.sh' so this command be run
# regardless of your current directory.
review_script = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "review.sh"
)
if not os.path.isfile(review_script):
review_script = "./hphp/hack/test/review.sh"
def fname_map_var(f: str) -> str:
return "hphp/hack/" + os.path.relpath(f, out_dir)
env_vars = []
if out_extension != DEFAULT_OUT_EXT:
env_vars.append("OUT_EXT=%s" % out_extension)
if expect_extension != DEFAULT_EXP_EXT:
env_vars.append("EXP_EXT=%s" % expect_extension)
if fallback_expect_extension is not None:
env_vars.append("FALLBACK_EXP_EXT=%s " % fallback_expect_extension)
if verify_pessimisation != VerifyPessimisationOptions.no:
env_vars.append("VERIFY_PESSIMISATION=true")
if no_copy:
env_vars.append("UPDATE=never")
env_vars.extend(["SOURCE_ROOT=%s" % exp_dir, "OUTPUT_ROOT=%s" % out_dir])
print(
"%s %s %s"
% (
" ".join(env_vars),
review_script,
" ".join(map(fname_map_var, fnames)),
)
)
# If more than 75% of files have changed, we're probably doing
# a transformation to all the .exp files.
if len(fnames) >= (0.75 * total):
print(
"\nJust want to update all the %s files? Use UPDATE=always with the above command."
% expect_extension
)
def dump_failures(failures: List[Result]) -> None:
for f in failures:
expected = f.test_case.expected
actual = f.output
diff = difflib.ndiff(expected.splitlines(True), actual.splitlines(True))
print("Details for the failed test %s:" % f.test_case.file_path)
print("\n>>>>> Expected output >>>>>>\n")
print(expected)
print("\n===== Actual output ======\n")
print(actual)
print("\n<<<<< End Actual output <<<<<<<\n")
print("\n>>>>> Diff >>>>>>>\n")
print("".join(diff))
print("\n<<<<< End Diff <<<<<<<\n")
def get_hh_flags(test_dir: str) -> List[str]:
path = os.path.join(test_dir, "HH_FLAGS")
if not os.path.isfile(path):
if verbose:
print("No HH_FLAGS file found")
return []
with open(path) as f:
return shlex.split(f.read())
def files_with_ext(files: List[str], ext: str) -> List[str]:
"""
Returns the set of filenames in :files that end in :ext
"""
filtered_files: List[str] = []
for file in files:
prefix, suffix = os.path.splitext(file)
if suffix == ext:
filtered_files.append(prefix)
return filtered_files
def list_test_files(
root: str, disabled_ext: str, test_ext: str, include_directories: bool
) -> List[str]:
if os.path.isfile(root):
if root.endswith(test_ext):
return [root]
else:
return []
elif os.path.isdir(root):
result: List[str] = []
if include_directories and root.endswith(test_ext):
result.append(root)
children = os.listdir(root)
disabled = files_with_ext(children, disabled_ext)
for child in children:
if child != "disabled" and child not in disabled:
result.extend(
list_test_files(
os.path.join(root, child),
disabled_ext,
test_ext,
include_directories,
)
)
return result
elif os.path.islink(root):
# Some editors create broken symlinks as part of their locking scheme,
# so ignore those.
return []
else:
raise Exception("Could not find test file or directory at %s" % root)
def get_content_(file_path: str, ext: str) -> str:
with open(file_path + ext, "r") as fexp:
return fexp.read()
def get_content(
file_path: str, ext: str = "", fallback_ext: Optional[str] = None
) -> str:
try:
return get_content_(file_path, ext)
except FileNotFoundError:
if fallback_ext is not None:
try:
return get_content_(file_path, fallback_ext)
except FileNotFoundError:
return ""
else:
return ""
def run_tests(
files: List[str],
expected_extension: str,
fallback_expect_extension: Optional[str],
out_extension: str,
use_stdin: str,
program: str,
default_expect_regex: Optional[str],
batch_mode: str,
ignore_error_text: bool,
no_stderr: bool,
force_color: bool,
verify_pessimisation: VerifyPessimisationOptions,
mode_flag: List[str],
get_flags: Callable[[str], List[str]],
check_expected_included_in_actual: bool,
timeout: Optional[float] = None,
only_compare_error_lines: bool = False,
) -> List[Result]:
# for each file, create a test case
test_cases = [
TestCase(
file_path=file,
expected=get_content(file, expected_extension, fallback_expect_extension),
input=get_content(file) if use_stdin else None,
)
for file in files
]
if batch_mode:
results = run_batch_tests(
test_cases,
program,
default_expect_regex,
ignore_error_text,
no_stderr,
force_color,
mode_flag,
get_flags,
out_extension,
verify_pessimisation,
check_expected_included_in_actual,
only_compare_error_lines,
)
else:
results = run_test_program(
test_cases,
program,
default_expect_regex,
ignore_error_text,
no_stderr,
force_color,
mode_flag,
get_flags,
verify_pessimisation,
check_expected_included_in_actual=check_expected_included_in_actual,
timeout=timeout,
)
failures = [result for result in results if result.is_failure]
num_results = len(results)
if failures == []:
print(
"All tests in the suite passed! "
"The number of tests that ran: %d\n" % num_results
)
else:
print("The number of tests that failed: %d/%d\n" % (len(failures), num_results))
report_failures(
num_results,
failures,
args.out_extension,
args.expect_extension,
args.fallback_expect_extension,
verify_pessimisation=verify_pessimisation,
only_compare_error_lines=only_compare_error_lines,
)
sys.exit(1) # this exit code fails the suite and lets Buck know
return results
def run_idempotence_tests(
results: List[Result],
expected_extension: str,
out_extension: str,
program: str,
default_expect_regex: Optional[str],
mode_flag: List[str],
get_flags: Callable[[str], List[str]],
check_expected_included_in_actual: bool,
) -> None:
idempotence_test_cases = [
TestCase(
file_path=result.test_case.file_path,
expected=result.test_case.expected,
input=result.output,
)
for result in results
]
idempotence_results = run_test_program(
idempotence_test_cases,
program,
default_expect_regex,
False,
False,
False,
mode_flag,
get_flags,
VerifyPessimisationOptions.no,
check_expected_included_in_actual=check_expected_included_in_actual,
)
num_idempotence_results = len(idempotence_results)
idempotence_failures = [
result for result in idempotence_results if result.is_failure
]
if idempotence_failures == []:
print(
"All idempotence tests in the suite passed! The number of "
"idempotence tests that ran: %d\n" % num_idempotence_results
)
else:
print(
"The number of idempotence tests that failed: %d/%d\n"
% (len(idempotence_failures), num_idempotence_results)
)
report_failures(
num_idempotence_results,
idempotence_failures,
out_extension + out_extension, # e.g., *.out.out
expected_extension,
None,
no_copy=True,
)
sys.exit(1) # this exit code fails the suite and lets Buck know
def get_flags_cache(args_flags: List[str]) -> Callable[[str], List[str]]:
flags_cache: Dict[str, List[str]] = {}
def get_flags(test_dir: str) -> List[str]:
if test_dir not in flags_cache:
flags_cache[test_dir] = get_hh_flags(test_dir)
flags = flags_cache[test_dir]
if args_flags is not None:
flags = flags + args_flags
return flags
return get_flags
def get_flags_dummy(args_flags: List[str]) -> Callable[[str], List[str]]:
def get_flags(_: str) -> List[str]:
return args_flags
return get_flags
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("test_path", help="A file or a directory. ")
parser.add_argument("--program", type=os.path.abspath)
parser.add_argument("--out-extension", type=str, default=DEFAULT_OUT_EXT)
parser.add_argument("--expect-extension", type=str, default=DEFAULT_EXP_EXT)
parser.add_argument("--fallback-expect-extension", type=str)
parser.add_argument("--default-expect-regex", type=str)
parser.add_argument("--in-extension", type=str, default=".php")
parser.add_argument("--include-directories", action="store_true")
parser.add_argument("--disabled-extension", type=str, default=".no_typecheck")
parser.add_argument("--verbose", action="store_true")
parser.add_argument(
"--idempotence",
action="store_true",
help="Verify that the output passed to the program "
"as input results in the same output.",
)
parser.add_argument("--max-workers", type=int, default="48")
parser.add_argument(
"--diff",
action="store_true",
help="On test failure, show the content of " "the files and a diff",
)
parser.add_argument("--mode-flag", type=str)
parser.add_argument("--flags", nargs=argparse.REMAINDER)
parser.add_argument(
"--stdin", action="store_true", help="Pass test input file via stdin"
)
parser.add_argument(
"--no-stderr",
action="store_true",
help="Do not include stderr output in the output file",
)
parser.add_argument(
"--batch", action="store_true", help="Run tests in batches to the test program"
)
parser.add_argument(
"--ignore-error-text",
action="store_true",
help="Do not compare error text when verifying output",
)
parser.add_argument(
"--only-compare-error-lines",
action="store_true",
help="Does not care about exact expected error message, "
"but only compare the error line numbers.",
)
parser.add_argument(
"--check-expected-included-in-actual",
action="store_true",
help="Check that the set of lines in the expected file is included in the set"
" of lines in the output",
)
parser.add_argument(
"--timeout",
type=int,
help="Timeout in seconds for each test, in non-batch mode.",
)
parser.add_argument(
"--force-color",
action="store_true",
help="Set the FORCE_ERROR_COLOR environment variable, "
"which causes the test output to retain terminal escape codes.",
)
parser.add_argument(
"--no-hh-flags", action="store_true", help="Do not read HH_FLAGS files"
)
parser.add_argument(
"--verify-pessimisation",
type=VerifyPessimisationOptions,
choices=list(VerifyPessimisationOptions),
default=VerifyPessimisationOptions.no,
help="Experimental test suite for hh_pessimisation",
)
parser.epilog = (
"%s looks for a file named HH_FLAGS in the same directory"
" as the test files it is executing. If found, the "
"contents will be passed as arguments to "
"<program> in addition to any arguments "
"specified by --flags" % parser.prog
)
args: argparse.Namespace = parser.parse_args()
max_workers = args.max_workers
verbose = args.verbose
dump_on_failure = args.diff
if os.getenv("SANDCASTLE") is not None:
dump_on_failure = True
if not os.path.isfile(args.program):
raise Exception("Could not find program at %s" % args.program)
# 'args.test_path' is a path relative to the current working
# directory. buck1 runs this test from fbsource/fbocde, buck2 runs
# it from fbsource.
if os.path.basename(os.getcwd()) != "fbsource":
# If running under buck1 then we are in fbcode, if running
# under dune then some ancestor directory of fbcode. These two
# cases are handled by the logic of this script and
# 'review.sh' and there are no adjustments to make.
pass
else:
# The buck2 case has us running in fbsource. This puts us in
# fbcode.
os.chdir("fbcode")
files: List[str] = list_test_files(
args.test_path,
args.disabled_extension,
args.in_extension,
args.include_directories,
)
if len(files) == 0:
raise Exception("Could not find any files to test in " + args.test_path)
mode_flag: List[str] = [] if args.mode_flag is None else [args.mode_flag]
get_flags: Callable[[str], List[str]] = (
get_flags_dummy(args.flags) if args.no_hh_flags else get_flags_cache(args.flags)
)
results: List[Result] = run_tests(
files,
args.expect_extension,
args.fallback_expect_extension,
args.out_extension,
args.stdin,
args.program,
args.default_expect_regex,
args.batch,
args.ignore_error_text,
args.no_stderr,
args.force_color,
args.verify_pessimisation,
mode_flag,
get_flags,
check_expected_included_in_actual=args.check_expected_included_in_actual,
timeout=args.timeout,
only_compare_error_lines=args.only_compare_error_lines,
)
# Doesn't make sense to check failures for idempotence
successes: List[Result] = [result for result in results if not result.is_failure]
if args.idempotence and successes:
run_idempotence_tests(
successes,
args.expect_extension,
args.out_extension,
args.program,
args.default_expect_regex,
mode_flag,
get_flags,
check_expected_included_in_actual=args.check_expected_included_in_actual,
) |
PHP | hhvm/hphp/hack/test/autocomplete/case.php | <?hh
// Namespace is important: we need to check that there's no user-supplied
// prefix, not just that there is no prefix at all, and AUTO332 expands to
// Foo\AUTO322
namespace Foo;
function main(): void {
switch(\random_int(123, 456)) {
case 123:AUTO332 // this should not invoke autocomplete
}
} |
PHP | hhvm/hphp/hack/test/autocomplete/case_with_ns.php | <?hh
// Namespace is important: we need to check that there's no user-supplied
// prefix, not just that there is no prefix at all, and AUTO332 expands to
// Foo\AUTO322
namespace Foo;
class ABC {}
function main(): void {
switch(\random_int(123, 456)) {
case 123:namespace\AUTO332
}
} |
PHP | hhvm/hphp/hack/test/autocomplete/case_with_prefix.php | <?hh
// Namespace is important: we need to check that there's no user-supplied
// prefix, not just that there is no prefix at all, and AUTO332 expands to
// Foo\AUTO322
namespace Foo;
class ABC {}
function main(): void {
switch(\random_int(123, 456)) {
case 123:AAUTO332
}
} |
PHP | hhvm/hphp/hack/test/autocomplete/chained_methods0.php | <?hh
enum class E : int {
int AAAA = 42;
int BBBB = 0;
}
class C {
const type T = this;
public function f(): this {
return $this;
}
public function g(HH\EnumClass\Label<E, int> $x): void {}
}
function main(): void {
$c = new C();
$c->f()->g(#AUTO332 // g has type dynamic | supportdyn<Tfun ...> |
PHP | hhvm/hphp/hack/test/autocomplete/dict_keys_str.php | <?hh
function foo(): string {
}
function bar(dict<string, string> $in): string {
return $in['AUTO332];
} |
hhvm/hphp/hack/test/autocomplete/dune | (rule
(alias autocomplete)
(deps
%{exe:../../src/hh_single_complete.exe}
%{project_root}/hack/test/verify.py
%{project_root}/hack/test/review.sh
(glob_files %{project_root}/hack/test/autocomplete/HH_FLAGS)
(glob_files %{project_root}/hack/test/autocomplete/*.php)
(glob_files %{project_root}/hack/test/autocomplete/*.exp))
(action
(run
%{project_root}/hack/test/verify.py
%{project_root}/hack/test/autocomplete
--program
%{exe:../../src/hh_single_complete.exe})))
(alias
(name runtest)
(deps
(alias autocomplete))) |
|
PHP | hhvm/hphp/hack/test/autocomplete/enum_fun_arg.php | <?hh
enum MyEnum: string {
TYPE_A = "A value";
TYPE_B = "B value";
TYPE_C = "C value";
}
function takes_enum(MyEnum $_): void {}
function demo(): void {
takes_enum(AUTO332);
} |
PHP | hhvm/hphp/hack/test/autocomplete/enum_in_case.php | <?hh
enum MyEnum: string {
TYPE_A = "A value";
TYPE_B = "B value";
TYPE_C = "C value";
}
function takes_enum(MyEnum $me): void {
switch ($me) {
case AUTO332
}
} |
PHP | hhvm/hphp/hack/test/autocomplete/enum_in_case_included.php | <?hh
enum MyEnumParent: string {
TYPE_A = "A value";
TYPE_B = "B value";
}
enum MyEnum: string {
use MyEnumParent;
TYPE_C = "C value";
TYPE_D = "D value";
}
function takes_enum(MyEnum $me): void {
switch ($me) {
case AUTO332
}
} |
PHP | hhvm/hphp/hack/test/autocomplete/enum_in_second_case.php | <?hh
enum MyEnum: string {
TYPE_A = "A value";
TYPE_B = "B value";
TYPE_C = "C value";
}
function takes_enum(MyEnum $me): void {
switch ($me) {
case MyEnum::TYPE_A:
break;
// We should only offer B and C in the completion.
case AUTO332
}
} |
PHP | hhvm/hphp/hack/test/autocomplete/enum_value_fun_arg.php | <?hh
enum MyEnum: string {
TYPE_A = "A value";
TYPE_B = "B value";
TYPE_C = "C value";
}
function takes_enum(MyEnum $_): void {}
function demo(): void {
// We should only offer concrete values here, not e.g. MyEnum::getValues().
takes_enum(MyEnum::AUTO332);
} |
PHP | hhvm/hphp/hack/test/autocomplete/force_contra_tvars.php | <?hh
enum class E : mixed {
int X = 42;
string A = 'zuck';
}
function f<T as int>(HH\EnumClass\Label<E, T> $label) : void {
}
function main(): void {
f(#AUTO332 // During type checking: Label<E, Tvar(0)> knowing that Tvar(0) <: int
// During auto-completion: Label<E, Tvar(0)>, no constraints on Tvar(0)
} |
PHP | hhvm/hphp/hack/test/autocomplete/generic_fun_enum_arg.php | <?hh
enum MyEnum: string {
TYPE_A = "A value";
TYPE_B = "B value";
TYPE_C = "C value";
}
function takes_vec(Vector<MyEnum> $_): void {}
// Invariant, so we solve to Vector<MyEnum> at the call site.
function creates_vec<T>(T $x): Vector<T> { return Vector {$x}; }
function foo(): void {
takes_vec(creates_vec(AUTO332));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.