objcgutl.pas 69 KB

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