Metadata.cs 144 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397
  1. using System;
  2. using System.IO;
  3. using System.Collections;
  4. using System.Text;
  5. namespace PEAPI {
  6. #region Enums
  7. /// <summary>
  8. /// flags for the assembly (.corflags)
  9. /// </summary>
  10. public enum CorFlags {CF_IL_ONLY = 1, CF_32_BITREQUIRED = 2,
  11. CF_STRONGNAMESIGNED = 8, CF_TRACKDEBUGDATA = 0x10000 }
  12. /// <summary>
  13. /// subsystem for the assembly (.subsystem)
  14. /// </summary>
  15. public enum SubSystem { Native = 1, Windows_GUI = 2,
  16. Windows_CUI = 3, OS2_CUI = 5, POSIX_CUI = 7, Native_Windows = 8,
  17. Windows_CE_GUI = 9}
  18. /// <summary>
  19. /// Hash algorithms for the assembly
  20. /// </summary>
  21. public enum HashAlgorithm { None, SHA1 }
  22. /// <summary>
  23. /// Attributes for this assembly
  24. /// </summary>
  25. public enum AssemAttr { EnableJITCompileTracking = 0x8000,
  26. DisableJITCompileOptimizer = 0x4000}
  27. /// <summary>
  28. /// Method call conventions
  29. /// </summary>
  30. public enum CallConv { Default, Cdecl, Stdcall, Thiscall,
  31. Fastcall, Vararg, Instance = 0x20, Generic = 0x10, InstanceExplicit = 0x60 }
  32. /// <summary>
  33. /// Type custom modifier
  34. /// </summary>
  35. public enum CustomModifier { modreq = 0x1F, modopt };
  36. /// <summary>
  37. /// Attibutes for a class
  38. /// </summary>
  39. public enum TypeAttr {Private, Public, NestedPublic, NestedPrivate,
  40. NestedFamily, NestedAssembly, NestedFamAndAssem, NestedFamOrAssem,
  41. SequentialLayout, ExplicitLayout = 0x10, Interface = 0x20,
  42. Abstract = 0x80, PublicAbstract = 0x81, Sealed = 0x100,
  43. PublicSealed = 0x101, SpecialName = 0x400, RTSpecialName = 0x800,
  44. Import = 0x1000, Serializable = 0x2000, UnicodeClass = 0x10000,
  45. AutoClass = 0x20000, HasSecurity = 0x40000, BeforeFieldInit = 0x100000 }
  46. /// <summary>
  47. /// Attributes for a field
  48. /// </summary>
  49. public enum FieldAttr {Default, Private, FamAndAssem, Assembly,
  50. Family, FamOrAssem, Public, Static = 0x10, PublicStatic = 0x16,
  51. Initonly = 0x20, Literal = 0x40, Notserialized = 0x80,
  52. SpecialName = 0x200, RTSpecialName = 0x400, HasFieldMarshal = 0x1000 }
  53. /// <summary>
  54. /// Attributes for a method
  55. /// </summary>
  56. public enum MethAttr { Default, Private, FamAndAssem, Assembly,
  57. Family, FamOrAssem, Public, Static = 0x0010, PublicStatic = 0x16,
  58. Final = 0x0020, PublicStaticFinal = 0x36, Virtual = 0x0040,
  59. PrivateVirtual, PublicVirtual = 0x0046, HideBySig = 0x0080,
  60. NewSlot = 0x0100, Abstract = 0x0400, SpecialName = 0x0800,
  61. RTSpecialName = 0x1000, SpecialRTSpecialName = 0x1800,
  62. HasSecurity = 0x4000, RequireSecObject = 0x8000}
  63. /// <summary>
  64. /// Attributes for .pinvokeimpl method declarations
  65. /// </summary>
  66. public enum PInvokeAttr { nomangle = 1, ansi = 2, unicode = 4, autochar = 6,
  67. lasterr = 0x0040, winapi = 0x0100, cdecl = 0x0200,
  68. stdcall = 0x0300, thiscall = 0x0400, fastcall = 0x0500 }
  69. /// <summary>
  70. /// Implementation attributes for a method
  71. /// </summary>
  72. public enum ImplAttr { IL, Native, Runtime = 0x03, Unmanaged = 0x04,
  73. ForwardRef = 0x10, PreserveSig = 0x0080, InternalCall = 0x1000,
  74. Synchronised = 0x0020, Synchronized = 0x0020, NoInLining = 0x0008, Optil = 0x0002}
  75. /// <summary>
  76. /// Modes for a parameter
  77. /// </summary>
  78. public enum ParamAttr { Default, In, Out, Opt = 16, HasDefault = 0x1000, HasFieldMarshal = 0x2000 }
  79. /// <summary>
  80. /// CIL instructions
  81. /// </summary>
  82. public enum Op { nop, breakOp, ldarg_0, ldarg_1, ldarg_2, ldarg_3,
  83. ldloc_0, ldloc_1, ldloc_2, ldloc_3, stloc_0, stloc_1, stloc_2, stloc_3,
  84. ldnull = 0x14, ldc_i4_m1, ldc_i4_0, ldc_i4_1, ldc_i4_2, ldc_i4_3,
  85. ldc_i4_4, ldc_i4_5, ldc_i4_6, ldc_i4_7, ldc_i4_8, dup = 0x25, pop,
  86. ret = 0x2A, ldind_i1 = 0x46, ldind_u1, ldind_i2, ldind_u2, ldind_i4,
  87. ldind_u4, ldind_i8, ldind_i, ldind_r4, ldind_r8, ldind_ref, stind_ref,
  88. stind_i1, stind_i2, stind_i4, stind_i8, stind_r4, stind_r8, add, sub, mul,
  89. div, div_un, rem, rem_un, and, or, xor, shl, shr, shr_un, neg, not,
  90. conv_i1, conv_i2, conv_i4, conv_i8, conv_r4, conv_r8, conv_u4, conv_u8,
  91. conv_r_un = 0x76, throwOp = 0x7A, conv_ovf_i1_un = 0x82, conv_ovf_i2_un,
  92. conv_ovf_i4_un, conv_ovf_i8_un, conf_ovf_u1_un, conv_ovf_u2_un,
  93. conv_ovf_u4_un, conv_ovf_u8_un, conv_ovf_i_un, conv_ovf_u_un,
  94. ldlen = 0x8E, ldelem_i1 = 0x90, ldelem_u1, ldelem_i2, ldelem_u2,
  95. ldelem_i4, ldelem_u4, ldelem_i8, ldelem_i, ldelem_r4, ldelem_r8,
  96. ldelem_ref, stelem_i, stelem_i1, stelem_i2, stelem_i4, stelem_i8, stelem_r4 = 0xA0, stelem_r8,
  97. stelem_ref, conv_ovf_i1 = 0xb3, conv_ovf_u1, conv_ovf_i2, conv_ovf_u2,
  98. conv_ovf_i4, conv_ovf_u4, conv_ovf_i8, conv_ovf_u8, ckfinite = 0xC3,
  99. conv_u2 = 0xD1, conv_u1, conv_i, conv_ovf_i, conv_ovf_u, add_ovf,
  100. add_ovf_un, mul_ovf, mul_ovf_un, sub_ovf, sub_ovf_un, endfinally,
  101. stind_i = 0xDF, conv_u, arglist = 0xFE00, ceq, cgt, cgt_un, clt, clt_un,
  102. localloc = 0xFE0F, endfilter = 0xFE11, volatile_ = 0xFE13, tail_,
  103. cpblk = 0xFE17, initblk, rethrow = 0xFE1A, refanytype = 0xFE1D}
  104. /// <summary>
  105. /// CIL instructions requiring an integer parameter
  106. /// </summary>
  107. public enum IntOp {ldarg_s = 0x0E, ldarga_s, starg_s, ldloc_s, ldloca_s,
  108. stloc_s, ldc_i4_s = 0x1F, ldc_i4, ldarg = 0xFE09,
  109. ldarga, starg, ldloc, ldloca, stloc, unaligned = 0xFE12 }
  110. /// <summary>
  111. /// CIL instructions requiring a field parameter
  112. /// </summary>
  113. public enum FieldOp {ldfld = 0x7B, ldflda, stfld, ldsfld, ldsflda,
  114. stsfld, ldtoken = 0xD0 }
  115. /// <summary>
  116. /// CIL instructions requiring a method parameter
  117. /// </summary>
  118. public enum MethodOp {jmp = 0x27, call, callvirt = 0x6F, newobj = 0x73,
  119. ldtoken = 0xD0, ldftn = 0xFE06, ldvirtfn }
  120. /// <summary>
  121. /// CIL instructions requiring a type parameter
  122. /// </summary>
  123. public enum TypeOp {cpobj = 0x70, ldobj, castclass = 0x74, isinst,
  124. unbox = 0x79, stobj = 0x81, box = 0x8C, newarr,
  125. ldelema = 0x8F, refanyval = 0xC2, mkrefany = 0xC6,
  126. ldtoken = 0xD0, initobj = 0xFE15, sizeOf = 0xFE1C,
  127. ldelem = 0xA3, stelem = 0xA4, unbox_any }
  128. /// <summary>
  129. /// CIL branch instructions
  130. /// </summary>
  131. public enum BranchOp {
  132. // short branches
  133. br_s = 0x2B, brfalse_s, brtrue_s, beq_s, bge_s, bgt_s,
  134. ble_s, blt_s, bne_un_s, bge_un_s, bgt_un_s, ble_un_s, blt_un_s,
  135. // long branches
  136. br = 0x38, brfalse, brtrue, beq, bge, bgt, ble, blt,
  137. bne_un, bge_un, bgt_un, ble_un, blt_un,
  138. leave = 0xDD, leave_s }
  139. /// <summary>
  140. /// Index for all the tables in the meta data
  141. /// </summary>
  142. public enum MDTable { Module, TypeRef, TypeDef, Field = 0x04, Method = 0x06,
  143. Param = 0x08, InterfaceImpl, MemberRef, Constant, CustomAttribute,
  144. FieldMarshal, DeclSecurity, ClassLayout, FieldLayout, StandAloneSig,
  145. EventMap, Event = 0x14, PropertyMap, Property = 0x17, MethodSemantics,
  146. MethodImpl, ModuleRef, TypeSpec, ImplMap, FieldRVA, Assembly = 0x20,
  147. AssemblyProcessor, AssemblyOS, AssemblyRef, AssemblyRefProcessor,
  148. AssemblyRefOS, File, ExportedType, ManifestResource, NestedClass,
  149. GenericParam, MethodSpec, GenericParamConstraint }
  150. public enum SafeArrayType { int16 = 2, int32, float32, float64,
  151. currency, date, bstr, dispatch, error, boolean, variant, unknown,
  152. Decimal, int8 = 16, uint8, uint16, uint32, Int = 22, UInt }
  153. internal enum CIx { TypeDefOrRef, HasConst, HasCustomAttr, HasFieldMarshal,
  154. HasDeclSecurity, MemberRefParent, HasSemantics, MethodDefOrRef,
  155. MemberForwarded, Implementation, CustomAttributeType, ResolutionScope,
  156. TypeOrMethodDef, MaxCIx }
  157. internal enum MapType { eventMap, propertyMap, nestedClass }
  158. public enum ValueClass { ValueType, Enum }
  159. /* Taken from Mono.Cecil */
  160. public enum SecurityAction : short {
  161. Request = 1,
  162. Demand = 2,
  163. Assert = 3,
  164. Deny = 4,
  165. PermitOnly = 5,
  166. LinkDemand = 6,
  167. InheritDemand = 7,
  168. RequestMinimum = 8,
  169. RequestOptional = 9,
  170. RequestRefuse = 10,
  171. PreJitGrant = 11,
  172. PreJitDeny = 12,
  173. NonCasDemand = 13,
  174. NonCasLinkDemand = 14,
  175. NonCasInheritance = 15,
  176. LinkDemandChoice = 16,
  177. InheritDemandChoice = 17,
  178. DemandChoice = 18
  179. }
  180. #endregion
  181. /**************************************************************************/
  182. /// <summary>
  183. /// Base class for all Meta Data table elements
  184. /// </summary>
  185. public abstract class MetaDataElement: IComparable {
  186. protected ArrayList customAttributes;
  187. private uint row = 0;
  188. protected bool done = false;
  189. protected MDTable tabIx;
  190. protected bool sortTable = false;
  191. internal MetaDataElement() { }
  192. public uint Row {
  193. get {
  194. return row;
  195. }
  196. set {
  197. if (row == 0) row = value;
  198. }
  199. }
  200. internal virtual uint GetCodedIx(CIx code) { return 0; }
  201. /// <summary>
  202. /// Add a custom attribute to this item
  203. /// </summary>
  204. /// <param name="ctorMeth">the constructor method for this attribute</param>
  205. /// <param name="val">the byte value of the parameters</param>
  206. public void AddCustomAttribute(Method ctorMeth, byte[] val)
  207. {
  208. if (customAttributes == null) {
  209. customAttributes = new ArrayList();
  210. }
  211. customAttributes.Add(new CustomAttribute(this,ctorMeth,val));
  212. }
  213. /// <summary>
  214. /// Add a custom attribute to this item
  215. /// </summary>
  216. /// <param name="ctorMeth">the constructor method for this attribute</param>
  217. /// <param name="val">the constant values of the parameters</param>
  218. public void AddCustomAttribute(Method ctorMeth, Constant[] cVals)
  219. {
  220. if (customAttributes == null) {
  221. customAttributes = new ArrayList();
  222. }
  223. // customAttributes.Add(new CustomAttribute(this,ctorMeth,cVals));
  224. }
  225. internal uint Token()
  226. {
  227. return (((uint)tabIx << 24) | row);
  228. }
  229. internal virtual void BuildTables(MetaData md)
  230. {
  231. done = true;
  232. }
  233. internal virtual uint Size(MetaData md)
  234. {
  235. return 0;
  236. }
  237. internal virtual void Write(FileImage output) { }
  238. internal virtual uint SortKey()
  239. {
  240. throw new PEFileException("Trying to sort table of " + this);
  241. //return 0;
  242. }
  243. internal virtual uint SortKey2()
  244. {
  245. return 0;
  246. }
  247. public int CompareTo(object obj)
  248. {
  249. uint otherKey = ((MetaDataElement)obj).SortKey();
  250. uint thisKey = SortKey();
  251. if (thisKey == otherKey) {
  252. otherKey = ((MetaDataElement)obj).SortKey2();
  253. thisKey = SortKey2();
  254. if (thisKey == otherKey)
  255. return 0;
  256. if (thisKey < otherKey)
  257. return -1;
  258. return 1;
  259. }
  260. if (thisKey < otherKey) return -1;
  261. return 1;
  262. }
  263. }
  264. /**************************************************************************/
  265. /// <summary>
  266. /// Layout information for a class (.class [sequential | explicit])
  267. /// </summary>
  268. internal class ClassLayout : MetaDataElement {
  269. ClassDef parent;
  270. ushort packSize = 0;
  271. uint classSize = 0;
  272. internal ClassLayout(int pack, int cSize, ClassDef par)
  273. {
  274. packSize = (ushort)pack;
  275. classSize = (uint)cSize;
  276. parent = par;
  277. tabIx = MDTable.ClassLayout;
  278. }
  279. internal sealed override uint Size(MetaData md)
  280. {
  281. return 6 + md.TableIndexSize(MDTable.TypeDef);
  282. }
  283. internal sealed override void Write(FileImage output)
  284. {
  285. output.Write(packSize);
  286. output.Write(classSize);
  287. output.WriteIndex(MDTable.TypeDef,parent.Row);
  288. }
  289. }
  290. /**************************************************************************/
  291. /// <summary>
  292. /// Summary description for ConstantElem.
  293. /// </summary>
  294. internal class ConstantElem : MetaDataElement {
  295. MetaDataElement parent;
  296. Constant cValue;
  297. uint valIx = 0;
  298. internal ConstantElem(MetaDataElement parent, Constant val)
  299. {
  300. this.parent = parent;
  301. cValue = val;
  302. tabIx = MDTable.Constant;
  303. sortTable = true;
  304. }
  305. internal override uint SortKey()
  306. {
  307. return (parent.Row << MetaData.CIxShiftMap[(uint)CIx.HasConst])
  308. | parent.GetCodedIx(CIx.HasConst);
  309. }
  310. internal sealed override void BuildTables(MetaData md)
  311. {
  312. if (done) return;
  313. valIx = cValue.GetBlobIndex(md);
  314. done = true;
  315. }
  316. internal void AddToBlob(BinaryWriter bw)
  317. {
  318. cValue.Write(bw);
  319. }
  320. internal sealed override uint Size(MetaData md)
  321. {
  322. return 2 + md.CodedIndexSize(CIx.HasConst) + md.BlobIndexSize();
  323. }
  324. internal sealed override void Write(FileImage output)
  325. {
  326. output.Write(cValue.GetTypeIndex());
  327. output.Write((byte)0);
  328. output.WriteCodedIndex(CIx.HasConst,parent);
  329. output.BlobIndex(valIx);
  330. }
  331. }
  332. /**************************************************************************/
  333. /// <summary>
  334. /// Descriptor for a Custom Attribute (.custom)
  335. /// </summary>
  336. public class CustomAttribute : MetaDataElement {
  337. private static readonly ushort prolog = 0x0001;
  338. MetaDataElement parent;
  339. Method type;
  340. uint valIx;
  341. Constant cVal;
  342. byte[] byteVal;
  343. ushort numNamed = 0;
  344. ArrayList names, vals;
  345. internal CustomAttribute(MetaDataElement paren, Method constrType,
  346. Constant val) {
  347. parent = paren;
  348. type = constrType;
  349. cVal = val;
  350. tabIx = MDTable.CustomAttribute;
  351. }
  352. internal CustomAttribute(MetaDataElement paren, Method constrType,
  353. byte[] val) {
  354. parent = paren;
  355. type = constrType;
  356. tabIx = MDTable.CustomAttribute;
  357. byteVal = val;
  358. }
  359. internal override uint SortKey()
  360. {
  361. return (parent.Row << MetaData.CIxShiftMap[(uint)CIx.HasCustomAttr])
  362. | parent.GetCodedIx(CIx.HasCustomAttr);
  363. }
  364. public void AddFieldOrProp(string name, Constant val)
  365. {
  366. if (numNamed == 0) {
  367. names = new ArrayList();
  368. vals = new ArrayList();
  369. }
  370. names.Add(name);
  371. vals.Add(val);
  372. }
  373. internal sealed override void BuildTables(MetaData md)
  374. {
  375. BinaryWriter bw = new BinaryWriter(new MemoryStream());
  376. bw.Write(byteVal);
  377. md.AddToTable(MDTable.CustomAttribute, this);
  378. MemoryStream str = (MemoryStream)bw.BaseStream;
  379. valIx = md.AddToBlobHeap(str.ToArray());
  380. }
  381. internal sealed override uint Size(MetaData md)
  382. {
  383. return md.CodedIndexSize(CIx.HasCustomAttr) + md.CodedIndexSize(CIx.CustomAttributeType) + md.BlobIndexSize();
  384. }
  385. internal sealed override void Write(FileImage output)
  386. {
  387. output.WriteCodedIndex(CIx.HasCustomAttr,parent);
  388. output.WriteCodedIndex(CIx.CustomAttributeType,type);
  389. output.BlobIndex(valIx);
  390. }
  391. }
  392. /**************************************************************************/
  393. /// <summary>
  394. /// Descriptor for security permissions for a class or a method
  395. /// </summary>
  396. public class DeclSecurity : MetaDataElement {
  397. ushort action;
  398. MetaDataElement parent;
  399. uint permissionIx;
  400. byte [] byteVal;
  401. internal DeclSecurity(MetaDataElement paren, ushort act, byte [] val)
  402. {
  403. parent = paren;
  404. action = act;
  405. tabIx = MDTable.DeclSecurity;
  406. byteVal = val;
  407. }
  408. internal override uint SortKey()
  409. {
  410. return (parent.Row << MetaData.CIxShiftMap[(uint)CIx.HasDeclSecurity])
  411. | parent.GetCodedIx(CIx.HasDeclSecurity);
  412. }
  413. internal sealed override uint Size(MetaData md)
  414. {
  415. return 2 + md.CodedIndexSize(CIx.HasDeclSecurity) + md.BlobIndexSize();
  416. }
  417. internal sealed override void BuildTables(MetaData md)
  418. {
  419. if (done) return;
  420. BinaryWriter bw = new BinaryWriter (new MemoryStream ());
  421. bw.Write (byteVal);
  422. md.AddToTable (MDTable.DeclSecurity, this);
  423. MemoryStream str = (MemoryStream)bw.BaseStream;
  424. permissionIx = md.AddToBlobHeap(str.ToArray());
  425. done = true;
  426. }
  427. internal sealed override void Write(FileImage output)
  428. {
  429. output.Write(action);
  430. output.WriteCodedIndex(CIx.HasDeclSecurity,parent);
  431. output.BlobIndex(permissionIx);
  432. }
  433. }
  434. /**************************************************************************/
  435. /// <summary>
  436. /// Descriptor for layout information for a field
  437. /// </summary>
  438. public class FieldLayout : MetaDataElement {
  439. Field field;
  440. uint offset;
  441. internal FieldLayout(Field field, uint offset)
  442. {
  443. this.field = field;
  444. this.offset = offset;
  445. tabIx = MDTable.FieldLayout;
  446. }
  447. internal sealed override uint Size(MetaData md)
  448. {
  449. return 4 + md.TableIndexSize(MDTable.Field);
  450. }
  451. internal sealed override void Write(FileImage output)
  452. {
  453. output.Write(offset);
  454. output.WriteIndex(MDTable.Field,field.Row);
  455. }
  456. }
  457. /*****************************************************************************/
  458. /// <summary>
  459. /// Marshalling information for a field or param
  460. /// </summary>
  461. public class FieldMarshal : MetaDataElement {
  462. MetaDataElement field;
  463. NativeType nt;
  464. uint ntIx;
  465. internal FieldMarshal(MetaDataElement field, NativeType nType)
  466. {
  467. this.field = field;
  468. this.nt = nType;
  469. tabIx = MDTable.FieldMarshal;
  470. }
  471. internal override uint SortKey()
  472. {
  473. return (field.Row << MetaData.CIxShiftMap[(uint)CIx.HasFieldMarshal])
  474. | field.GetCodedIx(CIx.HasFieldMarshal);
  475. }
  476. internal sealed override void BuildTables(MetaData md)
  477. {
  478. if (done) return;
  479. ntIx = md.AddToBlobHeap(nt.ToBlob());
  480. done = true;
  481. }
  482. internal sealed override uint Size(MetaData md)
  483. {
  484. return md.CodedIndexSize(CIx.HasFieldMarshal) + md.BlobIndexSize();
  485. }
  486. internal sealed override void Write(FileImage output)
  487. {
  488. output.WriteCodedIndex(CIx.HasFieldMarshal,field);
  489. output.BlobIndex(ntIx);
  490. }
  491. }
  492. /**************************************************************************/
  493. /// <summary>
  494. /// Descriptor for the address of a field's value in the PE file
  495. /// </summary>
  496. public class FieldRVA : MetaDataElement {
  497. Field field;
  498. DataConstant data;
  499. internal FieldRVA(Field field, DataConstant data)
  500. {
  501. this.field = field;
  502. this.data = data;
  503. tabIx = MDTable.FieldRVA;
  504. }
  505. internal sealed override void BuildTables(MetaData md)
  506. {
  507. if (done) return;
  508. md.AddData(data);
  509. done = true;
  510. }
  511. internal sealed override uint Size(MetaData md)
  512. {
  513. return 4 + md.TableIndexSize(MDTable.Field);
  514. }
  515. internal sealed override void Write(FileImage output)
  516. {
  517. output.WriteDataRVA(data.DataOffset);
  518. output.WriteIndex(MDTable.Field,field.Row);
  519. }
  520. }
  521. /**************************************************************************/
  522. /// <summary>
  523. /// Descriptor for a file referenced in THIS assembly/module (.file)
  524. /// </summary>
  525. public class FileRef : MetaDataElement {
  526. private static readonly uint NoMetaData = 0x1;
  527. uint nameIx = 0, hashIx = 0;
  528. uint flags = 0;
  529. protected string name;
  530. internal FileRef(string name, byte[] hashBytes, bool metaData,
  531. bool entryPoint, MetaData md) {
  532. if (!metaData) flags = NoMetaData;
  533. if (entryPoint) md.SetEntryPoint(this);
  534. this.name = name;
  535. nameIx = md.AddToStringsHeap(name);
  536. hashIx = md.AddToBlobHeap(hashBytes);
  537. tabIx = MDTable.File;
  538. }
  539. internal FileRef(uint nameIx, byte[] hashBytes, bool metaData,
  540. bool entryPoint, MetaData md) {
  541. if (!metaData) flags = NoMetaData;
  542. if (entryPoint) md.SetEntryPoint(this);
  543. this.nameIx = nameIx;
  544. hashIx = md.AddToBlobHeap(hashBytes);
  545. tabIx = MDTable.File;
  546. }
  547. internal sealed override uint Size(MetaData md)
  548. {
  549. return 4 + md.StringsIndexSize() + md.BlobIndexSize();
  550. }
  551. internal sealed override void BuildTables(MetaData md)
  552. {
  553. md.AddToTable(MDTable.File,this);
  554. }
  555. internal sealed override void Write(FileImage output)
  556. {
  557. output.Write(flags);
  558. output.StringsIndex(nameIx);
  559. output.BlobIndex(hashIx);
  560. }
  561. internal sealed override uint GetCodedIx(CIx code)
  562. {
  563. switch (code) {
  564. case (CIx.HasCustomAttr) : return 16;
  565. case (CIx.Implementation) : return 0;
  566. }
  567. return 0;
  568. }
  569. }
  570. /**************************************************************************/
  571. /// <summary>
  572. /// Descriptor for pinvoke information for a method NOT YET IMPLEMENTED
  573. /// </summary>
  574. public class ImplMap : MetaDataElement {
  575. private static readonly ushort NoMangle = 0x01;
  576. ushort flags;
  577. Method meth;
  578. string importName;
  579. uint iNameIx;
  580. ModuleRef importScope;
  581. internal ImplMap(ushort flag, Method implMeth, string iName, ModuleRef mScope)
  582. {
  583. flags = flag;
  584. meth = implMeth;
  585. importName = iName;
  586. importScope = mScope;
  587. tabIx = MDTable.ImplMap;
  588. if (iName == null) flags |= NoMangle;
  589. //throw(new NotYetImplementedException("PInvoke "));
  590. }
  591. internal override uint SortKey()
  592. {
  593. return (meth.Row << MetaData.CIxShiftMap[(uint)CIx.MemberForwarded])
  594. | meth.GetCodedIx(CIx.MemberForwarded);
  595. }
  596. internal sealed override void BuildTables(MetaData md)
  597. {
  598. if (done) return;
  599. iNameIx = md.AddToStringsHeap(importName);
  600. done = true;
  601. }
  602. internal sealed override uint Size(MetaData md)
  603. {
  604. return 2+ md.CodedIndexSize(CIx.MemberForwarded) +
  605. md.StringsIndexSize() + md.TableIndexSize(MDTable.ModuleRef);
  606. }
  607. internal sealed override void Write(FileImage output)
  608. {
  609. output.Write(flags);
  610. output.WriteCodedIndex(CIx.MemberForwarded,meth);
  611. output.StringsIndex(iNameIx);
  612. output.WriteIndex(MDTable.ModuleRef,importScope.Row);
  613. }
  614. }
  615. /**************************************************************************/
  616. public class GenericParameter : MetaDataElement {
  617. MetaDataElement owner;
  618. MetaData metadata;
  619. string name;
  620. uint nameIx;
  621. short index;
  622. internal GenericParameter (ClassDef owner, MetaData metadata,
  623. short index, string name) : this (owner, metadata, index, name, true)
  624. {
  625. }
  626. internal GenericParameter (MethodDef owner, MetaData metadata,
  627. short index, string name) : this (owner, metadata, index, name, true)
  628. {
  629. }
  630. private GenericParameter (MetaDataElement owner, MetaData metadata,
  631. short index, string name, bool nadda) {
  632. this.owner = owner;
  633. this.metadata = metadata;
  634. this.index = index;
  635. tabIx = MDTable.GenericParam;
  636. this.name = name;
  637. }
  638. internal override uint SortKey()
  639. {
  640. return (owner.Row << MetaData.CIxShiftMap[(uint)CIx.TypeOrMethodDef])
  641. | owner.GetCodedIx(CIx.TypeOrMethodDef);
  642. }
  643. public void AddConstraint (Type constraint)
  644. {
  645. metadata.AddToTable (MDTable.GenericParamConstraint,
  646. new GenericParamConstraint (this, constraint));
  647. }
  648. internal sealed override uint Size(MetaData md)
  649. {
  650. return (uint) (4 +
  651. md.CodedIndexSize(CIx.TypeOrMethodDef) +
  652. 4 +
  653. md.TableIndexSize(MDTable.TypeDef));
  654. }
  655. internal sealed override void BuildTables(MetaData md)
  656. {
  657. if (done) return;
  658. nameIx = md.AddToStringsHeap(name);
  659. done = true;
  660. }
  661. internal sealed override void Write(FileImage output)
  662. {
  663. output.Write ((short) index);
  664. output.Write ((short) 0);
  665. output.WriteCodedIndex(CIx.TypeOrMethodDef, owner);
  666. output.Write ((uint) nameIx);
  667. output.WriteIndex(MDTable.TypeDef,owner.Row);
  668. }
  669. }
  670. internal class GenericParamConstraint : MetaDataElement {
  671. GenericParameter param;
  672. Type type;
  673. public GenericParamConstraint (GenericParameter param, Type type)
  674. {
  675. this.param = param;
  676. this.type = type;
  677. tabIx = MDTable.GenericParamConstraint;
  678. }
  679. internal sealed override uint Size(MetaData md)
  680. {
  681. return (uint) (md.TableIndexSize(MDTable.GenericParam) +
  682. md.CodedIndexSize(CIx.TypeDefOrRef));
  683. }
  684. internal sealed override void Write(FileImage output)
  685. {
  686. output.WriteIndex(MDTable.GenericParam, param.Row);
  687. output.WriteCodedIndex(CIx.TypeDefOrRef, type);
  688. }
  689. }
  690. internal class MethodSpec : MetaDataElement {
  691. Method meth;
  692. GenericMethodSig g_sig;
  693. uint sidx;
  694. internal MethodSpec (Method meth, GenericMethodSig g_sig)
  695. {
  696. this.meth = meth;
  697. this.g_sig = g_sig;
  698. tabIx = MDTable.MethodSpec;
  699. }
  700. internal sealed override void BuildTables (MetaData md)
  701. {
  702. if (done) return;
  703. sidx = g_sig.GetSigIx (md);
  704. done = true;
  705. }
  706. internal sealed override uint Size (MetaData md)
  707. {
  708. return (uint) (md.CodedIndexSize(CIx.MethodDefOrRef) +
  709. md.BlobIndexSize ());
  710. }
  711. internal sealed override void Write (FileImage output)
  712. {
  713. output.WriteCodedIndex (CIx.MethodDefOrRef, meth);
  714. output.BlobIndex (sidx);
  715. }
  716. }
  717. /**************************************************************************/
  718. /// <summary>
  719. /// Descriptor for interface implemented by a class
  720. /// </summary>
  721. public class InterfaceImpl: MetaDataElement {
  722. ClassDef theClass;
  723. Class theInterface;
  724. internal InterfaceImpl(ClassDef theClass, Class theInterface)
  725. {
  726. this.theClass = theClass;
  727. this.theInterface = theInterface;
  728. tabIx = MDTable.InterfaceImpl;
  729. }
  730. internal sealed override uint Size(MetaData md)
  731. {
  732. return md.TableIndexSize(MDTable.TypeDef) +
  733. md.CodedIndexSize(CIx.TypeDefOrRef);
  734. }
  735. internal sealed override void Write(FileImage output)
  736. {
  737. output.WriteIndex(MDTable.TypeDef,theClass.Row);
  738. output.WriteCodedIndex(CIx.TypeDefOrRef,theInterface);
  739. }
  740. internal sealed override uint GetCodedIx(CIx code) { return 5; }
  741. internal override uint SortKey ()
  742. {
  743. return (theClass.Row << MetaData.CIxShiftMap[(uint)CIx.TypeDefOrRef])
  744. | theClass.GetCodedIx (CIx.TypeDefOrRef);
  745. }
  746. }
  747. /**************************************************************************/
  748. /// <summary>
  749. /// Descriptor for resources used in this PE file
  750. /// </summary>
  751. public class ManifestResource : MetaDataElement {
  752. public static readonly uint PublicResource = 0x1;
  753. public static readonly uint PrivateResource = 0x2;
  754. string mrName;
  755. MetaDataElement rRef;
  756. uint fileOffset;
  757. uint nameIx = 0;
  758. uint flags = 0;
  759. byte [] resourceBytes;
  760. public ManifestResource (string name, byte[] resBytes, uint flags)
  761. {
  762. InitResource (name, flags);
  763. this.resourceBytes = resBytes;
  764. }
  765. public ManifestResource(string name, uint flags, FileRef fileRef)
  766. {
  767. InitResource (name, flags);
  768. rRef = fileRef;
  769. }
  770. public ManifestResource(string name, uint flags, FileRef fileRef,
  771. uint fileIx) {
  772. InitResource (name, flags);
  773. rRef = fileRef;
  774. fileOffset = fileIx;
  775. }
  776. public ManifestResource(string name, uint flags, AssemblyRef assemRef)
  777. {
  778. InitResource (name, flags);
  779. rRef = assemRef;
  780. }
  781. internal ManifestResource (ManifestResource mres)
  782. {
  783. mrName = mres.mrName;
  784. flags = mres.flags;
  785. rRef = mres.rRef;
  786. fileOffset = mres.fileOffset;
  787. resourceBytes = mres.resourceBytes;
  788. }
  789. private void InitResource (string name, uint flags)
  790. {
  791. mrName = name;
  792. this.flags = flags;
  793. tabIx = MDTable.ManifestResource;
  794. }
  795. internal sealed override void BuildTables(MetaData md)
  796. {
  797. if (done) return;
  798. md.AddToTable (MDTable.ManifestResource, this);
  799. nameIx = md.AddToStringsHeap(mrName);
  800. if (resourceBytes != null) {
  801. if (rRef != null)
  802. throw new Exception("ERROR: Manifest Resource has byte value and file reference");
  803. fileOffset = md.AddResource(resourceBytes);
  804. } else {
  805. if (rRef == null)
  806. throw new Exception("ERROR: Manifest Resource has no implementation or value");
  807. rRef.BuildTables (md);
  808. }
  809. done = true;
  810. }
  811. internal sealed override uint Size(MetaData md)
  812. {
  813. return 8 + md.StringsIndexSize() +
  814. md.CodedIndexSize(CIx.Implementation);
  815. }
  816. internal sealed override void Write(FileImage output)
  817. {
  818. output.Write(fileOffset);
  819. output.Write(flags);
  820. output.StringsIndex(nameIx);
  821. output.WriteCodedIndex(CIx.Implementation,rRef);
  822. }
  823. internal sealed override uint GetCodedIx(CIx code) { return 18; }
  824. public string Name {
  825. get { return mrName; }
  826. set { mrName = value; }
  827. }
  828. }
  829. /**************************************************************************/
  830. /// <summary>
  831. /// Base class for elements in the PropertyMap, EventMap and
  832. /// NestedClass MetaData tables
  833. /// </summary>
  834. public class MapElem : MetaDataElement {
  835. ClassDef parent;
  836. uint elemIx;
  837. MDTable elemTable;
  838. internal MapElem(ClassDef par, uint elIx, MDTable elemTab)
  839. {
  840. parent = par;
  841. elemIx = elIx;
  842. elemTable = elemTab;
  843. }
  844. internal sealed override uint Size(MetaData md)
  845. {
  846. return md.TableIndexSize(MDTable.TypeDef) + md.TableIndexSize(elemTable);
  847. }
  848. internal sealed override void Write(FileImage output)
  849. {
  850. output.WriteIndex(MDTable.TypeDef,parent.Row);
  851. output.WriteIndex(elemTable,elemIx);
  852. }
  853. }
  854. /**************************************************************************/
  855. /// <summary>
  856. /// Descriptor for an overriding method (.override)
  857. /// </summary>
  858. public class MethodImpl : MetaDataElement {
  859. ClassDef parent;
  860. Method header, body;
  861. internal MethodImpl(ClassDef par, Method decl, Method bod)
  862. {
  863. parent = par;
  864. header = decl;
  865. body = bod;
  866. tabIx = MDTable.MethodImpl;
  867. }
  868. internal sealed override uint Size(MetaData md)
  869. {
  870. return md.TableIndexSize(MDTable.TypeDef) + 2 * md.CodedIndexSize(CIx.MethodDefOrRef);
  871. }
  872. internal sealed override void Write(FileImage output)
  873. {
  874. output.WriteIndex(MDTable.TypeDef,parent.Row);
  875. output.WriteCodedIndex(CIx.MethodDefOrRef,body);
  876. output.WriteCodedIndex(CIx.MethodDefOrRef,header);
  877. }
  878. }
  879. /**************************************************************************/
  880. /// <summary>
  881. /// Descriptor for Property and Event methods
  882. /// </summary>
  883. public class MethodSemantics : MetaDataElement {
  884. Feature.MethodType type;
  885. MethodDef meth;
  886. Feature eventOrProp;
  887. internal MethodSemantics(Feature.MethodType mType, MethodDef method, Feature feature)
  888. {
  889. type = mType;
  890. meth = method;
  891. eventOrProp = feature;
  892. tabIx = MDTable.MethodSemantics;
  893. }
  894. internal override uint SortKey()
  895. {
  896. return (eventOrProp.Row << MetaData.CIxShiftMap [(uint)CIx.HasSemantics])
  897. | eventOrProp.GetCodedIx (CIx.HasSemantics);
  898. }
  899. internal sealed override uint Size(MetaData md)
  900. {
  901. return 2 + md.TableIndexSize(MDTable.Method) + md.CodedIndexSize(CIx.HasSemantics);
  902. }
  903. internal sealed override void Write(FileImage output)
  904. {
  905. output.Write((ushort)type);
  906. output.WriteIndex(MDTable.Method,meth.Row);
  907. output.WriteCodedIndex(CIx.HasSemantics,eventOrProp);
  908. }
  909. }
  910. /**************************************************************************/
  911. /// <summary>
  912. /// Descriptor for a parameter of a method defined in this assembly/module
  913. /// </summary>
  914. public class Param : MetaDataElement {
  915. Type pType;
  916. string pName;
  917. internal ushort seqNo = 0;
  918. ushort parMode;
  919. ConstantElem defaultVal;
  920. uint nameIx = 0;
  921. FieldMarshal marshalInfo;
  922. /// <summary>
  923. /// Create a new parameter for a method
  924. /// </summary>
  925. /// <param name="mode">param mode (in, out, opt)</param>
  926. /// <param name="parName">parameter name</param>
  927. /// <param name="parType">parameter type</param>
  928. public Param(ParamAttr mode, string parName, Type parType)
  929. {
  930. pName = parName;
  931. pType = parType;
  932. parMode = (ushort)mode;
  933. tabIx = MDTable.Param;
  934. }
  935. /// <summary>
  936. /// Add a default value to this parameter
  937. /// </summary>
  938. /// <param name="c">the default value for the parameter</param>
  939. public void AddDefaultValue(Constant cVal)
  940. {
  941. defaultVal = new ConstantElem(this,cVal);
  942. parMode |= (ushort) ParamAttr.HasDefault;
  943. }
  944. /// <summary>
  945. /// Add marshalling information about this parameter
  946. /// </summary>
  947. public void AddMarshallInfo(NativeType marshallType)
  948. {
  949. parMode |= (ushort) ParamAttr.HasFieldMarshal;
  950. marshalInfo = new FieldMarshal(this,marshallType);
  951. }
  952. internal Type GetParType() { return pType; }
  953. internal sealed override void BuildTables(MetaData md)
  954. {
  955. if (done) return;
  956. nameIx = md.AddToStringsHeap(pName);
  957. if (defaultVal != null) {
  958. md.AddToTable(MDTable.Constant,defaultVal);
  959. defaultVal.BuildTables(md);
  960. }
  961. if (marshalInfo != null) {
  962. md.AddToTable(MDTable.FieldMarshal,marshalInfo);
  963. marshalInfo.BuildTables(md);
  964. }
  965. done = true;
  966. }
  967. internal void TypeSig(MemoryStream str)
  968. {
  969. pType.TypeSig(str);
  970. }
  971. internal sealed override uint Size(MetaData md)
  972. {
  973. return 4 + md.StringsIndexSize();
  974. }
  975. internal sealed override void Write(FileImage output)
  976. {
  977. output.Write(parMode);
  978. output.Write(seqNo);
  979. output.StringsIndex(nameIx);
  980. }
  981. internal sealed override uint GetCodedIx(CIx code)
  982. {
  983. switch (code) {
  984. case (CIx.HasCustomAttr) : return 4;
  985. case (CIx.HasConst) : return 1;
  986. case (CIx.HasFieldMarshal) : return 1;
  987. }
  988. return 0;
  989. }
  990. }
  991. /**************************************************************************/
  992. public abstract class Signature : MetaDataElement {
  993. protected uint sigIx;
  994. internal Signature()
  995. {
  996. tabIx = MDTable.StandAloneSig;
  997. }
  998. internal sealed override uint Size(MetaData md)
  999. {
  1000. return md.BlobIndexSize();
  1001. }
  1002. internal sealed override void Write(FileImage output)
  1003. {
  1004. output.BlobIndex(sigIx);
  1005. }
  1006. internal sealed override uint GetCodedIx(CIx code) { return (uint)tabIx; }
  1007. }
  1008. /**************************************************************************/
  1009. public class TypeSpec : MetaDataElement {
  1010. uint sigIx = 0;
  1011. internal TypeSpec(Type aType, MetaData md)
  1012. {
  1013. MemoryStream sig = new MemoryStream();
  1014. aType.TypeSig(sig);
  1015. sigIx = md.AddToBlobHeap(sig.ToArray());
  1016. tabIx = MDTable.TypeSpec;
  1017. }
  1018. internal sealed override uint GetCodedIx(CIx code)
  1019. {
  1020. switch (code) {
  1021. case (CIx.TypeDefOrRef) : return 2;
  1022. case (CIx.HasCustomAttr) : return 13;
  1023. case (CIx.MemberRefParent) : return 4;
  1024. }
  1025. return 0;
  1026. }
  1027. internal override uint Size(MetaData md)
  1028. {
  1029. return md.BlobIndexSize();
  1030. }
  1031. internal sealed override void Write(FileImage output)
  1032. {
  1033. //Console.WriteLine("Writing the blob index for a TypeSpec");
  1034. output.BlobIndex(sigIx);
  1035. }
  1036. }
  1037. /**************************************************************************/
  1038. /// <summary>
  1039. /// Base class for all IL types
  1040. /// </summary>
  1041. public abstract class Type : MetaDataElement {
  1042. protected byte typeIndex;
  1043. protected TypeSpec typeSpec;
  1044. internal Type(byte tyIx) { typeIndex = tyIx; }
  1045. internal byte GetTypeIndex() { return typeIndex; }
  1046. internal void SetTypeIndex (byte b) { typeIndex = b; }
  1047. internal virtual MetaDataElement GetTypeSpec(MetaData md)
  1048. {
  1049. if (typeSpec == null) {
  1050. typeSpec = new TypeSpec(this,md);
  1051. md.AddToTable(MDTable.TypeSpec,typeSpec);
  1052. }
  1053. return typeSpec;
  1054. }
  1055. internal virtual void TypeSig(MemoryStream str)
  1056. {
  1057. throw(new TypeSignatureException(this.GetType().AssemblyQualifiedName +
  1058. " doesn't have a type signature!!"));
  1059. }
  1060. }
  1061. public class ClassRefInst : Type {
  1062. private Type type;
  1063. private bool is_value;
  1064. public ClassRefInst (Type type, bool is_value) : base (PrimitiveType.Class.GetTypeIndex ())
  1065. {
  1066. this.type = type;
  1067. this.is_value = is_value;
  1068. if (is_value)
  1069. typeIndex = PrimitiveType.ValueType.GetTypeIndex ();
  1070. tabIx = MDTable.TypeSpec;
  1071. }
  1072. internal sealed override void TypeSig(MemoryStream str)
  1073. {
  1074. type.TypeSig (str);
  1075. }
  1076. }
  1077. /**************************************************************************/
  1078. /// <summary>
  1079. /// The base descriptor for a class
  1080. /// </summary>
  1081. public abstract class Class : Type {
  1082. protected int row = 0;
  1083. public string name, nameSpace;
  1084. protected uint nameIx, nameSpaceIx;
  1085. protected MetaData _metaData;
  1086. internal Class(string nameSpaceName, string className, MetaData md)
  1087. : base(PrimitiveType.Class.GetTypeIndex ())
  1088. {
  1089. nameSpace = nameSpaceName;
  1090. name = className;
  1091. nameIx = md.AddToStringsHeap(name);
  1092. nameSpaceIx = md.AddToStringsHeap(nameSpace);
  1093. _metaData = md;
  1094. }
  1095. internal Class(uint nsIx, uint nIx) : base(PrimitiveType.Class.GetTypeIndex ())
  1096. {
  1097. nameSpaceIx = nsIx;
  1098. nameIx = nIx;
  1099. }
  1100. internal virtual uint TypeDefOrRefToken() { return 0; }
  1101. internal virtual void MakeValueClass(ValueClass vClass)
  1102. {
  1103. typeIndex = PrimitiveType.ValueType.GetTypeIndex ();
  1104. }
  1105. internal virtual string TypeName()
  1106. {
  1107. return (nameSpace + "." + name);
  1108. }
  1109. internal override MetaDataElement GetTypeSpec(MetaData md)
  1110. {
  1111. return this;
  1112. }
  1113. }
  1114. /**************************************************************************/
  1115. // This Class produces entries in the TypeDef table of the MetaData
  1116. // in the PE meta data.
  1117. // NOTE: Entry 0 in TypeDef table is always the pseudo class <module>
  1118. // which is the parent for functions and variables declared a module level
  1119. /// <summary>
  1120. /// The descriptor for a class defined in the IL (.class) in the current assembly/module
  1121. /// </summary>
  1122. ///
  1123. public class ClassDef : Class {
  1124. private static readonly byte ElementType_Class = 0x12;
  1125. Class superType;
  1126. ArrayList fields = new ArrayList();
  1127. ArrayList methods = new ArrayList();
  1128. ArrayList events;
  1129. ArrayList properties;
  1130. bool typeIndexChecked = true;
  1131. uint fieldIx = 0, methodIx = 0;
  1132. byte[] securityActions;
  1133. uint flags;
  1134. ClassLayout layout;
  1135. ClassDef parentClass;
  1136. MetaData metaData;
  1137. internal ClassDef(TypeAttr attrSet, string nsName, string name,
  1138. MetaData md) : base(nsName, name, md)
  1139. {
  1140. metaData = md;
  1141. if (! ((nsName == "" && name == "<Module>") || (nsName == "System" && name == "Object")) ) {
  1142. superType = metaData.mscorlib.GetSpecialSystemClass(PrimitiveType.Object);
  1143. }
  1144. flags = (uint)attrSet;
  1145. tabIx = MDTable.TypeDef;
  1146. }
  1147. internal void SetSuper(Class sClass)
  1148. {
  1149. superType = sClass;
  1150. if (sClass is ClassRef)
  1151. typeIndex = superType.GetTypeIndex();
  1152. else
  1153. typeIndexChecked = false;
  1154. }
  1155. internal override void MakeValueClass(ValueClass vClass)
  1156. {
  1157. if (vClass == ValueClass.Enum)
  1158. superType = metaData.mscorlib.EnumType();
  1159. else
  1160. superType = metaData.mscorlib.ValueType();
  1161. typeIndex = PrimitiveType.ValueType.GetTypeIndex ();
  1162. }
  1163. public void SpecialNoSuper()
  1164. {
  1165. superType = null;
  1166. }
  1167. /// <summary>
  1168. /// Add an attribute to this class
  1169. /// </summary>
  1170. /// <param name="ta">the attribute to be added</param>
  1171. public void AddAttribute(TypeAttr ta)
  1172. {
  1173. flags |= (uint)ta;
  1174. }
  1175. /// <summary>
  1176. /// Add an interface that is implemented by this class
  1177. /// </summary>
  1178. /// <param name="iFace">the interface that is implemented</param>
  1179. public void AddImplementedInterface(Class iFace)
  1180. {
  1181. metaData.AddToTable(MDTable.InterfaceImpl,new InterfaceImpl(this,iFace));
  1182. }
  1183. /// <summary>
  1184. /// Add a named generic type parameter
  1185. /// </summary>
  1186. public GenericParameter AddGenericParameter (short index, string name)
  1187. {
  1188. GenericParameter gp = new GenericParameter (this, metaData, index, name);
  1189. metaData.AddToTable (MDTable.GenericParam, gp);
  1190. return gp;
  1191. }
  1192. /// <summary>
  1193. /// Add a field to this class
  1194. /// </summary>
  1195. /// <param name="name">field name</param>
  1196. /// <param name="fType">field type</param>
  1197. /// <returns>a descriptor for this new field</returns>
  1198. public FieldDef AddField(string name, Type fType)
  1199. {
  1200. FieldDef field = new FieldDef(name,fType);
  1201. fields.Add(field);
  1202. return field;
  1203. }
  1204. /// <summary>
  1205. /// Add a field to this class
  1206. /// </summary>
  1207. /// <param name="fAtts">attributes for this field</param>
  1208. /// <param name="name">field name</param>
  1209. /// <param name="fType">field type</param>
  1210. /// <returns>a descriptor for this new field</returns>
  1211. public FieldDef AddField(FieldAttr fAtts, string name, Type fType)
  1212. {
  1213. FieldDef field = new FieldDef(fAtts,name,fType);
  1214. fields.Add(field);
  1215. return field;
  1216. }
  1217. public void SetFieldOrder (ArrayList fields)
  1218. {
  1219. this.fields = fields;
  1220. }
  1221. /// <summary>
  1222. /// Add a method to this class
  1223. /// </summary>
  1224. /// <param name="name">method name</param>
  1225. /// <param name="retType">return type</param>
  1226. /// <param name="pars">parameters</param>
  1227. /// <returns>a descriptor for this new method</returns>
  1228. public MethodDef AddMethod(string name, Type retType, Param[] pars)
  1229. {
  1230. // Console.WriteLine("Adding method " + name + " to class " + this.name);
  1231. MethodDef meth = new MethodDef(metaData,name,retType, pars);
  1232. methods.Add(meth);
  1233. return meth;
  1234. }
  1235. /// <summary>
  1236. /// Add a method to this class
  1237. /// </summary>
  1238. /// <param name="mAtts">attributes for this method</param>
  1239. /// <param name="iAtts">implementation attributes for this method</param>
  1240. /// <param name="name">method name</param>
  1241. /// <param name="retType">return type</param>
  1242. /// <param name="pars">parameters</param>
  1243. /// <returns>a descriptor for this new method</returns>
  1244. public MethodDef AddMethod(MethAttr mAtts, ImplAttr iAtts, string name,
  1245. Type retType, Param[] pars) {
  1246. // Console.WriteLine("Adding method " + name + " to class " + this.name);
  1247. MethodDef meth = new MethodDef(metaData,mAtts,iAtts,name,retType,pars);
  1248. methods.Add(meth);
  1249. return meth;
  1250. }
  1251. /// <summary>
  1252. /// Add an event to this class
  1253. /// </summary>
  1254. /// <param name="name">event name</param>
  1255. /// <param name="eType">event type</param>
  1256. /// <returns>a descriptor for this new event</returns>
  1257. public Event AddEvent(string name, Type eType)
  1258. {
  1259. Event e = new Event(name,eType,this);
  1260. if (events == null) events = new ArrayList();
  1261. events.Add(e);
  1262. return e;
  1263. }
  1264. /// <summary>
  1265. /// Add a property to this class
  1266. /// </summary>
  1267. /// <param name="name">property name</param>
  1268. /// <param name="propType">property type</param>
  1269. /// <returns>a descriptor for this new property</returns>
  1270. public Property AddProperty(string name, Type retType, Type[] pars)
  1271. {
  1272. Property p = new Property(name, retType, pars, this);
  1273. if (properties == null) properties = new ArrayList();
  1274. properties.Add(p);
  1275. return p;
  1276. }
  1277. /// <summary>
  1278. /// Add a nested class to this class
  1279. /// </summary>
  1280. /// <param name="attrSet">attributes for this nested class</param>
  1281. /// <param name="nsName">nested name space name</param>
  1282. /// <param name="name">nested class name</param>
  1283. /// <returns>a descriptor for this new nested class</returns>
  1284. public ClassDef AddNestedClass(TypeAttr attrSet, string nsName,
  1285. string name) {
  1286. ClassDef nClass = new ClassDef(attrSet,"",name,metaData);
  1287. metaData.AddToTable(MDTable.TypeDef,nClass);
  1288. metaData.AddToTable(MDTable.NestedClass,new MapElem(nClass,Row,MDTable.TypeDef));
  1289. nClass.parentClass = this;
  1290. return (nClass);
  1291. }
  1292. public static bool IsValueType (Class type)
  1293. {
  1294. return IsValueType (type.nameSpace, type.name);
  1295. }
  1296. public static bool IsEnum (Class type)
  1297. {
  1298. return IsEnum (type.nameSpace, type.name);
  1299. }
  1300. public static bool IsValueType (string nsName, string name)
  1301. {
  1302. return (nsName == "System" && name == "ValueType");
  1303. }
  1304. public static bool IsEnum (string nsName, string name)
  1305. {
  1306. return (nsName == "System" && name == "Enum");
  1307. }
  1308. /// <summary>
  1309. /// Add a nested class to this class
  1310. /// </summary>
  1311. /// <param name="attrSet">attributes for this nested class</param>
  1312. /// <param name="nsName">nested name space name</param>
  1313. /// <param name="name">nested class name</param>
  1314. /// <param name="sType">super type of this nested class</param>
  1315. /// <returns>a descriptor for this new nested class</returns>
  1316. public ClassDef AddNestedClass(TypeAttr attrSet, string nsName,
  1317. string name, Class sType) {
  1318. ClassDef nClass = AddNestedClass (attrSet, nsName, name);
  1319. nClass.SetSuper(sType);
  1320. if (ClassDef.IsValueType (sType))
  1321. nClass.MakeValueClass (ValueClass.ValueType);
  1322. else
  1323. if (ClassDef.IsEnum (sType))
  1324. nClass.MakeValueClass (ValueClass.Enum);
  1325. if (ClassDef.IsValueType (sType) || ClassDef.IsEnum (sType))
  1326. nClass.SetTypeIndex (PrimitiveType.ValueType.GetTypeIndex ());
  1327. nClass.typeIndexChecked = true;
  1328. return (nClass);
  1329. }
  1330. /// <summary>
  1331. /// Add layout information for this class. This class must have the
  1332. /// sequential or explicit attribute.
  1333. /// </summary>
  1334. /// <param name="packSize">packing size (.pack)</param>
  1335. /// <param name="classSize">class size (.size)</param>
  1336. public void AddLayoutInfo (int packSize, int classSize)
  1337. {
  1338. layout = new ClassLayout(packSize,classSize,this);
  1339. }
  1340. /// <summary>
  1341. /// Use a method as the implementation for another method (.override)
  1342. /// </summary>
  1343. /// <param name="decl">the method to be overridden</param>
  1344. /// <param name="body">the implementation to be used</param>
  1345. public void AddMethodOverride(Method decl, Method body)
  1346. {
  1347. metaData.AddToTable(MDTable.MethodImpl,new MethodImpl(this,decl,body));
  1348. }
  1349. /// <summary>
  1350. /// Add security to this class NOT YET IMPLEMENTED
  1351. /// </summary>
  1352. /// <param name="permissionSet"></param>
  1353. public void AddSecurity(byte[] permissionSet)
  1354. {
  1355. throw(new NotYetImplementedException("Class security "));
  1356. //flags |= HasSecurity;
  1357. // securityActions = permissionSet;
  1358. }
  1359. //public void AddLineInfo(int row, int col) { }
  1360. internal void CheckTypeIndex()
  1361. {
  1362. if (typeIndexChecked) return;
  1363. if (!(superType is ClassRef))
  1364. ((ClassDef)superType).CheckTypeIndex();
  1365. typeIndex = superType.GetTypeIndex();
  1366. typeIndexChecked = true;
  1367. }
  1368. internal sealed override void BuildTables(MetaData md)
  1369. {
  1370. if (done) return;
  1371. if ((flags & (uint)TypeAttr.Interface) != 0) { superType = null; }
  1372. // Console.WriteLine("Building tables for " + name);
  1373. if (layout != null) md.AddToTable(MDTable.ClassLayout,layout);
  1374. // Console.WriteLine("adding methods " + methods.Count);
  1375. methodIx = md.TableIndex(MDTable.Method);
  1376. for (int i=0; i < methods.Count; i++) {
  1377. md.AddToTable(MDTable.Method,(MetaDataElement)methods[i]);
  1378. ((MethodDef)methods[i]).BuildTables(md);
  1379. }
  1380. // Console.WriteLine("adding fields");
  1381. fieldIx = md.TableIndex(MDTable.Field);
  1382. for (int i=0; i < fields.Count; i++) {
  1383. md.AddToTable(MDTable.Field,(MetaDataElement)fields[i]);
  1384. ((FieldDef)fields[i]).BuildTables(md);
  1385. }
  1386. // Console.WriteLine("adding events and properties");
  1387. if (events != null) {
  1388. for (int i=0; i < events.Count; i++) {
  1389. md.AddToTable(MDTable.Event,(Event)events[i]);
  1390. ((Event)events[i]).BuildTables(md);
  1391. }
  1392. md.AddToTable(MDTable.EventMap,
  1393. new MapElem(this,((Event)events[0]).Row,MDTable.Event));
  1394. }
  1395. if (properties != null) {
  1396. for (int i=0; i < properties.Count; i++) {
  1397. md.AddToTable(MDTable.Property,(Property)properties[i]);
  1398. ((Property)properties[i]).BuildTables(md);
  1399. }
  1400. md.AddToTable(MDTable.PropertyMap,new MapElem(this,
  1401. ((Property)properties[0]).Row,MDTable.Property));
  1402. }
  1403. // Console.WriteLine("End of building tables");
  1404. done = true;
  1405. }
  1406. internal sealed override uint Size(MetaData md)
  1407. {
  1408. return 4 + 2 * md.StringsIndexSize() +
  1409. md.CodedIndexSize(CIx.TypeDefOrRef) +
  1410. md.TableIndexSize(MDTable.Field) +
  1411. md.TableIndexSize(MDTable.Method);
  1412. }
  1413. internal sealed override void Write(FileImage output)
  1414. {
  1415. output.Write(flags);
  1416. output.StringsIndex(nameIx);
  1417. output.StringsIndex(nameSpaceIx);
  1418. //if (superType != null)
  1419. // Console.WriteLine("getting coded index for superType of " + name + " = " + superType.GetCodedIx(CIx.TypeDefOrRef));
  1420. output.WriteCodedIndex(CIx.TypeDefOrRef,superType);
  1421. output.WriteIndex(MDTable.Field,fieldIx);
  1422. output.WriteIndex(MDTable.Method,methodIx);
  1423. }
  1424. internal sealed override uint TypeDefOrRefToken()
  1425. {
  1426. uint cIx = Row;
  1427. cIx = cIx << 2;
  1428. return cIx;
  1429. }
  1430. internal sealed override void TypeSig(MemoryStream sig)
  1431. {
  1432. if (!typeIndexChecked) CheckTypeIndex();
  1433. sig.WriteByte(GetTypeIndex());
  1434. MetaData.CompressNum(TypeDefOrRefToken(),sig);
  1435. }
  1436. internal sealed override uint GetCodedIx(CIx code)
  1437. {
  1438. switch (code) {
  1439. case (CIx.TypeDefOrRef) : return 0;
  1440. case (CIx.HasCustomAttr) : return 3;
  1441. case (CIx.HasDeclSecurity) : return 0;
  1442. case (CIx.TypeOrMethodDef) : return 0;
  1443. }
  1444. return 0;
  1445. }
  1446. }
  1447. /**************************************************************************/
  1448. /// <summary>
  1449. /// Descriptor for a class/interface declared in another module of THIS
  1450. /// assembly, or in another assembly.
  1451. /// </summary>
  1452. public class ClassRef : Class, IExternRef, IResolutionScope {
  1453. protected IResolutionScope parent;
  1454. ExternClass externClass;
  1455. protected MetaData metaData;
  1456. internal ClassRef(string nsName, string name, MetaData md) : base(nsName, name, md)
  1457. {
  1458. metaData = md;
  1459. tabIx = MDTable.TypeRef;
  1460. }
  1461. /// <summary>
  1462. /// Add a method to this class
  1463. /// </summary>
  1464. /// <param name="name">method name</param>
  1465. /// <param name="retType">return type</param>
  1466. /// <param name="pars">parameter types</param>
  1467. /// <returns>a descriptor for this method</returns>
  1468. public MethodRef AddMethod(string name, Type retType, Type[] pars)
  1469. {
  1470. MethodRef meth = new MethodRef(this,name,retType,pars,false,null);
  1471. metaData.AddToTable(MDTable.MemberRef,meth);
  1472. return meth;
  1473. }
  1474. /// <summary>
  1475. /// Add a method to this class
  1476. /// </summary>
  1477. /// <param name="name">method name</param>
  1478. /// <param name="retType">return type</param>
  1479. /// <param name="pars">parameter types</param>
  1480. /// <returns>a descriptor for this method</returns>
  1481. public MethodRef AddVarArgMethod(string name, Type retType,
  1482. Type[] pars, Type[] optPars)
  1483. {
  1484. MethodRef meth = new MethodRef(this,name,retType,pars,true,optPars);
  1485. metaData.AddToTable(MDTable.MemberRef,meth);
  1486. return meth;
  1487. }
  1488. /// <summary>
  1489. /// Add a field to this class
  1490. /// </summary>
  1491. /// <param name="name">field name</param>
  1492. /// <param name="fType">field type</param>
  1493. /// <returns>a descriptor for this field</returns>
  1494. public FieldRef AddField(string name, Type fType)
  1495. {
  1496. FieldRef field = new FieldRef(this,name,fType);
  1497. metaData.AddToTable(MDTable.MemberRef,field);
  1498. return field;
  1499. }
  1500. public ClassRef AddClass (string nsName, string name)
  1501. {
  1502. ClassRef aClass = new ClassRef(nsName,name,metaData);
  1503. metaData.AddToTable(MDTable.TypeRef,aClass);
  1504. aClass.SetParent(this);
  1505. return aClass;
  1506. }
  1507. public ClassRef AddValueClass (string nsName, string name)
  1508. {
  1509. ClassRef aClass = AddClass (nsName, name);
  1510. aClass.MakeValueClass (ValueClass.ValueType);
  1511. return aClass;
  1512. }
  1513. internal void SetParent(IResolutionScope par)
  1514. {
  1515. parent = par;
  1516. }
  1517. internal override string TypeName()
  1518. {
  1519. if ((parent != null) && (parent is AssemblyRef))
  1520. return (nameSpace + "." + name + ", " + ((AssemblyRef)parent).TypeName());
  1521. else
  1522. return (nameSpace + name);
  1523. }
  1524. internal sealed override uint Size(MetaData md)
  1525. {
  1526. return md.CodedIndexSize(CIx.ResolutionScope) + 2 *
  1527. md.StringsIndexSize();
  1528. }
  1529. internal sealed override void Write(FileImage output)
  1530. {
  1531. output.WriteCodedIndex(CIx.ResolutionScope,(MetaDataElement) parent);
  1532. output.StringsIndex(nameIx);
  1533. output.StringsIndex(nameSpaceIx);
  1534. }
  1535. internal override sealed uint TypeDefOrRefToken()
  1536. {
  1537. uint cIx = Row;
  1538. cIx = (cIx << 2) | 0x1;
  1539. return cIx;
  1540. }
  1541. internal override void TypeSig(MemoryStream sig)
  1542. {
  1543. sig.WriteByte(GetTypeIndex());
  1544. MetaData.CompressNum(TypeDefOrRefToken(),sig);
  1545. }
  1546. internal sealed override uint GetCodedIx(CIx code)
  1547. {
  1548. switch (code) {
  1549. case (CIx.TypeDefOrRef) : return 1;
  1550. case (CIx.HasCustomAttr) : return 2;
  1551. case (CIx.MemberRefParent) : return 1;
  1552. case (CIx.ResolutionScope) : return 3;
  1553. }
  1554. return 0;
  1555. }
  1556. }
  1557. /**************************************************************************/
  1558. public class ExternClassRef : ClassRef {
  1559. ExternClass externClass;
  1560. internal ExternClassRef(TypeAttr attrs, string nsName, string name,
  1561. FileRef declFile, MetaData md) : base(nsName,name,md)
  1562. {
  1563. externClass = new ExternClass(attrs,nameSpaceIx,nameIx,declFile);
  1564. metaData.AddToTable(MDTable.ExportedType,externClass);
  1565. }
  1566. internal ExternClassRef(string name, MetaData md) : base(null,name,md)
  1567. {
  1568. }
  1569. public ClassRef AddNestedClass(TypeAttr attrs, string name)
  1570. {
  1571. ExternClassRef nestedClass = new ExternClassRef(name,metaData);
  1572. externClass = new ExternClass(attrs,0,nameIx,this.externClass);
  1573. metaData.AddToTable(MDTable.ExportedType,externClass);
  1574. return nestedClass;
  1575. }
  1576. }
  1577. /**************************************************************************/
  1578. /// <summary>
  1579. /// Descriptor for a class defined in another module of THIS assembly
  1580. /// and exported (.class extern)
  1581. /// </summary>
  1582. internal class ExternClass : Class {
  1583. MetaDataElement parent;
  1584. uint flags;
  1585. internal ExternClass(TypeAttr attr, uint nsIx, uint nIx,
  1586. MetaDataElement paren) : base(nsIx,nIx)
  1587. {
  1588. flags = (uint)attr;
  1589. parent = paren;
  1590. tabIx = MDTable.ExportedType;
  1591. }
  1592. internal sealed override uint Size(MetaData md)
  1593. {
  1594. return 8 + 2* md.StringsIndexSize() + md.CodedIndexSize(CIx.Implementation);
  1595. }
  1596. internal sealed override void Write(FileImage output)
  1597. {
  1598. output.Write(flags);
  1599. output.Write(0);
  1600. output.StringsIndex(nameIx);
  1601. output.StringsIndex(nameSpaceIx);
  1602. output.WriteCodedIndex(CIx.Implementation,parent);
  1603. }
  1604. internal sealed override uint GetCodedIx(CIx code)
  1605. {
  1606. switch (code) {
  1607. case (CIx.HasCustomAttr) : return 17;
  1608. case (CIx.Implementation) : return 2;
  1609. }
  1610. return 0;
  1611. }
  1612. }
  1613. public class MVar : Type {
  1614. private int index;
  1615. public MVar (int index) : base (0x1E)
  1616. {
  1617. this.index = index;
  1618. tabIx = MDTable.TypeSpec;
  1619. }
  1620. internal sealed override void TypeSig(MemoryStream str)
  1621. {
  1622. str.WriteByte(typeIndex);
  1623. MetaData.CompressNum ((uint) index, str);
  1624. }
  1625. }
  1626. public class GenericTypeSpec : Type {
  1627. private int index;
  1628. public GenericTypeSpec (int index) : base (0x13)
  1629. {
  1630. this.index = index;
  1631. tabIx = MDTable.TypeSpec;
  1632. }
  1633. internal sealed override void TypeSig(MemoryStream str)
  1634. {
  1635. str.WriteByte(typeIndex);
  1636. MetaData.CompressNum ((uint) index, str);
  1637. }
  1638. }
  1639. public class GenericTypeInst : Type {
  1640. private Type gen_type;
  1641. private Type[] gen_param;
  1642. public GenericTypeInst (Type gen_type, Type[] gen_param) : base (0x15)
  1643. {
  1644. typeIndex = 0x15;
  1645. this.gen_type = gen_type;
  1646. this.gen_param = gen_param;
  1647. tabIx = MDTable.TypeSpec;
  1648. }
  1649. internal sealed override void TypeSig(MemoryStream str)
  1650. {
  1651. str.WriteByte(typeIndex);
  1652. gen_type.TypeSig (str);
  1653. MetaData.CompressNum ((uint) gen_param.Length, str);
  1654. foreach (Type param in gen_param)
  1655. param.TypeSig (str);
  1656. }
  1657. }
  1658. public class GenericMethodSig {
  1659. private Type[] gen_param;
  1660. public GenericMethodSig (Type[] gen_param)
  1661. {
  1662. this.gen_param = gen_param;
  1663. }
  1664. internal void TypeSig (MemoryStream str)
  1665. {
  1666. MetaData.CompressNum ((uint) gen_param.Length, str); // THIS IS NOT RIGHT, but works
  1667. MetaData.CompressNum ((uint) gen_param.Length, str);
  1668. foreach (Type param in gen_param)
  1669. param.TypeSig (str);
  1670. }
  1671. internal uint GetSigIx (MetaData md)
  1672. {
  1673. MemoryStream sig = new MemoryStream();
  1674. TypeSig (sig);
  1675. return md.AddToBlobHeap (sig.ToArray());
  1676. }
  1677. }
  1678. public class Sentinel : Type {
  1679. public Sentinel () : base (0x41) { }
  1680. internal sealed override void TypeSig(MemoryStream str)
  1681. {
  1682. str.WriteByte(typeIndex);
  1683. }
  1684. }
  1685. /**************************************************************************/
  1686. /// <summary>
  1687. /// Descriptor for a FunctionPointer type
  1688. /// </summary>
  1689. ///
  1690. public class MethPtrType : Type {
  1691. bool varArgMeth;
  1692. Type retType;
  1693. Type [] parList;
  1694. Type [] optParList;
  1695. CallConv callConv;
  1696. uint numPars;
  1697. uint numOptPars;
  1698. uint sigIx = 0;
  1699. /// <summary>
  1700. /// Create a new function pointer type
  1701. /// </summary>
  1702. /// <param name="meth">the function to be referenced</param>
  1703. public MethPtrType (CallConv callconv, Type retType, Type[] pars,
  1704. bool varArgMeth, Type[] optPars) : base(0x1B)
  1705. {
  1706. this.retType = retType;
  1707. callConv = callconv;
  1708. parList = pars;
  1709. this.varArgMeth = varArgMeth;
  1710. if (parList != null) numPars = (uint)parList.Length;
  1711. if (varArgMeth) {
  1712. optParList = optPars;
  1713. if (optParList != null) numOptPars = (uint)optParList.Length;
  1714. callConv |= CallConv.Vararg;
  1715. }
  1716. tabIx = MDTable.TypeSpec;
  1717. }
  1718. internal sealed override void TypeSig(MemoryStream sig)
  1719. {
  1720. sig.WriteByte(typeIndex);
  1721. // Bootlegged from method ref
  1722. sig.WriteByte((byte)callConv);
  1723. MetaData.CompressNum (numPars + numOptPars, sig);
  1724. retType.TypeSig (sig);
  1725. for (int i=0; i < numPars; i++) {
  1726. parList[i].TypeSig (sig);
  1727. }
  1728. if (varArgMeth) {
  1729. sig.WriteByte (0x41); // Write the sentinel
  1730. for (int i=0; i < numOptPars; i++) {
  1731. optParList[i].TypeSig (sig);
  1732. }
  1733. }
  1734. }
  1735. internal sealed override void BuildTables(MetaData md)
  1736. {
  1737. if (done) return;
  1738. MemoryStream sig = new MemoryStream();
  1739. TypeSig(sig);
  1740. sigIx = md.AddToBlobHeap(sig.ToArray());
  1741. done = true;
  1742. }
  1743. internal sealed override uint Size(MetaData md)
  1744. {
  1745. return md.BlobIndexSize();
  1746. }
  1747. internal sealed override void Write(FileImage output)
  1748. {
  1749. output.BlobIndex(sigIx);
  1750. }
  1751. internal sealed override uint GetCodedIx(CIx code) { return 0x1B; }
  1752. }
  1753. #region Array Types
  1754. /* Classes for Arrays */
  1755. /// <summary>
  1756. /// The IL Array type
  1757. /// </summary>
  1758. public abstract class Array : Type {
  1759. protected Type elemType;
  1760. protected MetaData metaData;
  1761. protected string cnameSpace, cname;
  1762. internal Array(Type eType, byte TypeId) : base(TypeId)
  1763. {
  1764. elemType = eType;
  1765. tabIx = MDTable.TypeSpec;
  1766. }
  1767. }
  1768. /// <summary>
  1769. /// Single dimensional array with zero lower bound
  1770. /// </summary>
  1771. public class ZeroBasedArray : Array {
  1772. /// <summary>
  1773. /// Create a new array - elementType[]
  1774. /// </summary>
  1775. /// <param name="elementType">the type of the array elements</param>
  1776. public ZeroBasedArray(Type elementType) : base (elementType, PrimitiveType.SZArray.GetTypeIndex ()) { }
  1777. internal sealed override void TypeSig(MemoryStream str)
  1778. {
  1779. str.WriteByte(typeIndex);
  1780. elemType.TypeSig(str);
  1781. }
  1782. }
  1783. /// <summary>
  1784. /// Multi dimensional array with explicit bounds
  1785. /// </summary>
  1786. public class BoundArray : Array {
  1787. int[] lowerBounds;
  1788. int[] sizes;
  1789. uint numDims;
  1790. /// <summary>
  1791. /// Create a new multi dimensional array type
  1792. /// eg. elemType[1..5,3..10,5,,] would be
  1793. /// new BoundArray(elemType,5,[1,3,0],[5,10,4])
  1794. /// </summary>
  1795. /// <param name="elementType">the type of the elements</param>
  1796. /// <param name="dimensions">the number of dimensions</param>
  1797. /// <param name="loBounds">lower bounds of dimensions</param>
  1798. /// <param name="upBounds">upper bounds of dimensions</param>
  1799. public BoundArray(Type elementType, uint dimensions, int[] loBounds,
  1800. int[] upBounds) : base (elementType,0x14)
  1801. {
  1802. numDims = dimensions;
  1803. lowerBounds = loBounds;
  1804. sizes = new int[loBounds.Length];
  1805. for (int i=0; i < loBounds.Length; i++) {
  1806. sizes[i] = upBounds[i] - loBounds[i] + 1;
  1807. }
  1808. }
  1809. /// <summary>
  1810. /// Create a new multi dimensional array type
  1811. /// eg. elemType[5,10,20] would be new BoundArray(elemType,3,[5,10,20])
  1812. /// </summary>
  1813. /// <param name="elementType">the type of the elements</param>
  1814. /// <param name="dimensions">the number of dimensions</param>
  1815. /// <param name="size">the sizes of the dimensions</param>
  1816. public BoundArray(Type elementType, uint dimensions, int[] size)
  1817. : base (elementType,0x14)
  1818. {
  1819. numDims = dimensions;
  1820. sizes = size;
  1821. }
  1822. /// <summary>
  1823. /// Create a new multi dimensional array type
  1824. /// eg. elemType[,,] would be new BoundArray(elemType,3)
  1825. /// </summary>
  1826. /// <param name="elementType">the type of the elements</param>
  1827. /// <param name="dimensions">the number of dimensions</param>
  1828. public BoundArray(Type elementType, uint dimensions)
  1829. : base (elementType,0x14)
  1830. {
  1831. numDims = dimensions;
  1832. }
  1833. internal sealed override void TypeSig(MemoryStream str)
  1834. {
  1835. str.WriteByte(typeIndex);
  1836. elemType.TypeSig(str);
  1837. MetaData.CompressNum(numDims,str);
  1838. if ((sizes != null) && (sizes.Length > 0)) {
  1839. MetaData.CompressNum((uint)sizes.Length,str);
  1840. for (int i=0; i < sizes.Length; i++) {
  1841. MetaData.CompressNum((uint)sizes[i],str);
  1842. }
  1843. } else str.WriteByte(0);
  1844. if ((lowerBounds != null) && (lowerBounds.Length > 0)) {
  1845. MetaData.CompressNum((uint)lowerBounds.Length,str);
  1846. for (int i=0; i < lowerBounds.Length; i++) {
  1847. MetaData.CompressNum((uint)lowerBounds[i],str);
  1848. }
  1849. } else str.WriteByte(0);
  1850. }
  1851. }
  1852. #endregion
  1853. /* Empty interface for grouping TypeRef's possible ResolutionScope
  1854. namely : Module, ModuleRef, AssemblyRef and TypeRef */
  1855. public interface IResolutionScope {
  1856. }
  1857. /**************************************************************************/
  1858. /// <summary>
  1859. /// Base class for scopes (extended by Module, ModuleRef, Assembly, AssemblyRef)
  1860. /// </summary>
  1861. public abstract class ResolutionScope : MetaDataElement, IResolutionScope {
  1862. protected uint nameIx = 0;
  1863. protected MetaData metaData;
  1864. protected string name;
  1865. internal ResolutionScope(string name, MetaData md)
  1866. {
  1867. metaData = md;
  1868. this.name = name;
  1869. nameIx = md.AddToStringsHeap(name);
  1870. }
  1871. internal string GetName() { return name; }
  1872. }
  1873. /**************************************************************************/
  1874. /// <summary>
  1875. /// Descriptor for THIS assembly (.assembly)
  1876. /// </summary>
  1877. public class Assembly : ResolutionScope {
  1878. ushort majorVer, minorVer, buildNo, revisionNo;
  1879. uint flags;
  1880. uint hashAlgId;
  1881. uint keyIx = 0, cultIx = 0;
  1882. bool hasPublicKey = false;
  1883. internal Assembly(string name, MetaData md) : base(name,md)
  1884. {
  1885. tabIx = MDTable.Assembly;
  1886. }
  1887. /// <summary>
  1888. /// Add details about THIS assembly
  1889. /// </summary>
  1890. /// <param name="majVer">Major Version</param>
  1891. /// <param name="minVer">Minor Version</param>
  1892. /// <param name="bldNo">Build Number</param>
  1893. /// <param name="revNo">Revision Number</param>
  1894. /// <param name="key">Hash Key</param>
  1895. /// <param name="hash">Hash Algorithm</param>
  1896. /// <param name="cult">Culture</param>
  1897. public void AddAssemblyInfo(int majVer, int minVer, int bldNo, int revNo,
  1898. byte[] key, uint hash, string cult)
  1899. {
  1900. majorVer = (ushort)majVer;
  1901. minorVer = (ushort)minVer;
  1902. buildNo = (ushort)bldNo;
  1903. revisionNo = (ushort)revNo;
  1904. hashAlgId = hash;
  1905. hasPublicKey = (key != null);
  1906. keyIx = metaData.AddToBlobHeap(key);
  1907. cultIx = metaData.AddToStringsHeap(cult);
  1908. }
  1909. /// <summary>
  1910. /// Add an attribute to THIS assembly
  1911. /// </summary>
  1912. /// <param name="aa">assembly attribute</param>
  1913. public void AddAssemblyAttr(AssemAttr aa)
  1914. {
  1915. flags |= (uint)aa;
  1916. }
  1917. internal sealed override uint Size(MetaData md)
  1918. {
  1919. return 16 + md.BlobIndexSize() + 2 * md.StringsIndexSize();
  1920. }
  1921. internal sealed override void Write(FileImage output)
  1922. {
  1923. // Console.WriteLine("Writing assembly element with nameIx of " + nameIx + " at file offset " + output.Seek(0,SeekOrigin.Current));
  1924. output.Write((uint)hashAlgId);
  1925. output.Write(majorVer);
  1926. output.Write(minorVer);
  1927. output.Write(buildNo);
  1928. output.Write(revisionNo);
  1929. output.Write(flags);
  1930. output.BlobIndex(keyIx);
  1931. output.StringsIndex(nameIx);
  1932. output.StringsIndex(cultIx);
  1933. }
  1934. internal sealed override uint GetCodedIx(CIx code)
  1935. {
  1936. switch (code) {
  1937. case (CIx.HasCustomAttr) : return 14;
  1938. case (CIx.HasDeclSecurity) : return 2;
  1939. }
  1940. return 0;
  1941. }
  1942. internal bool HasPublicKey {
  1943. get { return hasPublicKey; }
  1944. }
  1945. }
  1946. /**************************************************************************/
  1947. /// <summary>
  1948. /// Descriptor for THIS module
  1949. /// </summary>
  1950. public class Module : ResolutionScope {
  1951. Guid mvid;
  1952. uint mvidIx = 0;
  1953. internal Module(string name, MetaData md) : base(name,md)
  1954. {
  1955. mvid = Guid.NewGuid();
  1956. mvidIx = md.AddToGUIDHeap(mvid);
  1957. tabIx = MDTable.Module;
  1958. }
  1959. public Guid Guid {
  1960. get { return mvid; }
  1961. }
  1962. internal sealed override uint Size(MetaData md)
  1963. {
  1964. return 2 + md.StringsIndexSize() + 3 * md.GUIDIndexSize();
  1965. }
  1966. internal sealed override void Write(FileImage output)
  1967. {
  1968. output.Write((short)0);
  1969. output.StringsIndex(nameIx);
  1970. output.GUIDIndex(mvidIx);
  1971. output.GUIDIndex(0);
  1972. output.GUIDIndex(0);
  1973. }
  1974. internal sealed override uint GetCodedIx(CIx code)
  1975. {
  1976. switch (code) {
  1977. case (CIx.HasCustomAttr) : return 7;
  1978. case (CIx.ResolutionScope) : return 0;
  1979. }
  1980. return 0;
  1981. }
  1982. }
  1983. /**************************************************************************/
  1984. /// <summary>
  1985. /// Descriptor for another module in THIS assembly
  1986. /// </summary>
  1987. public class ModuleRef : ResolutionScope, IExternRef {
  1988. internal ModuleRef(MetaData md, string name) : base(name,md)
  1989. {
  1990. tabIx = MDTable.ModuleRef;
  1991. }
  1992. /// <summary>
  1993. /// Add a class to this external module. This is a class declared in
  1994. /// another module of THIS assembly.
  1995. /// </summary>
  1996. /// <param name="nsName">name space name</param>
  1997. /// <param name="name">class name</param>
  1998. /// <returns>a descriptor for this class in another module</returns>
  1999. public ClassRef AddClass(string nsName, string name)
  2000. {
  2001. ClassRef aClass = new ClassRef(nsName,name,metaData);
  2002. metaData.AddToTable(MDTable.TypeRef,aClass);
  2003. aClass.SetParent(this);
  2004. return aClass;
  2005. }
  2006. /// <summary>
  2007. /// Make a file descriptor to correspond to this module. The file
  2008. /// descriptor will have the same name as the module descriptor
  2009. /// </summary>
  2010. /// <param name="hashBytes">the hash of the file</param>
  2011. /// <param name="hasMetaData">the file contains metadata</param>
  2012. /// <param name="entryPoint">the program entry point is in this file</param>
  2013. /// <returns>a descriptor for the file which contains this module</returns>
  2014. public FileRef MakeFile(byte[] hashBytes, bool hasMetaData, bool entryPoint)
  2015. {
  2016. FileRef file = new FileRef(nameIx,hashBytes,hasMetaData,entryPoint,metaData);
  2017. metaData.AddToTable(MDTable.File,file);
  2018. return file;
  2019. }
  2020. /// <summary>
  2021. /// Add a value class to this module. This is a class declared in
  2022. /// another module of THIS assembly.
  2023. /// </summary>
  2024. /// <param name="nsName">name space name</param>
  2025. /// <param name="name">class name</param>
  2026. /// <returns></returns>
  2027. public ClassRef AddValueClass(string nsName, string name)
  2028. {
  2029. ClassRef aClass = new ClassRef(nsName,name,metaData);
  2030. metaData.AddToTable(MDTable.TypeRef,aClass);
  2031. aClass.SetParent(this);
  2032. aClass.MakeValueClass(ValueClass.ValueType);
  2033. return aClass;
  2034. }
  2035. /// <summary>
  2036. /// Add a class which is declared public in this external module of
  2037. /// THIS assembly. This class will be exported from this assembly.
  2038. /// The ilasm syntax for this is .extern class
  2039. /// </summary>
  2040. /// <param name="attrSet">attributes of the class to be exported</param>
  2041. /// <param name="nsName">name space name</param>
  2042. /// <param name="name">external class name</param>
  2043. /// <param name="declFile">the file where the class is declared</param>
  2044. /// <param name="isValueClass">is this class a value type?</param>
  2045. /// <returns>a descriptor for this external class</returns>
  2046. public ExternClassRef AddExternClass(TypeAttr attrSet, string nsName,
  2047. string name, FileRef declFile,
  2048. bool isValueClass) {
  2049. ExternClassRef cRef = new ExternClassRef(attrSet,nsName,name,declFile,metaData);
  2050. metaData.AddToTable(MDTable.TypeRef,cRef);
  2051. cRef.SetParent(this);
  2052. if (isValueClass) cRef.MakeValueClass(ValueClass.ValueType);
  2053. return cRef;
  2054. }
  2055. /// <summary>
  2056. /// Add a "global" method in another module
  2057. /// </summary>
  2058. /// <param name="name">method name</param>
  2059. /// <param name="retType">return type</param>
  2060. /// <param name="pars">method parameter types</param>
  2061. /// <returns>a descriptor for this method in anther module</returns>
  2062. public MethodRef AddMethod(string name, Type retType, Type[] pars)
  2063. {
  2064. MethodRef meth = new MethodRef(this,name,retType,pars,false,null);
  2065. metaData.AddToTable(MDTable.MemberRef,meth);
  2066. return meth;
  2067. }
  2068. /// <summary>
  2069. /// Add a vararg method to this class
  2070. /// </summary>
  2071. /// <param name="name">method name</param>
  2072. /// <param name="retType">return type</param>
  2073. /// <param name="pars">parameter types</param>
  2074. /// <param name="optPars">optional param types for this vararg method</param>
  2075. /// <returns>a descriptor for this method</returns>
  2076. public MethodRef AddVarArgMethod(string name, Type retType,
  2077. Type[] pars, Type[] optPars) {
  2078. MethodRef meth = new MethodRef(this,name,retType,pars,true,optPars);
  2079. metaData.AddToTable(MDTable.MemberRef,meth);
  2080. return meth;
  2081. }
  2082. /// <summary>
  2083. /// Add a field in another module
  2084. /// </summary>
  2085. /// <param name="name">field name</param>
  2086. /// <param name="fType">field type</param>
  2087. /// <returns>a descriptor for this field in another module</returns>
  2088. public FieldRef AddField(string name, Type fType)
  2089. {
  2090. FieldRef field = new FieldRef(this,name,fType);
  2091. metaData.AddToTable(MDTable.MemberRef,field);
  2092. return field;
  2093. }
  2094. internal sealed override uint Size(MetaData md)
  2095. {
  2096. return md.StringsIndexSize();
  2097. }
  2098. internal sealed override void Write(FileImage output)
  2099. {
  2100. output.StringsIndex(nameIx);
  2101. }
  2102. internal sealed override uint GetCodedIx(CIx code)
  2103. {
  2104. switch (code) {
  2105. case (CIx.HasCustomAttr) : return 12;
  2106. case (CIx.MemberRefParent) : return 2;
  2107. case (CIx.ResolutionScope) : return 1;
  2108. }
  2109. return 0;
  2110. }
  2111. }
  2112. #region Classes for Constants
  2113. /// <summary>
  2114. /// Descriptor for a constant value
  2115. /// </summary>
  2116. public abstract class Constant {
  2117. protected uint size = 0;
  2118. protected Type type;
  2119. protected uint blobIndex;
  2120. protected bool addedToBlobHeap = false;
  2121. internal Constant() { }
  2122. internal virtual uint GetBlobIndex(MetaData md) { return 0; }
  2123. internal uint GetSize() { return size; }
  2124. internal byte GetTypeIndex() { return type.GetTypeIndex(); }
  2125. internal virtual void Write(BinaryWriter bw) { }
  2126. }
  2127. /// <summary>
  2128. /// Descriptor for a constant value
  2129. /// </summary>
  2130. public abstract class DataConstant : Constant {
  2131. private uint dataOffset = 0;
  2132. internal DataConstant() { }
  2133. public uint DataOffset {
  2134. get { return dataOffset; }
  2135. set { dataOffset = value; }
  2136. }
  2137. }
  2138. /// <summary>
  2139. /// Boolean constant
  2140. /// </summary>
  2141. public class BoolConst : Constant {
  2142. bool val;
  2143. /// <summary>
  2144. /// Create a new boolean constant with the value "val"
  2145. /// </summary>
  2146. /// <param name="val">value of this boolean constant</param>
  2147. public BoolConst(bool val)
  2148. {
  2149. this.val = val;
  2150. size = 1;
  2151. type = PrimitiveType.Boolean;
  2152. }
  2153. internal sealed override uint GetBlobIndex(MetaData md)
  2154. {
  2155. if (!addedToBlobHeap) {
  2156. if (val) blobIndex = md.AddToBlobHeap((sbyte)1);
  2157. else blobIndex = md.AddToBlobHeap((sbyte)0);
  2158. addedToBlobHeap = true;
  2159. }
  2160. return blobIndex;
  2161. }
  2162. internal sealed override void Write(BinaryWriter bw)
  2163. {
  2164. if (val) bw.Write((sbyte)1);
  2165. else bw.Write((sbyte)0);
  2166. }
  2167. }
  2168. public class ByteArrConst : DataConstant {
  2169. byte[] val;
  2170. public ByteArrConst(byte[] val)
  2171. {
  2172. type = PrimitiveType.String;
  2173. this.val = val;
  2174. size = (uint)val.Length;
  2175. }
  2176. public Type Type {
  2177. get { return type; }
  2178. set { type = value; }
  2179. }
  2180. internal sealed override uint GetBlobIndex(MetaData md)
  2181. {
  2182. if (!addedToBlobHeap) {
  2183. blobIndex = md.AddToBlobHeap(val);
  2184. addedToBlobHeap = true;
  2185. }
  2186. return blobIndex;
  2187. }
  2188. internal sealed override void Write(BinaryWriter bw)
  2189. {
  2190. bw.Write(val);
  2191. }
  2192. }
  2193. public class CharConst : Constant {
  2194. char val;
  2195. public CharConst(char val)
  2196. {
  2197. this.val = val;
  2198. size = 2;
  2199. type = PrimitiveType.Char;
  2200. }
  2201. internal sealed override uint GetBlobIndex(MetaData md)
  2202. {
  2203. if (!addedToBlobHeap) {
  2204. blobIndex = md.AddToBlobHeap(val);
  2205. addedToBlobHeap = true;
  2206. }
  2207. return blobIndex;
  2208. }
  2209. internal sealed override void Write(BinaryWriter bw)
  2210. {
  2211. bw.Write(val);
  2212. }
  2213. }
  2214. public class FloatConst : DataConstant {
  2215. float val;
  2216. public FloatConst(float val)
  2217. {
  2218. this.val = val;
  2219. size = 4;
  2220. type = PrimitiveType.Float32;
  2221. }
  2222. internal sealed override uint GetBlobIndex(MetaData md)
  2223. {
  2224. if (!addedToBlobHeap) {
  2225. blobIndex = md.AddToBlobHeap(val);
  2226. addedToBlobHeap = true;
  2227. }
  2228. return blobIndex;
  2229. }
  2230. internal sealed override void Write(BinaryWriter bw)
  2231. {
  2232. bw.Write(val);
  2233. }
  2234. }
  2235. public class DoubleConst : DataConstant {
  2236. double val;
  2237. public DoubleConst(double val)
  2238. {
  2239. this.val = val;
  2240. size = 8;
  2241. type = PrimitiveType.Float64;
  2242. }
  2243. internal sealed override uint GetBlobIndex(MetaData md)
  2244. {
  2245. if (!addedToBlobHeap) {
  2246. blobIndex = md.AddToBlobHeap(val);
  2247. addedToBlobHeap = true;
  2248. }
  2249. return blobIndex;
  2250. }
  2251. internal sealed override void Write(BinaryWriter bw)
  2252. {
  2253. bw.Write(val);
  2254. }
  2255. }
  2256. public class IntConst : DataConstant {
  2257. long val;
  2258. public IntConst(sbyte val)
  2259. {
  2260. this.val = val;
  2261. size = 1;
  2262. type = PrimitiveType.Int8;
  2263. }
  2264. public IntConst(short val)
  2265. {
  2266. this.val = val;
  2267. size = 2;
  2268. type = PrimitiveType.Int16;
  2269. }
  2270. public IntConst(int val)
  2271. {
  2272. this.val = val;
  2273. size = 4;
  2274. type = PrimitiveType.Int32;
  2275. }
  2276. public IntConst(long val)
  2277. {
  2278. this.val = val;
  2279. size = 8;
  2280. type = PrimitiveType.Int64;
  2281. }
  2282. internal sealed override uint GetBlobIndex(MetaData md)
  2283. {
  2284. if (!addedToBlobHeap) {
  2285. switch (size) {
  2286. case (1) : blobIndex = md.AddToBlobHeap((sbyte)val); break;
  2287. case (2) : blobIndex = md.AddToBlobHeap((short)val); break;
  2288. case (4) : blobIndex = md.AddToBlobHeap((int)val); break;
  2289. default : blobIndex = md.AddToBlobHeap(val); break;
  2290. }
  2291. addedToBlobHeap = true;
  2292. }
  2293. return blobIndex;
  2294. }
  2295. internal sealed override void Write(BinaryWriter bw)
  2296. {
  2297. switch (size) {
  2298. case (1) : bw.Write((sbyte)val); break;
  2299. case (2) : bw.Write((short)val); break;
  2300. case (4) : bw.Write((int)val); break;
  2301. default : bw.Write(val); break;
  2302. }
  2303. }
  2304. }
  2305. public class UIntConst : Constant {
  2306. long val;
  2307. public UIntConst(sbyte val)
  2308. {
  2309. this.val = val;
  2310. size = 1;
  2311. type = PrimitiveType.UInt8;
  2312. }
  2313. public UIntConst(short val)
  2314. {
  2315. this.val = val;
  2316. size = 2;
  2317. type = PrimitiveType.UInt16;
  2318. }
  2319. public UIntConst(int val)
  2320. {
  2321. this.val = val;
  2322. size = 4;
  2323. type = PrimitiveType.UInt32;
  2324. }
  2325. public UIntConst(long val)
  2326. {
  2327. this.val = val;
  2328. size = 8;
  2329. type = PrimitiveType.UInt64;
  2330. }
  2331. internal sealed override uint GetBlobIndex(MetaData md)
  2332. {
  2333. if (!addedToBlobHeap) {
  2334. switch (size) {
  2335. case (1) : blobIndex = md.AddToBlobHeap((sbyte)val); break;
  2336. case (2) : blobIndex = md.AddToBlobHeap((short)val); break;
  2337. case (4) : blobIndex = md.AddToBlobHeap((int)val); break;
  2338. default : blobIndex = md.AddToBlobHeap(val); break;
  2339. }
  2340. addedToBlobHeap = true;
  2341. }
  2342. return blobIndex;
  2343. }
  2344. internal sealed override void Write(BinaryWriter bw)
  2345. {
  2346. switch (size) {
  2347. case (1) : bw.Write((sbyte)val); break;
  2348. case (2) : bw.Write((short)val); break;
  2349. case (4) : bw.Write((int)val); break;
  2350. default : bw.Write(val); break;
  2351. }
  2352. }
  2353. }
  2354. public class StringConst : DataConstant {
  2355. string val;
  2356. public StringConst(string val)
  2357. {
  2358. this.val = val;
  2359. size = (uint)val.Length; // need to add null ??
  2360. type = PrimitiveType.String;
  2361. }
  2362. internal sealed override uint GetBlobIndex(MetaData md)
  2363. {
  2364. if (!addedToBlobHeap) {
  2365. byte [] b = Encoding.Unicode.GetBytes (val);
  2366. blobIndex = md.AddToBlobHeap(b);
  2367. addedToBlobHeap = true;
  2368. }
  2369. return blobIndex;
  2370. }
  2371. internal sealed override void Write(BinaryWriter bw)
  2372. {
  2373. bw.Write(val);
  2374. }
  2375. }
  2376. public class NullConst : Constant {
  2377. public NullConst()
  2378. {
  2379. size = 4;
  2380. type = PrimitiveType.Class;
  2381. }
  2382. internal sealed override uint GetBlobIndex(MetaData md)
  2383. {
  2384. if (!addedToBlobHeap) {
  2385. blobIndex = md.AddToBlobHeap((int)0);
  2386. addedToBlobHeap = true;
  2387. }
  2388. return blobIndex;
  2389. }
  2390. internal sealed override void Write(BinaryWriter bw)
  2391. {
  2392. bw.Write((int)0);
  2393. }
  2394. }
  2395. public class AddressConstant : DataConstant {
  2396. DataConstant data;
  2397. public AddressConstant(DataConstant dConst)
  2398. {
  2399. data = dConst;
  2400. size = 4;
  2401. type = PrimitiveType.TypedRef;
  2402. }
  2403. internal sealed override void Write(BinaryWriter bw)
  2404. {
  2405. ((FileImage)bw).WriteDataRVA(data.DataOffset);
  2406. }
  2407. }
  2408. public class RepeatedConstant : DataConstant {
  2409. DataConstant data;
  2410. uint repCount;
  2411. public RepeatedConstant(DataConstant dConst, int repeatCount)
  2412. {
  2413. data = dConst;
  2414. repCount = (uint)repeatCount;
  2415. int[] sizes = new int[1];
  2416. sizes[0] = repeatCount;
  2417. type = new BoundArray(type,1,sizes);
  2418. size = data.GetSize() * repCount;
  2419. }
  2420. internal sealed override void Write(BinaryWriter bw)
  2421. {
  2422. for (int i=0; i < repCount; i++) {
  2423. data.Write(bw);
  2424. }
  2425. }
  2426. }
  2427. public class ArrayConstant : DataConstant {
  2428. DataConstant[] dataVals;
  2429. public ArrayConstant(DataConstant[] dVals)
  2430. {
  2431. dataVals = dVals;
  2432. for (int i=0; i < dataVals.Length; i++) {
  2433. size += dataVals[i].GetSize();
  2434. }
  2435. }
  2436. internal sealed override void Write(BinaryWriter bw)
  2437. {
  2438. for (int i=0; i < dataVals.Length; i++) {
  2439. dataVals[i].Write(bw);
  2440. }
  2441. }
  2442. }
  2443. public class ClassType : Constant {
  2444. string name;
  2445. Class desc;
  2446. public ClassType(string className)
  2447. {
  2448. name = className;
  2449. type = PrimitiveType.ClassType;
  2450. }
  2451. public ClassType(Class classDesc)
  2452. {
  2453. desc = classDesc;
  2454. type = PrimitiveType.ClassType;
  2455. }
  2456. internal override void Write(BinaryWriter bw)
  2457. {
  2458. if (name == null) name = desc.TypeName();
  2459. bw.Write(name);
  2460. }
  2461. }
  2462. #endregion
  2463. /**************************************************************************/
  2464. /// <summary>
  2465. /// Descriptor for a custom modifier of a type (modopt or modreq)
  2466. /// </summary>
  2467. public class CustomModifiedType : Type {
  2468. Type type;
  2469. Class cmodType;
  2470. /// <summary>
  2471. /// Create a new custom modifier for a type
  2472. /// </summary>
  2473. /// <param name="type">the type to be modified</param>
  2474. /// <param name="cmod">the modifier</param>
  2475. /// <param name="cmodType">the type reference to be associated with the type</param>
  2476. public CustomModifiedType(Type type, CustomModifier cmod, Class cmodType)
  2477. : base((byte)cmod)
  2478. {
  2479. this.type = type;
  2480. this.cmodType = cmodType;
  2481. }
  2482. internal sealed override void TypeSig(MemoryStream str)
  2483. {
  2484. str.WriteByte(typeIndex);
  2485. MetaData.CompressNum(cmodType.TypeDefOrRefToken(),str);
  2486. type.TypeSig(str);
  2487. }
  2488. }
  2489. /**************************************************************************/
  2490. /// <summary>
  2491. /// Base class for Event and Property descriptors
  2492. /// </summary>
  2493. public class Feature : MetaDataElement {
  2494. internal enum MethodType : ushort { Setter = 0x01, Getter, Other = 0x04, AddOn = 0x08,
  2495. RemoveOn = 0x10, Fire = 0x20 }
  2496. private static readonly int INITSIZE = 5;
  2497. private static readonly ushort specialName = 0x200;
  2498. private static readonly ushort rtSpecialName = 0x400;
  2499. protected ClassDef parent;
  2500. protected ushort flags = 0;
  2501. protected string name;
  2502. protected int tide = 0;
  2503. protected uint nameIx;
  2504. protected MethodSemantics[] methods = new MethodSemantics[INITSIZE];
  2505. internal Feature(string name, ClassDef par)
  2506. {
  2507. parent = par;
  2508. this.name = name;
  2509. }
  2510. internal void AddMethod(MethodDef meth, MethodType mType)
  2511. {
  2512. if (tide >= methods.Length) {
  2513. int len = methods.Length;
  2514. MethodSemantics[] mTmp = methods;
  2515. methods = new MethodSemantics[len * 2];
  2516. for (int i=0; i < len; i++) {
  2517. methods[i] = mTmp[i];
  2518. }
  2519. }
  2520. methods[tide++] = new MethodSemantics(mType,meth,this);
  2521. }
  2522. /// <summary>
  2523. /// Set the specialName attribute for this Event or Property
  2524. /// </summary>
  2525. public void SetSpecialName()
  2526. {
  2527. flags |= specialName;
  2528. }
  2529. /// <summary>
  2530. /// Set the RTSpecialName attribute for this Event or Property
  2531. /// </summary>
  2532. public void SetRTSpecialName()
  2533. {
  2534. flags |= rtSpecialName;
  2535. }
  2536. }
  2537. /**************************************************************************/
  2538. /// <summary>
  2539. /// Descriptor for an event
  2540. /// </summary>
  2541. public class Event : Feature {
  2542. Type eventType;
  2543. internal Event(string name, Type eType, ClassDef parent)
  2544. : base(name, parent)
  2545. {
  2546. eventType = eType;
  2547. tabIx = MDTable.Event;
  2548. }
  2549. /// <summary>
  2550. /// Add the addon method to this event
  2551. /// </summary>
  2552. /// <param name="addon">the addon method</param>
  2553. public void AddAddon(MethodDef addon)
  2554. {
  2555. AddMethod(addon,MethodType.AddOn);
  2556. }
  2557. /// <summary>
  2558. /// Add the removeon method to this event
  2559. /// </summary>
  2560. /// <param name="removeOn">the removeon method</param>
  2561. public void AddRemoveOn(MethodDef removeOn)
  2562. {
  2563. AddMethod(removeOn,MethodType.RemoveOn);
  2564. }
  2565. /// <summary>
  2566. /// Add the fire method to this event
  2567. /// </summary>
  2568. /// <param name="fire">the fire method</param>
  2569. public void AddFire(MethodDef fire)
  2570. {
  2571. AddMethod(fire,MethodType.Fire);
  2572. }
  2573. /// <summary>
  2574. /// Add another method to this event
  2575. /// </summary>
  2576. /// <param name="other">the method to be added</param>
  2577. public void AddOther(MethodDef other)
  2578. {
  2579. AddMethod(other,MethodType.Other);
  2580. }
  2581. internal sealed override void BuildTables(MetaData md)
  2582. {
  2583. if (done) return;
  2584. nameIx = md.AddToStringsHeap(name);
  2585. for (int i=0; i < tide; i++) {
  2586. md.AddToTable(MDTable.MethodSemantics,methods[i]);
  2587. }
  2588. done = true;
  2589. }
  2590. internal sealed override uint Size(MetaData md)
  2591. {
  2592. return 2 + md.StringsIndexSize() + md.CodedIndexSize(CIx.TypeDefOrRef);
  2593. }
  2594. internal sealed override void Write(FileImage output)
  2595. {
  2596. output.Write(flags);
  2597. output.StringsIndex(nameIx);
  2598. output.WriteCodedIndex(CIx.TypeDefOrRef,eventType);
  2599. }
  2600. internal sealed override uint GetCodedIx(CIx code)
  2601. {
  2602. switch (code) {
  2603. case (CIx.HasCustomAttr) : return 10;
  2604. case (CIx.HasSemantics) : return 0;
  2605. }
  2606. return 0;
  2607. }
  2608. }
  2609. /**************************************************************************/
  2610. /// <summary>
  2611. /// Descriptor for the Property of a class
  2612. /// </summary>
  2613. public class Property : Feature {
  2614. private static readonly byte PropertyTag = 0x8;
  2615. MethodDef getterMeth;
  2616. ConstantElem constVal;
  2617. uint typeBlobIx = 0;
  2618. Type[] parList;
  2619. Type returnType;
  2620. uint numPars = 0;
  2621. internal Property(string name, Type retType, Type[] pars, ClassDef parent) : base(name, parent)
  2622. {
  2623. returnType = retType;
  2624. parList = pars;
  2625. if (pars != null) numPars = (uint)pars.Length;
  2626. tabIx = MDTable.Property;
  2627. }
  2628. /// <summary>
  2629. /// Add a set method to this property
  2630. /// </summary>
  2631. /// <param name="setter">the set method</param>
  2632. public void AddSetter(MethodDef setter)
  2633. {
  2634. AddMethod(setter,MethodType.Setter);
  2635. }
  2636. /// <summary>
  2637. /// Add a get method to this property
  2638. /// </summary>
  2639. /// <param name="getter">the get method</param>
  2640. public void AddGetter(MethodDef getter)
  2641. {
  2642. AddMethod(getter,MethodType.Getter);
  2643. getterMeth = getter;
  2644. }
  2645. /// <summary>
  2646. /// Add another method to this property
  2647. /// </summary>
  2648. /// <param name="other">the method</param>
  2649. public void AddOther(MethodDef other)
  2650. {
  2651. AddMethod(other,MethodType.Other);
  2652. }
  2653. /// <summary>
  2654. /// Add an initial value for this property
  2655. /// </summary>
  2656. /// <param name="constVal">the initial value for this property</param>
  2657. public void AddInitValue(Constant constVal)
  2658. {
  2659. this.constVal = new ConstantElem(this,constVal);
  2660. }
  2661. internal sealed override void BuildTables(MetaData md)
  2662. {
  2663. if (done) return;
  2664. nameIx = md.AddToStringsHeap(name);
  2665. MemoryStream sig = new MemoryStream();
  2666. sig.WriteByte(PropertyTag);
  2667. MetaData.CompressNum(numPars,sig);
  2668. returnType.TypeSig(sig);
  2669. for (int i=0; i < numPars; i++) {
  2670. parList[i].TypeSig(sig);
  2671. }
  2672. typeBlobIx = md.AddToBlobHeap(sig.ToArray());
  2673. for (int i=0; i < tide; i++) {
  2674. md.AddToTable(MDTable.MethodSemantics,methods[i]);
  2675. }
  2676. if (constVal != null) {
  2677. md.AddToTable(MDTable.Constant,constVal);
  2678. constVal.BuildTables(md);
  2679. }
  2680. done = true;
  2681. }
  2682. internal sealed override uint Size(MetaData md)
  2683. {
  2684. return 2 + md.StringsIndexSize() + md.BlobIndexSize();
  2685. }
  2686. internal sealed override void Write(FileImage output)
  2687. {
  2688. output.Write(flags);
  2689. output.StringsIndex(nameIx);
  2690. output.BlobIndex(typeBlobIx);
  2691. }
  2692. internal sealed override uint GetCodedIx(CIx code)
  2693. {
  2694. switch (code) {
  2695. case (CIx.HasCustomAttr) : return 9;
  2696. case (CIx.HasConst) : return 2;
  2697. case (CIx.HasSemantics) : return 1;
  2698. }
  2699. return 0;
  2700. }
  2701. }
  2702. /**************************************************************************/
  2703. /// <summary>
  2704. /// Base class for field/methods (member of a class)
  2705. /// </summary>
  2706. public abstract class Member : MetaDataElement {
  2707. protected string name;
  2708. protected uint nameIx = 0, sigIx = 0;
  2709. internal Member(string memName)
  2710. {
  2711. name = memName;
  2712. tabIx = MDTable.MemberRef;
  2713. }
  2714. }
  2715. /*****************************************************************************/
  2716. /// <summary>
  2717. /// Descriptor for a field of a class
  2718. /// </summary>
  2719. public abstract class Field : Member {
  2720. protected static readonly byte FieldSig = 0x6;
  2721. protected Type type;
  2722. internal Field(string pfName, Type pfType) : base(pfName)
  2723. {
  2724. type = pfType;
  2725. }
  2726. }
  2727. /**************************************************************************/
  2728. /// <summary>
  2729. /// Descriptor for a field defined in a class of THIS assembly/module
  2730. /// </summary>
  2731. public class FieldDef : Field {
  2732. //private static readonly uint PInvokeImpl = 0x2000;
  2733. private static readonly ushort HasFieldRVA = 0x100;
  2734. private static readonly ushort HasDefault = 0x8000;
  2735. FieldRVA rva;
  2736. ConstantElem constVal;
  2737. FieldLayout layout;
  2738. FieldMarshal marshalInfo;
  2739. ushort flags;
  2740. internal FieldDef(string name, Type fType) : base(name,fType)
  2741. {
  2742. tabIx = MDTable.Field;
  2743. }
  2744. internal FieldDef(FieldAttr attrSet, string name, Type fType) : base(name, fType)
  2745. {
  2746. flags = (ushort)attrSet;
  2747. tabIx = MDTable.Field;
  2748. }
  2749. /// <summary>
  2750. /// Add an attribute(s) to this field
  2751. /// </summary>
  2752. /// <param name="fa">the attribute(s) to be added</param>
  2753. public void AddFieldAttr(FieldAttr fa)
  2754. {
  2755. flags |= (ushort)fa;
  2756. }
  2757. /// <summary>
  2758. /// Add a value for this field
  2759. /// </summary>
  2760. /// <param name="val">the value for the field</param>
  2761. public void AddValue(Constant val)
  2762. {
  2763. constVal = new ConstantElem(this,val);
  2764. flags |= HasDefault;
  2765. }
  2766. /// <summary>
  2767. /// Add an initial value for this field (at dataLabel) (.data)
  2768. /// </summary>
  2769. /// <param name="val">the value for the field</param>
  2770. /// <param name="repeatVal">the number of repetitions of this value</param>
  2771. public void AddDataValue(DataConstant val)
  2772. {
  2773. flags |= HasFieldRVA;
  2774. rva = new FieldRVA(this,val);
  2775. }
  2776. /// <summary>
  2777. /// Set the offset of the field. Used for sequential or explicit classes.
  2778. /// (.field [offs])
  2779. /// </summary>
  2780. /// <param name="offs">field offset</param>
  2781. public void SetOffset(uint offs)
  2782. {
  2783. layout = new FieldLayout(this,offs);
  2784. }
  2785. /// <summary>
  2786. /// Set the marshalling info for a field
  2787. /// </summary>
  2788. /// <param name="mInf"></param>
  2789. public void SetMarshalInfo(NativeType marshallType)
  2790. {
  2791. flags |= (ushort) FieldAttr.HasFieldMarshal;
  2792. marshalInfo = new FieldMarshal(this,marshallType);
  2793. }
  2794. internal sealed override void BuildTables(MetaData md)
  2795. {
  2796. if (done) return;
  2797. nameIx = md.AddToStringsHeap(name);
  2798. MemoryStream sig = new MemoryStream();
  2799. sig.WriteByte(FieldSig);
  2800. type.TypeSig(sig);
  2801. sigIx = md.AddToBlobHeap(sig.ToArray());
  2802. if (rva != null) {
  2803. md.AddToTable(MDTable.FieldRVA,rva);
  2804. rva.BuildTables(md);
  2805. } else if (constVal != null) {
  2806. md.AddToTable(MDTable.Constant,constVal);
  2807. constVal.BuildTables(md);
  2808. }
  2809. if (layout != null) md.AddToTable(MDTable.FieldLayout,layout);
  2810. if (marshalInfo != null) {
  2811. md.AddToTable(MDTable.FieldMarshal,marshalInfo);
  2812. marshalInfo.BuildTables(md);
  2813. }
  2814. done = true;
  2815. }
  2816. internal sealed override uint Size(MetaData md)
  2817. {
  2818. return 2 + md.StringsIndexSize() + md.BlobIndexSize();
  2819. }
  2820. internal sealed override void Write(FileImage output)
  2821. {
  2822. output.Write(flags);
  2823. output.StringsIndex(nameIx);
  2824. output.BlobIndex(sigIx);
  2825. }
  2826. internal sealed override uint GetCodedIx(CIx code)
  2827. {
  2828. switch (code) {
  2829. case (CIx.HasConst) : return 0;
  2830. case (CIx.HasCustomAttr) : return 1;
  2831. case (CIx.HasFieldMarshal) : return 0;
  2832. case (CIx.MemberForwarded) : return 0;
  2833. }
  2834. return 0;
  2835. }
  2836. }
  2837. /**************************************************************************/
  2838. /// <summary>
  2839. /// Descriptor for a field of a class defined in another assembly/module
  2840. /// </summary>
  2841. public class FieldRef : Field {
  2842. MetaDataElement parent;
  2843. internal FieldRef(MetaDataElement paren, string name, Type fType) : base(name, fType)
  2844. {
  2845. parent = paren;
  2846. }
  2847. internal sealed override void BuildTables(MetaData md)
  2848. {
  2849. if (done) return;
  2850. nameIx = md.AddToStringsHeap(name);
  2851. MemoryStream sig = new MemoryStream();
  2852. sig.WriteByte(FieldSig);
  2853. type.TypeSig(sig);
  2854. sigIx = md.AddToBlobHeap(sig.ToArray());
  2855. done = true;
  2856. }
  2857. internal sealed override uint Size(MetaData md)
  2858. {
  2859. return md.CodedIndexSize(CIx.MemberRefParent) + md.StringsIndexSize() + md.BlobIndexSize();
  2860. }
  2861. internal sealed override void Write(FileImage output)
  2862. {
  2863. output.WriteCodedIndex(CIx.MemberRefParent,parent);
  2864. output.StringsIndex(nameIx);
  2865. output.BlobIndex(sigIx);
  2866. }
  2867. internal sealed override uint GetCodedIx(CIx code) { return 6; }
  2868. }
  2869. /**************************************************************************/
  2870. /// <summary>
  2871. /// Base class for Method Descriptors
  2872. /// </summary>
  2873. public abstract class Method : Member {
  2874. protected CallConv callConv = CallConv.Default;
  2875. protected Type retType;
  2876. internal Method(string methName, Type rType) : base(methName)
  2877. {
  2878. retType = rType;
  2879. }
  2880. /// <summary>
  2881. /// Add calling conventions to this method descriptor
  2882. /// </summary>
  2883. /// <param name="cconv"></param>
  2884. public void AddCallConv(CallConv cconv)
  2885. {
  2886. callConv |= cconv;
  2887. }
  2888. internal abstract void TypeSig(MemoryStream sig);
  2889. internal uint GetSigIx(MetaData md)
  2890. {
  2891. MemoryStream sig = new MemoryStream();
  2892. TypeSig(sig);
  2893. return md.AddToBlobHeap(sig.ToArray());
  2894. }
  2895. internal Type GetRetType()
  2896. {
  2897. return retType;
  2898. }
  2899. }
  2900. /**************************************************************************/
  2901. /// <summary>
  2902. /// Descriptor for a method defined in THIS assembly/module
  2903. /// IL .method
  2904. /// </summary>
  2905. public class MethodDef : Method {
  2906. private static readonly ushort PInvokeImpl = 0x2000;
  2907. //private static readonly uint UnmanagedExport = 0x0008;
  2908. // private static readonly byte LocalSigByte = 0x7;
  2909. uint parIx = 0, textOffset = 0;
  2910. MetaData metaData;
  2911. CILInstructions code;
  2912. ArrayList securityActions = new ArrayList();
  2913. Param[] parList;
  2914. Local[] locals;
  2915. bool initLocals;
  2916. ushort methFlags = 0, implFlags = 0;
  2917. int maxStack = 0, numPars = 0;
  2918. bool entryPoint = false;
  2919. LocalSig localSig;
  2920. ArrayList varArgSigList;
  2921. ImplMap pinvokeImpl;
  2922. Param ret_param;
  2923. internal MethodDef(MetaData md, string name, Type retType, Param[] pars) : base(name,retType)
  2924. {
  2925. metaData = md;
  2926. parList = pars;
  2927. if (parList != null) numPars = parList.Length;
  2928. tabIx = MDTable.Method;
  2929. }
  2930. internal MethodDef(MetaData md, MethAttr mAttrSet, ImplAttr iAttrSet, string name, Type retType, Param[] pars) : base(name,retType)
  2931. {
  2932. metaData = md;
  2933. parList = pars;
  2934. if (parList != null) numPars = parList.Length;
  2935. // Console.WriteLine("Creating method " + name + " with " + numPars + " parameters");
  2936. methFlags = (ushort)mAttrSet;
  2937. implFlags = (ushort)iAttrSet;
  2938. tabIx = MDTable.Method;
  2939. }
  2940. internal Param[] GetPars()
  2941. {
  2942. return parList;
  2943. }
  2944. /// <summary>
  2945. /// Add some attributes to this method descriptor
  2946. /// </summary>
  2947. /// <param name="ma">the attributes to be added</param>
  2948. public void AddMethAttribute(MethAttr ma)
  2949. {
  2950. methFlags |= (ushort)ma;
  2951. }
  2952. /// <summary>
  2953. /// Add some implementation attributes to this method descriptor
  2954. /// </summary>
  2955. /// <param name="ia">the attributes to be added</param>
  2956. public void AddImplAttribute(ImplAttr ia)
  2957. {
  2958. implFlags |= (ushort)ia;
  2959. }
  2960. public void AddPInvokeInfo(ModuleRef scope, string methName,
  2961. PInvokeAttr callAttr) {
  2962. pinvokeImpl = new ImplMap((ushort)callAttr,this,methName,scope);
  2963. methFlags |= PInvokeImpl;
  2964. }
  2965. /// <summary>
  2966. /// Add a named generic type parameter
  2967. /// </summary>
  2968. public GenericParameter AddGenericParameter (short index, string name)
  2969. {
  2970. GenericParameter gp = new GenericParameter (this, metaData, index, name);
  2971. metaData.AddToTable (MDTable.GenericParam, gp);
  2972. return gp;
  2973. }
  2974. /// <summary>
  2975. /// Set the maximum stack height for this method
  2976. /// </summary>
  2977. /// <param name="maxStack">the maximum height of the stack</param>
  2978. public void SetMaxStack(int maxStack)
  2979. {
  2980. this.maxStack = maxStack;
  2981. }
  2982. /// <summary>
  2983. /// Add local variables to this method
  2984. /// </summary>
  2985. /// <param name="locals">the locals to be added</param>
  2986. /// <param name="initLocals">are locals initialised to default values</param>
  2987. public void AddLocals(Local[] locals, bool initLocals)
  2988. {
  2989. this.locals = locals;
  2990. this.initLocals = initLocals;
  2991. }
  2992. /* Add Marshal info for return type */
  2993. public void AddRetTypeMarshallInfo (NativeType marshallType)
  2994. {
  2995. ret_param = new Param (ParamAttr.HasFieldMarshal, "", retType);
  2996. ret_param.AddMarshallInfo (marshallType);
  2997. }
  2998. /// <summary>
  2999. /// Mark this method as having an entry point
  3000. /// </summary>
  3001. public void DeclareEntryPoint()
  3002. {
  3003. entryPoint = true;
  3004. }
  3005. /// <summary>
  3006. /// Create a code buffer for this method to add the IL instructions to
  3007. /// </summary>
  3008. /// <returns>a buffer for this method's IL instructions</returns>
  3009. public CILInstructions CreateCodeBuffer()
  3010. {
  3011. code = new CILInstructions(metaData);
  3012. return code;
  3013. }
  3014. /// <summary>
  3015. /// Make a method reference descriptor for this method to be used
  3016. /// as a callsite signature for this vararg method
  3017. /// </summary>
  3018. /// <param name="optPars">the optional pars for the vararg method call</param>
  3019. /// <returns></returns>
  3020. public MethodRef MakeVarArgSignature(Type[] optPars)
  3021. {
  3022. Type[] pars = new Type[numPars];
  3023. MethodRef varArgSig;
  3024. for (int i=0; i < numPars; i++) {
  3025. pars[i] = parList[i].GetParType();
  3026. }
  3027. varArgSig = new MethodRef(this,name,retType,pars,true,optPars);
  3028. if (varArgSigList == null)
  3029. varArgSigList = new ArrayList ();
  3030. varArgSigList.Add (varArgSig);
  3031. return varArgSig;
  3032. }
  3033. internal sealed override void TypeSig(MemoryStream sig)
  3034. {
  3035. sig.WriteByte((byte)callConv);
  3036. MetaData.CompressNum((uint)numPars,sig);
  3037. if (ret_param != null)
  3038. ret_param.seqNo = 0;
  3039. retType.TypeSig(sig);
  3040. for (ushort i=0; i < numPars; i++) {
  3041. parList[i].seqNo = (ushort)(i+1);
  3042. parList[i].TypeSig(sig);
  3043. }
  3044. }
  3045. internal sealed override void BuildTables(MetaData md)
  3046. {
  3047. if (done) return;
  3048. if (pinvokeImpl != null) {
  3049. md.AddToTable(MDTable.ImplMap,pinvokeImpl);
  3050. pinvokeImpl.BuildTables(md);
  3051. }
  3052. if (entryPoint) md.SetEntryPoint(this);
  3053. uint locToken = 0;
  3054. if (locals != null) {
  3055. localSig = new LocalSig(locals);
  3056. md.AddToTable(MDTable.StandAloneSig,localSig);
  3057. localSig.BuildTables(md);
  3058. locToken = localSig.Token();
  3059. }
  3060. if (code != null) {
  3061. code.CheckCode(locToken,initLocals,maxStack);
  3062. textOffset = md.AddCode(code);
  3063. }
  3064. nameIx = md.AddToStringsHeap(name);
  3065. sigIx = GetSigIx(md);
  3066. parIx = md.TableIndex(MDTable.Param);
  3067. if (ret_param != null) {
  3068. md.AddToTable(MDTable.Param, ret_param);
  3069. ret_param.BuildTables(md);
  3070. }
  3071. for (int i=0; i < numPars; i++) {
  3072. md.AddToTable(MDTable.Param,parList[i]);
  3073. parList[i].BuildTables(md);
  3074. }
  3075. if (varArgSigList != null) {
  3076. foreach (MethodRef varArgSig in varArgSigList) {
  3077. md.AddToTable(MDTable.MemberRef,varArgSig);
  3078. varArgSig.BuildTables(md);
  3079. }
  3080. }
  3081. // Console.WriteLine("method has " + numPars + " parameters");
  3082. done = true;
  3083. }
  3084. internal sealed override uint Size(MetaData md)
  3085. {
  3086. return 8 + md.StringsIndexSize() + md.BlobIndexSize() + md.TableIndexSize(MDTable.Param);
  3087. }
  3088. internal sealed override void Write(FileImage output)
  3089. {
  3090. if (ZeroRva ()) output.Write(0);
  3091. else output.WriteCodeRVA(textOffset);
  3092. output.Write(implFlags);
  3093. output.Write(methFlags);
  3094. output.StringsIndex(nameIx);
  3095. output.BlobIndex(sigIx);
  3096. output.WriteIndex(MDTable.Param,parIx);
  3097. }
  3098. internal bool ZeroRva ()
  3099. {
  3100. return (((methFlags & (ushort)MethAttr.Abstract) != 0) ||
  3101. ((implFlags & (ushort)ImplAttr.Runtime) != 0) ||
  3102. ((implFlags & (ushort)ImplAttr.InternalCall) != 0) ||
  3103. (pinvokeImpl != null)); // TODO: Not entirely true but works for now
  3104. }
  3105. internal sealed override uint GetCodedIx(CIx code)
  3106. {
  3107. switch (code) {
  3108. case (CIx.HasCustomAttr) : return 0;
  3109. case (CIx.HasDeclSecurity) : return 1;
  3110. case (CIx.MemberRefParent) : return 3;
  3111. case (CIx.MethodDefOrRef) : return 0;
  3112. case (CIx.MemberForwarded) : return 1;
  3113. case (CIx.CustomAttributeType) : return 2;
  3114. case (CIx.TypeOrMethodDef) : return 1;
  3115. }
  3116. return 0;
  3117. }
  3118. }
  3119. /**************************************************************************/
  3120. /// <summary>
  3121. /// Descriptor for a method defined in another assembly/module
  3122. /// </summary>
  3123. public class MethodRef : Method {
  3124. private static readonly byte Sentinel = 0x41;
  3125. Type[] parList, optParList;
  3126. MetaDataElement parent;
  3127. uint numPars = 0, numOptPars = 0;
  3128. internal MethodRef(MetaDataElement paren, string name, Type retType,
  3129. Type[] pars, bool varArgMeth, Type[] optPars) : base(name,retType)
  3130. {
  3131. parent = paren;
  3132. parList = pars;
  3133. if (parList != null) numPars = (uint)parList.Length;
  3134. if (varArgMeth) {
  3135. optParList = optPars;
  3136. if (optParList != null) numOptPars = (uint)optParList.Length;
  3137. callConv = CallConv.Vararg;
  3138. }
  3139. }
  3140. internal sealed override void TypeSig(MemoryStream sig)
  3141. {
  3142. sig.WriteByte((byte)callConv);
  3143. MetaData.CompressNum(numPars+numOptPars,sig);
  3144. retType.TypeSig(sig);
  3145. for (int i=0; i < numPars; i++) {
  3146. parList[i].TypeSig(sig);
  3147. }
  3148. if (numOptPars > 0) {
  3149. sig.WriteByte(Sentinel);
  3150. for (int i=0; i < numOptPars; i++) {
  3151. optParList[i].TypeSig(sig);
  3152. }
  3153. }
  3154. }
  3155. internal sealed override void BuildTables(MetaData md)
  3156. {
  3157. if (done) return;
  3158. nameIx = md.AddToStringsHeap(name);
  3159. sigIx = GetSigIx(md);
  3160. done = true;
  3161. }
  3162. internal sealed override uint Size(MetaData md)
  3163. {
  3164. return md.CodedIndexSize(CIx.MemberRefParent) + md.StringsIndexSize() + md.BlobIndexSize();
  3165. }
  3166. internal sealed override void Write(FileImage output)
  3167. {
  3168. output.WriteCodedIndex(CIx.MemberRefParent,parent);
  3169. output.StringsIndex(nameIx);
  3170. output.BlobIndex(sigIx);
  3171. }
  3172. internal sealed override uint GetCodedIx(CIx code)
  3173. {
  3174. switch (code) {
  3175. case (CIx.HasCustomAttr) : return 6;
  3176. case (CIx.MethodDefOrRef) : return 1;
  3177. case (CIx.CustomAttributeType) : return 3;
  3178. }
  3179. return 0;
  3180. }
  3181. }
  3182. /**************************************************************************/
  3183. /// <summary>
  3184. /// Descriptors for native types used for marshalling
  3185. /// </summary>
  3186. public class NativeType {
  3187. public static readonly NativeType Void = new NativeType(0x01);
  3188. public static readonly NativeType Boolean = new NativeType(0x02);
  3189. public static readonly NativeType Int8 = new NativeType(0x03);
  3190. public static readonly NativeType UInt8 = new NativeType(0x04);
  3191. public static readonly NativeType Int16 = new NativeType(0x05);
  3192. public static readonly NativeType UInt16 = new NativeType(0x06);
  3193. public static readonly NativeType Int32 = new NativeType(0x07);
  3194. public static readonly NativeType UInt32 = new NativeType(0x08);
  3195. public static readonly NativeType Int64 = new NativeType(0x09);
  3196. public static readonly NativeType UInt64 = new NativeType(0x0A);
  3197. public static readonly NativeType Float32 = new NativeType(0x0B);
  3198. public static readonly NativeType Float64 = new NativeType(0x0C);
  3199. public static readonly NativeType Currency = new NativeType(0x0F);
  3200. public static readonly NativeType BStr = new NativeType(0x13);
  3201. public static readonly NativeType LPStr = new NativeType(0x14);
  3202. public static readonly NativeType LPWStr = new NativeType(0x15);
  3203. public static readonly NativeType LPTStr = new NativeType(0x16);
  3204. public static readonly NativeType FixedSysString = new NativeType(0x17);
  3205. public static readonly NativeType IUnknown = new NativeType(0x19);
  3206. public static readonly NativeType IDispatch = new NativeType(0x1A);
  3207. public static readonly NativeType Struct = new NativeType(0x1B);
  3208. public static readonly NativeType Interface = new NativeType(0x1C);
  3209. public static readonly NativeType Int = new NativeType(0x1F);
  3210. public static readonly NativeType UInt = new NativeType(0x20);
  3211. public static readonly NativeType ByValStr = new NativeType(0x22);
  3212. public static readonly NativeType AnsiBStr = new NativeType(0x23);
  3213. public static readonly NativeType TBstr = new NativeType(0x24);
  3214. public static readonly NativeType VariantBool = new NativeType(0x25);
  3215. public static readonly NativeType FuncPtr = new NativeType(0x26);
  3216. public static readonly NativeType AsAny = new NativeType(0x28);
  3217. protected byte typeIndex;
  3218. internal NativeType(byte tyIx) { typeIndex = tyIx; }
  3219. internal byte GetTypeIndex() { return typeIndex; }
  3220. internal virtual byte[] ToBlob()
  3221. {
  3222. byte[] bytes = new byte[1];
  3223. bytes[0] = GetTypeIndex();
  3224. return bytes;
  3225. }
  3226. }
  3227. public class FixedSysString : NativeType {
  3228. uint size;
  3229. public FixedSysString (uint size) : base (NativeType.FixedSysString.GetTypeIndex ())
  3230. {
  3231. this.size = size;
  3232. }
  3233. internal override byte [] ToBlob ()
  3234. {
  3235. MemoryStream str = new MemoryStream ();
  3236. str.WriteByte (GetTypeIndex ());
  3237. MetaData.CompressNum (size, str);
  3238. return str.ToArray ();
  3239. }
  3240. }
  3241. public class NativeArray : NativeType {
  3242. NativeType elemType;
  3243. int numElem = -1, parNum = -1, elemMult = -1;
  3244. public NativeArray(NativeType elemType) : this (elemType, -1, -1, -1)
  3245. {
  3246. this.elemType = elemType;
  3247. }
  3248. /* public NativeArray(NativeType elemType, int len) : base(0x2A) {
  3249. this.elemType = elemType;
  3250. this.len = len;
  3251. }
  3252. */
  3253. public NativeArray(NativeType elemType, int numElem, int parNumForLen, int elemMult) : base(0x2A)
  3254. {
  3255. this.elemType = elemType;
  3256. this.numElem = numElem;
  3257. parNum = parNumForLen;
  3258. this.elemMult = elemMult;
  3259. }
  3260. public NativeArray(NativeType elemType, int numElem, int parNumForLen)
  3261. : this (elemType, numElem, parNumForLen, -1)
  3262. {
  3263. }
  3264. internal override byte[] ToBlob()
  3265. {
  3266. MemoryStream str = new MemoryStream();
  3267. str.WriteByte(GetTypeIndex());
  3268. if (elemType == null) str.WriteByte(0x50); // no info (MAX)
  3269. else str.WriteByte(elemType.GetTypeIndex());
  3270. /* see : mono/metadata/metadata.c:mono_metadata_parse_marshal_spec
  3271. * LAMESPEC: Older spec versions say elemMult comes before
  3272. * len. Newer spec versions don't talk about elemMult at
  3273. * all, but csc still emits it, and it is used to distinguish
  3274. * between parNum being 0, and parNum being omitted.
  3275. */
  3276. if (parNum == -1)
  3277. // <native_type> []
  3278. return str.ToArray ();
  3279. MetaData.CompressNum((uint) parNum,str);
  3280. if (numElem != -1) {
  3281. MetaData.CompressNum ((uint) numElem, str);
  3282. if (elemMult != -1)
  3283. // <native_type> [ int32 ]
  3284. MetaData.CompressNum((uint) elemMult,str);
  3285. //else <native_type> [ int32 + int32 ]
  3286. } else if (elemMult != -1) {
  3287. // When can this occur ?
  3288. MetaData.CompressNum (0, str);
  3289. MetaData.CompressNum((uint) elemMult,str);
  3290. }
  3291. //else <native_type> [ + int32 ]
  3292. return str.ToArray();
  3293. }
  3294. }
  3295. public class SafeArray : NativeType {
  3296. SafeArrayType elemType;
  3297. bool hasElemType;
  3298. public SafeArray() : base(0x1D)
  3299. {
  3300. }
  3301. public SafeArray(SafeArrayType elemType) : base(0x1D)
  3302. {
  3303. this.elemType = elemType;
  3304. hasElemType = true;
  3305. }
  3306. internal override byte[] ToBlob()
  3307. {
  3308. byte[] bytes = new byte[hasElemType ? 2 : 1];
  3309. bytes[0] = GetTypeIndex();
  3310. if (hasElemType)
  3311. bytes[1] = (byte)elemType;
  3312. return bytes;
  3313. }
  3314. }
  3315. public class FixedArray : NativeType {
  3316. NativeType elemType;
  3317. uint numElem;
  3318. //public FixedArray(NativeType elemType, int numElems) : base(0x1E) {
  3319. public FixedArray(int numElems) : base(0x1E)
  3320. {
  3321. //this.elemType = elemType;
  3322. numElem = (uint)numElems;
  3323. }
  3324. internal override byte[] ToBlob()
  3325. {
  3326. MemoryStream str = new MemoryStream();
  3327. str.WriteByte(GetTypeIndex());
  3328. MetaData.CompressNum(numElem,str);
  3329. /* FIXME:
  3330. fixed array [5] lpstr [2]
  3331. This format is not supported by ilasm 1.1.4322.2032,
  3332. but is supported by 2.0.5125..
  3333. ilasm 1.1 only supports "fixed array [5]"
  3334. if (elemType == null) str.WriteByte(0x50); // no info (MAX)
  3335. else str.WriteByte(elemType.GetTypeIndex());*/
  3336. return str.ToArray();
  3337. }
  3338. }
  3339. public class CustomMarshaller : NativeType {
  3340. string typeName;
  3341. string marshallerName;
  3342. string cookie;
  3343. public CustomMarshaller(string typeNameOrGUID, string marshallerName,
  3344. string optCookie) : base(0x2C)
  3345. {
  3346. typeName = typeNameOrGUID;
  3347. this.marshallerName = marshallerName;
  3348. cookie = optCookie;
  3349. }
  3350. public CustomMarshaller(string marshallerName, string optCookie)
  3351. :this (null, marshallerName, optCookie)
  3352. {
  3353. }
  3354. internal override byte[] ToBlob()
  3355. {
  3356. MemoryStream str = new MemoryStream();
  3357. BinaryWriter bw = new BinaryWriter(str,new UTF8Encoding());
  3358. bw.Write(GetTypeIndex());
  3359. //Native type name & unmanaged type - unused
  3360. //See mono/metadata/metadata.c : mono_metadata_parse_marshal_spec
  3361. bw.Write ((byte) 0); // Native Type name, unused
  3362. bw.Write ((byte) 0); // Unmanaged type, unused
  3363. if (marshallerName != null) {
  3364. MetaData.CompressNum ((uint)marshallerName.Length, str);
  3365. bw.Write(marshallerName.ToCharArray());
  3366. } else {
  3367. bw.Write ((byte) 0);
  3368. }
  3369. if (cookie != null) {
  3370. MetaData.CompressNum ((uint)cookie.Length, str);
  3371. bw.Write(cookie.ToCharArray());
  3372. } else {
  3373. bw.Write ((byte) 0);
  3374. }
  3375. bw.Flush();
  3376. return str.ToArray();
  3377. }
  3378. }
  3379. /**************************************************************************/
  3380. /// <summary>
  3381. /// Descriptor for the Primitive types defined in IL
  3382. /// </summary>
  3383. public class PrimitiveType : Type {
  3384. private string name;
  3385. private int systemTypeIndex;
  3386. public static int NumSystemTypes = 18;
  3387. public static readonly PrimitiveType Void = new PrimitiveType(0x01,"Void",0);
  3388. public static readonly PrimitiveType Boolean = new PrimitiveType(0x02,"Boolean",1);
  3389. public static readonly PrimitiveType Char = new PrimitiveType(0x03,"Char",2);
  3390. public static readonly PrimitiveType Int8 = new PrimitiveType(0x04,"SByte",3);
  3391. public static readonly PrimitiveType UInt8 = new PrimitiveType(0x05,"Byte",4);
  3392. public static readonly PrimitiveType Int16 = new PrimitiveType(0x06,"Int16",5);
  3393. public static readonly PrimitiveType UInt16 = new PrimitiveType(0x07,"UInt16",6);
  3394. public static readonly PrimitiveType Int32 = new PrimitiveType(0x08,"Int32",7);
  3395. public static readonly PrimitiveType UInt32 = new PrimitiveType(0x09,"UInt32",8);
  3396. public static readonly PrimitiveType Int64 = new PrimitiveType(0x0A,"Int64",9);
  3397. public static readonly PrimitiveType UInt64 = new PrimitiveType(0x0B,"UInt64",10);
  3398. public static readonly PrimitiveType Float32 = new PrimitiveType(0x0C,"Single",11);
  3399. public static readonly PrimitiveType Float64 = new PrimitiveType(0x0D,"Double",12);
  3400. public static readonly PrimitiveType String = new PrimitiveType(0x0E,"String",13);
  3401. internal static readonly PrimitiveType Class = new PrimitiveType(0x12);
  3402. public static readonly PrimitiveType TypedRef = new PrimitiveType(0x16,"TypedReference",14);
  3403. public static readonly PrimitiveType IntPtr = new PrimitiveType(0x18,"IntPtr",15);
  3404. public static readonly PrimitiveType UIntPtr = new PrimitiveType(0x19,"UIntPtr",16);
  3405. public static readonly PrimitiveType Object = new PrimitiveType(0x1C,"Object",17);
  3406. internal static readonly PrimitiveType ClassType = new PrimitiveType(0x50);
  3407. internal static readonly PrimitiveType SZArray = new PrimitiveType(0x1D);
  3408. internal static readonly PrimitiveType ValueType = new PrimitiveType(0x11, "ValueType", 18);
  3409. public static readonly PrimitiveType NativeInt = IntPtr;
  3410. public static readonly PrimitiveType NativeUInt = UIntPtr;
  3411. internal PrimitiveType(byte typeIx) : base(typeIx) { }
  3412. internal PrimitiveType(byte typeIx, string name, int STIx) : base(typeIx)
  3413. {
  3414. this.name = name;
  3415. this.systemTypeIndex = STIx;
  3416. }
  3417. internal string GetName() { return name; }
  3418. internal int GetSystemTypeIx() { return systemTypeIndex; }
  3419. internal sealed override void TypeSig(MemoryStream str)
  3420. {
  3421. str.WriteByte(typeIndex);
  3422. }
  3423. internal override MetaDataElement GetTypeSpec(MetaData md)
  3424. {
  3425. TypeSpec tS = md.GetPrimitiveTypeSpec(systemTypeIndex);
  3426. if (tS == null) {
  3427. tS = new TypeSpec(this,md);
  3428. md.SetPrimitiveTypeSpec(systemTypeIndex,tS);
  3429. md.AddToTable(MDTable.TypeSpec,tS);
  3430. }
  3431. return tS;
  3432. }
  3433. }
  3434. /**************************************************************************/
  3435. /// <summary>
  3436. /// Descriptor for an pointer (type * or type &)
  3437. /// </summary>
  3438. public abstract class PtrType : Type {
  3439. Type baseType;
  3440. internal PtrType(Type bType, byte typeIx) : base(typeIx)
  3441. {
  3442. baseType = bType;
  3443. tabIx = MDTable.TypeSpec;
  3444. }
  3445. internal sealed override void TypeSig(MemoryStream str)
  3446. {
  3447. str.WriteByte(typeIndex);
  3448. baseType.TypeSig(str);
  3449. }
  3450. }
  3451. /**************************************************************************/
  3452. /// <summary>
  3453. /// Descriptor for a managed pointer (type & or byref)
  3454. /// </summary>
  3455. public class ManagedPointer : PtrType {
  3456. /// <summary>
  3457. /// Create new managed pointer to baseType
  3458. /// </summary>
  3459. /// <param name="bType">the base type of the pointer</param>
  3460. public ManagedPointer(Type baseType) : base(baseType,0x10) { }
  3461. }
  3462. /**************************************************************************/
  3463. /// <summary>
  3464. /// Descriptor for an unmanaged pointer (type *)
  3465. /// </summary>
  3466. public class UnmanagedPointer : PtrType {
  3467. /// <summary>
  3468. /// Create a new unmanaged pointer to baseType
  3469. /// </summary>
  3470. /// <param name="baseType">the base type of the pointer</param>
  3471. public UnmanagedPointer(Type baseType) : base(baseType, 0x0F) { }
  3472. }
  3473. /**************************************************************************/
  3474. public interface IExternRef {
  3475. ClassRef AddClass(string nsName, string name);
  3476. ClassRef AddValueClass(string nsName, string name);
  3477. }
  3478. /// <summary>
  3479. /// A reference to an external assembly (.assembly extern)
  3480. /// </summary>
  3481. public class AssemblyRef : ResolutionScope, IExternRef {
  3482. private ushort major, minor, build, revision;
  3483. uint flags, keyIx, hashIx, cultIx;
  3484. bool hasVersion = false, isKeyToken = false;
  3485. byte[] keyBytes;
  3486. string culture;
  3487. internal AssemblyRef(MetaData md, string name) : base(name,md)
  3488. {
  3489. tabIx = MDTable.AssemblyRef;
  3490. }
  3491. /// <summary>
  3492. /// Add version information about this external assembly
  3493. /// </summary>
  3494. /// <param name="majVer">Major Version</param>
  3495. /// <param name="minVer">Minor Version</param>
  3496. /// <param name="bldNo">Build Number</param>
  3497. /// <param name="revNo">Revision Number</param>
  3498. public void AddVersionInfo(int majVer, int minVer, int bldNo, int revNo)
  3499. {
  3500. major = (ushort)majVer;
  3501. minor = (ushort)minVer;
  3502. build = (ushort)bldNo;
  3503. revision = (ushort)revNo;
  3504. hasVersion = true;
  3505. }
  3506. /// <summary>
  3507. /// Add the hash value for this external assembly
  3508. /// </summary>
  3509. /// <param name="hash">bytes of the hash value</param>
  3510. public void AddHash(byte[] hash)
  3511. {
  3512. hashIx = metaData.AddToBlobHeap(hash);
  3513. }
  3514. /// <summary>
  3515. /// Set the culture for this external assembly
  3516. /// </summary>
  3517. /// <param name="cult">the culture string</param>
  3518. public void AddCulture(string cult)
  3519. {
  3520. cultIx = metaData.AddToStringsHeap(cult);
  3521. culture = cult;
  3522. }
  3523. /// <summary>
  3524. /// Add the full public key for this external assembly
  3525. /// </summary>
  3526. /// <param name="key">bytes of the public key</param>
  3527. public void AddKey(byte[] key)
  3528. {
  3529. flags |= 0x0001; // full public key
  3530. keyBytes = key;
  3531. keyIx = metaData.AddToBlobHeap(key);
  3532. }
  3533. /// <summary>
  3534. /// Add the public key token (low 8 bytes of the public key)
  3535. /// </summary>
  3536. /// <param name="key">low 8 bytes of public key</param>
  3537. public void AddKeyToken(byte[] key)
  3538. {
  3539. keyIx = metaData.AddToBlobHeap(key);
  3540. keyBytes = key;
  3541. isKeyToken = true;
  3542. }
  3543. /// <summary>
  3544. /// Add a class to this external assembly
  3545. /// </summary>
  3546. /// <param name="nsName">name space name</param>
  3547. /// <param name="name">class name</param>
  3548. /// <returns></returns>
  3549. public virtual ClassRef AddClass(string nsName, string name)
  3550. {
  3551. ClassRef aClass = new ClassRef(nsName,name,metaData);
  3552. metaData.AddToTable(MDTable.TypeRef,aClass);
  3553. aClass.SetParent(this);
  3554. return aClass;
  3555. }
  3556. /// <summary>
  3557. /// Add a value class to this external assembly
  3558. /// </summary>
  3559. /// <param name="nsName">name space name</param>
  3560. /// <param name="name">class name</param>
  3561. /// <returns></returns>
  3562. public virtual ClassRef AddValueClass(string nsName, string name)
  3563. {
  3564. ClassRef aClass = new ClassRef(nsName,name,metaData);
  3565. metaData.AddToTable(MDTable.TypeRef,aClass);
  3566. aClass.SetParent(this);
  3567. aClass.MakeValueClass(ValueClass.ValueType);
  3568. return aClass;
  3569. }
  3570. internal string TypeName()
  3571. {
  3572. string result = name;
  3573. if (hasVersion)
  3574. result = result + ", Version=" + major + "." + minor + "." +
  3575. build + "." + revision;
  3576. if (keyBytes != null) {
  3577. string tokenStr = "=";
  3578. if (isKeyToken) tokenStr = "Token=";
  3579. result = result + ", PublicKey" + tokenStr;
  3580. for (int i=0; i < keyBytes.Length; i++) {
  3581. result = result + Hex.Byte(keyBytes[i]);
  3582. }
  3583. }
  3584. if (culture != null)
  3585. result = result + ", Culture=" + culture;
  3586. return result;
  3587. }
  3588. internal sealed override uint Size(MetaData md)
  3589. {
  3590. return 12 + 2 * md.StringsIndexSize() + 2 * md.BlobIndexSize();
  3591. }
  3592. internal sealed override void Write(FileImage output)
  3593. {
  3594. output.Write(major);
  3595. output.Write(minor);
  3596. output.Write(build);
  3597. output.Write(revision);
  3598. output.Write(flags);
  3599. output.BlobIndex(keyIx);
  3600. output.StringsIndex(nameIx);
  3601. output.StringsIndex(cultIx);
  3602. output.BlobIndex(hashIx);
  3603. }
  3604. internal sealed override uint GetCodedIx(CIx code)
  3605. {
  3606. switch (code) {
  3607. case (CIx.ResolutionScope) : return 2;
  3608. case (CIx.HasCustomAttr) : return 15;
  3609. case (CIx.Implementation) : return 1;
  3610. }
  3611. return 0;
  3612. }
  3613. }
  3614. /**************************************************************************/
  3615. /// <summary>
  3616. /// Descriptor for a class defined in System (mscorlib)
  3617. /// </summary>
  3618. internal class SystemClass : ClassRef {
  3619. PrimitiveType elemType;
  3620. internal SystemClass(PrimitiveType eType, AssemblyRef paren, MetaData md)
  3621. : base("System",eType.GetName(),md) {
  3622. elemType = eType;
  3623. parent = paren;
  3624. }
  3625. internal override sealed MetaDataElement GetTypeSpec(MetaData md)
  3626. {
  3627. if (typeSpec == null) typeSpec = (TypeSpec)elemType.GetTypeSpec(md);
  3628. return typeSpec;
  3629. }
  3630. internal sealed override void TypeSig(MemoryStream str)
  3631. {
  3632. str.WriteByte(elemType.GetTypeIndex());
  3633. }
  3634. }
  3635. /**************************************************************************/
  3636. /// <summary>
  3637. /// The assembly for mscorlib.
  3638. /// </summary>
  3639. public sealed class MSCorLib : AssemblyRef {
  3640. private static readonly int valueTypeIx = 18;
  3641. private readonly string systemName = "System";
  3642. private Class[] systemClasses = new Class[valueTypeIx+2];
  3643. private PrimitiveType[] systemTypes = new PrimitiveType[valueTypeIx];
  3644. private TypeSpec[] specialTypeSpecs = new TypeSpec[valueTypeIx];
  3645. private static int[] specialNames = {
  3646. PrimitiveType.Void.GetName().GetHashCode(),
  3647. PrimitiveType.Boolean.GetName().GetHashCode(),
  3648. PrimitiveType.Char.GetName().GetHashCode(),
  3649. PrimitiveType.Int8.GetName().GetHashCode(),
  3650. PrimitiveType.UInt8.GetName().GetHashCode(),
  3651. PrimitiveType.Int16.GetName().GetHashCode(),
  3652. PrimitiveType.UInt16.GetName().GetHashCode(),
  3653. PrimitiveType.Int32.GetName().GetHashCode(),
  3654. PrimitiveType.UInt32.GetName().GetHashCode(),
  3655. PrimitiveType.Int64.GetName().GetHashCode(),
  3656. PrimitiveType.UInt64.GetName().GetHashCode(),
  3657. PrimitiveType.Float32.GetName().GetHashCode(),
  3658. PrimitiveType.Float64.GetName().GetHashCode(),
  3659. PrimitiveType.String.GetName().GetHashCode(),
  3660. PrimitiveType.TypedRef.GetName().GetHashCode(),
  3661. PrimitiveType.IntPtr.GetName().GetHashCode(),
  3662. PrimitiveType.UIntPtr.GetName().GetHashCode(),
  3663. PrimitiveType.Object.GetName().GetHashCode(),
  3664. PrimitiveType.ValueType.GetName ().GetHashCode(),
  3665. "Enum".GetHashCode()
  3666. };
  3667. internal MSCorLib(MetaData md) : base(md,"mscorlib")
  3668. {
  3669. if (!PEFile.IsMSCorlib)
  3670. md.AddToTable(MDTable.AssemblyRef,this);
  3671. systemTypes[PrimitiveType.Void.GetSystemTypeIx()] = PrimitiveType.Void;
  3672. systemTypes[PrimitiveType.Boolean.GetSystemTypeIx()] = PrimitiveType.Boolean;
  3673. systemTypes[PrimitiveType.Char.GetSystemTypeIx()] = PrimitiveType.Char;
  3674. systemTypes[PrimitiveType.Int8.GetSystemTypeIx()] = PrimitiveType.Int8;
  3675. systemTypes[PrimitiveType.UInt8.GetSystemTypeIx()] = PrimitiveType.UInt8;
  3676. systemTypes[PrimitiveType.Int16.GetSystemTypeIx()] = PrimitiveType.Int16;
  3677. systemTypes[PrimitiveType.UInt16.GetSystemTypeIx()] = PrimitiveType.UInt16;
  3678. systemTypes[PrimitiveType.Int32.GetSystemTypeIx()] = PrimitiveType.Int32;
  3679. systemTypes[PrimitiveType.UInt32.GetSystemTypeIx()] = PrimitiveType.UInt32;
  3680. systemTypes[PrimitiveType.Int64.GetSystemTypeIx()] = PrimitiveType.Int64;
  3681. systemTypes[PrimitiveType.UInt64.GetSystemTypeIx()] = PrimitiveType.UInt64;
  3682. systemTypes[PrimitiveType.Float32.GetSystemTypeIx()] = PrimitiveType.Float32;
  3683. systemTypes[PrimitiveType.Float64.GetSystemTypeIx()] = PrimitiveType.Float64;
  3684. systemTypes[PrimitiveType.IntPtr.GetSystemTypeIx()] = PrimitiveType.IntPtr;
  3685. systemTypes[PrimitiveType.UIntPtr.GetSystemTypeIx()] = PrimitiveType.UIntPtr;
  3686. systemTypes[PrimitiveType.String.GetSystemTypeIx()] = PrimitiveType.String;
  3687. systemTypes[PrimitiveType.Object.GetSystemTypeIx()] = PrimitiveType.Object;
  3688. systemTypes[PrimitiveType.TypedRef.GetSystemTypeIx()] = PrimitiveType.TypedRef;
  3689. }
  3690. /// <summary>
  3691. /// Add a class to the mscorlib assembly
  3692. /// </summary>
  3693. /// <param name="nsName">name space name</param>
  3694. /// <param name="name">class name</param>
  3695. /// <returns></returns>
  3696. public override ClassRef AddClass(string nsName, string name)
  3697. {
  3698. /* This gets called by !mscorlib, for adding references INTO mscorlib, so
  3699. it should be returning ClassRef ..*/
  3700. Class aClass = GetSpecialClass(nsName,name);
  3701. if (aClass == null) {
  3702. aClass = new ClassRef(nsName,name,metaData);
  3703. metaData.AddToTable(MDTable.TypeRef,aClass);
  3704. if (aClass is ClassRef)
  3705. ((ClassRef) aClass).SetParent(this);
  3706. }
  3707. //FIXME: Check for !ClassRef here?
  3708. return (ClassRef) aClass;
  3709. }
  3710. private Class GetSpecialClass(string nsName,string name)
  3711. {
  3712. if (nsName.CompareTo(systemName) != 0) return null;
  3713. int hash = name.GetHashCode();
  3714. for (int i=0; i < specialNames.Length; i++) {
  3715. if (hash != specialNames[i])
  3716. continue;
  3717. if (systemClasses[i] == null) {
  3718. if (i < valueTypeIx) {
  3719. systemClasses[i] = new SystemClass(systemTypes[i],this,metaData);
  3720. if ((systemTypes[i] != PrimitiveType.Object) &&
  3721. (systemTypes[i] != PrimitiveType.String)) {
  3722. systemClasses[i].MakeValueClass(ValueClass.ValueType);
  3723. }
  3724. } else {
  3725. systemClasses[i] = new ClassRef(nsName,name,metaData);
  3726. ((ClassRef) systemClasses[i]).SetParent(this);
  3727. if (!ClassDef.IsValueType (nsName, name) && !ClassDef.IsEnum (nsName, name))
  3728. systemClasses[i].MakeValueClass(ValueClass.ValueType);
  3729. }
  3730. metaData.AddToTable(MDTable.TypeRef,systemClasses[i]);
  3731. }
  3732. return systemClasses[i];
  3733. }
  3734. return null;
  3735. }
  3736. internal void SetSpecialSystemClass (string nsName, string name, Class aClass)
  3737. {
  3738. if (nsName != systemName) return;
  3739. int hash = name.GetHashCode ();
  3740. for (int i = 0; i < specialNames.Length; i++) {
  3741. if (hash != specialNames [i])
  3742. continue;
  3743. if (systemClasses [i] == null) {
  3744. systemClasses [i] = aClass;
  3745. }
  3746. }
  3747. }
  3748. internal Class GetSpecialSystemClass(PrimitiveType pType)
  3749. {
  3750. int ix = pType.GetSystemTypeIx();
  3751. if (systemClasses[ix] == null && !PEFile.IsMSCorlib) {
  3752. systemClasses[ix] = new SystemClass(pType,this,metaData);
  3753. metaData.AddToTable(MDTable.TypeRef,systemClasses[ix]);
  3754. }
  3755. return systemClasses[ix];
  3756. }
  3757. private ClassRef GetValueClass(string name, int hash)
  3758. {
  3759. /* Called by MSCorLib.AddValueClass, which is called by
  3760. !mscorlib, for adding ref to value class INTO mscorlib,
  3761. so this should be classref */
  3762. int ix = valueTypeIx;
  3763. if (hash != specialNames[valueTypeIx]) ix++;
  3764. if (systemClasses[ix] == null) {
  3765. systemClasses[ix] = new ClassRef(systemName,name,metaData);
  3766. ((ClassRef) systemClasses[ix]).SetParent(this);
  3767. ((ClassRef) systemClasses[ix]).MakeValueClass(ValueClass.ValueType);
  3768. metaData.AddToTable(MDTable.TypeRef,systemClasses[ix]);
  3769. }
  3770. return (ClassRef) systemClasses[ix];
  3771. }
  3772. internal Class ValueType()
  3773. {
  3774. if (systemClasses[valueTypeIx] == null && !PEFile.IsMSCorlib) {
  3775. ClassRef valType = new ClassRef("System","ValueType",metaData);
  3776. valType.SetParent(this);
  3777. valType.MakeValueClass(ValueClass.ValueType);
  3778. metaData.AddToTable(MDTable.TypeRef,valType);
  3779. systemClasses[valueTypeIx] = valType;
  3780. }
  3781. return systemClasses[valueTypeIx];
  3782. }
  3783. internal Class EnumType()
  3784. {
  3785. /* Called by both mscorlib & !mscorlib, so can be
  3786. either ClassRef or ClassDef */
  3787. //systemClasses [ valueTypeIx + 1] -> System.Enum
  3788. if (systemClasses[valueTypeIx + 1] == null && !PEFile.IsMSCorlib) {
  3789. ClassRef valType = new ClassRef("System","Enum",metaData);
  3790. valType.SetParent(this);
  3791. valType.MakeValueClass(ValueClass.Enum);
  3792. metaData.AddToTable(MDTable.TypeRef,valType);
  3793. systemClasses[valueTypeIx + 1] = valType;
  3794. }
  3795. return systemClasses[valueTypeIx + 1];
  3796. }
  3797. /// <summary>
  3798. /// Add a value class to this external assembly
  3799. /// </summary>
  3800. /// <param name="nsName">name space name</param>
  3801. /// <param name="name">class name</param>
  3802. /// <returns></returns>
  3803. public override ClassRef AddValueClass(string nsName, string name)
  3804. {
  3805. if (nsName.CompareTo(systemName) == 0) {
  3806. int hash = name.GetHashCode();
  3807. if ((hash == specialNames[valueTypeIx]) ||
  3808. (hash == specialNames[valueTypeIx+1])) {
  3809. return GetValueClass(name,hash);
  3810. }
  3811. }
  3812. ClassRef aClass = new ClassRef(nsName,name,metaData);
  3813. metaData.AddToTable(MDTable.TypeRef,aClass);
  3814. aClass.SetParent(this);
  3815. aClass.MakeValueClass(ValueClass.ValueType);
  3816. return aClass;
  3817. }
  3818. }
  3819. /**************************************************************************/
  3820. /// <summary>
  3821. /// MetaData
  3822. /// Root (20 bytes + UTF-8 Version String + quad align padding)
  3823. /// StreamHeaders (8 bytes + null terminated name string + quad align padding)
  3824. /// Streams
  3825. /// #~ (always present - holds metadata tables)
  3826. /// #Strings (always present - holds identifier strings)
  3827. /// #US (Userstring heap)
  3828. /// #Blob (signature blobs)
  3829. /// #GUID (guids for assemblies or Modules)
  3830. /// </summary>
  3831. public class MetaData {
  3832. internal static readonly int[] CIxShiftMap = {2,2,5,1,2,3,1,1,1,2,3,2,1};
  3833. private static readonly byte StringsHeapMask = 0x1;
  3834. private static readonly byte GUIDHeapMask = 0x2;
  3835. private static readonly byte BlobHeapMask = 0x4;
  3836. private static readonly uint MetaDataSignature = 0x424A5342;
  3837. private static readonly uint maxSmlIxSize = 0xFFFF;
  3838. private static readonly uint max1BitSmlIx = 0x7FFF;
  3839. private static readonly uint max2BitSmlIx = 0x3FFF;
  3840. private static readonly uint max3BitSmlIx = 0x1FFF;
  3841. private static readonly uint max5BitSmlIx = 0x7FF;
  3842. // NOTE: version and stream name strings MUST always be quad padded
  3843. private static readonly string version = "v1.1.4322\0\0\0";
  3844. private static readonly char[] tildeName = {'#','~','\0','\0'};
  3845. private static readonly char[] stringsName = {'#','S','t','r','i','n','g','s','\0','\0','\0','\0'};
  3846. private static readonly char[] usName = {'#','U','S','\0'};
  3847. private static readonly char[] guidName = {'#','G','U','I','D','\0','\0','\0'};
  3848. private static readonly char[] blobName = {'#','B','l','o','b','\0','\0','\0'};
  3849. private static readonly uint MetaDataHeaderSize = 20 + (uint)version.Length;
  3850. private static readonly uint TildeHeaderSize = 24;
  3851. private static readonly uint StreamHeaderSize = 8;
  3852. private static readonly uint numMetaDataTables = (int)MDTable.GenericParamConstraint + 1;
  3853. private static readonly uint tildeHeaderSize = 8 + (uint)tildeName.Length;
  3854. MetaDataStream strings, us, guid, blob;
  3855. MetaDataStream[] streams = new MetaDataStream[5];
  3856. uint numStreams = 5;
  3857. uint tildeTide = 0, tildePadding = 0, tildeStart = 0;
  3858. uint numTables = 0, resourcesSize = 0;
  3859. ArrayList[] metaDataTables = new ArrayList[numMetaDataTables];
  3860. ArrayList byteCodes = new ArrayList();
  3861. uint codeSize = 0, codeStart, byteCodePadding = 0, metaDataSize = 0;
  3862. ulong valid = 0, /*sorted = 0x000002003301FA00;*/ sorted = 0;
  3863. bool[] largeIx = new bool[numMetaDataTables];
  3864. bool[] lgeCIx = new bool[(int)CIx.MaxCIx];
  3865. bool largeStrings = false, largeUS = false, largeGUID = false, largeBlob = false;
  3866. private FileImage file;
  3867. private byte heapSizes = 0;
  3868. MetaDataElement entryPoint;
  3869. BinaryWriter output;
  3870. public MSCorLib mscorlib;
  3871. private TypeSpec[] systemTypeSpecs = new TypeSpec[PrimitiveType.NumSystemTypes];
  3872. long mdStart;
  3873. private ArrayList cattr_list;
  3874. private ArrayList declsec_list;
  3875. ArrayList resources;
  3876. internal MetaData(FileImage file)
  3877. {
  3878. // tilde = new MetaDataStream(tildeName,false,0);
  3879. this.file = file;
  3880. strings = new MetaDataStream(stringsName,new UTF8Encoding(),true);
  3881. us = new MetaDataStream(usName,new UnicodeEncoding(),true);
  3882. guid = new MetaDataStream(guidName,false);
  3883. blob = new MetaDataStream(blobName,true);
  3884. streams[1] = strings;
  3885. streams[2] = us;
  3886. streams[3] = guid;
  3887. streams[4] = blob;
  3888. for (int i=0; i < numMetaDataTables; i++) {
  3889. largeIx[i] = false;
  3890. }
  3891. for (int i=0; i < lgeCIx.Length; i++) {
  3892. lgeCIx[i] = false;
  3893. }
  3894. mscorlib = new MSCorLib(this);
  3895. }
  3896. internal TypeSpec GetPrimitiveTypeSpec(int ix)
  3897. {
  3898. return systemTypeSpecs[ix];
  3899. }
  3900. internal void SetPrimitiveTypeSpec(int ix, TypeSpec typeSpec)
  3901. {
  3902. systemTypeSpecs[ix] = typeSpec;
  3903. }
  3904. internal uint Size()
  3905. {
  3906. return metaDataSize;
  3907. }
  3908. private void CalcHeapSizes ()
  3909. {
  3910. if (strings.LargeIx()) {
  3911. largeStrings = true;
  3912. heapSizes |= StringsHeapMask;
  3913. }
  3914. if (guid.LargeIx()) {
  3915. largeGUID = true;
  3916. heapSizes |= GUIDHeapMask;
  3917. }
  3918. if (blob.LargeIx()) {
  3919. largeBlob = true;
  3920. heapSizes |= BlobHeapMask;
  3921. }
  3922. largeUS = us.LargeIx();
  3923. }
  3924. internal void StreamSize(byte mask)
  3925. {
  3926. heapSizes |= mask;
  3927. }
  3928. internal uint AddToUSHeap(string str)
  3929. {
  3930. if (str == null) return 0;
  3931. return us.Add(str,true);
  3932. }
  3933. internal uint AddToUSHeap(byte[] str)
  3934. {
  3935. if (str == null) return 0;
  3936. return us.Add (str, true);
  3937. }
  3938. internal uint AddToStringsHeap(string str)
  3939. {
  3940. if ((str == null) || (str.CompareTo("") == 0)) return 0;
  3941. return strings.Add(str,false);
  3942. }
  3943. internal uint AddToGUIDHeap(Guid guidNum)
  3944. {
  3945. return guid.Add(guidNum, false);
  3946. }
  3947. internal uint AddToBlobHeap(byte[] blobBytes)
  3948. {
  3949. if (blobBytes == null) return 0;
  3950. return blob.Add(blobBytes, true);
  3951. }
  3952. internal uint AddToBlobHeap(byte val)
  3953. {
  3954. return blob.Add(val, true);
  3955. }
  3956. internal uint AddToBlobHeap(sbyte val)
  3957. {
  3958. return blob.Add(val, true);
  3959. }
  3960. internal uint AddToBlobHeap(ushort val)
  3961. {
  3962. return blob.Add(val, true);
  3963. }
  3964. internal uint AddToBlobHeap(short val)
  3965. {
  3966. return blob.Add(val, true);
  3967. }
  3968. internal uint AddToBlobHeap(uint val)
  3969. {
  3970. return blob.Add(val, true);
  3971. }
  3972. internal uint AddToBlobHeap(int val)
  3973. {
  3974. return blob.Add(val, true);
  3975. }
  3976. internal uint AddToBlobHeap(ulong val)
  3977. {
  3978. return blob.Add(val, true);
  3979. }
  3980. internal uint AddToBlobHeap(long val)
  3981. {
  3982. return blob.Add(val, true);
  3983. }
  3984. internal uint AddToBlobHeap(float val)
  3985. {
  3986. return blob.Add(val, true);
  3987. }
  3988. internal uint AddToBlobHeap(double val)
  3989. {
  3990. return blob.Add(val, true);
  3991. }
  3992. internal uint AddToBlobHeap(string val)
  3993. {
  3994. return blob.Add(val,true);
  3995. }
  3996. internal void AddCustomAttribute (CustomAttribute cattr)
  3997. {
  3998. if (cattr_list == null)
  3999. cattr_list = new ArrayList ();
  4000. cattr_list.Add (cattr);
  4001. }
  4002. internal void AddDeclSecurity (DeclSecurity decl_sec)
  4003. {
  4004. if (declsec_list == null)
  4005. declsec_list = new ArrayList ();
  4006. declsec_list.Add (decl_sec);
  4007. }
  4008. private ArrayList GetTable(MDTable tableIx)
  4009. {
  4010. int tabIx = (int)tableIx;
  4011. if (metaDataTables[tabIx] == null) {
  4012. metaDataTables[tabIx] = new ArrayList();
  4013. valid |= ((ulong)0x1 << tabIx);
  4014. // Console.WriteLine("after creating table " + tableIx + "(" + tabIx + ") valid = " + valid);
  4015. numTables++;
  4016. }
  4017. return metaDataTables[tabIx];
  4018. }
  4019. internal void AddToTable(MDTable tableIx, MetaDataElement elem)
  4020. {
  4021. if (elem.Row > 0) {
  4022. // Console.Out.WriteLine("ERROR - element already in table " + tableIx);
  4023. return;
  4024. }
  4025. // updates Row field of the element
  4026. // Console.WriteLine("Adding element to table " + (uint)tableIx);
  4027. ArrayList table = GetTable(tableIx);
  4028. elem.Row = (uint)table.Count + 1;
  4029. table.Add(elem);
  4030. }
  4031. internal uint TableIndex(MDTable tableIx)
  4032. {
  4033. if (metaDataTables[(int)tableIx] == null) return 1;
  4034. return (uint)metaDataTables[(int)tableIx].Count+1;
  4035. }
  4036. internal uint AddCode(CILInstructions byteCode)
  4037. {
  4038. byteCodes.Add(byteCode);
  4039. uint offset = codeSize + codeStart;
  4040. codeSize += byteCode.GetCodeSize();
  4041. return offset;
  4042. }
  4043. internal void SetEntryPoint(MetaDataElement ep)
  4044. {
  4045. entryPoint = ep;
  4046. }
  4047. internal uint AddResource(byte[] resBytes)
  4048. {
  4049. if (resources == null) resources = new ArrayList ();
  4050. resources.Add (resBytes);
  4051. uint offset = resourcesSize;
  4052. resourcesSize += (uint)resBytes.Length + 4;
  4053. return offset;
  4054. }
  4055. internal void AddData(DataConstant cVal)
  4056. {
  4057. file.AddInitData(cVal);
  4058. }
  4059. internal static void CompressNum(uint val, MemoryStream sig)
  4060. {
  4061. if (val < 0x7F) {
  4062. sig.WriteByte((byte)val);
  4063. } else if (val < 0x3FFF) {
  4064. byte b1 = (byte)((val >> 8) | 0x80);
  4065. byte b2 = (byte)(val & FileImage.iByteMask[0]);
  4066. sig.WriteByte(b1);
  4067. sig.WriteByte(b2);
  4068. } else {
  4069. byte b1 = (byte)((val >> 24) | 0xC0);
  4070. byte b2 = (byte)((val & FileImage.iByteMask[2]) >> 16);
  4071. byte b3 = (byte)((val & FileImage.iByteMask[1]) >> 8);;
  4072. byte b4 = (byte)(val & FileImage.iByteMask[0]);
  4073. sig.WriteByte(b1);
  4074. sig.WriteByte(b2);
  4075. sig.WriteByte(b3);
  4076. sig.WriteByte(b4);
  4077. }
  4078. }
  4079. internal uint CodeSize()
  4080. {
  4081. return codeSize + byteCodePadding;
  4082. }
  4083. internal uint GetResourcesSize()
  4084. {
  4085. return resourcesSize;
  4086. }
  4087. internal uint StringsIndexSize()
  4088. {
  4089. if (largeStrings) return 4;
  4090. return 2;
  4091. }
  4092. internal uint GUIDIndexSize()
  4093. {
  4094. if (largeGUID) return 4;
  4095. return 2;
  4096. }
  4097. internal uint USIndexSize()
  4098. {
  4099. if (largeUS) return 4;
  4100. return 2;
  4101. }
  4102. internal uint BlobIndexSize()
  4103. {
  4104. if (largeBlob) return 4;
  4105. return 2;
  4106. }
  4107. internal uint CodedIndexSize(CIx code)
  4108. {
  4109. if (lgeCIx[(uint)code]) return 4;
  4110. return 2;
  4111. }
  4112. internal uint TableIndexSize(MDTable tabIx)
  4113. {
  4114. if (largeIx[(uint)tabIx]) return 4;
  4115. return 2;
  4116. }
  4117. private void SetIndexSizes()
  4118. {
  4119. for (int i=0; i < numMetaDataTables; i++) {
  4120. if (metaDataTables[i] == null)
  4121. continue;
  4122. uint count = (uint)metaDataTables[i].Count;
  4123. if (count > maxSmlIxSize)
  4124. largeIx[i] = true;
  4125. MDTable tabIx = (MDTable)i;
  4126. if (count > max5BitSmlIx) {
  4127. lgeCIx[(int)CIx.HasCustomAttr] = true;
  4128. }
  4129. if (count > max3BitSmlIx) {
  4130. if ((tabIx == MDTable.TypeRef) || (tabIx == MDTable.ModuleRef) || (tabIx == MDTable.Method) || (tabIx == MDTable.TypeSpec) || (tabIx == MDTable.Field))
  4131. lgeCIx[(int)CIx.CustomAttributeType] = true;
  4132. if ((tabIx == MDTable.Method) || (tabIx == MDTable.MemberRef))
  4133. lgeCIx[(int)CIx.MemberRefParent] = true;
  4134. }
  4135. if (count > max2BitSmlIx) {
  4136. if ((tabIx == MDTable.Field) || (tabIx == MDTable.Param) || (tabIx == MDTable.Property))
  4137. lgeCIx[(int)CIx.HasConst] = true;
  4138. if ((tabIx == MDTable.TypeDef) || (tabIx == MDTable.TypeRef) || (tabIx == MDTable.TypeSpec))
  4139. lgeCIx[(int)CIx.TypeDefOrRef] = true;
  4140. if ((tabIx == MDTable.TypeDef) || (tabIx == MDTable.Method) || (tabIx == MDTable.Assembly))
  4141. lgeCIx[(int)CIx.HasDeclSecurity] = true;
  4142. if ((tabIx == MDTable.File) || (tabIx == MDTable.AssemblyRef) || (tabIx == MDTable.ExportedType))
  4143. lgeCIx[(int)CIx.Implementation] = true;
  4144. if ((tabIx == MDTable.Module) || (tabIx == MDTable.ModuleRef) || (tabIx == MDTable.AssemblyRef) || (tabIx == MDTable.TypeRef))
  4145. lgeCIx[(int)CIx.ResolutionScope] = true;
  4146. }
  4147. if (count > max1BitSmlIx) {
  4148. if ((tabIx == MDTable.Field) || (tabIx == MDTable.Param))
  4149. lgeCIx[(int)CIx.HasFieldMarshal] = true;
  4150. if ((tabIx == MDTable.Event) || (tabIx == MDTable.Property))
  4151. lgeCIx[(int)CIx.HasSemantics] = true;
  4152. if ((tabIx == MDTable.Method) || (tabIx == MDTable.MemberRef))
  4153. lgeCIx[(int)CIx.MethodDefOrRef] = true;
  4154. if ((tabIx == MDTable.Field) || (tabIx == MDTable.Method))
  4155. lgeCIx[(int)CIx.MemberForwarded] = true;
  4156. if ((tabIx == MDTable.TypeDef) || (tabIx == MDTable.Method))
  4157. lgeCIx[(int)CIx.TypeOrMethodDef] = true;
  4158. }
  4159. }
  4160. }
  4161. private void SetStreamOffsets()
  4162. {
  4163. uint sizeOfHeaders = StreamHeaderSize + (uint)tildeName.Length;
  4164. for (int i=1; i < numStreams; i++) {
  4165. sizeOfHeaders += streams[i].headerSize();
  4166. }
  4167. metaDataSize = MetaDataHeaderSize + sizeOfHeaders;
  4168. tildeStart = metaDataSize;
  4169. metaDataSize += tildeTide + tildePadding;
  4170. for (int i=1; i < numStreams; i++) {
  4171. streams[i].Start = metaDataSize;
  4172. metaDataSize += streams[i].Size();
  4173. streams[i].WriteDetails();
  4174. }
  4175. }
  4176. internal void CalcTildeStreamSize()
  4177. {
  4178. CalcHeapSizes ();
  4179. //tilde.SetIndexSizes(strings.LargeIx(),us.LargeIx(),guid.LargeIx(),blob.LargeIx());
  4180. tildeTide = TildeHeaderSize;
  4181. tildeTide += 4 * numTables;
  4182. //Console.WriteLine("Tilde header + sizes = " + tildeTide);
  4183. for (int i=0; i < numMetaDataTables; i++) {
  4184. if (metaDataTables[i] != null) {
  4185. ArrayList table = metaDataTables[i];
  4186. // Console.WriteLine("Meta data table " + i + " at offset " + tildeTide);
  4187. tildeTide += (uint)table.Count * ((MetaDataElement)table[0]).Size(this);
  4188. // Console.WriteLine("Metadata table " + i + " has size " + table.Count);
  4189. // Console.WriteLine("tildeTide = " + tildeTide);
  4190. }
  4191. }
  4192. if ((tildeTide % 4) != 0) tildePadding = 4 - (tildeTide % 4);
  4193. //Console.WriteLine("tildePadding = " + tildePadding);
  4194. }
  4195. internal void WriteTildeStream(FileImage output)
  4196. {
  4197. long startTilde = output.Seek(0,SeekOrigin.Current);
  4198. output.Write((uint)0); // Reserved
  4199. output.Write((byte)1); // MajorVersion
  4200. output.Write((byte)0); // MinorVersion
  4201. output.Write(heapSizes);
  4202. output.Write((byte)1); // Reserved
  4203. output.Write(valid);
  4204. output.Write(sorted);
  4205. for (int i=0; i < numMetaDataTables; i++) {
  4206. if (metaDataTables[i] != null) {
  4207. uint count = (uint)metaDataTables[i].Count;
  4208. output.Write(count);
  4209. }
  4210. }
  4211. long tabStart = output.Seek(0,SeekOrigin.Current);
  4212. // Console.WriteLine("Starting metaData tables at " + tabStart);
  4213. for (int i=0; i < numMetaDataTables; i++) {
  4214. if (metaDataTables[i] != null) {
  4215. // Console.WriteLine("Starting metaData table " + i + " at " + (output.Seek(0,SeekOrigin.Current) - startTilde));
  4216. ArrayList table = metaDataTables[i];
  4217. for (int j=0; j < table.Count; j++) {
  4218. ((MetaDataElement)table[j]).Write(output);
  4219. }
  4220. }
  4221. }
  4222. // Console.WriteLine("Writing padding at " + output.Seek(0,SeekOrigin.Current));
  4223. for (int i=0; i < tildePadding; i++) output.Write((byte)0);
  4224. }
  4225. private void BuildTable(ArrayList table)
  4226. {
  4227. if (table == null) return;
  4228. for (int j=0; j < table.Count; j++) {
  4229. ((MetaDataElement)table[j]).BuildTables(this);
  4230. }
  4231. }
  4232. private void SortTable (ArrayList mTable)
  4233. {
  4234. if (mTable == null) return;
  4235. mTable.Sort();
  4236. for (int i=0; i < mTable.Count; i++) {
  4237. ((MetaDataElement)mTable[i]).Row = (uint)i+1;
  4238. }
  4239. }
  4240. internal void BuildMetaData(uint codeStartOffset)
  4241. {
  4242. codeStart = codeStartOffset;
  4243. BuildTable(metaDataTables[(int)MDTable.TypeDef]);
  4244. BuildTable(metaDataTables[(int)MDTable.MemberRef]);
  4245. BuildTable(metaDataTables[(int)MDTable.GenericParam]);
  4246. BuildTable(metaDataTables[(int)MDTable.MethodSpec]);
  4247. BuildTable(metaDataTables[(int)MDTable.GenericParamConstraint]);
  4248. BuildTable(metaDataTables[(int)MDTable.ManifestResource]);
  4249. if (cattr_list != null) {
  4250. foreach (CustomAttribute cattr in cattr_list)
  4251. cattr.BuildTables (this);
  4252. }
  4253. if (declsec_list != null) {
  4254. foreach (DeclSecurity decl_sec in declsec_list)
  4255. decl_sec.BuildTables (this);
  4256. }
  4257. /* for (int i=0; i < metaDataTables.Length; i++) {
  4258. ArrayList table = metaDataTables[i];
  4259. if (table != null) {
  4260. for (int j=0; j < table.Count; j++) {
  4261. ((MetaDataElement)table[j]).BuildTables(this);
  4262. }
  4263. }
  4264. }
  4265. */
  4266. SetIndexSizes();
  4267. for (int i=1; i < numStreams; i++) {
  4268. streams[i].EndStream();
  4269. }
  4270. CalcTildeStreamSize();
  4271. SetStreamOffsets();
  4272. byteCodePadding = NumToAlign(codeSize,4);
  4273. if (entryPoint != null) file.SetEntryPoint(entryPoint.Token());
  4274. // Check ordering of specific tables
  4275. // Constant, CustomAttribute, FieldMarshal, DeclSecurity, MethodSemantics
  4276. // ImplMap, GenericParam
  4277. // Need to load GenericParamConstraint AFTER GenericParam table in correct order
  4278. // The tables:
  4279. // InterfaceImpl, ClassLayout, FieldLayout, MethodImpl, FieldRVA, NestedClass
  4280. // will _ALWAYS_ be in the correct order as embedded in BuildMDTables
  4281. SortTable(metaDataTables[(int)MDTable.Constant]);
  4282. SortTable(metaDataTables[(int)MDTable.CustomAttribute]);
  4283. SortTable(metaDataTables[(int)MDTable.FieldMarshal]);
  4284. SortTable(metaDataTables[(int)MDTable.DeclSecurity]);
  4285. SortTable(metaDataTables[(int)MDTable.MethodSemantics]);
  4286. SortTable(metaDataTables[(int)MDTable.ImplMap]);
  4287. if (metaDataTables[(int)MDTable.GenericParam] != null) {
  4288. SortTable(metaDataTables[(int)MDTable.GenericParam]);
  4289. // Now add GenericParamConstraints
  4290. /*for (int i=0; i < metaDataTables[(int)MDTable.GenericParam].Count; i++) {
  4291. ((GenericParameter)metaDataTables[(int)MDTable.GenericParam][i]).AddConstraints(this);
  4292. }*/
  4293. }
  4294. SortTable(metaDataTables[(int)MDTable.GenericParamConstraint]);
  4295. SortTable(metaDataTables[(int)MDTable.InterfaceImpl]);
  4296. }
  4297. internal void WriteByteCodes(FileImage output)
  4298. {
  4299. for (int i=0; i < byteCodes.Count; i++) {
  4300. ((CILInstructions)byteCodes[i]).Write(output);
  4301. }
  4302. for (int i=0; i < byteCodePadding; i++) {
  4303. output.Write((byte)0);
  4304. }
  4305. }
  4306. internal void WriteResources (FileImage output)
  4307. {
  4308. if (resources == null) return;
  4309. for (int i = 0; i < resources.Count; i ++) {
  4310. byte [] resBytes = (byte []) resources [i];
  4311. output.Write ((uint) resBytes.Length);
  4312. output.Write (resBytes);
  4313. }
  4314. }
  4315. internal void WriteMetaData(FileImage output)
  4316. {
  4317. this.output = output;
  4318. mdStart = output.Seek(0,SeekOrigin.Current);
  4319. // Console.WriteLine("Writing metaData at " + Hex.Long(mdStart));
  4320. output.Write(MetaDataSignature);
  4321. output.Write((short)1); // Major Version
  4322. output.Write((short)1); // Minor Version ECMA = 0, PEFiles = 1
  4323. output.Write(0); // Reserved
  4324. output.Write(version.Length);
  4325. output.Write(version.ToCharArray()); // version string is already zero padded
  4326. output.Write((short)0);
  4327. output.Write((ushort)numStreams);
  4328. // write tilde header
  4329. output.Write(tildeStart);
  4330. output.Write(tildeTide + tildePadding);
  4331. output.Write(tildeName);
  4332. for (int i=1; i < numStreams; i++) streams[i].WriteHeader(output);
  4333. // Console.WriteLine("Writing tilde stream at " + output.Seek(0,SeekOrigin.Current) + " = " + tildeStart);
  4334. WriteTildeStream(output);
  4335. for (int i=1; i < numStreams; i++) streams[i].Write(output);
  4336. // Console.WriteLine("Finished Writing metaData at " + output.Seek(0,SeekOrigin.Current));
  4337. }
  4338. internal bool LargeStringsIndex() { return strings.LargeIx(); }
  4339. internal bool LargeGUIDIndex() { return guid.LargeIx(); }
  4340. internal bool LargeUSIndex() { return us.LargeIx(); }
  4341. internal bool LargeBlobIndex() { return blob.LargeIx(); }
  4342. internal bool LargeIx(MDTable tabIx) { return largeIx[(uint)tabIx]; }
  4343. private uint NumToAlign(uint val, uint alignVal)
  4344. {
  4345. if ((val % alignVal) == 0) return 0;
  4346. return alignVal - (val % alignVal);
  4347. }
  4348. internal void WriteCodedIndex(CIx code, MetaDataElement elem, FileImage output)
  4349. {
  4350. uint ix = 0;
  4351. if (elem != null) {
  4352. ix = (elem.Row << CIxShiftMap[(uint)code]) | elem.GetCodedIx(code);
  4353. // Console.WriteLine("coded index = " + ix + " row = " + elem.Row);
  4354. //} else {
  4355. // Console.WriteLine("elem for coded index is null");
  4356. }
  4357. if (lgeCIx[(uint)code])
  4358. output.Write(ix);
  4359. else
  4360. output.Write((ushort)ix);
  4361. }
  4362. }
  4363. /**************************************************************************/
  4364. /// <summary>
  4365. /// Stream in the Meta Data (#Strings, #US, #Blob and #GUID)
  4366. /// </summary>
  4367. internal class MetaDataStream : BinaryWriter {
  4368. private static readonly uint StreamHeaderSize = 8;
  4369. private static uint maxSmlIxSize = 0xFFFF;
  4370. private uint start = 0;
  4371. uint size = 0, tide = 1;
  4372. bool largeIx = false;
  4373. uint sizeOfHeader;
  4374. char[] name;
  4375. Hashtable htable = new Hashtable();
  4376. Hashtable btable = new Hashtable (new ByteArrayHashCodeProvider (), new ByteArrayComparer ());
  4377. internal MetaDataStream(char[] name, bool addInitByte) : base(new MemoryStream())
  4378. {
  4379. if (addInitByte) { Write((byte)0); size = 1; }
  4380. this.name = name;
  4381. sizeOfHeader = StreamHeaderSize + (uint)name.Length;
  4382. }
  4383. internal MetaDataStream(char[] name, System.Text.Encoding enc, bool addInitByte) : base(new MemoryStream(),enc)
  4384. {
  4385. if (addInitByte) { Write((byte)0); size = 1; }
  4386. this.name = name;
  4387. sizeOfHeader = StreamHeaderSize + (uint)name.Length;
  4388. }
  4389. public uint Start {
  4390. get { return start; }
  4391. set { start = value; }
  4392. }
  4393. internal uint headerSize()
  4394. {
  4395. // Console.WriteLine(name + " stream has headersize of " + sizeOfHeader);
  4396. return sizeOfHeader;
  4397. }
  4398. internal void SetSize(uint siz)
  4399. {
  4400. size = siz;
  4401. }
  4402. internal uint Size()
  4403. {
  4404. return size;
  4405. }
  4406. internal bool LargeIx()
  4407. {
  4408. return largeIx;
  4409. }
  4410. internal void WriteDetails()
  4411. {
  4412. // Console.WriteLine(name + " - size = " + size);
  4413. }
  4414. internal uint Add(string str, bool prependSize)
  4415. {
  4416. Object val = htable[str];
  4417. uint index = 0;
  4418. if (val == null) {
  4419. index = size;
  4420. htable[str] = index;
  4421. char[] arr = str.ToCharArray();
  4422. if (prependSize) CompressNum((uint)arr.Length*2+1);
  4423. Write(arr);
  4424. Write((byte)0);
  4425. size = (uint)Seek(0,SeekOrigin.Current);
  4426. } else {
  4427. index = (uint)val;
  4428. }
  4429. return index;
  4430. }
  4431. internal uint Add (byte[] str, bool prependSize)
  4432. {
  4433. Object val = btable [str];
  4434. uint index = 0;
  4435. if (val == null) {
  4436. index = size;
  4437. btable [str] = index;
  4438. if (prependSize) CompressNum ((uint) str.Length);
  4439. Write (str);
  4440. size = (uint) Seek (0, SeekOrigin.Current);
  4441. } else {
  4442. index = (uint) val;
  4443. }
  4444. return index;
  4445. }
  4446. internal uint Add(Guid guid, bool prependSize)
  4447. {
  4448. byte [] b = guid.ToByteArray ();
  4449. if (prependSize) CompressNum ((uint) b.Length);
  4450. Write(guid.ToByteArray());
  4451. size =(uint)Seek(0,SeekOrigin.Current);
  4452. return tide++;
  4453. }
  4454. internal uint Add(byte[] blob)
  4455. {
  4456. uint ix = size;
  4457. CompressNum((uint)blob.Length);
  4458. Write(blob);
  4459. size = (uint)Seek(0,SeekOrigin.Current);
  4460. return ix;
  4461. }
  4462. internal uint Add(byte val, bool prependSize)
  4463. {
  4464. uint ix = size;
  4465. if (prependSize) CompressNum (1);
  4466. Write(val);
  4467. size = (uint)Seek(0,SeekOrigin.Current);
  4468. return ix;
  4469. }
  4470. internal uint Add(sbyte val, bool prependSize)
  4471. {
  4472. uint ix = size;
  4473. if (prependSize) CompressNum (1);
  4474. Write(val);
  4475. size = (uint)Seek(0,SeekOrigin.Current);
  4476. return ix;
  4477. }
  4478. internal uint Add(ushort val, bool prependSize)
  4479. {
  4480. uint ix = size;
  4481. if (prependSize) CompressNum (2);
  4482. Write(val);
  4483. size = (uint)Seek(0,SeekOrigin.Current);
  4484. return ix;
  4485. }
  4486. internal uint Add(short val, bool prependSize)
  4487. {
  4488. uint ix = size;
  4489. if (prependSize) CompressNum (2);
  4490. Write(val);
  4491. size = (uint)Seek(0,SeekOrigin.Current);
  4492. return ix;
  4493. }
  4494. internal uint Add(uint val, bool prependSize)
  4495. {
  4496. uint ix = size;
  4497. if (prependSize) CompressNum (4);
  4498. Write(val);
  4499. size = (uint)Seek(0,SeekOrigin.Current);
  4500. return ix;
  4501. }
  4502. internal uint Add(int val, bool prependSize)
  4503. {
  4504. uint ix = size;
  4505. if (prependSize) CompressNum (4);
  4506. Write (val);
  4507. size = (uint)Seek(0,SeekOrigin.Current);
  4508. return ix;
  4509. }
  4510. internal uint Add(ulong val, bool prependSize)
  4511. {
  4512. uint ix = size;
  4513. if (prependSize) CompressNum (8);
  4514. Write(val);
  4515. size = (uint)Seek(0,SeekOrigin.Current);
  4516. return ix;
  4517. }
  4518. internal uint Add(long val, bool prependSize)
  4519. {
  4520. uint ix = size;
  4521. if (prependSize) CompressNum (8);
  4522. Write(val);
  4523. size = (uint)Seek(0,SeekOrigin.Current);
  4524. return ix;
  4525. }
  4526. internal uint Add(float val, bool prependSize)
  4527. {
  4528. uint ix = size;
  4529. if (prependSize) CompressNum (4);
  4530. Write(val);
  4531. size = (uint)Seek(0,SeekOrigin.Current);
  4532. return ix;
  4533. }
  4534. internal uint Add(double val, bool prependSize)
  4535. {
  4536. uint ix = size;
  4537. if (prependSize) CompressNum (8);
  4538. Write(val);
  4539. size = (uint)Seek(0,SeekOrigin.Current);
  4540. return ix;
  4541. }
  4542. private void CompressNum(uint val)
  4543. {
  4544. if (val < 0x7F) {
  4545. Write((byte)val);
  4546. } else if (val < 0x3FFF) {
  4547. byte b1 = (byte)((val >> 8) | 0x80);
  4548. byte b2 = (byte)(val & FileImage.iByteMask[0]);
  4549. Write(b1);
  4550. Write(b2);
  4551. } else {
  4552. byte b1 = (byte)((val >> 24) | 0xC0);
  4553. byte b2 = (byte)((val & FileImage.iByteMask[2]) >> 16);
  4554. byte b3 = (byte)((val & FileImage.iByteMask[1]) >> 8);;
  4555. byte b4 = (byte)(val & FileImage.iByteMask[0]);
  4556. Write(b1);
  4557. Write(b2);
  4558. Write(b3);
  4559. Write(b4);
  4560. }
  4561. }
  4562. private void QuadAlign()
  4563. {
  4564. if ((size % 4) != 0) {
  4565. uint pad = 4 - (size % 4);
  4566. size += pad;
  4567. for (int i=0; i < pad; i++) {
  4568. Write((byte)0);
  4569. }
  4570. }
  4571. }
  4572. internal void EndStream()
  4573. {
  4574. QuadAlign();
  4575. if (size > maxSmlIxSize) {
  4576. largeIx = true;
  4577. }
  4578. }
  4579. internal void WriteHeader(BinaryWriter output)
  4580. {
  4581. output.Write(start);
  4582. output.Write(size);
  4583. output.Write(name);
  4584. }
  4585. internal virtual void Write(BinaryWriter output)
  4586. {
  4587. // Console.WriteLine("Writing " + name + " stream at " + output.Seek(0,SeekOrigin.Current) + " = " + start);
  4588. MemoryStream str = (MemoryStream)BaseStream;
  4589. output.Write(str.ToArray());
  4590. }
  4591. }
  4592. /**************************************************************************/
  4593. class ByteArrayComparer : IComparer {
  4594. public int Compare (object x, object y)
  4595. {
  4596. byte [] a = (byte []) x;
  4597. byte [] b = (byte []) y;
  4598. int len = a.Length;
  4599. if (b.Length != len)
  4600. return 1;
  4601. for (int i = 0; i < len; ++i)
  4602. if (a [i] != b [i])
  4603. return 1;
  4604. return 0;
  4605. }
  4606. }
  4607. class ByteArrayHashCodeProvider : IHashCodeProvider {
  4608. public int GetHashCode (Object key)
  4609. {
  4610. byte [] arr = (byte []) key;
  4611. int len = arr.Length;
  4612. int h = 0;
  4613. for (int i = 0; i < len; ++i)
  4614. h = (h << 5) - h + arr [i];
  4615. return h;
  4616. }
  4617. }
  4618. }