objcgutl.pas 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938
  1. {
  2. Copyright (c) 2009 by Jonas Maebe
  3. This unit implements some Objective-C helper routines at the code generator
  4. level.
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License,or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16. ****************************************************************************
  17. }
  18. {$i fpcdefs.inc}
  19. unit objcgutl;
  20. interface
  21. uses
  22. cclasses,
  23. aasmbase,aasmdata,
  24. symbase,symdef;
  25. procedure objcfinishstringrefpoolentry(entry: phashsetitem; stringpool: tconstpooltype; refsec, stringsec: tasmsectiontype);
  26. procedure objcfinishclassrefnfpoolentry(entry: phashsetitem; classdef: tobjectdef);
  27. procedure MaybeGenerateObjectiveCImageInfo(globalst, localst: tsymtable);
  28. implementation
  29. uses
  30. globtype,globals,fmodule,cutils,
  31. systems,
  32. aasmtai,
  33. cgbase,
  34. objcdef,objcutil,
  35. aasmcnst,
  36. symconst,symtype,symsym,symtable,
  37. verbose;
  38. type
  39. tobjcabi = (oa_fragile, oa_nonfragile);
  40. (* tivarlayouttype = (il_weak,il_strong); *)
  41. tobjcrttiwriter = class
  42. protected
  43. fabi: tobjcabi;
  44. classdefs,
  45. catdefs: tfpobjectlist;
  46. classrttidefs,
  47. catrttidefs: tfpobjectlist;
  48. classsyms,
  49. catsyms: tfpobjectlist;
  50. procedure gen_objc_methods(list: tasmlist; objccls: tobjectdef; out methodslabel: tasmsymbol; classmethods, iscategory: Boolean);
  51. procedure gen_objc_protocol_elements(list: tasmlist; protocol: tobjectdef; out reqinstsym, optinstsym, reqclssym, optclssym: TAsmLabel);
  52. procedure gen_objc_protocol_list(list:TAsmList; protolist: TFPObjectList; out protolistsym: TAsmLabel);
  53. procedure gen_objc_cat_methods(list:TAsmList; items: TFPObjectList; section: tasmsectiontype;const sectname: string; out listsym: TAsmLabel);
  54. procedure gen_objc_protocol(list:TAsmList; protocol: tobjectdef; out protocollabel: TAsmSymbol);virtual;abstract;
  55. procedure gen_objc_category_sections(list:TAsmList; objccat: tobjectdef; out catlabel: TAsmSymbol; out catlabeldef: tdef);virtual;abstract;
  56. procedure gen_objc_classes_sections(list:TAsmList; objclss: tobjectdef; out classlabel: TAsmSymbol; out classlabeldef: tdef);virtual;abstract;
  57. procedure gen_objc_info_sections(list: tasmlist);virtual;abstract;
  58. public
  59. constructor create(_abi: tobjcabi);
  60. destructor destroy;override;
  61. procedure gen_objc_rtti_sections(list:TAsmList; st:TSymtable);
  62. property abi: tobjcabi read fabi;
  63. end;
  64. { Used by by PowerPC/32 and i386 }
  65. tobjcrttiwriter_fragile = class(tobjcrttiwriter)
  66. protected
  67. function gen_objc_protocol_ext(list: TAsmList; optinstsym, optclssym: TAsmLabel): TAsmLabel;
  68. procedure gen_objc_ivars(list: TAsmList; objccls: tobjectdef; out ivarslabel: TAsmLabel);
  69. procedure gen_objc_protocol(list:TAsmList; protocol: tobjectdef; out protocollabel: TAsmSymbol);override;
  70. procedure gen_objc_category_sections(list:TAsmList; objccat: tobjectdef; out catlabel: TAsmSymbol; out catlabeldef: tdef);override;
  71. procedure gen_objc_classes_sections(list:TAsmList; objclss: tobjectdef; out classlabel: TAsmSymbol; out classlabeldef: tdef);override;
  72. procedure gen_objc_info_sections(list: tasmlist);override;
  73. public
  74. constructor create;
  75. end;
  76. { Used by PowerPC/64, ARM, x86_64 and AArch64 }
  77. tobjcrttiwriter_nonfragile = class(tobjcrttiwriter)
  78. protected
  79. ObjCEmptyCacheVar,
  80. ObjCEmptyVtableVar: TAsmSymbol;
  81. procedure gen_objc_class_ro_part(list: TAsmList; objclss: tobjectdef; protolistsym: TAsmSymbol; out classrolabel: TAsmSymbol; metaclass: boolean);
  82. procedure addclasslist(list: tasmlist; section: tasmsectiontype; const symname: string; classes: tfpobjectlist);
  83. procedure gen_objc_ivars(list: TAsmList; objccls: tobjectdef; out ivarslabel: TAsmLabel);
  84. procedure gen_objc_protocol(list:TAsmList; protocol: tobjectdef; out protocollabel: TAsmSymbol);override;
  85. procedure gen_objc_category_sections(list:TAsmList; objccat: tobjectdef; out catlabel: TAsmSymbol; out catlabeldef: tdef);override;
  86. procedure gen_objc_classes_sections(list:TAsmList; objclss: tobjectdef; out classlabel: TAsmSymbol; out classlabeldef: tdef);override;
  87. procedure gen_objc_info_sections(list: tasmlist);override;
  88. public
  89. constructor create;
  90. end;
  91. {******************************************************************
  92. Protocol declaration helpers
  93. *******************************************************************}
  94. function objcfindprotocolentry(const p: shortstring): TAsmSymbol;
  95. var
  96. item : PHashSetItem;
  97. begin
  98. result:=nil;
  99. if not assigned(current_asmdata.ConstPools[sp_objcprotocolrefs]) then
  100. exit;
  101. item:=current_asmdata.constpools[sp_objcprotocolrefs].Find(@p[1], length(p));
  102. if not assigned(item) then
  103. exit;
  104. result:=TAsmSymbol(item^.Data);
  105. end;
  106. function objcaddprotocolentry(const p: shortstring; ref: TAsmSymbol): Boolean;
  107. var
  108. item : PHashSetItem;
  109. begin
  110. item:=current_asmdata.constpools[sp_objcprotocolrefs].FindOrAdd(@p[1], length(p));
  111. Result:=(item^.Data=nil);
  112. if Result then
  113. item^.Data:=ref;
  114. end;
  115. {******************************************************************
  116. Pool section helpers
  117. *******************************************************************}
  118. procedure objcreatestringpoolentryintern(p: pchar; len: longint; pooltype: tconstpooltype; stringsec: tasmsectiontype; out sym: TAsmLabel; out def: tdef);
  119. var
  120. entry : PHashSetItem;
  121. strlab : tasmlabel;
  122. pc : pchar;
  123. pool : THashSet;
  124. tcb : ttai_typedconstbuilder;
  125. begin
  126. pool := current_asmdata.constpools[pooltype];
  127. entry:=pool.FindOrAdd(p,len);
  128. if not assigned(entry^.data) then
  129. begin
  130. { create new entry }
  131. current_asmdata.getlabel(strlab,alt_data);
  132. entry^.Data:=strlab;
  133. getmem(pc,entry^.keylength+1);
  134. move(entry^.key^,pc^,entry^.keylength);
  135. pc[entry^.keylength]:=#0;
  136. { add the string to the approriate section }
  137. tcb:=ctai_typedconstbuilder.create([tcalo_is_lab,tcalo_new_section]);
  138. def:=tcb.emit_pchar_const(pc,entry^.keylength,false);
  139. current_asmdata.asmlists[al_objc_pools].concatList(
  140. tcb.get_final_asmlist(strlab,def,stringsec,strlab.name,1)
  141. );
  142. tcb.free;
  143. def:=cpointerdef.getreusable(def);
  144. end
  145. else
  146. def:=cpointerdef.getreusable(carraydef.getreusable(cansichartype,len+1));
  147. sym:=TAsmLabel(Entry^.Data);
  148. end;
  149. procedure objcfinishstringrefpoolentry(entry: phashsetitem; stringpool: tconstpooltype; refsec, stringsec: tasmsectiontype);
  150. var
  151. reflab,
  152. strlab : tasmlabel;
  153. classname: string;
  154. tcb: ttai_typedconstbuilder;
  155. strdef: tdef;
  156. begin
  157. { have we already generated a reference for this string entry? }
  158. if not assigned(entry^.Data) then
  159. begin
  160. { no, add the string to the associated strings section }
  161. objcreatestringpoolentryintern(pchar(entry^.key),entry^.keylength,stringpool,stringsec,strlab,strdef);
  162. { and now finish the reference }
  163. current_asmdata.getlabel(reflab,alt_data);
  164. entry^.Data:=reflab;
  165. { add a pointer to the string in the string references section }
  166. tcb:=ctai_typedconstbuilder.create([tcalo_is_lab,tcalo_new_section]);
  167. tcb.emit_tai(Tai_const.Create_sym(strlab),strdef);
  168. current_asmdata.asmlists[al_objc_pools].concatList(
  169. tcb.get_final_asmlist(reflab,strdef,refsec,reflab.name,sizeof(pint))
  170. );
  171. tcb.free;
  172. { in case of a class reference, also add a lazy symbol reference for
  173. the class (the linker requires this for the fragile ABI). }
  174. if (refsec=sec_objc_cls_refs) and
  175. not(target_info.system in systems_objc_nfabi) then
  176. begin
  177. setlength(classname,entry^.keylength);
  178. move(entry^.key^,classname[1],entry^.keylength);
  179. { no way to express this in LLVM either, they also just emit
  180. module level assembly for it }
  181. current_asmdata.asmlists[al_pure_assembler].concat(tai_directive.Create(asd_lazy_reference,'.objc_class_name_'+classname));
  182. end;
  183. end;
  184. end;
  185. procedure objcreatestringpoolentry(const s: string; pooltype: tconstpooltype; stringsec: tasmsectiontype; out sym: TAsmLabel; out def: tdef);
  186. begin
  187. objcreatestringpoolentryintern(@s[1],length(s),pooltype,stringsec,sym,def);
  188. end;
  189. procedure objcfinishclassrefnfpoolentry(entry: phashsetitem; classdef: tobjectdef);
  190. var
  191. reflab: TAsmLabel;
  192. classym: TasmSymbol;
  193. tcb: ttai_typedconstbuilder;
  194. begin
  195. { have we already generated a reference for this class ref entry? }
  196. if not assigned(entry^.Data) then
  197. begin
  198. { no, add the classref to the sec_objc_cls_refs section }
  199. current_asmdata.getlabel(reflab,alt_data);
  200. entry^.Data:=reflab;
  201. { add a pointer to the class }
  202. classym:=current_asmdata.RefAsmSymbol(classdef.rtti_mangledname(objcclassrtti));
  203. tcb:=ctai_typedconstbuilder.create([tcalo_is_lab,tcalo_new_section]);
  204. tcb.emit_tai(Tai_const.Create_sym(classym),voidpointertype);
  205. current_asmdata.asmlists[al_objc_pools].concatList(
  206. tcb.get_final_asmlist(reflab,voidpointertype,sec_objc_cls_refs,reflab.name,sizeof(pint))
  207. );
  208. tcb.free;
  209. end;
  210. end;
  211. {******************************************************************
  212. RTTI generation -- Helpers
  213. *******************************************************************}
  214. procedure ConcatSymOrNil(tcb: ttai_typedconstbuilder; sym: TAsmSymbol; def: tdef); inline;
  215. begin
  216. if Assigned(sym) then
  217. tcb.emit_tai(tai_const.Create_sym(sym),def)
  218. else
  219. tcb.emit_tai(tai_const.Create_nil_dataptr,def);
  220. end;
  221. {******************************************************************
  222. RTTI generation -- Common
  223. *******************************************************************}
  224. { generate a method list, either of class methods or of instance methods,
  225. and both for obj-c classes and categories. }
  226. procedure tobjcrttiwriter.gen_objc_methods(list: tasmlist; objccls: tobjectdef; out methodslabel: tasmsymbol; classmethods, iscategory: Boolean);
  227. const
  228. {clas/cat inst/cls}
  229. SectType : array [Boolean, Boolean] of tasmsectiontype =
  230. ((sec_objc_inst_meth, sec_objc_cls_meth),
  231. (sec_objc_cat_inst_meth, sec_objc_cat_cls_meth));
  232. {clas/cat inst/cls}
  233. SectName : array [Boolean, Boolean] of string[20] =
  234. (('_OBJC_INST_METH','_OBJC_CLS_METH'),
  235. ('_OBJC_CAT_INST_METH','_OBJC_CAT_CLS_METH'));
  236. {inst/cls}
  237. instclsName : array [Boolean] of string = ('INSTANCE','CLASS');
  238. type
  239. method_data = record
  240. def : tprocdef;
  241. selsym : TAsmLabel;
  242. seldef : tdef;
  243. encsym : TAsmLabel;
  244. encdef : tdef;
  245. end;
  246. var
  247. i : Integer;
  248. def : tprocdef;
  249. defs : array of method_data;
  250. mcnt : integer;
  251. mtype : tdef;
  252. tcb : ttai_typedconstbuilder;
  253. mdef : tdef;
  254. begin
  255. methodslabel:=nil;
  256. mcnt:=0;
  257. { collect all instance/class methods }
  258. SetLength(defs,objccls.vmtentries.count);
  259. for i:=0 to objccls.vmtentries.count-1 do
  260. begin
  261. def:=pvmtentry(objccls.vmtentries[i])^.procdef;
  262. if (def.owner.defowner=objccls) and
  263. (classmethods = (po_classmethod in def.procoptions)) then
  264. begin
  265. defs[mcnt].def:=def;
  266. objcreatestringpoolentry(def.messageinf.str^,sp_objcvarnames,sec_objc_meth_var_names,defs[mcnt].selsym,defs[mcnt].seldef);
  267. objcreatestringpoolentry(objcencodemethod(def),sp_objcvartypes,sec_objc_meth_var_types,defs[mcnt].encsym,defs[mcnt].encdef);
  268. inc(mcnt);
  269. end;
  270. end;
  271. if mcnt=0 then
  272. exit;
  273. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  274. tcb.begin_anonymous_record(internaltypeprefixName[itp_objc_method_list]+tostr(mcnt),
  275. C_alignment,1,
  276. targetinfos[target_info.system]^.alignment.recordalignmin,
  277. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  278. if (abi=oa_fragile) then
  279. { not used, always zero }
  280. tcb.emit_ord_const(0,u32inttype)
  281. else
  282. begin
  283. { size of each entry -- always 32 bit value }
  284. mtype:=search_named_unit_globaltype('OBJC','OBJC_METHOD',true).typedef;
  285. tcb.emit_ord_const(mtype.size,u32inttype);
  286. end;
  287. { number of objc_method entries in the method_list array -- always 32 bit}
  288. tcb.emit_ord_const(mcnt,u32inttype);
  289. for i:=0 to mcnt-1 do
  290. begin
  291. { reference to the selector name }
  292. tcb.queue_init(charpointertype);
  293. tcb.queue_emit_asmsym(defs[i].selsym,defs[i].seldef);
  294. { reference to the obj-c encoded function parameters (signature) }
  295. tcb.queue_init(charpointertype);
  296. tcb.queue_emit_asmsym(defs[i].encsym,defs[i].encdef);
  297. { mangled name of the method }
  298. tcb.queue_init(voidcodepointertype);
  299. tcb.queue_emit_proc(defs[i].def);
  300. end;
  301. mdef:=tcb.end_anonymous_record;
  302. if iscategory then
  303. begin
  304. methodslabel:=current_asmdata.DefineAsmSymbol('l_OBJC_$_CATEGORY_'+instclsName[classmethods]+'_METHODS_'+objccls.objextname^+'_$_'+objccls.childof.objextname^,AB_LOCAL,AT_DATA,mdef);
  305. end
  306. else
  307. begin
  308. methodslabel:=current_asmdata.DefineAsmSymbol('l_OBJC_$_'+instclsName[classmethods]+'_METHODS_'+objccls.objextname^,AB_LOCAL,AT_DATA,mdef);
  309. end;
  310. list.concatList(
  311. tcb.get_final_asmlist(methodslabel,mdef,
  312. SectType[iscategory,classmethods],
  313. SectName[iscategory,classmethods],sizeof(ptrint)
  314. )
  315. );
  316. tcb.free;
  317. end;
  318. { generate method (and in the future also property) info for protocols }
  319. procedure tobjcrttiwriter.gen_objc_protocol_elements(list: tasmlist; protocol: tobjectdef; out reqinstsym, optinstsym, reqclssym, optclssym: TAsmLabel);
  320. var
  321. proc : tprocdef;
  322. reqinstmlist,
  323. reqclsmlist,
  324. optinstmlist,
  325. optclsmlist : TFPObjectList;
  326. i : ptrint;
  327. begin
  328. reqinstmlist:=TFPObjectList.Create(false);
  329. reqclsmlist:=TFPObjectList.Create(false);
  330. optinstmlist:=TFPObjectList.Create(false);
  331. optclsmlist:=TFPObjectList.Create(false);
  332. for i:=0 to protocol.vmtentries.Count-1 do
  333. begin
  334. proc:=pvmtentry(protocol.vmtentries[i])^.procdef;
  335. if (po_classmethod in proc.procoptions) then
  336. if not(po_optional in proc.procoptions) then
  337. reqclsmlist.Add(proc)
  338. else
  339. optclsmlist.Add(proc)
  340. else if not(po_optional in proc.procoptions) then
  341. reqinstmlist.Add(proc)
  342. else
  343. optinstmlist.Add(proc);
  344. end;
  345. if reqinstmlist.Count > 0 then
  346. gen_objc_cat_methods(list,reqinstmlist,sec_objc_cat_inst_meth,'_OBJC_CAT_INST_METH',reqinstsym)
  347. else
  348. reqinstsym:=nil;
  349. if optinstmlist.Count > 0 then
  350. gen_objc_cat_methods(list,optinstmlist,sec_objc_cat_inst_meth,'_OBJC_CAT_INST_METH',optinstsym)
  351. else
  352. optinstsym:=nil;
  353. if reqclsmlist.Count>0 then
  354. gen_objc_cat_methods(list,reqclsmlist,sec_objc_cat_cls_meth,'_OBJC_CAT_CLS_METH',reqclssym)
  355. else
  356. reqclssym:=nil;
  357. if optclsmlist.Count>0 then
  358. gen_objc_cat_methods(list,optclsmlist,sec_objc_cat_cls_meth,'_OBJC_CAT_CLS_METH',optclssym)
  359. else
  360. optclssym:=nil;
  361. reqinstmlist.Free;
  362. reqclsmlist.Free;
  363. optinstmlist.Free;
  364. optclsmlist.Free;
  365. end;
  366. (*
  367. From CLang:
  368. struct objc_protocol_list
  369. {
  370. #ifdef FRAGILE_ABI
  371. struct objc_protocol_list *next;
  372. int count;
  373. #else
  374. long count;
  375. #endif
  376. Protocol *list[1];
  377. };
  378. *)
  379. procedure tobjcrttiwriter.gen_objc_protocol_list(list: tasmlist; protolist: tfpobjectlist; out protolistsym: tasmlabel);
  380. var
  381. i : Integer;
  382. protosym : TAsmSymbol;
  383. protodef : tobjectdef;
  384. tcb : ttai_typedconstbuilder;
  385. begin
  386. if not Assigned(protolist) or
  387. (protolist.Count=0) then
  388. begin
  389. protolistsym:=nil;
  390. Exit;
  391. end;
  392. for i:=0 to protolist.Count-1 do
  393. begin
  394. protodef:=TImplementedInterface(protolist[i]).IntfDef;
  395. protosym:=objcfindprotocolentry(protodef.objextname^);
  396. if not assigned(protosym) then
  397. begin
  398. gen_objc_protocol(list,protodef,protosym);
  399. objcaddprotocolentry(protodef.objextname^,protosym);
  400. end;
  401. end;
  402. tcb:=ctai_typedconstbuilder.create([tcalo_is_lab,tcalo_new_section]);
  403. tcb.begin_anonymous_record(internaltypeprefixName[itp_objc_proto_list]+tostr(protolist.Count),
  404. C_alignment,1,
  405. targetinfos[target_info.system]^.alignment.recordalignmin,
  406. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  407. { protocol lists are stored in .objc_cat_cls_meth section }
  408. current_asmdata.getlabel(protolistsym, alt_data);
  409. if (abi=oa_fragile) then
  410. { From Clang: next, always nil}
  411. tcb.emit_tai(tai_const.Create_pint(0),ptruinttype);
  412. { From Clang: protocols count}
  413. tcb.emit_tai(Tai_const.Create_pint(protolist.Count),ptruinttype);
  414. for i:=0 to protolist.Count-1 do
  415. begin
  416. protodef:=(protolist[i] as TImplementedInterface).IntfDef;
  417. protosym:=objcfindprotocolentry(protodef.objextname^);
  418. if not Assigned(protosym) then
  419. begin
  420. { For some reason protosym is not declared, though must be!
  421. Probably gen_obcj1_protocol returned wrong protosym
  422. }
  423. InternalError(2009091602);
  424. end;
  425. tcb.emit_tai(tai_const.Create_sym(protosym),voidpointertype);
  426. end;
  427. list.concatList(
  428. tcb.get_final_asmlist(
  429. protolistsym,tcb.end_anonymous_record,
  430. sec_objc_cat_cls_meth,'_OBJC_PROTOCOLLIST',sizeof(pint)
  431. )
  432. );
  433. tcb.free;
  434. { the symbol will point to a record }
  435. end;
  436. { Generate rtti for an Objective-C methods (methods without implementation) }
  437. { items : TFPObjectList of Tprocdef }
  438. procedure tobjcrttiwriter.gen_objc_cat_methods(list:TAsmList; items: TFPObjectList; section: tasmsectiontype;
  439. const sectname: string; out listsym: TAsmLabel);
  440. var
  441. i : integer;
  442. m : tprocdef;
  443. lab : tasmlabel;
  444. ldef : tdef;
  445. mtype : tdef;
  446. tcb : ttai_typedconstbuilder;
  447. begin
  448. if not assigned(items) or
  449. (items.count=0) then
  450. exit;
  451. tcb:=ctai_typedconstbuilder.create([tcalo_is_lab,tcalo_new_section]);
  452. current_asmdata.getlabel(listsym,alt_data);
  453. tcb.begin_anonymous_record(
  454. internaltypeprefixName[itp_objc_cat_methods]+tostr(items.count),
  455. C_alignment,1,
  456. targetinfos[target_info.system]^.alignment.recordalignmin,
  457. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  458. if (abi=oa_nonfragile) then
  459. begin
  460. { size of each entry -- always 32 bit value }
  461. mtype:=search_named_unit_globaltype('OBJC','OBJC_METHOD',true).typedef;
  462. tcb.emit_ord_const(mtype.size,u32inttype);
  463. end;
  464. tcb.emit_ord_const(items.count,u32inttype);
  465. for i:=0 to items.Count-1 do
  466. begin
  467. m:=tprocdef(items[i]);
  468. objcreatestringpoolentry(m.messageinf.str^,sp_objcvarnames,sec_objc_meth_var_names,lab,ldef);
  469. tcb.emit_tai(Tai_const.Create_sym(lab),ldef);
  470. objcreatestringpoolentry(objcencodemethod(m),sp_objcvartypes,sec_objc_meth_var_types,lab,ldef);
  471. tcb.emit_tai(Tai_const.Create_sym(lab),ldef);
  472. { placeholder for address of implementation? }
  473. if (abi=oa_nonfragile) then
  474. tcb.emit_tai(Tai_const.Create_pint(0),ptruinttype);
  475. end;
  476. list.concatList(
  477. tcb.get_final_asmlist(
  478. listsym,tcb.end_anonymous_record,section,sectname,sizeof(pint))
  479. );
  480. tcb.free;
  481. end;
  482. { Generate the rtti sections for all obj-c classes defined in st, and return
  483. these classes in the classes list. }
  484. procedure tobjcrttiwriter.gen_objc_rtti_sections(list:TAsmList; st:TSymtable);
  485. var
  486. i: longint;
  487. def,
  488. rttidef: tdef;
  489. sym: TAsmSymbol;
  490. begin
  491. if not Assigned(st) then
  492. exit;
  493. for i:=0 to st.DefList.Count-1 do
  494. begin
  495. def:=tdef(st.DefList[i]);
  496. { check whether all types used in Objective-C class/protocol/category
  497. declarations can be used with the Objective-C run time (can only be
  498. done now, because at parse-time some of these types can still be
  499. forwarddefs) }
  500. if is_objc_class_or_protocol(def) then
  501. if not tobjectdef(def).check_objc_types then
  502. continue;
  503. if is_objcclass(def) and
  504. not(oo_is_external in tobjectdef(def).objectoptions) then
  505. begin
  506. if not(oo_is_classhelper in tobjectdef(def).objectoptions) then
  507. begin
  508. gen_objc_classes_sections(list,tobjectdef(def),sym,rttidef);
  509. classsyms.add(sym);
  510. classrttidefs.add(rttidef);
  511. classdefs.add(def);
  512. end
  513. else
  514. begin
  515. gen_objc_category_sections(list,tobjectdef(def),sym,rttidef);
  516. catsyms.add(sym);
  517. catrttidefs.add(rttidef);
  518. catdefs.add(def);
  519. end
  520. end;
  521. end;
  522. end;
  523. constructor tobjcrttiwriter.create(_abi: tobjcabi);
  524. begin
  525. fabi:=_abi;
  526. classdefs:=tfpobjectlist.create(false);
  527. classsyms:=tfpobjectlist.create(false);
  528. classrttidefs:=tfpobjectlist.create(false);
  529. catrttidefs:=tfpobjectlist.create(false);
  530. catdefs:=tfpobjectlist.create(false);
  531. catsyms:=tfpobjectlist.create(false);
  532. end;
  533. destructor tobjcrttiwriter.destroy;
  534. begin
  535. classdefs.free;
  536. classsyms.free;
  537. classrttidefs.free;
  538. catrttidefs.free;
  539. catdefs.free;
  540. catsyms.free;
  541. inherited destroy;
  542. end;
  543. {******************************************************************
  544. RTTI generation -- Fragile ABI
  545. *******************************************************************}
  546. { generate an instance variables list for an obj-c class. }
  547. procedure tobjcrttiwriter_fragile.gen_objc_ivars(list: TAsmList; objccls: tobjectdef; out ivarslabel: TAsmLabel);
  548. type
  549. ivar_data = record
  550. vf : tfieldvarsym;
  551. namesym : TAsmLabel;
  552. namedef : tdef;
  553. typesym : TAsmLabel;
  554. typedef : tdef;
  555. end;
  556. var
  557. i : integer;
  558. vf : tfieldvarsym;
  559. vars : array of ivar_data;
  560. vcnt : Integer;
  561. enctype : ansistring;
  562. encerr : tdef;
  563. begin
  564. ivarslabel:=nil;
  565. vcnt:=0;
  566. setLength(vars,objccls.symtable.SymList.Count);
  567. for i:=0 to objccls.symtable.SymList.Count-1 do
  568. if tsym(objccls.symtable.SymList[i]).typ=fieldvarsym then
  569. begin
  570. vf:=tfieldvarsym(objccls.symtable.SymList[i]);
  571. if objctryencodetype(vf.vardef,enctype,encerr) then
  572. begin
  573. vars[vcnt].vf:=vf;
  574. objcreatestringpoolentry(vf.RealName,sp_objcvarnames,sec_objc_meth_var_names,vars[vcnt].namesym,vars[vcnt].namedef);
  575. objcreatestringpoolentry(enctype,sp_objcvartypes,sec_objc_meth_var_types,vars[vcnt].typesym,vars[vcnt].typedef);
  576. inc(vcnt);
  577. end
  578. else
  579. { Should be caught during parsing }
  580. internalerror(2009090601);
  581. end;
  582. if vcnt=0 then
  583. exit;
  584. new_section(list,sec_objc_instance_vars,'_OBJC_INSTANCE_VARS',sizeof(pint));
  585. current_asmdata.getlabel(ivarslabel,alt_data);
  586. list.Concat(tai_label.Create(ivarslabel));
  587. { objc_ivar_list: first the number of elements }
  588. list.Concat(tai_const.Create_32bit(vcnt));
  589. for i:=0 to vcnt-1 do
  590. begin
  591. { reference to the instance variable name }
  592. list.Concat(tai_const.Create_sym(vars[i].namesym));
  593. { reference to the encoded type }
  594. list.Concat(tai_const.Create_sym(vars[i].typesym));
  595. { and the offset of the field }
  596. list.Concat(tai_const.Create_32bit(vars[i].vf.fieldoffset));
  597. end;
  598. end;
  599. (* From GCC:
  600. struct _objc_protocol_extension
  601. {
  602. uint32_t size; // sizeof (struct _objc_protocol_extension)
  603. struct objc_method_list *optional_instance_methods;
  604. struct objc_method_list *optional_class_methods;
  605. struct objc_prop_list *instance_properties;
  606. }
  607. *)
  608. function tobjcrttiwriter_fragile.gen_objc_protocol_ext(list: TAsmList; optinstsym, optclssym: TAsmLabel): TAsmLabel;
  609. var
  610. tcb: ttai_typedconstbuilder;
  611. begin
  612. if assigned(optinstsym) or
  613. assigned(optclssym) then
  614. begin
  615. current_asmdata.getlabel(Result,alt_data);
  616. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  617. tcb.begin_anonymous_record(
  618. internaltypeprefixName[itb_objc_fr_protocol_ext],
  619. C_alignment,1,
  620. targetinfos[target_info.system]^.alignment.recordalignmin,
  621. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  622. { size of this structure }
  623. tcb.emit_ord_const(16,u32inttype);
  624. { optional instance methods }
  625. ConcatSymOrNil(tcb,optinstsym,voidpointertype);
  626. { optional class methods }
  627. ConcatSymOrNil(tcb,optclssym,voidpointertype);
  628. { optional properties (todo) }
  629. ConcatSymOrNil(tcb,nil,voidpointertype);
  630. list.concatList(
  631. tcb.get_final_asmlist(
  632. result,tcb.end_anonymous_record,
  633. sec_objc_protocol_ext,'_OBJC_PROTOCOLEXT',sizeof(pint)
  634. )
  635. );
  636. tcb.free;
  637. end
  638. else
  639. Result:=nil;
  640. end;
  641. { Generate rtti for an Objective-C protocol }
  642. procedure tobjcrttiwriter_fragile.gen_objc_protocol(list:TAsmList; protocol: tobjectdef; out protocollabel: TAsmSymbol);
  643. var
  644. namesym : TAsmLabel;
  645. namedef : tdef;
  646. protolist : TAsmLabel;
  647. reqinstsym,
  648. optinstsym,
  649. reqclssym,
  650. optclssym,
  651. protoext,
  652. lbl : TAsmLabel;
  653. tcb : ttai_typedconstbuilder;
  654. begin
  655. gen_objc_protocol_list(list,protocol.ImplementedInterfaces,protolist);
  656. gen_objc_protocol_elements(list,protocol,reqinstsym,optinstsym,reqclssym,optclssym);
  657. protoext:=gen_objc_protocol_ext(list,optinstsym,optclssym);
  658. current_asmdata.getlabel(lbl,alt_data);
  659. protocollabel:=lbl;
  660. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);;
  661. tcb.begin_anonymous_record(
  662. internaltypeprefixName[itb_objc_fr_protocol],
  663. C_alignment,1,
  664. targetinfos[target_info.system]^.alignment.recordalignmin,
  665. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  666. { protocol's isa - points to information about optional methods/properties }
  667. ConcatSymOrNil(tcb,protoext,voidpointertype);
  668. { name }
  669. objcreatestringpoolentry(protocol.objextname^,sp_objcclassnames,sec_objc_class_names,namesym,namedef);
  670. tcb.queue_init(voidpointertype);
  671. tcb.queue_emit_asmsym(namesym,namedef);
  672. { protocol's list }
  673. ConcatSymOrNil(tcb,protolist,voidpointertype);
  674. { instance methods, in __cat_inst_meth }
  675. ConcatSymOrNil(tcb,reqinstsym,voidpointertype);
  676. { class methods, in __cat_cls_meth }
  677. ConcatSymOrNil(tcb,reqclssym,voidpointertype);
  678. list.concatList(
  679. tcb.get_final_asmlist(
  680. lbl,tcb.end_anonymous_record,
  681. sec_objc_protocol,'_OBJC_PROTOCOL',sizeof(pint)
  682. )
  683. );
  684. tcb.free;
  685. end;
  686. (*
  687. From Clang:
  688. struct _objc_category {
  689. char *category_name;
  690. char *class_name;
  691. struct _objc_method_list *instance_methods;
  692. struct _objc_method_list *class_methods;
  693. struct _objc_protocol_list *protocols;
  694. uint32_t size; // <rdar://4585769>
  695. struct _objc_property_list *instance_properties;
  696. };
  697. *)
  698. { Generate rtti for an Objective-C class and its meta-class. }
  699. procedure tobjcrttiwriter_fragile.gen_objc_category_sections(list:TAsmList; objccat: tobjectdef; out catlabel: TAsmSymbol; out catlabeldef: tdef);
  700. var
  701. catstrsym,
  702. clsstrsym,
  703. protolistsym : TAsmLabel;
  704. instmthdlist,
  705. clsmthdlist,
  706. catsym : TAsmSymbol;
  707. catstrdef,
  708. clsstrdef,
  709. catdef : tdef;
  710. tcb : ttai_typedconstbuilder;
  711. begin
  712. { the category name }
  713. objcreatestringpoolentry(objccat.objextname^,sp_objcclassnames,sec_objc_class_names,catstrsym,catstrdef);
  714. { the name of the class it extends }
  715. objcreatestringpoolentry(objccat.childof.objextname^,sp_objcclassnames,sec_objc_class_names,clsstrsym,clsstrdef);
  716. { generate the methods lists }
  717. gen_objc_methods(list,objccat,instmthdlist,false,true);
  718. gen_objc_methods(list,objccat,clsmthdlist,true,true);
  719. { generate implemented protocols list }
  720. gen_objc_protocol_list(list,objccat.ImplementedInterfaces,protolistsym);
  721. { category declaration section }
  722. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  723. tcb.begin_anonymous_record(
  724. internaltypeprefixName[itb_objc_fr_category],
  725. C_alignment,1,
  726. targetinfos[target_info.system]^.alignment.recordalignmin,
  727. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  728. tcb.queue_init(voidpointertype);
  729. tcb.queue_emit_asmsym(catstrsym,catstrdef);
  730. tcb.queue_init(voidpointertype);
  731. tcb.queue_emit_asmsym(clsstrsym,clsstrdef);
  732. ConcatSymOrNil(tcb,instmthdlist,voidpointertype);
  733. ConcatSymOrNil(tcb,clsmthdlist,voidpointertype);
  734. ConcatSymOrNil(tcb,protolistsym,voidpointertype);
  735. { size of this structure }
  736. tcb.emit_ord_const(28,u32inttype);
  737. { properties, not yet supported }
  738. tcb.emit_ord_const(0,u32inttype);
  739. catdef:=tcb.end_anonymous_record;
  740. catsym:=current_asmdata.DefineAsmSymbol(objccat.rtti_mangledname(objcclassrtti),AB_LOCAL,AT_DATA,catdef);
  741. list.concatList(
  742. tcb.get_final_asmlist(
  743. catsym,catdef,
  744. sec_objc_category,'_OBJC_CATEGORY',sizeof(pint)
  745. )
  746. );
  747. tcb.free;
  748. catlabel:=catsym;
  749. catlabeldef:=catdef;
  750. end;
  751. (*
  752. From Clang:
  753. struct _objc_class {
  754. Class isa;
  755. Class super_class;
  756. const char *name;
  757. long version;
  758. long info;
  759. long instance_size;
  760. struct _objc_ivar_list *ivars;
  761. struct _objc_method_list *methods;
  762. struct _objc_cache *cache;
  763. struct _objc_protocol_list *protocols;
  764. // Objective-C 1.0 extensions (<rdr://4585769>) -- for garbage collection
  765. const char *ivar_layout;
  766. struct _objc_class_ext *ext;
  767. };
  768. *)
  769. { Generate rtti for an Objective-C class and its meta-class. }
  770. procedure tobjcrttiwriter_fragile.gen_objc_classes_sections(list:TAsmList; objclss: tobjectdef; out classlabel: TAsmSymbol; out classlabeldef: tdef);
  771. const
  772. CLS_CLASS = 1;
  773. CLS_META = 2;
  774. CLS_HIDDEN = $20000;
  775. META_INST_SIZE = 40+8; // sizeof(objc_class) + 8
  776. var
  777. root : tobjectdef;
  778. metasym,
  779. mthdlist,
  780. clssym : TAsmSymbol;
  781. superStrDef,
  782. classStrDef,
  783. metaisaStrDef,
  784. metaDef,
  785. clsDef : tdef;
  786. superStrSym,
  787. classStrSym,
  788. metaisaStrSym,
  789. ivarslist,
  790. protolistsym : TAsmLabel;
  791. hiddenflag : cardinal;
  792. tcb : ttai_typedconstbuilder;
  793. begin
  794. { generate the class methods list }
  795. gen_objc_methods(list,objclss,mthdlist,true,false);
  796. { generate implemented protocols list }
  797. gen_objc_protocol_list(list,objclss.ImplementedInterfaces,protolistsym);
  798. { register necessary names }
  799. { 1) the superclass }
  800. if assigned(objclss.childof) then
  801. objcreatestringpoolentry(objclss.childof.objextname^,sp_objcclassnames,sec_objc_class_names,superStrSym,superStrDef)
  802. else
  803. begin
  804. { not empty string, but nil! }
  805. superStrSym:=nil;
  806. superStrDef:=voidpointertype;
  807. end;
  808. { 2) the current class }
  809. objcreatestringpoolentry(objclss.objextname^,sp_objcclassnames,sec_objc_class_names,classStrSym,classStrDef);
  810. { 3) the isa }
  811. { From Clang: The isa for the meta-class is the root of the hierarchy. }
  812. root:=objclss;
  813. while assigned(root.childof) do
  814. root:=root.childof;
  815. objcreatestringpoolentry(root.objextname^,sp_objcclassnames,sec_objc_class_names,metaisaStrSym,metaisaStrDef);
  816. { 4) the flags }
  817. { consider every class declared in the implementation section of a unit
  818. as "hidden"
  819. }
  820. hiddenflag:=0;
  821. if (objclss.owner.symtabletype=staticsymtable) and
  822. current_module.is_unit then
  823. hiddenflag:=CLS_HIDDEN;
  824. { class declaration section }
  825. { 1) meta-class declaration }
  826. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  827. tcb.begin_anonymous_record(internaltypeprefixName[itb_objc_fr_meta_class],
  828. C_alignment,1,
  829. targetinfos[target_info.system]^.alignment.recordalignmin,
  830. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  831. tcb.queue_init(voidpointertype);
  832. tcb.queue_emit_asmsym(metaisaStrSym,metaisaStrDef);
  833. { pointer to the superclass name if any, otherwise nil }
  834. if assigned(superstrsym) then
  835. begin
  836. tcb.queue_init(voidpointertype);
  837. tcb.queue_emit_asmsym(superStrSym,superStrDef);
  838. end
  839. else
  840. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  841. { pointer to the class name }
  842. tcb.queue_init(voidpointertype);
  843. tcb.queue_emit_asmsym(classStrSym,classStrDef);
  844. { version is always 0 currently }
  845. tcb.emit_ord_const(0,u32inttype);
  846. { CLS_META for meta-classes }
  847. tcb.emit_ord_const(hiddenflag or CLS_META,u32inttype);
  848. { size of the meta-class instance: sizeof(objc_class) + 8 bytes }
  849. tcb.emit_ord_const(META_INST_SIZE,u32inttype);
  850. { meta-classes don't have ivars list (=0) }
  851. tcb.emit_ord_const(0,u32inttype);
  852. { class methods list (stored in "__cls_meth" section) }
  853. ConcatSymOrNil(tcb,mthdlist,voidpointertype);
  854. { From Clang: cache is always nil }
  855. tcb.emit_ord_const(0,u32inttype);
  856. { protocols }
  857. ConcatSymOrNil(tcb,protolistsym,voidpointertype);
  858. { From Clang: ivar_layout for meta-class is always NULL. }
  859. tcb.emit_ord_const(0,u32inttype);
  860. { From Clang: The class extension is always unused for meta-classes. }
  861. tcb.emit_ord_const(0,u32inttype);
  862. metaDef:=tcb.end_anonymous_record;
  863. metasym:=current_asmdata.DefineAsmSymbol(objclss.rtti_mangledname(objcmetartti),AB_LOCAL,AT_DATA,metadef);
  864. list.concatList(
  865. tcb.get_final_asmlist(
  866. metasym,metaDef,
  867. sec_objc_meta_class,'_OBJC_META_CLASS',sizeof(pint)
  868. )
  869. );
  870. tcb.free;
  871. { 2) regular class declaration }
  872. { generate the instance methods list }
  873. gen_objc_methods(list,objclss,mthdlist,false,false);
  874. { generate the instance variables list }
  875. gen_objc_ivars(list,objclss,ivarslist);
  876. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  877. tcb.begin_anonymous_record(internaltypeprefixName[itb_objc_fr_class],
  878. C_alignment,1,
  879. targetinfos[target_info.system]^.alignment.recordalignmin,
  880. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  881. { for class declaration: the isa points to the meta-class declaration }
  882. tcb.emit_tai(Tai_const.Create_sym(metasym),cpointerdef.getreusable(metaDef));
  883. { pointer to the super_class name if any, nil otherwise }
  884. if assigned(superStrSym) then
  885. begin
  886. tcb.queue_init(voidcodepointertype);
  887. tcb.queue_emit_asmsym(superStrSym,superStrDef)
  888. end
  889. else
  890. tcb.emit_tai(Tai_const.Create_nil_dataptr,voidcodepointertype);
  891. { pointer to the class name }
  892. tcb.queue_init(voidcodepointertype);
  893. tcb.queue_emit_asmsym(classStrSym,classStrDef);
  894. { version is always 0 currently }
  895. tcb.emit_ord_const(0,u32inttype);
  896. { CLS_CLASS for classes }
  897. tcb.emit_ord_const(hiddenflag or CLS_CLASS,u32inttype);
  898. { size of instance: total size of instance variables }
  899. tcb.emit_ord_const(tobjectsymtable(objclss.symtable).datasize,u32inttype);
  900. { objc_ivar_list (stored in "__instance_vars" section) }
  901. ConcatSymOrNil(tcb,ivarslist,voidpointertype);
  902. { instance methods list (stored in "__inst_meth" section) }
  903. ConcatSymOrNil(tcb,mthdlist,voidpointertype);
  904. { From Clang: cache is always NULL }
  905. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  906. { protocols, protolistsym has been created for meta-class, no need to create another one}
  907. ConcatSymOrNil(tcb, protolistsym,voidpointertype);
  908. { From Clang: strong ivar_layout, necessary for garbage collection support }
  909. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  910. { TODO: From Clang: weak ivar_layout, necessary for garbage collection support }
  911. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  912. clsDef:=tcb.end_anonymous_record;
  913. clssym:=current_asmdata.DefineAsmSymbol(objclss.rtti_mangledname(objcclassrtti),AB_LOCAL,AT_DATA,clsDef);
  914. list.concatList(
  915. tcb.get_final_asmlist(
  916. clssym,clsDef,
  917. sec_objc_class,'_OBJC_CLASS',sizeof(pint)
  918. )
  919. );
  920. tcb.free;
  921. classlabel:=clssym;
  922. classlabeldef:=clsDef;
  923. end;
  924. { Generate the global information sections (objc_symbols and objc_module_info)
  925. for this module. }
  926. procedure tobjcrttiwriter_fragile.gen_objc_info_sections(list: tasmlist);
  927. var
  928. i: longint;
  929. sym : TAsmSymbol;
  930. lab : TAsmLabel;
  931. symsdef,
  932. def : tdef;
  933. parent: tobjectdef;
  934. superclasses: tfpobjectlist;
  935. tcb: ttai_typedconstbuilder;
  936. begin
  937. if (classsyms.count<>0) or
  938. (catsyms.count<>0) then
  939. begin
  940. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  941. tcb.begin_anonymous_record('',
  942. C_alignment,1,
  943. targetinfos[target_info.system]^.alignment.recordalignmin,
  944. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  945. { ??? (always 0 in Clang) }
  946. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  947. { ??? (From Clang: always 0, pointer to some selector) }
  948. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  949. { From Clang: number of defined classes }
  950. tcb.emit_ord_const(classsyms.count,u16inttype);
  951. { From Clang: number of defined categories }
  952. tcb.emit_ord_const(catsyms.count,u16inttype);
  953. { first all classes }
  954. for i:=0 to classsyms.count-1 do
  955. tcb.emit_tai(Tai_const.Create_sym(tasmsymbol(classsyms[i])),tdef(classrttidefs[i]));
  956. { then all categories }
  957. for i:=0 to catsyms.count-1 do
  958. tcb.emit_tai(Tai_const.Create_sym(tasmsymbol(catsyms[i])),tdef(catrttidefs[i]));
  959. symsdef:=tcb.end_anonymous_record;
  960. sym := current_asmdata.DefineAsmSymbol(target_asm.labelprefix+'_OBJC_SYMBOLS_$',AB_LOCAL,AT_DATA,symsdef);
  961. list.concatList(tcb.get_final_asmlist(sym,
  962. symsdef,
  963. sec_objc_symbols,'_OBJC_SYMBOLS',
  964. sizeof(pint)));
  965. end
  966. else
  967. begin
  968. sym:=nil;
  969. symsdef:=nil;
  970. end;
  971. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  972. tcb.begin_anonymous_record('',
  973. C_alignment,1,
  974. targetinfos[target_info.system]^.alignment.recordalignmin,
  975. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  976. { version number = 7 (always, both for gcc and clang) }
  977. tcb.emit_ord_const(7,ptruinttype);
  978. { sizeof(objc_module): 4 pointer-size entities }
  979. list.Concat(Tai_const.Create_pint(sizeof(pint)*4));
  980. tcb.emit_ord_const(sizeof(pint)*4,ptruinttype);
  981. { used to be file name, now unused (points to empty string) }
  982. objcreatestringpoolentry('',sp_objcclassnames,sec_objc_class_names,lab,def);
  983. tcb.emit_tai(Tai_const.Create_sym(lab),def);
  984. { pointer to classes/categories list declared in this module }
  985. if assigned(sym) then
  986. tcb.emit_tai(tai_const.Create_sym(sym),symsdef)
  987. else
  988. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  989. current_asmdata.getlabel(lab,alt_data);
  990. list.concatList(tcb.get_final_asmlist(lab,
  991. tcb.end_anonymous_record,sec_objc_module_info,'_OBJC_MODULE_INFO',4));
  992. { Add lazy references to parent classes of all classes defined in this unit }
  993. superclasses:=tfpobjectlist.create(false);
  994. for i:=0 to classdefs.count-1 do
  995. begin
  996. parent:=tobjectdef(classdefs[i]).childof;
  997. { warning: linear search, performance hazard if large number of subclasses }
  998. if assigned(parent) and
  999. (superclasses.indexof(parent)=-1) then
  1000. begin
  1001. list.concat(tai_directive.create(asd_lazy_reference,'.objc_class_name_'+parent.objextname^));
  1002. superclasses.add(parent);
  1003. end;
  1004. end;
  1005. for i:=0 to catdefs.count-1 do
  1006. begin
  1007. parent:=tobjectdef(catdefs[i]).childof;
  1008. { warning: linear search, performance hazard if large number of subclasses }
  1009. if assigned(parent) and
  1010. (superclasses.indexof(parent)=-1) then
  1011. begin
  1012. list.concat(tai_directive.create(asd_lazy_reference,'.objc_class_name_'+parent.objextname^));
  1013. superclasses.add(parent);
  1014. end;
  1015. end;
  1016. superclasses.free;
  1017. { reference symbols for all classes and categories defined in this unit }
  1018. for i:=0 to classdefs.count-1 do
  1019. list.concat(tai_symbol.Createname_global_value('.objc_class_name_'+tobjectdef(classdefs[i]).objextname^,AT_DATA,0,0,voidpointertype));
  1020. for i:=0 to catdefs.count-1 do
  1021. list.concat(tai_symbol.Createname_global_value('.objc_category_name_'+
  1022. tobjectdef(catdefs[i]).childof.objextname^+'_'+
  1023. tobjectdef(catdefs[i]).objextname^,AT_DATA,0,0,voidpointertype));
  1024. end;
  1025. constructor tobjcrttiwriter_fragile.create;
  1026. begin
  1027. inherited create(oa_fragile);
  1028. end;
  1029. {******************************************************************
  1030. RTTI generation -- Non-Fragile ABI
  1031. *******************************************************************}
  1032. (*
  1033. From Clang:
  1034. /// EmitIvarList - Emit the ivar list for the given
  1035. /// implementation. The return value has type
  1036. /// IvarListnfABIPtrTy.
  1037. /// struct _ivar_t {
  1038. /// unsigned long int *offset; // pointer to ivar offset location
  1039. /// char *name;
  1040. /// char *type;
  1041. /// uint32_t alignment;
  1042. /// uint32_t size;
  1043. /// }
  1044. /// struct _ivar_list_t {
  1045. /// uint32 entsize; // sizeof(struct _ivar_t)
  1046. /// uint32 count;
  1047. /// struct _iver_t list[count];
  1048. /// }
  1049. ///
  1050. *)
  1051. procedure tobjcrttiwriter_nonfragile.gen_objc_ivars(list: tasmlist; objccls: tobjectdef; out ivarslabel: tasmlabel);
  1052. type
  1053. ivar_data = record
  1054. vf : tfieldvarsym;
  1055. namesym : TAsmLabel;
  1056. namedef : tdef;
  1057. typesym : TAsmLabel;
  1058. typedef : tdef;
  1059. offssym : TAsmSymbol;
  1060. end;
  1061. var
  1062. ivtype: tdef;
  1063. vf : tfieldvarsym;
  1064. vars : array of ivar_data;
  1065. i : integer;
  1066. vcnt : integer;
  1067. enctype : ansistring;
  1068. encerr : tdef;
  1069. prefix : shortstring;
  1070. vis : TAsmsymbind;
  1071. tcb : ttai_typedconstbuilder;
  1072. pptruinttype : tdef;
  1073. begin
  1074. ivarslabel:=nil;
  1075. prefix:='';
  1076. vcnt:=0;
  1077. setLength(vars,objccls.symtable.SymList.Count);
  1078. tcb:=nil;
  1079. prefix:='';
  1080. for i:=0 to objccls.symtable.SymList.Count-1 do
  1081. if tsym(objccls.symtable.SymList[i]).typ=fieldvarsym then
  1082. begin
  1083. vf:=tfieldvarsym(objccls.symtable.SymList[i]);
  1084. if objctryencodetype(vf.vardef,enctype,encerr) then
  1085. begin
  1086. vars[vcnt].vf:=vf;
  1087. objcreatestringpoolentry(vf.RealName,sp_objcvarnames,sec_objc_meth_var_names,vars[vcnt].namesym,vars[vcnt].namedef);
  1088. objcreatestringpoolentry(enctype,sp_objcvartypes,sec_objc_meth_var_types,vars[vcnt].typesym,vars[vcnt].typedef);
  1089. if (vcnt=0) then
  1090. begin
  1091. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  1092. prefix:=target_info.cprefix+'OBJC_IVAR_$_'+objccls.objextname^+'.';
  1093. end
  1094. else
  1095. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  1096. { This matches gcc/Clang, but is strange: I would expect private
  1097. fields to be local symbols rather than private_extern (which
  1098. is "package-global") (JM)
  1099. }
  1100. if not(vf.visibility in [vis_public,vis_protected,vis_strictprotected]) then
  1101. vis:=AB_PRIVATE_EXTERN
  1102. else
  1103. vis:=AB_GLOBAL;
  1104. vars[vcnt].offssym:=current_asmdata.DefineAsmSymbol(prefix+vf.RealName,vis,AT_DATA,ptruinttype);
  1105. tcb.emit_tai(tai_const.create_pint(vf.fieldoffset),ptruinttype);
  1106. list.concatList(
  1107. tcb.get_final_asmlist(
  1108. vars[vcnt].offssym,ptruinttype,
  1109. sec_objc_const,'_OBJC_IVAR_OFFSETS',sizeof(pint)
  1110. )
  1111. );
  1112. tcb.free;
  1113. inc(vcnt);
  1114. end
  1115. else
  1116. { must be caught during parsing }
  1117. internalerror(2009092301);
  1118. end;
  1119. if vcnt=0 then
  1120. exit;
  1121. tcb:=ctai_typedconstbuilder.create([tcalo_is_lab,tcalo_new_section]);
  1122. current_asmdata.getlabel(ivarslabel,alt_data);
  1123. tcb.begin_anonymous_record(
  1124. internaltypeprefixName[itb_objc_nf_ivars]+tostr(vcnt),
  1125. C_alignment,1,
  1126. targetinfos[target_info.system]^.alignment.recordalignmin,
  1127. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1128. { size of each entry -- always 32 bit value }
  1129. ivtype:=search_named_unit_globaltype('OBJC','OBJC_IVAR',true).typedef;
  1130. tcb.emit_ord_const(ivtype.size,u32inttype);
  1131. { number of entries -- always 32 bit value }
  1132. tcb.emit_ord_const(vcnt,u32inttype);
  1133. { we use voidpointertype for all elements so that we can reuse the
  1134. recorddef for all ivar tables with the same number of elements }
  1135. pptruinttype:=cpointerdef.getreusable(ptruinttype);
  1136. for i:=0 to vcnt-1 do
  1137. begin
  1138. { reference to the offset }
  1139. tcb.emit_tai(tai_const.Create_sym(vars[i].offssym),pptruinttype);
  1140. { reference to the instance variable name (}
  1141. tcb.queue_init(voidpointertype);
  1142. tcb.queue_emit_asmsym(vars[i].namesym,vars[i].namedef);
  1143. { reference to the encoded type }
  1144. tcb.queue_init(voidpointertype);
  1145. tcb.queue_emit_asmsym(vars[i].typesym,vars[i].typedef);
  1146. { alignment -- always 32 bit value }
  1147. tcb.emit_ord_const(vars[i].vf.vardef.alignment,u32inttype);
  1148. { size -- always 32 bit value }
  1149. tcb.emit_ord_const(vars[i].vf.vardef.size,u32inttype);
  1150. end;
  1151. list.concatList(
  1152. tcb.get_final_asmlist(
  1153. ivarslabel,tcb.end_anonymous_record,
  1154. sec_objc_instance_vars,'_OBJC_INSTANCE_VARS',sizeof(pint)
  1155. )
  1156. );
  1157. tcb.free;
  1158. end;
  1159. (*
  1160. From Clang:
  1161. /// GetOrEmitProtocol - Generate the protocol meta-data:
  1162. /// @code
  1163. /// struct _protocol_t {
  1164. /// id isa; // NULL
  1165. /// const char * const protocol_name;
  1166. /// const struct _protocol_list_t * protocol_list; // super protocols
  1167. /// const struct method_list_t * const instance_methods;
  1168. /// const struct method_list_t * const class_methods;
  1169. /// const struct method_list_t *optionalInstanceMethods;
  1170. /// const struct method_list_t *optionalClassMethods;
  1171. /// const struct _prop_list_t * properties;
  1172. /// const uint32_t size; // sizeof(struct _protocol_t)
  1173. /// const uint32_t flags; // = 0
  1174. /// }
  1175. /// @endcode
  1176. *)
  1177. procedure tobjcrttiwriter_nonfragile.gen_objc_protocol(list: tasmlist; protocol: tobjectdef; out protocollabel: tasmsymbol);
  1178. var
  1179. lbl,
  1180. listsym : TAsmSymbol;
  1181. namedef : tdef;
  1182. namesym,
  1183. protolist : TAsmLabel;
  1184. reqinstsym,
  1185. reqclssym,
  1186. optinstsym,
  1187. optclssym : TAsmLabel;
  1188. prottype : tdef;
  1189. tcb : ttai_typedconstbuilder;
  1190. begin
  1191. gen_objc_protocol_list(list,protocol.ImplementedInterfaces,protolist);
  1192. gen_objc_protocol_elements(list,protocol,reqinstsym,optinstsym,reqclssym,optclssym);
  1193. { label for the protocol needs to be
  1194. a) in a coalesced section (so multiple definitions of the same protocol
  1195. can be merged by the linker)
  1196. b) private_extern (should only be merged within the same module)
  1197. c) weakly defined (so multiple definitions don't cause errors)
  1198. }
  1199. prottype:=search_named_unit_globaltype('OBJC','OBJC_PROTOCOL',true).typedef;
  1200. lbl:=current_asmdata.DefineAsmSymbol(protocol.rtti_mangledname(objcclassrtti),AB_PRIVATE_EXTERN,AT_DATA,prottype);
  1201. protocollabel:=lbl;
  1202. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_weak]);
  1203. tcb.maybe_begin_aggregate(prottype);
  1204. { protocol's isa - always nil }
  1205. tcb.emit_tai(Tai_const.Create_nil_dataptr,objc_idtype);
  1206. { name }
  1207. objcreatestringpoolentry(protocol.objextname^,sp_objcclassnames,sec_objc_class_names,namesym,namedef);
  1208. tcb.queue_init(charpointertype);
  1209. tcb.queue_emit_asmsym(namesym,namedef);
  1210. { parent protocols list }
  1211. ConcatSymOrNil(tcb,protolist,voidpointertype);
  1212. { required instance methods }
  1213. ConcatSymOrNil(tcb,reqinstsym,voidpointertype);
  1214. { required class methods }
  1215. ConcatSymOrNil(tcb,reqclssym,voidpointertype);
  1216. { optional instance methods }
  1217. ConcatSymOrNil(tcb,optinstsym,voidpointertype);
  1218. { optional class methods }
  1219. ConcatSymOrNil(tcb,optclssym,voidpointertype);
  1220. { TODO: properties }
  1221. tcb.emit_tai(Tai_const.Create_nil_dataptr,voidpointertype);
  1222. { size of this type }
  1223. tcb.emit_ord_const(prottype.size,u32inttype);
  1224. { flags }
  1225. tcb.emit_ord_const(0,u32inttype);
  1226. tcb.maybe_end_aggregate(prottype);
  1227. list.concatList(
  1228. tcb.get_final_asmlist(
  1229. lbl,prottype,
  1230. sec_data_coalesced,'_OBJC_PROTOCOL',sizeof(pint)
  1231. )
  1232. );
  1233. tcb.free;
  1234. { also add an entry to the __DATA, __objc_protolist section, required to
  1235. register the protocol with the runtime }
  1236. listsym:=current_asmdata.DefineAsmSymbol(protocol.rtti_mangledname(objcmetartti),AB_PRIVATE_EXTERN,AT_DATA,cpointerdef.getreusable(prottype));
  1237. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_weak]);
  1238. tcb.emit_tai(tai_const.Create_sym(lbl),cpointerdef.getreusable(prottype));
  1239. list.concatList(
  1240. tcb.get_final_asmlist(
  1241. listsym,cpointerdef.getreusable(prottype),
  1242. sec_objc_protolist,'_OBJC_PROTOLIST',sizeof(pint)
  1243. )
  1244. );
  1245. tcb.free;
  1246. end;
  1247. (*
  1248. From Clang:
  1249. /// struct _category_t {
  1250. /// const char * const name;
  1251. /// struct _class_t *const cls;
  1252. /// const struct _method_list_t * const instance_methods;
  1253. /// const struct _method_list_t * const class_methods;
  1254. /// const struct _protocol_list_t * const protocols;
  1255. /// const struct _prop_list_t * const properties;
  1256. /// }
  1257. *)
  1258. procedure tobjcrttiwriter_nonfragile.gen_objc_category_sections(list:TAsmList; objccat: tobjectdef; out catlabel: TAsmSymbol; out catlabeldef: tdef);
  1259. var
  1260. catstrsym,
  1261. protolistsym : TAsmLabel;
  1262. instmthdlist,
  1263. clsmthdlist,
  1264. clssym,
  1265. catsym : TAsmSymbol;
  1266. catstrdef,
  1267. catdef : tdef;
  1268. tcb : ttai_typedconstbuilder;
  1269. begin
  1270. { the category name }
  1271. objcreatestringpoolentry(objccat.objextname^,sp_objcclassnames,sec_objc_class_names,catstrsym,catstrdef);
  1272. { the class it extends }
  1273. clssym:=current_asmdata.RefAsmSymbol(objccat.childof.rtti_mangledname(objcclassrtti));
  1274. { generate the methods lists }
  1275. gen_objc_methods(list,objccat,instmthdlist,false,true);
  1276. gen_objc_methods(list,objccat,clsmthdlist,true,true);
  1277. { generate implemented protocols list }
  1278. gen_objc_protocol_list(list,objccat.ImplementedInterfaces,protolistsym);
  1279. { category declaration section }
  1280. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  1281. tcb.begin_anonymous_record(internaltypeprefixName[itb_objc_nf_category],
  1282. C_alignment,1,
  1283. targetinfos[target_info.system]^.alignment.recordalignmin,
  1284. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1285. tcb.queue_init(voidpointertype);
  1286. tcb.queue_emit_asmsym(catstrsym,catstrdef);
  1287. tcb.emit_tai(Tai_const.Create_sym(clssym),voidpointertype);
  1288. ConcatSymOrNil(tcb,instmthdlist,voidpointertype);
  1289. ConcatSymOrNil(tcb,clsmthdlist,voidpointertype);
  1290. ConcatSymOrNil(tcb,protolistsym,voidpointertype);
  1291. { properties, not yet supported }
  1292. tcb.emit_tai(Tai_const.Create_nil_dataptr,voidpointertype);
  1293. catdef:=tcb.end_anonymous_record;
  1294. catsym:=current_asmdata.DefineAsmSymbol(objccat.rtti_mangledname(objcclassrtti),AB_LOCAL,AT_DATA,catdef);
  1295. list.concatList(
  1296. tcb.get_final_asmlist(
  1297. catsym,catdef,
  1298. sec_objc_const,'_OBJC_CATEGORY',sizeof(pint)
  1299. )
  1300. );
  1301. tcb.free;
  1302. catlabel:=catsym;
  1303. catlabeldef:=catdef;
  1304. end;
  1305. (*
  1306. From Clang:
  1307. /// BuildIvarLayout - Builds ivar layout bitmap for the class
  1308. /// implementation for the __strong or __weak case.
  1309. /// The layout map displays which words in ivar list must be skipped
  1310. /// and which must be scanned by GC (see below). String is built of bytes.
  1311. /// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
  1312. /// of words to skip and right nibble is count of words to scan. So, each
  1313. /// nibble represents up to 15 workds to skip or scan. Skipping the rest is
  1314. /// represented by a 0x00 byte which also ends the string.
  1315. /// 1. when ForStrongLayout is true, following ivars are scanned:
  1316. /// - id, Class
  1317. /// - object * // note: this "object" means "Objective-C object" (JM)
  1318. /// - __strong anything
  1319. ///
  1320. /// 2. When ForStrongLayout is false, following ivars are scanned:
  1321. /// - __weak anything
  1322. *)
  1323. (*
  1324. Only required when supporting garbage collection
  1325. procedure tobjcrttiwriter_nonfragile.gen_objc_ivargc_recursive(st: tabstractrecordsymtable; ptrbset: tbitset; startoffset: puint; il: tivarlayouttype);
  1326. var
  1327. i: longint;
  1328. fs: tfieldvarsym;
  1329. includelen: longint;
  1330. begin
  1331. for i:=0 to st.SymList.count-1 do
  1332. if (tsym(st.symlist[i]).typ=fieldvarsym) then
  1333. begin
  1334. fs:=tfieldvarsym(st.symlist[i]);
  1335. includelen:=0;
  1336. case fs.vardef.typ of
  1337. pointerdef,
  1338. classrefdef:
  1339. if (fs.vardef=objc_idtype) or
  1340. (fs.vardef=objc_metaclasstype) then
  1341. includelen:=1;
  1342. recorddef:
  1343. TODO: bitpacking -> offset differences
  1344. gen_objc_ivargc_recursive(tabstractrecordsymtable(trecorddef(fs.vardef).symtable),ptrbset,startoffset+fs.fieldoffset,il);
  1345. arraydef:
  1346. begin
  1347. if not is_special_
  1348. end;
  1349. objectdef :
  1350. begin
  1351. case tobjectdef(fs.vardef).objecttype of
  1352. odt_objcclass,
  1353. odt_objcprotocol:
  1354. includelen:=1;
  1355. odt_object:
  1356. gen_objc_ivargc_recursive(tabstractrecordsymtable(tobjectdef(fs.vardef).symtable),ptrbset,startoffset+fs.fieldoffset,il);
  1357. end;
  1358. end;
  1359. end;
  1360. end;
  1361. end;
  1362. function tobjcrttiwriter_nonfragile.gen_objc_ivargcstring(objclss: tobjectdef; il: tivarlayouttype): ansistring;
  1363. var
  1364. ptrbset: tbitset;
  1365. parent: tobjectdef;
  1366. size,
  1367. startoffset: puint;
  1368. i: longint;
  1369. begin
  1370. size:=tObjectSymtable(objclss.symtable).datasize;
  1371. if assigned(objclss.childof) then
  1372. startoffset:=tObjectSymtable(objclss.childof.symtable).datasize
  1373. else
  1374. startoffset:=0;
  1375. size:=size-startoffset;
  1376. ptrbset:=tbitset.create_bytesize((size+sizeof(ptruint)-1) div sizeof(ptruint));
  1377. { has to include info for this class' fields and those of all parent
  1378. classes as well
  1379. }
  1380. parent:=obclss;
  1381. repeat
  1382. gen_objc_ivargc_recursive(parent.symtable,ptrbset,0,il);
  1383. parent:=parent.childof;
  1384. until not assigned(parent);
  1385. { convert bits set to encoded string }
  1386. end;
  1387. *)
  1388. (*
  1389. From Clang:
  1390. /// struct _class_ro_t {
  1391. /// uint32_t const flags;
  1392. /// uint32_t const instanceStart;
  1393. /// uint32_t const instanceSize;
  1394. /// uint32_t const reserved; // only when building for 64bit targets
  1395. /// const uint8_t * const ivarLayout;
  1396. /// const char *const name;
  1397. /// const struct _method_list_t * const baseMethods;
  1398. /// const struct _protocol_list_t *const baseProtocols;
  1399. /// const struct _ivar_list_t *const ivars;
  1400. /// const uint8_t * const weakIvarLayout;
  1401. /// const struct _prop_list_t * const properties;
  1402. /// }
  1403. *)
  1404. procedure tobjcrttiwriter_nonfragile.gen_objc_class_ro_part(list: tasmlist; objclss: tobjectdef; protolistsym: TAsmSymbol; out classrolabel: tasmsymbol; metaclass: boolean);
  1405. const
  1406. CLS_CLASS = 0;
  1407. CLS_META = 1;
  1408. CLS_ROOT = 2;
  1409. OBJC2_CLS_HIDDEN = $10;
  1410. CLS_EXCEPTION = $20;
  1411. var
  1412. methodssym,
  1413. rosym : TAsmSymbol;
  1414. classStrDef : tdef;
  1415. classStrSym,
  1416. ivarslab : TAsmLabel;
  1417. rodef,
  1418. class_type : tdef;
  1419. start,
  1420. size,
  1421. flags : cardinal;
  1422. rttitype : trttitype;
  1423. firstfield : tfieldvarsym;
  1424. i : longint;
  1425. tcb : ttai_typedconstbuilder;
  1426. begin
  1427. { consider every class declared in the implementation section of a unit
  1428. as "hidden"
  1429. }
  1430. flags:=0;
  1431. if (objclss.owner.symtabletype=staticsymtable) and
  1432. current_module.is_unit then
  1433. flags:=OBJC2_CLS_HIDDEN;
  1434. if metaclass then
  1435. begin
  1436. flags:=flags or CLS_META;
  1437. rttitype:=objcmetarortti;
  1438. { metaclass size/start: always size of objc_object }
  1439. class_type:=search_named_unit_globaltype('OBJC','OBJC_OBJECT',true).typedef;
  1440. start:=class_type.size;
  1441. size:=start;
  1442. end
  1443. else
  1444. begin
  1445. flags:=flags or CLS_CLASS;
  1446. rttitype:=objcclassrortti;
  1447. size:=tObjectSymtable(objclss.symtable).datasize;
  1448. { can't simply use childof's datasize, because alignment may cause the
  1449. first field to skip a couple of bytes after the previous end }
  1450. firstfield:=nil;
  1451. for i:=0 to objclss.symtable.SymList.Count-1 do
  1452. if (tsym(objclss.symtable.SymList[i]).typ=fieldvarsym) then
  1453. begin
  1454. firstfield:=tfieldvarsym(objclss.symtable.SymList[i]);
  1455. break;
  1456. end;
  1457. if assigned(firstfield) then
  1458. start:=firstfield.fieldoffset
  1459. else
  1460. { no extra fields -> start = size }
  1461. start:=size;
  1462. end;
  1463. if not assigned(objclss.childof) then
  1464. flags:=flags or CLS_ROOT;
  1465. objcreatestringpoolentry(objclss.objextname^,sp_objcclassnames,sec_objc_class_names,classStrSym,classStrDef);
  1466. { generate methods list }
  1467. gen_objc_methods(list,objclss,methodssym,metaclass,false);
  1468. { generate ivars (nil for metaclass) }
  1469. if metaclass then
  1470. ivarslab:=nil
  1471. else
  1472. gen_objc_ivars(list,objclss,ivarslab);
  1473. { class declaration section }
  1474. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  1475. tcb.begin_anonymous_record(
  1476. internaltypeprefixName[itb_obcj_nf_class_ro_part],
  1477. C_alignment,1,
  1478. targetinfos[target_info.system]^.alignment.recordalignmin,
  1479. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1480. tcb.emit_ord_const(flags,u32inttype);
  1481. tcb.emit_ord_const(start,u32inttype);
  1482. tcb.emit_ord_const(size,u32inttype);
  1483. { strong ivar layout for garbage collection (deprecated) }
  1484. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  1485. tcb.queue_init(voidpointertype);
  1486. tcb.queue_emit_asmsym(classStrSym,classStrDef);
  1487. ConcatSymOrNil(tcb,methodssym,voidpointertype);
  1488. ConcatSymOrNil(tcb,protolistsym,voidpointertype);
  1489. ConcatSymOrNil(tcb,ivarslab,voidpointertype);
  1490. { weak ivar layout for garbage collection (deprecated) }
  1491. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  1492. { TODO: properties }
  1493. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  1494. rodef:=tcb.end_anonymous_record;
  1495. rosym:=current_asmdata.DefineAsmSymbol(objclss.rtti_mangledname(rttitype),AB_LOCAL,AT_DATA,rodef);
  1496. list.concatList(
  1497. tcb.get_final_asmlist(
  1498. rosym,rodef,
  1499. sec_objc_const,'_OBJC_META_CLASS',sizeof(pint)
  1500. )
  1501. );
  1502. tcb.free;
  1503. classrolabel:=rosym;
  1504. end;
  1505. (*
  1506. From Clang:
  1507. /// struct _class_t {
  1508. /// struct _class_t *isa;
  1509. /// struct _class_t * const superclass;
  1510. /// void *cache;
  1511. /// IMP *vtable;
  1512. /// struct class_ro_t *ro;
  1513. /// }
  1514. ///
  1515. *)
  1516. { Generate rtti for an Objective-C class and its meta-class. }
  1517. procedure tobjcrttiwriter_nonfragile.gen_objc_classes_sections(list:TAsmList; objclss: tobjectdef; out classlabel: TAsmSymbol; out classlabeldef: tdef);
  1518. var
  1519. root : tobjectdef;
  1520. superSym,
  1521. superMetaSym,
  1522. metaisaSym,
  1523. metasym,
  1524. clssym,
  1525. metarosym,
  1526. rosym : TAsmSymbol;
  1527. protolistsym : TAsmLabel;
  1528. vis : TAsmsymbind;
  1529. isatcb,
  1530. metatcb : ttai_typedconstbuilder;
  1531. metadef,
  1532. classdef : tdef;
  1533. begin
  1534. { A) Register necessary names }
  1535. { 1) the current class and metaclass }
  1536. if (objclss.owner.symtabletype=globalsymtable) then
  1537. vis:=AB_GLOBAL
  1538. else
  1539. vis:=AB_PRIVATE_EXTERN;
  1540. { create the typed const builders so we can get the (provisional) types
  1541. for the class and metaclass symbols }
  1542. isatcb:=ctai_typedconstbuilder.create([]);
  1543. classdef:=isatcb.begin_anonymous_record(
  1544. internaltypeprefixName[itb_objc_nf_class],
  1545. C_alignment,1,
  1546. targetinfos[target_info.system]^.alignment.recordalignmin,
  1547. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1548. metatcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  1549. metadef:=metatcb.begin_anonymous_record(
  1550. internaltypeprefixName[itb_objc_nf_meta_class],
  1551. C_alignment,1,
  1552. targetinfos[target_info.system]^.alignment.recordalignmin,
  1553. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1554. clssym:=current_asmdata.DefineAsmSymbol(objclss.rtti_mangledname(objcclassrtti),vis,AT_DATA,classdef);
  1555. metasym:=current_asmdata.DefineAsmSymbol(objclss.rtti_mangledname(objcmetartti),vis,AT_DATA,metadef);
  1556. { 2) the superclass and meta superclass }
  1557. if assigned(objclss.childof) then
  1558. begin
  1559. superSym:=current_asmdata.RefAsmSymbol(objclss.childof.rtti_mangledname(objcclassrtti));
  1560. superMetaSym:=current_asmdata.RefAsmSymbol(objclss.childof.rtti_mangledname(objcmetartti));
  1561. end
  1562. else
  1563. begin
  1564. superSym:=nil;
  1565. { the class itself }
  1566. superMetaSym:=clssym;
  1567. end;
  1568. { 3) the isa }
  1569. { From Clang: The isa for the meta-class is the root of the hierarchy. }
  1570. root:=objclss;
  1571. while assigned(root.childof) do
  1572. root:=root.childof;
  1573. metaisaSym:=current_asmdata.RefAsmSymbol(root.rtti_mangledname(objcmetartti));
  1574. { 4) the implemented protocols (same for metaclass and regular class) }
  1575. gen_objc_protocol_list(list,objclss.ImplementedInterfaces,protolistsym);
  1576. { 5) the read-only parts of the class definitions }
  1577. gen_objc_class_ro_part(list,objclss,protolistsym,metarosym,true);
  1578. gen_objc_class_ro_part(list,objclss,protolistsym,rosym,false);
  1579. { B) Class declaration section }
  1580. { both class and metaclass are in the objc_data section for obj-c 2 }
  1581. { 1) meta-class declaration }
  1582. { the isa }
  1583. metatcb.emit_tai(Tai_const.Create_sym(metaisaSym),voidpointertype);
  1584. { the superclass }
  1585. metatcb.emit_tai(Tai_const.Create_sym(superMetaSym),voidpointertype);
  1586. { pointer to cache }
  1587. if not assigned(ObjCEmptyCacheVar) then
  1588. ObjCEmptyCacheVar:=current_asmdata.RefAsmSymbol(target_info.Cprefix+'_objc_empty_cache');
  1589. metatcb.emit_tai(Tai_const.Create_sym(ObjCEmptyCacheVar),voidpointertype);
  1590. { pointer to vtable }
  1591. if not assigned(ObjCEmptyVtableVar) and
  1592. not(target_info.system in [system_arm_darwin,system_aarch64_darwin,system_i386_iphonesim,system_x86_64_iphonesim]) then
  1593. ObjCEmptyVtableVar:=current_asmdata.RefAsmSymbol(target_info.Cprefix+'_objc_empty_vtable');
  1594. ConcatSymOrNil(metatcb,ObjCEmptyVtableVar,voidpointertype);
  1595. { the read-only part }
  1596. metatcb.emit_tai(Tai_const.Create_sym(metarosym),voidpointertype);
  1597. metatcb.end_anonymous_record;
  1598. list.concatList(
  1599. metatcb.get_final_asmlist(
  1600. metasym,metadef,
  1601. sec_objc_data,'_OBJC_CLASS',sizeof(pint)
  1602. )
  1603. );
  1604. metatcb.free;
  1605. { 2) regular class declaration }
  1606. { the isa }
  1607. isatcb.emit_tai(Tai_const.Create_sym(metasym),cpointerdef.getreusable(metadef));
  1608. { the superclass }
  1609. ConcatSymOrNil(isatcb,supersym,voidpointertype);
  1610. { pointer to cache }
  1611. isatcb.emit_tai(Tai_const.Create_sym(ObjCEmptyCacheVar),voidpointertype);
  1612. { pointer to vtable }
  1613. ConcatSymOrNil(isatcb,ObjCEmptyVtableVar,voidpointertype);
  1614. { the read-only part }
  1615. isatcb.emit_tai(Tai_const.Create_sym(rosym),voidpointertype);
  1616. isatcb.end_anonymous_record;
  1617. list.concatList(
  1618. isatcb.get_final_asmlist(
  1619. clssym,classdef,
  1620. sec_objc_data,'_OBJC_CLASS',sizeof(pint)
  1621. )
  1622. );
  1623. isatcb.free;
  1624. classlabel:=clssym;
  1625. classlabeldef:=classdef;;
  1626. end;
  1627. procedure tobjcrttiwriter_nonfragile.addclasslist(list: tasmlist; section: tasmsectiontype; const symname: string; classes: tfpobjectlist);
  1628. var
  1629. i: longint;
  1630. sym: TAsmSymbol;
  1631. tcb: ttai_typedconstbuilder;
  1632. arrdef: tdef;
  1633. begin
  1634. if classes.count=0 then
  1635. exit;
  1636. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  1637. arrdef:=carraydef.getreusable(voidpointertype,classes.count);
  1638. sym:=current_asmdata.DefineAsmSymbol(symname,AB_LOCAL,AT_DATA,arrdef);
  1639. tcb.maybe_begin_aggregate(arrdef);
  1640. for i:=0 to classes.count-1 do
  1641. tcb.emit_tai(
  1642. tai_const.Create_sym(current_asmdata.RefAsmSymbol(tobjectdef(classes[i]).rtti_mangledname(objcclassrtti))),
  1643. voidpointertype
  1644. );
  1645. tcb.maybe_end_aggregate(arrdef);
  1646. list.concatList(
  1647. tcb.get_final_asmlist(
  1648. sym,arrdef,
  1649. section,symname,sizeof(pint)
  1650. )
  1651. );
  1652. end;
  1653. procedure tobjcrttiwriter_nonfragile.gen_objc_info_sections(list: tasmlist);
  1654. function collectnonlazyclasses(classes: tfpobjectlist): tfpobjectlist;
  1655. var
  1656. symentry : tsym;
  1657. procdef : tprocdef;
  1658. i,j : longint;
  1659. begin
  1660. { non-lazy classes are all classes that define a class method with the
  1661. selector called "load" (simply inheriting this class method is not enough,
  1662. they have to implement it themselves)
  1663. -- TODO: this currently only works if the Pascal identifier is also 'load'! }
  1664. result:=tfpobjectlist.create(false);
  1665. for i:=0 to classes.count-1 do
  1666. begin
  1667. symentry:=tsym(tobjectsymtable(tobjectdef(classes[i]).symtable).find('LOAD'));
  1668. if assigned(symentry) and
  1669. (symentry.typ=procsym) then
  1670. begin
  1671. for j:=0 to tprocsym(symentry).ProcdefList.count do
  1672. begin
  1673. procdef:=tprocdef(tprocsym(symentry).ProcdefList[0]);
  1674. if ((po_classmethod in procdef.procoptions) and
  1675. (procdef.messageinf.str^='load')) then
  1676. begin
  1677. result.add(classes[i]);
  1678. break;
  1679. end;
  1680. end;
  1681. end;
  1682. end;
  1683. end;
  1684. var
  1685. nonlazyclasses,
  1686. nonlazycategories : tfpobjectlist;
  1687. begin
  1688. if (classdefs.count=0) and
  1689. (catdefs.count=0) then
  1690. exit;
  1691. nonlazyclasses:=collectnonlazyclasses(classdefs);
  1692. nonlazycategories:=collectnonlazyclasses(catdefs);
  1693. { this list has to include all classes, also the non-lazy ones }
  1694. addclasslist(list,sec_objc_classlist,target_asm.labelprefix+'_OBJC_LABEL_CLASS_$',classdefs);
  1695. addclasslist(list,sec_objc_nlclasslist,target_asm.labelprefix+'_OBJC_LABEL_NONLAZY_CLASS_$',nonlazyclasses);
  1696. { category and non-lazy category lists }
  1697. addclasslist(list,sec_objc_catlist,target_asm.labelprefix+'_OBJC_LABEL_CATEGORY_$',catdefs);
  1698. addclasslist(list,sec_objc_nlcatlist,target_asm.labelprefix+'_OBJC_LABEL_NONLAZY_CATEGORY_$',nonlazycategories);
  1699. nonlazyclasses.free;
  1700. nonlazycategories.free;
  1701. { the non-fragile abi doesn't have any module info, nor lazy references
  1702. to used classes or to parent classes }
  1703. end;
  1704. constructor tobjcrttiwriter_nonfragile.create;
  1705. begin
  1706. inherited create(oa_nonfragile);
  1707. end;
  1708. {******************************************************************
  1709. RTTI generation -- Main function
  1710. *******************************************************************}
  1711. procedure MaybeGenerateObjectiveCImageInfo(globalst, localst: tsymtable);
  1712. var
  1713. objcrttiwriter: tobjcrttiwriter;
  1714. tcb: ttai_typedconstbuilder;
  1715. begin
  1716. if (m_objectivec1 in current_settings.modeswitches) then
  1717. begin
  1718. { first 4 bytes contain version information about this section (currently version 0),
  1719. next 4 bytes contain flags (currently only regarding whether the code in the object
  1720. file supports or requires garbage collection)
  1721. }
  1722. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  1723. tcb.emit_ord_const(0,u64inttype);
  1724. current_asmdata.asmlists[al_objc_data].concatList(
  1725. tcb.get_final_asmlist(
  1726. current_asmdata.DefineAsmSymbol(target_asm.labelprefix+'_OBJC_IMAGE_INFO',AB_LOCAL,AT_DATA,u64inttype),
  1727. u64inttype,sec_objc_image_info,'_OBJC_IMAGE_INFO',sizeof(pint)
  1728. )
  1729. );
  1730. tcb.free;
  1731. { generate rtti for all obj-c classes, protocols and categories
  1732. defined in this module. }
  1733. if not(target_info.system in systems_objc_nfabi) then
  1734. objcrttiwriter:=tobjcrttiwriter_fragile.create
  1735. else
  1736. objcrttiwriter:=tobjcrttiwriter_nonfragile.create;
  1737. objcrttiwriter.gen_objc_rtti_sections(current_asmdata.asmlists[al_objc_data],globalst);
  1738. objcrttiwriter.gen_objc_rtti_sections(current_asmdata.asmlists[al_objc_data],localst);
  1739. objcrttiwriter.gen_objc_info_sections(current_asmdata.asmlists[al_objc_data]);
  1740. objcrttiwriter.free;
  1741. end;
  1742. end;
  1743. end.