CodeGen.ml 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628
  1. (*
  2. * Copyright (C) 2011-2018 Intel Corporation. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. *
  8. * * Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * * Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in
  12. * the documentation and/or other materials provided with the
  13. * distribution.
  14. * * Neither the name of Intel Corporation nor the names of its
  15. * contributors may be used to endorse or promote products derived
  16. * from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. *
  30. *)
  31. open Printf
  32. open Util (* for failwithf *)
  33. (* --------------------------------------------------------------------
  34. * We first introduce a `parse_enclave_ast' function (see below) to
  35. * parse a value of type `Ast.enclave' into a `enclave_content' record.
  36. * --------------------------------------------------------------------
  37. *)
  38. (* This record type is used to better organize a value of Ast.enclave *)
  39. type enclave_content = {
  40. file_shortnm : string; (* the short name of original EDL file *)
  41. enclave_name : string; (* the normalized C identifier *)
  42. include_list : string list;
  43. import_exprs : Ast.import_decl list;
  44. comp_defs : Ast.composite_type list;
  45. tfunc_decls : Ast.trusted_func list;
  46. ufunc_decls : Ast.untrusted_func list;
  47. }
  48. (* Whether to prefix untrusted proxy with Enclave name *)
  49. let g_use_prefix = ref false
  50. let g_untrusted_dir = ref "."
  51. let g_trusted_dir = ref "."
  52. let empty_ec =
  53. { file_shortnm = "";
  54. enclave_name = "";
  55. include_list = [];
  56. import_exprs = [];
  57. comp_defs = [];
  58. tfunc_decls = [];
  59. ufunc_decls = []; }
  60. let get_tf_fname (tf: Ast.trusted_func) =
  61. tf.Ast.tf_fdecl.Ast.fname
  62. let is_priv_ecall (tf: Ast.trusted_func) =
  63. tf.Ast.tf_is_priv
  64. let get_uf_fname (uf: Ast.untrusted_func) =
  65. uf.Ast.uf_fdecl.Ast.fname
  66. let get_trusted_func_names (ec: enclave_content) =
  67. List.map get_tf_fname ec.tfunc_decls
  68. let get_untrusted_func_names (ec: enclave_content) =
  69. List.map get_uf_fname ec.ufunc_decls
  70. let tf_list_to_fd_list (tfs: Ast.trusted_func list) =
  71. List.map (fun (tf: Ast.trusted_func) -> tf.Ast.tf_fdecl) tfs
  72. let tf_list_to_priv_list (tfs: Ast.trusted_func list) =
  73. List.map is_priv_ecall tfs
  74. (* Get a list of names of all private ECALLs *)
  75. let get_priv_ecall_names (tfs: Ast.trusted_func list) =
  76. List.filter is_priv_ecall tfs |> List.map get_tf_fname
  77. let uf_list_to_fd_list (ufs: Ast.untrusted_func list) =
  78. List.map (fun (uf: Ast.untrusted_func) -> uf.Ast.uf_fdecl) ufs
  79. (* Get a list of names of all allowed ECALLs from `allow(...)' *)
  80. let get_allowed_names (ufs: Ast.untrusted_func list) =
  81. let allow_lists =
  82. List.map (fun (uf: Ast.untrusted_func) -> uf.Ast.uf_allow_list) ufs
  83. in
  84. List.flatten allow_lists |> dedup_list
  85. (* With `parse_enclave_ast', each enclave AST is traversed only once. *)
  86. let parse_enclave_ast (e: Ast.enclave) =
  87. let ac_include_list = ref [] in
  88. let ac_import_exprs = ref [] in
  89. let ac_comp_defs = ref [] in
  90. let ac_tfunc_decls = ref [] in
  91. let ac_ufunc_decls = ref [] in
  92. List.iter (fun ex ->
  93. match ex with
  94. Ast.Composite x -> ac_comp_defs := x :: !ac_comp_defs
  95. | Ast.Include x -> ac_include_list := x :: !ac_include_list
  96. | Ast.Importing x -> ac_import_exprs := x :: !ac_import_exprs
  97. | Ast.Interface xs ->
  98. List.iter (fun ef ->
  99. match ef with
  100. Ast.Trusted f ->
  101. ac_tfunc_decls := f :: !ac_tfunc_decls
  102. | Ast.Untrusted f ->
  103. ac_ufunc_decls := f :: !ac_ufunc_decls) xs
  104. ) e.Ast.eexpr;
  105. { file_shortnm = e.Ast.ename;
  106. enclave_name = Util.to_c_identifier e.Ast.ename;
  107. include_list = List.rev !ac_include_list;
  108. import_exprs = List.rev !ac_import_exprs;
  109. comp_defs = List.rev !ac_comp_defs;
  110. tfunc_decls = List.rev !ac_tfunc_decls;
  111. ufunc_decls = List.rev !ac_ufunc_decls; }
  112. let is_foreign_array (pt: Ast.parameter_type) =
  113. match pt with
  114. Ast.PTVal _ -> false
  115. | Ast.PTPtr(t, a) ->
  116. match t with
  117. Ast.Foreign _ -> a.Ast.pa_isary
  118. | _ -> false
  119. (* A naked function has neither parameters nor return value. *)
  120. let is_naked_func (fd: Ast.func_decl) =
  121. fd.Ast.rtype = Ast.Void && fd.Ast.plist = []
  122. (*
  123. * If user only defined a trusted function w/o neither parameter nor
  124. * return value, the generated trusted bridge will not call any tRTS
  125. * routines. If the real trusted function doesn't call tRTS function
  126. * either (highly possible), then the MSVC linker will not link tRTS
  127. * into the result enclave.
  128. *)
  129. let tbridge_gen_dummy_variable (ec: enclave_content) =
  130. let _dummy_variable =
  131. sprintf "\n#ifdef _MSC_VER\n\
  132. \t/* In case enclave `%s' doesn't call any tRTS function. */\n\
  133. \tvolatile int force_link_trts = sgx_is_within_enclave(NULL, 0);\n\
  134. \t(void) force_link_trts; /* avoid compiler warning */\n\
  135. #endif\n\n" ec.enclave_name
  136. in
  137. if ec.ufunc_decls <> [] then ""
  138. else
  139. if List.for_all (fun tfd -> is_naked_func tfd.Ast.tf_fdecl) ec.tfunc_decls
  140. then _dummy_variable
  141. else ""
  142. (* This function is used to convert Array form into Pointer form.
  143. * e.g.: int array[10][20] => [count = 200] int* array
  144. *
  145. * This function is called when generating proxy/bridge code and
  146. * the marshaling structure.
  147. *)
  148. let conv_array_to_ptr (pd: Ast.pdecl): Ast.pdecl =
  149. let (pt, declr) = pd in
  150. let get_count_attr ilist =
  151. (* XXX: assume the size of each dimension will be > 0. *)
  152. Ast.ANumber (List.fold_left (fun acc i -> acc*i) 1 ilist)
  153. in
  154. match pt with
  155. Ast.PTVal _ -> (pt, declr)
  156. | Ast.PTPtr(aty, pa) ->
  157. if Ast.is_array declr then
  158. let tmp_declr = { declr with Ast.array_dims = [] } in
  159. let tmp_aty = Ast.Ptr aty in
  160. let tmp_cnt = get_count_attr declr.Ast.array_dims in
  161. let tmp_pa = { pa with Ast.pa_size = { Ast.empty_ptr_size with Ast.ps_count = Some tmp_cnt } }
  162. in (Ast.PTPtr(tmp_aty, tmp_pa), tmp_declr)
  163. else (pt, declr)
  164. (* ------------------------------------------------------------------
  165. * Code generation for edge-routines.
  166. * ------------------------------------------------------------------
  167. *)
  168. (* Little functions for naming of a struct and its members etc *)
  169. let retval_name = "retval"
  170. let retval_declr = { Ast.identifier = retval_name; Ast.array_dims = []; }
  171. let eid_name = "eid"
  172. let ms_ptr_name = "pms"
  173. let ms_struct_val = "ms"
  174. let mk_ms_member_name (pname: string) = "ms_" ^ pname
  175. let mk_ms_struct_name (fname: string) = "ms_" ^ fname ^ "_t"
  176. let ms_retval_name = mk_ms_member_name retval_name
  177. let mk_tbridge_name (fname: string) = "sgx_" ^ fname
  178. let mk_parm_accessor name = sprintf "%s->%s" ms_struct_val (mk_ms_member_name name)
  179. let mk_tmp_var name = "_tmp_" ^ name
  180. let mk_len_var name = "_len_" ^ name
  181. let mk_in_var name = "_in_" ^ name
  182. let mk_ocall_table_name enclave_name = "ocall_table_" ^ enclave_name
  183. (* Un-trusted bridge name is prefixed with enclave file short name. *)
  184. let mk_ubridge_name (file_shortnm: string) (funcname: string) =
  185. sprintf "%s_%s" file_shortnm funcname
  186. let mk_ubridge_proto (file_shortnm: string) (funcname: string) =
  187. sprintf "static sgx_status_t SGX_CDECL %s(void* %s)"
  188. (mk_ubridge_name file_shortnm funcname) ms_ptr_name
  189. (* Common macro definitions. *)
  190. let common_macros = "#include <stdlib.h> /* for size_t */\n\n\
  191. #define SGX_CAST(type, item) ((type)(item))\n\n\
  192. #ifdef __cplusplus\n\
  193. extern \"C\" {\n\
  194. #endif\n"
  195. (* Header footer *)
  196. let header_footer = "\n#ifdef __cplusplus\n}\n#endif /* __cplusplus */\n\n#endif\n"
  197. (* Little functions for generating file names. *)
  198. let get_uheader_short_name (file_shortnm: string) = file_shortnm ^ "_u.h"
  199. let get_uheader_name (file_shortnm: string) =
  200. !g_untrusted_dir ^ separator_str ^ (get_uheader_short_name file_shortnm)
  201. let get_usource_name (file_shortnm: string) =
  202. !g_untrusted_dir ^ separator_str ^ file_shortnm ^ "_u.c"
  203. let get_theader_short_name (file_shortnm: string) = file_shortnm ^ "_t.h"
  204. let get_theader_name (file_shortnm: string) =
  205. !g_trusted_dir ^ separator_str ^ (get_theader_short_name file_shortnm)
  206. let get_tsource_name (file_shortnm: string) =
  207. !g_trusted_dir ^ separator_str ^ file_shortnm ^ "_t.c"
  208. (* Construct the string of structure definition *)
  209. let mk_struct_decl (fs: string) (name: string) =
  210. sprintf "typedef struct %s {\n%s} %s;\n" name fs name
  211. (* Construct the string of union definition *)
  212. let mk_union_decl (fs: string) (name: string) =
  213. sprintf "typedef union %s {\n%s} %s;\n" name fs name
  214. (* Generate a definition of enum *)
  215. let mk_enum_def (e: Ast.enum_def) =
  216. let gen_enum_ele_str (ele: Ast.enum_ele) =
  217. let k, v = ele in
  218. match v with
  219. Ast.EnumValNone -> k
  220. | Ast.EnumVal ev -> sprintf "%s = %s" k (Ast.attr_value_to_string ev)
  221. in
  222. let enname = e.Ast.enname in
  223. let enbody = e.Ast.enbody in
  224. let enbody_str =
  225. if enbody = [] then ""
  226. else List.fold_left (fun acc ele ->
  227. acc ^ "\t" ^ gen_enum_ele_str ele ^ ",\n") "" enbody
  228. in
  229. if enname = "" then sprintf "enum {\n%s};\n" enbody_str
  230. else sprintf "typedef enum %s {\n%s} %s;\n" enname enbody_str enname
  231. let get_array_dims (ns: int list) =
  232. (* Get the array declaration from a list of array dimensions.
  233. * Empty `ns' indicates the corresponding declarator is a simple identifier.
  234. * Element of value -1 means that user does not specify the dimension size.
  235. *)
  236. let get_dim n = if n = -1 then "[]" else sprintf "[%d]" n
  237. in
  238. if ns = [] then ""
  239. else List.fold_left (fun acc n -> acc ^ get_dim n) "" ns
  240. let get_typed_declr_str (ty: Ast.atype) (declr: Ast.declarator) =
  241. let tystr = Ast.get_tystr ty in
  242. let dmstr = get_array_dims declr.Ast.array_dims in
  243. sprintf "%s %s%s" tystr declr.Ast.identifier dmstr
  244. (* Construct a member declaration string *)
  245. let mk_member_decl (ty: Ast.atype) (declr: Ast.declarator) =
  246. sprintf "\t%s;\n" (get_typed_declr_str ty declr)
  247. (* Note that, for a foreign array type `foo_array_t' we will generate
  248. * foo_array_t* ms_field;
  249. * in the marshaling data structure to keep the pass-by-address scheme
  250. * as in the C programming language.
  251. *)
  252. let mk_ms_member_decl (pt: Ast.parameter_type) (declr: Ast.declarator) =
  253. let aty = Ast.get_param_atype pt in
  254. let tystr = Ast.get_tystr aty in
  255. let ptr = if is_foreign_array pt then "* " else "" in
  256. let field = mk_ms_member_name declr.Ast.identifier in
  257. let dmstr = get_array_dims declr.Ast.array_dims in
  258. sprintf "\t%s%s %s%s;\n" tystr ptr field dmstr
  259. (* Generate data structure definition *)
  260. let gen_comp_def (st: Ast.composite_type) =
  261. let gen_member_list mlist =
  262. List.fold_left (fun acc (ty, declr) ->
  263. acc ^ mk_member_decl ty declr) "" mlist
  264. in
  265. match st with
  266. Ast.StructDef s -> mk_struct_decl (gen_member_list s.Ast.mlist) s.Ast.sname
  267. | Ast.UnionDef u -> mk_union_decl (gen_member_list u.Ast.mlist) u.Ast.sname
  268. | Ast.EnumDef e -> mk_enum_def e
  269. (* Generate a list of '#include' *)
  270. let gen_include_list (xs: string list) =
  271. List.fold_left (fun acc s -> acc ^ sprintf "#include \"%s\"\n" s) "" xs
  272. (* Get the type string from 'parameter_type' *)
  273. let get_param_tystr (pt: Ast.parameter_type) =
  274. Ast.get_tystr (Ast.get_param_atype pt)
  275. (* Generate marshaling structure definition *)
  276. let gen_marshal_struct (fd: Ast.func_decl) (errno: string) =
  277. let member_list_str = errno ^
  278. let new_param_list = List.map conv_array_to_ptr fd.Ast.plist in
  279. List.fold_left (fun acc (pt, declr) ->
  280. acc ^ mk_ms_member_decl pt declr) "" new_param_list in
  281. let struct_name = mk_ms_struct_name fd.Ast.fname in
  282. match fd.Ast.rtype with
  283. (* A function w/o return value and parameters doesn't need
  284. a marshaling struct. *)
  285. Ast.Void -> if fd.Ast.plist = [] && errno = "" then ""
  286. else mk_struct_decl member_list_str struct_name
  287. | _ -> let rv_str = mk_ms_member_decl (Ast.PTVal fd.Ast.rtype) retval_declr
  288. in mk_struct_decl (rv_str ^ member_list_str) struct_name
  289. let gen_ecall_marshal_struct (tf: Ast.trusted_func) =
  290. gen_marshal_struct tf.Ast.tf_fdecl ""
  291. let gen_ocall_marshal_struct (uf: Ast.untrusted_func) =
  292. let errno_decl = if uf.Ast.uf_propagate_errno then "\tint ocall_errno;\n" else "" in
  293. gen_marshal_struct uf.Ast.uf_fdecl errno_decl
  294. (* Check whether given parameter is `const' specified. *)
  295. let is_const_ptr (pt: Ast.parameter_type) =
  296. let aty = Ast.get_param_atype pt in
  297. match pt with
  298. Ast.PTVal _ -> false
  299. | Ast.PTPtr(_, pa) ->
  300. if not pa.Ast.pa_rdonly then false
  301. else
  302. match aty with
  303. Ast.Foreign _ -> false
  304. | _ -> true
  305. (* Generate parameter representation. *)
  306. let gen_parm_str (p: Ast.pdecl) =
  307. let (pt, (declr : Ast.declarator)) = p in
  308. let aty = Ast.get_param_atype pt in
  309. let str = get_typed_declr_str aty declr in
  310. if is_const_ptr pt then "const " ^ str else str
  311. (* Generate parameter representation of return value. *)
  312. let gen_parm_retval (rt: Ast.atype) =
  313. if rt = Ast.Void then ""
  314. else Ast.get_tystr rt ^ "* " ^ retval_name
  315. (* ---------------------------------------------------------------------- *)
  316. (* `gen_ecall_table' is used to generate ECALL table with the following form:
  317. SGX_EXTERNC const struct {
  318. size_t nr_ecall; /* number of ECALLs */
  319. struct {
  320. void *ecall_addr;
  321. uint8_t is_priv;
  322. } ecall_table [nr_ecall];
  323. } g_ecall_table = {
  324. 2, { {sgx_foo, 1}, {sgx_bar, 0} }
  325. };
  326. *)
  327. let gen_ecall_table (tfs: Ast.trusted_func list) =
  328. let ecall_table_name = "g_ecall_table" in
  329. let ecall_table_size = List.length tfs in
  330. let trusted_fds = tf_list_to_fd_list tfs in
  331. let priv_bits = tf_list_to_priv_list tfs in
  332. let tbridge_names = List.map (fun (fd: Ast.func_decl) ->
  333. mk_tbridge_name fd.Ast.fname) trusted_fds in
  334. let ecall_table =
  335. let bool_to_int b = if b then 1 else 0 in
  336. let inner_table =
  337. List.fold_left2 (fun acc s b ->
  338. sprintf "%s\t\t{(void*)(uintptr_t)%s, %d},\n" acc s (bool_to_int b)) "" tbridge_names priv_bits
  339. in "\t{\n" ^ inner_table ^ "\t}\n"
  340. in
  341. sprintf "SGX_EXTERNC const struct {\n\
  342. \tsize_t nr_ecall;\n\
  343. \tstruct {void* ecall_addr; uint8_t is_priv;} ecall_table[%d];\n\
  344. } %s = {\n\
  345. \t%d,\n\
  346. %s};\n" ecall_table_size
  347. ecall_table_name
  348. ecall_table_size
  349. (if ecall_table_size = 0 then "" else ecall_table)
  350. (* `gen_entry_table' is used to generate Dynamic Entry Table with the form:
  351. SGX_EXTERNC const struct {
  352. /* number of OCALLs (number of ECALLs can be found in ECALL table) */
  353. size_t nr_ocall;
  354. /* entry_table[m][n] = 1 iff. ECALL n is allowed in the OCALL m. */
  355. uint8_t entry_table[NR_OCALL][NR_ECALL];
  356. } g_dyn_entry_table = {
  357. 3, {{0, 0}, {0, 1}, {1, 0}}
  358. };
  359. *)
  360. let gen_entry_table (ec: enclave_content) =
  361. let dyn_entry_table_name = "g_dyn_entry_table" in
  362. let ocall_table_size = List.length ec.ufunc_decls in
  363. let trusted_func_names = get_trusted_func_names ec in
  364. let ecall_table_size = List.length trusted_func_names in
  365. let get_entry_array (allowed_ecalls: string list) =
  366. List.fold_left (fun acc name ->
  367. acc ^ (if List.exists (fun x -> x=name) allowed_ecalls
  368. then "1"
  369. else "0") ^ ", ") "" trusted_func_names in
  370. let entry_table =
  371. let inner_table =
  372. List.fold_left (fun acc (uf: Ast.untrusted_func) ->
  373. let entry_array = get_entry_array uf.Ast.uf_allow_list
  374. in acc ^ "\t\t{" ^ entry_array ^ "},\n") "" ec.ufunc_decls
  375. in
  376. "\t{\n" ^ inner_table ^ "\t}\n"
  377. in
  378. (* Generate dynamic entry table iff. both sgx_ecall/ocall_table_size > 0 *)
  379. let gen_table_p = (ecall_table_size > 0) && (ocall_table_size > 0) in
  380. (* When NR_ECALL is 0, or NR_OCALL is 0, there will be no entry table field. *)
  381. let entry_table_field =
  382. if gen_table_p then
  383. sprintf "\tuint8_t entry_table[%d][%d];\n" ocall_table_size ecall_table_size
  384. else
  385. ""
  386. in
  387. sprintf "SGX_EXTERNC const struct {\n\
  388. \tsize_t nr_ocall;\n%s\
  389. } %s = {\n\
  390. \t%d,\n\
  391. %s};\n" entry_table_field
  392. dyn_entry_table_name
  393. ocall_table_size
  394. (if gen_table_p then entry_table else "")
  395. (* ---------------------------------------------------------------------- *)
  396. (* Generate the function prototype for untrusted proxy in COM style.
  397. * For example, un-trusted functions
  398. * int foo(double d);
  399. * void bar(float f);
  400. *
  401. * will have an untrusted proxy like below:
  402. * sgx_status_t foo(int* retval, double d);
  403. * sgx_status_t bar(float f);
  404. *)
  405. let gen_tproxy_proto (fd: Ast.func_decl) =
  406. let parm_list =
  407. match fd.Ast.plist with
  408. [] -> ""
  409. | x :: xs ->
  410. List.fold_left (fun acc pd ->
  411. acc ^ ", " ^ gen_parm_str pd) (gen_parm_str x) xs
  412. in
  413. let retval_parm_str = gen_parm_retval fd.Ast.rtype in
  414. if fd.Ast.plist = [] then
  415. sprintf "sgx_status_t SGX_CDECL %s(%s)" fd.Ast.fname retval_parm_str
  416. else if fd.Ast.rtype = Ast.Void then
  417. sprintf "sgx_status_t SGX_CDECL %s(%s)" fd.Ast.fname parm_list
  418. else
  419. sprintf "sgx_status_t SGX_CDECL %s(%s, %s)" fd.Ast.fname retval_parm_str parm_list
  420. (* Generate the function prototype for untrusted proxy in COM style.
  421. * For example, trusted functions
  422. * int foo(double d);
  423. * void bar(float f);
  424. *
  425. * will have an untrusted proxy like below:
  426. * sgx_status_t foo(sgx_enclave_id_t eid, int* retval, double d);
  427. * sgx_status_t foo(sgx_enclave_id_t eid, float f);
  428. *
  429. * When `g_use_prefix' is true, the untrusted proxy name is prefixed
  430. * with the `prefix' parameter.
  431. *
  432. *)
  433. let gen_uproxy_com_proto (fd: Ast.func_decl) (prefix: string) =
  434. let retval_parm_str = gen_parm_retval fd.Ast.rtype in
  435. let eid_parm_str =
  436. if fd.Ast.rtype = Ast.Void then sprintf "(sgx_enclave_id_t %s" eid_name
  437. else sprintf "(sgx_enclave_id_t %s, " eid_name in
  438. let parm_list =
  439. List.fold_left (fun acc pd -> acc ^ ", " ^ gen_parm_str pd)
  440. retval_parm_str fd.Ast.plist in
  441. let fname =
  442. if !g_use_prefix then sprintf "%s_%s" prefix fd.Ast.fname
  443. else fd.Ast.fname
  444. in "sgx_status_t " ^ fname ^ eid_parm_str ^ parm_list ^ ")"
  445. let get_ret_tystr (fd: Ast.func_decl) = Ast.get_tystr fd.Ast.rtype
  446. let get_plist_str (fd: Ast.func_decl) =
  447. if fd.Ast.plist = [] then ""
  448. else List.fold_left (fun acc pd -> acc ^ ", " ^ gen_parm_str pd)
  449. (gen_parm_str (List.hd fd.Ast.plist))
  450. (List.tl fd.Ast.plist)
  451. (* Generate the function prototype as is. *)
  452. let gen_func_proto (fd: Ast.func_decl) =
  453. let ret_tystr = get_ret_tystr fd in
  454. let plist_str = get_plist_str fd in
  455. sprintf "%s %s(%s)" ret_tystr fd.Ast.fname plist_str
  456. (* Generate prototypes for untrusted function. *)
  457. let gen_ufunc_proto (uf: Ast.untrusted_func) =
  458. let dllimport = if uf.Ast.uf_fattr.Ast.fa_dllimport then "SGX_DLLIMPORT " else "" in
  459. let ret_tystr = get_ret_tystr uf.Ast.uf_fdecl in
  460. let cconv_str = "SGX_" ^ Ast.get_call_conv_str uf.Ast.uf_fattr.Ast.fa_convention in
  461. let func_name = uf.Ast.uf_fdecl.Ast.fname in
  462. let plist_str = get_plist_str uf.Ast.uf_fdecl in
  463. sprintf "%s%s SGX_UBRIDGE(%s, %s, (%s))"
  464. dllimport ret_tystr cconv_str func_name plist_str
  465. (* The preemble contains common include expressions. *)
  466. let gen_uheader_preemble (guard: string) (inclist: string)=
  467. let grd_hdr = sprintf "#ifndef %s\n#define %s\n\n" guard guard in
  468. let inc_exp = "#include <stdint.h>\n\
  469. #include <wchar.h>\n\
  470. #include <stddef.h>\n\
  471. #include <string.h>\n\
  472. #include \"sgx_edger8r.h\" /* for sgx_satus_t etc. */\n" in
  473. grd_hdr ^ inc_exp ^ "\n" ^ inclist ^ "\n" ^ common_macros
  474. let ms_writer out_chan ec =
  475. let ms_struct_ecall = List.map gen_ecall_marshal_struct ec.tfunc_decls in
  476. let ms_struct_ocall = List.map gen_ocall_marshal_struct ec.ufunc_decls in
  477. let output_struct s =
  478. match s with
  479. "" -> s
  480. | _ -> sprintf "%s\n" s
  481. in
  482. List.iter (fun s -> output_string out_chan (output_struct s)) ms_struct_ecall;
  483. List.iter (fun s -> output_string out_chan (output_struct s)) ms_struct_ocall
  484. (* Generate untrusted header for enclave *)
  485. let gen_untrusted_header (ec: enclave_content) =
  486. let header_fname = get_uheader_name ec.file_shortnm in
  487. let guard_macro = sprintf "%s_U_H__" (String.uppercase ec.enclave_name) in
  488. let preemble_code =
  489. let include_list = gen_include_list (ec.include_list @ !untrusted_headers) in
  490. gen_uheader_preemble guard_macro include_list
  491. in
  492. let comp_def_list = List.map gen_comp_def ec.comp_defs in
  493. let func_proto_ufunc = List.map gen_ufunc_proto ec.ufunc_decls in
  494. let uproxy_com_proto =
  495. List.map (fun (tf: Ast.trusted_func) ->
  496. gen_uproxy_com_proto tf.Ast.tf_fdecl ec.enclave_name)
  497. ec.tfunc_decls
  498. in
  499. let out_chan = open_out header_fname in
  500. output_string out_chan (preemble_code ^ "\n");
  501. List.iter (fun s -> output_string out_chan (s ^ "\n")) comp_def_list;
  502. List.iter (fun s -> output_string out_chan (s ^ ";\n")) func_proto_ufunc;
  503. output_string out_chan "\n";
  504. List.iter (fun s -> output_string out_chan (s ^ ";\n")) uproxy_com_proto;
  505. output_string out_chan header_footer;
  506. close_out out_chan
  507. (* It generates preemble for trusted header file. *)
  508. let gen_theader_preemble (guard: string) (inclist: string) =
  509. let grd_hdr = sprintf "#ifndef %s\n#define %s\n\n" guard guard in
  510. let inc_exp = "#include <stdint.h>\n\
  511. #include <wchar.h>\n\
  512. #include <stddef.h>\n\
  513. #include \"sgx_edger8r.h\" /* for sgx_ocall etc. */\n\n" in
  514. grd_hdr ^ inc_exp ^ inclist ^ "\n" ^ common_macros
  515. (* Generate function prototype for functions used by `sizefunc' attribute. *)
  516. let gen_sizefunc_proto out_chan (ec: enclave_content) =
  517. let tfunc_decls = tf_list_to_fd_list ec.tfunc_decls in
  518. let ufunc_decls = uf_list_to_fd_list ec.ufunc_decls in
  519. let dict = Hashtbl.create 4 in
  520. let get_sizefunc_proto s =
  521. let (pt, ns) = Hashtbl.find dict s in
  522. let tmpdeclr = { Ast.identifier = "val"; Ast.array_dims = ns; } in
  523. sprintf "size_t %s(const %s);\n" s (get_typed_declr_str pt tmpdeclr)
  524. in
  525. let add_item (fname: string) (ty: Ast.atype * int list) =
  526. try
  527. let v = Hashtbl.find dict fname
  528. in
  529. if v <> ty then
  530. failwithf "`%s' requires different parameter types" fname
  531. with Not_found -> Hashtbl.add dict fname ty
  532. in
  533. let fill_dict (pd: Ast.pdecl) =
  534. let (pt, declr) = pd in
  535. match pt with
  536. Ast.PTVal _ -> ()
  537. | Ast.PTPtr(aty, pattr) ->
  538. match pattr.Ast.pa_size.Ast.ps_sizefunc with
  539. Some s -> add_item s (aty, declr.Ast.array_dims)
  540. | _ -> ()
  541. in
  542. List.iter (fun (fd: Ast.func_decl) ->
  543. List.iter fill_dict fd.Ast.plist) (tfunc_decls @ ufunc_decls);
  544. Hashtbl.iter (fun x y ->
  545. output_string out_chan (get_sizefunc_proto x)) dict;
  546. output_string out_chan "\n"
  547. (* Generate trusted header for enclave *)
  548. let gen_trusted_header (ec: enclave_content) =
  549. let header_fname = get_theader_name ec.file_shortnm in
  550. let guard_macro = sprintf "%s_T_H__" (String.uppercase ec.enclave_name) in
  551. let guard_code =
  552. let include_list = gen_include_list (ec.include_list @ !trusted_headers) in
  553. gen_theader_preemble guard_macro include_list in
  554. let comp_def_list = List.map gen_comp_def ec.comp_defs in
  555. let func_proto_list = List.map gen_func_proto (tf_list_to_fd_list ec.tfunc_decls) in
  556. let func_tproxy_list= List.map gen_tproxy_proto (uf_list_to_fd_list ec.ufunc_decls) in
  557. let out_chan = open_out header_fname in
  558. output_string out_chan (guard_code ^ "\n");
  559. List.iter (fun s -> output_string out_chan (s ^ "\n")) comp_def_list;
  560. gen_sizefunc_proto out_chan ec;
  561. List.iter (fun s -> output_string out_chan (s ^ ";\n")) func_proto_list;
  562. output_string out_chan "\n";
  563. List.iter (fun s -> output_string out_chan (s ^ ";\n")) func_tproxy_list;
  564. output_string out_chan header_footer;
  565. close_out out_chan
  566. (* It generates function invocation expression. *)
  567. let mk_parm_name_raw (pt: Ast.parameter_type) (declr: Ast.declarator) =
  568. let cast_expr =
  569. if Ast.is_array declr && List.length declr.Ast.array_dims > 1
  570. then
  571. let tystr = get_param_tystr pt in
  572. let dims = get_array_dims (List.tl declr.Ast.array_dims) in
  573. sprintf "(%s (*)%s)" tystr dims
  574. else ""
  575. in
  576. cast_expr ^ mk_parm_accessor declr.Ast.identifier
  577. (* We passed foreign array `foo_array_t foo' as `&foo[0]', thus we
  578. * need to get back `foo' by '* array_ptr' where
  579. * array_ptr = &foo[0]
  580. *)
  581. let add_foreign_array_ptrref
  582. (f: Ast.parameter_type -> Ast.declarator -> string)
  583. (pt: Ast.parameter_type)
  584. (declr: Ast.declarator) =
  585. let arg = f pt declr in
  586. if is_foreign_array pt
  587. then sprintf "(%s != NULL) ? (*%s) : NULL" arg arg
  588. else arg
  589. let mk_parm_name_ubridge (pt: Ast.parameter_type) (declr: Ast.declarator) =
  590. add_foreign_array_ptrref mk_parm_name_raw pt declr
  591. let mk_parm_name_ext (pt: Ast.parameter_type) (declr: Ast.declarator) =
  592. let name = declr.Ast.identifier in
  593. match pt with
  594. Ast.PTVal _ -> mk_parm_name_raw pt declr
  595. | Ast.PTPtr (_, attr) ->
  596. match attr.Ast.pa_direction with
  597. | Ast.PtrNoDirection -> mk_parm_name_raw pt declr
  598. | _ -> mk_in_var name
  599. let gen_func_invoking (fd: Ast.func_decl)
  600. (mk_parm_name: Ast.parameter_type -> Ast.declarator -> string) =
  601. let gen_parm_str pt declr =
  602. let parm_name = mk_parm_name pt declr in
  603. let tystr = get_param_tystr pt in
  604. if is_const_ptr pt then sprintf "(const %s)%s" tystr parm_name else parm_name
  605. in
  606. match fd.Ast.plist with
  607. [] -> sprintf "%s();" fd.Ast.fname
  608. | (pt, (declr : Ast.declarator)) :: ps ->
  609. sprintf "%s(%s);"
  610. fd.Ast.fname
  611. (let p0 = gen_parm_str pt declr in
  612. List.fold_left (fun acc (pty, dlr) ->
  613. acc ^ ", " ^ gen_parm_str pty dlr) p0 ps)
  614. (* Generate untrusted bridge code for a given untrusted function. *)
  615. let gen_func_ubridge (file_shortnm: string) (ufunc: Ast.untrusted_func) =
  616. let fd = ufunc.Ast.uf_fdecl in
  617. let propagate_errno = ufunc.Ast.uf_propagate_errno in
  618. let func_open = sprintf "%s\n{\n" (mk_ubridge_proto file_shortnm fd.Ast.fname) in
  619. let func_close = "\treturn SGX_SUCCESS;\n}\n" in
  620. let set_errno = if propagate_errno then "\tms->ocall_errno = errno;" else "" in
  621. let ms_struct_name = mk_ms_struct_name fd.Ast.fname in
  622. let declare_ms_ptr = sprintf "%s* %s = SGX_CAST(%s*, %s);"
  623. ms_struct_name
  624. ms_struct_val
  625. ms_struct_name
  626. ms_ptr_name in
  627. let call_with_pms =
  628. let invoke_func = gen_func_invoking fd mk_parm_name_ubridge in
  629. if fd.Ast.rtype = Ast.Void then invoke_func
  630. else sprintf "%s = %s" (mk_parm_accessor retval_name) invoke_func
  631. in
  632. if (is_naked_func fd) && (propagate_errno = false) then
  633. let check_pms =
  634. sprintf "if (%s != NULL) return SGX_ERROR_INVALID_PARAMETER;" ms_ptr_name
  635. in
  636. sprintf "%s\t%s\n\t%s\n%s" func_open check_pms call_with_pms func_close
  637. else
  638. sprintf "%s\t%s\n\t%s\n%s\n%s" func_open declare_ms_ptr call_with_pms set_errno func_close
  639. let fill_ms_field (isptr: bool) (pd: Ast.pdecl) =
  640. let accessor = if isptr then "->" else "." in
  641. let (pt, declr) = pd in
  642. let param_name = declr.Ast.identifier in
  643. let ms_member_name = mk_ms_member_name param_name in
  644. let assignment_str (use_cast: bool) (aty: Ast.atype) =
  645. let cast_str = if use_cast then sprintf "(%s)" (Ast.get_tystr aty) else ""
  646. in
  647. sprintf "%s%s%s = %s%s;" ms_struct_val accessor ms_member_name cast_str param_name
  648. in
  649. let gen_setup_foreign_array aty =
  650. sprintf "%s%s%s = (%s *)&%s[0];"
  651. ms_struct_val accessor ms_member_name (Ast.get_tystr aty) param_name
  652. in
  653. if declr.Ast.array_dims = [] then
  654. match pt with
  655. Ast.PTVal(aty) -> assignment_str false aty
  656. | Ast.PTPtr(aty, pattr) ->
  657. if pattr.Ast.pa_isary
  658. then gen_setup_foreign_array aty
  659. else
  660. if pattr.Ast.pa_rdonly then assignment_str true aty
  661. else assignment_str false aty
  662. else
  663. (* Arrays are passed by address. *)
  664. let tystr = Ast.get_tystr (Ast.Ptr (Ast.get_param_atype pt)) in
  665. sprintf "%s%s%s = (%s)%s;" ms_struct_val accessor ms_member_name tystr param_name
  666. (* Generate untrusted proxy code for a given trusted function. *)
  667. let gen_func_uproxy (fd: Ast.func_decl) (idx: int) (ec: enclave_content) =
  668. let func_open =
  669. gen_uproxy_com_proto fd ec.enclave_name ^
  670. "\n{\n\tsgx_status_t status;\n"
  671. in
  672. let func_close = "\treturn status;\n}\n" in
  673. let ocall_table_name = mk_ocall_table_name ec.enclave_name in
  674. let ms_struct_name = mk_ms_struct_name fd.Ast.fname in
  675. let declare_ms_expr = sprintf "%s %s;" ms_struct_name ms_struct_val in
  676. let ocall_table_ptr =
  677. sprintf "&%s" ocall_table_name in
  678. (* Normal case - do ECALL with marshaling structure*)
  679. let ecall_with_ms = sprintf "status = sgx_ecall(%s, %d, %s, &%s);"
  680. eid_name idx ocall_table_ptr ms_struct_val in
  681. (* Rare case - the trusted function doesn't have parameter nor return value.
  682. * In this situation, no marshaling structure is required - passing in NULL.
  683. *)
  684. let ecall_null = sprintf "status = sgx_ecall(%s, %d, %s, NULL);"
  685. eid_name idx ocall_table_ptr
  686. in
  687. let update_retval = sprintf "if (status == SGX_SUCCESS && %s) *%s = %s.%s;"
  688. retval_name retval_name ms_struct_val ms_retval_name in
  689. let func_body = ref [] in
  690. if is_naked_func fd then
  691. sprintf "%s\t%s\n%s" func_open ecall_null func_close
  692. else
  693. begin
  694. func_body := declare_ms_expr :: !func_body;
  695. List.iter (fun pd -> func_body := fill_ms_field false pd :: !func_body) fd.Ast.plist;
  696. func_body := ecall_with_ms :: !func_body;
  697. if fd.Ast.rtype <> Ast.Void then func_body := update_retval :: !func_body;
  698. List.fold_left (fun acc s -> acc ^ "\t" ^ s ^ "\n") func_open (List.rev !func_body) ^ func_close
  699. end
  700. (* Generate an expression to check the pointers. *)
  701. let mk_check_ptr (name: string) (lenvar: string) =
  702. let checker = "CHECK_UNIQUE_POINTER"
  703. in sprintf "\t%s(%s, %s);\n" checker name lenvar
  704. (* Pointer to marshaling structure should never be NULL. *)
  705. let mk_check_pms (fname: string) =
  706. let lenvar = sprintf "sizeof(%s)" (mk_ms_struct_name fname)
  707. in sprintf "\t%s(%s, %s);\n" "CHECK_REF_POINTER" ms_ptr_name lenvar
  708. (* Generate code to get the size of the pointer. *)
  709. let gen_ptr_size (ty: Ast.atype) (pattr: Ast.ptr_attr) (name: string) (get_parm: string -> string) =
  710. let len_var = mk_len_var name in
  711. let parm_name = get_parm name in
  712. let mk_len_size v =
  713. match v with
  714. Ast.AString s -> get_parm s
  715. | Ast.ANumber n -> sprintf "%d" n in
  716. let mk_len_count v size_str =
  717. match v with
  718. Ast.AString s -> sprintf "%s * %s" (get_parm s) size_str
  719. | Ast.ANumber n -> sprintf "%d * %s" n size_str in
  720. let mk_len_sizefunc s = sprintf "((%s) ? %s(%s) : 0)" parm_name s parm_name in
  721. (* Note, during the parsing stage, we already eliminated the case that
  722. * user specified both 'size' and 'sizefunc' attribute.
  723. *)
  724. let do_attribute (pattr: Ast.ptr_attr) =
  725. let do_ps_attribute (sattr: Ast.ptr_size) =
  726. let size_str =
  727. match sattr.Ast.ps_size with
  728. Some a -> mk_len_size a
  729. | None ->
  730. match sattr.Ast.ps_sizefunc with
  731. None -> sprintf "sizeof(*%s)" parm_name
  732. | Some a -> mk_len_sizefunc a
  733. in
  734. match sattr.Ast.ps_count with
  735. None -> size_str
  736. | Some a -> mk_len_count a size_str
  737. in
  738. if pattr.Ast.pa_isstr then
  739. sprintf "%s ? strlen(%s) + 1 : 0" parm_name parm_name
  740. else if pattr.Ast.pa_iswstr then
  741. sprintf "%s ? (wcslen(%s) + 1) * sizeof(wchar_t) : 0" parm_name parm_name
  742. else
  743. do_ps_attribute pattr.Ast.pa_size
  744. in
  745. sprintf "size_t %s = %s;\n"
  746. len_var
  747. (if pattr.Ast.pa_isary
  748. then sprintf "sizeof(%s)" (Ast.get_tystr ty)
  749. else do_attribute pattr)
  750. (* Find the data type of a parameter. *)
  751. let find_param_type (name: string) (plist: Ast.pdecl list) =
  752. try
  753. let (pt, _) = List.find (fun (pd: Ast.pdecl) ->
  754. let (pt, declr) = pd
  755. in declr.Ast.identifier = name) plist
  756. in get_param_tystr pt
  757. with
  758. Not_found -> failwithf "parameter `%s' not found." name
  759. (* Generate code to check the length of buffers. *)
  760. let gen_check_tbridge_length_overflow (plist: Ast.pdecl list) =
  761. let gen_check_length (ty: Ast.atype) (attr: Ast.ptr_attr) (declr: Ast.declarator) =
  762. let name = declr.Ast.identifier in
  763. let tmp_ptr_name= mk_tmp_var name in
  764. let mk_len_size v =
  765. match v with
  766. Ast.AString s -> mk_tmp_var s
  767. | Ast.ANumber n -> sprintf "%d" n in
  768. let mk_len_sizefunc s = sprintf "((%s) ? %s(%s) : 0)" tmp_ptr_name s tmp_ptr_name in
  769. let gen_check_overflow cnt size_str =
  770. let if_statement =
  771. match cnt with
  772. Ast.AString s -> sprintf "\tif (%s != 0 &&\n\t\t(size_t)%s > (SIZE_MAX / %s)) {\n" size_str (mk_tmp_var s) size_str
  773. | Ast.ANumber n -> sprintf "\tif (%s != 0 &&\n\t\t%d > (SIZE_MAX / %s)) {\n" size_str n size_str
  774. in
  775. sprintf "%s\t\tstatus = SGX_ERROR_INVALID_PARAMETER;\n\t\tgoto err;\n\t}" if_statement
  776. in
  777. let size_str =
  778. match attr.Ast.pa_size.Ast.ps_size with
  779. Some a -> mk_len_size a
  780. | None ->
  781. match attr.Ast.pa_size.Ast.ps_sizefunc with
  782. None -> sprintf "sizeof(*%s)" tmp_ptr_name
  783. | Some a -> mk_len_sizefunc a
  784. in
  785. match attr.Ast.pa_size.Ast.ps_count with
  786. None -> ""
  787. | Some a -> sprintf "%s\n\n" (gen_check_overflow a size_str)
  788. in
  789. List.fold_left
  790. (fun acc (pty, declr) ->
  791. match pty with
  792. Ast.PTVal _ -> acc
  793. | Ast.PTPtr(ty, attr) -> acc ^ gen_check_length ty attr declr) "" plist
  794. (* Generate code to check all function parameters which are pointers. *)
  795. let gen_check_tbridge_ptr_parms (plist: Ast.pdecl list) =
  796. let gen_check_ptr (ty: Ast.atype) (pattr: Ast.ptr_attr) (declr: Ast.declarator) =
  797. if not pattr.Ast.pa_chkptr then ""
  798. else
  799. let name = declr.Ast.identifier in
  800. let len_var = mk_len_var name in
  801. let parm_name = mk_tmp_var name in
  802. if pattr.Ast.pa_chkptr
  803. then mk_check_ptr parm_name len_var
  804. else ""
  805. in
  806. let new_param_list = List.map conv_array_to_ptr plist
  807. in
  808. List.fold_left
  809. (fun acc (pty, declr) ->
  810. match pty with
  811. Ast.PTVal _ -> acc
  812. | Ast.PTPtr(ty, attr) -> acc ^ gen_check_ptr ty attr declr) "" new_param_list
  813. (* If a foreign type is a readonly pointer, we cast it to 'void*' for memcpy() and free() *)
  814. let mk_in_ptr_dst_name (rdonly: bool) (ptr_name: string) =
  815. if rdonly then "(void*)" ^ ptr_name
  816. else ptr_name
  817. (* Generate the code to handle function pointer parameter direction,
  818. * which is to be inserted before actually calling the trusted function.
  819. *)
  820. let gen_parm_ptr_direction_pre (plist: Ast.pdecl list) =
  821. let clone_in_ptr (ty: Ast.atype) (attr: Ast.ptr_attr) (declr: Ast.declarator) =
  822. let name = declr.Ast.identifier in
  823. let is_ary = (Ast.is_array declr || attr.Ast.pa_isary) in
  824. let in_ptr_name = mk_in_var name in
  825. let in_ptr_type = sprintf "%s%s" (Ast.get_tystr ty) (if is_ary then "*" else "") in
  826. let len_var = mk_len_var name in
  827. let in_ptr_dst_name = mk_in_ptr_dst_name attr.Ast.pa_rdonly in_ptr_name in
  828. let tmp_ptr_name= mk_tmp_var name in
  829. let mk_len_count v =
  830. match v with
  831. None -> ""
  832. |Some a ->
  833. match a with
  834. Ast.AString s -> sprintf "_tmp_%s * " s
  835. | Ast.ANumber n -> sprintf "%d * " n
  836. in
  837. let check_sizefunc_with_cnt_ptr v fn =
  838. sprintf "\t\t/* check whether the pointer is modified. */\n\
  839. \t\tif (%s%s(%s) != %s) {\n\
  840. \t\t\tstatus = SGX_ERROR_INVALID_PARAMETER;\n\
  841. \t\t\tgoto err;\n\
  842. \t\t}\n\n\
  843. \t\t//\n\t\t// fence after final sizefunc check\n\t\t//\n\t\t__builtin_ia32_lfence();\n\n" (mk_len_count v) fn in_ptr_name len_var
  844. in
  845. let malloc_and_copy pre_indent =
  846. match attr.Ast.pa_direction with
  847. Ast.PtrIn | Ast.PtrInOut ->
  848. let code_template = [
  849. sprintf "if (%s != NULL && %s != 0) {" tmp_ptr_name len_var;
  850. sprintf "\t%s = (%s)malloc(%s);" in_ptr_name in_ptr_type len_var;
  851. sprintf "\tif (%s == NULL) {" in_ptr_name;
  852. "\t\tstatus = SGX_ERROR_OUT_OF_MEMORY;";
  853. "\t\tgoto err;";
  854. "\t}\n";
  855. sprintf "\tmemcpy(%s, %s, %s);" in_ptr_dst_name tmp_ptr_name len_var;
  856. ]
  857. in
  858. let s1 = List.fold_left (fun acc s -> acc ^ pre_indent ^ s ^ "\n") "" code_template in
  859. let s2 =
  860. if attr.Ast.pa_isstr
  861. then sprintf "%s\t\t%s[%s - 1] = '\\0';\n" s1 in_ptr_name len_var
  862. else if attr.Ast.pa_iswstr
  863. then sprintf "%s\t\t%s[(%s - sizeof(wchar_t))/sizeof(wchar_t)] = (wchar_t)0;\n" s1 in_ptr_name len_var
  864. else s1 in
  865. let s3 =
  866. match attr.Ast.pa_size.Ast.ps_sizefunc with
  867. None -> s2
  868. | Some s -> sprintf "%s\n%s\n" s2 (check_sizefunc_with_cnt_ptr attr.Ast.pa_size.Ast.ps_count s)
  869. in sprintf "%s\t}\n" s3
  870. | Ast.PtrOut ->
  871. let code_template = [
  872. sprintf "if (%s != NULL && %s != 0) {" tmp_ptr_name len_var;
  873. sprintf "\tif ((%s = (%s)malloc(%s)) == NULL) {" in_ptr_name in_ptr_type len_var;
  874. "\t\tstatus = SGX_ERROR_OUT_OF_MEMORY;";
  875. "\t\tgoto err;";
  876. "\t}\n";
  877. sprintf "\tmemset((void*)%s, 0, %s);" in_ptr_name len_var;
  878. "}"]
  879. in
  880. List.fold_left (fun acc s -> acc ^ pre_indent ^ s ^ "\n") "" code_template
  881. | _ -> ""
  882. in
  883. malloc_and_copy "\t"
  884. in List.fold_left
  885. (fun acc (pty, declr) ->
  886. match pty with
  887. Ast.PTVal _ -> acc
  888. | Ast.PTPtr (ty, attr) -> acc ^ clone_in_ptr ty attr declr) "" plist
  889. (* Generate the code to handle function pointer parameter direction,
  890. * which is to be inserted after finishing calling the trusted function.
  891. *)
  892. let gen_parm_ptr_direction_post (plist: Ast.pdecl list) =
  893. let copy_and_free (attr: Ast.ptr_attr) (declr: Ast.declarator) =
  894. let name = declr.Ast.identifier in
  895. let in_ptr_name = mk_in_var name in
  896. let len_var = mk_len_var name in
  897. let in_ptr_dst_name = mk_in_ptr_dst_name attr.Ast.pa_rdonly in_ptr_name in
  898. match attr.Ast.pa_direction with
  899. Ast.PtrIn -> sprintf "\tif (%s) free(%s);\n" in_ptr_name in_ptr_dst_name
  900. | Ast.PtrInOut | Ast.PtrOut ->
  901. sprintf "\tif (%s) {\n\t\tmemcpy(%s, %s, %s);\n\t\tfree(%s);\n\t}\n"
  902. in_ptr_name
  903. (mk_tmp_var name)
  904. in_ptr_name
  905. len_var
  906. in_ptr_name
  907. | _ -> ""
  908. in List.fold_left
  909. (fun acc (pty, declr) ->
  910. match pty with
  911. Ast.PTVal _ -> acc
  912. | Ast.PTPtr (ty, attr) -> acc ^ copy_and_free attr declr) "" plist
  913. (* Generate an "err:" goto mark if necessary. *)
  914. let gen_err_mark (plist: Ast.pdecl list) =
  915. let has_inout_p (attr: Ast.ptr_attr): bool =
  916. attr.Ast.pa_direction <> Ast.PtrNoDirection
  917. in
  918. if List.exists (fun (pt, name) ->
  919. match pt with
  920. Ast.PTVal _ -> false
  921. | Ast.PTPtr(_, attr) -> has_inout_p attr) plist
  922. then "err:"
  923. else ""
  924. (* It is used to save the parameters used as the value of size/count attribute. *)
  925. let param_cache = Hashtbl.create 1
  926. let is_in_param_cache s = Hashtbl.mem param_cache s
  927. (* Try to generate a temporary value to save the size of the buffer. *)
  928. let gen_tmp_size (pattr: Ast.ptr_attr) (plist: Ast.pdecl list) =
  929. let do_gen_temp_var (s: string) =
  930. if is_in_param_cache s then ""
  931. else
  932. let param_tystr = find_param_type s plist in
  933. let tmp_var = mk_tmp_var s in
  934. let parm_str = mk_parm_accessor s in
  935. Hashtbl.add param_cache s true;
  936. sprintf "\t%s %s = %s;\n" param_tystr tmp_var parm_str
  937. in
  938. let gen_temp_var (v: Ast.attr_value) =
  939. match v with
  940. Ast.ANumber _ -> ""
  941. | Ast.AString s -> do_gen_temp_var s
  942. in
  943. let tmp_size_str =
  944. match pattr.Ast.pa_size.Ast.ps_size with
  945. Some v -> gen_temp_var v
  946. | None -> ""
  947. in
  948. let tmp_count_str =
  949. match pattr.Ast.pa_size.Ast.ps_count with
  950. Some v -> gen_temp_var v
  951. | None -> ""
  952. in
  953. sprintf "%s%s" tmp_size_str tmp_count_str
  954. let is_ptr (pt: Ast.parameter_type) =
  955. match pt with
  956. Ast.PTVal _ -> false
  957. | Ast.PTPtr _ -> true
  958. let is_ptr_type (aty: Ast.atype) =
  959. match aty with
  960. Ast.Ptr _ -> true
  961. | _ -> false
  962. let ptr_has_direction (pt: Ast.parameter_type) =
  963. match pt with
  964. Ast.PTVal _ -> false
  965. | Ast.PTPtr(_, a) -> a.Ast.pa_direction <> Ast.PtrNoDirection
  966. let tbridge_mk_parm_name_ext (pt: Ast.parameter_type) (declr: Ast.declarator) =
  967. if is_in_param_cache declr.Ast.identifier || (is_ptr pt && (not (is_foreign_array pt)))
  968. then
  969. if ptr_has_direction pt
  970. then mk_in_var declr.Ast.identifier
  971. else mk_tmp_var declr.Ast.identifier
  972. else mk_parm_name_ext pt declr
  973. let mk_parm_name_tbridge (pt: Ast.parameter_type) (declr: Ast.declarator) =
  974. add_foreign_array_ptrref tbridge_mk_parm_name_ext pt declr
  975. (* Generate local variables required for the trusted bridge. *)
  976. let gen_tbridge_local_vars (plist: Ast.pdecl list) =
  977. let status_var = "\tsgx_status_t status = SGX_SUCCESS;\n" in
  978. let do_gen_local_var (ty: Ast.atype) (attr: Ast.ptr_attr) (name: string) =
  979. let tmp_var =
  980. (* Save a copy of pointer in case it might be modified in the marshaling structure. *)
  981. sprintf "\t%s %s = %s;\n" (Ast.get_tystr ty) (mk_tmp_var name) (mk_parm_accessor name)
  982. in
  983. let len_var =
  984. if not attr.Ast.pa_chkptr then ""
  985. else gen_tmp_size attr plist ^ "\t" ^ gen_ptr_size ty attr name mk_tmp_var in
  986. let in_ptr =
  987. match attr.Ast.pa_direction with
  988. Ast.PtrNoDirection -> ""
  989. | _ -> sprintf "\t%s %s = NULL;\n" (Ast.get_tystr ty) (mk_in_var name)
  990. in
  991. tmp_var ^ len_var ^ in_ptr
  992. in
  993. let gen_local_var_for_foreign_array (ty: Ast.atype) (attr: Ast.ptr_attr) (name: string) =
  994. let tystr = Ast.get_tystr ty in
  995. let tmp_var =
  996. sprintf "\t%s* %s = %s;\n" tystr (mk_tmp_var name) (mk_parm_accessor name)
  997. in
  998. let len_var = sprintf "\tsize_t %s = sizeof(%s);\n" (mk_len_var name) tystr
  999. in
  1000. let in_ptr = sprintf "\t%s* %s = NULL;\n" tystr (mk_in_var name)
  1001. in
  1002. match attr.Ast.pa_direction with
  1003. Ast.PtrNoDirection -> ""
  1004. | _ -> tmp_var ^ len_var ^ in_ptr
  1005. in
  1006. let gen_local_var (pd: Ast.pdecl) =
  1007. let (pty, declr) = pd in
  1008. match pty with
  1009. Ast.PTVal _ -> ""
  1010. | Ast.PTPtr (ty, attr) ->
  1011. if is_foreign_array pty
  1012. then gen_local_var_for_foreign_array ty attr declr.Ast.identifier
  1013. else do_gen_local_var ty attr declr.Ast.identifier
  1014. in
  1015. let new_param_list = List.map conv_array_to_ptr plist
  1016. in
  1017. Hashtbl.clear param_cache;
  1018. List.fold_left (fun acc pd -> acc ^ gen_local_var pd) status_var new_param_list
  1019. (* It generates trusted bridge code for a trusted function. *)
  1020. let gen_func_tbridge (fd: Ast.func_decl) (dummy_var: string) =
  1021. let func_open = sprintf "static sgx_status_t SGX_CDECL %s(void* %s)\n{\n"
  1022. (mk_tbridge_name fd.Ast.fname)
  1023. ms_ptr_name in
  1024. let local_vars = gen_tbridge_local_vars fd.Ast.plist in
  1025. let func_close = "\treturn status;\n}\n" in
  1026. let ms_struct_name = mk_ms_struct_name fd.Ast.fname in
  1027. let declare_ms_ptr = sprintf "%s* %s = SGX_CAST(%s*, %s);"
  1028. ms_struct_name
  1029. ms_struct_val
  1030. ms_struct_name
  1031. ms_ptr_name in
  1032. let invoke_func = gen_func_invoking fd mk_parm_name_tbridge in
  1033. let update_retval = sprintf "%s = %s"
  1034. (mk_parm_accessor retval_name)
  1035. invoke_func in
  1036. if is_naked_func fd then
  1037. let check_pms =
  1038. sprintf "if (%s != NULL) return SGX_ERROR_INVALID_PARAMETER;" ms_ptr_name
  1039. in
  1040. sprintf "%s%s%s\t%s\n\t%s\n%s" func_open local_vars dummy_var check_pms invoke_func func_close
  1041. else
  1042. sprintf "%s%s\t%s\n%s\n%s%s\n%s\n%s\n\t%s\n%s\n%s\n%s"
  1043. func_open
  1044. (mk_check_pms fd.Ast.fname)
  1045. declare_ms_ptr
  1046. local_vars
  1047. (gen_check_tbridge_length_overflow fd.Ast.plist)
  1048. (gen_check_tbridge_ptr_parms fd.Ast.plist)
  1049. "\n\t//\n\t// fence after pointer checks\n\t//\n\t__builtin_ia32_lfence();\n"
  1050. (gen_parm_ptr_direction_pre fd.Ast.plist)
  1051. (if fd.Ast.rtype <> Ast.Void then update_retval else invoke_func)
  1052. (gen_err_mark fd.Ast.plist)
  1053. (gen_parm_ptr_direction_post fd.Ast.plist)
  1054. func_close
  1055. let tproxy_fill_ms_field (pd: Ast.pdecl) =
  1056. let (pt, declr) = pd in
  1057. let name = declr.Ast.identifier in
  1058. let len_var = mk_len_var name in
  1059. let parm_accessor = mk_parm_accessor name in
  1060. match pt with
  1061. Ast.PTVal _ -> fill_ms_field true pd
  1062. | Ast.PTPtr(ty, attr) ->
  1063. let is_ary = (Ast.is_array declr || attr.Ast.pa_isary) in
  1064. let tystr = sprintf "%s%s" (get_param_tystr pt) (if is_ary then "*" else "") in
  1065. if is_ary && is_ptr_type ty then
  1066. sprintf "\n#pragma message(\"Pointer array `%s' in trusted proxy `\"\
  1067. __FUNCTION__ \"' is dangerous. No code generated.\")\n" name
  1068. else
  1069. if not attr.Ast.pa_chkptr (* [user_check] specified *)
  1070. then sprintf "%s = SGX_CAST(%s, %s);" parm_accessor tystr name
  1071. else
  1072. match attr.Ast.pa_direction with
  1073. Ast.PtrOut ->
  1074. let code_template =
  1075. [sprintf "if (%s != NULL && sgx_is_within_enclave(%s, %s)) {" name name len_var;
  1076. sprintf "\t%s = (%s)__tmp;" parm_accessor tystr;
  1077. sprintf "\t__tmp_%s = __tmp;" name;
  1078. sprintf "\tmemset(__tmp_%s, 0, %s);" name len_var;
  1079. sprintf "\t__tmp = (void *)((size_t)__tmp + %s);" len_var;
  1080. sprintf "} else if (%s == NULL) {" name;
  1081. sprintf "\t%s = NULL;" parm_accessor;
  1082. "} else {";
  1083. "\tsgx_ocfree();";
  1084. "\treturn SGX_ERROR_INVALID_PARAMETER;";
  1085. "}"
  1086. ]
  1087. in List.fold_left (fun acc s -> acc ^ s ^ "\n\t") "" code_template
  1088. | Ast.PtrInOut ->
  1089. let code_template =
  1090. [sprintf "if (%s != NULL && sgx_is_within_enclave(%s, %s)) {" name name len_var;
  1091. sprintf "\t%s = (%s)__tmp;" parm_accessor tystr;
  1092. sprintf "\t__tmp_%s = __tmp;" name;
  1093. sprintf "\tmemcpy(__tmp_%s, %s, %s);" name name len_var;
  1094. sprintf "\t__tmp = (void *)((size_t)__tmp + %s);" len_var;
  1095. sprintf "} else if (%s == NULL) {" name;
  1096. sprintf "\t%s = NULL;" parm_accessor;
  1097. "} else {";
  1098. "\tsgx_ocfree();";
  1099. "\treturn SGX_ERROR_INVALID_PARAMETER;";
  1100. "}"
  1101. ]
  1102. in List.fold_left (fun acc s -> acc ^ s ^ "\n\t") "" code_template
  1103. | _ ->
  1104. let code_template =
  1105. [sprintf "if (%s != NULL && sgx_is_within_enclave(%s, %s)) {" name name len_var;
  1106. sprintf "\t%s = (%s)__tmp;" parm_accessor tystr;
  1107. sprintf "\tmemcpy(__tmp, %s, %s);" name len_var;
  1108. sprintf "\t__tmp = (void *)((size_t)__tmp + %s);" len_var;
  1109. sprintf "} else if (%s == NULL) {" name;
  1110. sprintf "\t%s = NULL;" parm_accessor;
  1111. "} else {";
  1112. "\tsgx_ocfree();";
  1113. "\treturn SGX_ERROR_INVALID_PARAMETER;";
  1114. "}"
  1115. ]
  1116. in List.fold_left (fun acc s -> acc ^ s ^ "\n\t") "" code_template
  1117. (* Generate local variables required for the trusted proxy. *)
  1118. let gen_tproxy_local_vars (plist: Ast.pdecl list) =
  1119. let status_var = "sgx_status_t status = SGX_SUCCESS;\n" in
  1120. let do_gen_local_var (ty: Ast.atype) (attr: Ast.ptr_attr) (name: string) =
  1121. if not attr.Ast.pa_chkptr then ""
  1122. else "\t" ^ gen_ptr_size ty attr name (fun x -> x)
  1123. in
  1124. let gen_local_var (pd: Ast.pdecl) =
  1125. let (pty, declr) = pd in
  1126. match pty with
  1127. Ast.PTVal _ -> ""
  1128. | Ast.PTPtr (ty, attr) -> do_gen_local_var ty attr declr.Ast.identifier
  1129. in
  1130. let new_param_list = List.map conv_array_to_ptr plist
  1131. in
  1132. List.fold_left (fun acc pd -> acc ^ gen_local_var pd) status_var new_param_list
  1133. (* Generate only one ocalloc block required for the trusted proxy. *)
  1134. let gen_ocalloc_block (fname: string) (plist: Ast.pdecl list) =
  1135. let ms_struct_name = mk_ms_struct_name fname in
  1136. let local_vars_block = sprintf "%s* %s = NULL;\n\tsize_t ocalloc_size = sizeof(%s);\n\tvoid *__tmp = NULL;\n\n" ms_struct_name ms_struct_val ms_struct_name in
  1137. let local_var (attr: Ast.ptr_attr) (name: string) =
  1138. if not attr.Ast.pa_chkptr then ""
  1139. else
  1140. match attr.Ast.pa_direction with
  1141. Ast.PtrOut | Ast.PtrInOut -> sprintf "\tvoid *__tmp_%s = NULL;\n" name
  1142. | _ -> ""
  1143. in
  1144. let do_local_var (pd: Ast.pdecl) =
  1145. let (pty, declr) = pd in
  1146. match pty with
  1147. Ast.PTVal _ -> ""
  1148. | Ast.PTPtr (_, attr) -> local_var attr declr.Ast.identifier
  1149. in
  1150. let count_ocalloc_size (ty: Ast.atype) (attr: Ast.ptr_attr) (name: string) =
  1151. if not attr.Ast.pa_chkptr then ""
  1152. else sprintf "\tocalloc_size += (%s != NULL && sgx_is_within_enclave(%s, %s)) ? %s : 0;\n" name name (mk_len_var name) (mk_len_var name)
  1153. in
  1154. let do_count_ocalloc_size (pd: Ast.pdecl) =
  1155. let (pty, declr) = pd in
  1156. match pty with
  1157. Ast.PTVal _ -> ""
  1158. | Ast.PTPtr (ty, attr) -> count_ocalloc_size ty attr declr.Ast.identifier
  1159. in
  1160. let do_gen_ocalloc_block = [
  1161. "\n\t__tmp = sgx_ocalloc(ocalloc_size);\n";
  1162. "\tif (__tmp == NULL) {\n";
  1163. "\t\tsgx_ocfree();\n";
  1164. "\t\treturn SGX_ERROR_UNEXPECTED;\n";
  1165. "\t}\n";
  1166. sprintf "\t%s = (%s*)__tmp;\n" ms_struct_val ms_struct_name;
  1167. sprintf "\t__tmp = (void *)((size_t)__tmp + sizeof(%s));\n" ms_struct_name;
  1168. ]
  1169. in
  1170. let new_param_list = List.map conv_array_to_ptr plist
  1171. in
  1172. let s1 = List.fold_left (fun acc pd -> acc ^ do_local_var pd) local_vars_block new_param_list in
  1173. let s2 = List.fold_left (fun acc pd -> acc ^ do_count_ocalloc_size pd) s1 new_param_list in
  1174. List.fold_left (fun acc s -> acc ^ s) s2 do_gen_ocalloc_block
  1175. (* Generate trusted proxy code for a given untrusted function. *)
  1176. let gen_func_tproxy (ufunc: Ast.untrusted_func) (idx: int) =
  1177. let fd = ufunc.Ast.uf_fdecl in
  1178. let propagate_errno = ufunc.Ast.uf_propagate_errno in
  1179. let func_open = sprintf "%s\n{\n" (gen_tproxy_proto fd) in
  1180. let local_vars = gen_tproxy_local_vars fd.Ast.plist in
  1181. let ocalloc_ms_struct = gen_ocalloc_block fd.Ast.fname fd.Ast.plist in
  1182. let gen_ocfree rtype plist =
  1183. if rtype = Ast.Void && plist = [] then "" else "\tsgx_ocfree();\n"
  1184. in
  1185. let handle_out_ptr plist =
  1186. let copy_memory (attr: Ast.ptr_attr) (declr: Ast.declarator) =
  1187. let name = declr.Ast.identifier in
  1188. match attr.Ast.pa_direction with
  1189. Ast.PtrInOut | Ast.PtrOut ->
  1190. sprintf "\tif (%s) memcpy((void*)%s, __tmp_%s, %s);\n" name name name (mk_len_var name)
  1191. | _ -> ""
  1192. in List.fold_left (fun acc (pty, declr) ->
  1193. match pty with
  1194. Ast.PTVal _ -> acc
  1195. | Ast.PTPtr(ty, attr) -> acc ^ copy_memory attr declr) "" plist in
  1196. let set_errno = if propagate_errno then "\terrno = ms->ocall_errno;" else "" in
  1197. let func_close = sprintf "%s%s\n%s%s\n"
  1198. (handle_out_ptr fd.Ast.plist)
  1199. set_errno
  1200. (gen_ocfree fd.Ast.rtype fd.Ast.plist)
  1201. "\treturn status;\n}" in
  1202. let ocall_null = sprintf "status = sgx_ocall(%d, NULL);\n" idx in
  1203. let ocall_with_ms = sprintf "status = sgx_ocall(%d, %s);\n"
  1204. idx ms_struct_val in
  1205. let update_retval = sprintf "if (%s) *%s = %s;"
  1206. retval_name retval_name (mk_parm_accessor retval_name) in
  1207. let func_body = ref [] in
  1208. if (is_naked_func fd) && (propagate_errno = false) then
  1209. sprintf "%s\t%s\t%s%s" func_open local_vars ocall_null func_close
  1210. else
  1211. begin
  1212. func_body := local_vars :: !func_body;
  1213. func_body := ocalloc_ms_struct:: !func_body;
  1214. List.iter (fun pd -> func_body := tproxy_fill_ms_field pd :: !func_body) fd.Ast.plist;
  1215. func_body := ocall_with_ms :: !func_body;
  1216. if fd.Ast.rtype <> Ast.Void then func_body := update_retval :: !func_body;
  1217. List.fold_left (fun acc s -> acc ^ "\t" ^ s ^ "\n") func_open (List.rev !func_body) ^ func_close
  1218. end
  1219. (* It generates OCALL table and the untrusted proxy to setup OCALL table. *)
  1220. let gen_ocall_table (ec: enclave_content) =
  1221. let func_proto_ubridge = List.map (fun (uf: Ast.untrusted_func) ->
  1222. let fd : Ast.func_decl = uf.Ast.uf_fdecl in
  1223. mk_ubridge_name ec.file_shortnm fd.Ast.fname)
  1224. ec.ufunc_decls in
  1225. let nr_ocall = List.length ec.ufunc_decls in
  1226. let ocall_table_name = mk_ocall_table_name ec.enclave_name in
  1227. let ocall_table =
  1228. let ocall_members =
  1229. List.fold_left
  1230. (fun acc proto -> acc ^ "\t\t(void*)" ^ proto ^ ",\n") "" func_proto_ubridge
  1231. in "\t{\n" ^ ocall_members ^ "\t}\n"
  1232. in
  1233. sprintf "static const struct {\n\
  1234. \tsize_t nr_ocall;\n\
  1235. \tvoid * table[%d];\n\
  1236. } %s = {\n\
  1237. \t%d,\n\
  1238. %s};\n" (max nr_ocall 1)
  1239. ocall_table_name
  1240. nr_ocall
  1241. (if nr_ocall <> 0 then ocall_table else "\t{ NULL },\n")
  1242. (* It generates untrusted code to be saved in a `.c' file. *)
  1243. let gen_untrusted_source (ec: enclave_content) =
  1244. let code_fname = get_usource_name ec.file_shortnm in
  1245. let include_hd = "#include \"" ^ get_uheader_short_name ec.file_shortnm ^ "\"\n" in
  1246. let include_errno = "#include <errno.h>\n" in
  1247. let uproxy_list =
  1248. List.map2 (fun fd ecall_idx -> gen_func_uproxy fd ecall_idx ec)
  1249. (tf_list_to_fd_list ec.tfunc_decls)
  1250. (Util.mk_seq 0 (List.length ec.tfunc_decls - 1))
  1251. in
  1252. let ubridge_list =
  1253. List.map (fun fd -> gen_func_ubridge ec.file_shortnm fd)
  1254. (ec.ufunc_decls) in
  1255. let out_chan = open_out code_fname in
  1256. output_string out_chan (include_hd ^ include_errno ^ "\n");
  1257. ms_writer out_chan ec;
  1258. List.iter (fun s -> output_string out_chan (s ^ "\n")) ubridge_list;
  1259. output_string out_chan (gen_ocall_table ec);
  1260. List.iter (fun s -> output_string out_chan (s ^ "\n")) uproxy_list;
  1261. close_out out_chan
  1262. (* It generates trusted code to be saved in a `.c' file. *)
  1263. let gen_trusted_source (ec: enclave_content) =
  1264. let code_fname = get_tsource_name ec.file_shortnm in
  1265. let include_hd = "#include \"" ^ get_theader_short_name ec.file_shortnm ^ "\"\n\n\
  1266. #include \"sgx_trts.h\" /* for sgx_ocalloc, sgx_is_outside_enclave */\n\n\
  1267. #include <errno.h>\n\
  1268. #include <string.h> /* for memcpy etc */\n\
  1269. #include <stdlib.h> /* for malloc/free etc */\n\
  1270. \n\
  1271. #define CHECK_REF_POINTER(ptr, siz) do {\t\\\n\
  1272. \tif (!(ptr) || ! sgx_is_outside_enclave((ptr), (siz)))\t\\\n\
  1273. \t\treturn SGX_ERROR_INVALID_PARAMETER;\\\n\
  1274. } while (0)\n\
  1275. \n\
  1276. #define CHECK_UNIQUE_POINTER(ptr, siz) do {\t\\\n\
  1277. \tif ((ptr) && ! sgx_is_outside_enclave((ptr), (siz)))\t\\\n\
  1278. \t\treturn SGX_ERROR_INVALID_PARAMETER;\\\n\
  1279. } while (0)\n\
  1280. \n" in
  1281. let trusted_fds = tf_list_to_fd_list ec.tfunc_decls in
  1282. let tbridge_list =
  1283. let dummy_var = tbridge_gen_dummy_variable ec in
  1284. List.map (fun tfd -> gen_func_tbridge tfd dummy_var) trusted_fds in
  1285. let ecall_table = gen_ecall_table ec.tfunc_decls in
  1286. let entry_table = gen_entry_table ec in
  1287. let tproxy_list = List.map2
  1288. (fun fd idx -> gen_func_tproxy fd idx)
  1289. (ec.ufunc_decls)
  1290. (Util.mk_seq 0 (List.length ec.ufunc_decls - 1)) in
  1291. let out_chan = open_out code_fname in
  1292. output_string out_chan (include_hd ^ "\n");
  1293. ms_writer out_chan ec;
  1294. List.iter (fun s -> output_string out_chan (s ^ "\n")) tbridge_list;
  1295. output_string out_chan (ecall_table ^ "\n");
  1296. output_string out_chan (entry_table ^ "\n");
  1297. output_string out_chan "\n";
  1298. List.iter (fun s -> output_string out_chan (s ^ "\n")) tproxy_list;
  1299. close_out out_chan
  1300. (* We use a stack to keep record of imported files.
  1301. *
  1302. * A file will be pushed to the stack before we parsing it,
  1303. * and we will pop the stack after each `parse_import_file'.
  1304. *)
  1305. let already_read = SimpleStack.create ()
  1306. let save_file fullpath =
  1307. if SimpleStack.mem fullpath already_read
  1308. then failwithf "detected circled import for `%s'" fullpath
  1309. else SimpleStack.push fullpath already_read
  1310. (* The entry point of the Edger8r parser front-end.
  1311. * ------------------------------------------------
  1312. *)
  1313. let start_parsing (fname: string) : Ast.enclave =
  1314. let set_initial_pos lexbuf filename =
  1315. lexbuf.Lexing.lex_curr_p <- {
  1316. lexbuf.Lexing.lex_curr_p with Lexing.pos_fname = fname;
  1317. }
  1318. in
  1319. try
  1320. let fullpath = Util.get_file_path fname in
  1321. let preprocessed =
  1322. save_file fullpath; Preprocessor.processor_macro(fullpath) in
  1323. let lexbuf =
  1324. match preprocessed with
  1325. | None ->
  1326. let chan = open_in fullpath in
  1327. Lexing.from_channel chan
  1328. | Some(preprocessed_string) -> Lexing.from_string preprocessed_string
  1329. in
  1330. try
  1331. set_initial_pos lexbuf fname;
  1332. let e : Ast.enclave = Parser.start_parsing Lexer.tokenize lexbuf in
  1333. let short_name = Util.get_short_name fname in
  1334. if short_name = ""
  1335. then (eprintf "error: %s: file short name is empty\n" fname; exit 1;)
  1336. else
  1337. let res = { e with Ast.ename = short_name } in
  1338. if Util.is_c_identifier short_name then res
  1339. else (eprintf "warning: %s: file short name `%s' is not a valid C identifier\n" fname short_name; res)
  1340. with exn ->
  1341. begin match exn with
  1342. | Parsing.Parse_error ->
  1343. let curr = lexbuf.Lexing.lex_curr_p in
  1344. let line = curr.Lexing.pos_lnum in
  1345. let cnum = curr.Lexing.pos_cnum - curr.Lexing.pos_bol in
  1346. let tok = Lexing.lexeme lexbuf in
  1347. failwithf "%s:%d:%d: unexpected token: %s\n" fname line cnum tok
  1348. | _ -> raise exn
  1349. end
  1350. with Sys_error s -> failwithf "%s\n" s
  1351. (* Check duplicated ECALL/OCALL names.
  1352. *
  1353. * This is a pretty simple implementation - to improve it, the
  1354. * location information of each token should be carried to AST.
  1355. *)
  1356. let check_duplication (ec: enclave_content) =
  1357. let dict = Hashtbl.create 10 in
  1358. let trusted_fds = tf_list_to_fd_list ec.tfunc_decls in
  1359. let untrusted_fds = uf_list_to_fd_list ec.ufunc_decls in
  1360. let check_and_add fname =
  1361. if Hashtbl.mem dict fname then
  1362. failwithf "Multiple definition of function \"%s\" detected." fname
  1363. else
  1364. Hashtbl.add dict fname true
  1365. in
  1366. List.iter (fun (fd: Ast.func_decl) ->
  1367. check_and_add fd.Ast.fname) (trusted_fds @ untrusted_fds)
  1368. (* For each untrusted functions, check that allowed ECALL does exist. *)
  1369. let check_allow_list (ec: enclave_content) =
  1370. let trusted_func_names = get_trusted_func_names ec in
  1371. let do_check_allow_list fname allowed_ecalls =
  1372. List.iter (fun trusted_func ->
  1373. if List.exists (fun x -> x = trusted_func) trusted_func_names
  1374. then ()
  1375. else
  1376. failwithf "\"%s\" declared to allow unknown function \"%s\"."
  1377. fname trusted_func) allowed_ecalls
  1378. in
  1379. List.iter (fun (uf: Ast.untrusted_func) ->
  1380. let fd = uf.Ast.uf_fdecl in
  1381. let allowed_ecalls = uf.Ast.uf_allow_list in
  1382. do_check_allow_list fd.Ast.fname allowed_ecalls) ec.ufunc_decls
  1383. (* Report private ECALL not used in any "allow(...)" expression. *)
  1384. let report_orphaned_priv_ecall (ec: enclave_content) =
  1385. let priv_ecall_names = get_priv_ecall_names ec.tfunc_decls in
  1386. let allowed_names = get_allowed_names ec.ufunc_decls in
  1387. let check_ecall n = if List.mem n allowed_names then ()
  1388. else eprintf "warning: private ECALL `%s' is not used by any OCALL\n" n
  1389. in
  1390. List.iter check_ecall priv_ecall_names
  1391. (* Check that there is at least one public ECALL function. *)
  1392. let check_priv_funcs (ec: enclave_content) =
  1393. let priv_bits = tf_list_to_priv_list ec.tfunc_decls in
  1394. if List.for_all (fun is_priv -> is_priv) priv_bits
  1395. then failwithf "the enclave `%s' contains no public root ECALL.\n" ec.file_shortnm
  1396. else report_orphaned_priv_ecall ec
  1397. (* When generating edge-routines, it need first to check whether there
  1398. * are `import' expressions inside EDL. If so, it will parse the given
  1399. * importing file to get an `enclave_content' record, recursively.
  1400. *
  1401. * `ec' is the toplevel `enclave_content' record.
  1402. * Here, a tree reduce algorithm is used. `ec' is the root-node, each
  1403. * `import' expression is considered as a children.
  1404. *)
  1405. let reduce_import (ec: enclave_content) =
  1406. (* Append a EDL list to another. Keep the first element and replace the
  1407. second one with empty element contains functions not in the first one
  1408. if both lists contain a same EDL. The function sequence is backwards compatible.*)
  1409. let join (ec1: enclave_content list) (ec2: enclave_content list) =
  1410. let join_one (acc: enclave_content list) (ec: enclave_content) =
  1411. if List.exists (fun (x: enclave_content) -> x.enclave_name = ec.enclave_name) acc
  1412. then
  1413. let match_ec = List.find (fun (x: enclave_content) -> x.enclave_name = ec.enclave_name) acc in
  1414. let filter_one func_decls decl= List.filter(fun x -> not (x = decl)) func_decls in
  1415. let filtered_ec =
  1416. {empty_ec with
  1417. tfunc_decls = List.fold_left(filter_one) ec.tfunc_decls match_ec.tfunc_decls;
  1418. ufunc_decls = List.fold_left(filter_one) ec.ufunc_decls match_ec.ufunc_decls; }
  1419. in
  1420. acc @ filtered_ec::[]
  1421. else
  1422. acc @ ec ::[]
  1423. in
  1424. List.fold_left(join_one) ec1 ec2
  1425. in
  1426. let parse_import_file fname =
  1427. parse_enclave_ast (start_parsing fname)
  1428. in
  1429. let check_funs funcs (ec: enclave_content list) =
  1430. (* Check whether `funcs' are listed in head of `ec'. It returns a
  1431. production (x, y), where:
  1432. x - functions not listed in head `ec';
  1433. y - a new `ec' that its head contains functions from `funcs' listed in `ec'.
  1434. *)
  1435. let enclave_funcs =
  1436. let trusted_func_names = get_trusted_func_names (List.hd ec) in
  1437. let untrusted_func_names = get_untrusted_func_names (List.hd ec) in
  1438. trusted_func_names @ untrusted_func_names
  1439. in
  1440. let in_ec_def name = List.exists (fun x -> x = name) enclave_funcs in
  1441. let in_import_list name = List.exists (fun x -> x = name) funcs in
  1442. let x = List.filter (fun name -> not (in_ec_def name)) funcs in
  1443. let y =
  1444. { (List.hd ec) with
  1445. tfunc_decls = List.filter (fun tf ->
  1446. in_import_list (get_tf_fname tf)) (List.hd ec).tfunc_decls;
  1447. ufunc_decls = List.filter (fun uf ->
  1448. in_import_list (get_uf_fname uf)) (List.hd ec).ufunc_decls; }
  1449. in (x, y::(List.tl ec))
  1450. in
  1451. (* Import functions listed in `funcs' from `importee'. *)
  1452. let rec import_funcs (funcs: string list) (importee: enclave_content list) =
  1453. (* A `*' means importing all the functions. *)
  1454. if List.exists (fun x -> x = "*") funcs
  1455. then
  1456. let finished_ec = List.fold_left (fun acc (ipd: Ast.import_decl) ->
  1457. let next_ec = parse_import_file ipd.Ast.mname
  1458. in join acc (import_funcs ipd.Ast.flist (next_ec::[]))) importee (List.hd importee).import_exprs
  1459. in
  1460. (SimpleStack.pop already_read |> ignore; finished_ec)
  1461. else
  1462. let (x, y) = check_funs funcs importee
  1463. in
  1464. match (List.hd importee).import_exprs with
  1465. [] ->
  1466. if x = []
  1467. then (SimpleStack.pop already_read |> ignore;y) (* Resolved all importings *)
  1468. else failwithf "import failed - functions `%s' not found" (List.hd x)
  1469. | ex ->
  1470. (* Continue importing even if all function importings resolved to avoid circled import.*)
  1471. let finished_ec = List.fold_left (fun acc (ipd: Ast.import_decl) ->
  1472. let next_ec = parse_import_file ipd.Ast.mname
  1473. in join acc (import_funcs x (next_ec::[]))) y ex
  1474. in
  1475. (SimpleStack.pop already_read |> ignore; finished_ec)
  1476. in
  1477. let imported_ec_list = import_funcs ["*"] (ec::[])
  1478. in
  1479. (* combine two EDLs by appending items except import. *)
  1480. let combine (acc: enclave_content) (ec2: enclave_content) =
  1481. { acc with
  1482. include_list = acc.include_list @ ec2.include_list;
  1483. import_exprs = [];
  1484. comp_defs = acc.comp_defs @ ec2.comp_defs;
  1485. tfunc_decls = acc.tfunc_decls @ ec2.tfunc_decls;
  1486. ufunc_decls = acc.ufunc_decls @ ec2.ufunc_decls; }
  1487. in
  1488. List.fold_left (combine) (List.hd imported_ec_list) (List.tl imported_ec_list)
  1489. (* Generate the Enclave code. *)
  1490. let gen_enclave_code (e: Ast.enclave) (ep: edger8r_params) =
  1491. let ec = reduce_import (parse_enclave_ast e) in
  1492. g_use_prefix := ep.use_prefix;
  1493. g_untrusted_dir := ep.untrusted_dir;
  1494. g_trusted_dir := ep.trusted_dir;
  1495. create_dir ep.untrusted_dir;
  1496. create_dir ep.trusted_dir;
  1497. check_duplication ec;
  1498. check_allow_list ec;
  1499. (if not ep.header_only then check_priv_funcs ec);
  1500. (if ep.gen_untrusted then (gen_untrusted_header ec; if not ep.header_only then gen_untrusted_source ec));
  1501. (if ep.gen_trusted then (gen_trusted_header ec; if not ep.header_only then gen_trusted_source ec))