CodeGen.ml 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571
  1. (*
  2. * Copyright (C) 2011-2017 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}" (mk_len_count v) fn in_ptr_name len_var
  843. in
  844. let malloc_and_copy pre_indent =
  845. match attr.Ast.pa_direction with
  846. Ast.PtrIn | Ast.PtrInOut ->
  847. let code_template = [
  848. sprintf "if (%s != NULL && %s != 0) {" tmp_ptr_name len_var;
  849. sprintf "\t%s = (%s)malloc(%s);" in_ptr_name in_ptr_type len_var;
  850. sprintf "\tif (%s == NULL) {" in_ptr_name;
  851. "\t\tstatus = SGX_ERROR_OUT_OF_MEMORY;";
  852. "\t\tgoto err;";
  853. "\t}\n";
  854. sprintf "\tmemcpy(%s, %s, %s);" in_ptr_dst_name tmp_ptr_name len_var;
  855. ]
  856. in
  857. let s1 = List.fold_left (fun acc s -> acc ^ pre_indent ^ s ^ "\n") "" code_template in
  858. let s2 =
  859. if attr.Ast.pa_isstr
  860. then sprintf "%s\t\t%s[%s - 1] = '\\0';\n" s1 in_ptr_name len_var
  861. else if attr.Ast.pa_iswstr
  862. then sprintf "%s\t\t%s[(%s - sizeof(wchar_t))/sizeof(wchar_t)] = (wchar_t)0;\n" s1 in_ptr_name len_var
  863. else s1 in
  864. let s3 =
  865. match attr.Ast.pa_size.Ast.ps_sizefunc with
  866. None -> s2
  867. | Some s -> sprintf "%s\n%s\n" s2 (check_sizefunc_with_cnt_ptr attr.Ast.pa_size.Ast.ps_count s)
  868. in sprintf "%s\t}\n" s3
  869. | Ast.PtrOut ->
  870. let code_template = [
  871. sprintf "if (%s != NULL && %s != 0) {" tmp_ptr_name len_var;
  872. sprintf "\tif ((%s = (%s)malloc(%s)) == NULL) {" in_ptr_name in_ptr_type len_var;
  873. "\t\tstatus = SGX_ERROR_OUT_OF_MEMORY;";
  874. "\t\tgoto err;";
  875. "\t}\n";
  876. sprintf "\tmemset((void*)%s, 0, %s);" in_ptr_name len_var;
  877. "}"]
  878. in
  879. List.fold_left (fun acc s -> acc ^ pre_indent ^ s ^ "\n") "" code_template
  880. | _ -> ""
  881. in
  882. malloc_and_copy "\t"
  883. in List.fold_left
  884. (fun acc (pty, declr) ->
  885. match pty with
  886. Ast.PTVal _ -> acc
  887. | Ast.PTPtr (ty, attr) -> acc ^ clone_in_ptr ty attr declr) "" plist
  888. (* Generate the code to handle function pointer parameter direction,
  889. * which is to be inserted after finishing calling the trusted function.
  890. *)
  891. let gen_parm_ptr_direction_post (plist: Ast.pdecl list) =
  892. let copy_and_free (attr: Ast.ptr_attr) (declr: Ast.declarator) =
  893. let name = declr.Ast.identifier in
  894. let in_ptr_name = mk_in_var name in
  895. let len_var = mk_len_var name in
  896. let in_ptr_dst_name = mk_in_ptr_dst_name attr.Ast.pa_rdonly in_ptr_name in
  897. match attr.Ast.pa_direction with
  898. Ast.PtrIn -> sprintf "\tif (%s) free(%s);\n" in_ptr_name in_ptr_dst_name
  899. | Ast.PtrInOut | Ast.PtrOut ->
  900. sprintf "\tif (%s) {\n\t\tmemcpy(%s, %s, %s);\n\t\tfree(%s);\n\t}\n"
  901. in_ptr_name
  902. (mk_tmp_var name)
  903. in_ptr_name
  904. len_var
  905. in_ptr_name
  906. | _ -> ""
  907. in List.fold_left
  908. (fun acc (pty, declr) ->
  909. match pty with
  910. Ast.PTVal _ -> acc
  911. | Ast.PTPtr (ty, attr) -> acc ^ copy_and_free attr declr) "" plist
  912. (* Generate an "err:" goto mark if necessary. *)
  913. let gen_err_mark (plist: Ast.pdecl list) =
  914. let has_inout_p (attr: Ast.ptr_attr): bool =
  915. attr.Ast.pa_direction <> Ast.PtrNoDirection
  916. in
  917. if List.exists (fun (pt, name) ->
  918. match pt with
  919. Ast.PTVal _ -> false
  920. | Ast.PTPtr(_, attr) -> has_inout_p attr) plist
  921. then "err:"
  922. else ""
  923. (* It is used to save the parameters used as the value of size/count attribute. *)
  924. let param_cache = Hashtbl.create 1
  925. let is_in_param_cache s = Hashtbl.mem param_cache s
  926. (* Try to generate a temporary value to save the size of the buffer. *)
  927. let gen_tmp_size (pattr: Ast.ptr_attr) (plist: Ast.pdecl list) =
  928. let do_gen_temp_var (s: string) =
  929. if is_in_param_cache s then ""
  930. else
  931. let param_tystr = find_param_type s plist in
  932. let tmp_var = mk_tmp_var s in
  933. let parm_str = mk_parm_accessor s in
  934. Hashtbl.add param_cache s true;
  935. sprintf "\t%s %s = %s;\n" param_tystr tmp_var parm_str
  936. in
  937. let gen_temp_var (v: Ast.attr_value) =
  938. match v with
  939. Ast.ANumber _ -> ""
  940. | Ast.AString s -> do_gen_temp_var s
  941. in
  942. let tmp_size_str =
  943. match pattr.Ast.pa_size.Ast.ps_size with
  944. Some v -> gen_temp_var v
  945. | None -> ""
  946. in
  947. let tmp_count_str =
  948. match pattr.Ast.pa_size.Ast.ps_count with
  949. Some v -> gen_temp_var v
  950. | None -> ""
  951. in
  952. sprintf "%s%s" tmp_size_str tmp_count_str
  953. let is_ptr (pt: Ast.parameter_type) =
  954. match pt with
  955. Ast.PTVal _ -> false
  956. | Ast.PTPtr _ -> true
  957. let is_ptr_type (aty: Ast.atype) =
  958. match aty with
  959. Ast.Ptr _ -> true
  960. | _ -> false
  961. let ptr_has_direction (pt: Ast.parameter_type) =
  962. match pt with
  963. Ast.PTVal _ -> false
  964. | Ast.PTPtr(_, a) -> a.Ast.pa_direction <> Ast.PtrNoDirection
  965. let tbridge_mk_parm_name_ext (pt: Ast.parameter_type) (declr: Ast.declarator) =
  966. if is_in_param_cache declr.Ast.identifier || (is_ptr pt && (not (is_foreign_array pt)))
  967. then
  968. if ptr_has_direction pt
  969. then mk_in_var declr.Ast.identifier
  970. else mk_tmp_var declr.Ast.identifier
  971. else mk_parm_name_ext pt declr
  972. let mk_parm_name_tbridge (pt: Ast.parameter_type) (declr: Ast.declarator) =
  973. add_foreign_array_ptrref tbridge_mk_parm_name_ext pt declr
  974. (* Generate local variables required for the trusted bridge. *)
  975. let gen_tbridge_local_vars (plist: Ast.pdecl list) =
  976. let status_var = "\tsgx_status_t status = SGX_SUCCESS;\n" in
  977. let do_gen_local_var (ty: Ast.atype) (attr: Ast.ptr_attr) (name: string) =
  978. let tmp_var =
  979. (* Save a copy of pointer in case it might be modified in the marshaling structure. *)
  980. sprintf "\t%s %s = %s;\n" (Ast.get_tystr ty) (mk_tmp_var name) (mk_parm_accessor name)
  981. in
  982. let len_var =
  983. if not attr.Ast.pa_chkptr then ""
  984. else gen_tmp_size attr plist ^ "\t" ^ gen_ptr_size ty attr name mk_tmp_var in
  985. let in_ptr =
  986. match attr.Ast.pa_direction with
  987. Ast.PtrNoDirection -> ""
  988. | _ -> sprintf "\t%s %s = NULL;\n" (Ast.get_tystr ty) (mk_in_var name)
  989. in
  990. tmp_var ^ len_var ^ in_ptr
  991. in
  992. let gen_local_var_for_foreign_array (ty: Ast.atype) (attr: Ast.ptr_attr) (name: string) =
  993. let tystr = Ast.get_tystr ty in
  994. let tmp_var =
  995. sprintf "\t%s* %s = %s;\n" tystr (mk_tmp_var name) (mk_parm_accessor name)
  996. in
  997. let len_var = sprintf "\tsize_t %s = sizeof(%s);\n" (mk_len_var name) tystr
  998. in
  999. let in_ptr = sprintf "\t%s* %s = NULL;\n" tystr (mk_in_var name)
  1000. in
  1001. match attr.Ast.pa_direction with
  1002. Ast.PtrNoDirection -> ""
  1003. | _ -> tmp_var ^ len_var ^ in_ptr
  1004. in
  1005. let gen_local_var (pd: Ast.pdecl) =
  1006. let (pty, declr) = pd in
  1007. match pty with
  1008. Ast.PTVal _ -> ""
  1009. | Ast.PTPtr (ty, attr) ->
  1010. if is_foreign_array pty
  1011. then gen_local_var_for_foreign_array ty attr declr.Ast.identifier
  1012. else do_gen_local_var ty attr declr.Ast.identifier
  1013. in
  1014. let new_param_list = List.map conv_array_to_ptr plist
  1015. in
  1016. Hashtbl.clear param_cache;
  1017. List.fold_left (fun acc pd -> acc ^ gen_local_var pd) status_var new_param_list
  1018. (* It generates trusted bridge code for a trusted function. *)
  1019. let gen_func_tbridge (fd: Ast.func_decl) (dummy_var: string) =
  1020. let func_open = sprintf "static sgx_status_t SGX_CDECL %s(void* %s)\n{\n"
  1021. (mk_tbridge_name fd.Ast.fname)
  1022. ms_ptr_name in
  1023. let local_vars = gen_tbridge_local_vars fd.Ast.plist in
  1024. let func_close = "\treturn status;\n}\n" in
  1025. let ms_struct_name = mk_ms_struct_name fd.Ast.fname in
  1026. let declare_ms_ptr = sprintf "%s* %s = SGX_CAST(%s*, %s);"
  1027. ms_struct_name
  1028. ms_struct_val
  1029. ms_struct_name
  1030. ms_ptr_name in
  1031. let invoke_func = gen_func_invoking fd mk_parm_name_tbridge in
  1032. let update_retval = sprintf "%s = %s"
  1033. (mk_parm_accessor retval_name)
  1034. invoke_func in
  1035. if is_naked_func fd then
  1036. let check_pms =
  1037. sprintf "if (%s != NULL) return SGX_ERROR_INVALID_PARAMETER;" ms_ptr_name
  1038. in
  1039. sprintf "%s%s%s\t%s\n\t%s\n%s" func_open local_vars dummy_var check_pms invoke_func func_close
  1040. else
  1041. sprintf "%s%s\t%s\n%s\n%s%s\n%s\t%s\n%s\n%s\n%s"
  1042. func_open
  1043. (mk_check_pms fd.Ast.fname)
  1044. declare_ms_ptr
  1045. local_vars
  1046. (gen_check_tbridge_length_overflow fd.Ast.plist)
  1047. (gen_check_tbridge_ptr_parms fd.Ast.plist)
  1048. (gen_parm_ptr_direction_pre fd.Ast.plist)
  1049. (if fd.Ast.rtype <> Ast.Void then update_retval else invoke_func)
  1050. (gen_err_mark fd.Ast.plist)
  1051. (gen_parm_ptr_direction_post fd.Ast.plist)
  1052. func_close
  1053. let tproxy_fill_ms_field (pd: Ast.pdecl) =
  1054. let (pt, declr) = pd in
  1055. let name = declr.Ast.identifier in
  1056. let len_var = mk_len_var name in
  1057. let parm_accessor = mk_parm_accessor name in
  1058. match pt with
  1059. Ast.PTVal _ -> fill_ms_field true pd
  1060. | Ast.PTPtr(ty, attr) ->
  1061. let is_ary = (Ast.is_array declr || attr.Ast.pa_isary) in
  1062. let tystr = sprintf "%s%s" (get_param_tystr pt) (if is_ary then "*" else "") in
  1063. if is_ary && is_ptr_type ty then
  1064. sprintf "\n#pragma message(\"Pointer array `%s' in trusted proxy `\"\
  1065. __FUNCTION__ \"' is dangerous. No code generated.\")\n" name
  1066. else
  1067. let in_ptr_dst_name = mk_in_ptr_dst_name attr.Ast.pa_rdonly parm_accessor in
  1068. if not attr.Ast.pa_chkptr (* [user_check] specified *)
  1069. then sprintf "%s = SGX_CAST(%s, %s);" parm_accessor tystr name
  1070. else
  1071. match attr.Ast.pa_direction with
  1072. Ast.PtrOut ->
  1073. let code_template =
  1074. [sprintf "if (%s != NULL && sgx_is_within_enclave(%s, %s)) {" name name len_var;
  1075. sprintf "\t%s = (%s)__tmp;" parm_accessor tystr;
  1076. sprintf "\t__tmp = (void *)((size_t)__tmp + %s);" len_var;
  1077. sprintf "\tmemset(%s, 0, %s);" in_ptr_dst_name len_var;
  1078. sprintf "} else if (%s == NULL) {" name;
  1079. sprintf "\t%s = NULL;" parm_accessor;
  1080. "} else {";
  1081. "\tsgx_ocfree();";
  1082. "\treturn SGX_ERROR_INVALID_PARAMETER;";
  1083. "}"
  1084. ]
  1085. in List.fold_left (fun acc s -> acc ^ s ^ "\n\t") "" code_template
  1086. | _ ->
  1087. let code_template =
  1088. [sprintf "if (%s != NULL && sgx_is_within_enclave(%s, %s)) {" name name len_var;
  1089. sprintf "\t%s = (%s)__tmp;" parm_accessor tystr;
  1090. sprintf "\t__tmp = (void *)((size_t)__tmp + %s);" len_var;
  1091. sprintf "\tmemcpy(%s, %s, %s);" in_ptr_dst_name name len_var;
  1092. sprintf "} else if (%s == NULL) {" name;
  1093. sprintf "\t%s = NULL;" parm_accessor;
  1094. "} else {";
  1095. "\tsgx_ocfree();";
  1096. "\treturn SGX_ERROR_INVALID_PARAMETER;";
  1097. "}"
  1098. ]
  1099. in List.fold_left (fun acc s -> acc ^ s ^ "\n\t") "" code_template
  1100. (* Generate local variables required for the trusted proxy. *)
  1101. let gen_tproxy_local_vars (plist: Ast.pdecl list) =
  1102. let status_var = "sgx_status_t status = SGX_SUCCESS;\n" in
  1103. let do_gen_local_var (ty: Ast.atype) (attr: Ast.ptr_attr) (name: string) =
  1104. if not attr.Ast.pa_chkptr then ""
  1105. else "\t" ^ gen_ptr_size ty attr name (fun x -> x)
  1106. in
  1107. let gen_local_var (pd: Ast.pdecl) =
  1108. let (pty, declr) = pd in
  1109. match pty with
  1110. Ast.PTVal _ -> ""
  1111. | Ast.PTPtr (ty, attr) -> do_gen_local_var ty attr declr.Ast.identifier
  1112. in
  1113. let new_param_list = List.map conv_array_to_ptr plist
  1114. in
  1115. List.fold_left (fun acc pd -> acc ^ gen_local_var pd) status_var new_param_list
  1116. (* Generate only one ocalloc block required for the trusted proxy. *)
  1117. let gen_ocalloc_block (fname: string) (plist: Ast.pdecl list) =
  1118. let ms_struct_name = mk_ms_struct_name fname in
  1119. 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
  1120. let count_ocalloc_size (ty: Ast.atype) (attr: Ast.ptr_attr) (name: string) =
  1121. if not attr.Ast.pa_chkptr then ""
  1122. 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)
  1123. in
  1124. let do_count_ocalloc_size (pd: Ast.pdecl) =
  1125. let (pty, declr) = pd in
  1126. match pty with
  1127. Ast.PTVal _ -> ""
  1128. | Ast.PTPtr (ty, attr) -> count_ocalloc_size ty attr declr.Ast.identifier
  1129. in
  1130. let do_gen_ocalloc_block = [
  1131. "\n\t__tmp = sgx_ocalloc(ocalloc_size);\n";
  1132. "\tif (__tmp == NULL) {\n";
  1133. "\t\tsgx_ocfree();\n";
  1134. "\t\treturn SGX_ERROR_UNEXPECTED;\n";
  1135. "\t}\n";
  1136. sprintf "\t%s = (%s*)__tmp;\n" ms_struct_val ms_struct_name;
  1137. sprintf "\t__tmp = (void *)((size_t)__tmp + sizeof(%s));\n" ms_struct_name;
  1138. ]
  1139. in
  1140. let new_param_list = List.map conv_array_to_ptr plist
  1141. in
  1142. let s1 = List.fold_left (fun acc pd -> acc ^ do_count_ocalloc_size pd) local_vars_block new_param_list in
  1143. List.fold_left (fun acc s -> acc ^ s) s1 do_gen_ocalloc_block
  1144. (* Generate trusted proxy code for a given untrusted function. *)
  1145. let gen_func_tproxy (ufunc: Ast.untrusted_func) (idx: int) =
  1146. let fd = ufunc.Ast.uf_fdecl in
  1147. let propagate_errno = ufunc.Ast.uf_propagate_errno in
  1148. let func_open = sprintf "%s\n{\n" (gen_tproxy_proto fd) in
  1149. let local_vars = gen_tproxy_local_vars fd.Ast.plist in
  1150. let ocalloc_ms_struct = gen_ocalloc_block fd.Ast.fname fd.Ast.plist in
  1151. let gen_ocfree rtype plist =
  1152. if rtype = Ast.Void && plist = [] then "" else "\tsgx_ocfree();\n"
  1153. in
  1154. let handle_out_ptr plist =
  1155. let copy_memory (attr: Ast.ptr_attr) (declr: Ast.declarator) =
  1156. let name = declr.Ast.identifier in
  1157. match attr.Ast.pa_direction with
  1158. Ast.PtrInOut | Ast.PtrOut ->
  1159. sprintf "\tif (%s) memcpy((void*)%s, %s, %s);\n" name name (mk_parm_accessor name) (mk_len_var name)
  1160. | _ -> ""
  1161. in List.fold_left (fun acc (pty, declr) ->
  1162. match pty with
  1163. Ast.PTVal _ -> acc
  1164. | Ast.PTPtr(ty, attr) -> acc ^ copy_memory attr declr) "" plist in
  1165. let set_errno = if propagate_errno then "\terrno = ms->ocall_errno;" else "" in
  1166. let func_close = sprintf "%s%s\n%s%s\n"
  1167. (handle_out_ptr fd.Ast.plist)
  1168. set_errno
  1169. (gen_ocfree fd.Ast.rtype fd.Ast.plist)
  1170. "\treturn status;\n}" in
  1171. let ocall_null = sprintf "status = sgx_ocall(%d, NULL);\n" idx in
  1172. let ocall_with_ms = sprintf "status = sgx_ocall(%d, %s);\n"
  1173. idx ms_struct_val in
  1174. let update_retval = sprintf "if (%s) *%s = %s;"
  1175. retval_name retval_name (mk_parm_accessor retval_name) in
  1176. let func_body = ref [] in
  1177. if (is_naked_func fd) && (propagate_errno = false) then
  1178. sprintf "%s\t%s\t%s%s" func_open local_vars ocall_null func_close
  1179. else
  1180. begin
  1181. func_body := local_vars :: !func_body;
  1182. func_body := ocalloc_ms_struct:: !func_body;
  1183. List.iter (fun pd -> func_body := tproxy_fill_ms_field pd :: !func_body) fd.Ast.plist;
  1184. func_body := ocall_with_ms :: !func_body;
  1185. if fd.Ast.rtype <> Ast.Void then func_body := update_retval :: !func_body;
  1186. List.fold_left (fun acc s -> acc ^ "\t" ^ s ^ "\n") func_open (List.rev !func_body) ^ func_close
  1187. end
  1188. (* It generates OCALL table and the untrusted proxy to setup OCALL table. *)
  1189. let gen_ocall_table (ec: enclave_content) =
  1190. let func_proto_ubridge = List.map (fun (uf: Ast.untrusted_func) ->
  1191. let fd : Ast.func_decl = uf.Ast.uf_fdecl in
  1192. mk_ubridge_name ec.file_shortnm fd.Ast.fname)
  1193. ec.ufunc_decls in
  1194. let nr_ocall = List.length ec.ufunc_decls in
  1195. let ocall_table_name = mk_ocall_table_name ec.enclave_name in
  1196. let ocall_table =
  1197. let ocall_members =
  1198. List.fold_left
  1199. (fun acc proto -> acc ^ "\t\t(void*)" ^ proto ^ ",\n") "" func_proto_ubridge
  1200. in "\t{\n" ^ ocall_members ^ "\t}\n"
  1201. in
  1202. sprintf "static const struct {\n\
  1203. \tsize_t nr_ocall;\n\
  1204. \tvoid * table[%d];\n\
  1205. } %s = {\n\
  1206. \t%d,\n\
  1207. %s};\n" (max nr_ocall 1)
  1208. ocall_table_name
  1209. nr_ocall
  1210. (if nr_ocall <> 0 then ocall_table else "\t{ NULL },\n")
  1211. (* It generates untrusted code to be saved in a `.c' file. *)
  1212. let gen_untrusted_source (ec: enclave_content) =
  1213. let code_fname = get_usource_name ec.file_shortnm in
  1214. let include_hd = "#include \"" ^ get_uheader_short_name ec.file_shortnm ^ "\"\n" in
  1215. let include_errno = "#include <errno.h>\n" in
  1216. let uproxy_list =
  1217. List.map2 (fun fd ecall_idx -> gen_func_uproxy fd ecall_idx ec)
  1218. (tf_list_to_fd_list ec.tfunc_decls)
  1219. (Util.mk_seq 0 (List.length ec.tfunc_decls - 1))
  1220. in
  1221. let ubridge_list =
  1222. List.map (fun fd -> gen_func_ubridge ec.file_shortnm fd)
  1223. (ec.ufunc_decls) in
  1224. let out_chan = open_out code_fname in
  1225. output_string out_chan (include_hd ^ include_errno ^ "\n");
  1226. ms_writer out_chan ec;
  1227. List.iter (fun s -> output_string out_chan (s ^ "\n")) ubridge_list;
  1228. output_string out_chan (gen_ocall_table ec);
  1229. List.iter (fun s -> output_string out_chan (s ^ "\n")) uproxy_list;
  1230. close_out out_chan
  1231. (* It generates trusted code to be saved in a `.c' file. *)
  1232. let gen_trusted_source (ec: enclave_content) =
  1233. let code_fname = get_tsource_name ec.file_shortnm in
  1234. let include_hd = "#include \"" ^ get_theader_short_name ec.file_shortnm ^ "\"\n\n\
  1235. #include \"sgx_trts.h\" /* for sgx_ocalloc, sgx_is_outside_enclave */\n\n\
  1236. #include <errno.h>\n\
  1237. #include <string.h> /* for memcpy etc */\n\
  1238. #include <stdlib.h> /* for malloc/free etc */\n\
  1239. \n\
  1240. #define CHECK_REF_POINTER(ptr, siz) do {\t\\\n\
  1241. \tif (!(ptr) || ! sgx_is_outside_enclave((ptr), (siz)))\t\\\n\
  1242. \t\treturn SGX_ERROR_INVALID_PARAMETER;\\\n\
  1243. } while (0)\n\
  1244. \n\
  1245. #define CHECK_UNIQUE_POINTER(ptr, siz) do {\t\\\n\
  1246. \tif ((ptr) && ! sgx_is_outside_enclave((ptr), (siz)))\t\\\n\
  1247. \t\treturn SGX_ERROR_INVALID_PARAMETER;\\\n\
  1248. } while (0)\n\
  1249. \n" in
  1250. let trusted_fds = tf_list_to_fd_list ec.tfunc_decls in
  1251. let tbridge_list =
  1252. let dummy_var = tbridge_gen_dummy_variable ec in
  1253. List.map (fun tfd -> gen_func_tbridge tfd dummy_var) trusted_fds in
  1254. let ecall_table = gen_ecall_table ec.tfunc_decls in
  1255. let entry_table = gen_entry_table ec in
  1256. let tproxy_list = List.map2
  1257. (fun fd idx -> gen_func_tproxy fd idx)
  1258. (ec.ufunc_decls)
  1259. (Util.mk_seq 0 (List.length ec.ufunc_decls - 1)) in
  1260. let out_chan = open_out code_fname in
  1261. output_string out_chan (include_hd ^ "\n");
  1262. ms_writer out_chan ec;
  1263. List.iter (fun s -> output_string out_chan (s ^ "\n")) tbridge_list;
  1264. output_string out_chan (ecall_table ^ "\n");
  1265. output_string out_chan (entry_table ^ "\n");
  1266. output_string out_chan "\n";
  1267. List.iter (fun s -> output_string out_chan (s ^ "\n")) tproxy_list;
  1268. close_out out_chan
  1269. (* We use a stack to keep record of imported files.
  1270. *
  1271. * A file will be pushed to the stack before we parsing it,
  1272. * and we will pop the stack after each `parse_import_file'.
  1273. *)
  1274. let already_read = SimpleStack.create ()
  1275. let save_file fullpath =
  1276. if SimpleStack.mem fullpath already_read
  1277. then failwithf "detected circled import for `%s'" fullpath
  1278. else SimpleStack.push fullpath already_read
  1279. (* The entry point of the Edger8r parser front-end.
  1280. * ------------------------------------------------
  1281. *)
  1282. let start_parsing (fname: string) : Ast.enclave =
  1283. let set_initial_pos lexbuf filename =
  1284. lexbuf.Lexing.lex_curr_p <- {
  1285. lexbuf.Lexing.lex_curr_p with Lexing.pos_fname = fname;
  1286. }
  1287. in
  1288. try
  1289. let fullpath = Util.get_file_path fname in
  1290. let preprocessed =
  1291. save_file fullpath; Preprocessor.processor_macro(fullpath) in
  1292. let lexbuf =
  1293. match preprocessed with
  1294. | None ->
  1295. let chan = open_in fullpath in
  1296. Lexing.from_channel chan
  1297. | Some(preprocessed_string) -> Lexing.from_string preprocessed_string
  1298. in
  1299. try
  1300. set_initial_pos lexbuf fname;
  1301. let e : Ast.enclave = Parser.start_parsing Lexer.tokenize lexbuf in
  1302. let short_name = Util.get_short_name fname in
  1303. if short_name = ""
  1304. then (eprintf "error: %s: file short name is empty\n" fname; exit 1;)
  1305. else
  1306. let res = { e with Ast.ename = short_name } in
  1307. if Util.is_c_identifier short_name then res
  1308. else (eprintf "warning: %s: file short name `%s' is not a valid C identifier\n" fname short_name; res)
  1309. with exn ->
  1310. begin match exn with
  1311. | Parsing.Parse_error ->
  1312. let curr = lexbuf.Lexing.lex_curr_p in
  1313. let line = curr.Lexing.pos_lnum in
  1314. let cnum = curr.Lexing.pos_cnum - curr.Lexing.pos_bol in
  1315. let tok = Lexing.lexeme lexbuf in
  1316. failwithf "%s:%d:%d: unexpected token: %s\n" fname line cnum tok
  1317. | _ -> raise exn
  1318. end
  1319. with Sys_error s -> failwithf "%s\n" s
  1320. (* Check duplicated ECALL/OCALL names.
  1321. *
  1322. * This is a pretty simple implementation - to improve it, the
  1323. * location information of each token should be carried to AST.
  1324. *)
  1325. let check_duplication (ec: enclave_content) =
  1326. let dict = Hashtbl.create 10 in
  1327. let trusted_fds = tf_list_to_fd_list ec.tfunc_decls in
  1328. let untrusted_fds = uf_list_to_fd_list ec.ufunc_decls in
  1329. let check_and_add fname =
  1330. if Hashtbl.mem dict fname then
  1331. failwithf "Multiple definition of function \"%s\" detected." fname
  1332. else
  1333. Hashtbl.add dict fname true
  1334. in
  1335. List.iter (fun (fd: Ast.func_decl) ->
  1336. check_and_add fd.Ast.fname) (trusted_fds @ untrusted_fds)
  1337. (* For each untrusted functions, check that allowed ECALL does exist. *)
  1338. let check_allow_list (ec: enclave_content) =
  1339. let trusted_func_names = get_trusted_func_names ec in
  1340. let do_check_allow_list fname allowed_ecalls =
  1341. List.iter (fun trusted_func ->
  1342. if List.exists (fun x -> x = trusted_func) trusted_func_names
  1343. then ()
  1344. else
  1345. failwithf "\"%s\" declared to allow unknown function \"%s\"."
  1346. fname trusted_func) allowed_ecalls
  1347. in
  1348. List.iter (fun (uf: Ast.untrusted_func) ->
  1349. let fd = uf.Ast.uf_fdecl in
  1350. let allowed_ecalls = uf.Ast.uf_allow_list in
  1351. do_check_allow_list fd.Ast.fname allowed_ecalls) ec.ufunc_decls
  1352. (* Report private ECALL not used in any "allow(...)" expression. *)
  1353. let report_orphaned_priv_ecall (ec: enclave_content) =
  1354. let priv_ecall_names = get_priv_ecall_names ec.tfunc_decls in
  1355. let allowed_names = get_allowed_names ec.ufunc_decls in
  1356. let check_ecall n = if List.mem n allowed_names then ()
  1357. else eprintf "warning: private ECALL `%s' is not used by any OCALL\n" n
  1358. in
  1359. List.iter check_ecall priv_ecall_names
  1360. (* Check that there is at least one public ECALL function. *)
  1361. let check_priv_funcs (ec: enclave_content) =
  1362. let priv_bits = tf_list_to_priv_list ec.tfunc_decls in
  1363. if List.for_all (fun is_priv -> is_priv) priv_bits
  1364. then failwithf "the enclave `%s' contains no public root ECALL.\n" ec.file_shortnm
  1365. else report_orphaned_priv_ecall ec
  1366. (* When generating edge-routines, it need first to check whether there
  1367. * are `import' expressions inside EDL. If so, it will parse the given
  1368. * importing file to get an `enclave_content' record, recursively.
  1369. *
  1370. * `ec' is the toplevel `enclave_content' record.
  1371. * Here, a tree reduce algorithm is used. `ec' is the root-node, each
  1372. * `import' expression is considered as a children.
  1373. *)
  1374. let reduce_import (ec: enclave_content) =
  1375. let combine (ec1: enclave_content) (ec2: enclave_content) =
  1376. { ec1 with
  1377. include_list = ec1.include_list @ ec2.include_list;
  1378. import_exprs = [];
  1379. comp_defs = ec1.comp_defs @ ec2.comp_defs;
  1380. tfunc_decls = ec1.tfunc_decls @ ec2.tfunc_decls;
  1381. ufunc_decls = ec1.ufunc_decls @ ec2.ufunc_decls; }
  1382. in
  1383. let parse_import_file fname =
  1384. let ec = parse_enclave_ast (start_parsing fname)
  1385. in
  1386. match ec.import_exprs with
  1387. [] -> (SimpleStack.pop already_read |> ignore; ec )
  1388. | _ -> ec
  1389. in
  1390. let check_funs funcs (ec: enclave_content) =
  1391. (* Check whether `funcs' are listed in `ec'. It returns a
  1392. production (x, y), where:
  1393. x - functions not listed in `ec';
  1394. y - a new `ec' that contains functions from `funcs' listed in `ec'.
  1395. *)
  1396. let enclave_funcs =
  1397. let trusted_func_names = get_trusted_func_names ec in
  1398. let untrusted_func_names = get_untrusted_func_names ec in
  1399. trusted_func_names @ untrusted_func_names
  1400. in
  1401. let in_ec_def name = List.exists (fun x -> x = name) enclave_funcs in
  1402. let in_import_list name = List.exists (fun x -> x = name) funcs in
  1403. let x = List.filter (fun name -> not (in_ec_def name)) funcs in
  1404. let y =
  1405. { empty_ec with
  1406. tfunc_decls = List.filter (fun tf ->
  1407. in_import_list (get_tf_fname tf)) ec.tfunc_decls;
  1408. ufunc_decls = List.filter (fun uf ->
  1409. in_import_list (get_uf_fname uf)) ec.ufunc_decls; }
  1410. in (x, y)
  1411. in
  1412. (* Import functions listed in `funcs' from `importee'. *)
  1413. let rec import_funcs (funcs: string list) (importee: enclave_content) =
  1414. (* A `*' means importing all the functions. *)
  1415. if List.exists (fun x -> x = "*") funcs
  1416. then
  1417. List.fold_left (fun acc (ipd: Ast.import_decl) ->
  1418. let next_ec = parse_import_file ipd.Ast.mname
  1419. in combine acc (import_funcs ipd.Ast.flist next_ec)) importee importee.import_exprs
  1420. else
  1421. let (x, y) = check_funs funcs importee
  1422. in
  1423. if x = [] then y (* Resolved all importings *)
  1424. else
  1425. match importee.import_exprs with
  1426. [] -> failwithf "import failed - functions `%s' not found" (List.hd x)
  1427. | ex -> List.fold_left (fun acc (ipd: Ast.import_decl) ->
  1428. let next_ec = parse_import_file ipd.Ast.mname
  1429. in combine acc (import_funcs x next_ec)) y ex
  1430. in
  1431. import_funcs ["*"] ec
  1432. (* Generate the Enclave code. *)
  1433. let gen_enclave_code (e: Ast.enclave) (ep: edger8r_params) =
  1434. let ec = reduce_import (parse_enclave_ast e) in
  1435. g_use_prefix := ep.use_prefix;
  1436. g_untrusted_dir := ep.untrusted_dir;
  1437. g_trusted_dir := ep.trusted_dir;
  1438. create_dir ep.untrusted_dir;
  1439. create_dir ep.trusted_dir;
  1440. check_duplication ec;
  1441. check_allow_list ec;
  1442. (if not ep.header_only then check_priv_funcs ec);
  1443. (if ep.gen_untrusted then (gen_untrusted_header ec; if not ep.header_only then gen_untrusted_source ec));
  1444. (if ep.gen_trusted then (gen_trusted_header ec; if not ep.header_only then gen_trusted_source ec))