text stringlengths 12 786k |
|---|
module Backward ( D : Backward_domain ) ( T : Backward_transfer with type domain = D . t ) : Backward_S with type domain = D . t = struct type domain = D . t type _ map = | Block : domain Label . Tbl . t map | Instr : domain Instr . Tbl . t map module WorkSetElement = struct type t = { label : Label . t ; value : domain } let compare { label = left_label ; value = left_value } { label = right_label ; value = right_value } = match Label . compare left_label right_label with | 0 -> D . compare left_value right_value | res -> res end module WorkSet = Set . Make ( WorkSetElement ) let transfer_block : domain Instr . Tbl . t option -> domain -> exn : domain -> Cfg . basic_block -> domain = fun tbl value ~ exn block -> let replace ( instr : _ Cfg . instruction ) value = match tbl with | None -> value | Some tbl -> Instr . Tbl . replace tbl instr . id value ; value in let value = replace block . terminator ( T . terminator value ~ exn block . terminator ) in let value = ListLabels . fold_right block . body ~ init : value ~ f ( : fun instr value -> replace instr ( T . basic value ~ exn instr ) ) in value let create : Cfg . t -> init : domain -> domain Label . Tbl . t * domain Instr . Tbl . t * WorkSet . t ref = fun cfg ~ init -> let map_block = Label . Tbl . create ( Label . Tbl . length cfg . Cfg . blocks ) in let map_instr = Instr . Tbl . create ( Label . Tbl . length cfg . Cfg . blocks ) in let set = ref WorkSet . empty in let value = init in Cfg . iter_blocks cfg ~ f ( : fun label _block -> Label . Tbl . replace map_block label value ; set := WorkSet . add { WorkSetElement . label ; value } ! set ) ; map_block , map_instr , set let remove_and_return : Cfg . t -> WorkSet . t ref -> WorkSetElement . t * Cfg . basic_block = fun cfg set -> let element = WorkSet . choose ! set in set := WorkSet . remove element ! set ; element , Cfg . get_block_exn cfg element . label let run : type a . Cfg . t -> ? max_iteration : int -> init : domain -> map : a map -> unit -> ( a , a ) Result . t = fun cfg ( ? max_iteration = max_int ) ~ init ~ map ( ) -> let res_block , res_instr , work_set = create cfg ~ init in let iteration = ref 0 in let handler_map : D . t Label . Tbl . t = Label . Tbl . create ( Label . Tbl . length cfg . Cfg . blocks ) in let instr_map : D . t Instr . Tbl . t option = match map with Block -> None | Instr -> Some res_instr in while ( not ( WorkSet . is_empty ! work_set ) ) && ! iteration < max_iteration do incr iteration ; let element , block = remove_and_return cfg work_set in let exn : domain = Option . map ( fun exceptional_successor -> Label . Tbl . find_opt handler_map exceptional_successor ) block . exn |> Option . join |> Option . value ~ default : D . bot in let value = transfer_block instr_map element . value ~ exn block in if block . is_trap_handler then begin let old_value = Option . value ( Label . Tbl . find_opt handler_map block . start ) ~ default : D . bot in let new_value = T . exception_ value in if not ( D . less_equal new_value old_value ) then begin Label . Tbl . replace handler_map block . start new_value ; List . iter ( fun predecessor_label -> let current_value = Option . value ( Label . Tbl . find_opt res_block predecessor_label ) ~ default : D . bot in work_set := WorkSet . add { WorkSetElement . label = predecessor_label ; value = current_value } ! work_set ) ( Cfg . predecessor_labels block ) end end else List . iter ( fun predecessor_label -> let old_value = Option . value ( Label . Tbl . find_opt res_block predecessor_label ) ~ default : D . bot in let new_value = D . join old_value value in if not ( D . less_equal new_value old_value ) then begin Label . Tbl . replace res_block predecessor_label new_value ; let already_in_workset = ref false in work_set := WorkSet . filter ( fun { WorkSetElement . label ; value } -> if Label . equal label predecessor_label then begin if D . less_equal new_value value then already_in_workset := true ; not ( D . less_equal value new_value ) end else true ) ! work_set ; if not ! already_in_workset then work_set := WorkSet . add { WorkSetElement . label = predecessor_label ; value = new_value } ! work_set end ) ( Cfg . predecessor_labels block ) done ; let return x = if WorkSet . is_empty ! work_set then Result . Ok x else Result . Error x in match map with Block -> return res_block | Instr -> return res_instr end |
type location = string exception Different of { location : location ; message : string } |
let different : location -> string -> _ = fun location message -> raise ( Different { location ; message } ) |
module type State = sig type t val make : unit -> t val add_to_explore : t -> Label . t -> Label . t -> unit val to_explore : t -> ( Label . t * Label . t ) option val add_seen : t -> Label . t -> unit val has_seen : t -> Label . t -> bool val num_seen : t -> int val add_labels_to_check : t -> location -> Label . t -> Label . t -> unit val _add_label_sets_to_check : t -> location -> Label . Set . t -> Label . Set . t -> unit val check : t -> Cfg . t -> unit end |
module type Container = sig type ' a t val make : unit -> ' a t val add : ' a -> ' a t -> unit val get : ' a t -> ' a option end |
module StackContainer : Container = struct type ' a t = ' a Stack . t let make = Stack . create let add = Stack . push let get = Stack . pop_opt end |
module Make_state ( C : Container ) : State = struct type t = { subst : Label . t Label . Tbl . t ; to_explore : ( Label . t * Label . t ) C . t ; mutable seen : Label . Set . t ; mutable labels_to_check : ( location * Label . t * Label . t ) list ; mutable label_sets_to_check : ( location * Label . Set . t * Label . Set . t ) list } let make ( ) = let subst = Label . Tbl . create 123 in let to_explore = C . make ( ) in let seen = Label . Set . empty in let labels_to_check = [ ] in let label_sets_to_check = [ ] in { to_explore ; subst ; seen ; labels_to_check ; label_sets_to_check } let add_subst t from to_ = Label . Tbl . iter ( fun key data -> match Label . equal key from , Label . equal data to_ with | true , true | false , false -> ( ) | true , false | false , true -> Misc . fatal_errorf " Cfg_equivalence : inconsistent substitution ( trying to add % a % a ) " Label . print from Label . print to_ ) t . subst ; Label . Tbl . replace t . subst from to_ let add_to_explore t lbl1 lbl2 = add_subst t lbl1 lbl2 ; C . add ( lbl1 , lbl2 ) t . to_explore let to_explore t = C . get t . to_explore let add_seen t lbl = t . seen <- Label . Set . add lbl t . seen let has_seen t lbl = Label . Set . mem lbl t . seen let num_seen t = Label . Set . cardinal t . seen let add_labels_to_check t location lbl1 lbl2 = t . labels_to_check <- ( location , lbl1 , lbl2 ) :: t . labels_to_check let _add_label_sets_to_check t location set1 set2 = t . label_sets_to_check <- ( location , set1 , set2 ) :: t . label_sets_to_check let check_label t cfg location lbl1 lbl2 = if Label . Tbl . mem cfg . Cfg . blocks lbl1 then begin match Label . Tbl . find_opt t . subst lbl1 with | None -> different location ( Printf . sprintf " label % s is not mapped " ( Label . to_string lbl1 ) ) | Some lbl2 ' -> if not ( Label . equal lbl2 lbl2 ' ) then different location ( Printf . sprintf " label % s is mapped to % s ( but % s was expected ) " ( Label . to_string lbl1 ) ( Label . to_string lbl2 ' ) ( Label . to_string lbl2 ) ) end else ( ) let check t cfg = List . iter ( fun ( location , lbl1 , lbl2 ) -> check_label t cfg location lbl1 lbl2 ) t . labels_to_check ; List . iter ( fun ( location , set1 , set2 ) -> let set1 ' = Label . Set . fold ( fun lbl acc -> match Label . Tbl . find_opt t . subst lbl with | Some lbl ' -> Label . Set . add lbl ' acc | None -> different location ( Printf . sprintf " label % s is not mapped " ( Label . to_string lbl ) ) ) set1 Label . Set . empty in if not ( Label . Set . equal set1 ' set2 ) then let string_of_label_set set = set |> Label . Set . elements |> ListLabels . map ~ f : Label . to_string |> StringLabels . concat ~ sep " , " : in different location ( Printf . sprintf " { % s } { /% s } <> { % s } " ( string_of_label_set set1 ) ( string_of_label_set set1 ' ) ( string_of_label_set set2 ) ) ) t . label_sets_to_check end |
module State = Make_state ( StackContainer ) |
let equal_raise_kind : Lambda . raise_kind -> Lambda . raise_kind -> bool = fun left right -> match left , right with | Raise_regular , Raise_regular -> true | Raise_reraise , Raise_reraise -> true | Raise_notrace , Raise_notrace -> true | Raise_regular , ( Raise_reraise | Raise_notrace ) | Raise_reraise , ( Raise_regular | Raise_notrace ) | Raise_notrace , ( Raise_regular | Raise_reraise ) -> false |
let array_equal eq left right = Array . length left = Array . length right && Array . for_all2 eq left right |
let is_valid_stack_offset : int -> bool = fun stack_offset -> stack_offset >= 0 |
let check_external_call_operation : location -> Cfg . external_call_operation -> Cfg . external_call_operation -> unit = fun location expected result -> if not ( String . equal expected . func_symbol result . func_symbol ) then different location " function symbol " ; if not ( Bool . equal expected . alloc result . alloc ) then different location " allocating " ; if not ( array_equal Cmm . equal_machtype_component expected . ty_res result . ty_res ) then different location " result type " ; if not ( List . equal Cmm . equal_exttype expected . ty_args result . ty_args ) then different location " argument types " |
let check_operation : location -> Cfg . operation -> Cfg . operation -> unit = fun location expected result -> match expected , result with | Move , Move -> ( ) | Spill , Spill -> ( ) | Reload , Reload -> ( ) | Const_int expected , Const_int result when Nativeint . equal expected result -> ( ) | Const_float expected , Const_float result when Int64 . equal expected result -> ( ) | Const_symbol expected , Const_symbol result when String . equal expected result -> ( ) | Stackoffset expected , Stackoffset result when Int . equal expected result -> ( ) | ( Load ( expected_mem , expected_arch_mode , expected_mut ) , Load ( result_mem , result_arch_mode , result_mut ) ) when Cmm . equal_memory_chunk expected_mem result_mem && expected_mut = result_mut && Arch . equal_addressing_mode expected_arch_mode result_arch_mode -> ( ) | ( Store ( expected_mem , expected_arch_mode , expected_bool ) , Store ( result_mem , result_arch_mode , result_bool ) ) when Cmm . equal_memory_chunk expected_mem result_mem && Arch . equal_addressing_mode expected_arch_mode result_arch_mode && Bool . equal expected_bool result_bool -> ( ) | Intop left_op , Intop right_op when Mach . equal_integer_operation left_op right_op -> ( ) | Intop_imm ( left_op , left_imm ) , Intop_imm ( right_op , right_imm ) when Mach . equal_integer_operation left_op right_op && Int . equal left_imm right_imm -> ( ) | Negf , Negf -> ( ) | Absf , Absf -> ( ) | Addf , Addf -> ( ) | Subf , Subf -> ( ) | Mulf , Mulf -> ( ) | Divf , Divf -> ( ) | Compf left_comp , Compf right_comp when Cmm . equal_float_comparison left_comp right_comp -> ( ) | Floatofint , Floatofint -> ( ) | Intoffloat , Intoffloat -> ( ) | ( Probe { name = expected_name ; handler_code_sym = expected_handler_code_sym } , Probe { name = result_name ; handler_code_sym = result_handler_code_sym } ) when String . equal expected_name result_name && String . equal expected_handler_code_sym result_handler_code_sym -> ( ) | ( Probe_is_enabled { name = expected_name } , Probe_is_enabled { name = result_name } ) when String . equal expected_name result_name -> ( ) | Specific expected_spec , Specific result_spec when Arch . equal_specific_operation expected_spec result_spec -> ( ) | Opaque , Opaque -> ( ) | Begin_region , Begin_region -> ( ) | End_region , End_region -> ( ) | ( Name_for_debugger { ident = left_ident ; which_parameter = left_which_parameter ; provenance = left_provenance ; is_assignment = left_is_assignment } , Name_for_debugger { ident = right_ident ; which_parameter = right_which_parameter ; provenance = right_provenance ; is_assignment = right_is_assignment } ) when Ident . equal left_ident right_ident && Option . equal Int . equal left_which_parameter right_which_parameter && Option . equal Unit . equal left_provenance right_provenance && Bool . equal left_is_assignment right_is_assignment -> ( ) | _ -> different location " operation " [ @@ ocaml . warning " - 4 " ] |
let check_prim_call_operation : location -> Cfg . prim_call_operation -> Cfg . prim_call_operation -> unit = fun location expected result -> match expected , result with | External expected , External result -> check_external_call_operation location expected result | ( Alloc { bytes = expected_bytes ; dbginfo = _expected_dbginfo ; mode = expected_mode } , Alloc { bytes = result_bytes ; dbginfo = _result_dbginfo ; mode = result_mode } ) when Int . equal expected_bytes result_bytes && Lambda . eq_mode expected_mode result_mode -> ( ) | ( Checkbound { immediate = expected_immediate } , Checkbound { immediate = result_immediate } ) when Option . equal Int . equal expected_immediate result_immediate -> ( ) | _ -> different location " primitive call operation " [ @@ ocaml . warning " - 4 " ] |
let check_func_call_operation : location -> Cfg . func_call_operation -> Cfg . func_call_operation -> unit = fun location expected result -> match expected , result with | Indirect , Indirect -> ( ) | ( Direct { func_symbol = expected_func_symbol } , Direct { func_symbol = result_func_symbol } ) when String . equal expected_func_symbol result_func_symbol -> ( ) | _ -> different location " function call operation " [ @@ ocaml . warning " - 4 " ] |
let check_tail_call_operation : State . t -> location -> Cfg . tail_call_operation -> Cfg . tail_call_operation -> unit = fun state location expected result -> match expected , result with | ( Self { destination = expected_destination } , Self { destination = result_destination } ) -> State . add_labels_to_check state location expected_destination result_destination | Func expected_func , Func result_func -> check_func_call_operation location expected_func result_func | _ -> different location " tail call operation " [ @@ ocaml . warning " - 4 " ] |
let check_call_operation : location -> Cfg . call_operation -> Cfg . call_operation -> unit = fun location expected result -> match expected , result with | P expected , P result -> check_prim_call_operation location expected result | F expected , F result -> check_func_call_operation location expected result | _ -> different location " call operation " [ @@ ocaml . warning " - 4 " ] |
let check_basic : State . t -> location -> Cfg . basic -> Cfg . basic -> unit = fun state location expected result -> match expected , result with | Op expected , Op result -> check_operation location expected result | Call expected , Call result -> check_call_operation location expected result | Reloadretaddr , Reloadretaddr -> ( ) | ( Pushtrap { lbl_handler = expected_lbl_handler } , Pushtrap { lbl_handler = result_lbl_handler } ) -> State . add_to_explore state expected_lbl_handler result_lbl_handler | Poptrap , Poptrap -> ( ) | Prologue , Prologue -> ( ) | _ -> different location " basic " [ @@ ocaml . warning " - 4 " ] |
let check_instruction : type a . check_live : bool -> check_dbg : bool -> check_arg : bool -> int -> location -> a Cfg . instruction -> a Cfg . instruction -> unit = fun ~ check_live ~ check_dbg ~ check_arg idx location expected result -> let location = Printf . sprintf " % s ( index % d ) " location idx in if check_arg && not ( array_equal Reg . same_loc expected . arg result . arg ) then different location " input registers " ; if not ( array_equal Reg . same_loc expected . res result . res ) then different location " output registers " ; if check_dbg && not ( Debuginfo . compare expected . dbg result . dbg = 0 ) then different location " debug info " ; if not ( Fdo_info . equal expected . fdo result . fdo ) then different location " FDO info " ; if check_live && not ( Reg . Set . equal expected . live result . live ) then different location " live register set " ; if is_valid_stack_offset expected . stack_offset && is_valid_stack_offset result . stack_offset && not ( Int . equal expected . stack_offset result . stack_offset ) then different location " stack offset " ; ( ) |
let check_basic_instruction : State . t -> location -> int -> Cfg . basic Cfg . instruction -> Cfg . basic Cfg . instruction -> unit = fun state location idx expected result -> check_basic state location expected . desc result . desc ; let check_dbg = match expected . desc with Prologue -> false | _ -> true [ @@ ocaml . warning " - 4 " ] in check_instruction ~ check_live : true ~ check_dbg ~ check_arg : true idx location expected result |
let rec check_basic_instruction_list : State . t -> location -> int -> Cfg . basic Cfg . instruction list -> Cfg . basic Cfg . instruction list -> unit = fun state location idx expected result -> match expected , result with | [ ] , [ ] -> ( ) | _ :: _ , [ ] -> different location " bodies with different sizes ( expected is longer ) " | [ ] , _ :: _ -> different location " bodies with different sizes ( result is longer ) " | expected_hd :: expected_tl , result_hd :: result_tl -> check_basic_instruction state location idx expected_hd result_hd ; check_basic_instruction_list state location ( succ idx ) expected_tl result_tl |
let check_terminator_instruction : State . t -> location -> Cfg . terminator Cfg . instruction -> Cfg . terminator Cfg . instruction -> unit = fun state location expected result -> begin match expected . desc , result . desc with | Never , Never -> ( ) | Always lbl1 , Always lbl2 -> State . add_to_explore state lbl1 lbl2 | ( Parity_test { ifso = ifso1 ; ifnot = ifnot1 } , Parity_test { ifso = ifso2 ; ifnot = ifnot2 } ) -> State . add_to_explore state ifso1 ifso2 ; State . add_to_explore state ifnot1 ifnot2 | ( Truth_test { ifso = ifso1 ; ifnot = ifnot1 } , Truth_test { ifso = ifso2 ; ifnot = ifnot2 } ) -> State . add_to_explore state ifso1 ifso2 ; State . add_to_explore state ifnot1 ifnot2 | ( Float_test { lt = lt1 ; eq = eq1 ; gt = gt1 ; uo = uo1 } , Float_test { lt = lt2 ; eq = eq2 ; gt = gt2 ; uo = uo2 } ) -> State . add_to_explore state lt1 lt2 ; State . add_to_explore state eq1 eq2 ; State . add_to_explore state gt1 gt2 ; State . add_to_explore state uo1 uo2 | ( Int_test { lt = lt1 ; eq = eq1 ; gt = gt1 ; is_signed = is_signed1 ; imm = imm1 } , Int_test { lt = lt2 ; eq = eq2 ; gt = gt2 ; is_signed = is_signed2 ; imm = imm2 } ) when Bool . equal is_signed1 is_signed2 && Option . equal Int . equal imm1 imm2 -> State . add_to_explore state lt1 lt2 ; State . add_to_explore state eq1 eq2 ; State . add_to_explore state gt1 gt2 | ( Int_test { lt = lt1 ; eq = eq1 ; gt = gt1 ; is_signed = is_signed1 ; imm = Some imm1 } , Int_test { lt = lt2 ; eq = eq2 ; gt = gt2 ; is_signed = is_signed2 ; imm = Some imm2 } ) when Bool . equal is_signed1 is_signed2 && Int . equal imm1 ( Int . pred imm2 ) && Label . equal lt1 eq1 && Label . equal eq2 gt2 -> State . add_to_explore state lt1 lt2 ; State . add_to_explore state gt1 gt2 | Switch a1 , Switch a2 when Array . length a1 = Array . length a2 -> Array . iter2 ( fun l1 l2 -> State . add_to_explore state l1 l2 ) a1 a2 | Return , Return -> ( ) | Raise rk1 , Raise rk2 when equal_raise_kind rk1 rk2 -> ( ) | Tailcall tc1 , Tailcall tc2 -> let location = location ^ " ( terminator ) " in check_tail_call_operation state location tc1 tc2 | Call_no_return cn1 , Call_no_return cn2 -> check_external_call_operation location cn1 cn2 | _ -> different location " terminator " end ; let check_arg = match expected . desc with | Always _ -> false | Never | Parity_test _ | Truth_test _ | Float_test _ | Int_test _ | Switch _ | Return | Raise _ | Tailcall _ | Call_no_return _ -> true in check_instruction ~ check_live : false ~ check_dbg : false ~ check_arg ( - 1 ) location expected result [ @@ ocaml . warning " - 4 " ] |
let check_basic_block : State . t -> Cfg . basic_block -> Cfg . basic_block -> unit = fun state expected result -> let location = Printf . sprintf " block % s /% s " ( Label . to_string expected . start ) ( Label . to_string result . start ) in check_basic_instruction_list state location 0 expected . body result . body ; check_terminator_instruction state location expected . terminator result . terminator ; if is_valid_stack_offset expected . stack_offset && is_valid_stack_offset result . stack_offset then begin if not ( Int . equal expected . stack_offset result . stack_offset ) then different location ( Printf . sprintf " stack offset : expected =% d result =% d " expected . stack_offset result . stack_offset ) ; let location = location ^ " ( exceptional successors ) " in match expected . exn , result . exn with | None , None -> ( ) | None , Some _ -> different location " unexpected successor " | Some _ , None -> different location " missing successor " | Some expected , Some result -> State . add_labels_to_check state location expected result end ; if not ( Bool . equal expected . can_raise result . can_raise ) then different location " can_raise " ; if not ( Bool . equal expected . is_trap_handler result . is_trap_handler ) then different location " is_trap_handler " ; if not ( Bool . equal expected . dead result . dead ) then different location " dead " |
let rec explore_cfg : State . t -> Cfg . t -> Cfg . t -> unit = fun state expected result -> match State . to_explore state with | None -> ( ) | Some ( lbl1 , lbl2 ) -> ( if not ( State . has_seen state lbl1 ) then let expected_block = Label . Tbl . find_opt expected . blocks lbl1 in let result_block = Label . Tbl . find_opt result . blocks lbl2 in match expected_block , result_block with | None , None -> assert false | None , Some _ -> different " graph " " extra block " | Some _ , None -> different " graph " " missing block " | Some expected_block , Some result_block -> State . add_seen state lbl1 ; check_basic_block state expected_block result_block ) ; explore_cfg state expected result |
let check_cfg : State . t -> Cfg . t -> Cfg . t -> unit = fun state expected result -> let expected_num_blocks = Label . Tbl . length expected . blocks in let result_num_blocks = Label . Tbl . length result . blocks in if not ( Int . equal expected_num_blocks result_num_blocks ) then different " CFG " " number of blocks " ; if not ( String . equal expected . fun_name result . fun_name ) then different " CFG " " fun_name " ; if not ( Debuginfo . compare expected . fun_dbg result . fun_dbg = 0 ) then different " CFG " " fun_dbg " ; State . add_to_explore state expected . entry_label result . entry_label ; explore_cfg state expected result |
let _check_layout : State . t -> Label . t list -> Label . t list -> unit = fun state expected result -> let expected_length = List . length expected in let result_length = List . length result in if expected_length <> result_length then different " layout sizes " ( Printf . sprintf " expected % d , got % d " expected_length result_length ) ; List . iter2 ( fun expected_label result_label -> State . add_labels_to_check state " layout " expected_label result_label ) expected result |
let save_cfg_as_dot : Cfg_with_layout . t -> string -> unit = fun cfg_with_layout msg -> Cfg_with_layout . save_as_dot cfg_with_layout ~ show_instr : true ~ show_exn : true ~ annotate_succ ( : Printf . sprintf " % d ->% d " ) msg |
let check_cfg_with_layout : ? mach : Mach . fundecl -> ? linear : Linear . fundecl -> Cfg_with_layout . t -> Cfg_with_layout . t -> unit = fun ? mach ? linear expected result -> try let state = State . make ( ) in check_cfg state ( Cfg_with_layout . cfg expected ) ( Cfg_with_layout . cfg result ) ; State . check state ( Cfg_with_layout . cfg expected ) ; let num_seen = State . num_seen state in if not ( Int . equal num_seen ( Label . Tbl . length ( Cfg_with_layout . cfg expected ) . blocks ) ) then different " exploration " " partial " with Different { location ; message } -> save_cfg_as_dot expected " expected " ; save_cfg_as_dot result " result " ; Option . iter ( fun f -> Format . eprintf " % a \ n " %! Printmach . fundecl f ) mach ; Option . iter ( fun f -> Format . eprintf " % a \ n " %! Printlinear . fundecl f ) linear ; Misc . fatal_errorf " Cfg_equivalence : error in % s \ n % s : % s \ n " ( Cfg . fun_name ( Cfg_with_layout . cfg expected ) ) location message |
type cfg_item_info = | Cfg of Cfg_with_layout . t | Data of Cmm . data_item list |
type cfg_unit_info = { mutable unit_name : string ; mutable items : cfg_item_info list ; mutable for_pack : string option } |
type error = | Wrong_format of string | Wrong_version of string | Corrupted of string | Marshal_failed of string |
let save filename cfg_unit_info = let ch = open_out_bin filename in Misc . try_finally ( fun ( ) -> output_string ch Config . cfg_magic_number ; output_value ch cfg_unit_info ; output_value ch ( Cmm . cur_label ( ) ) ; flush ch ; let crc = Digest . file filename in Digest . output ch crc ) ~ always ( : fun ( ) -> close_out ch ) ~ exceptionally ( : fun ( ) -> raise ( Error ( Marshal_failed filename ) ) ) |
let restore filename = let ic = open_in_bin filename in Misc . try_finally ( fun ( ) -> let magic = Config . cfg_magic_number in let buffer = really_input_string ic ( String . length magic ) in if String . equal buffer magic then begin try let cfg_unit_info = ( input_value ic : cfg_unit_info ) in let last_label = ( input_value ic : Cmm . label ) in Cmm . reset ( ) ; Cmm . set_label last_label ; let crc = Digest . input ic in cfg_unit_info , crc with End_of_file | Failure _ -> raise ( Error ( Corrupted filename ) ) | Error e -> raise ( Error e ) end else if String . sub buffer 0 9 = String . sub magic 0 9 then raise ( Error ( Wrong_version filename ) ) else raise ( Error ( Wrong_format filename ) ) ) ~ always ( : fun ( ) -> close_in ic ) |
let report_error ppf = function | Wrong_format filename -> fprintf ppf " Expected Cfg format . Incompatible file % a " Location . print_filename filename | Wrong_version filename -> fprintf ppf " % a @ is not compatible with this version of OCaml " Location . print_filename filename | Corrupted filename -> fprintf ppf " Corrupted format @ % a " Location . print_filename filename | Marshal_failed filename -> fprintf ppf " Failed to marshal Cfg to file @ % a " Location . print_filename filename |
let ( ) = Location . register_error_of_exn ( function | Error err -> Some ( Location . error_of_printer_file report_error err ) | _ -> None ) |
module S = struct type func_call_operation = | Indirect | Direct of { func_symbol : string } type tail_call_operation = | Self of { destination : Label . t } | Func of func_call_operation type external_call_operation = { func_symbol : string ; alloc : bool ; ty_res : Cmm . machtype ; ty_args : Cmm . exttype list } type prim_call_operation = | External of external_call_operation | Alloc of { bytes : int ; dbginfo : Debuginfo . alloc_dbginfo ; mode : Lambda . alloc_mode } | Checkbound of { immediate : int option } type operation = | Move | Spill | Reload | Const_int of nativeint | Const_float of int64 | Const_symbol of string | Stackoffset of int | Load of Cmm . memory_chunk * Arch . addressing_mode * Mach . mutable_flag | Store of Cmm . memory_chunk * Arch . addressing_mode * bool | Intop of Mach . integer_operation | Intop_imm of Mach . integer_operation * int | Negf | Absf | Addf | Subf | Mulf | Divf | Compf of Mach . float_comparison | Floatofint | Intoffloat | Probe of { name : string ; handler_code_sym : string } | Probe_is_enabled of { name : string } | Opaque | Begin_region | End_region | Specific of Arch . specific_operation | Name_for_debugger of { ident : Ident . t ; which_parameter : int option ; provenance : unit option ; is_assignment : bool } type call_operation = | P of prim_call_operation | F of func_call_operation type bool_test = { ifso : Label . t ; ifnot : Label . t } type int_test = { lt : Label . t ; eq : Label . t ; gt : Label . t ; is_signed : bool ; imm : int option } type float_test = { lt : Label . t ; eq : Label . t ; gt : Label . t ; uo : Label . t } type ' a instruction = { desc : ' a ; arg : Reg . t array ; res : Reg . t array ; dbg : Debuginfo . t ; fdo : Fdo_info . t ; live : Reg . Set . t ; stack_offset : int ; id : int } type basic = | Op of operation | Call of call_operation | Reloadretaddr | Pushtrap of { lbl_handler : Label . t } | Poptrap | Prologue type terminator = | Never | Always of Label . t | Parity_test of bool_test | Truth_test of bool_test | Float_test of float_test | Int_test of int_test | Switch of Label . t array | Return | Raise of Lambda . raise_kind | Tailcall of tail_call_operation | Call_no_return of external_call_operation end |
type domain = { before : Reg . Set . t ; across : Reg . Set . t } |
module Domain : Cfg_dataflow . Backward_domain with type t = domain = struct type t = domain = { before : Reg . Set . t ; across : Reg . Set . t } let bot = { before = Reg . Set . empty ; across = Reg . Set . empty } let compare { before = left_before ; across = _ } { before = right_before ; across = _ } = Reg . Set . compare left_before right_before let join { before = left_before ; across = _ } { before = right_before ; across = _ } = { before = Reg . Set . union left_before right_before ; across = Reg . Set . empty } let less_equal { before = left_before ; across = _ } { before = right_before ; across = _ } = Reg . Set . subset left_before right_before let with_formatter ~ f x = let buff = Buffer . create 64 in let fmt = Format . formatter_of_buffer buff in f fmt x ; Format . pp_print_flush fmt ( ) ; Buffer . contents buff let to_string { before = regset ; across = _ } = regset |> Reg . Set . elements |> ListLabels . map ~ f ( : with_formatter ~ f : Printmach . reg ) |> StringLabels . concat ~ sep " , : " end |
module Transfer : Cfg_dataflow . Backward_transfer with type domain = domain = struct type nonrec domain = domain = { before : Reg . Set . t ; across : Reg . Set . t } let basic : domain -> exn : domain -> Cfg . basic Cfg . instruction -> domain = fun { before ; across = _ } ~ exn instr -> match instr . desc with | Op _ | Call _ -> if Cfg . is_pure_basic instr . desc && Reg . disjoint_set_array before instr . res && ( not ( Proc . regs_are_volatile instr . arg ) ) && not ( Proc . regs_are_volatile instr . res ) then { before ; across = before } else let across = Reg . diff_set_array before instr . res in let across = if Cfg . can_raise_basic instr . desc && instr . stack_offset > 0 then Reg . Set . union across exn . before else across in let before = Reg . add_set_array across instr . arg in { before ; across } | Reloadretaddr -> { before = Reg . diff_set_array before Proc . destroyed_at_reloadretaddr ; across = Reg . Set . empty } | Pushtrap _ -> { before ; across = Reg . Set . empty } | Poptrap -> { before ; across = Reg . Set . empty } | Prologue -> { before ; across = Reg . Set . empty } let terminator : domain -> exn : domain -> Cfg . terminator Cfg . instruction -> domain = fun { before ; across = _ } ~ exn instr -> match instr . desc with | Never -> assert false | Always _ -> { before = Reg . add_set_array before instr . arg ; across = before } | Parity_test _ -> { before = Reg . add_set_array before instr . arg ; across = before } | Truth_test _ -> { before = Reg . add_set_array before instr . arg ; across = before } | Float_test _ -> { before = Reg . add_set_array before instr . arg ; across = before } | Int_test _ -> { before = Reg . add_set_array before instr . arg ; across = before } | Switch _ -> { before = Reg . add_set_array before instr . arg ; across = before } | Return -> { before = Reg . set_of_array instr . arg ; across = Reg . Set . empty } | Tailcall ( Self _ ) -> { before = Reg . set_of_array instr . arg ; across = Reg . Set . empty } | Raise _ -> { before = Reg . add_set_array exn . before instr . arg ; across = exn . before } | Tailcall ( Func _ ) -> { before = Reg . set_of_array instr . arg ; across = Reg . Set . empty } | Call_no_return _ -> { before = Reg . add_set_array exn . before instr . arg ; across = exn . before } let exception_ : domain -> domain = fun { before ; across = _ } -> { before = Reg . Set . remove Proc . loc_exn_bucket before ; across = Reg . Set . empty } end |
module Liveness = Cfg_dataflow . Backward ( Domain ) ( Transfer ) |
let to_linear_instr ( ? like : _ Cfg . instruction option ) desc ~ next : L . instruction = let arg , res , dbg , live , fdo = match like with | None -> [ ] , || [ ] , || Debuginfo . none , Reg . Set . empty , Fdo_info . none | Some like -> like . arg , like . res , like . dbg , like . live , like . fdo in { desc ; next ; arg ; res ; dbg ; live ; fdo } |
let from_basic ( basic : Cfg . basic ) : L . instruction_desc = match basic with | Prologue -> Lprologue | Reloadretaddr -> Lreloadretaddr | Pushtrap { lbl_handler } -> Lpushtrap { lbl_handler } | Poptrap -> Lpoptrap | Call ( F Indirect ) -> Lop Icall_ind | Call ( F ( Direct { func_symbol } ) ) -> Lop ( Icall_imm { func = func_symbol } ) | Call ( P ( External { func_symbol ; alloc ; ty_args ; ty_res } ) ) -> Lop ( Iextcall { func = func_symbol ; alloc ; ty_args ; ty_res ; returns = true } ) | Call ( P ( Checkbound { immediate = None } ) ) -> Lop ( Iintop Icheckbound ) | Call ( P ( Checkbound { immediate = Some i } ) ) -> Lop ( Iintop_imm ( Icheckbound , i ) ) | Call ( P ( Alloc { bytes ; dbginfo ; mode } ) ) -> Lop ( Ialloc { bytes ; dbginfo ; mode } ) | Op op -> let op : Mach . operation = match op with | Move -> Imove | Spill -> Ispill | Reload -> Ireload | Const_int n -> Iconst_int n | Const_float n -> Iconst_float n | Const_symbol n -> Iconst_symbol n | Stackoffset n -> Istackoffset n | Load ( c , m , i ) -> Iload ( c , m , i ) | Store ( c , m , b ) -> Istore ( c , m , b ) | Intop op -> Iintop op | Intop_imm ( op , i ) -> Iintop_imm ( op , i ) | Negf -> Inegf | Absf -> Iabsf | Addf -> Iaddf | Subf -> Isubf | Mulf -> Imulf | Divf -> Idivf | Compf c -> Icompf c | Floatofint -> Ifloatofint | Intoffloat -> Iintoffloat | Probe { name ; handler_code_sym } -> Iprobe { name ; handler_code_sym } | Probe_is_enabled { name } -> Iprobe_is_enabled { name } | Opaque -> Iopaque | Specific op -> Ispecific op | Begin_region -> Ibeginregion | End_region -> Iendregion | Name_for_debugger { ident ; which_parameter ; provenance ; is_assignment } -> Iname_for_debugger { ident ; which_parameter ; provenance ; is_assignment } in Lop op |
let basic_to_linear ( i : _ Cfg . instruction ) ~ next = let desc = from_basic i . desc in to_linear_instr ~ like : i desc ~ next |
let mk_int_test ~ lt ~ eq ~ gt : Cmm . integer_comparison = match eq , lt , gt with | true , false , false -> Ceq | false , true , false -> Clt | false , false , true -> Cgt | false , true , true -> Cne | true , true , false -> Cle | true , false , true -> Cge | true , true , true -> assert false | false , false , false -> assert false |
type float_cond = | Must_be_last | Any of Cmm . float_comparison list |
let mk_float_cond ~ lt ~ eq ~ gt ~ uo = match eq , lt , gt , uo with | true , false , false , false -> Any [ CFeq ] | false , true , false , false -> Any [ CFlt ] | false , false , true , false -> Any [ CFgt ] | true , true , false , false -> Any [ CFle ] | true , false , true , false -> Any [ CFge ] | false , true , true , true -> Any [ CFneq ] | true , false , true , true -> Any [ CFnlt ] | true , true , false , true -> Any [ CFngt ] | false , false , true , true -> Any [ CFnle ] | false , true , false , true -> Any [ CFnge ] | true , true , true , true -> assert false | false , false , false , false -> assert false | true , true , true , false -> Misc . fatal_error " Encountered disjunction of conditions : [ CFle ; CFgt ] " | false , true , true , false -> Misc . fatal_error " Encountered disjunction of conditions [ CFlt ; CFgt ] " | false , false , false , true -> Must_be_last | true , false , false , true -> Must_be_last |
let linearize_terminator cfg ( terminator : Cfg . terminator Cfg . instruction ) ( ~ next : Linear_utils . labelled_insn ) : L . instruction * Label . t option = let branch_or_fallthrough lbl = if Label . equal next . label lbl then [ ] else [ L . Lbranch lbl ] in let emit_bool ( c1 , l1 ) ( c2 , l2 ) = match Label . equal l1 next . label , Label . equal l2 next . label with | true , true -> [ ] | false , true -> [ L . Lcondbranch ( c1 , l1 ) ] | true , false -> [ L . Lcondbranch ( c2 , l2 ) ] | false , false -> if Label . equal l1 l2 then [ L . Lbranch l1 ] else [ L . Lcondbranch ( c1 , l1 ) ; L . Lbranch l2 ] in let desc_list , tailrec_label = match terminator . desc with | Return -> [ L . Lreturn ] , None | Raise kind -> [ L . Lraise kind ] , None | Tailcall ( Func Indirect ) -> [ L . Lop Itailcall_ind ] , None | Tailcall ( Func ( Direct { func_symbol } ) ) -> [ L . Lop ( Itailcall_imm { func = func_symbol } ) ] , None | Tailcall ( Self { destination } ) -> [ L . Lop ( Itailcall_imm { func = Cfg . fun_name cfg } ) ] , Some destination | Call_no_return { func_symbol ; alloc ; ty_args ; ty_res } -> ( [ L . Lop ( Iextcall { func = func_symbol ; alloc ; ty_args ; ty_res ; returns = false } ) ] , None ) | Switch labels -> [ L . Lswitch labels ] , None | Never -> Misc . fatal_error " Cannot linearize terminator : Never " | Always label -> branch_or_fallthrough label , None | Parity_test { ifso ; ifnot } -> emit_bool ( Ieventest , ifso ) ( Ioddtest , ifnot ) , None | Truth_test { ifso ; ifnot } -> emit_bool ( Itruetest , ifso ) ( Ifalsetest , ifnot ) , None | Float_test { lt ; eq ; gt ; uo } -> ( let successor_labels = Label . Set . singleton lt |> Label . Set . add gt |> Label . Set . add eq |> Label . Set . add uo in match Label . Set . cardinal successor_labels with | 0 -> assert false | 1 -> branch_or_fallthrough ( Label . Set . min_elt successor_labels ) , None | 2 | 3 | 4 -> let must_be_last , any = Label . Set . fold ( fun lbl ( must_be_last , any ) -> let cond = mk_float_cond ~ lt ( : Label . equal lt lbl ) ~ eq ( : Label . equal eq lbl ) ~ gt ( : Label . equal gt lbl ) ~ uo ( : Label . equal uo lbl ) in match cond with | Any cl -> let l = List . map ( fun c -> c , lbl ) cl in must_be_last , l @ any | Must_be_last -> lbl :: must_be_last , any ) successor_labels ( [ ] , [ ] ) in let last = match must_be_last with | [ ] -> if Label . Set . mem next . label successor_labels then next . label else Label . Set . min_elt successor_labels | [ lbl ] -> Printf . eprintf " One success label must be last : % d \ n " lbl ; Misc . fatal_errorf " Illegal branch : one successor label must be last % d " lbl ( ) | _ -> Misc . fatal_error " Illegal branch : more than one successor label that must be last " in let branches = List . filter_map ( fun ( c , lbl ) -> if Label . equal lbl last then None else Some ( L . Lcondbranch ( Ifloattest c , lbl ) ) ) any in branches @ branch_or_fallthrough last , None | _ -> assert false ) | Int_test { lt ; eq ; gt ; imm ; is_signed } -> ( let successor_labels = Label . Set . singleton lt |> Label . Set . add gt |> Label . Set . add eq in match Label . Set . cardinal successor_labels with | 0 -> assert false | 1 -> branch_or_fallthrough ( Label . Set . min_elt successor_labels ) , None | 2 | 3 -> let last = if Label . Set . mem next . label successor_labels then next . label else Label . Set . min_elt successor_labels in let cond_successor_labels = Label . Set . remove last successor_labels in let can_emit_Lcondbranch3 = match is_signed , imm with | false , Some 1 -> true | false , Some _ | false , None | true , _ -> false in if Label . Set . cardinal cond_successor_labels = 2 && can_emit_Lcondbranch3 then let find l = if Label . equal next . label l then None else Some l in [ L . Lcondbranch3 ( find lt , find eq , find gt ) ] , None else let init = branch_or_fallthrough last in ( Label . Set . fold ( fun lbl acc -> let cond = mk_int_test ~ lt ( : Label . equal lt lbl ) ~ eq ( : Label . equal eq lbl ) ~ gt ( : Label . equal gt lbl ) in let comp = match is_signed with | true -> Mach . Isigned cond | false -> Mach . Iunsigned cond in let test = match imm with | None -> Mach . Iinttest comp | Some n -> Mach . Iinttest_imm ( comp , n ) in L . Lcondbranch ( test , lbl ) :: acc ) cond_successor_labels init , None ) | _ -> assert false ) in ( List . fold_left ( fun next desc -> to_linear_instr ~ like : terminator desc ~ next ) next . insn ( List . rev desc_list ) , tailrec_label ) |
let need_starting_label ( cfg_with_layout : CL . t ) ( block : Cfg . basic_block ) ( ~ prev_block : Cfg . basic_block ) = if block . is_trap_handler then true else match Label . Set . elements block . predecessors with | [ ] | _ :: _ :: _ -> true | [ pred ] when not ( Label . equal pred prev_block . start ) -> true | [ _ ] -> ( match prev_block . terminator . desc with | Switch _ -> true | Never -> Misc . fatal_error " Cannot linearize terminator : Never " | Always _ | Parity_test _ | Truth_test _ | Float_test _ | Int_test _ -> let new_labels = CL . new_labels cfg_with_layout in CL . preserve_orig_labels cfg_with_layout && not ( Label . Set . mem block . start new_labels ) | Return | Raise _ | Tailcall _ | Call_no_return _ -> assert false ) |
let adjust_stack_offset body ( block : Cfg . basic_block ) ( ~ prev_block : Cfg . basic_block ) = let block_stack_offset = block . stack_offset in let prev_stack_offset = prev_block . terminator . stack_offset in if block_stack_offset = prev_stack_offset then body else let delta_bytes = block_stack_offset - prev_stack_offset in to_linear_instr ( Ladjust_stack_offset { delta_bytes } ) ~ next : body |
let run cfg_with_layout = let cfg = CL . cfg cfg_with_layout in let layout = Array . of_list ( CL . layout cfg_with_layout ) in let len = Array . length layout in let next = ref Linear_utils . labelled_insn_end in let tailrec_label = ref None in for i = len - 1 downto 0 do let label = layout . ( i ) in if not ( Label . Tbl . mem cfg . blocks label ) then Misc . fatal_errorf " Unknown block labelled % d \ n " label ; let block = Label . Tbl . find cfg . blocks label in assert ( Label . equal label block . start ) ; let body = let terminator , terminator_tailrec_label = linearize_terminator cfg block . terminator ~ next :! next in ( match ! tailrec_label , terminator_tailrec_label with | ( Some _ | None ) , None -> ( ) | None , Some _ -> tailrec_label := terminator_tailrec_label | Some old_trl , Some new_trl -> assert ( Label . equal old_trl new_trl ) ) ; List . fold_left ( fun next i -> basic_to_linear i ~ next ) terminator ( List . rev block . body ) in let insn = if i = 0 then body else let body = if block . is_trap_handler then to_linear_instr Lentertrap ~ next : body else body in let prev = layout . ( i - 1 ) in let prev_block = Label . Tbl . find cfg . blocks prev in let body = if not ( need_starting_label cfg_with_layout block ~ prev_block ) then body else to_linear_instr ( Llabel block . start ) ~ next : body in adjust_stack_offset body block ~ prev_block in next := { Linear_utils . label ; insn } done ; let fun_contains_calls = cfg . fun_contains_calls in let fun_num_stack_slots = cfg . fun_num_stack_slots in let fun_frame_required = Proc . frame_required ~ fun_contains_calls ~ fun_num_stack_slots in let fun_prologue_required = Proc . prologue_required ~ fun_contains_calls ~ fun_num_stack_slots in { Linear . fun_name = cfg . fun_name ; fun_body = ! next . insn ; fun_tailrec_entry_point_label = ! tailrec_label ; fun_fast = cfg . fun_fast ; fun_dbg = cfg . fun_dbg ; fun_contains_calls ; fun_num_stack_slots ; fun_frame_required ; fun_prologue_required } |
let print_assembly ( blocks : Cfg . basic_block list ) = let layout = List . map ( fun ( b : Cfg . basic_block ) -> b . start ) blocks in let fun_name = " _fun_start_ " in let cfg = Cfg . create ~ fun_name ~ fun_args [ ] :|| ~ fun_dbg : Debuginfo . none ~ fun_fast : false ~ fun_contains_calls : true ~ fun_num_stack_slots [ ] :|| in List . iter ( fun ( block : Cfg . basic_block ) -> Label . Tbl . add cfg . blocks block . start block ) blocks ; let cl = Cfg_with_layout . create cfg ~ layout ~ new_labels : Label . Set . empty ~ preserve_orig_labels : true in let fundecl = run cl in X86_proc . reset_asm_code ( ) ; Emit . fundecl fundecl ; X86_proc . generate_code ( Some ( X86_gas . generate_asm ! Emitaux . output_channel ) ) |
type t = { cfg : Cfg . t ; mutable layout : Label . t list ; mutable new_labels : Label . Set . t ; preserve_orig_labels : bool } |
let create cfg ~ layout ~ preserve_orig_labels ~ new_labels = { cfg ; layout ; new_labels ; preserve_orig_labels } |
let cfg t = t . cfg |
let layout t = t . layout |
let preserve_orig_labels t = t . preserve_orig_labels |
let new_labels t = t . new_labels |
let set_layout t layout = let cur_layout = Label . Set . of_list t . layout in let new_layout = Label . Set . of_list layout in if not ( Label . Set . equal cur_layout new_layout && Label . equal ( List . hd layout ) t . cfg . entry_label ) then Misc . fatal_error " Cfg set_layout : new layout is not a permutation of the current layout , \ or first label is not entry " ; t . layout <- layout |
let remove_block t label = Cfg . remove_block_exn t . cfg label ; t . layout <- List . filter ( fun l -> not ( Label . equal l label ) ) t . layout ; t . new_labels <- Label . Set . remove label t . new_labels |
let is_trap_handler t label = let block = Cfg . get_block_exn t . cfg label in block . is_trap_handler |
let dump ppf t ~ msg = let open Format in fprintf ppf " \ ncfg for % s \ n " msg ; fprintf ppf " % s \ n " t . cfg . fun_name ; fprintf ppf " layout . length =% d \ n " ( List . length t . layout ) ; fprintf ppf " blocks . length =% d \ n " ( Label . Tbl . length t . cfg . blocks ) ; let print_block label = let block = Label . Tbl . find t . cfg . blocks label in fprintf ppf " \ n % d :\ n " label ; List . iter ( fprintf ppf " % a \ n " Cfg . print_basic ) block . body ; Cfg . print_terminator ppf block . terminator ; fprintf ppf " \ npredecessors " ; : Label . Set . iter ( fprintf ppf " % d " ) block . predecessors ; fprintf ppf " \ nsuccessors " ; : Label . Set . iter ( fprintf ppf " % d " ) ( Cfg . successor_labels ~ normal : true ~ exn : false block ) ; fprintf ppf " \ nexn - successors " ; : Label . Set . iter ( fprintf ppf " % d " ) ( Cfg . successor_labels ~ normal : false ~ exn : true block ) ; fprintf ppf " \ n " in List . iter print_block t . layout |
let print_dot ( ? show_instr = true ) ( ? show_exn = true ) ? annotate_block ? annotate_succ ppf t = Format . fprintf ppf " strict digraph " \% s " \ { \ n " t . cfg . fun_name ; let annotate_block label = match annotate_block with | None -> " " | Some f -> Printf . sprintf " \ n % s " ( f label ) in let annotate_succ l1 l2 = match annotate_succ with | None -> " " | Some f -> Printf . sprintf " label " =\% s " " \ ( f l1 l2 ) in let print_block_dot label ( block : Cfg . basic_block ) index = let name l = Printf . sprintf " " . \ L % d " " \ l in let show_index = Option . value index ~ default ( :- 1 ) in Format . fprintf ppf " \ n % s [ shape = box label " . =\ L % d : I % d : S % d % s % s % s " ( name label ) label show_index ( List . length block . body ) ( if block . stack_offset > 0 then " : T " ^ string_of_int block . stack_offset else " " ) ( if block . is_trap_handler then " : eh " else " " ) ( annotate_block label ) ; if show_instr then ( Format . fprintf ppf " \ npreds " ; : Label . Set . iter ( Format . fprintf ppf " % d " ) block . predecessors ; Format . fprintf ppf " \\ l " ; List . iter ( fun i -> Format . fprintf ppf " % a \\ l " Cfg . print_basic i ) block . body ; Format . fprintf ppf " % a \\ l " ( Cfg . print_terminator ~ sep " :\\ l " ) block . terminator ) ; Format . fprintf ppf " " ] \\ n " ; Label . Set . iter ( fun l -> Format . fprintf ppf " % s ->% s [ % s ] \ n " ( name label ) ( name l ) ( annotate_succ label l ) ) ( Cfg . successor_labels ~ normal : true ~ exn : false block ) ; if show_exn then ( Label . Set . iter ( fun l -> Format . fprintf ppf " % s ->% s [ style = dashed % s ] \ n " ( name label ) ( name l ) ( annotate_succ label l ) ) ( Cfg . successor_labels ~ normal : false ~ exn : true block ) ; if Cfg . can_raise_interproc block then Format . fprintf ppf " % s ->% s [ style = dashed ] \ n " ( name label ) " placeholder " ) in List . iteri ( fun index label -> let block = Label . Tbl . find t . cfg . blocks label in print_block_dot label block ( Some index ) ) t . layout ; if List . length t . layout < Label . Tbl . length t . cfg . blocks then Label . Tbl . iter ( fun label block -> match List . find_opt ( fun lbl -> Label . equal label lbl ) t . layout with | None -> print_block_dot label block None | _ -> ( ) ) t . cfg . blocks ; Format . fprintf ppf " } \ n " |
let save_as_dot t ? show_instr ? show_exn ? annotate_block ? annotate_succ msg = let filename = Printf . sprintf " % s % s % s . dot " ( X86_proc . string_of_symbol " " t . cfg . fun_name ) ( if msg = " " then " " else " . " ) msg in if ! Cfg . verbose then Printf . printf " Writing cfg for % s to % s \ n " msg filename ; let oc = open_out filename in Misc . try_finally ( fun ( ) -> let ppf = Format . formatter_of_out_channel oc in print_dot ? show_instr ? show_exn ? annotate_block ? annotate_succ ppf t ) ~ always ( : fun ( ) -> close_out oc ) ~ exceptionally ( : fun _exn -> Misc . remove_file filename ) |
module Permute = struct external unsafe_set : ' a array -> int -> ' a -> unit = " % array_unsafe_set " external unsafe_get : ' a array -> int -> ' a = " % array_unsafe_get " let default_random_state = Random . State . make_self_init ( ) let array ( ? random_state = default_random_state ) t = let swap t i j = let elt_i = unsafe_get t i in let elt_j = unsafe_get t j in unsafe_set t i elt_j ; unsafe_set t j elt_i in let num_swaps = Array . length t - 1 in for i = num_swaps downto 1 do let random_i = Random . State . int random_state ( i + 1 ) in swap t i random_i done let list ( ? random_state = default_random_state ) list = match list with | [ ] | [ _ ] -> list | [ x ; y ] -> if Random . State . bool random_state then [ y ; x ] else list | _ -> let arr = Array . of_list list in array ~ random_state arr ; Array . to_list arr end |
let reorder_blocks_random ? random_state t = let original_layout = layout t in let new_layout = List . hd original_layout :: Permute . list ? random_state ( List . tl original_layout ) in set_layout t new_layout |
let create ( ) = { id = Runtime . Chan_id . gen ( ) ; channel = Event . new_channel ( ) ; closed_flag = false ; clients_count = 0 ; mutex = Mutex . create ( ) ; } ; ; |
let maintain_clients_count chan delta = let will_block = ( delta * chan . clients_count >= 0 ) in ( if will_block then ( chan . clients_count <- chan . clients_count + delta ; Runtime . Fiber . blocked ( ) ) else ( chan . clients_count <- chan . clients_count + delta ; Runtime . Fiber . unblocked ( ) ) ) ; ; ; |
let unblocked_send_impl chan value = if None <> Event . poll ( Event . send chan . channel value ) then ( maintain_clients_count chan 1 ; true ) else false ; ; |
let unblocked_send chan value = Mutex . lock chan . mutex ; if chan . closed_flag then ( Mutex . unlock chan . mutex ; false ) else let rst = unblocked_send_impl chan value in Mutex . unlock chan . mutex ; rst ; ; |
let send chan value = Mutex . lock chan . mutex ; if chan . closed_flag then ( Mutex . unlock chan . mutex ; closed_chan chan ) ; if unblocked_send_impl chan value then Mutex . unlock chan . mutex else ( maintain_clients_count chan 1 ; Mutex . unlock chan . mutex ; Event . sync ( Event . send chan . channel value ) ) ; ; |
let unblocked_receive_impl chan = if chan . closed_flag then Some EofObject else ( let rst = Event . poll ( Event . receive chan . channel ) in if None <> rst then maintain_clients_count chan ( - 1 ) ; rst ) ; ; |
let unblocked_receive chan = Mutex . lock chan . mutex ; if chan . closed_flag then ( Mutex . unlock chan . mutex ; None ) else let rst = unblocked_receive_impl chan in Mutex . unlock chan . mutex ; rst ; ; |
let receive chan = Mutex . lock chan . mutex ; match unblocked_receive_impl chan with | Some value -> ( Mutex . unlock chan . mutex ; value ) | None -> ( maintain_clients_count chan ( - 1 ) ; Mutex . unlock chan . mutex ; Event . sync ( Event . receive chan . channel ) ) ; ; |
let close chan = Mutex . lock chan . mutex ; if chan . closed_flag then ( Mutex . unlock chan . mutex ; closed_chan chan ) else chan . closed_flag <- true ; if chan . clients_count > 0 then closed_chan chan else for i = 1 to ( - chan . clients_count ) do Event . sync ( Event . send chan . channel EofObject ) ; Runtime . Fiber . unblocked ( ) done ; Mutex . unlock chan . mutex ; ; ; |
let chr n = if n < 0 || n > 255 then invalid_arg " Char . chr " else unsafe_chr n = " % bytes_unsafe_set " |
let escaped = function | ' ' ' \ -> " ' " \\ | ' ' \\ -> " " \\\\ | ' \ n ' -> " \\ n " | ' \ t ' -> " \\ t " | ' \ r ' -> " \\ r " | ' \ b ' -> " \\ b " | ' ' . . ' ' ~ as c -> let s = bytes_create 1 in bytes_unsafe_set s 0 c ; unsafe_to_string s | c -> let n = code c in let s = bytes_create 4 in bytes_unsafe_set s 0 ' ' ; \\ bytes_unsafe_set s 1 ( unsafe_chr ( 48 + n / 100 ) ) ; bytes_unsafe_set s 2 ( unsafe_chr ( 48 + ( n / 10 ) mod 10 ) ) ; bytes_unsafe_set s 3 ( unsafe_chr ( 48 + n mod 10 ) ) ; unsafe_to_string s |
let lowercase = function | ' A ' . . ' Z ' | ' \ 192 ' . . ' \ 214 ' | ' \ 216 ' . . ' \ 222 ' as c -> unsafe_chr ( code c + 32 ) | c -> c |
let uppercase = function | ' a ' . . ' z ' | ' \ 224 ' . . ' \ 246 ' | ' \ 248 ' . . ' \ 254 ' as c -> unsafe_chr ( code c - 32 ) | c -> c |
let lowercase_ascii = function | ' A ' . . ' Z ' as c -> unsafe_chr ( code c + 32 ) | c -> c |
let uppercase_ascii = function | ' a ' . . ' z ' as c -> unsafe_chr ( code c - 32 ) | c -> c |
let compare c1 c2 = code c1 - code c2 |
let equal ( c1 : t ) ( c2 : t ) = compare c1 c2 = 0 |
let ( ) = Printexc . record_backtrace true |
let filter_map f l = List . rev @@ List . fold_left ( fun a v -> match f v with Some v ' -> v ' :: a | None -> a ) [ ] l |
let level_of_string = function | " warning " -> Lwt_log . Warning | " notice " -> Lwt_log . Notice | " debug " -> Lwt_log . Debug | _ -> invalid_arg " Unknown verbosity level " |
let go_safe user group = let ( pw , _gr ) = try ( Unix . getpwnam user , Unix . getgrnam group ) with _ -> failwith " No user and / or group _charruad found , please create them . " in Unix . chroot pw . Unix . pw_dir ; Unix . chdir " " ; / let ogid = Unix . getgid ( ) in let oegid = Unix . getegid ( ) in let ouid = Unix . getuid ( ) in let oeuid = Unix . geteuid ( ) in Unix . setgroups ( Array . of_list [ pw . Unix . pw_gid ] ) ; Unix . setgid pw . Unix . pw_gid ; Unix . setuid pw . Unix . pw_uid ; if ogid = pw . Unix . pw_gid || oegid = pw . Unix . pw_gid || ouid = pw . Unix . pw_uid || oeuid = pw . Unix . pw_uid then failwith " Unexpected uid or gid after dropping privileges " ; let canrestore = try Unix . setuid ouid ; Unix . setuid oeuid ; Unix . setgid ogid ; Unix . setgid oegid ; true with _ -> false in if canrestore then failwith " Was able to restore UID , setuid is broken " |
let read_file f = let ic = open_in f in let n = in_channel_length ic in let buf = Bytes . create n in really_input ic buf 0 n ; close_in ic ; Bytes . to_string buf |
let go_daemon ( ) = Lwt_daemon . daemonize ~ syslog : false ( ) |
let init_log vlevel daemon = Lwt_log_core . Section . ( set_level main vlevel ) ; Lwt_log . default := if daemon then Lwt_log . syslog ~ template " ( :$ date ) ( $ level ) ( $ name ) [ ( $ pid ) ] : ( $ message ) " ~ facility ` : Daemon ~ paths [ " :/ dev / log " ; " / var / run / log " ; " / var / run / syslog " ] ( ) else Lwt_log . channel ~ template " ( :$ date ) ( $ level ) : ( $ message ) " ~ close_mode ` : Keep ~ channel : Lwt_io . stdout ( ) |
let uptime_in_sec ( ) = Mtime_clock . elapsed ( ) |> Mtime . Span . to_s |> Int . of_float |
let maybe_gc db now gbcol = let open Lwt in if ( now - gbcol ) >= 60 then Lwt_log . debug " Garbage collecting . . . " >>= fun ( ) -> return ( Dhcp_server . Lease . garbage_collect db ~ now ( : Int32 . of_int now ) , now + 60 ) else return ( db , gbcol ) |
let rec input config db link gbcol = let open Dhcp_server . Input in let open Lwt in Lwt_rawlink . read_packet link >>= fun buf -> let now = uptime_in_sec ( ) in maybe_gc db now gbcol >>= fun ( db , gbcol ) -> let t = match Dhcp_wire . pkt_of_buf buf ( Cstruct . length buf ) with | Error e -> Lwt_log . error e >>= fun ( ) -> return db | Ok pkt -> Lwt_log . debug_f " Received packet : % s " ( Dhcp_wire . pkt_to_string pkt ) >>= fun ( ) -> match ( input_pkt config db pkt ( Int32 . of_int now ) ) with | Silence -> return db | Update db -> return db | Reply ( reply , db ) -> Lwt_rawlink . send_packet link ( Dhcp_wire . buf_of_pkt reply ) >>= fun ( ) -> Lwt_log . debug_f " Sent reply packet : % s " ( Dhcp_wire . pkt_to_string reply ) >>= fun ( ) -> return db | Warning w -> Lwt_log . warning w >>= fun ( ) -> return db | Error e -> Lwt_log . error e >>= fun ( ) -> return db in t >>= fun db -> input config db link gbcol |
let ifname_of_address ip_addr interfaces = let ifnet = List . find ( function _name , cidr -> Ipaddr . V4 . compare ip_addr ( Ipaddr . V4 . Prefix . address cidr ) = 0 ) interfaces in match ifnet with name , _ -> name |
let charruad configfile group pidfile user verbosity daemonize = let open Dhcp_server . Config in let open Dhcp_server . Lease in let open Lwt in init_log ( level_of_string verbosity ) daemonize ; let interfaces = Tuntap . getifaddrs_v4 ( ) in let addresses = List . map ( function name , cidr -> ( Ipaddr . V4 . Prefix . address cidr , Tuntap . get_macaddr name ) ) interfaces in let configtxt = read_file configfile in let db = make_db ( ) in if daemonize then go_daemon ( ) ; Lwt_log . ign_notice " Charrua DHCPD starting " ; let threads = filter_map ( fun addr_tuple -> let addr = fst addr_tuple in let s = Ipaddr . V4 . to_string addr in let config = try Some ( parse configtxt addr_tuple ) with Not_found -> None in match config with | Some config -> Lwt_log . ign_notice_f " Found network for % s " s ; let ifname = ifname_of_address addr interfaces in let link = Lwt_rawlink . ( open_link ~ filter ( : dhcp_server_filter ( ) ) ifname ) in Some ( input config db link ( uptime_in_sec ( ) ) ) | None -> let ( ) = Lwt_log . ign_debug_f " No network found for % s " s in None ) addresses in if List . length threads = 0 then failwith " Could not match any interface address with any network section . " ; let pidc = open_out pidfile in go_safe user group ; Printf . fprintf pidc " % d " ( Unix . getpid ( ) ) ; close_out pidc ; Lwt_main . run ( Lwt . pick threads >>= fun _ -> Lwt_log . notice " Charrua DHCPD exiting " ) |
let cmd = let configfile = Arg . ( value & opt string " / etc / charruad . conf " & info [ " c " ; " config " ] ~ doc " : Configuration file path . " ) in let group = Arg . ( value & opt string " _charruad " & info [ " g " ; " group " ] ~ doc " : Group to run as . " ) in let pidfile = Arg . ( value & opt string " / run / charruad . pid " & info [ " p " ; " pidfile " ] ~ doc " : Pid file path . " ) in let user = Arg . ( value & opt string " _charruad " & info [ " u " ; " user " ] ~ doc " : User to run as . " ) in let verbosity = Arg . ( value & opt string " notice " & info [ " v " ; " verbosity " ] ~ doc " : Log verbosity , warning | notice | debug " ) in let daemonize = Arg . ( value & flag & info [ " D " ; " daemon " ] ~ doc " : Daemonize . " ) in Cmd . v ( Cmd . info " charruad " ~ version " :%% VERSION " %% ~ doc " : Charrua DHCPD " ) Term . ( const charruad $ configfile $ group $ pidfile $ user $ verbosity $ daemonize ) |
let ( ) = exit ( Cmd . eval cmd ) |
let get_element ( ? f = Str . search_forward ) ~ regexp ( ? start = 0 ) line = try f ( Str . regexp regexp ) line start |> ignore ; Str . matched_string line with _ -> " " |
let get_path = get_element ~ regexp " . . [ ] . . :\\/*</* mli " ? |
let get_pos line = let pos = get_element ~ regexp " [ :: 0 - 9 ] " *: line in int_of_string ( if pos <> " " then String . sub pos 1 @@ String . length pos - 2 else pos ) |
let get_info line = let info = get_element ~ regexp " :: . " *$ ~ f : Str . search_backward ~ start ( : String . length line - 1 ) line in String . sub info 1 ( String . length info - 1 ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.