prog.tex 254 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920
  1. %
  2. % $Id$
  3. % This file is part of the FPC documentation.
  4. % Copyright (C) 1997, by Michael Van Canneyt
  5. %
  6. % The FPC documentation is free text; you can redistribute it and/or
  7. % modify it under the terms of the GNU Library General Public License as
  8. % published by the Free Software Foundation; either version 2 of the
  9. % License, or (at your option) any later version.
  10. %
  11. % The FPC Documentation is distributed in the hope that it will be useful,
  12. % but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. % Library General Public License for more details.
  15. %
  16. % You should have received a copy of the GNU Library General Public
  17. % License along with the FPC documentation; see the file COPYING.LIB. If not,
  18. % write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  19. % Boston, MA 02111-1307, USA.
  20. %
  21. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  22. % Preamble.
  23. \input{preamble.inc}
  24. \begin{latexonly}
  25. \ifpdf
  26. \pdfinfo{/Author(Michael Van Canneyt)
  27. /Title(Programmers' Guide)
  28. /Subject(Free Pascal Programmers' guide)
  29. /Keywords(Free Pascal)
  30. }
  31. \fi
  32. \end{latexonly}
  33. %
  34. % Settings
  35. %
  36. \makeindex
  37. \FPCexampledir{progex}
  38. %
  39. % Start of document.
  40. %
  41. \begin{document}
  42. \title{Free Pascal \\ Programmers' manual}
  43. \docdescription{Programmers' manual for \fpc, version \fpcversion}
  44. \docversion{1.9}
  45. \input{date.inc}
  46. \author{Micha\"el Van Canneyt}
  47. \maketitle
  48. \tableofcontents
  49. \newpage
  50. \listoftables
  51. \newpage
  52. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  53. % Introduction
  54. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  55. \section{About this document}
  56. This is the programmer's manual for \fpc.
  57. It describes some of the peculiarities of the \fpc compiler, and provides a
  58. glimpse of how the compiler generates its code, and how you can change the
  59. generated code. It will not, however, provide a detailed account of
  60. the inner workings of the compiler, nor will it describe how to use the
  61. compiler (described in the \userref). It also will not describe the inner
  62. workings of the Run-Time Library (RTL). The best way to learn about the way
  63. the RTL is implemented is from the sources themselves.
  64. The things described here are useful when things need to be done that
  65. require greater flexibility than the standard Pascal language constructs
  66. (described in the \refref).
  67. Since the compiler is continuously under development, this document may get
  68. out of date. Wherever possible, the information in this manual will be
  69. updated. If you find something which isn't correct, or you think something
  70. is missing, feel free to contact me\footnote{at
  71. \var{[email protected]}}.
  72. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  73. % Compiler switches
  74. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  75. \chapter{Compiler directives}
  76. \label{ch:CompSwitch}
  77. \fpc supports compiler directives in the source file. They are not the same
  78. as Turbo Pascal directives, although some are supported for compatibility.
  79. There is a distinction between local and global directives; local directives
  80. take effect from the moment they are encountered, global directives have an
  81. effect on all of the compiled code.
  82. Many switches have a long form also. If they do, then the name of the
  83. long form is given also. For long switches, the + or - character to switch
  84. the option on or off, may be replaced by \var{ON} or \var{OFF} keywords.
  85. Thus \verb|{$I+}| is equivalent to \verb|{$IOCHECKS ON}| or
  86. \verb|{$IOCHECKS +}| and
  87. \verb|{$C-}| is equivalent to \verb|{$ASSERTIONS OFF}| or
  88. \verb|{$ASSERTIONS -}|
  89. The long forms of the switches are the same as their Delphi
  90. counterparts.
  91. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  92. % Local switches
  93. \section{Local directives}
  94. \label{se:LocalSwitch}
  95. Local directives can occur more than once in a unit or program,
  96. If they have a command-line counterpart, the command-line argument is
  97. restored as the default for each compiled file. The local directives
  98. influence the compiler's behaviour from the moment they're encountered
  99. until the moment another switch annihilates their behaviour, or the end
  100. of the current unit or program is reached.
  101. \subsection{\var{\protect\$A} or \var{\protect\$ALIGN} : Align Data}
  102. This switch is recognized for Turbo Pascal Compatibility, but is not
  103. yet implemented. The alignment of data will be different in any case.
  104. \subsection{\var{\protect\$ASMMODE} : Assembler mode (Intel 80x86 only)}
  105. \label{se:AsmReader}
  106. The \var{\{\$ASMMODE XXX\}} directive informs the compiler what kind of assembler
  107. it can expect in an \var{asm} block. The \var{XXX} should be replaced by one
  108. of the following:
  109. \begin{description}
  110. \item [att\ ] Indicates that \var{asm} blocks contain AT\&T syntax assembler.
  111. \item [intel\ ] Indicates that \var{asm} blocks contain Intel syntax
  112. assembler.
  113. \item [direct\ ] Tells the compiler that asm blocks should be copied
  114. directly to the assembler file.
  115. \end{description}
  116. These switches are local, and retain their value to the end of the unit that
  117. is compiled, unless they are replaced by another directive of the same type.
  118. The command-line switch that corresponds to this switch is \var{-R}.
  119. The default assembler reader is the AT\&T reader.
  120. \subsection{\var{\protect\$B} or \var{\protect\$BOOLEVAL} : Complete boolean evaluation}
  121. This switch is understood by the \fpc compiler, but is ignored. The compiler
  122. always uses shortcut evaluation, i.e. the evaluation of a boolean expression
  123. is stopped once the result of the total exression is known with certainty.
  124. So, in the following example, the function \var{Bofu}, which has a boolean
  125. result, will never get called.
  126. \begin{verbatim}
  127. If False and Bofu then
  128. ...
  129. \end{verbatim}
  130. This has as a consequence that any additional actions that are done by
  131. \var{Bofu} are not executed.
  132. \subsection{\var{\protect\$C} or \var{\protect\$ASSERTIONS} : Assertion support}
  133. The \var{\{\$ASSERTIONS\}} switch determines if assert statements are
  134. compiled into the binary or not. If the switch is on, the statement
  135. \begin{verbatim}
  136. Assert(BooleanExpression,AssertMessage);
  137. \end{verbatim}
  138. Will be compiled in the binary. If te \var{BooleanExpression} evaluates to
  139. \var{False}, the RTL will check if the \var{AssertErrorProc} is set. If it
  140. is set, it will be called with as parameters the \var{AssertMessage}
  141. message, the name of the file, the LineNumber and the address. If it is not
  142. set, a runtime error 227 is generated.
  143. The \var{AssertErrorProc} is defined as
  144. \begin{verbatim}
  145. Type
  146. TAssertErrorProc=procedure(const msg,fname:string;lineno,erroraddr:longint);
  147. Var
  148. AssertErrorProc = TAssertErrorProc;
  149. \end{verbatim}
  150. This can be used mainly for debugging purposes. The \file{system} unit sets the
  151. \var{AssertErrorProc} to a handler that displays a message on \var{stderr}
  152. and simply exits. The \file{sysutils} unit catches the run-time error 227
  153. and raises an \var{EAssertionFailed} exception.
  154. \subsection{\var{\protect\$DEFINE} : Define a symbol}
  155. The directive
  156. \begin{verbatim}
  157. {$DEFINE name}
  158. \end{verbatim}
  159. defines the symbol \var{name}. This symbol remains defined until the end of
  160. the current module (i.e. unit or program), or until a \var{\$UNDEF name} directive is encountered.
  161. If \var{name} is already defined, this has no effect. \var{Name} is case
  162. insensitive.
  163. The symbols that are defined in a unit, are not saved in the unit file,
  164. so they are also not exported from a unit.
  165. \subsection{\var{\protect\$ELSE} : Switch conditional compilation}
  166. The \var{\{\$ELSE\}} switches between compiling and ignoring the source
  167. text delimited by the preceding \var{\{\$IFxxx\}} and following
  168. \var{\{\$ENDIF\}}. Any text after the \var{ELSE} keyword but before the
  169. brace is ignored:
  170. \begin{verbatim}
  171. {$ELSE some ignored text}
  172. \end{verbatim}
  173. is the same as
  174. \begin{verbatim}
  175. {$ELSE}
  176. \end{verbatim}
  177. This is useful for indication what switch is meant.
  178. \subsection{\var{\protect\$ENDIF} : End conditional compilation}
  179. The \var{\{\$ENDIF\}} directive ends the conditional compilation initiated by the
  180. last \var{\{\$IFxxx\}} directive. Any text after the \var{ENDIF} keyword but
  181. before the closing brace is ignored:
  182. \begin{verbatim}
  183. {$ENDIF some ignored text}
  184. \end{verbatim}
  185. is the same as
  186. \begin{verbatim}
  187. {$ENDIF}
  188. \end{verbatim}
  189. This is useful for indication what switch is meant to be ended.
  190. \subsection{\var{\protect\$ERROR} : Generate error message}
  191. The following code
  192. \begin{verbatim}
  193. {$ERROR This code is erroneous !}
  194. \end{verbatim}
  195. will display an error message when the compiler encounters it,
  196. and increase the error count of the compiler.
  197. The compiler will continue to compile, but no code will be emitted.
  198. \subsection{\var{\protect\$F} : Far or near functions}
  199. This directive is recognized for compatibility with Turbo Pascal. Under the
  200. 32-bit and 64-bit programming models, the concept of near and far calls have
  201. no meaning, hence the directive is ignored. A warning is printed to the screen,
  202. as a reminder.
  203. As an example, the following piece of code:
  204. \begin{verbatim}
  205. {$F+}
  206. Procedure TestProc;
  207. begin
  208. Writeln ('Hello From TestProc');
  209. end;
  210. begin
  211. testProc
  212. end.
  213. \end{verbatim}
  214. Generates the following compiler output:
  215. \begin{verbatim}
  216. malpertuus: >pp -vw testf
  217. Compiler: ppc386
  218. Units are searched in: /home/michael;/usr/bin/;/usr/lib/ppc/0.9.1/linuxunits
  219. Target OS: Linux
  220. Compiling testf.pp
  221. testf.pp(1) Warning: illegal compiler switch
  222. 7739 kB free
  223. Calling assembler...
  224. Assembled...
  225. Calling linker...
  226. 12 lines compiled,
  227. 1.00000000000000E+0000
  228. \end{verbatim}
  229. One can see that the verbosity level was set to display warnings.
  230. When declaring a function as \var{Far} (this has the same effect as setting it
  231. between \var{\{\$F+\} \dots \{\$F-\}} directives), the compiler also generates a
  232. warning:
  233. \begin{verbatim}
  234. testf.pp(3) Warning: FAR ignored
  235. \end{verbatim}
  236. The same story is true for procedures declared as \var{Near}. The warning
  237. displayed in that case is:
  238. \begin{verbatim}
  239. testf.pp(3) Warning: NEAR ignored
  240. \end{verbatim}
  241. \subsection{\var{\protect\$FATAL} : Generate fatal error message}
  242. The following code
  243. \begin{verbatim}
  244. {$FATAL This code is erroneous !}
  245. \end{verbatim}
  246. will display an error message when the compiler encounters it,
  247. and the compiler will immediatly stop the compilation process.
  248. This is mainly useful inc conjunction wih \var{\{\$IFDEF\}} or
  249. \var{\{\$IFOPT\}} statements.
  250. \subsection{\var{\protect\$GOTO} : Support \var{Goto} and \var{Label}}
  251. If \var{\{\$GOTO ON\}} is specified, the compiler will support \var{Goto}
  252. statements and \var{Label} declarations. By default, \var{\$GOTO OFF} is
  253. assumed. This directive corresponds to the \var{-Sg} command-line option.
  254. As an example, the following code can be compiled:
  255. \begin{verbatim}
  256. {$GOTO ON}
  257. label Theend;
  258. begin
  259. If ParamCount=0 then
  260. GoTo TheEnd;
  261. Writeln ('You specified command-line options');
  262. TheEnd:
  263. end.
  264. \end{verbatim}
  265. \begin{remark}When compiling assembler code using the inline assembler
  266. readers, any labels used in the assembler code must be declared, and
  267. the \var{\{\$GOTO ON\}} directive should be used.
  268. \end{remark}
  269. \subsection{\var{\protect\$H} or \var{\protect\$LONGSTRINGS} : Use AnsiStrings}
  270. If \var{\{\$LONGSTRINGS ON\}} is specified, the keyword \var{String} (no
  271. length specifier) will be treated as \var{AnsiString}, and the compiler
  272. will treat the corresponding variable as an ansistring, and will
  273. generate corresponding code.
  274. By default, the use of ansistrings is off, corresponding to \var{\{\$H-\}}.
  275. The \file{system} unit is compiled without ansistrings, all its functions accept
  276. shortstring arguments. The same is true for all RTL units, except the
  277. \file{sysutils} unit, which is compiled with ansistrings.
  278. \subsection{\var{\protect\$HINT} : Generate hint message}
  279. If the generation of hints is turned on, through the \var{-vh} command-line
  280. option or the \var{\{\$HINTS ON\}} directive, then
  281. \begin{verbatim}
  282. {$Hint This code should be optimized }
  283. \end{verbatim}
  284. will display a hint message when the compiler encounters it.
  285. By default, no hints are generated.
  286. \subsection{\var{\protect\$HINTS} : Emit hints}
  287. \var{\{\$HINTS ON\}} switches the generation of hints on.
  288. \var{\{\$HINTS OFF\}} switches the generation of hints off.
  289. Contrary to the command-line option \var{-vh} this is a local switch,
  290. this is useful for checking parts of the code.
  291. \subsection{\var{\protect\$IF} : Start conditional compilation}
  292. The directive \var{\{\$IF expr\}} will continue the compilation
  293. if the boolean expression \var{expr} evaluates to \var{true}. If the
  294. compilation evaluates to false, then the source is skipped to the first
  295. \var{\{\$ELSE\}} or \var{\{\$ENDIF\}} directive.
  296. The compiler must be able to evaluate the expression at parse time.
  297. This means that variables or constants that are defined in
  298. the source cannot be used. Macros and symbols may be used, however.
  299. More information on this can be found in the section about
  300. conditionals.
  301. \subsection{\var{\protect\$IFDEF Name} : Start conditional compilation}
  302. If the symbol \var{Name} is not defined then the \var{\{\$IFDEF name\}}
  303. will skip the compilation of the text that follows it to the first
  304. \var{\{\$ELSE\}} or \var{\{\$ENDIF\}} directive.
  305. If \var{Name} is defined, then compilation continues as if the directive
  306. wasn't there.
  307. \subsection{\var{\protect\$IFNDEF} : Start conditional compilation}
  308. If the symbol \var{Name} is defined then the \var{\{\$IFNDEF name\}}
  309. will skip the compilation of the text that follows it to the first
  310. \var{\{\$ELSE\}} or \var{\{\$ENDIF\}} directive.
  311. If it is not defined, then compilation continues as if the directive
  312. wasn't there.
  313. \subsection{\var{\protect\$IFOPT} : Start conditional compilation}
  314. The \var{\{\$IFOPT switch\}} will compile the text that follows it if the
  315. switch \var{switch} is currently in the specified state.
  316. If it isn't in the specified state, then compilation continues after the
  317. corresponding \var{\{\$ELSE\}} or \var{\{\$ENDIF\}} directive.
  318. As an example:
  319. \begin{verbatim}
  320. {$IFOPT M+}
  321. Writeln ('Compiled with type information');
  322. {$ENDIF}
  323. \end{verbatim}
  324. Will compile the writeln statement if generation of type information is on.
  325. \begin{remark}The \var{\{\$IFOPT\}} directive accepts only short options,
  326. i.e. \var{\{\$IFOPT TYPEINFO\}} will not be accepted.
  327. \end{remark}
  328. \subsection{\var{\protect\$INFO} : Generate info message}
  329. If the generation of info is turned on, through the \var{-vi} command-line
  330. option, then
  331. \begin{verbatim}
  332. {$INFO This was coded on a rainy day by Bugs Bunny}
  333. \end{verbatim}
  334. will display an info message when the compiler encounters it.
  335. This is useful in conjunction with the \var{\{\$IFDEF\}} directive, to show
  336. information about which part of the code is being compiled.
  337. \subsection{\var{\protect\$INLINE} : Allow inline code.}
  338. The \var{\{\$INLINE ON\}} directive tells the compiler that the \var{Inline}
  339. procedure modifier should be allowed. Procedures that are declared inline
  340. are copied to the places where they are called. This has the effect that
  341. there is no actual procedure call, the code of the procedure is just copied
  342. to where the procedure is needed, this results in faster execution speed if
  343. the function or procedure is used a lot.
  344. By default, \var{Inline} procedures are not allowed. This directive must be
  345. specified to use inlined code. The directive is equivalent to the command-line
  346. switch \var{-Si}. For more information on inline routines, consult the \refref.
  347. \subsection{\var{\protect\$I} or \var{\protect\$IOCHECKS} : Input/Output checking}
  348. The \var{\{\$I-\}} or \var{\{\$IOCHECKS OFF\}} directive tells the compiler
  349. not to generate input/output checking code in the program. By default, the
  350. compiler does not generate this code, it must be switched on using the \var{-Ci}
  351. command-line switch.
  352. When compiling using the \var{-Ci} compiler switch, the \fpc compiler inserts
  353. input/output checking code after every input/output call in the code.
  354. If an error occurred during input or output, then a run-time error will
  355. be generated. Use this switch to avoid this behaviour.
  356. To check if something went wrong, the \var{IOResult} function can be used
  357. to see if everything went without problems.
  358. Conversely, \var{\{\$I+\}} will turn error-checking back on, until another
  359. directive is encountered which turns it off again.
  360. The most common use for this switch is to check if the opening of a file
  361. went without problems, as in the following piece of code:
  362. \begin{verbatim}
  363. assign (f,'file.txt');
  364. {$I-}
  365. rewrite (f);
  366. {$I+}
  367. if IOResult<>0 then
  368. begin
  369. Writeln ('Error opening file: "file.txt"');
  370. exit
  371. end;
  372. \end{verbatim}
  373. See the \var{IOResult} function explanation in \refref for a
  374. detailed description of the possible errors that can occur when using
  375. input/output checking.
  376. \subsection{\var{\protect\$I} or \var{\protect\$INCLUDE} : Include file }
  377. The \var{\{\$I filename\}} or \var{\{\$INCLUDE filename\}} directive
  378. tells the compiler to read further statements from the file \var{filename}.
  379. The statements read there will be inserted as if they occurred in the
  380. current file.
  381. The compiler will append the \file{.pp} extension to the file if no
  382. extension is given. Do not put the filename between quotes, as
  383. they will be regarded as part of the file's name.
  384. Include files can be nested, but not infinitely deep. The number of files is
  385. restricted to the number of file descriptors available to the \fpc compiler.
  386. Contrary to Turbo Pascal, include files can cross blocks. I.e.
  387. a block can start in one file (with a \var{Begin} keyword) and can end in another (with
  388. a \var{End} keyword). The smallest entity in an include file must be a token,
  389. i.e. an identifier, keyword or operator.
  390. The compiler will look for the file to include in the following places:
  391. \begin{enumerate}
  392. \item It will look in the path specified in the include file name.
  393. \item It will look in the directory where the current source file is.
  394. \item it will look in all directories specified in the include file search
  395. path.
  396. \end{enumerate}
  397. Directories can be added to the include file search path with the \var{-I}
  398. command-line option.
  399. \subsection{\var{\protect\$I} or \var{\protect\$INCLUDE} : Include compiler info}
  400. In this form:
  401. \begin{verbatim}
  402. {$INCLUDE %xxx%}
  403. \end{verbatim}
  404. where \var{xxx} is one of the following:
  405. \begin{description}
  406. \item[DATE] Inserts the current date.
  407. \item[FPCTARGET] Inserts the target CPU name. (deprecated, use
  408. \var{FPCTARGETCPU})
  409. \item[FPCTARGETCPU] Inserts the target CPU name.
  410. \item[FPCTARGETOS] Inserts the target OS name.
  411. \item[FPCVERSION] Current compiler version number.
  412. \item[FILE] Filename in which the directive is found.
  413. \item[LINE] Linenumer on which the directive is found.
  414. \item[TIME] Current time.
  415. \end{description}
  416. If \var{xxx} is none of the above, then it is assumed to be the name of
  417. an environment variable. Its value will be fetched.
  418. As a reult, this will generate a macro with the value of these things,
  419. as if it were a string.
  420. For example, the following program
  421. \begin{verbatim}
  422. Program InfoDemo;
  423. Const User = {$I %USER%};
  424. begin
  425. Write ('This program was compiled at ',{$I %TIME%});
  426. Writeln (' on ',{$I %DATE%});
  427. Writeln ('By ',User);
  428. Writeln ('Compiler version: ',{$I %FPCVERSION%});
  429. Writeln ('Target CPU: ',{$I %FPCTARGET%});
  430. end.
  431. \end{verbatim}
  432. Creates the following output:
  433. \begin{verbatim}
  434. This program was compiled at 17:40:18 on 1998/09/09
  435. By michael
  436. Compiler version: 0.99.7
  437. Target CPU: i386
  438. \end{verbatim}
  439. % Assembler type
  440. \subsection{\var{\protect\$I386\_XXX} : Specify assembler format (Intel 80x86 only)}
  441. This switch selects the assembler reader. \var{\{\$I386\_XXX\}}
  442. has the same effect as \var{\{\$ASMMODE XXX\}}, \sees{AsmReader}
  443. This switch is deprecated, the \var{\{\$ASMMODE XXX\}} directive should
  444. be used instead.
  445. \subsection{\var{\protect\$L} or \var{\protect\$LINK} : Link object file}
  446. The \var{\{\$L filename\}} or \var{\{\$LINK filename\}} directive
  447. tells the compiler that the file \file{filename} should be linked to
  448. the program. This cannot be used for libraries, see section
  449. \sees{linklib} for that.
  450. The compiler will look for this file in the following way:
  451. \begin{enumerate}
  452. \item It will look in the path specified in the object file name.
  453. \item It will look in the directory where the current source file is.
  454. \item it will look in all directories specified in the object file search path.
  455. \end{enumerate}
  456. Directories can be added to the object file search path with the \var{-Fo}
  457. option.
  458. On \linux systems and on operating systems with case-sensitive filesystems
  459. (such as \unix systems), the name is case sensitive, and must be typed
  460. exactly as it appears on your system.
  461. \begin{remark}Take care that the object file you're linking is in a
  462. format the linker understands. Which format this is, depends on the platform
  463. you're on. Typing \var{ld} or \var{ld --help} on the command line gives a list of formats
  464. \var{ld} knows about.
  465. \end{remark}
  466. Other files and options can be passed to the linker using the \var{-k}
  467. command-line option. More than one of these options can be used, and
  468. they will be passed to the linker, in the order that they were specified on
  469. the command line, just before the names of the object files that must be
  470. linked.
  471. \subsection{\var{\protect\$LINKLIB} : Link to a library}
  472. \label{se:linklib}
  473. The \var{\{\$LINKLIB name\}} will link to a library \file{name}.
  474. This has the effect of passing \var{-lname} to the linker.
  475. As an example, consider the following unit:
  476. \begin{verbatim}
  477. unit getlen;
  478. interface
  479. {$LINKLIB c}
  480. function strlen (P : pchar) : longint;cdecl;
  481. implementation
  482. function strlen (P : pchar) : longint;cdecl;external;
  483. end.
  484. \end{verbatim}
  485. If one would issue the command
  486. \begin{verbatim}
  487. ppc386 foo.pp
  488. \end{verbatim}
  489. where foo.pp has the above unit in its \var{uses} clause,
  490. then the compiler would link the program to the c library, by passing the
  491. linker the \var{-lc} option.
  492. The same effect could be obtained by removing the linklib directive in the
  493. above unit, and specify \var{-k-lc} on the command-line:
  494. \begin{verbatim}
  495. ppc386 -k-lc foo.pp
  496. \end{verbatim}
  497. \subsection{\var{\protect\$M} or \var{\protect\$TYPEINFO} : Generate type info}
  498. For classes that are compiled in the \var{\{\$M+\}} or \var{\{\$TYPEINFO ON\}}
  499. state, the compiler will generate Run-Time Type Information (RTTI). All
  500. descendent objects of an object that was compiled in the \var{\{\$M+\}} state
  501. will get RTTI information too, as well as any published classes.
  502. By default, no Run-Time Type Information is generated. The \var{TPersistent}
  503. object that is present in the FCL (Free Component Library) is generated in
  504. the \var{\{\$M+\}} state. The generation of RTTI allows programmers to
  505. stream objects, and to access published properties of objects, without
  506. knowing the actual class of the object.
  507. The run-time type information is accessible through the \var{TypInfo} unit,
  508. which is part of the \fpc Run-Time Library.
  509. \begin{remark}
  510. The streaming system implemented by \fpc requires that all
  511. streamable components be descendent from \var{TPersistent}.
  512. \end{remark}
  513. \subsection{\var{\protect\$MACRO} : Allow use of macros.}
  514. In the \var{\{\$MACRO ON\}} state, the compiler allows to use C-style
  515. (although not as elaborate) macros. Macros provide a means for simple text
  516. substitution. More information on using macros can be found in the
  517. \sees{Macros} section. This directive is equivalent to the command-line
  518. switch \var{-Sm}.
  519. By default, macros are not allowed.
  520. \subsection{\var{\protect\$MAXFPUREGISTERS} : Maximum number of FPU registers for variables (Intel 80x86 only)}
  521. The \var{\{\$MAXFPUREGISTERS XXX\}} directive tells the compiler how much floating point
  522. variables can be kept in the floating point processor registers. This switch is ignored
  523. unless the \var{-Or} (use register variables) optimization is used.
  524. This is quite tricky because the Intel FPU stack is limited to 8 entries.
  525. The compiler uses a heuristic algorithm to determine how much variables should be
  526. put onto the stack: in leaf procedures it is limited to 3 and in non leaf
  527. procedures to 1. But in case of a deep call tree or, even worse, a recursive
  528. procedure this can still lead to a FPU stack overflow, so the user can tell
  529. the compiler how much (floating point) variables should be kept in registers.
  530. The directive accepts the following arguments:
  531. \begin{description}
  532. \item [N] where \var{N} is the maximum number of FPU registers to use.
  533. Currently this can be in the range 0 to 7.
  534. \item[Normal] restores the heuristic and standard behavior.
  535. \item[Default] restores the heuristic and standard behaviour.
  536. \end{description}
  537. \begin{remark}This directive is valid until the end of the current procedure.
  538. \end{remark}
  539. \subsection{\var{\protect\$MESSAGE} : Generate info message}
  540. If the generation of info is turned on, through the \var{-vi} command-line
  541. option, then
  542. \begin{verbatim}
  543. {$MESSAGE This was coded on a rainy day by Bugs Bunny }
  544. \end{verbatim}
  545. will display an info message when the compiler encounters it. The effect is
  546. the same as the \var{\{\$INFO\}} directive.
  547. \subsection{\var{\protect\$MMX} : Intel MMX support (Intel 80x86 only)}
  548. \fpc supports optimization for the \textbf{MMX} Intel
  549. processor (see also chapter \ref{ch:MMXSupport}).
  550. This optimizes certain code parts for the \textbf{MMX} Intel
  551. processor, thus greatly improving speed. The speed is noticed mostly when
  552. moving large amounts of data. Things that change are
  553. \begin{itemize}
  554. \item Data with a size that is a multiple of 8 bytes is moved using the
  555. \var{movq} assembler instruction, which moves 8 bytes at a time
  556. \end{itemize}
  557. \begin{remark}MMX support is NOT emulated on non-MMX systems, i.e. if
  558. the processor doesn't have the MMX extensions, the MMX optimizations cannot
  559. be used.
  560. \end{remark}
  561. When \textbf{MMX} support is on, it is not allowed to do floating point
  562. arithmetic. It is allowed to move floating point data, but no arithmetic
  563. can be done. If floating point math must be done anyway, first \textbf{MMX}
  564. support must be switched off and the FPU must be cleared using the \var{emms}
  565. function of the \file{cpu} unit.
  566. The following example will make this more clear:
  567. \begin{verbatim}
  568. Program MMXDemo;
  569. uses mmx;
  570. var
  571. d1 : double;
  572. a : array[0..10000] of double;
  573. i : longint;
  574. begin
  575. d1:=1.0;
  576. {$mmx+}
  577. { floating point data is used, but we do _no_ arithmetic }
  578. for i:=0 to 10000 do
  579. a[i]:=d2; { this is done with 64 bit moves }
  580. {$mmx-}
  581. emms; { clear fpu }
  582. { now we can do floating point arithmetic }
  583. ...
  584. end.
  585. \end{verbatim}
  586. See, however, the chapter on MMX (\ref{ch:MMXSupport}) for more information
  587. on this topic.
  588. \subsection{\var{\protect\$NOTE} : Generate note message}
  589. If the generation of notes is turned on, through the \var{-vn} command-line
  590. option or the \var{\{\$NOTES ON\}} directive, then
  591. \begin{verbatim}
  592. {$NOTE Ask Santa Claus to look at this code}
  593. \end{verbatim}
  594. will display a note message when the compiler encounters it.
  595. \subsection{\var{\protect\$NOTES} : Emit notes}
  596. \var{\{\$NOTES ON\}} switches the generation of notes on.
  597. \var{\{\$NOTES OFF\}} switches the generation of notes off.
  598. Contrary to the command-line option \var{-vn} this is a local switch,
  599. this is useful for checking parts of the code.
  600. By default, \var{\{\$NOTES\}} is off.
  601. \subsection{\var{\protect\$OUTPUT\_FORMAT} : Specify the output format}
  602. \var{\{\$OUTPUT\_FORMAT format\}} has the same functionality as the \var{-A}
  603. command-line option: it tells the compiler what kind of object file must be
  604. generated. You can specify this switch only {\em before} the \var{Program}
  605. or \var{Unit} clause in your source file. The different kinds of formats are
  606. shown in \seet{Formats}.
  607. The default output format depends on the platform the compiler was compiled
  608. on.
  609. \begin{FPCltable}{ll}{Formats generated by the x86 compiler}{Formats} \hline
  610. Switch value & Generated format \\ \hline
  611. AS & AT\&T assembler file. \\
  612. AS\_AOUT & Go32v1 assembler file.\\
  613. ASW & AT\&T Win32 assembler file. \\
  614. COFF & Go32v2 COFF object file.\\
  615. MASM & Masm assembler file.\\
  616. NASM & Nasm assembler file.\\
  617. NASMCOFF & Nasm assembler file (COFF format).\\
  618. NASMELF & Nasm assembler file (ELF format).\\
  619. PECOFF & PECOFF object file (Win32).\\
  620. TASM & Tasm assembler file.\\
  621. \end{FPCltable}
  622. \subsection{\var{\protect\$P} or \var{\protect\$OPENSTRINGS} : Use open strings}
  623. If this switch is on, all function or procedure parameters of type string
  624. are considered to be open string parameters; this parameter only has effect
  625. for short strings, not for ansistrings.
  626. When using openstrings, the declared type of the string can be different
  627. from the type of string that is actually passed, even for strings that are
  628. passed by reference. The declared size of the string passed can be examined
  629. with the \var{High(P)} call.
  630. Default the use of openstrings is off.
  631. \subsection{\var{\protect\$PACKENUM} : Minimum enumeration type size}
  632. This directive tells the compiler the minimum number of bytes it should
  633. use when storing enumerated types. It is of the following form:
  634. \begin{verbatim}
  635. {$PACKENUM xxx}
  636. {$MINENUMSIZE xxx}
  637. \end{verbatim}
  638. Where the form with \var{\$MINENUMSIZE} is for Delphi compatibility.
  639. \var{xxx} can be one of \var{1,2} or \var{4}, or \var{NORMAL} or
  640. \var{DEFAULT}.
  641. As an alternative form one can use \var{\{\$Z1\}}, \var{\{\$Z2\}}
  642. \var{\{\$Z4\}}. Contrary to Delphi, the default is (\var{\{\$Z4\}}).
  643. So the following code
  644. \begin{verbatim}
  645. {$PACKENUM 1}
  646. Type
  647. Days = (monday, tuesday, wednesday, thursday, friday,
  648. saturday, sunday);
  649. \end{verbatim}
  650. will use 1 byte to store a variable of type \var{Days}, whereas it nomally
  651. would use 4 bytes. The above code is equivalent to
  652. \begin{verbatim}
  653. {$Z1}
  654. Type
  655. Days = (monday, tuesday, wednesday, thursday, friday,
  656. saturday, sunday);
  657. \end{verbatim}
  658. \subsection{\var{\protect\$PACKRECORDS} : Alignment of record elements}
  659. This directive controls the byte alignment of the elements in a record,
  660. object or class type definition.
  661. It is of the following form:
  662. \begin{verbatim}
  663. {$PACKRECORDS n}
  664. \end{verbatim}
  665. Where \var{n} is one of 1, 2, 4, 16, \var{C}, \var{NORMAL} or \var{DEFAULT}.
  666. This means that the elements of a record that have size greater than \var{n}
  667. will be aligned on \var{n} byte boundaries. Elements with size less than or
  668. equal to \var{n} will be aligned to a natural boundary, i.e. to a power of
  669. two that is equal to or larger than the element's size. The type \var{C}
  670. is used to specify alignment as by the GNU CC compiler. It should be used
  671. only when making import units for C routines.
  672. The default alignment (which can be selected with \var{DEFAULT}) is 2,
  673. contrary to Turbo Pascal, where it is 1.
  674. More information on this and an example program can be found in the reference
  675. guide, in the section about record types.
  676. \subsection{\var{\protect\$Q} \var{\protect\$OVERFLOWCHECKS}: Overflow checking}
  677. The \var{\{\$Q+\}} or \var{\{\$OVERFLOWCHECKS ON\}} directive turns on
  678. integer overflow checking. This means that the compiler inserts code
  679. to check for overflow when doing computations with integers.
  680. When an overflow occurs, the run-time library will print a message
  681. \var{Overflow at xxx}, and exit the program with exit code 215.
  682. \begin{remark}Overflow checking behaviour is not the same as in
  683. Turbo Pascal since all arithmetic operations are done via 32-bit or
  684. 64-bit values. Furthermore, the \var{Inc()} and \var{Dec} standard system
  685. procedures {\em are} checked for overflow in \fpc, while in Turbo
  686. Pascal they are not.
  687. \end{remark}
  688. Using the \var{\{\$Q-\}} switch switches off the overflow checking code
  689. generation.
  690. The generation of overflow checking code can also be controlled
  691. using the \var{-Co} command line compiler option (see \userref).
  692. \subsection{\var{\protect\$R} or \var{\protect\$RANGECHECKS} : Range checking}
  693. By default, the compiler doesn't generate code to check the ranges of array
  694. indices, enumeration types, subrange types, etc. Specifying the
  695. \var{\{\$R+\}} switch tells the computer to generate code to check these
  696. indices. If, at run-time, an index or enumeration type is specified that is
  697. out of the declared range of the compiler, then a run-time error is
  698. generated, and the program exits with exit code 201. This can happen when
  699. doing a typecast (implicit or explicit) on an enumeration type or subrange
  700. type.
  701. The \var{\{\$RANGECHECKS OFF\}} switch tells the compiler not to generate range checking
  702. code. This may result in faulty program behaviour, but no run-time errors
  703. will be generated.
  704. \begin{remark}The standard functions \var{val} and \var{Read} will also check ranges
  705. when the call is compiled in \var{\{\$R+\}} mode.
  706. \end{remark}
  707. \subsection{\var{\protect\$SATURATION} : Saturation operations (Intel 80x86 only)}
  708. This works only on the intel compiler, and MMX support must be on
  709. (\var{\{\$MMX +\}}) for this to have any effect. See the section on
  710. saturation support (\sees{SaturationSupport}) for more information
  711. on the effect of this directive.
  712. \subsection{\var{\protect\$SMARTLINK} : Use smartlinking}
  713. A unit that is compiled in the \var{\{\$SMARTLINK ON\}} state will be
  714. compiled in such a way that it can be used for smartlinking. This means that
  715. the unit is chopped in logical pieces: each procedure is put in it's own
  716. object file, and all object files are put together in a big archive. When
  717. using such a unit, only the pieces of code that you really need or call,
  718. will be linked in your program, thus reducing the size of your executable
  719. substantially.
  720. Beware: using smartlinked units slows down the compilation process, because
  721. a separate object file must be created for each procedure. If you have units
  722. with many functions and procedures, this can be a time consuming process,
  723. even more so if you use an external assembler (the assembler is called to
  724. assemble each procedure or function code block separately).
  725. The smartlinking directive should be specified {\em before} the unit
  726. declaration part:
  727. \begin{verbatim}
  728. {$SMARTLINK ON}
  729. Unit MyUnit;
  730. Interface
  731. ...
  732. \end{verbatim}
  733. This directive is equivalent to the \var{-Cx} command-line switch.
  734. \subsection{\var{\protect\$STATIC} : Allow use of \var{Static} keyword.}
  735. If you specify the \var{\{\$STATIC ON\}} directive, then \var{Static}
  736. methods are allowed for objects. \var{Static} objects methods do not require
  737. a \var{Self} variable. They are equivalent to \var{Class} methods for
  738. classes. By default, \var{Static} methods are not allowed. Class methods
  739. are always allowed.
  740. By default, the address operator returns an untyped pointer.
  741. This directive is equivalent to the \var{-St} command-line option.
  742. \subsection{\var{\protect\$STOP} : Generate fatal error message}
  743. The following code
  744. \begin{verbatim}
  745. {$STOP This code is erroneous !}
  746. \end{verbatim}
  747. will display an error message when the compiler encounters it.
  748. The compiler will immediatly stop the compilation process.
  749. It has the same effect as the \var{\{\$FATAL\}} directive.
  750. \subsection{\var{\protect\$T} or \var{\protect\$TYPEDADDRESS} : Typed address operator (@)}
  751. In the \var{\{\$T+\}} or \var{\{\$TYPEDADDRESS ON\}} state the @ operator,
  752. when applied to a variable, returns a result of type \var{\^{}T}, if the
  753. type of the variable is \var{T}. In the \var{\{\$T-\}} state, the result is
  754. always an untyped pointer, which is assignment compatible with all other
  755. pointer types.
  756. \subsection{\var{\protect\$UNDEF} : Undefine a symbol}
  757. The directive
  758. \begin{verbatim}
  759. {$UNDEF name}
  760. \end{verbatim}
  761. un-defines the symbol \var{name} if it was previously defined.
  762. \var{Name} is case insensitive.
  763. \subsection{\var{\protect\$V} or \var{\protect\$VARSTRINGCHECKS} : Var-string checking}
  764. When in the \var{+} or \var{ON} state, the compiler checks that strings
  765. passed as parameters are of the same, identical, string type as the declared
  766. parameters of the procedure.
  767. \subsection{\var{\protect\$WAIT} : Wait for enter key press}
  768. If the compiler encounters a
  769. \begin{verbatim}
  770. {$WAIT}
  771. \end{verbatim}
  772. directive, it will resume compiling only after the user has pressed the
  773. enter key. If the generation of info messages is turned on, then the compiler
  774. will display the following message:
  775. \begin{verbatim}
  776. Press <return> to continue
  777. \end{verbatim}
  778. before waiting for a keypress.
  779. \begin{remark}This may interfere with automatic
  780. compilation processes. It should be used for debugging purposes only.
  781. \end{remark}
  782. \subsection{\var{\protect\$WARNING} : Generate warning message}
  783. If the generation of warnings is turned on, through the \var{-vw}
  784. command-line option or the \var{\{\$WARNINGS ON\}} directive, then
  785. \begin{verbatim}
  786. {$WARNING This is dubious code}
  787. \end{verbatim}
  788. will display a warning message when the compiler encounters it.
  789. \subsection{\var{\protect\$WARNINGS} : Emit warnings}
  790. \var{\{\$WARNINGS ON\}} switches the generation of warnings on.
  791. \var{\{\$WARNINGS OFF\}} switches the generation of warnings off.
  792. Contrary to the command-line option \var{-vw} this
  793. is a local switch, this is useful for checking parts of your code.
  794. By default, no warnings are emitted.
  795. \subsection{\var{\protect\$X} or \var{\protect\$EXTENDEDSYNTAX} : Extended syntax}
  796. Extended syntax allows you to drop the result of a function. This means that
  797. you can use a function call as if it were a procedure. Standard this feature
  798. is on. You can switch it off using the \var{\{\$X-\}} or
  799. \var{\{\$EXTENDEDSYNTAX OFF\}}directive.
  800. The following, for instance, will not compile:
  801. \begin{verbatim}
  802. function Func (var Arg : sometype) : longint;
  803. begin
  804. ... { declaration of Func }
  805. end;
  806. ...
  807. {$X-}
  808. Func (A);
  809. \end{verbatim}
  810. The reason this construct is supported is that you may wish to call a
  811. function for certain side-effects it has, but you don't need the function
  812. result. In this case you don't need to assign the function result, saving
  813. you an extra variable.
  814. The command-line compiler switch \var{-Sa1} has the same effect as the
  815. \var{\{\$X+\}} directive.
  816. By default, extended syntax is assumed.
  817. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  818. % Global switches
  819. \section{Global directives}
  820. \label{se:GlobalSwitch}
  821. Global directives affect the whole of the compilation process. That is why
  822. they also have a command-line counterpart. The command-line counterpart is
  823. given for each of the directives.
  824. \subsection{\var{\protect\$APPTYPE} : Specify type of application (Win32 and AmigaOS only)}
  825. The \var{\{\$APPTYPE XXX\}} accepts one argument that can have two possible
  826. values: \var{GUI} or \var{CONSOLE}. It is used to tell the \windows
  827. Operating system if an application is a console application or a graphical
  828. application. By default, a program compiled by \fpc is a console
  829. application. Running it will display a console window. Specifying the
  830. \var{\{\$APPTYPE GUI\}} directive will mark the application as a graphical
  831. application; no console window will be opened when the application is run.
  832. If run from the command-line, the command prompt will be returned immediatly
  833. after the application was started.
  834. Care should be taken when compiling \var{GUI} applications; the \var{Input}
  835. and \var{Output} files are not available in a GUI application, and
  836. attempting to read from or write to them will result in a run-time error.
  837. It is possible to determine the application type of a \windows or \amiga application
  838. at runtime. The \var{IsConsole} constant, declared in the Win32 and Amiga
  839. system units as
  840. \begin{verbatim}
  841. Const
  842. IsConsole : Boolean
  843. \end{verbatim}
  844. contains \var{True} if the application is a console application, \var{False}
  845. if the application is a GUI application.
  846. \subsection{\var{\protect\$D} or \var{\protect\$DEBUGINFO} : Debugging symbols}
  847. When this switch is on,
  848. the compiler inserts GNU debugging information in
  849. the executable. The effect of this switch is the same as the command-line
  850. switch \var{-g}.
  851. By default, insertion of debugging information is off.
  852. \subsection{\var{\protect\$DESCRIPTION} : Application description}
  853. This switch is recognised for compatibility only, but is ignored completely
  854. by the compiler. At a later stage, this switch may be activated.
  855. \subsection{\var{\protect\$E} : Emulation of coprocessor}
  856. This directive controls the emulation of the coprocessor. There is no
  857. command-line counterpart for this directive.
  858. \subsubsection{Intel 80x86 version}
  859. When this switch is enabled, all floating point instructions
  860. which are not supported by standard coprocessor emulators will give out
  861. a warning.
  862. The compiler itself doesn't do the emulation of the coprocessor.
  863. To use coprocessor emulation under \dos go32v2 you must use the
  864. emu387 unit, which contains correct initialization code for the
  865. emulator.
  866. Under \linux and most \unix'es, the kernel takes care of the
  867. coprocessor support.
  868. \subsubsection{Motorola 680x0 version}
  869. When the switch is on, no floating point opcodes are emitted
  870. by the code generator. Instead, internal run-time library routines
  871. are called to do the necessary calculations. In this case all
  872. real types are mapped to the single IEEE floating point type.
  873. \begin{remark}By default, emulation is on for non-unix targets.
  874. For unix targets, floating point emulation (if required) is handled
  875. by the operating system, and by default it is off.
  876. \end{remark}
  877. \subsection{\var{\protect\$G} : Generate 80286 code}
  878. This option is recognised for Turbo Pascal compatibility, but is ignored,
  879. since the compiler works only on 32-bit and 64-bit processors.
  880. \subsection{\var{\protect\$INCLUDEPATH} : Specify include path.}
  881. This option serves to specify the include path, where the compiler looks for
  882. include files. \var{\{\$INCLUDEPATH XXX\}} will add \var{XXX} to the include
  883. path. \var{XXX} can contain one or more paths, separated by semi-colons or
  884. colons.
  885. For example:
  886. \begin{verbatim}
  887. {$INCLUDEPATH ../inc;../i386}
  888. {$I strings.inc}
  889. \end{verbatim}
  890. will add the directories \file{../inc} and \file{../i386} to the include
  891. path of the compiler. The compiler will look for the file \file{strings.inc}
  892. in both these directories, and will include the first found file. This directive is
  893. equivalent to the \var{-Fi} command-line switch.
  894. Caution is in order when using this directive: If you distribute files, the
  895. places of the files may not be the same as on your machine; moreover, the
  896. directory structure may be different. In general it would be fair to say
  897. that you should avoid using {\em absolute} paths, instead use {\em relative}
  898. paths, as in the example above. Only use this directive if you are certain
  899. of the places where the files reside. If you are not sure, it is better
  900. practice to use makefiles and makefile variables.
  901. \subsection{\var{\protect\$L} or \var{\protect\$LOCALSYMBOLS} : Local symbol information}
  902. This switch (not to be confused with the \var{\{\$L file\}} file linking
  903. directive) is recognised for Turbo Pascal compatibility, but is ignored.
  904. Generation of symbol information is controlled by the \var{\$D} switch.
  905. \subsection{\var{\protect\$LIBRARYPATH} : Specify library path.}
  906. This option serves to specify the library path, where the linker looks for
  907. static or dynamic libraries. \var{\{\$LIBRARYPATH XXX\}} will add \var{XXX}
  908. to the library path. \var{XXX} can contain one or more paths, separated
  909. by semi-colons or colons.
  910. For example:
  911. \begin{verbatim}
  912. {$LIBRARYPATH /usr/X11/lib;/usr/local/lib}
  913. {$LINKLIB X11}
  914. \end{verbatim}
  915. will add the directories \file{/usr/X11/lib} and \file{/usr/local/lib} to
  916. the linker library path. The linker will look for the library \file{libX11.so}
  917. in both these directories, and use the first found file. This directive is
  918. equivalent to the \var{-Fl} command-line switch.
  919. Caution is in order when using this directive: If you distribute files, the
  920. places of the libraries may not be the same as on your machine; moreover, the
  921. directory structure may be different. In general it would be fair to say
  922. that you should avoid using this directive. If you are not sure, it is better
  923. practice to use makefiles and makefile variables.
  924. \subsection{\var{\protect\$M} or \var{\protect\$MEMORY} : Memory sizes}
  925. This switch can be used to set the heap and stacksize. It's format is as
  926. follows:
  927. \begin{verbatim}
  928. {$M StackSize,HeapSize}
  929. \end{verbatim}
  930. where \var{StackSize} and \var{HeapSize} should be two integer values,
  931. greater than 1024. The first number sets the size of the stack, and the
  932. second the size of the heap. (Stack setting is ignored under \linux, \netbsd and \freebsd).
  933. The two numbers can be set on the command line using the \var{-Ch}
  934. and \var{-Cs} switches.
  935. \subsection{\var{\protect\$MODE} : Set compiler compatibility mode}
  936. The \var{\{\$MODE\}} sets the compatibility mode of the compiler. This
  937. is equivalent to setting one of the command-line options \var{-So},
  938. \var{-Sd}, \var{-Sp} or \var{-S2}. it has the following arguments:
  939. \begin{description}
  940. \item[Default] Default mode. This reverts back to the mode that was set on
  941. the command-line.
  942. \item[Delphi] Delphi compatibility mode. All object-pascal extensions are
  943. enabled. This is the same as the command-line option \var{-Sd}.
  944. \item[TP] Turbo pascal compatibility mode. Object pascal extensions are
  945. disabled, except ansistrings, which remain valid.
  946. This is the same as the command-line option \var{-So}.
  947. \item[FPC] FPC mode. This is the default, if no command-line switch is
  948. supplied.
  949. \item[OBJFPC] Object pascal mode. This is the same as the \var{-S2}
  950. command-line option.
  951. \item[GPC] GNU pascal mode. This is the same as the \var{-Sp} command-line
  952. option.
  953. \end{description}
  954. For an exact description of each of these modes, see appendix \ref{ch:AppD},
  955. on page \pageref{ch:AppD}.
  956. \subsection{\var{\protect\$N} : Numeric processing }
  957. This switch is recognised for Turbo Pascal compatibility, but is otherwise
  958. ignored, since the compiler always uses the coprocessor for floating point
  959. mathematics.
  960. \subsection{\var{\protect\$O} : Overlay code generation }
  961. This switch is recognised for Turbo Pascal compatibility, but is otherwise
  962. ignored.
  963. \subsection{\var{\protect\$OBJECTPATH} : Specify object path.}
  964. This option serves to specify the object path, where the compiler looks for
  965. object files. \var{\{\$OBJECTPATH XXX\}} will add \var{XXX} to the object
  966. path. \var{XXX} can contain one or more paths, separated by semi-colons or
  967. colons.
  968. For example:
  969. \begin{verbatim}
  970. {$OBJECTPATH ../inc;../i386}
  971. {$L strings.o}
  972. \end{verbatim}
  973. will add the directories \file{../inc} and \file{../i386} to the
  974. object path of the compiler. The compiler will look for the file \file{strings.o}
  975. in both these directories, and will link the first found file in the
  976. program. This directive is equivalent to the \var{-Fo} command-line switch.
  977. Caution is in order when using this directive: If you distribute files, the
  978. places of the files may not be the same as on your machine; moreover, the
  979. directory structure may be different. In general it would be fair to say
  980. that you should avoid using {\em absolute} paths, instead use {\em relative}
  981. paths, as in the example above. Only use this directive if you are certain
  982. of the places where the files reside. If you are not sure, it is better
  983. practice to use makefiles and makefile variables.
  984. \subsection{\var{\protect\$S} : Stack checking}
  985. The \var{\{\$S+\}} directive tells the compiler to generate stack checking
  986. code. This generates code to check if a stack overflow occurred, i.e. to see
  987. whether the stack has grown beyond its maximally allowed size. If the stack
  988. grows beyond the maximum size, then a run-time error is generated, and the
  989. program will exit with exit code 202.
  990. Specifying \var{\{\$S-\}} will turn generation of stack-checking code off.
  991. The command-line compiler switch \var{-Ct} has the same effect as the
  992. \var{\{\$S+\}} directive.
  993. By default, no stack checking is performed.
  994. \subsection{\var{\protect\$UNITPATH} : Specify unit path.}
  995. This option serves to specify the unit path, where the compiler looks for
  996. unit files. \var{\{\$UNITPATH XXX\}} will add \var{XXX} to the unit
  997. path. \var{XXX} can contain one or more paths, separated by semi-colons or
  998. colons.
  999. For example:
  1000. \begin{verbatim}
  1001. {$UNITPATH ../units;../i386/units}
  1002. Uses strings;
  1003. \end{verbatim}
  1004. will add the directories \file{../units} and \file{../i386/units} to the unit
  1005. path of the compiler. The compiler will look for the file \file{strings.ppu}
  1006. in both these directories, and will link the first found file in the
  1007. program. This directive is equivalent to the \var{-Fu} command-line switch.
  1008. Caution is in order when using this directive: If you distribute files, the
  1009. places of the files may not be the same as on your machine; moreover, the
  1010. directory structure may be different. In general it would be fair to say
  1011. that you should avoid using {\em absolute} paths, instead use {\em relative}
  1012. paths, as in the example above. Only use this directive if you are certain
  1013. of the places where the files reside. If you are not sure, it is better
  1014. practice to use makefiles and makefile variables.
  1015. \subsection{\var{\protect\$W} or \var{\protect\$STACKFRAMES} : Generate stackframes}
  1016. The \var{\{\$W\}} switch directove controls the generation of stackframes.
  1017. In the on state, the compiler will generate a
  1018. stackframe for every procedure or function.
  1019. In the off state, the compiler will omit the generation of a stackframe if
  1020. the following conditions are satisfied:
  1021. \begin{itemize}
  1022. \item The procedure has no parameters.
  1023. \item The procedure has no local variables.
  1024. \item If the procedure is not an \var{assembler} procedure, it must not have
  1025. a \var{asm \dots end;} block.
  1026. \item it is not a constructor or destructor.
  1027. \end{itemize}
  1028. If these conditions are satisfied, the stack frame will be omitted.
  1029. \subsection{\var{\protect\$Y} or \var{\protect\$REFERENCEINFO} : Insert Browser information}
  1030. This switch controls the generation of browser inforation. It is recognized
  1031. for compatibility with Turbo Pascal and Delphi only, as Browser information
  1032. generation is not yet fully supported.
  1033. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1034. % Using conditionals and macros
  1035. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1036. \chapter{Using conditionals, messages and macros}
  1037. \label{ch:CondMessageMacro}
  1038. The \fpc compiler supports conditionals as in normal Turbo Pascal. It does,
  1039. however, more than that. It allows you to make macros which can be used in
  1040. your code, and it allows you to define messages or errors which will be
  1041. displayed when compiling.
  1042. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1043. % Conditionals
  1044. \section{Conditionals}
  1045. \label{se:Conditionals}
  1046. The rules for using conditional symbols are the same as under Turbo Pascal.
  1047. Defining a symbol goes as follows:
  1048. \begin{verbatim}
  1049. {$define Symbol}
  1050. \end{verbatim}
  1051. From this point on in your code, the compiler knows the symbol \var{Symbol}.
  1052. Symbols are, like the Pascal language, case insensitive.
  1053. You can also define a symbol on the command line. the \var{-dSymbol} option
  1054. defines the symbol \var{Symbol}. You can specify as many symbols on the
  1055. command line as you want.
  1056. Undefining an existing symbol is done in a similar way:
  1057. \begin{verbatim}
  1058. {$undef Symbol}
  1059. \end{verbatim}
  1060. If the symbol didn't exist yet, this doesn't do anything. If the symbol
  1061. existed previously, the symbol will be erased, and will not be recognized
  1062. any more in the code following the \verb|{$undef \dots}| statement.
  1063. You can also undefine symbols from the command line with the \var{-u}
  1064. command-line switch.
  1065. To compile code conditionally, depending on whether a symbol is defined or
  1066. not, you can enclose the code in a \verb|{$ifdef Symbol}| \dots \verb|{$endif}|
  1067. pair. For instance the following code will never be compiled:
  1068. \begin{verbatim}
  1069. {$undef MySymbol}
  1070. {$ifdef Mysymbol}
  1071. DoSomething;
  1072. ...
  1073. {$endif}
  1074. \end{verbatim}
  1075. Similarly, you can enclose your code in a \verb|{$ifndef Symbol}| \dots \verb|{$endif}|
  1076. pair. Then the code between the pair will only be compiled when the used
  1077. symbol doesn't exist. For example, in the following example, the call to the
  1078. \var{DoSomething} will always be compiled:
  1079. \begin{verbatim}
  1080. {$undef MySymbol}
  1081. {$ifndef Mysymbol}
  1082. DoSomething;
  1083. ...
  1084. {$endif}
  1085. \end{verbatim}
  1086. You can combine the two alternatives in one structure, namely as follows
  1087. \begin{verbatim}
  1088. {$ifdef Mysymbol}
  1089. DoSomething;
  1090. {$else}
  1091. DoSomethingElse
  1092. {$endif}
  1093. \end{verbatim}
  1094. In this example, if \var{MySymbol} exists, then the call to \var{DoSomething}
  1095. will be compiled. If it doesn't exist, the call to \var{DoSomethingElse} is
  1096. compiled.
  1097. Except for the Turbo Pascal constructs the \fpc compiler also
  1098. supports a stronger conditional compile mechanism: The \var{\{\$if\}}
  1099. construct.
  1100. The prototype of this construct is as follows:
  1101. \begin{verbatim}
  1102. {$if expr}
  1103. CompileTheseLines;
  1104. {$else}
  1105. BetterCompileTheseLines;
  1106. {$endif}
  1107. \end{verbatim}
  1108. In this directive \var{expr} is a Pascal expression which is evaluated using
  1109. strings, unless both parts of a comparision can be evaluated as numbers,
  1110. in which case they are evaluated using numbers\footnote{Otherwise
  1111. \var{\{\$if 8>54\}} would evaluate to \var{True}}.
  1112. If the complete expression evaluates to \var{'0'}, then it is considered
  1113. false and rejected. Otherwise it is considered true and accepted. This may
  1114. have unexpected consequences:
  1115. \begin{verbatim}
  1116. {$if 0}
  1117. \end{verbatim}
  1118. will evaluate to \var{False} and be rejected, while
  1119. \begin{verbatim}
  1120. {$if 00}
  1121. \end{verbatim}
  1122. will evaluate to \var{True}.
  1123. You can use any Pascal operator to construct your expression: \var{=, <>,
  1124. >, <, >=, <=, AND, NOT, OR} and you can use round brackets to change the
  1125. precedence of the operators.
  1126. The following example shows you many of the possibilities:
  1127. \begin{verbatim}
  1128. {$ifdef fpc}
  1129. var
  1130. y : longint;
  1131. {$else fpc}
  1132. var
  1133. z : longint;
  1134. {$endif fpc}
  1135. var
  1136. x : longint;
  1137. begin
  1138. {$if (fpc_version=0) and (fpc_release>6) and (fpc_patch>4)}
  1139. {$info At least this is version 0.9.5}
  1140. {$else}
  1141. {$fatal Problem with version check}
  1142. {$endif}
  1143. {$define x:=1234}
  1144. {$if x=1234}
  1145. {$info x=1234}
  1146. {$else}
  1147. {$fatal x should be 1234}
  1148. {$endif}
  1149. {$if 12asdf and 12asdf}
  1150. {$info $if 12asdf and 12asdf is ok}
  1151. {$else}
  1152. {$fatal $if 12asdf and 12asdf rejected}
  1153. {$endif}
  1154. {$if 0 or 1}
  1155. {$info $if 0 or 1 is ok}
  1156. {$else}
  1157. {$fatal $if 0 or 1 rejected}
  1158. {$endif}
  1159. {$if 0}
  1160. {$fatal $if 0 accepted}
  1161. {$else}
  1162. {$info $if 0 is ok}
  1163. {$endif}
  1164. {$if 12=12}
  1165. {$info $if 12=12 is ok}
  1166. {$else}
  1167. {$fatal $if 12=12 rejected}
  1168. {$endif}
  1169. {$if 12<>312}
  1170. {$info $if 12<>312 is ok}
  1171. {$else}
  1172. {$fatal $if 12<>312 rejected}
  1173. {$endif}
  1174. {$if 12<=312}
  1175. {$info $if 12<=312 is ok}
  1176. {$else}
  1177. {$fatal $if 12<=312 rejected}
  1178. {$endif}
  1179. {$if 12<312}
  1180. {$info $if 12<312 is ok}
  1181. {$else}
  1182. {$fatal $if 12<312 rejected}
  1183. {$endif}
  1184. {$if a12=a12}
  1185. {$info $if a12=a12 is ok}
  1186. {$else}
  1187. {$fatal $if a12=a12 rejected}
  1188. {$endif}
  1189. {$if a12<=z312}
  1190. {$info $if a12<=z312 is ok}
  1191. {$else}
  1192. {$fatal $if a12<=z312 rejected}
  1193. {$endif}
  1194. {$if a12<z312}
  1195. {$info $if a12<z312 is ok}
  1196. {$else}
  1197. {$fatal $if a12<z312 rejected}
  1198. {$endif}
  1199. {$if not(0)}
  1200. {$info $if not(0) is OK}
  1201. {$else}
  1202. {$fatal $if not(0) rejected}
  1203. {$endif}
  1204. {$info *************************************************}
  1205. {$info * Now have to follow at least 2 error messages: *}
  1206. {$info *************************************************}
  1207. {$if not(0}
  1208. {$endif}
  1209. {$if not(<}
  1210. {$endif}
  1211. end.
  1212. \end{verbatim}
  1213. As you can see from the example, this construct isn't useful when used
  1214. with normal symbols, only if you use macros, which are explained in
  1215. \sees{Macros}. They can be very useful. When trying this example, you must
  1216. switch on macro support, with the \var{-Sm} command-line switch.
  1217. \subsection{Predefined symbols}
  1218. The \fpc compiler defines some symbols before starting to compile your
  1219. program or unit. You can use these symbols to differentiate between
  1220. different versions of the compiler, and between different compilers.
  1221. To get all the possible defines when starting compilation,
  1222. see appendix \ref{ch:AppG}
  1223. \begin{remark}Symbols, even when they're defined in the interface part of
  1224. a unit, are not available outside that unit.
  1225. \end{remark}
  1226. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1227. % Macros
  1228. \section{Messages}
  1229. \label{se:Messages}
  1230. \fpc lets you define normal, warning and error messages in your code.
  1231. Messages can be used to display useful information, such as copyright
  1232. notices, a list of symbols that your code reacts on etc.
  1233. Warnings can be used if you think some part of your code is still buggy, or
  1234. if you think that a certain combination of symbols isn't useful.
  1235. Error messages can be useful if you need a certain symbol to be defined,
  1236. to warn that a certain variable isn't defined, or when the compiler
  1237. version isn't suitable for your code.
  1238. The compiler treats these messages as if they were generated by the
  1239. compiler. This means that if you haven't turned on warning messages, the
  1240. warning will not be displayed. Errors are always displayed, and the
  1241. compiler stops if 50 errors have occurred. After a fatal error, the compiler
  1242. stops at once.
  1243. For messages, the syntax is as follows:
  1244. \begin{verbatim}
  1245. {$Message Message text}
  1246. \end{verbatim}
  1247. or
  1248. \begin{verbatim}
  1249. {$Info Message text}
  1250. \end{verbatim}
  1251. For notes:
  1252. \begin{verbatim}
  1253. {$Note Message text}
  1254. \end{verbatim}
  1255. For warnings:
  1256. \begin{verbatim}
  1257. {$Warning Warning Message text}
  1258. \end{verbatim}
  1259. For errors:
  1260. \begin{verbatim}
  1261. {$Error Error Message text}
  1262. \end{verbatim}
  1263. Lastly, for fatal errors:
  1264. \begin{verbatim}
  1265. {$Fatal Error Message text}
  1266. \end{verbatim}
  1267. or
  1268. \begin{verbatim}
  1269. {$Stop Error Message text}
  1270. \end{verbatim}
  1271. The difference between \var{\$Error} and \var{\$FatalError} or \var{\$Stop}
  1272. messages is that when the compiler encounters an error, it still continues
  1273. to compile. With a fatal error, the compiler stops.
  1274. \begin{remark}You cannot use the '\var{\}}' character in your message, since
  1275. this will be treated as the closing brace of the message.
  1276. \end{remark}
  1277. As an example, the following piece of code will generate an error when
  1278. the symbol \var{RequiredVar} isn't defined:
  1279. \begin{verbatim}
  1280. {$ifndef RequiredVar}
  1281. {$Error Requiredvar isn't defined !}
  1282. {$endif}
  1283. \end{verbatim}
  1284. But the compiler will continue to compile. It will not, however, generate a
  1285. unit file or a program (since an error occurred).
  1286. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1287. % Macros
  1288. \section{Macros}
  1289. \label{se:Macros}
  1290. Macros are very much like symbols in their syntax, the difference is that
  1291. macros have a value whereas a symbol simply is defined or is not defined.
  1292. If you want macro support, you need to specify the \var{-Sm} command-line
  1293. switch, otherwise your macro will be regarded as a symbol.
  1294. Defining a macro in your program is done in the same way as defining a symbol;
  1295. in a \var{\{\$define\}} preprocessor statement\footnote{In compiler
  1296. versions older than 0.9.8, the assignment operator for a macros wasn't
  1297. \var{:=} but \var{=}}:
  1298. \begin{verbatim}
  1299. {$define ident:=expr}
  1300. \end{verbatim}
  1301. If the compiler encounters \var{ident} in the rest of the source file, it
  1302. will be replaced immediately by \var{expr}. This replacement works
  1303. recursive, meaning that when the compiler expanded one of your macros, it
  1304. will look at the resulting expression again to see if another replacement
  1305. can be made. You need to be careful with this, because an infinite loop can
  1306. occur in this manner.
  1307. Here are two examples which illustrate the use of macros:
  1308. \begin{verbatim}
  1309. {$define sum:=a:=a+b;}
  1310. ...
  1311. sum { will be expanded to 'a:=a+b;'
  1312. remark the absence of the semicolon}
  1313. ...
  1314. {$define b:=100}
  1315. sum { Will be expanded recursively to a:=a+100; }
  1316. ...
  1317. \end{verbatim}
  1318. The previous example could go wrong:
  1319. \begin{verbatim}
  1320. {$define sum:=a:=a+b;}
  1321. ...
  1322. sum { will be expanded to 'a:=a+b;'
  1323. remark the absence of the semicolon}
  1324. ...
  1325. {$define b=sum} { DON'T do this !!!}
  1326. sum { Will be infinitely recursively expanded \dots }
  1327. ...
  1328. \end{verbatim}
  1329. On my system, the last example results in a heap error, causing the compiler
  1330. to exit with a run-time error 203.
  1331. \begin{remark}Macros defined in the interface part of a unit are not
  1332. available outside that unit! They can just be used as a notational
  1333. convenience, or in conditional compiles.
  1334. \end{remark}
  1335. By default the compiler predefines three
  1336. macros, containing the version number, the release number and the patch
  1337. number. They are listed in \seet{DefMacros}.
  1338. \begin{FPCltable}{ll}{Predefined macros}{DefMacros} \hline
  1339. Symbol & Contains \\ \hline
  1340. \var{FPC\_VERSION} & The version number of the compiler. \\
  1341. \var{FPC\_RELEASE} & The release number of the compiler. \\
  1342. \var{FPC\_PATCH} & The patch number of the compiler. \\
  1343. \hline
  1344. \end{FPCltable}
  1345. \begin{remark}Don't forget that macros support isn't on by default. You
  1346. need to compile with the \var{-Sm} command-line switch.
  1347. \end{remark}
  1348. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1349. % Using assembly language
  1350. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1351. \chapter{Using Assembly language}
  1352. \label{ch:AsmLang}
  1353. \fpc supports inserting assembler statements in your code. The
  1354. mechanism for this is the same as under Turbo Pascal. There are, however
  1355. some substantial differences, as will be explained in the following
  1356. sections.
  1357. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1358. % 80x86 Assembler syntax
  1359. \section{Intel 80x86 Inline assembler}
  1360. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1361. % Intel syntax
  1362. \subsection{Intel syntax}
  1363. \label{se:Intel}
  1364. \fpc supports Intel syntax for the Intel family of Ix86 processors
  1365. in its \var{asm} blocks.
  1366. The Intel syntax in your \var{asm} block is converted to AT\&T syntax by the
  1367. compiler, after which it is inserted in the compiled source.
  1368. The supported assembler constructs are a subset of the normal assembly
  1369. syntax. In what follows we specify what constructs are not supported in
  1370. \fpc, but which exist in Turbo Pascal:
  1371. \begin{itemize}
  1372. \item The \var{TBYTE} qualifier is not supported.
  1373. \item The \var{\&} identifier override is not supported.
  1374. \item The \var{HIGH} operator is not supported.
  1375. \item The \var{LOW} operator is not supported.
  1376. \item The \var{OFFSET} and \var{SEG} operators are not supported.
  1377. Use \var{LEA} and the various \var{Lxx} instructions instead.
  1378. \item Expressions with constant strings are not allowed.
  1379. \item Access to record fields via parenthesis is not allowed
  1380. \item Typecasts with normal pascal types are not allowed, only
  1381. recognized assembler typecasts are allowed. Example:
  1382. \begin{verbatim}
  1383. mov al, byte ptr MyWord -- allowed,
  1384. mov al, byte(MyWord) -- allowed,
  1385. mov al, shortint(MyWord) -- not allowed.
  1386. \end{verbatim}
  1387. \item Pascal type typecasts on constants are not allowed.
  1388. Example:
  1389. \begin{verbatim}
  1390. const s= 10; const t = 32767;
  1391. \end{verbatim}
  1392. in Turbo Pascal:
  1393. \begin{verbatim}
  1394. mov al, byte(s) -- useless typecast.
  1395. mov al, byte(t) -- syntax error!
  1396. \end{verbatim}
  1397. In this parser, either of those cases will give out a syntax error.
  1398. \item Constant references expressions with constants only are not
  1399. allowed (in all cases they do not work in protected mode,
  1400. under \linux i386). Examples:
  1401. \begin{verbatim}
  1402. mov al,byte ptr ['c'] -- not allowed.
  1403. mov al,byte ptr [100h] -- not allowed.
  1404. \end{verbatim}
  1405. (This is due to the limitation of Turbo Assembler).
  1406. \item Brackets within brackets are not allowed
  1407. \item Expressions with segment overrides fully in brackets are
  1408. presently not supported, but they can easily be implemented
  1409. in BuildReference if requested. Example:
  1410. \begin{verbatim}
  1411. mov al,[ds:bx] -- not allowed
  1412. \end{verbatim}
  1413. use instead:
  1414. \begin{verbatim}
  1415. mov al,ds:[bx]
  1416. \end{verbatim}
  1417. \item Possible allowed indexing are as follows:
  1418. \begin{itemize}
  1419. \item \var{Sreg:[REG+REG*SCALING+/-disp]}
  1420. \item \var{SReg:[REG+/-disp]}
  1421. \item \var{SReg:[REG]}
  1422. \item \var{SReg:[REG+REG+/-disp]}
  1423. \item \var{SReg:[REG+REG*SCALING]}
  1424. \end{itemize}
  1425. Where \var{Sreg} is optional and specifies the segment override.
  1426. {\em Notes:}
  1427. \begin{enumerate}
  1428. \item The order of terms is important contrary to Turbo Pascal.
  1429. \item The Scaling value must be a value, and not an identifier
  1430. to a symbol. Examples:
  1431. \begin{verbatim}
  1432. const myscale = 1;
  1433. ...
  1434. mov al,byte ptr [esi+ebx*myscale] -- not allowed.
  1435. \end{verbatim}
  1436. use:
  1437. \begin{verbatim}
  1438. mov al, byte ptr [esi+ebx*1]
  1439. \end{verbatim}
  1440. \end{enumerate}
  1441. \item Possible variable identifier syntax is as follows:
  1442. (Id = Variable or typed constant identifier.)
  1443. \begin{enumerate}
  1444. \item \var{ID}
  1445. \item \var{[ID]}
  1446. \item \var{[ID+expr]}
  1447. \item \var{ID[expr]}
  1448. \end{enumerate}
  1449. Possible fields are as follow:
  1450. \begin{enumerate}
  1451. \item \var{ID.subfield.subfield \dots}
  1452. \item \var{[ref].ID.subfield.subfield \dots}
  1453. \item \var{[ref].typename.subfield \dots}
  1454. \end{enumerate}
  1455. \item Local abels: Contrary to Turbo Pascal, local labels, must
  1456. at least contain one character after the local symbol indicator.
  1457. Example:
  1458. \begin{verbatim}
  1459. @: -- not allowed
  1460. \end{verbatim}
  1461. use instead, for example:
  1462. \begin{verbatim}
  1463. @1: -- allowed
  1464. \end{verbatim}
  1465. \item Contrary to Turbo Pascal local references cannot be used as references,
  1466. only as displacements. Example:
  1467. \begin{verbatim}
  1468. lds si,@mylabel -- not allowed
  1469. \end{verbatim}
  1470. \item Contrary to Turbo Pascal, \var{SEGCS}, \var{SEGDS}, \var{SEGES} and
  1471. \var{SEGSS} segment overrides are presently not supported.
  1472. (This is a planned addition though).
  1473. \item Contrary to Turbo Pascal where memory sizes specifiers can
  1474. be practically anywhere, the \fpc Intel inline assembler requires
  1475. memory size specifiers to be outside the brackets. Example:
  1476. \begin{verbatim}
  1477. mov al,[byte ptr myvar] -- not allowed.
  1478. \end{verbatim}
  1479. use:
  1480. \begin{verbatim}
  1481. mov al,byte ptr [myvar] -- allowed.
  1482. \end{verbatim}
  1483. \item Base and Index registers must be 32-bit registers.
  1484. (limitation of the GNU Assembler).
  1485. \item \var{XLAT} is equivalent to \var{XLATB}.
  1486. \item Only Single and Double FPU opcodes are supported.
  1487. \item Floating point opcodes are currently not supported
  1488. (except those which involve only floating point registers).
  1489. \end{itemize}
  1490. The Intel inline assembler supports the following macros:
  1491. \begin{description}
  1492. \item [@Result] represents the function result return value.
  1493. \item [Self] represents the object method pointer in methods.
  1494. \end{description}
  1495. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1496. % AT&T syntax
  1497. \subsection{AT\&T Syntax}
  1498. \label{se:AttSyntax}
  1499. \fpc uses the \gnu \var{as} assembler to generate its object files for
  1500. the Intel Ix86 processors. Since
  1501. the \gnu assembler uses AT\&T assembly syntax, the code you write should
  1502. use the same syntax. The differences between AT\&T and Intel syntax as used
  1503. in Turbo Pascal are summarized in the following:
  1504. \begin{itemize}
  1505. \item The opcode names include the size of the operand. In general, one can
  1506. say that the AT\&T opcode name is the Intel opcode name, suffixed with a
  1507. '\var{l}', '\var{w}' or '\var{b}' for, respectively, longint (32 bit),
  1508. word (16 bit) and byte (8 bit) memory or register references. As an example,
  1509. the Intel construct \mbox{'\var{mov al bl}} is equivalent to the AT\&T style '\var{movb
  1510. \%bl,\%al}' instruction.
  1511. \item AT\&T immediate operands are designated with '\$', while Intel syntax
  1512. doesn't use a prefix for immediate operands. Thus the Intel construct
  1513. '\var{mov ax, 2}' becomes '\var{movb \$2, \%al}' in AT\&T syntax.
  1514. \item AT\&T register names are preceded by a '\var{\%}' sign.
  1515. They are undelimited in Intel syntax.
  1516. \item AT\&T indicates absolute jump/call operands with '\var{*}', Intel
  1517. syntax doesn't delimit these addresses.
  1518. \item The order of the source and destination operands are switched. AT\&T
  1519. syntax uses '\var{Source, Dest}', while Intel syntax features '\var{Dest,
  1520. Source}'. Thus the Intel construct '\var{add eax, 4}' transforms to
  1521. '\var{addl \$4, \%eax}' in the AT\&T dialect.
  1522. \item Immediate long jumps are prefixed with the '\var{l}' prefix. Thus the
  1523. Intel '\var{call/jmp section:offset'} is transformed to '\var{lcall/ljmp
  1524. \$section,\$offset}'. Similarly the far return is '\var{lret}', instead of the
  1525. Intel '\var{ret far}'.
  1526. \item Memory references are specified differently in AT\&T and Intel
  1527. assembly. The Intel indirect memory reference
  1528. \begin{quote}
  1529. \var{Section:[Base + Index*Scale + Offs]}
  1530. \end{quote}
  1531. is written in AT\&T syntax as:
  1532. \begin{quote}
  1533. \var{Section:Offs(Base,Index,Scale)}
  1534. \end{quote}
  1535. Where \var{Base} and \var{Index} are optional 32-bit base and index
  1536. registers, and \var{Scale} is used to multiply \var{Index}. It can take the
  1537. values 1,2,4 and 8. The \var{Section} is used to specify an optional section
  1538. register for the memory operand.
  1539. \end{itemize}
  1540. More information about the AT\&T syntax can be found in the \var{as} manual,
  1541. although the following differences with normal AT\&T assembly must be taken
  1542. into account:
  1543. \begin{itemize}
  1544. \item Only the following directives are presently supported:
  1545. \begin{description}
  1546. \item[.byte]
  1547. \item[.word]
  1548. \item[.long]
  1549. \item[.ascii]
  1550. \item[.asciz]
  1551. \item[.globl]
  1552. \end{description}
  1553. \item The following directives are recognized but are not
  1554. supported:
  1555. \begin{description}
  1556. \item[.align]
  1557. \item[.lcomm]
  1558. \end{description}
  1559. Eventually they will be supported.
  1560. \item Directives are case sensitive, other identifiers are not case sensitive.
  1561. \item Contrary to GAS local labels/symbols {\em must} start with \var{.L}
  1562. \item The not operator \var{'!'} is not supported.
  1563. \item String expressions in operands are not supported.
  1564. \item CBTW,CWTL,CWTD and CLTD are not supported, use the normal intel
  1565. equivalents instead.
  1566. \item Constant expressions which represent memory references are not
  1567. allowed even though constant immediate value expressions are supported.
  1568. Examples:
  1569. \begin{verbatim}
  1570. const myid = 10;
  1571. ...
  1572. movl $myid,%eax -- allowed
  1573. movl myid(%esi),%eax -- not allowed.
  1574. \end{verbatim}
  1575. \item When the \var{.globl} directive is found, the symbol following
  1576. it is made public and is immediately emitted.
  1577. Therefore label names with this name will be ignored.
  1578. \item Only Single and Double FPU opcodes are supported.
  1579. \end{itemize}
  1580. The AT\&T inline assembler supports the following macros:
  1581. \begin{description}
  1582. \item [\_\_RESULT] represents the function result return value.
  1583. \item [\_\_SELF] represents the object method pointer in methods.
  1584. \item [\_\_OLDEBP] represents the old base pointer in recusrive routines.
  1585. \end{description}
  1586. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1587. % Motorola 680x0 assembler
  1588. \section{Motorola 680x0 Inline assembler}
  1589. The inline assembler reader for the Motorola 680x0 family of processors,
  1590. uses the Motorola Assembler syntax (q.v). A few differences do exit:
  1591. \begin{itemize}
  1592. \item Local labels start with the @ character, such as
  1593. \begin{verbatim}
  1594. @MyLabel:
  1595. \end{verbatim}
  1596. \item The \var{XDEF} directive in an assembler block will
  1597. make the symbol available publicly with the specified name
  1598. (this name is case sensitive)
  1599. \item The \var{DB}, \var{DW}, \var{DD} directives can only
  1600. be used to declare constants which will be stored in the
  1601. code segment.
  1602. \item The \var{Align} directive is not supported.
  1603. \item Arithmetic operations on constant expression use the same
  1604. operands as the intel version (e.g : \var{AND}, \var{XOR} ...)
  1605. \item Segment directives are not supported
  1606. \item Only 68000 and a subset of 68020 opcodes are currently supported
  1607. \end{itemize}
  1608. The inline assembler supports the following macros:
  1609. \begin{description}
  1610. \item [@Result] represents the function result return value.
  1611. \item [Self] represents the object method pointer in methods.
  1612. \end{description}
  1613. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1614. % Telling the compiler what registers have changed
  1615. \section{Signaling changed registers}
  1616. \label{se:RegChanges}
  1617. When the compiler uses variables, it sometimes stores them, or the result of
  1618. some calculations, in the processor registers. If you insert assembler code
  1619. in your program that modifies the processor registers, then this may
  1620. interfere with the compiler's idea about the registers. To avoid this
  1621. problem, \fpc allows you to tell the compiler which registers have changed.
  1622. The compiler will then avoid using these registers. Telling the compiler
  1623. which registers have changed is done by specifying a set of register names
  1624. behind an assembly block, as follows:
  1625. \begin{verbatim}
  1626. asm
  1627. ...
  1628. end ['R1', ... ,'Rn'];
  1629. \end{verbatim}
  1630. Here \var{R1} to \var{Rn} are the names of the registers you
  1631. modify in your assembly code.
  1632. As an example:
  1633. \begin{verbatim}
  1634. asm
  1635. movl BP,%eax
  1636. movl 4(%eax),%eax
  1637. movl %eax,__RESULT
  1638. end ['EAX'];
  1639. \end{verbatim}
  1640. This example tells the compiler that the \var{EAX} register was modified.
  1641. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1642. % Generated code
  1643. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1644. \chapter{Generated code}
  1645. \label{ch:GenCode}
  1646. The \fpc compiler relies on the assembler to make object files. It generates
  1647. just the assembly language file. In the following two sections, we discuss
  1648. what is generated when you compile a unit or a program.
  1649. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1650. % Units
  1651. \section{Units}
  1652. \label{se:Units}
  1653. When you compile a unit, the \fpc compiler generates 2 files:
  1654. \begin{enumerate}
  1655. \item A unit description file.
  1656. \item An assembly language file.
  1657. \end{enumerate}
  1658. The assembly language file contains the actual source code for the
  1659. statements in your unit, and the necessary memory allocations for any
  1660. variables you use in your unit. This file is converted by the assembler to
  1661. an object file (with extension \file{.o}) which can then be linked to other
  1662. units and your program, to form an executable.
  1663. By default, the assembly file is removed after it has been compiled.
  1664. Only in the case of the \var{-s} command-line option, the assembly file
  1665. will be left on disk, so the assembler can be called later. You can
  1666. disable the erasing of the assembler file with the \var{-a} switch.
  1667. The unit file contains all the information the compiler needs to use the
  1668. unit:
  1669. \begin{enumerate}
  1670. \item Other used units, both in interface and implementation.
  1671. \item Types and variables from the interface section of the unit.
  1672. \item Function declarations from the interface section of the unit.
  1673. \item Some debugging information, when compiled with debugging.
  1674. \end{enumerate}
  1675. The detailed contents and structure of this file are described in the first
  1676. appendix. You can examine a unit description file using the \file{ppudump}
  1677. program, which shows the contents of the file.
  1678. If you want to distribute a unit without source code, you must provide both
  1679. the unit description file and the object file.
  1680. You can also provide a C header file to go with the object file. In that
  1681. case, your unit can be used by someone who wishes to write his programs in
  1682. C. However, you must make this header file yourself since the \fpc compiler
  1683. doesn't make one for you.
  1684. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1685. % Programs
  1686. \section{Programs}
  1687. \label{se:Programs}
  1688. When you compile a program, the compiler produces again 2 files:
  1689. \begin{enumerate}
  1690. \item An assembly language file containing the statements of your program,
  1691. and memory allocations for all used variables.
  1692. \item A linker response file. This file contains a list of object files the
  1693. linker must link together.
  1694. \end{enumerate}
  1695. The link response file is, by default, removed from the disk. Only when you
  1696. specify the \var{-s} command-line option or when linking fails, then the file
  1697. is left on the disk. It is named \file{link.res}.
  1698. The assembly language file is converted to an object file by the assembler,
  1699. and then linked together with the rest of the units and a program header, to
  1700. form your final program.
  1701. The program header file is a small assembly program which provides the entry
  1702. point for the program. This is where the execution of your program starts,
  1703. so it depends on the operating system, because operating systems pass
  1704. parameters to executables in wildly different ways.
  1705. It's name is \file{prt0.o}, and the
  1706. source file resides in \file{prt0.as} or some variant of this name. It
  1707. usually resided where the system unit source for your system resides.
  1708. It's main function is to save the environment and command-line arguments and
  1709. set up the stack. Then it calls the main program.
  1710. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1711. % MMX Support
  1712. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1713. \chapter{Intel MMX support}
  1714. \label{ch:MMXSupport}
  1715. \section{What is it about?}
  1716. \label{se:WhatisMMXabout}
  1717. \fpc supports the new MMX (Multi-Media extensions)
  1718. instructions of Intel processors. The idea of MMX is to
  1719. process multiple data with one instruction, for example the processor
  1720. can add simultaneously 4 words. To implement this efficiently, the
  1721. Pascal language needs to be extended. So Free Pascal allows
  1722. to add for example two \var{array[0..3] of word},
  1723. if MMX support is switched on. The operation is done
  1724. by the \var{MMX} unit and allows people without assembler knowledge to take
  1725. advantage of the MMX extensions.
  1726. Here is an example:
  1727. \begin{verbatim}
  1728. uses
  1729. MMX; { include some predefined data types }
  1730. const
  1731. { tmmxword = array[0..3] of word;, declared by unit MMX }
  1732. w1 : tmmxword = (111,123,432,4356);
  1733. w2 : tmmxword = (4213,63456,756,4);
  1734. var
  1735. w3 : tmmxword;
  1736. l : longint;
  1737. begin
  1738. if is_mmx_cpu then { is_mmx_cpu is exported from unit mmx }
  1739. begin
  1740. {$mmx+} { turn mmx on }
  1741. w3:=w1+w2;
  1742. {$mmx-}
  1743. end
  1744. else
  1745. begin
  1746. for i:=0 to 3 do
  1747. w3[i]:=w1[i]+w2[i];
  1748. end;
  1749. end.
  1750. \end{verbatim}
  1751. \section{Saturation support}
  1752. \label{se:SaturationSupport}
  1753. One important point of MMX is the support of saturated operations.
  1754. If a operation would cause an overflow, the value stays at the
  1755. highest or lowest possible value for the data type:
  1756. If you use byte values you get normally 250+12=6. This is very
  1757. annoying when doing color manipulations or changing audio samples,
  1758. when you have to do a word add and check if the value is greater than
  1759. 255. The solution is saturation: 250+12 gives 255.
  1760. Saturated operations are supported by the \var{MMX} unit. If you
  1761. want to use them, you have simple turn the switch saturation on:
  1762. \var{\$saturation+}
  1763. Here is an example:
  1764. \begin{verbatim}
  1765. Program SaturationDemo;
  1766. {
  1767. example for saturation, scales data (for example audio)
  1768. with 1.5 with rounding to negative infinity
  1769. }
  1770. uses mmx;
  1771. var
  1772. audio1 : tmmxword;
  1773. i: smallint;
  1774. const
  1775. helpdata1 : tmmxword = ($c000,$c000,$c000,$c000);
  1776. helpdata2 : tmmxword = ($8000,$8000,$8000,$8000);
  1777. begin
  1778. { audio1 contains four 16 bit audio samples }
  1779. {$mmx+}
  1780. { convert it to $8000 is defined as zero, multiply data with 0.75 }
  1781. audio1:=(audio1+helpdata2)*(helpdata1);
  1782. {$saturation+}
  1783. { avoid overflows (all values>$7fff becomes $ffff) }
  1784. audio1:=(audio1+helpdata2)-helpdata2;
  1785. {$saturation-}
  1786. { now mupltily with 2 and change to integer }
  1787. for i:=0 to 3 do
  1788. audio1[i] := audio1[i] shl 1;
  1789. audio1:=audio1-helpdata2;
  1790. {$mmx-}
  1791. end.
  1792. \end{verbatim}
  1793. \section{Restrictions of MMX support}
  1794. \label{se:MMXrestrictions}
  1795. In the beginning of 1997 the MMX instructions were introduced in the
  1796. Pentium processors, so multitasking systems wouldn't save the
  1797. newly introduced MMX registers. To work around that problem, Intel
  1798. mapped the MMX registers to the FPU register.
  1799. The consequence is that
  1800. you can't mix MMX and floating point operations. After using
  1801. MMX operations and before using floating point operations, you
  1802. have to call the routine \var{EMMS} of the \var{MMX} unit.
  1803. This routine restores the FPU registers.
  1804. {\em Careful:} The compiler doesn't warn if you mix floating point and
  1805. MMX operations, so be careful.
  1806. The MMX instructions are optimized for multi media (what else?).
  1807. So it isn't possible to perform each operation, some operations
  1808. give a type mismatch, see section \ref{se:SupportedMMX} for the supported
  1809. MMX operations
  1810. An important restriction is that MMX operations aren't range or overflow
  1811. checked, even when you turn range and overflow checking on. This is due to
  1812. the nature of MMX operations.
  1813. The \var{MMX} unit must always be used when doing MMX operations
  1814. because the exit code of this unit clears the MMX unit. If it wouldn't do
  1815. that, other program will crash. A consequence of this is that you can't use
  1816. MMX operations in the exit code of your units or programs, since they would
  1817. interfere with the exit code of the \var{MMX} unit. The compiler can't
  1818. check this, so you are responsible for this!
  1819. \section{Supported MMX operations}
  1820. \label{se:SupportedMMX}
  1821. The following operations are supported in the compiler when MMX
  1822. extensions are enabled:
  1823. \begin{itemize}
  1824. \item addition (\var{+})
  1825. \item subtraction (\var{-})
  1826. \item multiplication(\var{*})
  1827. \item logical exclusive or (\var{xor})
  1828. \item logical and (\var{and})
  1829. \item logical or (\var{or})
  1830. \item sign change (\var{-})
  1831. \end{itemize}
  1832. \section{Optimizing MMX support}
  1833. \label{se:OptimizingMMX}
  1834. Here are some helpful hints to get optimal performance:
  1835. \begin{itemize}
  1836. \item The \var{EMMS} call takes a lot of time, so try to seperate floating
  1837. point and MMX operations.
  1838. \item Use MMX only in low level routines because the compiler
  1839. saves all used MMX registers when calling a subroutine.
  1840. \item The NOT-operator isn't supported natively by MMX, so the
  1841. compiler has to generate a workaround and this operation
  1842. is inefficient.
  1843. \item Simple assignements of floating point numbers don't access
  1844. floating point registers, so you need no call to the \var{EMMS}
  1845. procedure. Only when doing arithmetic, you need to call the \var{EMMS}
  1846. procedure.
  1847. \end{itemize}
  1848. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1849. % Code issues
  1850. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1851. \chapter{Code issues}
  1852. \label{ch:Code}
  1853. This chapter gives detailed information on the generated code by
  1854. \fpc. It can be useful to write external object files which will
  1855. be linked to \fpc created code blocks.
  1856. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1857. % Register conventions
  1858. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1859. \section{Register Conventions}
  1860. \label{se:RegConvs}
  1861. The compiler has different register conventions, depending on the
  1862. target processor used; some of the registers have specific uses
  1863. during the code generation. The following section describes the
  1864. generic names of the registers on a platform per platform basis. It
  1865. also indicates what registers are used as scratch registers, and
  1866. which can be freely used in assembler blocks.
  1867. \subsection{accumulator register}
  1868. The accumulator register is at least a 32-bit integer
  1869. hardware register, and is used to return results of
  1870. function calls which return integral values.
  1871. \subsection{accumulator 64-bit register}
  1872. The accumulator 64-bit register is used in 32-bit environments
  1873. and is defined as the group of registers which will be used when
  1874. returning 64-bit integral results in function calls. This is a
  1875. register pair.
  1876. \subsection{float result register}
  1877. This register is used for returning floating point values
  1878. from functions.
  1879. \subsection{self register}
  1880. The self register contains a pointer to the actual object or class.
  1881. This register gives access to the data of the object or class, and
  1882. the VMT pointer of that object or class.
  1883. \subsection{frame pointer register}
  1884. The frame pointer register is used to access parameters in subroutines,
  1885. as well as to access local variables. References to the pushed
  1886. prameters and local variables are constructed using the frame pointer.
  1887. \footnote{The frame pointer is not available on all platforms}.
  1888. \subsection{stack pointer register}
  1889. The stack pointer is used to give the address of the stack area,
  1890. where the local variables and parameters to subroutines are stored.
  1891. \subsection{scratch registers}
  1892. Scratch registers are those which can be used in assembler
  1893. blocks, or in external object files without requiring any saving
  1894. before usage.
  1895. \subsection{Processor mapping of registers}
  1896. This indicates what registers are used for what purposes
  1897. on each of the processors supported by \fpc. It also indicates
  1898. which registers can be used as scratch registers.
  1899. \subsubsection{Intel 80x86 version}
  1900. \begin{FPCltable}{ll}{Intel 80x86 Register table}{80x86Regs} \hline
  1901. Generic register name & CPU Register name \\ \hline
  1902. accumulator & EAX \\
  1903. accumulator (64-bit) high / low & EDX:EAX \\
  1904. float result & FP(0) \\
  1905. self & ESI \\
  1906. frame pointer & EBP \\
  1907. stack pointer & ESP \\
  1908. scratch regs. & N/A \\
  1909. \end{FPCltable}
  1910. \subsubsection{Motorola 680x0 version}
  1911. \begin{FPCltable}{ll}{Motorola 680x0 Register table}{680x0Regs} \hline
  1912. Generic register name & CPU Register name \\ \hline
  1913. accumulator & D0\footnotemark \\
  1914. accumulator (64-bit) high / low & D0:D1 \\
  1915. float result & FP0\footnotemark\\
  1916. self & A5 \\
  1917. frame pointer & A6 \\
  1918. stack pointer & A7 \\
  1919. scratch regs. & D0, D1, A0, A1, FP0, FP1 \\
  1920. \end{FPCltable}
  1921. \addtocounter{footnote}{-1}\footnotetext{For compatibility with some C compilers, when
  1922. the function result is a pointer and is declared with the cdecl convention,
  1923. the result is also stored in the A0 register}
  1924. \addtocounter{footnote}{1}\footnotetext{On simulated FPU's the result is returned in D0}
  1925. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1926. % Name mangling
  1927. \section{Name mangling}
  1928. \label{se:NameMangling}
  1929. Contrary to most C compilers and assemblers, all labels generated
  1930. to pascal variables and routines have mangled names\footnote{This can be avoided
  1931. by using the \var{alias} or \var{cdecl} modifiers}. This
  1932. is done so that the compiler can do stronger type checking when parsing
  1933. the pascal code. It also permits function and procedure overloading.
  1934. \subsection{Mangled names for data blocks}
  1935. The rules for mangled names for variables and typed constants
  1936. are as follows:
  1937. \begin{itemize}
  1938. \item All variable names are converted to upper case
  1939. \item Variables in the main program or private to a unit have an \_ prepended to their names
  1940. \item Typed constants in the main program have an TC\_\_ prepended to their names
  1941. \item Public variables in a unit have their unit name prepended to them : U\_UNITNAME\_
  1942. \item Public and private typed constants in a unit have their unit name prepended to them :TC\_\_UNITNAME\$\$
  1943. \end{itemize}
  1944. Currently, in \fpc v1.0, if you declare a variable in unit name \var{tunit},
  1945. with the name \var{\_a}, and you declare the same variable with name \var{a}
  1946. in unit name \var{tunit\_}, you will get the same mangled name. This is
  1947. a limitation of the compiler which will be fixed in release v1.1.
  1948. Examples
  1949. \begin{verbatim}
  1950. unit testvars;
  1951. interface
  1952. const
  1953. publictypedconst : integer = 0;
  1954. var
  1955. publicvar : integer;
  1956. implementation
  1957. const
  1958. privatetypedconst : integer = 1;
  1959. var
  1960. privatevar : integer;
  1961. end.
  1962. \end{verbatim}
  1963. Will give the following assembler output under GNU as :
  1964. \begin{verbatim}
  1965. .file "testvars.pas"
  1966. .text
  1967. .data
  1968. # [6] publictypedconst : integer = 0;
  1969. .globl TC__TESTVARS$$_PUBLICTYPEDCONST
  1970. TC__TESTVARS$$_PUBLICTYPEDCONST:
  1971. .short 0
  1972. # [12] privatetypedconst : integer = 1;
  1973. TC__TESTVARS$$_PRIVATETYPEDCONST:
  1974. .short 1
  1975. .bss
  1976. # [8] publicvar : integer;
  1977. .comm U_TESTVARS_PUBLICVAR,2
  1978. # [14] privatevar : integer;
  1979. .lcomm _PRIVATEVAR,2
  1980. \end{verbatim}
  1981. \subsection{Mangled names for code blocks}
  1982. The rules for mangled names for routines are as follows:
  1983. \begin{itemize}
  1984. \item All routine names are converted to upper case.
  1985. \item Routines in a unit have their unit name prepended to them : \_UNITNAME\$\$\_
  1986. \item All Routines in the main program have a \_ prepended to them.
  1987. \item All parameters in a routine are mangled using the type of the parameter
  1988. (in uppercase) prepended by the \$ character. This is done in left to right order
  1989. for each parameter of the routine.
  1990. \item Objects and classes use special mangling : The class type or object type
  1991. is given in the mangled name; The mangled name is as follows: \_\$\$\_TYPEDECL\_\$\$
  1992. optionally preceded by mangled name of the unit and finishing with the method
  1993. name.
  1994. \end{itemize}
  1995. The following constructs
  1996. \begin{verbatim}
  1997. unit testman;
  1998. interface
  1999. type
  2000. myobject = object
  2001. constructor init;
  2002. procedure mymethod;
  2003. end;
  2004. implementation
  2005. constructor myobject.init;
  2006. begin
  2007. end;
  2008. procedure myobject.mymethod;
  2009. begin
  2010. end;
  2011. function myfunc: pointer;
  2012. begin
  2013. end;
  2014. procedure myprocedure(var x: integer; y: longint; z : pchar);
  2015. begin
  2016. end;
  2017. end.
  2018. \end{verbatim}
  2019. will result in the following assembler file for the Intel 80x86 target:
  2020. \begin{verbatim}
  2021. .file "testman.pas"
  2022. .text
  2023. .balign 16
  2024. .globl _TESTMAN$$_$$_MYOBJECT_$$_INIT
  2025. _TESTMAN$$_$$_MYOBJECT_$$_INIT:
  2026. pushl %ebp
  2027. movl %esp,%ebp
  2028. subl $4,%esp
  2029. movl $0,%edi
  2030. call FPC_HELP_CONSTRUCTOR
  2031. jz .L5
  2032. jmp .L7
  2033. .L5:
  2034. movl 12(%ebp),%esi
  2035. movl $0,%edi
  2036. call FPC_HELP_FAIL
  2037. .L7:
  2038. movl %esi,%eax
  2039. testl %esi,%esi
  2040. leave
  2041. ret $8
  2042. .balign 16
  2043. .globl _TESTMAN$$_$$_MYOBJECT_$$_MYMETHOD
  2044. _TESTMAN$$_$$_MYOBJECT_$$_MYMETHOD:
  2045. pushl %ebp
  2046. movl %esp,%ebp
  2047. leave
  2048. ret $4
  2049. .balign 16
  2050. _TESTMAN$$_MYFUNC:
  2051. pushl %ebp
  2052. movl %esp,%ebp
  2053. subl $4,%esp
  2054. movl -4(%ebp),%eax
  2055. leave
  2056. ret
  2057. .balign 16
  2058. _TESTMAN$$_MYPROCEDURE$INTEGER$LONGINT$PCHAR:
  2059. pushl %ebp
  2060. movl %esp,%ebp
  2061. leave
  2062. ret $12
  2063. \end{verbatim}
  2064. \subsection{Modifying the mangled names}
  2065. To make the symbols externally accessible, it is possible to
  2066. give nicknames to mangled names, or to change the mangled
  2067. name directly. Two modifiers can be used:
  2068. \begin{description}
  2069. \item [cdecl:\ ] A function that has a \var{cdecl} modifier, will be used
  2070. with C calling conventions, that is, the caller clears the stack. Also
  2071. the mangled name will be the name {\em exactly} as it is declared.
  2072. \var{cdecl} is part of the function declaration, and hence must be present
  2073. both in the interface and implementation section of a unit.
  2074. \item [alias: ] The \var{alias} modifier can be used to assign a second
  2075. assembler label to your function. This label has the same name as the
  2076. alias name you declared. This doesn't modify the calling conventions
  2077. of the function. In other words, the \var{alias} modifier allows you to specify
  2078. another name (a nickname) for your function or procedure.
  2079. The prototype for an aliased function or procedure is as follows:
  2080. \begin{verbatim}
  2081. Procedure AliasedProc; alias : 'AliasName';
  2082. \end{verbatim}
  2083. The procedure \var{AliasedProc} will also be known as \var{AliasName}. Take
  2084. care, the name you specify is case sensitive (as C is).
  2085. \end{description}
  2086. Furthermore, the \var{exports} section of a library is also used to
  2087. declare the names that will be exported by the shared library. The
  2088. names in the exports section are case-sensitive (while the actual
  2089. declaration of the routine is not). For more information on the
  2090. creating shared libraries, \seec{libraries}.
  2091. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2092. % Calling mechanism
  2093. \section{Calling mechanism}
  2094. \label{se:CallingConventions}
  2095. Procedures and Functions are called with their parameters on the stack.
  2096. Contrary to Turbo Pascal, {\em all} parameters are pushed on the stack, and
  2097. they are pushed {\em right} to {\em left}, instead of left to right for
  2098. Turbo Pascal. This is especially important if you have some assembly
  2099. subroutines in Turbo Pascal which you would like to translate to \fpc.
  2100. Function results are returned in the accumulator, if they fit in the
  2101. register. Methods calls (from either objects or clases) have an additional
  2102. invisible parameter which is \var{self}. This parameter is the leftmost
  2103. parameter within a method call (it is therefore the last parameter passed
  2104. to the method).
  2105. When the procedure or function exits, it clears the stack.
  2106. Other calling methods are available for linking with
  2107. external object files and libraries, these are summarized in \seet{CallingTable}.
  2108. The first column lists the modifier you specify for a procedure declaration.
  2109. The second one lists the order the paramaters are pushed on the stack.
  2110. The third column specifies who is responsible for cleaning the stack:
  2111. the caller or the called function. The alignment column indicates the
  2112. alignment of the parameters sent to the stack area. Finally, the fifth
  2113. column indicates if any registers are saved in the entry code of the
  2114. subroutine.
  2115. \begin{FPCltable}{lllll}{Calling mechanisms in \fpc}{CallingTable}\hline
  2116. Modifier & Pushing order & Stack cleaned by & alignment & registers saved \\
  2117. \hline
  2118. <none> & Right-to-left & Function & default & None\\
  2119. cdecl & Right-to-left & Caller & GCC alignment & GCC registers\\
  2120. interrupt & Right-to-left & Function & default & all registers\\
  2121. pascal & Left-to-right & Function & default & None\\
  2122. safecall & Right-to-left & Function & default & GCC registers\\
  2123. stdcall & Right-to-left & Function & GCC alignment & GCC registers \\
  2124. popstack & Right-to-left & Caller & default & None \\
  2125. register & Left-to-right & Caller & default & None \\ \hline
  2126. \end{FPCltable}
  2127. More about this can be found in \seec{Linking} on linking. Information
  2128. on GCC registers saved, GCC stack alignment and general stack alignment
  2129. on an operating system basis can be found in Appendix \ref{ch:AppH}. The \var{register}
  2130. modifier is currently not supported, and maps to the default calling
  2131. convention.
  2132. Furthermore, the \var{saveregisters} modifier can be used with
  2133. any of the calling mechanism specifiers. When \var{saveregisters}
  2134. is used, all registers will be saved on entry to the routine,
  2135. and will be restored upon exit. Of course, if the routine is
  2136. a function, and it normally returns its retun value in a register,
  2137. that register will not be saved. Also, if the self register is
  2138. used, it will also neither be saved nor restored.
  2139. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2140. % Nested subroutines
  2141. \section{Nested procedure and functions}
  2142. \label{se:NestedRoutines}
  2143. When a routine is declared within the scope of a procedure or
  2144. function, it is said to be nested. In this case, an additional
  2145. invisible parameter is passed to the nested routine. This
  2146. additional parameter is the frame pointer address of the
  2147. calling routine. This permits the nested routine to access
  2148. the local variables and parameters of the calling routine.
  2149. The resulting stack frame after the entry code of a simple nested procedure
  2150. has been executed is shown in \seet{NestedStackFrame32}.
  2151. \begin{FPCltable}{ll}{Stack frame when calling a nested procedure (32-bit processors)}{NestedStackFrame32}
  2152. \hline
  2153. Offset from frame pointer & What is stored \\ \hline
  2154. +x & parameters\\
  2155. +8 & Frame pointer of parent routine\\
  2156. +4 & Return address\\
  2157. +0 & Saved frame pointer\\ \hline
  2158. \end{FPCltable}
  2159. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2160. % Constructor and destructor calls
  2161. \section{Constructor and Destructor calls}
  2162. \label{se:ConsDest}
  2163. Constructor and destructors have special invisible parameters
  2164. which are passed to them. These invisible parameters are used
  2165. internally to instanciate the objects and classes.
  2166. \subsection{objects}
  2167. The actual invisible declaration of an object constructoir
  2168. is as follows:
  2169. \begin{verbatim}
  2170. constructor init(_vmt : pointer; _self : pointer ...);
  2171. \end{verbatim}
  2172. Where \var{\_vmt} is a pointer to the virtual method table
  2173. for this object. This value is nil if a constructor is called
  2174. within the object instance (such as calling an ihnerited constructor).
  2175. \var{\_self} is either nil if the instance must be allocated
  2176. dynamically (object is declared as pointer), or the address of
  2177. the object instance if the object is declared as a normal object
  2178. (stored in the data area) or if the object instance has already
  2179. been allocated.
  2180. The allocated instance (if allocated via new) (\var{self})
  2181. is returned in the accumulator.
  2182. The declaration of a destructor is as follows:
  2183. \begin{verbatim}
  2184. destructor done(_vmt : pointer; _self : pointer ...);
  2185. \end{verbatim}
  2186. Where \var{\_vmt} is a pointer to the virtual method table
  2187. for this object. This value is nil if a destructor is called
  2188. within the object instance (such as calling an ihnerited constructor),
  2189. or if the object instance is a variable and not a pointer.
  2190. \var{\_self} is the address of the object instance.
  2191. \subsection{classes}
  2192. The actual invisible declaration of a class constructoir
  2193. is as follows:
  2194. \begin{verbatim}
  2195. constructor init(_vmt: pointer; flag : longint; ..);
  2196. \end{verbatim}
  2197. \var{\_vmt} is either nil if called from the instance
  2198. or if calling an inherited constructor, otherwise
  2199. it points to the address of the virtual method table.
  2200. Where \var{flag} is zero if the constructor is called
  2201. within the object instance or with an instance qualifier
  2202. otherwise this flag is set to one.
  2203. The allocated instance (\var{self}) is returned in the accumulator.
  2204. The declaration of a destructor is as follows:
  2205. \begin{verbatim}
  2206. destructor done(_self : pointer; flag : longint ...);
  2207. \end{verbatim}
  2208. \var{\_self} is the address of the object instance.
  2209. \var{flag} is zero if the destructor is called
  2210. within the object instance or with an instance qualifier
  2211. otherwise this flag is set to one.
  2212. \section{Entry and exit code}
  2213. Each Pascal procedure and function begins and ends with standard
  2214. epilogue and prologue code.
  2215. \subsection{Intel 80x86 standard routine prologue / epilogue}
  2216. Standard entry code for procedures and functions is as follows on the
  2217. 80x86 architecture:
  2218. \begin{verbatim}
  2219. pushl %ebp
  2220. movl %esp,%ebp
  2221. \end{verbatim}
  2222. The generated exit sequence for procedure and functions looks as follows:
  2223. \begin{verbatim}
  2224. leave
  2225. ret $xx
  2226. \end{verbatim}
  2227. Where \var{xx} is the total size of the pushed parameters.
  2228. To have more information on function return values take a look at
  2229. \sees{RegConvs}.
  2230. \subsection{Motorola 680x0 standard routine prologue / epilogue}
  2231. Standard entry code for procedures and functions is as follows on the
  2232. 680x0 architecture:
  2233. \begin{verbatim}
  2234. move.l a6,-(sp)
  2235. move.l sp,a6
  2236. \end{verbatim}
  2237. The generated exit sequence for procedure and functions looks as follows
  2238. (in the default processor mode):
  2239. \begin{verbatim}
  2240. unlk a6
  2241. rtd #xx
  2242. \end{verbatim}
  2243. Where \var{xx} is the total size of the pushed parameters.
  2244. To have more information on function return values take a look at
  2245. \sees{RegConvs}.
  2246. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2247. % Parameter passing
  2248. \section{Parameter passing}
  2249. \label{se:Parameters}
  2250. When a function or procedure is called, then the following is done by the
  2251. compiler:
  2252. \begin{enumerate}
  2253. \item If there are any parameters to be passed to the procedure, they are
  2254. pushed from right to left on the stack.
  2255. \item If a function is called that returns a variable of type \var{String},
  2256. \var{Set}, \var{Record}, \var{Object} or \var{Array}, then an address to
  2257. store the function result in, is pushed on the stack.
  2258. \item If the called procedure or function is an object method, then the
  2259. pointer to \var{self} is pushed on the stack.
  2260. \item If the procedure or function is nested in another function or
  2261. procedure, then the frame pointer of the parent procedure is pushed on the
  2262. stack.
  2263. \item The return address is pushed on the stack (This is done automatically
  2264. by the instruction which calls the subroutine).
  2265. \end{enumerate}
  2266. The resulting stack frame upon entering looks as in \seet{StackFrame}.
  2267. \begin{FPCltable}{llc}{Stack frame when calling a procedure (32-bit model)}{StackFrame}
  2268. \hline
  2269. Offset & What is stored & Optional? \\ \hline
  2270. +x & parameters & Yes \\
  2271. +12 & function result & Yes \\
  2272. +8 & self & Yes \\
  2273. +4 & Return address & No\\
  2274. +0 & Frame pointer of parent procedure & Yes \\ \hline
  2275. \end{FPCltable}
  2276. \subsection{Parameter alignment}
  2277. Each parameter passed to a routine is guaranteed to decrement the
  2278. stack pointer by a certain minimum amount. This behavior varies
  2279. from one operating system to another. For example, passing a
  2280. byte as a value parameter to a routine could either decrement the
  2281. stack pointer by 1, 2, 4 or even 8 bytes depending on the target
  2282. operating system and processor. The minimal default stack pointer decrement
  2283. value is given in Appendix \ref{ch:AppH}.
  2284. For example, on \freebsd, all parameters passed to a routine guarantee
  2285. a minimal stack decrease of four bytes per parameter, even if the
  2286. parameter actually takes less then 4 bytes to store on the stack (such
  2287. as passing a byte value parameter to the stack).
  2288. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2289. \section{Processor limitations}
  2290. \label{se:ProcessorLimits}
  2291. Certain processors have limitations on the size of the parameters
  2292. and local variables in routines. This is shown in \seet{CPULimits}.
  2293. \begin{FPCltable}{lll}{Maximum limits for processors}{CPULimits}
  2294. \hline
  2295. Processor & Parameters & Local variables \\ \hline
  2296. Intel 80x86 (all) & 64K & No limit\\
  2297. Motorola 68020 (default) & 32K & No limit\\
  2298. Motorola 68000 & 32K & 32K \\ \hline
  2299. \end{FPCltable}
  2300. Furthermore, the m68k compiler, in \var{68000} mode, limits the
  2301. size of data elements to 32K (arrays, records, objects, etc.).
  2302. This restriction does not exist in \var{68020} mode.
  2303. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2304. % Local variables
  2305. %\section{Local variables}
  2306. %\label{se:LocalVars}
  2307. %
  2308. % Stack alignment for local variables to complete -
  2309. % Currently the FPC version 1.0 stack alignment is
  2310. % simply too messy to describe consistently.
  2311. %
  2312. %
  2313. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2314. % Linking issues
  2315. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2316. \chapter{Linking issues}
  2317. \label{ch:Linking}
  2318. When you only use Pascal code, and Pascal units, then you will not see much
  2319. of the part that the linker plays in creating your executable.
  2320. The linker is only called when you compile a program. When compiling units,
  2321. the linker isn't invoked.
  2322. However, there are times that linking to C libraries, or to external
  2323. object files created by other compilers may be necessary. The \fpc compiler
  2324. can generate calls to a C function, and can generate functions that can
  2325. be called from C (exported functions).
  2326. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2327. % Using external code or variables
  2328. \section{Using external code and variables}
  2329. In general, there are 3 things you must do to use a function that resides in
  2330. an external library or object file:
  2331. \begin{enumerate}
  2332. \item You must make a pascal declaration of the function or procedure you
  2333. want to use.
  2334. \item You must declare the correct calling convention to use.
  2335. \item You must tell the compiler where the function resides, i.e. in what
  2336. object file or what library, so the compiler can link the necessary code in.
  2337. \end{enumerate}
  2338. The same holds for variables. To access a variable that resides in an
  2339. external object file, you must declare it, and tell the compiler where to
  2340. find it.
  2341. The following sections attempt to explain how to do this.
  2342. \subsection{Declaring external functions or procedures}
  2343. \label{se:ExternalFunction}
  2344. The first step in using external code blocks is declaring the function you
  2345. want to use. \fpc supports Delphi syntax, i.e. you must use the
  2346. \var{external} directive. The \var{external} directive replaces, in effect,
  2347. the code block of the function.
  2348. The external directive doesn't specify a calling convention; it just tells
  2349. the compiler that the code for a procedure or function resides in an
  2350. external code block. A calling convention modifier should be declared
  2351. if the external code blocks does not have the same calling conventions
  2352. as \fpc. For more information on the calling conventions
  2353. \sees{CallingConventions}.
  2354. There exist four variants of the external directive:
  2355. \begin{enumerate}
  2356. \item A simple external declaration:
  2357. \begin{verbatim}
  2358. Procedure ProcName (Args : TPRocArgs); external;
  2359. \end{verbatim}
  2360. The \var{external} directive tells the compiler that the function resides in
  2361. an external block of code. You can use this together with the \var{\{\$L\}}
  2362. or \var{\{\$LinkLib\}} directives to link to a function or procedure in a
  2363. library or external object file. Object files are looked for in the object
  2364. search path (set by \var{-Fo}) and libraries are searched for in the linker
  2365. path (set by \var{-Fl}).
  2366. \item You can give the \var{external} directive a library name as an
  2367. argument:
  2368. \begin{verbatim}
  2369. Procedure ProcName (Args : TPRocArgs); external 'Name';
  2370. \end{verbatim}
  2371. This tells the compiler that the procedure resides in a library with name
  2372. \var{'Name'}. This method is equivalent to the following:
  2373. \begin{verbatim}
  2374. Procedure ProcName (Args : TPRocArgs);external;
  2375. {$LinkLib 'Name'}
  2376. \end{verbatim}
  2377. \item The \var{external} can also be used with two arguments:
  2378. \begin{verbatim}
  2379. Procedure ProcName (Args : TPRocArgs); external 'Name'
  2380. name 'OtherProcName';
  2381. \end{verbatim}
  2382. This has the same meaning as the previous declaration, only the compiler
  2383. will use the name \var{'OtherProcName'} when linking to the library. This
  2384. can be used to give different names to procedures and functions in an
  2385. external library. The name of the routine is case-sensitive and should
  2386. match exactly the name of the routine in the object file.
  2387. This method is equivalent to the following code:
  2388. \begin{verbatim}
  2389. Procedure OtherProcName (Args : TProcArgs); external;
  2390. {$LinkLib 'Name'}
  2391. Procedure ProcName (Args : TPRocArgs);
  2392. begin
  2393. OtherProcName (Args);
  2394. end;
  2395. \end{verbatim}
  2396. \item Lastly, onder \windows and \ostwo, there is a fourth possibility
  2397. to specify an external function: In \file{.DLL} files, functions also have
  2398. a unique number (their index). It is possible to refer to these fuctions
  2399. using their index:
  2400. \begin{verbatim}
  2401. Procedure ProcName (Args : TPRocArgs); external 'Name' Index SomeIndex;
  2402. \end{verbatim}
  2403. This tells the compiler that the procedure \var{ProcName} resides in a
  2404. dynamic link library, with index {SomeIndex}.
  2405. \begin{remark}Note that this is ONLY available under \windows and \ostwo.
  2406. \end{remark}
  2407. \end{enumerate}
  2408. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2409. % Declaring an external variable
  2410. \subsection{Declaring external variables}
  2411. \label{se:ExternalVars}
  2412. Some libaries or code blocks have variables which they export. You can access
  2413. these variables much in the same way as external functions. To access an
  2414. external variable, you declare it as follows:
  2415. \begin{verbatim}
  2416. Var
  2417. MyVar : MyType; external name 'varname';
  2418. \end{verbatim}
  2419. The effect of this declaration is twofold:
  2420. \begin{enumerate}
  2421. \item No space is allocated for this variable.
  2422. \item The name of the variable used in the assembler code is \var{varname}.
  2423. This is a case sensitive name, so you must be careful.
  2424. \end{enumerate}
  2425. The variable will be
  2426. accessible with it's declared name, i.e. \var{MyVar} in this case.
  2427. A second possibility is the declaration:
  2428. \begin{verbatim}
  2429. Var
  2430. varname : MyType; cvar; external;
  2431. \end{verbatim}
  2432. The effect of this declaration is twofold as in the previous case:
  2433. \begin{enumerate}
  2434. \item The \var{external} modifier ensures that no space is allocated for
  2435. this variable.
  2436. \item The \var{cvar} modifier tells the compiler that the name of the
  2437. variable used in the assembler code is exactly as specified in the
  2438. declaration. This is a case sensitive name, so you must be careful.
  2439. \end{enumerate}
  2440. The first possibility allows you to change the name of the
  2441. external variable for internal use.
  2442. As an example, let's look at the following C file (in \file{extvar.c}):
  2443. \begin{verbatim}
  2444. /*
  2445. Declare a variable, allocate storage
  2446. */
  2447. int extvar = 12;
  2448. \end{verbatim}
  2449. And the following program (in \file{extdemo.pp}):
  2450. \begin{verbatim}
  2451. Program ExtDemo;
  2452. {$L extvar.o}
  2453. Var { Case sensitive declaration !! }
  2454. extvar : longint; cvar;external;
  2455. I : longint; external name 'extvar';
  2456. begin
  2457. { Extvar can be used case insensitive !! }
  2458. Writeln ('Variable ''extvar'' has value: ',ExtVar);
  2459. Writeln ('Variable ''I'' has value: ',i);
  2460. end.
  2461. \end{verbatim}
  2462. Compiling the C file, and the pascal program:
  2463. \begin{verbatim}
  2464. gcc -c -o extvar.o extvar.c
  2465. ppc386 -Sv extdemo
  2466. \end{verbatim}
  2467. Will produce a program \file{extdemo} which will print
  2468. \begin{verbatim}
  2469. Variable 'extvar' has value: 12
  2470. Variable 'I' has value: 12
  2471. \end{verbatim}
  2472. on your screen.
  2473. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2474. % Declaring the calling conventions
  2475. \subsection{Declaring the calling convention modifier}
  2476. To make sure that all parameters are correctly passed to the
  2477. external routines, you should declare it with the correct
  2478. calling convention modifier. When linking with code blocks
  2479. compiled with standard C compilers (such as GCC), the \var{cdecl}
  2480. modifier should be used so as to indicate that the external
  2481. routine uses C type calling conventions. For more information
  2482. on the supported calling conventions, \sees{CallingConventions}.
  2483. As might expected, external variable declarations do not require
  2484. any calling convention modifier.
  2485. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2486. % Linking an object file in your program
  2487. \subsection{Declaring the external object code}
  2488. \subsubsection{Linking to an object file}
  2489. \label{se:LinkIn}
  2490. Having declared the external function or variable that resides in an object file,
  2491. you can use it as if it was defined in your own program or unit.
  2492. To produce an executable, you must still link the object file in.
  2493. This can be done with the \var{\{\$L file.o\}} directive.
  2494. This will cause the linker to link in the object file \file{file.o}. On
  2495. most systems, this filename is case sensitive. The object file is
  2496. first searched in the current directory, and then the directories specified
  2497. by the \var{-Fo} command line.
  2498. You cannot specify libraries in this way, it is for object files only.
  2499. Here we present an example. Consider that you have some assembly routine which uses
  2500. the C calling convention that calculates the nth Fibonacci number:
  2501. \begin{verbatim}
  2502. .text
  2503. .align 4
  2504. .globl Fibonacci
  2505. .type Fibonacci,@function
  2506. Fibonacci:
  2507. pushl %ebp
  2508. movl %esp,%ebp
  2509. movl 8(%ebp),%edx
  2510. xorl %ecx,%ecx
  2511. xorl %eax,%eax
  2512. movl $1,%ebx
  2513. incl %edx
  2514. loop:
  2515. decl %edx
  2516. je endloop
  2517. movl %ecx,%eax
  2518. addl %ebx,%eax
  2519. movl %ebx,%ecx
  2520. movl %eax,%ebx
  2521. jmp loop
  2522. endloop:
  2523. movl %ebp,%esp
  2524. popl %ebp
  2525. ret
  2526. \end{verbatim}
  2527. Then you can call this function with the following Pascal Program:
  2528. \begin{verbatim}
  2529. Program FibonacciDemo;
  2530. var i : longint;
  2531. Function Fibonacci (L : longint):longint;cdecl;external;
  2532. {$L fib.o}
  2533. begin
  2534. For I:=1 to 40 do
  2535. writeln ('Fib(',i,') : ',Fibonacci (i));
  2536. end.
  2537. \end{verbatim}
  2538. With just two commands, this can be made into a program:
  2539. \begin{verbatim}
  2540. as -o fib.o fib.s
  2541. ppc386 fibo.pp
  2542. \end{verbatim}
  2543. This example supposes that you have your assembler routine in \file{fib.s},
  2544. and your Pascal program in \file{fibo.pp}.
  2545. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2546. % Linking your program to a library
  2547. \subsubsection{Linking to a library}
  2548. \label{se:LinkOut}
  2549. To link your program to a library, the procedure depends on how you declared
  2550. the external procedure.
  2551. In case you used the following syntax to declare your procedure:
  2552. \begin{verbatim}
  2553. Procedure ProcName (Args : TPRocArgs); external 'Name';
  2554. \end{verbatim}
  2555. You don't need to take additional steps to link your file in, the compiler
  2556. will do all that is needed for you. On \windows it will link to
  2557. \file{name.dll}, on \linux and most \unix'es your program will be linked to library
  2558. \file{libname}, which can be a static or dynamic library.
  2559. In case you used
  2560. \begin{verbatim}
  2561. Procedure ProcName (Args : TPRocArgs); external;
  2562. \end{verbatim}
  2563. You still need to explicity link to the library. This can be done in 2 ways:
  2564. \begin{enumerate}
  2565. \item You can tell the compiler in the source file what library to link to
  2566. using the \var{\{\$LinkLib 'Name'\}} directive:
  2567. \begin{verbatim}
  2568. {$LinkLib 'gpm'}
  2569. \end{verbatim}
  2570. This will link to the \file{gpm} library. On \unix systems (such as \linux),
  2571. you must not specify the extension or 'lib' prefix of the library. The compiler takes
  2572. care of that. On other systems (such as \windows, you need to specify the full
  2573. name.
  2574. \item You can also tell the compiler on the command-line to link in a
  2575. library: The \var{-k} option can be used for that. For example
  2576. \begin{verbatim}
  2577. ppc386 -k'-lgpm' myprog.pp
  2578. \end{verbatim}
  2579. Is equivalent to the above method, and tells the linker to link to the
  2580. \file{gpm} library.
  2581. \end{enumerate}
  2582. As an example; consider the following program:
  2583. \begin{verbatim}
  2584. program printlength;
  2585. {$linklib c} { Case sensitive }
  2586. { Declaration for the standard C function strlen }
  2587. Function strlen (P : pchar) : longint; cdecl;external;
  2588. begin
  2589. Writeln (strlen('Programming is easy !'));
  2590. end.
  2591. \end{verbatim}
  2592. This program can be compiled with:
  2593. \begin{verbatim}
  2594. ppc386 prlen.pp
  2595. \end{verbatim}
  2596. Supposing, of course, that the program source resides in \file{prlen.pp}.
  2597. To use functions in C that have a variable number of arguments, you must
  2598. compile your unit or program in \var{objfpc} mode or \var{Delphi} mode,
  2599. and use the \var{Array of const} argument, as in the following example:
  2600. \begin{verbatim}
  2601. program testaocc;
  2602. {$mode objfpc}
  2603. Const
  2604. P : Pchar
  2605. = 'example';
  2606. F : Pchar
  2607. = 'This %s uses printf to print numbers (%d) and strings.'#10;
  2608. procedure printf(fm: pchar;args: array of const);cdecl;external 'c';
  2609. begin
  2610. printf(F,[P,123]);
  2611. end.
  2612. \end{verbatim}
  2613. The output of this program looks like this:
  2614. \begin{verbatim}
  2615. This example uses printf to print numbers (123) and strings.
  2616. \end{verbatim}
  2617. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2618. % Making a library
  2619. \section{Making libraries}
  2620. \label{se:StaticLib}
  2621. \fpc supports making shared or static libraries in a straightforward and
  2622. easy manner. If you want to make static libraries for other \fpc programmers,
  2623. you just need to provide a command line switch. To make shared libraries,
  2624. refer to the \seec{libraries}. If you want C programmers to be able to use your
  2625. code as well, you will need to adapt your code a little. This process
  2626. is described first.
  2627. % Exporting functions.
  2628. \subsection{Exporting functions}
  2629. When exporting functions from a library, there are 2 things you must take in
  2630. account:
  2631. \begin{enumerate}
  2632. \item Calling conventions.
  2633. \item Naming scheme.
  2634. \end{enumerate}
  2635. The calling conventions are controlled by the modifiers \var{cdecl},
  2636. \var{popstack}, \var{pascal}, \var{safecall}, \var{stdcall} and
  2637. \var{register}. See \sees{CallingConventions} for more information on the
  2638. different kinds of calling scheme.
  2639. The naming conventions can be controlled by 2 modifiers in the case
  2640. of static libraries:
  2641. \begin{itemize}
  2642. \item \var{cdecl}
  2643. \item \var{alias}
  2644. \end{itemize}
  2645. For more information on how these different modifiers change the name
  2646. mangling of the routine \sees{NameMangling}.
  2647. \begin{remark}If you use in your unit functions that are in other units, or
  2648. system functions, then the C program will need to link in the object files
  2649. from these units too.
  2650. \end{remark}
  2651. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2652. % Exporting variables.
  2653. \subsection{Exporting variables}
  2654. Similarly as when you export functions, you can export variables.
  2655. When exportig variables, one should only consider the names of the
  2656. variables. To declare a variable that should be used by a C program,
  2657. one declares it with the \var{cvar} modifier:
  2658. \begin{verbatim}
  2659. Var MyVar : MyTpe; cvar;
  2660. \end{verbatim}
  2661. This will tell the compiler that the assembler name of the variable (the one
  2662. which is used by C programs) should be exactly as specified in the
  2663. declaration, i.e., case sensitive.
  2664. It is not allowed to declare multiple variables as \var{cvar} in one
  2665. statement, i.e. the following code will produce an error:
  2666. \begin{verbatim}
  2667. var Z1,Z2 : longint;cvar;
  2668. \end{verbatim}
  2669. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2670. % Compiling libraries
  2671. \subsection {Compiling libraries}
  2672. Once you have your (adapted) code, with exported and other functions,
  2673. you can compile your unit, and tell the compiler to make it into a library.
  2674. The compiler will simply compile your unit, and perform the necessary steps
  2675. to transform it into a \var{static} or \var{shared} (\var{dynamic}) library.
  2676. You can do this as follows, for a dynamic library:
  2677. \begin{verbatim}
  2678. ppc386 -CD myunit
  2679. \end{verbatim}
  2680. On \unix systems, such as \linux, this will leave you with a file \file{libmyunit.so}. On \windows
  2681. and \ostwo, this will leave you with \file{myunit.dll}. An easier way to
  2682. create shared libraries is to use the \var{library} keyword. For more
  2683. information on creating shared libraries, \seec{libraries}.
  2684. If you want a static library, you can do
  2685. \begin{verbatim}
  2686. ppc386 -CS myunit
  2687. \end{verbatim}
  2688. This will leave you with \file{libmyunit.a} and a file \file{myunit.ppu}.
  2689. The \file{myunit.ppu} is the unit file needed by the \fpc compiler.
  2690. The resulting files are then libraries. To make static libraries, you need
  2691. the \file{ranlib} or \var{ar} program on your system. It is standard on most
  2692. \unix systems, and is provided with the \file{gcc} compiler under \dos.
  2693. For the dos distribution, a copy of ar is included in the file
  2694. \file{gnuutils.zip}.
  2695. {\em BEWARE:} This command doesn't include anything but the current unit in
  2696. the library. Other units are left out, so if you use code from other units,
  2697. you must deploy them together with your library.
  2698. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2699. % unit searching
  2700. \subsection{Unit searching strategy}
  2701. When you compile a unit, the compiler will by
  2702. default always look for unit files.
  2703. To be able to differentiate between units that have been compiled as static
  2704. or dynamic libraries, there are 2 switches:
  2705. \begin{description}
  2706. \item [-XD:\ ] This will define the symbol \var{FPC\_LINK\_DYNAMIC}
  2707. \item [-XS:\ ] This will define the symbol \var{FPC\_LINK\_STATIC}
  2708. \end{description}
  2709. Definition of one symbol will automatically undefine the other.
  2710. These two switches can be used in conjunction with the configuration file
  2711. \file{fpc.cfg}. The existence of one of these symbols can be used to
  2712. decide which unit search path to set. For example, on \linux:
  2713. \begin{verbatim}
  2714. # Set unit paths
  2715. #IFDEF FPC_LINK_STATIC
  2716. -Up/usr/lib/fpc/linuxunits/staticunits
  2717. #ENDIF
  2718. #IFDEF FPC_LINK_DYNAMIC
  2719. -Up/usr/lib/fpc/linuxunits/sharedunits
  2720. #ENDIF
  2721. \end{verbatim}
  2722. With such a configuration file, the compiler will look for it's units in
  2723. different directories, depending on whether \var{-XD} or \var{-XS} is used.
  2724. \section{Using smart linking}
  2725. \label{se:SmartLinking}
  2726. You can compile your units using smart linking. When you use smartlinking,
  2727. the compiler creates a series of code blocks that are as small as possible,
  2728. i.e. a code block will contain only the code for one procedure or function.
  2729. When you compile a program that uses a smart-linked unit, the compiler will
  2730. only link in the code that you actually need, and will leave out all other
  2731. code. This will result in a smaller binary, which is loaded in memory
  2732. faster, thus speeding up execution.
  2733. To enable smartlinking, one can give the smartlink option on the command
  2734. line: \var{-Cx}, or one can put the \var{\{\$SMARTLINK ON\}} directive in
  2735. the unit file:
  2736. \begin{verbatim}
  2737. Unit Testunit
  2738. {SMARTLINK ON}
  2739. Interface
  2740. ...
  2741. \end{verbatim}
  2742. Smartlinking will slow down the compilation process, especially for large
  2743. units.
  2744. When a unit \file{foo.pp} is smartlinked, the name of the codefile is
  2745. changed to \file{libfoo.a}.
  2746. Technically speaking, the compiler makes small assembler files for each
  2747. procedure and function in the unit, as well as for all global defined
  2748. variables (whether they're in the interface section or not). It then
  2749. assembles all these small files, and uses \file{ar} to collect the resulting
  2750. object files in one archive.
  2751. Smartlinking and the creation of shared (or dynamic) libraries are mutually
  2752. exclusive, that is, if you turn on smartlinking, then the creation of shared
  2753. libraries is turned of. The creation of static libraries is still possible.
  2754. The reason for this is that it has little sense in making a smartlinked
  2755. dynamical library. The whole shared library is loaded into memory anyway by
  2756. the dynamic linker (or the operating system), so there would be no gain in size by
  2757. making it smartlinked.
  2758. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2759. % Memory issues
  2760. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2761. \chapter{Memory issues}
  2762. \label{ch:Memory}
  2763. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2764. % The memory model
  2765. \section{The memory model.}
  2766. \label{se:ThirtytwoBit}
  2767. The \fpc compiler issues 32-bit or 64-bit code.
  2768. This has several consequences:
  2769. \begin{itemize}
  2770. \item You need a 32-bit or 64-bit processor to run the generated code. The
  2771. compiler functions on a 286 when you compile it using Turbo Pascal,
  2772. but the generated programs cannot be assembled or executed.
  2773. \item You don't need to bother with segment selectors. Memory can be
  2774. addressed using a single 32-bit (on 32-bit processors) or 64-bit (on
  2775. 64-bit processors with 64-bit addressing) pointer.
  2776. The amount of memory is limited only by the available amount of (virtual)
  2777. memory on your machine.
  2778. \item The structures you define are unlimited in size. Arrays can be as long
  2779. as you want. You can request memory blocks from any size.
  2780. \end{itemize}
  2781. The fact that 16-bit code is no longer used, means that some of the older
  2782. Turbo Pascal constructs and functions are obsolete. The following is a
  2783. list of functions which shouldn't be used anymore:
  2784. \begin{description}
  2785. \item [Seg()]: Returned the segment of a memory address. Since segments have
  2786. no more meaning, zero is returned in the \fpc run-time library implementation of
  2787. \var{Seg}.
  2788. \item [Ofs()]: Returned the offset of a memory address. Since segments have
  2789. no more meaning, the complete address is returned in the \fpc implementation
  2790. of this function. This has as a consequence that the return type is
  2791. \var{longint} or \var{int64} instead of \var{Word}.
  2792. \item [Cseg(), Dseg()]: Returned, respectively, the code and data segments
  2793. of your program. This returns zero in the \fpc implementation of the
  2794. system unit, since both code and data are in the same memory space.
  2795. \item [Ptr]: Accepted a segment and offset from an address, and would return
  2796. a pointer to this address. This has been changed in the run-time library, it
  2797. now simply returns the offset.
  2798. \item [memw and mem]: These arrays gave access to the \dos memory. \fpc
  2799. supports them on the go32v2 platform, they are mapped into \dos memory
  2800. space. You need the \file{go32} unit for this. On other platforms, they are
  2801. {\em not} supported
  2802. \end{description}
  2803. You shouldn't use these functions, since they are very non-portable, they're
  2804. specific to \dos and the 80x86 processor. The \fpc compiler is designed to be
  2805. portable to other platforms, so you should keep your code as portable as
  2806. possible, and not system specific. That is, unless you're writing some driver
  2807. units, of course.
  2808. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2809. % Data formats
  2810. \section{Data formats}
  2811. \label{se:Dataformats}
  2812. This section gives information on the storage space occupied by
  2813. the different possible types in \fpc. Information on internal
  2814. alignment will also be given.
  2815. \subsection{integer types}
  2816. The storage size of the default integer types are given in
  2817. \refref. In the case of user defined-types, the storage space
  2818. occupied depends on the bounds of the type:
  2819. \begin{itemize}
  2820. \item If both bounds are within range -128..127, the variable
  2821. is stored as a shortint (signed 8-bit quantity).
  2822. \item If both bounds are within the range 0..255, the variable
  2823. is stored as a byte (unsigned 8-bit quantity).
  2824. \item If both bounds are within the range -32768..32767, the variable
  2825. is stored as a smallint (signed 16-bit quantity).
  2826. \item If both bounds are within the range 0..65535, the variable
  2827. is stored as a word (unsigned 16-bit quantity)
  2828. \item If both bounds are within the range 0..4294967295, the
  2829. variable is stored as a longword (unsigned 32-bit quantity).
  2830. \item Otherwise the variable is stored as a longint (signed
  2831. 32-bit quantity).
  2832. \end{itemize}
  2833. \subsection{char types}
  2834. A \var{char}, or a subrange of the char type is stored
  2835. as a byte.
  2836. \subsection{boolean types}
  2837. The \var{boolean} type is stored as a byte and can take
  2838. a value of \var{true} or \var{false}.
  2839. A \var{ByteBool} is stored as a byte, a \var{WordBool}
  2840. type is stored as a word, and a \var{longbool} is stored
  2841. as a longint.
  2842. \subsection{enumeration types}
  2843. By default all enumerations are stored as a
  2844. longword (4 bytes), which is equivalent to specifying
  2845. the \var{\{\$Z4\}}, \var{\{\$PACKENUM 4\}} or
  2846. \var{\{\$PACKENUM DEFAULT\}} switches.
  2847. This default behavior can be changed by compiler switches,
  2848. and by the compiler mode.
  2849. In the \var{tp} compiler mode, or while the \var{\{\$Z1\}} or
  2850. \var{\{\$PACKENUM 1\}} switches are in effect, the storage
  2851. space used is shown in \seet{enumstoragetp}.
  2852. \begin{FPCltable}{ll}{Enumeration storage for \var{tp} mode}{enumstoragetp}
  2853. \# Of Elements in Enum. & Storage space used\\ \hline
  2854. 0..255 & byte (1 byte) \\
  2855. 256..65535 & word (2 bytes) \\
  2856. > 65535 & longword (4 bytes) \\
  2857. \hline
  2858. \end{FPCltable}
  2859. When the \var{\{\$Z2\}} or \var{\{\$PACKENUM 2\}}
  2860. switches are in effect, the value is stored on 2
  2861. bytes (word), if the enumeration has less or equal
  2862. then 65535 elements, otherwise, the enumeration
  2863. value is stored as a 4 byte value (longword).
  2864. \subsection{floating point types}
  2865. Floating point type sizes and mapping vary from one
  2866. processor to another. Except for the Intel 80x86
  2867. architecture, the \var{extended} type maps to the IEEE
  2868. double type if a hardware floating point coprocessor
  2869. is present.
  2870. \begin{FPCltable}{lr}{Processor mapping of real type}{RealMapping}
  2871. Processor & Real type mapping\\
  2872. \hline
  2873. Intel 80x86 & \var{double}\\
  2874. Motorola 680x0 (with \{\$E-\} switch) & \var{double}\\
  2875. Motorola 680x0 (with \{\$E+\} switch) & \var{single}\\
  2876. \hline
  2877. \end{FPCltable}
  2878. Floating point types have a storage binary format divided
  2879. into three distinct fields : the mantissa, the exponent
  2880. and the sign bit which stores the sign of the floating
  2881. point value.
  2882. \subsubsection{single}
  2883. The \var{single} type occupies 4 bytes of storage space,
  2884. and its memory structure is the same as the IEEE-754 single
  2885. type. This type is the only type which is guaranteed to
  2886. be available on all platforms (either emulated via software
  2887. or directly via hardware).
  2888. The memory format of the \var{single} format looks like
  2889. what is shown in \seefig{single}.
  2890. \FPCpic{The single format}{}{single}
  2891. \subsubsection{double}
  2892. The \var{double} type occupies 8 bytes of storage space,
  2893. and its memory structure is the same as the IEEE-754 double
  2894. type.
  2895. The memory format of the \var{double} format looks like
  2896. like what is shown in \seefig{double}.
  2897. \FPCpic{The double format}{}{double}
  2898. On processors which do not support co-processor operations (and which have
  2899. the \{\$E+\} switch), the \var{double} type does not exist.
  2900. \subsubsection{extended}
  2901. For Intel 80x86 processors, the \var{extended} type has
  2902. takes up 10 bytes of memory space. For more information
  2903. on the extended type consult the Intel Programmer's reference.
  2904. For all other processors which support floating point operations,
  2905. the \var{extended} type is a nickname for the type which supports
  2906. the most precision, this is usually the \var{double} type.
  2907. On processors which do not support co-processor operations (and which have
  2908. the \{\$E+\} switch), the \var{extended} type usually maps to the
  2909. \var{single} type.
  2910. \subsubsection{comp}
  2911. For Intel 80x86 processors, the \var{comp} type contains
  2912. a 63-bit integral value, and a sign bit (in the MSB position).
  2913. The \var{comp} type takes up 8 bytes of storage space.
  2914. On other processors, the \var{comp} type is not supported.
  2915. \subsubsection{real}
  2916. Contrary to Turbo Pascal, where the \var{real} type had
  2917. a special internal format, under \fpc the \var{real} type
  2918. simply maps to one of the other real types. It maps to the
  2919. \var{double} type on processors which support floating
  2920. point operations, while it maps to the \var{single} type
  2921. on processors which do not support floating point operations
  2922. in hardware. See \seet{RealMapping} for more information
  2923. on this.
  2924. \subsection{pointer types}
  2925. A \var{pointer} type is stored as a longword (unsigned 32-bit value) on
  2926. 32-bit processors, and is stored as a 64-bit unsigned value\footnote{this
  2927. is actually the \var{qword} type, which is not supported in \fpc v1.0}
  2928. on 64-bit processors.
  2929. \subsection{string types}
  2930. \subsubsection{ansistring types}
  2931. The ansistring is a dynamically allocated string which
  2932. has no length limitation. When the string is no longer
  2933. being referenced (its reference count reaches zero),
  2934. its memory is automatically freed.
  2935. If the ansistring is a constant, then its reference
  2936. count will be equal to -1, indicating that it should
  2937. never be freed. The structure in memory for an
  2938. ansistring is shown in \seet{ansistrings}.
  2939. \begin{FPCltable}{rl}{AnsiString memory structure (32-bit model)}{ansistrings}
  2940. Offset & Contains \\ \hline
  2941. -12 & Longint with maximum string size. \\
  2942. -8 & Longint with actual string size.\\
  2943. -4 & Longint with reference count.\\
  2944. 0 & Actual array of \var{char}, null-terminated. \\ \hline
  2945. \end{FPCltable}
  2946. \subsubsection{shortstring types}
  2947. A shortstring occupies as many bytes as its maximum length plus one.
  2948. The first byte contains the current dynamic length of the string. The
  2949. following bytes contain the actual characters (of type \var{char})
  2950. of the string. The maximum size of a short string is the length
  2951. byte followed by 255 characters.
  2952. \subsubsection{widestring types}
  2953. The widestring (composed of unicode characters) is not supported
  2954. in \fpc v1.0.
  2955. \subsection{set types}
  2956. A set is stored as an array of bits, where each bit indicates
  2957. if the element is in the set or excluded from the set. The maximum
  2958. number of elements in a set is 256.
  2959. If a set has less than 32 elements, it is coded as an unsigned
  2960. 32-bit value. Otherwise it is coded as a 8 element array of
  2961. 32-bit unsigned values (longword) (hence a size of 256 bytes).
  2962. The longword number of a specific element \var{E} is given by :
  2963. \begin{verbatim}
  2964. LongwordNumber = (E div 32);
  2965. \end{verbatim}
  2966. and the bit number within that 32-bit value is given by:
  2967. \begin{verbatim}
  2968. BitNumber = (E mod 32);
  2969. \end{verbatim}
  2970. \subsection{array types}
  2971. An array is stored as a contiguous sequence of variables
  2972. of the components of the array. The components with the
  2973. lowest indexes are stored first in memory. No alignment
  2974. is done between each element of the array. A multi-dimensional
  2975. array is stored with the rightmost dimension increasing first.
  2976. \subsection{record types}
  2977. Each field of a record are stored in a contigous sequence
  2978. of variables, where the first field is stored at the
  2979. lowest address in memory. In case of variant fields in
  2980. a record, each variant starts at the same address in
  2981. memory. Fields of record are usually aligned, unless
  2982. the \var{packed} directive is specified when declaring
  2983. the record type. For more information on field alignment,
  2984. consult \sees{StructuredAlignment}.
  2985. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2986. % memory storage of Objects
  2987. \subsection{object types}
  2988. \label{subse:ObjMemory}
  2989. Objects are stored in memory just as ordinary records with an extra field:
  2990. a pointer to the Virtual Method Table (VMT). This field is stored first, and
  2991. all fields in the object are stored in the order they are declared (with possible
  2992. alignment of field addresses, unless the object was declared as being \var{packed}).
  2993. This field is initialized by the call to the object's \var{Constructor} method.
  2994. If the \var{new} operator was used to call the constructor, the data fields
  2995. of the object will be stored in heap memory, otherwise they will directly
  2996. be stored in the data section of the final executable.
  2997. If an object doesn't have virtual methods, no pointer to a VMT is inserted.
  2998. The memory allocated looks as in \seet{ObjMem}.
  2999. \begin{FPCltable}{ll}{Object memory layout (32-bit model)}{ObjMem} \hline
  3000. Offset & What \\ \hline
  3001. +0 & Pointer to VMT (optional). \\
  3002. +4 & Data. All fields in the order they've been declared. \\
  3003. \dots & \\
  3004. \hline
  3005. \end{FPCltable}
  3006. The Virtual Method Table (VMT) for each object type consists of 2 check
  3007. fields (containing the size of the data), a pointer to the object's ancestor's
  3008. VMT (\var{Nil} if there is no ancestor), and then the pointers to all virtual
  3009. methods. The VMT layout is illustrated in \seet{ObjVMTMem}. The VMT is
  3010. constructed by the compiler.
  3011. \begin{FPCltable}{ll}{Object Virtual Method Table memory layout (32-bit model)}{ObjVMTMem} \hline
  3012. Offset & What \\ \hline
  3013. +0 & Size of object type data \\
  3014. +4 & Minus the size of object type data. Enables determining of valid VMT
  3015. pointers. \\
  3016. +8 & Pointer to ancestor VMT, \var{Nil} if no ancestor available.\\
  3017. +12 & Pointers to the virtual methods. \\
  3018. \dots & \\
  3019. \hline
  3020. \end{FPCltable}
  3021. \subsection{class types}
  3022. Just like objects, classes are stored in memory just as ordinary records
  3023. with an extra field: a pointer to the Virtual Method Table (VMT).
  3024. This field is stored first, and all fields in the class are stored in
  3025. the order they are declared.
  3026. Contrary to objects, all data fields of a class are always stored
  3027. in heap memory.
  3028. The memory allocated looks as in \seet{ClassMem}.
  3029. \begin{FPCltable}{ll}{Class memory layout (32-bit model)}{ClassMem} \hline
  3030. Offset & What \\ \hline
  3031. +0 & Pointer to VMT. \\
  3032. +4 & Data. All fields in the order they've been declared. \\
  3033. \dots & \\
  3034. \hline
  3035. \end{FPCltable}
  3036. The Virtual Method Table (VMT) of each class consists of several fields,
  3037. which are used for runtime type information. The VMT layout is illustrated
  3038. in \seet{ClassVMTMem}. The VMT is constructed by the compiler.
  3039. \begin{FPCltable}{ll}{Class Virtual Method Table memory layout (32-bit model)}{ClassVMTMem} \hline
  3040. Offset & What \\ \hline
  3041. +0 & Size of object type data \\
  3042. +4 & Minus the size of object type data. Enables determining of valid VMT
  3043. pointers. \\
  3044. +8 & Pointer to ancestor VMT, \var{Nil} if no ancestor available.\\
  3045. +12 & Pointer to the class name (stored as a \var{shortstring}). \\
  3046. +16 & Pointer to the dynamic method table (using \var{message} with integers).\\
  3047. +20 & Pointer to the method definition table. \\
  3048. +24 & Pointer to the field definition table. \\
  3049. +28 & Pointer to type information table. \\
  3050. +32 & Pointer to instance initialization table. \\
  3051. +36 & Reserved.\\
  3052. +40 & Pointer to the interface table. \\
  3053. +44 & Pointer to the dynamic method table (using \var{message} with strings).\\
  3054. +48 & Pointer to the \var{Destroy} destructor. \\
  3055. +52 & Pointer to the \var{NewInstance} method. \\
  3056. +56 & Pointer to the \var{FreeInstance} method. \\
  3057. +60 & Pointer to the \var{SafeCallException} method. \\
  3058. +64 & Pointer to the \var{DefaultHandler} method. \\
  3059. +68 & Pointer to the \var{AfterConstruction} method. \\
  3060. +72 & Pointer to the \var{BeforeDestruction} method. \\
  3061. +76 & Pointer to the \var{DefaultHandlerStr} method. \\
  3062. +80 & Pointers to other virtual methods. \\
  3063. \dots & \\
  3064. \hline
  3065. \end{FPCltable}
  3066. \subsection{file types}
  3067. File types are represented as records. Typed files and untyped
  3068. files are represented as a fixed record:
  3069. \begin{verbatim}
  3070. filerec = packed record
  3071. handle : longint;
  3072. mode : longint;
  3073. recsize : longint;
  3074. _private : array[1..32] of byte;
  3075. userdata : array[1..16] of byte;
  3076. name : array[0..255] of char;
  3077. End;
  3078. \end{verbatim}
  3079. Text files are described using the following record:
  3080. \begin{verbatim}
  3081. TextBuf = array[0..255] of char;
  3082. textrec = packed record
  3083. handle : longint;
  3084. mode : longint;
  3085. bufsize : longint;
  3086. _private : longint;
  3087. bufpos : longint;
  3088. bufend : longint;
  3089. bufptr : ^textbuf;
  3090. openfunc : pointer;
  3091. inoutfunc : pointer;
  3092. flushfunc : pointer;
  3093. closefunc : pointer;
  3094. userdata : array[1..16] of byte;
  3095. name : array[0..255] of char;
  3096. buffer : textbuf;
  3097. End;
  3098. \end{verbatim}
  3099. \begin{description}
  3100. \item[handle] The handle field returns the file handle (if the file is
  3101. opened), as returned by the operating system.
  3102. \item[mode] The mode field can take one of several values. When it is
  3103. \var{fmclosed}, then the file is closed, and the \var{handle} field is invalid.
  3104. When the value is equal to \var{fminput}, it indicates that the file is
  3105. opened for read only access. \var{fmoutput} indicates write only access,
  3106. and the \var{fminout} indicates read-write access to the file.
  3107. \item[name] The \var{name} field is a null terminated character string representing
  3108. the name of the file.
  3109. \item[userdata] The \var{userdata} field is never used by \fpc, and can
  3110. be used for special purposes by software developpers.
  3111. \end{description}
  3112. \subsection{procedural types}
  3113. <<<<<<< prog.tex
  3114. A procedural type is stored as a generic pointer, which stores
  3115. the address of the routine.
  3116. =======
  3117. A procedural type to a normal procedure or function is stored as a generic pointer,
  3118. which stores the address of the entry point of the routine.
  3119. >>>>>>> 1.29
  3120. <<<<<<< prog.tex
  3121. =======
  3122. In the case of a method procedural type, the storage consists of two pointers,
  3123. the first being a pointer to the entry point of the method, and the second
  3124. one being a pointer to \var{self} (the object instance).
  3125. >>>>>>> 1.29
  3126. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3127. % The alignment of data elements
  3128. \section{Data alignment}
  3129. \label{se:Alignment}
  3130. \subsection{Typed constants and variable alignment}
  3131. All static data (variables and typed constants) which are greater than
  3132. a byte are usually aligned on a power of two boundary. This alignment
  3133. applies only to the start address of the variables, and not the alignment
  3134. of fields within structures or objects for example. For more information
  3135. on structured alignment, \sees{StructuredAlignment}. The alignment
  3136. is similar across the different target processors. \footnote{The Intel
  3137. 80x86 version does not align data in the case of constant strings,
  3138. constant sets, constant floating point values amd global variables.
  3139. This will be fixed in the version 1.1 release.}
  3140. \begin{FPCltable}{lccc}{Data alignment}{DataAlignment}
  3141. \hline
  3142. Data size (bytes) & Alignment (small size) & Alignment (fast)\\
  3143. 1 & 1 & 1\\
  3144. 2-3 & 2 & 2\\
  3145. 4-7 & 2 & 4\\
  3146. 8+ & 2 & 4\\
  3147. \hline
  3148. \end{FPCltable}
  3149. The alignment columns indicates the address alignment of the variable,
  3150. i.e the start address of the variable will be aligned on that boundary.
  3151. The small size alignment is valid when the code generated should be
  3152. optimized for size (\var{-Og} compiler option) and not speed, otherwise and
  3153. by default, the fast alignment is used to align the data.
  3154. \subsection{Structured types alignment}
  3155. \label{se:StructuredAlignment}
  3156. By default all elements in a structure are aligned to a 2 byte boundary,
  3157. unless the \var{\$PACKRECORDS} directive or \var{packed} modifier is used
  3158. to align the data in another way. For example a \var{record} or \var{object}
  3159. having a 1 byte element, will have its size rounded up to 2, so the size of
  3160. the structure will actually be 2 bytes.
  3161. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3162. % The heap
  3163. \section{The heap}
  3164. \label{se:Heap}
  3165. The heap is used to store all dynamic variables, and to store class
  3166. instances. The interface to the heap is the same as in Turbo Pascal,
  3167. although the effects are maybe not the same. On top of that, the \fpc
  3168. run-time library has some extra possibilities, not available in Turbo
  3169. Pascal. These extra possibilities are explained in the next subsections.
  3170. % The heap algorithm
  3171. \subsection{Heap allocation strategy}
  3172. The heap is a memory structure which is organized as a stack. The heap
  3173. bottom is stored in the variable \var{HeapOrg}. Initially the heap
  3174. pointer (\var{HeapPtr}) points to the bottom of the heap. When a
  3175. variable is allocated on the heap, \var{HeapPtr} is incremented by the
  3176. size of the allocated memory block. This has the effect of stacking
  3177. dynamic variables on top of each other.
  3178. Each time a block is allocated, its size is normalized to have
  3179. a granularity of 16 bytes.
  3180. When \var{Dispose} or \var{FreeMem} is called to dispose of a
  3181. memory block which is not on the top of the heap, the heap becomes
  3182. fragmented. The deallocation routines also add the freed blocks to
  3183. the \var{freelist} which is actually a linked list of free blocks.
  3184. Furthermore, if the deallocated block was less then 8K in size, the
  3185. free list cache is also updated.
  3186. The free list cache is actually a cache of free heap blocks which
  3187. have specific lengths (the adjusted block size divided by 16 gives the
  3188. index into the free list cache table). It is faster to access then
  3189. searching through the entire \var{freelist}.
  3190. The format of an entry in the \var{freelist} is as follows:
  3191. \begin{verbatim}
  3192. PFreeRecord = ^TFreeRecord;
  3193. TFreeRecord = record
  3194. Size : longint;
  3195. Next : PFreeRecord;
  3196. Prev : PFreeRecord;
  3197. end;
  3198. \end{verbatim}
  3199. The \var{Next} field points to the next free block, while
  3200. the \var{Prev} field points to the previous free block.
  3201. The algorithm for allocating memory is as follows:
  3202. \begin{enumerate}
  3203. \item The size of the block to allocate is adjusted to a 16 byte granularity.
  3204. \item The cached free list is searched to find a free block of the specified
  3205. size or bigger size, if so it is allocated and the routine exits.
  3206. \item The \var{freelist} is searched to find a free block of the specified size
  3207. or of bigger size, if so it is allocated and the routine exits.
  3208. \item If not found in the \var{freelist} the heap is grown to allocate the
  3209. specified memory, and the routine exits.
  3210. \item If the heap cannot be grown internally anymore and if \var{heaperror} is set
  3211. accordingly, it calls the heap error handler. If there is no heap error handler
  3212. installed, the runtime library generates a runtime error 203.
  3213. \end{enumerate}
  3214. % Error handler routinr
  3215. \subsection{The HeapError variable}
  3216. The heap error permits developpers to install a heap error hook which
  3217. is called each time an allocation cannot be completed by the default
  3218. heap manager. \var{HeapError} is a pointer that points to a function
  3219. with the following prototype:
  3220. \begin{verbatim}
  3221. function HeapFunc(size : longint): integer;
  3222. \end{verbatim}
  3223. The \var{size} parameter indicates the size of the block which could
  3224. not be allocated. Depending on the success, the error handler routine
  3225. should return a value which indicates what the default heap manager
  3226. should do thereafter (cf. \seet{Heaperrorresult}).
  3227. \begin{FPCltable}{|c|l|}{Heap error result}{Heaperrorresult}
  3228. \hline
  3229. Value returned & Memory manager action \\ \hline
  3230. 0 & Generates a runtime error 203 \\
  3231. 1 & \var{GetMem},\var{ReallocMem} and \var{New} returns \var{nil} \\
  3232. 2 & Try allocating the memory block once again \\
  3233. \hline
  3234. \end{FPCltable}
  3235. % The heap grows
  3236. \subsection{The heap grows}
  3237. By default, \var{HeapError} points to the \var{GrowHeap} function,
  3238. which tries to increase the heap.
  3239. The \var{GrowHeap} function issues a system call to try to increase the size of the
  3240. memory available to your program. It first tries to increase memory in a 256Kb
  3241. chunk if the size to allocate is less than 256Kb, or 1024K otherwise.
  3242. If this fails, it tries to increase the heap by the amount you requested
  3243. from the heap.
  3244. If the call to \var{GrowHeap} was successful, then the needed memory will be
  3245. allocated.
  3246. If the call to \var{GrowHeap} fails, the value returned depends on the
  3247. value of the \var{ReturnNilIfGrowHeapFails} global variable. This is summarized
  3248. in \seet{growheapnil}.
  3249. \begin{FPCltable}{|c|l|}{ReturnNilIfGrowHeapFails value}{growheapnil}
  3250. \hline
  3251. ReturnNilGrowHeapFails & Default memory \\
  3252. value & manager action \\
  3253. \hline
  3254. FALSE & (The default) Runtime error 203 generated \\
  3255. TRUE & \var{GetMem}, \var{ReallocMem} and \var{New} returns \var{nil} \\
  3256. \hline
  3257. \end{FPCltable}
  3258. \var{ReturnNilIfGrowHeapFails} can be set to change the behavior of
  3259. the default memory manager error handler.
  3260. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3261. % Debugging the heap
  3262. \subsection{Debugging the heap}
  3263. \fpc provides a unit that allows you to trace allocation and deallocation
  3264. of heap memory: \file{heaptrc}.
  3265. If you specify the \var{-gh} switch on the command-line, or if you include
  3266. \var{heaptrc} as the first unit in your uses clause, the memory manager
  3267. will trace what is allocated and deallocated, and on exit of your program,
  3268. a summary will be sent to standard output.
  3269. More information on using the \var{heaptrc} mechanism can be found in the
  3270. \userref and \unitsref.
  3271. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3272. % Writing your own memory manager.
  3273. \subsection{Writing your own memory manager}
  3274. \fpc allows you to write and use your own memory manager. The standard
  3275. functions \var{GetMem}, \var{FreeMem}, \var{ReallocMem} and \var{Maxavail}
  3276. use a special record in the \file{system} unit to do the actual memory management.
  3277. The \file{system} unit initializes this record with the \file{system} unit's own memory
  3278. manager, but you can read and set this record using the
  3279. \var{GetMemoryManager} and \var{SetMemoryManager} calls:
  3280. \begin{verbatim}
  3281. procedure GetMemoryManager(var MemMgr: TMemoryManager);
  3282. procedure SetMemoryManager(const MemMgr: TMemoryManager);
  3283. \end{verbatim}
  3284. the \var{TMemoryManager} record is defined as follows:
  3285. \begin{verbatim}
  3286. TMemoryManager = record
  3287. Getmem : Function(Size:Longint):Pointer;
  3288. Freemem : Function(var p:pointer):Longint;
  3289. FreememSize : Function(var p:pointer;Size:Longint):Longint;
  3290. AllocMem : Function(Size:longint):Pointer;
  3291. ReAllocMem : Function(var p:pointer;Size:longint):Pointer;
  3292. MemSize : function(p:pointer):Longint;
  3293. MemAvail : Function:Longint;
  3294. MaxAvail : Function:Longint;
  3295. HeapSize : Function:Longint;
  3296. end;
  3297. \end{verbatim}
  3298. As you can see, the elements of this record are procedural variables.
  3299. The \file{system} unit does nothing but call these various variables when you
  3300. allocate or deallocate memory.
  3301. Each of these functions corresponds to the corresponding call in the \file{system}
  3302. unit. We'll describe each one of them:
  3303. \begin{description}
  3304. \item[Getmem] This function allocates a new block on the heap. The block
  3305. should be \var{Size} bytes long. The return value is a pointer to the newly
  3306. allocated block.
  3307. \item[Freemem] should release a previously allocated block. The pointer
  3308. \var{P} points to a previously allocated block. The Memory manager should
  3309. implement a mechanism to determine what the size of the memory block is
  3310. \footnote{By storing it's size at a negative offset for instance.} The
  3311. return value is optional, and can be used to return the size of the freed
  3312. memory.
  3313. \item[FreememSize] This function should release the memory pointed to by
  3314. \var{P}. The argument \var{Size} is the expected size of the memory block
  3315. pointed to by P. This should be disregarded, but can be used to check the
  3316. behaviour of the program.
  3317. \item[AllocMem] Is the same as getmem, only the allocated memory should
  3318. be filled with zeroes before the call returns.
  3319. \item[ReAllocMem] Should allocate a memory block \var{Size} bytes large,
  3320. and should fill it with the contents of the memory block pointed to by
  3321. \var{P}, truncating this to the new size of needed. After that, the memory
  3322. pointed to by P may be deallocated. The return value is a pointer to the
  3323. new memory block. Note that \var{P} may be \var{Nil}, in which case the
  3324. behaviour is equivalent to \var{GetMem}.
  3325. \item[MemSize] should return the total amount of memory available for
  3326. allocation. This function may return zero if the memory manager does not
  3327. allow to determine this information.
  3328. \item[MaxAvail] should return the size of the largest block of memory that
  3329. is still available for allocation. This function may return zero if the
  3330. memory manager does not allow to determine this information.
  3331. \item[HeapSize] should return the total size of the heap. This may be zero
  3332. is the memory manager does not allow to determine this information.
  3333. \end{description}
  3334. To implement your own memory manager, it is sufficient to construct such a
  3335. record and to issue a call to \var{SetMemoryManager}.
  3336. To avoid conflicts with the system memory manager, setting the memory
  3337. manager should happen as soon as possible in the initialization of your
  3338. program, i.e. before any call to \var{getmem} is processed.
  3339. This means in practice that the unit implementing the memory manager should
  3340. be the first in the \var{uses} clause of your program or library, since it
  3341. will then be initialized before all other units (except of the \file{system} unit)
  3342. This also means that it is not possible to use the \file{heaptrc} unit in
  3343. combination with a custom memory manager, since the \file{heaptrc} unit uses
  3344. the system memory manager to do all it's allocation. Putting the
  3345. \file{heaptrc} unit after the unit implementing the memory manager would
  3346. overwrite the memory manager record installed by the custom memory manager,
  3347. and vice versa.
  3348. The following unit shows a straightforward implementation of a custom
  3349. memory manager using the memory manager of the \var{C} library. It is
  3350. distributed as a package with \fpc.
  3351. \begin{verbatim}
  3352. unit cmem;
  3353. {$mode objfpc}
  3354. interface
  3355. Function Malloc (Size : Longint) : Pointer;cdecl;
  3356. external 'c' name 'malloc';
  3357. Procedure Free (P : pointer); cdecl; external 'c' name 'free';
  3358. Procedure FreeMem (P : Pointer); cdecl; external 'c' name 'free';
  3359. function ReAlloc (P : Pointer; Size : longint) : pointer; cdecl;
  3360. external 'c' name 'realloc';
  3361. Function CAlloc (unitSize,UnitCount : Longint) : pointer;cdecl;
  3362. external 'c' name 'calloc';
  3363. implementation
  3364. Function CGetMem (Size : Longint) : Pointer;
  3365. begin
  3366. result:=Malloc(Size);
  3367. end;
  3368. Function CFreeMem (Var P : pointer) : Longint;
  3369. begin
  3370. Free(P);
  3371. Result:=0;
  3372. end;
  3373. Function CFreeMemSize(var p:pointer;Size:Longint):Longint;
  3374. begin
  3375. Result:=CFreeMem(P);
  3376. end;
  3377. Function CAllocMem(Size : Longint) : Pointer;
  3378. begin
  3379. Result:=calloc(Size,1);
  3380. end;
  3381. Function CReAllocMem (var p:pointer;Size:longint):Pointer;
  3382. begin
  3383. Result:=realloc(p,size);
  3384. end;
  3385. Function CMemSize (p:pointer): Longint;
  3386. begin
  3387. Result:=0;
  3388. end;
  3389. Function CMemAvail : Longint;
  3390. begin
  3391. Result:=0;
  3392. end;
  3393. Function CMaxAvail: Longint;
  3394. begin
  3395. Result:=0;
  3396. end;
  3397. Function CHeapSize : Longint;
  3398. begin
  3399. Result:=0;
  3400. end;
  3401. Const
  3402. CMemoryManager : TMemoryManager =
  3403. (
  3404. GetMem : CGetmem;
  3405. FreeMem : CFreeMem;
  3406. FreememSize : CFreememSize;
  3407. AllocMem : CAllocMem;
  3408. ReallocMem : CReAllocMem;
  3409. MemSize : CMemSize;
  3410. MemAvail : CMemAvail;
  3411. MaxAvail : MaxAvail;
  3412. HeapSize : CHeapSize;
  3413. );
  3414. Var
  3415. OldMemoryManager : TMemoryManager;
  3416. Initialization
  3417. GetMemoryManager (OldMemoryManager);
  3418. SetMemoryManager (CmemoryManager);
  3419. Finalization
  3420. SetMemoryManager (OldMemoryManager);
  3421. end.
  3422. \end{verbatim}
  3423. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3424. % Accessing DOS memory under the GO32 extender
  3425. \section{Using \dos memory under the Go32 extender}
  3426. \label{se:AccessingDosMemory}
  3427. Because \fpc for \dos is a 32 bit compiler, and uses a \dos extender, accessing DOS
  3428. memory isn't trivial. What follows is an attempt to an explanation of how to
  3429. access and use \dos or real mode memory\footnote{Thanks for the explanation to
  3430. Thomas Schatzl (E-mail: \var{tom\_at\[email protected]})}.
  3431. In {\em Proteced Mode}, memory is accessed through {\em Selectors} and
  3432. {\em Offsets}. You can think of Selectors as the protected mode
  3433. equivalents of segments.
  3434. In \fpc, a pointer is an offset into the \var{DS} selector, which points to
  3435. the Data of your program.
  3436. To access the (real mode) \dos memory, somehow you need a selector that
  3437. points to the \dos memory.
  3438. The \file{go32} unit provides you with such a selector: The
  3439. \var{DosMemSelector} variable, as it is conveniently called.
  3440. You can also allocate memory in \dos's memory space, using the
  3441. \var{global\_dos\_alloc} function of the \file{go32} unit.
  3442. This function will allocate memory in a place where \dos sees it.
  3443. As an example, here is a function that returns memory in real mode \dos and
  3444. returns a selector:offset pair for it.
  3445. \begin{verbatim}
  3446. procedure dosalloc(var selector : word;
  3447. var segment : word;
  3448. size : longint);
  3449. var result : longint;
  3450. begin
  3451. result := global_dos_alloc(size);
  3452. selector := word(result);
  3453. segment := word(result shr 16);
  3454. end;
  3455. \end{verbatim}
  3456. (You need to free this memory using the \var{global\_dos\_free} function.)
  3457. You can access any place in memory using a selector. You can get a selector
  3458. using the \var{allocate\_ldt\_descriptor} function, and then let this selector
  3459. point to the physical memory you want using the
  3460. \var{set\_segment\_base\_address} function, and set its length using
  3461. \var{set\_segment\_limit} function.
  3462. You can manipulate the memory pointed to by the selector using the functions
  3463. of the GO32 unit. For instance with the \var{seg\_fillchar} function.
  3464. After using the selector, you must free it again using the
  3465. \var{free\_ldt\_selector} function.
  3466. More information on all this can be found in the \unitsref, the chapter on
  3467. the \file{go32} unit.
  3468. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3469. % Resource strings
  3470. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3471. \chapter{Resource strings}
  3472. \label{resourcestrings}
  3473. \section{Introduction}
  3474. Resource strings primarily exist to make internationalization of
  3475. applications easier, by introducing a language construct that provides
  3476. a uniform way of handling constant strings.
  3477. Most applications communicate with the user through some messages on the
  3478. graphical screen or console. Storing these messages in special constants
  3479. allows to store them in a uniform way in separate files, which can be used
  3480. for translation. A programmers interface exists to manipulate the actual
  3481. values of the constant strings at runtime, and a utility tool comes with the
  3482. Free Pascal compiler to convert the resource string files to whatever format
  3483. is wanted by the programmer. Both these things are discussed in the
  3484. following sections.
  3485. \section{The resource string file}
  3486. When a unit is compiled that contains a \var{resourcestring} section,
  3487. the compiler does 2 things:
  3488. \begin{enumerate}
  3489. \item It generates a table that contains the value of the strings as it
  3490. is declared in the sources.
  3491. \item It generates a {\em resource string file} that contains the names
  3492. of all strings, together with their declared values.
  3493. \end{enumerate}
  3494. This approach has 2 advantages: first of all, the value of the string is
  3495. always present in the program. If the programmer doesn't care to translate
  3496. the strings, the default values are always present in the binary. This also
  3497. avoids having to provide a file containing the strings. Secondly, having all
  3498. strings together in a compiler generated file ensures that all strings are
  3499. together (you can have multiple resourcestring sections in 1 unit or program)
  3500. and having this file in a fixed format, allows the programmer to choose his
  3501. way of internationalization.
  3502. For each unit that is compiled and that contains a resourcestring section,
  3503. the compiler generates a file that has the name of the unit, and an
  3504. extension \file{.rst}. The format of this file is as follows:
  3505. \begin{enumerate}
  3506. \item An empty line.
  3507. \item A line starting with a hash sign (\var{\#}) and the hash value of the
  3508. string, preceded by the text \var{hash value =}.
  3509. \item A third line, containing the name of the resource string in the format
  3510. \var{unitname.constantname}, all lowercase, followed by an equal sign, and
  3511. the string value, in a format equal to the pascal representation of this
  3512. string. The line may be continued on the next line, in that case it reads as
  3513. a pascal string expression with a plus sign in it.
  3514. \item Another empty line.
  3515. \end{enumerate}
  3516. If the unit contains no \var{resourcestring} section, no file is generated.
  3517. For example, the following unit:
  3518. \begin{verbatim}
  3519. unit rsdemo;
  3520. {$mode delphi}
  3521. {$H+}
  3522. interface
  3523. resourcestring
  3524. First = 'First';
  3525. Second = 'A Second very long string that should cover more than 1 line';
  3526. implementation
  3527. end.
  3528. \end{verbatim}
  3529. Will result in the following resource string file:
  3530. \begin{verbatim}
  3531. # hash value = 5048740
  3532. rsdemo.first='First'
  3533. # hash value = 171989989
  3534. rsdemo.second='A Second very long string that should cover more than 1 li'+
  3535. 'ne'
  3536. \end{verbatim}
  3537. The hash value is calculated with the function \var{Hash}. It is present in
  3538. the \file{objpas} unit. The value is the same value that the GNU gettext
  3539. mechanism uses. It is in no way unique, and can only be used to speed up
  3540. searches.
  3541. The \file{rstconv} utility that comes with the \fpc compiler allows to
  3542. manipulate these resource string files. At the moment, it can only be used
  3543. to make a \file{.po} file that can be fed to the GNU \file{msgfmt} program.
  3544. If someone wishes to have another format (Win32 resource files spring to
  3545. mind), one can enhance the \file{rstconv} program so it can generate
  3546. other types of files as well. GNU gettext was chosen because it is available
  3547. on all platforms, and is already widely used in the \var{Unix} and free
  3548. software community. Since the \fpc team doesn't want to restrict the use
  3549. of resource strings, the \file{.rst} format was chosen to provide a neutral
  3550. method, not restricted to any tool.
  3551. If you use resource strings in your units, and you want people to be able to
  3552. translate the strings, you must provide the resource string file. Currently,
  3553. there is no way to extract them from the unit file, though this is in
  3554. principle possible. It is not required to do this, the program can be
  3555. compiled without it, but then the translation of the strings isn't possible.
  3556. \section{Updating the string tables}
  3557. Having compiled a program with resourcestrings is not enough to
  3558. internationalize your program. At run-time, the program must initialize
  3559. the string tables with the correct values for the anguage that the user
  3560. selected. By default no such initialization is performed. All strings
  3561. are initialized with their declared values.
  3562. The \file{objpas} unit provides the mechanism to correctly initialize
  3563. the string tables. There is no need to include this unit in a \var{uses}
  3564. clause, since it is automatically loaded when a program or unit is
  3565. compiled in \var{Delphi} or \var{objfpc} mode. Since this is required
  3566. to use resource strings, the unit is always loaded when needed.
  3567. The resource strings are stored in tables, one per unit, and one for the
  3568. program, if it contains a \var{resourcestring} section as well. Each
  3569. resourcestring is stored with it's name, hash value, default value, and
  3570. the current value, all as \var{AnsiStrings}.
  3571. The objpas unit offers methods to retrieve the number of resourcestring
  3572. tables, the number of strings per table, and the above information for each
  3573. string. It also offers a method to set the current value of the strings.
  3574. Here are the declarations of all the functions:
  3575. \begin{verbatim}
  3576. Function ResourceStringTableCount : Longint;
  3577. Function ResourceStringCount(TableIndex : longint) : longint;
  3578. Function GetResourceStringName(TableIndex,
  3579. StringIndex : Longint) : Ansistring;
  3580. Function GetResourceStringHash(TableIndex,
  3581. StringIndex : Longint) : Longint;
  3582. Function GetResourceStringDefaultValue(TableIndex,
  3583. StringIndex : Longint) : AnsiString;
  3584. Function GetResourceStringCurrentValue(TableIndex,
  3585. StringIndex : Longint) : AnsiString;
  3586. Function SetResourceStringValue(TableIndex,
  3587. StringIndex : longint;
  3588. Value : Ansistring) : Boolean;
  3589. Procedure SetResourceStrings (SetFunction : TResourceIterator);
  3590. \end{verbatim}
  3591. Two other function exist, for convenience only:
  3592. \begin{verbatim}
  3593. Function Hash(S : AnsiString) : longint;
  3594. Procedure ResetResourceTables;
  3595. \end{verbatim}
  3596. Here is a short explanation of what each function does. A more detailed
  3597. explanation of the functions can be found in the \refref.
  3598. \begin{description}
  3599. \item[ResourceStringTableCount] returns the number of resource string tables
  3600. in the program.
  3601. \item[ResourceStringCount] returns the number of resource string entries in
  3602. a given table (tables are denoted by a zero-based index).
  3603. \item[GetResourceStringName] returns the name of a resource string in a
  3604. resource table. This is the name of the unit, a dot (.) and the name of
  3605. the string constant, all in lowercase. The strings are denoted by index,
  3606. also zero-based.
  3607. \item[GetResourceStringHash] returns the hash value of a resource string, as
  3608. calculated by the compiler with the \var{Hash} function.
  3609. \item[GetResourceStringDefaultValue] returns the default value of a resource
  3610. string, i.e. the value that appears in the resource string declaration, and
  3611. that is stored in the binary.
  3612. \item[GetResourceStringCurrentValue] returns the current value of a resource
  3613. string, i.e. the value set by the initialization (the default value), or the
  3614. value set by some previous internationalization routine.
  3615. \item[SetResourceStringValue] sets the current value of a resource string.
  3616. This function must be called to initialize all strings.
  3617. \item[SetResourceStrings] giving this function a callback will cause the
  3618. calback to be called for all resource strings, one by one, and set the value
  3619. of the string to the return value of the callback.
  3620. \end{description}
  3621. Two other functions exist, for convenience only:
  3622. \begin{description}
  3623. \item [Hash] can be used to calculate the hash value of a string. The hash
  3624. value stored in the tables is the result of this function, applied on the
  3625. default value. That value is calculated at compile time by the compiler.
  3626. \item[ResetResourceTables] will reset all the resource strings to their
  3627. default values. It is called by the initialization code of the objpas unit.
  3628. \end{description}
  3629. Given some \var{Translate} function, the following code would initialize
  3630. all resource strings:
  3631. \begin{verbatim}
  3632. Var I,J : Longint;
  3633. S : AnsiString;
  3634. begin
  3635. For I:=0 to ResourceStringTableCount-1 do
  3636. For J:=0 to ResourceStringCount(i)-1 do
  3637. begin
  3638. S:=Translate(GetResourceStringDefaultValue(I,J));
  3639. SetResourceStringValue(I,J,S);
  3640. end;
  3641. end;
  3642. \end{verbatim}
  3643. Other methods are of course possible, and the \var{Translate} function
  3644. can be implemented in a variety of ways.
  3645. \section{GNU gettext}
  3646. The unit \file{gettext} provides a way to internationalize an application
  3647. with the GNU \file{gettext} utilities. This unit is supplied with the
  3648. Free Component Library (FCL). it can be used as follows:
  3649. for a given application, the following steps must be followed:
  3650. \begin{enumerate}
  3651. \item Collect all resource string files and concatenate them together.
  3652. \item Invoke the \file{rstconv} program with the file resulting out of step
  3653. 1, resulting in a single \file{.po} file containing all resource strings of
  3654. the program.
  3655. \item Translate the \file{.po} file of step 2 in all required languages.
  3656. \item Run the \file{msgfmt} formatting program on all the \file{.po} files,
  3657. resulting in a set of \file{.mo} files, which can be distributed with your
  3658. application.
  3659. \item Call the \file{gettext} unit's \var{TranslateReosurceStrings} method,
  3660. giving it a template for the location of the \file{.mo} files, e.g. as in
  3661. \begin{verbatim}
  3662. TranslateResourcestrings('intl/restest.%s.mo');
  3663. \end{verbatim}
  3664. the \var{\%s} specifier will be replaced by the contents of the \var{LANG}
  3665. environment variable. This call should happen at program startup.
  3666. \end{enumerate}
  3667. An example program exists in the FCL sources, in the \file{fcl/tests}
  3668. directory.
  3669. \section{Caveat}
  3670. In principle it is possible to translate all resource strings at any time in
  3671. a running program. However, this change is not communicated to other
  3672. strings; its change is noticed only when a constant string is being used.
  3673. Consider the following example:
  3674. \begin{verbatim}
  3675. Const
  3676. help = 'With a little help of a programmer.';
  3677. Var
  3678. A : AnsiString;
  3679. begin
  3680. { lots of code }
  3681. A:=Help;
  3682. { Again some code}
  3683. TranslateStrings;
  3684. { More code }
  3685. \end{verbatim}
  3686. After the call to \var{TranslateStrings}, the value of \var{A} will remain
  3687. unchanged. This means that the assignment \var{A:=Help} must be executed
  3688. again in order for the change to become visible. This is important,
  3689. especially for GUI programs which have e.g. a menu. In order for the
  3690. change in resource strings to become visible, the new values must be
  3691. reloaded by program code into the menus \dots
  3692. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3693. % Optimizations done in the compiler
  3694. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3695. \chapter{Optimizations}
  3696. \section{Non processor specific}
  3697. The following sections describe the general optimizations
  3698. done by the compiler, they are not processor specific. Some
  3699. of these require some compiler switch override while others are done
  3700. automatically (those which require a switch will be noted as such).
  3701. \subsection{Constant folding}
  3702. In \fpc, if the operand(s) of an operator are constants, they
  3703. will be evaluated at compile time.
  3704. Example
  3705. \begin{verbatim}
  3706. x:=1+2+3+6+5;
  3707. \end{verbatim}
  3708. will generate the same code as
  3709. \begin{verbatim}
  3710. x:=17;
  3711. \end{verbatim}
  3712. Furthermore, if an array index is a constant, the offset will
  3713. be evaluated at compile time. This means that accessing MyData[5]
  3714. is as efficient as accessing a normal variable.
  3715. Finally, calling \var{Chr}, \var{Hi}, \var{Lo}, \var{Ord}, \var{Pred},
  3716. or \var{Succ} functions with constant parameters generates no
  3717. run-time library calls, instead, the values are evaluated at
  3718. compile time.
  3719. \subsection{Constant merging}
  3720. Using the same constant string, floating point value or constant set
  3721. two or more times generates only one copy of that constant.
  3722. \subsection{Short cut evaluation}
  3723. Evaluation of boolean expression stops as soon as the result is
  3724. known, which makes code execute faster then if all boolean operands
  3725. were evaluated.
  3726. \subsection{Constant set inlining}
  3727. Using the \var{in} operator is always more efficient then using the
  3728. equivalent \verb|<>|, \verb|=|, \verb|<=|, \verb|>=|, \verb|<| and \verb|>|
  3729. operators. This is because range comparisons can be done more easily with
  3730. \var{in} then with normal comparison operators.
  3731. \subsection{Small sets}
  3732. Sets which contain less then 33 elements can be directly encoded
  3733. using a 32-bit value, therefore no run-time library calls to
  3734. evaluate operands on these sets are required; they are directly encoded
  3735. by the code generator.
  3736. \subsection{Range checking}
  3737. Assignments of constants to variables are range checked at compile
  3738. time, which removes the need of the generation of runtime range checking
  3739. code.
  3740. \subsection{And instead of modulo}
  3741. When the second operand of a \var{mod} on an unsigned value is a constant
  3742. power of 2, an \var{and} instruction is used instead of an integer division.
  3743. This generates more efficient code.
  3744. \subsection{Shifts instead of multiply or divide}
  3745. When one of the operands in a multiplication is a power of
  3746. two, they are encoded using arithmetic shift instructions,
  3747. which generates more efficient code.
  3748. Similarly, if the divisor in a \var{div} operation is a power
  3749. of two, it is encoded using arithmetic shift instructions.
  3750. The same is true when accessing array indexes which are
  3751. powers of two, the address is calculated using arithmetic
  3752. shifts instead of the multiply instruction.
  3753. \subsection{Automatic alignment}
  3754. By default all variables larger then a byte are guaranteed to be aligned
  3755. at least on a word boundary.
  3756. Alignment on the stack and in the data section is processor dependant.
  3757. \subsection{Smart linking}
  3758. This feature removes all unreferenced code in the final executable
  3759. file, making the executable file much smaller.
  3760. Smart linking is switched on with the \var{-Cx} command-line switch, or
  3761. using the \var{\{\$SMARTLINK ON\}} global directive.
  3762. \subsection{Inline routines}
  3763. The following runtime library routines are coded directly into the
  3764. final executable: \var{Lo}, \var{Hi}, \var{High}, \var{Sizeof},
  3765. \var{TypeOf}, \var{Length}, \var{Pred}, \var{Succ}, \var{Inc},
  3766. \var{Dec} and \var{Assigned}.
  3767. \subsection{Stack frame omission}
  3768. Under specific conditions, the stack frame (entry and exit code for
  3769. the routine, see section \sees{CallingConventions}) will be omitted, and the
  3770. variable will directly be accessed via the stack pointer.
  3771. Conditions for omission of the stack frame:
  3772. \begin{itemize}
  3773. \item The function has no parameters nor local variables.
  3774. \item Routine is declared with the \var{assembler} modifier.
  3775. \item Routine is not a class.
  3776. \end{itemize}
  3777. \subsection{Register variables}
  3778. When using the \var{-Or} switch, local variables or parameters
  3779. which are used very often will be moved to registers for faster
  3780. access.
  3781. \section{Processor specific}
  3782. This lists the low-level optimizations performed, on a processor
  3783. per processor basis.
  3784. \subsection{Intel 80x86 specific}
  3785. Here follows a listing of the optimizing techniques used in the compiler:
  3786. \begin{enumerate}
  3787. \item When optimizing for a specific Processor (\var{-Op1, -Op2, -Op3},
  3788. the following is done:
  3789. \begin{itemize}
  3790. \item In \var{case} statements, a check is done whether a jump table
  3791. or a sequence of conditional jumps should be used for optimal performance.
  3792. \item Determines a number of strategies when doing peephole optimization, e.g.:
  3793. \var{movzbl (\%ebp), \%eax} will be changed into
  3794. \var{xorl \%eax,\%eax; movb (\%ebp),\%al } for Pentium and PentiumMMX.
  3795. \end{itemize}
  3796. \item When optimizing for speed (\var{-OG}, the default) or size (\var{-Og}), a choice is
  3797. made between using shorter instructions (for size) such as \var{enter \$4},
  3798. or longer instructions \var{subl \$4,\%esp} for speed. When smaller size is
  3799. requested, data is aligned to minimal boundaries. When speed is
  3800. requested, data is aligned on most efficient boundaries as much as possible.
  3801. \item Fast optimizations (\var{-O1}): activate the peephole optimizer
  3802. \item Slower optimizations (\var{-O2}): also activate the common subexpression
  3803. elimination (formerly called the "reloading optimizer")
  3804. \item Uncertain optimizations (\var{-Ou}): With this switch, the common subexpression
  3805. elimination algorithm can be forced into making uncertain optimizations.
  3806. Although you can enable uncertain optimizations in most cases, for people who
  3807. do not understand the following technical explanation, it might be the safest to
  3808. leave them off.
  3809. % Jonas's own words..
  3810. \begin{remark}If uncertain optimizations are enabled, the CSE algortihm assumes
  3811. that
  3812. \begin{itemize}
  3813. \item If something is written to a local/global register or a
  3814. procedure/function parameter, this value doesn't overwrite the value to
  3815. which a pointer points.
  3816. \item If something is written to memory pointed to by a pointer variable,
  3817. this value doesn't overwrite the value of a local/global variable or a
  3818. procedure/function parameter.
  3819. \end{itemize}
  3820. % end of quote
  3821. \end{remark}
  3822. The practical upshot of this is that you cannot use the uncertain
  3823. optimizations if you both write and read local or global variables directly and
  3824. through pointers (this includes \var{Var} parameters, as those are pointers too).
  3825. The following example will produce bad code when you switch on
  3826. uncertain optimizations:
  3827. \begin{verbatim}
  3828. Var temp: Longint;
  3829. Procedure Foo(Var Bar: Longint);
  3830. Begin
  3831. If (Bar = temp)
  3832. Then
  3833. Begin
  3834. Inc(Bar);
  3835. If (Bar <> temp) then Writeln('bug!')
  3836. End
  3837. End;
  3838. Begin
  3839. Foo(Temp);
  3840. End.
  3841. \end{verbatim}
  3842. The reason it produces bad code is because you access the global variable
  3843. \var{Temp} both through its name \var{Temp} and through a pointer, in this
  3844. case using the \var{Bar} variable parameter, which is nothing but a pointer
  3845. to \var{Temp} in the above code.
  3846. On the other hand, you can use the uncertain optimizations if
  3847. you access global/local variables or parameters through pointers,
  3848. and {\em only} access them through this pointer\footnote{
  3849. You can use multiple pointers to point to the same variable as well, that
  3850. doesn't matter.}.
  3851. For example:
  3852. \begin{verbatim}
  3853. Type TMyRec = Record
  3854. a, b: Longint;
  3855. End;
  3856. PMyRec = ^TMyRec;
  3857. TMyRecArray = Array [1..100000] of TMyRec;
  3858. PMyRecArray = ^TMyRecArray;
  3859. Var MyRecArrayPtr: PMyRecArray;
  3860. MyRecPtr: PMyRec;
  3861. Counter: Longint;
  3862. Begin
  3863. New(MyRecArrayPtr);
  3864. For Counter := 1 to 100000 Do
  3865. Begin
  3866. MyRecPtr := @MyRecArrayPtr^[Counter];
  3867. MyRecPtr^.a := Counter;
  3868. MyRecPtr^.b := Counter div 2;
  3869. End;
  3870. End.
  3871. \end{verbatim}
  3872. Will produce correct code, because the global variable \var{MyRecArrayPtr}
  3873. is not accessed directly, but only through a pointer (\var{MyRecPtr} in this
  3874. case).
  3875. In conclusion, one could say that you can use uncertain optimizations {\em
  3876. only} when you know what you're doing.
  3877. \end{enumerate}
  3878. \subsection{Motorola 680x0 specific}
  3879. Using the \var{-O2} (the default) switch does several optimizations
  3880. in the code produced, the most notable being:
  3881. \begin{itemize}
  3882. \item Sign extension from byte to long will use \var{EXTB}
  3883. \item Returning of functions will use \var{RTD}
  3884. \item Range checking will generate no run-time calls
  3885. \item Multiplication will use the long \var{MULS} instruction, no
  3886. runtime library call will be generated
  3887. \item Division will use the long \var{DIVS} instruction, no
  3888. runtime library call will be generated
  3889. \end{itemize}
  3890. \section{Optimization switches}
  3891. This is where the various optimizing switches and their actions are
  3892. described, grouped per switch.
  3893. \begin{description}
  3894. \item [-On:\ ] with n = 1..3: these switches activate the optimizer.
  3895. A higher level automatically includes all lower levels.
  3896. \begin{itemize}
  3897. \item Level 1 (\var{-O1}) activates the peephole optimizer
  3898. (common instruction sequences are replaced by faster equivalents).
  3899. \item Level 2 (\var{-O2}) enables the assembler data flow analyzer,
  3900. which allows the common subexpression elimination procedure to
  3901. remove unnecessary reloads of registers with values they already contain.
  3902. \item Level 3 (\var{-O3}) enables uncertain optimizations. For more info, see -Ou.
  3903. \end{itemize}
  3904. \item[-OG:\ ]
  3905. This causes the code generator (and optimizer, IF activated), to favor
  3906. faster, but code-wise larger, instruction sequences (such as
  3907. "\verb|subl $4,%esp|") instead of slower, smaller instructions
  3908. ("\verb|enter $4|"). This is the default setting.
  3909. \item[-Og:\ ] This one is exactly the reverse of -OG, and as such these
  3910. switches are mutually exclusive: enabling one will disable the other.
  3911. \item[-Or:\ ] This setting causes the code generator to
  3912. check which variables are used most, so it can keep those in a register.
  3913. \item[-Opn:\ ] with n = 1..3: Setting the target processor does NOT
  3914. activate the optimizer. It merely influences the code generator and,
  3915. if activated, the optimizer:
  3916. \begin{itemize}
  3917. \item During the code generation process, this setting is used to
  3918. decide whether a jump table or a sequence of successive jumps provides
  3919. the best performance in a case statement.
  3920. \item The peephole optimizer takes a number of decisions based on this
  3921. setting, for example it translates certain complex instructions, such
  3922. as
  3923. \begin{verbatim}
  3924. movzbl (mem), %eax|
  3925. \end{verbatim}
  3926. to a combination of simpler instructions
  3927. \begin{verbatim}
  3928. xorl %eax, %eax
  3929. movb (mem), %al
  3930. \end{verbatim}
  3931. for the Pentium.
  3932. \end{itemize}
  3933. \item[-Ou:\ ] This enables uncertain optimizations. You cannot use these
  3934. always, however. The previous section explains when they can be used, and
  3935. when they cannot be used.
  3936. \end{description}
  3937. \section{Tips to get faster code}
  3938. Here, some general tips for getting better code are presented. They
  3939. mainly concern coding style.
  3940. \begin{itemize}
  3941. \item Find a better algorithm. No matter how much you and the compiler
  3942. tweak the code, a quicksort will (almost) always outperform a bubble
  3943. sort, for example.
  3944. \item Use variables of the native size of the processor you're writing
  3945. for. This is currently 32-bit or 64-bit for \fpc, so you are best to
  3946. use longword and longint variables.
  3947. \item Turn on the optimizer.
  3948. \item Write your if/then/else statements so that the code in the "then"-part
  3949. gets executed most of the time (improves the rate of successful jump prediction).
  3950. \item Do not use ansistrings, widestrings and exception support, as these
  3951. require a lot of code overhead.
  3952. \item Profile your code (see the -pg switch) to find out where the
  3953. bottlenecks are. If you want, you can rewrite those parts in assembler.
  3954. You can take the code generated by the compiler as a starting point. When
  3955. given the \var{-a} command-line switch, the compiler will not erase the
  3956. assembler file at the end of the assembly process, so you can study the
  3957. assembler file.
  3958. \end{itemize}
  3959. \section{Tips to get smaller code}
  3960. Here are some tips given to get the smallest code possible.
  3961. \begin{itemize}
  3962. \item Find a better algorithm.
  3963. \item Use the \var{-Og} compiler switch.
  3964. \item Regroup global static variables in the same module which have the same
  3965. size together to minimize the number of alignment directives (which increases
  3966. the \var{.bss} and \var{.data} sections unecessarily). Internally this is
  3967. due to the fact that all static data is written to in the assembler file,
  3968. in the order they are declared in the pascal source code.
  3969. \item Do not use the \var{cdecl} modifier, as this generates
  3970. about 1 additional instruction after each subroutine call.
  3971. \item Use the smartlinking options for all your units
  3972. (including the \var{system} unit).
  3973. \item Do not use ansistrings, widestrings and exception support, as these
  3974. require a lot of code overhead.
  3975. \item Turn off range checking and stack-checking.
  3976. \item Turn off runtime type information generation
  3977. \end{itemize}
  3978. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3979. % programming shared libraries
  3980. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3981. \chapter{Programming shared libraries}
  3982. \label{ch:libraries}
  3983. \section{Introduction}
  3984. \fpc supports the creation of shared libraries on several operating
  3985. systems. The following table (\seet{DLLSupport}) indicates which
  3986. operating systems support the creation of shared libraries.
  3987. \begin{FPCltable}{lll}{Shared library support}{DLLSupport} \hline
  3988. Operating systems & Library extension & Library prefix \\ \hline
  3989. linux & .so & lib \\
  3990. windows & .dll & <none> \\
  3991. BeOS & .so & lib \\
  3992. FreeBSD & .so & lib \\
  3993. NetBSD & .so & lib \\
  3994. \hline
  3995. \end{FPCltable}
  3996. The library prefix column indicates how the names of the libraries are
  3997. resolved and created. For example, under \linux, the library name will
  3998. alwaus have the \var{lib} prefix when it is created. So if you create a
  3999. library called \file{mylib}, under \linux, this will result in the
  4000. \file{libmylib.so}. Furthermore, when importing routines from shared
  4001. libraries, it is not necessary to give the library prefix or the
  4002. filename extension.
  4003. In the following sections we discuss how to create a library, and how
  4004. to use these libraries in programs.
  4005. \section{Creating a library}
  4006. Creation of libraries is supported in any mode of the \fpc compiler,
  4007. but it may be that the arguments or return values differ if the library is
  4008. compiled in 2 different modes. E.g. if your function expects an
  4009. \var{Integer} argument, then the library will expect different integer
  4010. sizes if you compile it in Delphi mode or in TP mode.
  4011. A library can be created just as a program, only it uses the \var{library}
  4012. keyword, and it has an \var{exports} section. The following listing
  4013. demonstrates a simple library:
  4014. \FPCexample{subs}
  4015. The function \var{SubStr} does not have to be declared in the library file
  4016. itself. It can also be declared in the interface section of a unit that
  4017. is used by the library.
  4018. Compilation of this source will result in the creation of a library called
  4019. \file{libsubs.so} on \unix systems, or \file{subs.dll} on \windows or \ostwo.
  4020. The compiler will take care of any additional linking that is required to create a
  4021. shared library.
  4022. The library exports one function: \var{SubStr}. The case is important. The
  4023. case as it appears in the \var{exports} clause is used to export the
  4024. function.
  4025. If you want your library to be called from programs compiled with
  4026. other compilers, it is important to specify the correct calling
  4027. convention for the exported functions. Since the generated programs
  4028. by other compilers do not know about the \fpc calling conventions,
  4029. your functions would be called incorrectly, resulting in a corrupted
  4030. stack.
  4031. On \windows, most libraries use the \var{stdcall} convention, so it may be
  4032. better to use that one if your library is to be used on \windows systems. On
  4033. most \unix systems, the C calling convention is used, therefore the
  4034. \var{cdecl} modifier should be used in that case.
  4035. \section{Using a library in a pascal program}
  4036. In order to use a function that resides in a library, it is sufficient to
  4037. declare the function as it exists in the library as an \var{external}
  4038. function, with correct arguments and return type. The calling convention
  4039. used by the function should be declared correctly as well. The compiler
  4040. will then link the library as specified in the \var{external} statement
  4041. to your program\footnote{If you omit the library name in the \var{external}
  4042. modifier, then you can still tell the compiler to link to that library using
  4043. the \var{\{\$Linklib\}} directive.}.
  4044. For example, to use the library as defined above from a pascal program, you can use
  4045. the following pascal program:
  4046. \FPCexample{psubs}
  4047. As is shown in the example, you must declare the function as \var{external}.
  4048. Here also, it is necessary to specify the correct calling convention (it
  4049. should always match the convention as used by the function in the library),
  4050. and to use the correct casing for your declaration. Also notice, that
  4051. the library importing did not specify the filename extension, nor
  4052. was the \var{lib} prefix added.
  4053. This program can be compiled without any additional command-switches,
  4054. and should run just like that, provided the library is placed where
  4055. the system can find it. For example, on \linux, this is \file{/usr/lib} or any
  4056. directory listed in the \file{/etc/ld.so.conf} file. On \windows, this
  4057. can be the program directory, the \windows system directory, or any directoy
  4058. mentioned in the \var{PATH}.
  4059. Using the library in this way links the library to your program at compile
  4060. time. This means that
  4061. \begin{enumerate}
  4062. \item The library must be present on the system where the program is
  4063. compiled.
  4064. \item The library must be present on the system where the program is
  4065. executed.
  4066. \item Both libraries must be exactly the same.
  4067. \end{enumerate}
  4068. Or it may simply be that you don't know the name of the function to
  4069. be called, you just know the arguments it expects.
  4070. It is therefore also possible to load the library at run-time, store
  4071. the function address in a procedural variable, and use this procedural
  4072. variable to access the function in the library.
  4073. The following example demonstrates this technique:
  4074. \FPCexample{plsubs}
  4075. As in the case of compile-time linking, the crucial thing in this
  4076. listing is the declaration of the \var{TSubStrFunc} type.
  4077. It should match the declaration of the function you're trying to use.
  4078. Failure to specify a correct definition will result in a faulty stack or,
  4079. worse still, may cause your program to crash with an access violation.
  4080. \section{Using a pascal library from a C program}
  4081. \begin{remark}The examples in this section assume a \linux system; similar commands
  4082. as the ones below exist for other operating systems, though.
  4083. \end{remark}
  4084. You can also call a \fpc generated library from a C program:
  4085. \Cexample{ctest}
  4086. To compile this example, the following command can be used:
  4087. \begin{verbatim}
  4088. gcc -o ctest ctest.c -lsubs
  4089. \end{verbatim}
  4090. provided the code is in \file{ctest.c}.
  4091. The library can also be loaded dynamically from C, as shown in the following
  4092. example:
  4093. \Cexample{ctest2}
  4094. This can be compiled using the following command:
  4095. \begin{verbatim}
  4096. gcc -o ctest2 ctest2.c -ldl
  4097. \end{verbatim}
  4098. The \var{-ldl} tells gcc that the program needs the \file{libdl.so} library
  4099. to load dynamical libraries.
  4100. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4101. % Some windows issues
  4102. \section{Some Windows issues}
  4103. \label{shlibwinissues}
  4104. By default, \fpc (actually, the linker used by \fpc)
  4105. creates libraries that are not relocatable. This means that they must be
  4106. loaded at a fixed address in memory: this address is called the
  4107. ImageBase address. If two \fpc generated libraries are loaded by a
  4108. program, there will be a conflict, because the first librarie already
  4109. occupies the memory location where the second library should be loaded.
  4110. There are 2 switches in Free Pascal which control the generation of
  4111. shared libraries under \windows:
  4112. \begin{description}
  4113. \item[-WR] Generate a relocatable library. This library can be moved to
  4114. another location in memory if the ImageBase address it wants is already
  4115. in use.
  4116. \item[-WB] Specify the ImageBase address for the generated library.
  4117. The standard ImageBase used by \fpc is \var{0x10000000}. This switch
  4118. allows to change that by specifying another address, for instance
  4119. \var{-WB11000000}.
  4120. \end{description}
  4121. The first option is preferred, as a program may load many libraries
  4122. present on the system, and they could already be using the ImageBase
  4123. address. The second option is faster, as no relocation needs to be
  4124. done if the ImageBase address is not yet in use.
  4125. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4126. % using resources
  4127. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4128. \chapter{Using Windows resources}
  4129. \label{ch:windres}
  4130. \section{The resource directive \var{\$R}}
  4131. Under \windows, you can include resources in your executable or library
  4132. using the \var{\{\$R filename\}} directive. These resources can then
  4133. be accessed through the standard \windows API calls.
  4134. When the compiler encounters a resource directive, it just creates an
  4135. entry in the unit \file{.ppu} file; it doesn't link the resource. Only
  4136. when it creates a library or executable, it looks for all the resource
  4137. files for which it encountered a directive, and tries to link them in.
  4138. The default extension for resource files is \file{.res}. When the
  4139. filename has as the first character an asterix (\var{*}), the
  4140. compiler will replace the asterix with the name of the current unit,
  4141. library or program.
  4142. \begin{remark}This means that the asterix may only be used after a \var{unit},
  4143. \var{library} or \var{program} clause.
  4144. \end{remark}
  4145. \section{Creating resources}
  4146. The \fpc compiler itself doesn't create any resource files; it just
  4147. compiles them into the executable. To create resource files, you
  4148. can use some GUI tools as the Borland resource workshop; but it is
  4149. also possible to use a \windows resource compiler like \gnu
  4150. \file{windres}. \file{windres} comes with the \gnu binutils, but the
  4151. \fpc distribution also contains a version which you can use.
  4152. The usage of windres is straightforward; it reads an input file
  4153. describing the resources to create and outputs a resource file.
  4154. A typical invocation of \file{windres} would be
  4155. \begin{verbatim}
  4156. windres -i mystrings.rc -o mystrings.res
  4157. \end{verbatim}
  4158. this will read the \file{mystrings.rc} file and output a
  4159. \file{mystrings.res} resource file.
  4160. A complete overview of the windres tools is outside the scope of this
  4161. document, but here are some things you can use it for:
  4162. \begin{description}
  4163. \item[stringtables] that contain lists of strings.
  4164. \item[bitmaps] which are read from an external file.
  4165. \item[icons] which are also read from an external file.
  4166. \item[Version information] which can be viewed with the \windows
  4167. explorer.
  4168. \item[Menus] Can be designed as resources and used in your GUI
  4169. applications.
  4170. \item[Arbitrary data] Can be included as resources and read with the
  4171. windows API calls.
  4172. \end{description}
  4173. Some of these will be described below.
  4174. \section{Using string tables.}
  4175. String tables can be used to store and retrieve large collections of
  4176. strings in your application.
  4177. A string table looks as follows:
  4178. \begin{verbatim}
  4179. STRINGTABLE { 1, "hello World !"
  4180. 2, "hello world again !"
  4181. 3, "last hello world !" }
  4182. \end{verbatim}
  4183. You can compile this (we assume the file is called \file{tests.rc}) as
  4184. follows:
  4185. \begin{verbatim}
  4186. windres -i tests.rc -o tests.res
  4187. \end{verbatim}
  4188. And this is the way to retrieve the strings from your program:
  4189. \begin{verbatim}
  4190. program tests;
  4191. {$mode objfpc}
  4192. Uses Windows;
  4193. {$R *.res}
  4194. Function LoadResourceString (Index : longint): Shortstring;
  4195. begin
  4196. SetLength(Result,LoadString(FindResource(0,Nil,RT_STRING),Index,@Result[1],SizeOf(Result)))
  4197. end;
  4198. Var
  4199. I: longint;
  4200. begin
  4201. For i:=1 to 3 do
  4202. Writeln (Loadresourcestring(I));
  4203. end.
  4204. \end{verbatim}
  4205. The call to \var{FindResource} searches for the stringtable in the
  4206. compiled-in resources. The \var{LoadString} function then reads the
  4207. string with index \var{i} out of the table, and puts it in a buffer,
  4208. which can then be used. Both calls are in the \file{windows} unit.
  4209. \section{Inserting version information}
  4210. The win32 API allows to store version information in your binaries.
  4211. This information can be made visible with the \windows Explorer, by
  4212. right-clicking on the executable or library, and selecting the
  4213. 'Properties' menu. In the tab 'Version' the version information will
  4214. be displayed.
  4215. Here is how to insert version information in your binary:
  4216. \begin{verbatim}
  4217. 1 VERSIONINFO
  4218. FILEVERSION 4, 0, 3, 17
  4219. PRODUCTVERSION 3, 0, 0, 0
  4220. FILEFLAGSMASK 0
  4221. FILEOS 0x40000
  4222. FILETYPE 1
  4223. {
  4224. BLOCK "StringFileInfo"
  4225. {
  4226. BLOCK "040904E4"
  4227. {
  4228. VALUE "CompanyName", "Free Pascal"
  4229. VALUE "FileDescription", "Free Pascal version information extractor"
  4230. VALUE "FileVersion", "1.0"
  4231. VALUE "InternalName", "Showver"
  4232. VALUE "LegalCopyright", "GNU Public License"
  4233. VALUE "OriginalFilename", "showver.pp"
  4234. VALUE "ProductName", "Free Pascal"
  4235. VALUE "ProductVersion", "1.0"
  4236. }
  4237. }
  4238. }
  4239. \end{verbatim}
  4240. As you can see, you can insert various kinds of information in the version info
  4241. block. The keyword \var{VERSIONINFO} marks the beginning of the version
  4242. information resource block. The keywords \var{FILEVERSION},
  4243. \var{PRODUCTVERSION} give the actual file version, while the block
  4244. \var{StringFileInfo} gives other information that is displayed in the
  4245. explorer.
  4246. The Free Component Library comes with a unit (\file{fileinfo}) that allows
  4247. to extract and view version information in a straightforward and easy manner;
  4248. the demo program that comes with it (\file{showver}) shows version information
  4249. for an arbitrary executable or DLL.
  4250. \section{Inserting an application icon}
  4251. When \windows shows an executable in the Explorer, it looks for an icon
  4252. in the executable to show in front of the filename, the application
  4253. icon.
  4254. Inserting an application icon is very easy and can be done as follows
  4255. \begin{verbatim}
  4256. AppIcon ICON "filename.ico"
  4257. \end{verbatim}
  4258. This will read the file \file{filename.ico} and insert it in the
  4259. resource file.
  4260. \section{Using a pascal preprocessor}
  4261. Sometimes you want to use symbolic names in your resource file, and
  4262. use the same names in your program to access the resources. To accomplish
  4263. this, there exists a preprocessor for \file{windres} that understands pascal
  4264. syntax: \file{fprcp}. This preprocessor is shipped with the \fpc
  4265. distribution.
  4266. The idea is that the preprocessor reads a pascal unit that has some
  4267. symbolic constants defined in it, and replaces symbolic names in the
  4268. resource file by the values of the constants in the unit:
  4269. As an example: consider the follwoing unit:
  4270. \begin{verbatim}
  4271. unit myunit;
  4272. interface
  4273. Const
  4274. First = 1;
  4275. Second = 2:
  4276. Third = 3;
  4277. Implementation
  4278. end.
  4279. \end{verbatim}
  4280. And the following resource file:
  4281. \begin{verbatim}
  4282. #include "myunit.pp"
  4283. STRINGTABLE { First, "hello World !"
  4284. Second, "hello world again !"
  4285. Third, "last hello world !" }
  4286. \end{verbatim}
  4287. if you invoke windres with the \var{--preprocessor} option:
  4288. \begin{verbatim}
  4289. windres --preprocessor fprcp -i myunit.rc -o myunit.res
  4290. \end{verbatim}
  4291. Then the preprocessor will replace the symbolic names 'first', 'second'
  4292. and 'third' with their actual values.
  4293. In your program, you can then refer to the strings by their symbolic
  4294. names (the constants) instead of using a numeric index.
  4295. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4296. % Appendices
  4297. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4298. \appendix
  4299. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4300. % Appendix A
  4301. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4302. \chapter{Anatomy of a unit file}
  4303. \label{ch:AppA}
  4304. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4305. % Basics
  4306. \section{Basics}
  4307. As described in \seec{GenCode}, unit description files (hereafter
  4308. called PPU files for short), are used to determine if the unit
  4309. code must be recompiled or not. In other words, the PPU files act
  4310. as mini-makefiles, which is used to check dependencies of the
  4311. different code modules, as well as verify if the modules are up
  4312. to date or not. Furthermore, it contains all public symbols defined
  4313. for a module.
  4314. The general format of the \var{ppu} file format is shown
  4315. in \seefig{ppu}.
  4316. \FPCpic{The PPU file format}{}{ppu}
  4317. To read or write the ppufile, the ppu unit \file{ppu.pas} can be used,
  4318. which has an object called tppufile which holds all routines that deal
  4319. with ppufile handling. While describing the layout of a ppufile, the
  4320. methods which can be used for it are presented as well.
  4321. A unit file consists of basically five or six parts:
  4322. \begin{enumerate}
  4323. \item A unit header.
  4324. \item A general information part (wrongly named interface section in the code)
  4325. \item A definition part. Contains all type and procedure definitions.
  4326. \item A symbol part. Contains all symbol names and references to their
  4327. definitions.
  4328. \item A browser part. Contains all references from this unit to other
  4329. units and inside this unit. Only available when the \var{uf\_has\_browser} flag is
  4330. set in the unit flags
  4331. \item A file implementation part (currently unused).
  4332. \end{enumerate}
  4333. \section{reading ppufiles}
  4334. We will first create an object ppufile which will be used below. We are
  4335. opening unit \file{test.ppu} as an example.
  4336. \begin{verbatim}
  4337. var
  4338. ppufile : pppufile;
  4339. begin
  4340. { Initialize object }
  4341. ppufile:=new(pppufile,init('test.ppu');
  4342. { open the unit and read the header, returns false when it fails }
  4343. if not ppufile.openfile then
  4344. error('error opening unit test.ppu');
  4345. { here we can read the unit }
  4346. { close unit }
  4347. ppufile.closefile;
  4348. { release object }
  4349. dispose(ppufile,done);
  4350. end;
  4351. \end{verbatim}
  4352. Note: When a function fails (for example not enough bytes left in an
  4353. entry) it sets the \var{ppufile.error} variable.
  4354. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4355. % The Header
  4356. \section{The Header}
  4357. The header consists of a record (\var{tppuheader}) containing
  4358. several pieces of information for recompilation. This is shown
  4359. in \seet{PPUHeader}. The header is always stored in little-endian
  4360. format.
  4361. \begin{FPCltable}{|l|c|l|}{PPU Header}{PPUHeader}
  4362. \hline
  4363. offset & size (bytes) & description \\
  4364. \hline
  4365. 00h & 3 & Magic : 'PPU' in ASCII \\
  4366. 03h & 3 & PPU File format version (e.g : '021' in ASCII) \\
  4367. 06h & 2 & Compiler version used to compile this module (major,minor)\\
  4368. 08h & 2 & Code module target processor \\
  4369. 0Ah & 2 & Code module target operating system \\
  4370. 0Ch & 4 & Flags for PPU file \\
  4371. 10h & 4 & Size of PPU file (without header) \\
  4372. 14h & 4 & CRC-32 of the entire PPU file \\
  4373. 18h & 4 & CRC-32 of partial data of PPU file (public data mostly) \\
  4374. 1Ch & 8 & Reserved \\
  4375. \hline
  4376. \end{FPCltable}
  4377. The header is already read by the \var{ppufile.openfile} command.
  4378. You can access all fields using \var{ppufile.header} which holds
  4379. the current header record.
  4380. \begin{FPCltable}{|ll|}{PPU CPU Field values}{PPUHeaderCPU}
  4381. \hline
  4382. value & description \\
  4383. \hline
  4384. 0 & unknown \\
  4385. 1 & Intel 80x86 or compatible \\
  4386. 2 & Motorola 680x0 or compatible \\
  4387. 3 & Alpha AXP or compatible \\
  4388. 4 & PowerPC or compatible \\
  4389. \hline
  4390. \end{FPCltable}
  4391. Some of the possible flags in the header, are described in \seet{PPUHeaderFlags}.
  4392. Not all the flags are described, for more information, read the source code of
  4393. \file{ppu.pas}.
  4394. \begin{FPCltable}{|ll|}{PPU Header Flag values}{PPUHeaderFlags}
  4395. \hline
  4396. Symbolic bit flag name & Description\\
  4397. \hline
  4398. uf\_init & Module has an initialization (either Delphi or TP style) section. \\
  4399. uf\_finalize & Module has a finalization section. \\
  4400. uf\_big\_endian & All the data stored in the chunks is in big-endian format.\\
  4401. uf\_has\_browser & Unit contains symbol browser information. \\
  4402. uf\_smart\_linked & The code module has been smartlinked.\\
  4403. uf\_static\_linked & The code is statically linked. \\
  4404. uf\_has\_resources & Unit has resource section. \\
  4405. \hline
  4406. \end{FPCltable}
  4407. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
  4408. % The sections
  4409. \section{The sections}
  4410. Apart from the header section, all the data in the PPU file is separated
  4411. into data blocks, which permit easily adding additional data blocks,
  4412. without compromising backward compatibility. This is similar to both
  4413. Electronic Arts IFF chunk format and Microsoft's RIFF chunk format.
  4414. Each 'chunk' (\var{tppuentry}) has the following format, and can be
  4415. nested:
  4416. \begin{FPCltable}{|l|c|l|}{chunk data format}{ChunkFormats}
  4417. \hline
  4418. offset & size (bytes) & description \\
  4419. \hline
  4420. 00h & 1 & Block type (nested (2) or main (1)) \\
  4421. 01h & 1 & Block identifier \\
  4422. 02h & 4 & Size of this data block \\
  4423. 06h+ & <variable> & Data for this block \\
  4424. \hline
  4425. \end{FPCltable}
  4426. Each main section chunk must end with an end chunk. Nested chunks
  4427. are used for record, class or object fields.
  4428. To read an entry you can simply call \var{ppufile.readentry:byte},
  4429. it returns the
  4430. \var{tppuentry.nr} field, which holds the type of the entry.
  4431. A common way how this works is (example is for the symbols):
  4432. \begin{verbatim}
  4433. repeat
  4434. b:=ppufile.readentry;
  4435. case b of
  4436. ib<etc> : begin
  4437. end;
  4438. ibendsyms : break;
  4439. end;
  4440. until false;
  4441. \end{verbatim}
  4442. The possible entry types are found in \file{ppu.pas}, but a short
  4443. description of the most common ones are shown in \seet{PPUEntryTypes}.
  4444. \begin{FPCltable}{|lll|}{Possible PPU Entry types}{PPUEntryTypes}
  4445. \hline
  4446. Symbolic name & Location & Description\\
  4447. \hline
  4448. ibmodulename & General & Name of this unit.\\
  4449. ibsourcefiles & General & Name of source files.\\
  4450. ibusedmacros & General & Name and state of macros used.\\
  4451. ibloadunit & General & Modules used by this units. \\
  4452. inlinkunitofiles & General & Object files associated with this unit. \\
  4453. iblinkunitstaticlibs & General & Static libraries associated with this unit. \\
  4454. iblinkunitsharedlibs & General & Shared libraries associated with this unit. \\
  4455. ibendinterface & General & End of General information section. \\
  4456. ibstartdefs & Interface & Start of definitions. \\
  4457. ibenddefs & Interface & End of definitions. \\
  4458. ibstartsyms & Interface & Start of symbol data. \\
  4459. ibendsyms & Interface & End of symbol data. \\
  4460. ibendimplementation & Implementation & End of implementation data. \\
  4461. ibendbrowser & Browser & End of browser section. \\
  4462. ibend & General & End of Unit file. \\
  4463. \hline
  4464. \end{FPCltable}
  4465. Then you can parse each entry type yourself. \var{ppufile.readentry} will take
  4466. care of skipping unread bytes in the entry and reads the next entry
  4467. correctly! A special function is \var{skipuntilentry(untilb:byte):boolean;}
  4468. which will read the ppufile until it finds entry \var{untilb} in the main
  4469. entries.
  4470. Parsing an entry can be done with \var{ppufile.getxxx} functions. The
  4471. available functions are:
  4472. \begin{verbatim}
  4473. procedure ppufile.getdata(var b;len:longint);
  4474. function getbyte:byte;
  4475. function getword:word;
  4476. function getlongint:longint;
  4477. function getreal:ppureal;
  4478. function getstring:string;
  4479. \end{verbatim}
  4480. To check if you're at the end of an entry you can use the following
  4481. function:
  4482. \begin{verbatim}
  4483. function EndOfEntry:boolean;
  4484. \end{verbatim}
  4485. {\em notes:}
  4486. \begin{enumerate}
  4487. \item \var{ppureal} is the best real that exists for the cpu where the
  4488. unit is created for. Currently it is \var{extended} for i386 and
  4489. \var{single} for m68k.
  4490. \item the \var{ibobjectdef} and \var{ibrecorddef} have stored a definition
  4491. and symbol section for themselves. So you'll need a recursive call. See
  4492. \file{ppudump.pp} for a correct implementation.
  4493. \end{enumerate}
  4494. A complete list of entries and what their fields contain can be found
  4495. in \file{ppudump.pp}.
  4496. \section{Creating ppufiles}
  4497. Creating a new ppufile works almost the same as reading one.
  4498. First you need to init the object and call create:
  4499. \begin{verbatim}
  4500. ppufile:=new(pppufile,init('output.ppu'));
  4501. ppufile.createfile;
  4502. \end{verbatim}
  4503. After that you can simply write all needed entries. You'll have to take
  4504. care that you write at least the basic entries for the sections:
  4505. \begin{verbatim}
  4506. ibendinterface
  4507. ibenddefs
  4508. ibendsyms
  4509. ibendbrowser (only when you've set uf_has_browser!)
  4510. ibendimplementation
  4511. ibend
  4512. \end{verbatim}
  4513. Writing an entry is a little different than reading it. You need to first
  4514. put everything in the entry with ppufile.putxxx:
  4515. \begin{verbatim}
  4516. procedure putdata(var b;len:longint);
  4517. procedure putbyte(b:byte);
  4518. procedure putword(w:word);
  4519. procedure putlongint(l:longint);
  4520. procedure putreal(d:ppureal);
  4521. procedure putstring(s:string);
  4522. \end{verbatim}
  4523. After putting all the things in the entry you need to call
  4524. \var{ppufile.writeentry(ibnr:byte)} where \var{ibnr} is the entry number
  4525. you're writing.
  4526. At the end of the file you need to call \var{ppufile.writeheader} to write the
  4527. new header to the file. This takes automatically care of the new size of the
  4528. ppufile. When that is also done you can call \var{ppufile.closefile} and dispose the
  4529. object.
  4530. Extra functions/variables available for writing are:
  4531. \begin{verbatim}
  4532. ppufile.NewHeader;
  4533. ppufile.NewEntry;
  4534. \end{verbatim}
  4535. This will give you a clean header or entry. Normally this is called
  4536. automatically in \var{ppufile.writeentry}, so there should be no need to
  4537. call these methods.
  4538. \begin{verbatim}
  4539. ppufile.flush;
  4540. \end{verbatim}
  4541. to flush the current buffers to the disk
  4542. \begin{verbatim}
  4543. ppufile.do_crc:boolean;
  4544. \end{verbatim}
  4545. set to false if you don't want that the crc is updated, this is necessary
  4546. if you write for example the browser data.
  4547. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4548. % Appendix B
  4549. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4550. \chapter{Compiler and RTL source tree structure}
  4551. \label{ch:AppB}
  4552. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4553. % The compiler source tree
  4554. \section{The compiler source tree}
  4555. All compiler source files are in several directories, normally the
  4556. non-processor specific parts are in \file{source/compiler}. Subdirectories
  4557. are present for each of the supported processors and target operating systems.
  4558. For more informations about the structure of the compiler have a look at the
  4559. Compiler Manual which contains also some informations about
  4560. compiler internals.
  4561. The \file{compiler} directory also contains a subdirectory \var{utils},
  4562. which contains mainly the utilities for creation and maintainance of the
  4563. message files.
  4564. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4565. % The RTL source tree
  4566. \section{The RTL source tree}
  4567. The RTL source tree is divided in many subdirectories, but is very
  4568. structured and easy to understand. It mainly consists of three parts:
  4569. \begin{enumerate}
  4570. \item A OS-dependent directory. This contains the files that are different for
  4571. each operating system. When compiling the RTL, you should do it here. The
  4572. following directories exist:
  4573. \begin{itemize}
  4574. \item \file{atari} for the \atari.
  4575. \item \file{amiga} for the \amiga.
  4576. \item \file{beos} for \beos. It has one subdirectory for each of the
  4577. supported processors.
  4578. \item \file{freebsd} for the \freebsd platform.
  4579. \item \file{go32v1} For \dos, using the GO32v1 extender. Not maintained any
  4580. more.
  4581. \item \file{go32v2} For \dos, using the GO32v2 extender.
  4582. \item \file{linux} for \linux platforms. It has one subdirectory for each of the supported
  4583. processors.
  4584. \item \file{netbsd} for \netbsd platforms. It has one subdirectory for each of the supported
  4585. processors.
  4586. \item \file{palmos} for the \palmos Dragonball processor based platform.
  4587. \item \file{os2} for \ostwo.
  4588. \item \file{sunos} for the \solaris platform. It has one subdirectory for each of the supported
  4589. processors.
  4590. \item \file{qnx} for the \qnx.
  4591. \item \file{win32} for Win32 platforms.
  4592. \item \file{posix} for posix interfaces (used for easier porting).
  4593. \item \file{unix} for unix common interfaces (used for easier porting).
  4594. \end{itemize}
  4595. \item A processor dependent directory. This contains files that are system
  4596. independent, but processor dependent. It contains mostly optimized routines
  4597. for a specific processor. The following directories exist:
  4598. \begin{itemize}
  4599. \item \file{i386} for the Intel 80x86 series of processors.
  4600. \item \file{m68k} for the Motorola 680x0 series of processors.
  4601. \end{itemize}
  4602. \item An OS-independent and Processor independent directory: \file{inc}. This
  4603. contains complete units, and include files containing interface parts of
  4604. units as well as generic versions of processor specific routines.
  4605. \end{enumerate}
  4606. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4607. % Appendix C
  4608. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4609. \chapter{Compiler limits}
  4610. \label{ch:AppC}
  4611. There are certain compiler limits inherent to the compiler:
  4612. \begin{enumerate}
  4613. \item Procedure or Function definitions can be nested to a level of 32. This
  4614. can be changed by changing the \var{maxnesting} constant.
  4615. \item Maximally 1024 units can be used in a program when using the compiler.
  4616. You can change this by redefining the \var{maxunits} constant in the compiler
  4617. source file.
  4618. \item The maximum nesting level of pre-processor macros is 16. This can be
  4619. changed by changing the value of \var{max\_macro\_nesting}.
  4620. \item Arrays are limited to 2 GBytes in size in the default processor mode.
  4621. \end{enumerate}
  4622. For processor specific compiler limitations refer to the Processor
  4623. Limitations section in this guide (\ref{se:ProcessorLimits}).
  4624. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4625. % Appendix D
  4626. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4627. \chapter{Compiler modes}
  4628. \label{ch:AppD}
  4629. Here we list the exact effect of the different compiler modes. They can be
  4630. set with the \var{\$Mode} switch, or by command line switches.
  4631. \section{FPC mode}
  4632. This mode is selected by the \var{{\$MODE FPC}} switch. On the command-line,
  4633. this means that you use none of the other compatibility mode switches.
  4634. It is the default mode of the compiler. This means essentially:
  4635. \begin{enumerate}
  4636. \item You must use the address operator to assign procedural variables.
  4637. \item A forward declaration must be repeated exactly the same by the
  4638. implementation of a function/procedure. In particular, you can not omit the
  4639. parameters when implementing the function or procedure.
  4640. \item Overloading of functions is allowed.
  4641. \item Nested comments are allowed.
  4642. \item The Objpas unit is NOT loaded.
  4643. \item You can use the cvar type.
  4644. \item PChars are converted to strings automatically.
  4645. \end{enumerate}
  4646. \section{TP mode}
  4647. This mode is selected by the \var{{\$MODE TP}} switch. It tries to emulate,
  4648. as closely as possible, the behavior of Turbo Pascal 7. On the command-line,
  4649. this mode is selected by the \var{-So} switch.
  4650. \begin{enumerate}
  4651. \item Enumeration sizes default to a storage size of 1 byte if there
  4652. are less than 257 elements.
  4653. \item You cannot use the address operator to assign procedural variables.
  4654. \item A forward declaration must not be repeated exactly the same by the
  4655. implementation of a function/procedure. In particular, you can omit the
  4656. parameters when implementing the function or procedure.
  4657. \item Overloading of functions is not allowed.
  4658. \item The Objpas unit is NOT loaded.
  4659. \item Nested comments are not allowed.
  4660. \item You can not use the cvar type.
  4661. \end{enumerate}
  4662. \section{Delphi mode}
  4663. This mode is selected by the \var{{\$MODE DELPHI}} switch. It tries to emulate,
  4664. as closely as possible, the behavior of Delphi 4. On the command-line,
  4665. this mode is selected by the \var{-Sd} switch.
  4666. \begin{enumerate}
  4667. \item You can not use the address operator to assign procedural variables.
  4668. \item A forward declaration must not be repeated exactly the same by the
  4669. implementation of a function/procedure. In particular, you not omit the
  4670. parameters when implementing the function or procedure.
  4671. \item Overloading of functions is not allowed.
  4672. \item Nested comments are not allowed.
  4673. \item The Objpas unit is loaded right after the \file{system} unit. One of the
  4674. consequences of this is that the type \var{Integer} is redefined as
  4675. \var{Longint}.
  4676. \end{enumerate}
  4677. \section{GPC mode}
  4678. This mode is selected by the \var{{\$MODE GPC}} switch. On the command-line,
  4679. this mode is selected by the \var{-Sp} switch.
  4680. \begin{enumerate}
  4681. \item You must use the address operator to assign procedural variables.
  4682. \item A forward declaration must not be repeated exactly the same by the
  4683. implementation of a function/procedure. In particular, you can omit the
  4684. parameters when implementing the function or procedure.
  4685. \item Overloading of functions is not allowed.
  4686. \item The Objpas unit is NOT loaded.
  4687. \item Nested comments are not allowed.
  4688. \item You can not use the cvar type.
  4689. \end{enumerate}
  4690. \section{OBJFPC mode}
  4691. This mode is selected by the \var{{\$MODE OBJFPC}} switch. On the command-line,
  4692. this mode is selected by the \var{-S2} switch.
  4693. \begin{enumerate}
  4694. \item You must use the address operator to assign procedural variables.
  4695. \item A forward declaration must be repeated exactly the same by the
  4696. implementation of a function/procedure. In particular, you can not omit the
  4697. parameters when implementing the function or procedure.
  4698. \item Overloading of functions is allowed.
  4699. \item Nested comments are allowed.
  4700. \item The Objpas unit is loaded right after the \file{system} unit. One of the
  4701. consequences of this is that the type \var{Integer} is redefined as
  4702. \var{Longint}.
  4703. \item You can use the cvar type.
  4704. \item PChars are converted to strings automatically.
  4705. \end{enumerate}
  4706. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4707. % Appendix E
  4708. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4709. \chapter{Using \file{fpcmake}}
  4710. \label{ch:makefile}
  4711. \newcommand{\mvar}[1]{\var{\$(#1)}}
  4712. \newcommand{\fpcmake}{\file{fpcmake}}
  4713. \section{Introduction}
  4714. \fpc comes with a special makefile tool, \fpcmake{}, which can be
  4715. used to construct a \file{Makefile} for use with \gnu \file{make}.
  4716. All sources from the \fpc team are compiled with this system.
  4717. \fpcmake{} uses a file \file{Makefile.fpc} and constructs a file
  4718. \file{Makefile} from it, based on the settings in \file{Makefile.fpc}.
  4719. The following sections explain what settings can be set in \file{Makefile.fpc},
  4720. what variables are set by \var{fpcmake}, what variables it expects to be set,
  4721. and what targets it defines. After that, some settings in the resulting
  4722. \file{Makefile} are explained.
  4723. \section{Functionality}
  4724. \label{se:fpcmakefunctionality}
  4725. \file{fpcmake} generates a makefile, suitable for GNU \file{make},
  4726. which can be used to
  4727. \begin{enumerate}
  4728. \item Compile units and programs, fit for testing or for final distribution.
  4729. \item Compile example units and programs separately.
  4730. \item Install compiled units and programs in standard locations.
  4731. \item Make archives for distribution of the generated programs and units.
  4732. \item Clean up after compilation and tests.
  4733. \end{enumerate}
  4734. \file{fpcmake} knows how the \fpc compiler operates, which command line
  4735. options it uses, how it searches for files and so on; It uses this knowledge
  4736. to construct sensible command-lines.
  4737. Specifically, it constructs the following targets in the final makefile:
  4738. \begin{description}
  4739. \item[all] Makes all units and programs.
  4740. \item[debug] Makes all units and programs with debug info included.
  4741. \item[smart] Makes all units and programs in smartlinked version.
  4742. \item[examples] Makes all example units and programs.
  4743. \item[shared] Makes all units and programs in shared library version
  4744. (currently disabled)
  4745. \item[install] Installs all units and programs.
  4746. \item[sourceinstall] Installs the sources to the \fpc source tree.
  4747. \item[exampleinstall] Installs any example programs and units.
  4748. \item[distinstall] Installs all units and programs, as well as example units
  4749. and programs.
  4750. \item[zipinstall] Makes an archive of the programs and units which can be
  4751. used to install them on another location, i.e. it makes an archive that can
  4752. be used to distribute the units and programs.
  4753. \item[zipsourceinstall] Makes an archive of the program and unit sources
  4754. which can be used to distribute the sources.
  4755. \item[zipexampleinstall] Makes an archive of the example programs and units
  4756. which can be used to install them on another location, i.e. it makes an
  4757. archive that can be used to distribute the example units and programs.
  4758. \item[zipdistinstall] Makes an archive of both the normal as well as the
  4759. example programs and units. This archive can be used to install them on
  4760. another location, i.e. it makes an archive that can be used to
  4761. distribute.
  4762. \item[clean] Cleans all files that are produced by a compilation.
  4763. \item[distclean] Cleans all files that are produced by a compilation, as
  4764. well as any archives, examples or files left by examples.
  4765. \item[cleanall] Same as clean.
  4766. \item[info] Produces some information on the screen about used programs,
  4767. file and directory locations, where things will go when installing and so
  4768. on.
  4769. \end{description}
  4770. Each of these targets can be highly configured, or even totally overridden
  4771. by the configuration file \file{Makefile.fpc}
  4772. \section{Usage}
  4773. \file {fpcmake} reads a \file{Makefile.fpc} and converts it to a
  4774. \file{Makefile} suitable for reading by \gnu \file{make}
  4775. to compile your projects. It is similar in functionality to GNU
  4776. \file{configure} or \file{Imake} for making X projects.
  4777. \fpcmake{} accepts filenames of makefile description files
  4778. as its command-line arguments. For each of these files it will
  4779. create a \file{Makefile} in the same directory where the file is
  4780. located, overwriting any existing file with that name.
  4781. If no options are given, it just attempts to read the file
  4782. \file{Makefile.fpc} in the current directory and tries to
  4783. construct a \file{Makefile} from it if the \var{-m} option is
  4784. given. Any previously existing \file{Makefile} will be erased.
  4785. if the \var{-p} option is given, instead of a \file{Makefile}, a
  4786. \var{Package.fpc} is generated. A \file{Package.fpc} file describes the
  4787. package and it's dependencies on other packages.
  4788. Additionally, the following command-line options are recognized:
  4789. \begin{description}
  4790. \item[-p] A \file{Package.fpc} file is generated.
  4791. \item[-w] A \file{Makefile} is generated.
  4792. \item[-T targets] Support only specified target systems. \var{Targets} is a
  4793. comma-separated list of targets. Only rule for the specified targets
  4794. will be written.
  4795. \item[-v] Be more verbose.
  4796. \item[-q] be quiet.
  4797. \item[-h] Writes a small help message to the screen.
  4798. \end{description}
  4799. % Makefile.fpc format.
  4800. \section{Format of the configuration file}
  4801. This section describes the rules that can be present in the file
  4802. that is fed to \fpcmake{}.
  4803. The file \file{Makefile.fpc} is a plain ASCII file that contains
  4804. a number of pre-defined sections as in a \windows \file{.ini}-file,
  4805. or a Samba configuration file.
  4806. They look more or less as follows:
  4807. \begin{verbatim}
  4808. [package]
  4809. name=mysql
  4810. version=1.0.5
  4811. [target]
  4812. units=mysql_com mysql_version mysql
  4813. examples=testdb
  4814. [require]
  4815. libc=y
  4816. [install]
  4817. fpcpackage=y
  4818. [default]
  4819. fpcdir=../..
  4820. \end{verbatim}
  4821. The following sections are recognized (in alphabetical order):
  4822. \subsection{clean}
  4823. Specifies rules for cleaning the directory of units and programs.
  4824. The following entries are recognized:
  4825. \begin{description}
  4826. \item[units] names of all units that should be removed when cleaning.
  4827. Don't specify extensions, the makefile will append these by itself.
  4828. \item[files] names of files that should be removed. Specify full filenames.
  4829. \end{description}
  4830. \subsection{compiler}
  4831. In this section values for various compiler options can be specified,
  4832. such as the location of several directories and search paths.
  4833. The following general keywords are recognised:
  4834. \begin{description}
  4835. \item[options] The value of this key will be passed on to the compiler as
  4836. options.
  4837. \item[version] If a specific or minimum compiler version is needed to
  4838. compile the units or programs, then this version should be specified here.
  4839. \end{description}
  4840. The following keys can be used to control the location of the various
  4841. directories used by the compiler:
  4842. \begin{description}
  4843. \item[unitdir]
  4844. A colon-separated list of directories that must be added to the unit
  4845. search path of the compiler.
  4846. \item[librarydir]
  4847. A colon-separated list of directories that must be added to the library
  4848. search path of the compiler.
  4849. \item[objectdir]
  4850. A colon-separated list of directories that must be added to the object file
  4851. search path of the compiler.
  4852. \item[targetdir]
  4853. Specifies the directory where the compiled programs should go.
  4854. \item[sourcedir]
  4855. A space separated list of directories where sources can reside.
  4856. This will be used for the \var{vpath} setting of \gnu \file{make}.
  4857. \item[unittargetdir]
  4858. Specifies the directory where the compiled units should go.
  4859. \item[includedir]
  4860. A colon-separated list of directories that must be added to the include file
  4861. search path of the compiler.
  4862. \item[sourcedir]
  4863. \end{description}
  4864. \subsection{Default}
  4865. The \var{default} section contains some default settings. The following keywords
  4866. are recognized:
  4867. \begin{description}
  4868. \item[cpu]
  4869. Specifies the default target processor for which the \file{Makefile}
  4870. should compile the units and programs. By default this is determined from
  4871. the default compiler processor.
  4872. \item[dir]
  4873. Specifies any subdirectories that make should also descend in and
  4874. make the specified target there as well.
  4875. \item[fpcdir]
  4876. Specifies the directory where all the \fpc source trees reside. Below this
  4877. directory the \file{Makefile} expects to find the \file{rtl}, \file{fcl} and
  4878. \file{packages} directory trees.
  4879. \item[rule] Specifies the default rule to execute. \fpcmake{}
  4880. will make sure that this rule is executed if make is executed without
  4881. arguments, i.e., without an explicit target.
  4882. \item[target]
  4883. Specifies the default operating system target for which the \file{Makefile}
  4884. should compile the units and programs. By default this is determined from
  4885. the default compiler target.
  4886. \end{description}
  4887. \subsection{Dist}
  4888. The \var{Dist} section controls the generation of a distribution package.
  4889. A distribution package is a set of archive files (zip files or tar files
  4890. on unix systems) that can be used to distribute the package.
  4891. The following keys can be placed in this section:
  4892. \begin{description}
  4893. \item[destdir] Specifies the directory where the generated zip files should
  4894. be placed.
  4895. \item[zipname] Name of the archive file to be created. If no zipname is
  4896. specified, this defaults to the package name.
  4897. \item[ziptarget] This is the target that should be executed before the
  4898. archive file is made. This defaults to \var{install}.
  4899. \end{description}
  4900. \subsection{Install}
  4901. Contains instructions for installation of the compiler units and programs. The
  4902. following keywords are recognized:
  4903. \begin{description}
  4904. \item[basedir]
  4905. The directory that is used as the base directory for the installation of
  4906. units. Default this is \var{prefix} appended with \var{/lib/fpc/FPC\_VERSION}
  4907. for \linux or simply the \var{prefix} on other platforms.
  4908. \item[datadir] Directory where data files will be installed, i.e. the files
  4909. specified with the \var{Files} keyword.
  4910. \item[fpcpackage] A boolean key. If this key is specified and equals \var{y},
  4911. the files will be installed as a fpc package under the \fpc units directory,
  4912. i.e. under a separate directory. The directory will be named with the name
  4913. specified in the \var{package} section.
  4914. \item[files] extra data files to be installed in the directory specified
  4915. with the \var{datadir} key.
  4916. \item[prefix] is the directory below which all installs are done.
  4917. This corresponds to the \var{--prefix} argument to \gnu \file{configure}.
  4918. It is used for the installation of programs and units. By default, this is
  4919. \file{/usr} on \linux, and \file{/pp} on all other platforms.
  4920. \item[units] extra units that should be installed, and which are not part of
  4921. the unit targets. The units in the units target will be installed
  4922. automatically.
  4923. \end{description}
  4924. Units will be installed in the subdirectory \file{units/\$(OS\_TARGET)}
  4925. of the \var{dirbase} entry.
  4926. \subsection{Package}
  4927. If a package (i.e. a collection of units that work together) is being
  4928. compiled, then this section is used to keep package information.
  4929. The following information can be stored:
  4930. \begin{description}
  4931. \item[name] The name of the package. When installing it under the package
  4932. directory, this name will be used to create a directory (unless it is
  4933. overridden by one of the installation options)
  4934. \item[version] The version of this package.
  4935. \item[main] If the package is part of another package, this key can be
  4936. specified to indicate which package it is part of.
  4937. \end{description}
  4938. \subsection{Prerules}
  4939. Anything that is in this section will be inserted as-is in the makefile
  4940. \textit{before} the makefile target rules that are generated by fpcmake.
  4941. This means that any variables that are normally defined by fpcmake rules
  4942. should not be used in this section.
  4943. \subsection{Requires}
  4944. This section is used to indicate dependency on external packages (i.e units)
  4945. or tools. The following keywords can be used:
  4946. \begin{description}
  4947. \item[fpcmake] Minimal version of fpcmake that this \file{makefile.fpc} needs.
  4948. \item[packages] Other packages that should be compiled before this package
  4949. can be compiled. Note that this will also add all packages these packages
  4950. depend on to the dependencies of this package. By default, the \fpc Run-Time
  4951. Library is added to this list.
  4952. \item[libc] a boolean value that indicates whether this package needs the C
  4953. library.
  4954. \item[nortl] a boolean that prevents the addition of the \fpc Run-Time
  4955. Library to the required packages.
  4956. \item[unitdir] These directories will be added to the units search path of
  4957. the compiler.
  4958. \item[packagedir] List of package directories. The packages in these
  4959. directories will be made as well before making the current package.
  4960. \item[tools] A list of executables of extra tools that are required. The
  4961. full path to these tools will be defined in the makefile as a variable with
  4962. the same name as the tool name, only in uppercase. For example, the
  4963. following definition:
  4964. \begin{verbatim}
  4965. tools=upx
  4966. \end{verbatim}
  4967. will lead to the definition of a variable with the name \var{UPX} which will
  4968. contain the full path to the \file{upx} executable.
  4969. \end{description}
  4970. \subsection{Rules}
  4971. In this section dependency rules for the units and any other needed
  4972. targets can be inserted. It will be included at the end of the generated
  4973. makefile. Targets or 'default rules' that are defined by \fpcmake{}
  4974. can be inserted here; if they are not present, then \fpcmake{} will generate
  4975. a rule that will call the generic \var{fpc\_} version. For a list of standard
  4976. targets that will be defined by \fpcmake{}, see \sees{fpcmakefunctionality}.
  4977. For example, it is possible to define a target \var{all:}. If it is not
  4978. defined, then \fpcmake{} will generate one which simply calls
  4979. \var{fpc\_all}:
  4980. \begin{verbatim}
  4981. all: fpc_all
  4982. \end{verbatim}
  4983. The \var{fpc\_all} rule will make all targets as defined in the \var{Target}
  4984. section.
  4985. \subsection{Target}
  4986. This is the most important section of the \file{makefile.fpc} file. Here the
  4987. files are defined which should be compiled when the 'all' target is
  4988. executed.
  4989. The following keywords can be used there:
  4990. \begin{description}
  4991. \item[dirs]
  4992. A space separated list of directories where make should also be run.
  4993. \item[exampledirs]
  4994. A space separated list of directories with example programs. The examples
  4995. target will descend in this list of directories as well.
  4996. \item[examples]
  4997. A space separated list of example programs that need to be compiled when
  4998. the user asks to compile the examples. Do not specify an extension,
  4999. the extension will be appended.
  5000. \item[loaders]
  5001. A space separated list of names of assembler files that must be assembled.
  5002. Don't specify the extension, the extension will be appended.
  5003. \item[programs]
  5004. A space separated list of program names that need to be compiled. Do not
  5005. specify an extension, the extension will be appended.
  5006. \item[rsts] a list of \file{rst} files that needs to be converted to \file{.po}
  5007. files for use with \gnu \file{gettext} and internationalization routines.
  5008. \item[units]
  5009. A space separated list of unit names that need to be compiled. Do not
  5010. specify an extension, just the name of the unit as it would appear un a
  5011. \var{uses} clause is sufficient.
  5012. \end{description}
  5013. \section{Programs needed to use the generated makefile}
  5014. At least the following programs are needed by the generated \file{Makefile}
  5015. to function correctly:
  5016. \begin{description}
  5017. \item[cp] a copy program.
  5018. \item[date] a program that prints the date.
  5019. \item[install] a program to install files.
  5020. \item[make] the \file{make} program, obviously.
  5021. \item[pwd] a program that prints the current working directory.
  5022. \item[rm] a program to delete files.
  5023. \item[zip] the zip archiver program. (on dos/windows/OS2 systems only)
  5024. \item[tar] the tar archiver program (on Unix systems only).
  5025. \end{description}
  5026. These are standard programs on \linux systems, with the possible exception of
  5027. \file{make}. For \dos or \windowsnt, they can be found in the
  5028. file \file{makeutil.zip} on the \fpc FTP site.
  5029. The following programs are optionally needed if you use some special targets.
  5030. Which ones you need are controlled by the settings in the \var{tools} section.
  5031. \begin{description}
  5032. \item[cmp] a \dos and \windowsnt file comparer.
  5033. \item[diff] a file comparer.
  5034. \item[ppdep] the ppdep depency lister. Distributed with \fpc.
  5035. \item[ppufiles] the ppufiles unit file dependency lister. Distributed with \fpc.
  5036. \item[ppumove] the \fpc unit mover.
  5037. \item[sed] the \file{sed} program.
  5038. \item[upx] the UPX executable packer.
  5039. \end{description}
  5040. All of these can also be found on the \fpc FTP site for \dos and \windowsnt.
  5041. \file{ppdep,ppufiles} and \file{ppumove} are distributed with the \fpc
  5042. compiler.
  5043. %
  5044. \section{Variables that affect the generated makefile}
  5045. The makefile generated by \fpcmake{} contains a lot of variables.
  5046. Some of them are set in the makefile itself, others can be set and are taken
  5047. into account when set.
  5048. These variables can be split in two groups:
  5049. \begin{itemize}
  5050. \item Directory variables.
  5051. \item Compiler command-line variables.
  5052. \end{itemize}
  5053. Each group will be discussed separately.
  5054. \subsection{Directory variables}
  5055. The first set of variables controls the directories that are
  5056. recognised in the makefile. They should not be set in the
  5057. \file{Makefile.fpc} file, but can be specified on the commandline.
  5058. \begin{description}
  5059. \item[INCDIR] this is a list of directories, separated by spaces, that will
  5060. be added as include directories to the compiler command-line. Each
  5061. directory in the list is prepended with \var{-I} and added to the
  5062. compiler options.
  5063. \item[UNITDIR] this is a list of directories, separated by spaces, that will
  5064. be added as unit search directories to the compiler command-line. Each
  5065. directory in the list is prepended with \var{-Fu} and added to the
  5066. compiler options.
  5067. \item[LIBDIR] is a list of library paths, separated by spaces. Each
  5068. directory in the list is prepended with \var{-Fl} and added to the
  5069. compiler options.
  5070. \item[OBJDIR] is a list of object file directories, separated by spaces, that is
  5071. added to the object files path, i.e. Each directory in the list is prepended with
  5072. \var{-Fo}.
  5073. \end{description}
  5074. \subsection{Compiler command-line variables }
  5075. The following variable can be set on the \file{make} command-line,
  5076. they will be recognised and integrated in the compiler command-line options.:
  5077. \begin{description}
  5078. \item[CREATESMART] If this variable is defined, it tells the compiler to
  5079. create smartlinked units. Adds \var{-CX} to the command-line options.
  5080. \item[DEBUG] If defined, this will cause the compiler to include debug information in
  5081. the generated units and programs. It adds \var{-gl} to the compiler
  5082. command-line, and will define the \var{DEBUG} define.
  5083. \item[LINKSMART] Defining this variable tells the compiler to use smartlinking.
  5084. It adds \var{-XX} to the compiler command-line options.
  5085. \item[OPT] Any options that you want to pass to the compiler. The contents
  5086. of \var{OPT} is simply added to the compiler command-line.
  5087. \item[OPTDEF] Are optional defines, added to the command-line of the
  5088. compiler. They get \var{-d} prepended to them.
  5089. \item[OPTIMIZE] if this variable is defined, this will add \var{-OG2p3} to
  5090. the command-line options.
  5091. \item[RELEASE] if this variable is defined, this will add the \var{-Xs -OG2p3 -n}
  5092. options to the command-line options, and will define the \var{RELEASE} define.
  5093. \item[STRIP] if this variable is defined, this will add the \var{-Xs} option
  5094. to the command-line options.
  5095. \item[VERBOSE] if this variable is defined, then \var{-vnwi} will be added
  5096. to the command-line options.
  5097. \end{description}
  5098. \section{Variables set by \fpcmake{}}
  5099. The makefile generated by \fpcmake{} contains a lot of makefile variables.
  5100. \fpcmake{} will write all of the keys in the \file{makefile.fpc} as
  5101. makefile variables in the form \var{SECTION\_KEYNAME}. This means that the
  5102. following section:
  5103. \begin{verbatim}
  5104. [package]
  5105. name=mysql
  5106. version=1.0.5
  5107. \end{verbatim}
  5108. will result in the following variable definitions:
  5109. \begin{verbatim}
  5110. override PACKAGE_NAME=mysql
  5111. override PACKAGE_VERSION=1.0.5
  5112. \end{verbatim}
  5113. Most targets and rules are constructed using these variables. They will be
  5114. listed below, together with other variables that are defined by \fpcmake{}.
  5115. The following sets of variables are defined:
  5116. \begin{itemize}
  5117. \item Directory variables.
  5118. \item Program names.
  5119. \item File extensions.
  5120. \item Target files.
  5121. \end{itemize}
  5122. Each of these sets is discussed in the subsequent:
  5123. \subsection{Directory variables}
  5124. The following compiler directories are defined by the makefile:
  5125. \begin{description}
  5126. \item[BASEDIR] is set to the current directory if the \file{pwd} command is
  5127. available. If not, it is set to '.'.
  5128. \item[COMPILER\_INCDIR] is a space-separated list of library paths. Each
  5129. directory in the list is prepended with \var{-Fl} and added to the
  5130. compiler options. Set by the \var{incdir} keyword in the \var{Compiler} section.
  5131. \item[COMPILER\_LIBDIR] is a space-separated list of library paths. Each
  5132. directory in the list is prepended with \var{-Fl} and added to the
  5133. compiler options. Set by the \var{libdir} keyword in the \var{Compiler} section.
  5134. \item[COMPILER\_OBJDIR] is a list of object file directories, separated by
  5135. spaces. Each directory in the list is prepended with \var{-Fo} and
  5136. added to the compiler options.
  5137. Set by the \var{objdir} keyword in the \var{Compiler} section.
  5138. \item[COMPILER\_TARGETDIR] This directory is added as the output directory of
  5139. the compiler, where all units and executables are written, i.e. it gets
  5140. \var{-FE} prepended. It is set by the \var{targtdir} keyword in the
  5141. \var{Compiler} section.
  5142. \item[COMPILER\_TARGETUNITDIR] If set, this directory is added as the output directory of
  5143. the compiler, where all units and executables are written, i.e. it gets
  5144. \var{-FU} prepended.It is set by the \var{targtdir} keyword in the
  5145. \var{Dirs} section.
  5146. \item[COMPILER\_UNITDIR] is a list of unit directories, separated by spaces.
  5147. Each directory in the list is prepended with \var{-Fu} and is added to the
  5148. compiler options.
  5149. Set by the \var{unitdir} keyword in the \var{Compiler} section.
  5150. \item[GCCLIBDIR] (\linux only) is set to the directory where \file{libgcc.a}
  5151. is. If \var{needgcclib} is set to \var{True} in the \var{Libs} section, then
  5152. this directory is added to the compiler commandline with \var{-Fl}.
  5153. \item[OTHERLIBDIR] is a space-separated list of library paths. Each
  5154. directory in the list is prepended with \var{-Fl} and added to the
  5155. compiler options. If it is not defined on linux, then the contents of
  5156. the \file{/etc/ld.so.conf} file is added.
  5157. \end{description}
  5158. The following directories are used for installs:
  5159. \begin{description}
  5160. \item[INSTALL\_BASEDIR] is the base for all directories where units are
  5161. installed. By default, On \linux, this is set to
  5162. \mvar{INSTALL\_PREFIX}\var{/lib/fpc/}\mvar{RELEASEVER}.\\ On other systems,
  5163. it is set to \mvar{PREFIXINSTALLDIR}. You can also set it with the
  5164. \var{basedir} variable in the \var{Install} section.
  5165. \item[INSTALL\_BINDIR] is set to \mvar{INSTALL\_BASEDIR}/\var{bin} on \linux,
  5166. and\\ \mvar{INSTALL\_BASEDIR}/\var{bin}/\mvar{OS\_TARGET} on other systems.
  5167. This is the place where binaries are installed.
  5168. \item[INSTALL\_DATADIR] The directory where data files are installed. Set by
  5169. the \var{Data} key in the \var{Install} section.
  5170. \item[INSTALL\_LIBDIR] is set to \mvar{INSTALL\_PREFIX}/lib on \linux,\\
  5171. and \mvar{INSTALL\_UNITDIR} on other systems.
  5172. \item[INSTALL\_PREFIX] is set to \file{/usr/local} on \linux, \file{/pp} on \dos
  5173. or \windowsnt. Set by the \var{prefix} keyword in the \var{Install}
  5174. section.
  5175. \item[INSTALL\_UNITDIR] is where units will be installed. This is set to\\
  5176. \mvar{INSTALL\_BASEDIR}/units/\mvar{OS\_TARGET}. If the units are compiled
  5177. as a package, \mvar{PACKAGE\_NAME} is added to the directory.
  5178. \end{description}
  5179. \subsection{Target variables}
  5180. The second set of variables controls the targets that are constructed
  5181. by the makefile. They are created by \fpcmake{}, so you can use
  5182. them in your rules, but you shouldn't assign values to them yourself.
  5183. \begin{description}
  5184. \item[TARGET\_DIRS] This is the list of directories that make will descend
  5185. into when compiling. Set by the \var{Dirs} key in the \var{Target} section?
  5186. \item[TARGET\_EXAMPLES] The list of examples programs that must be compiled.
  5187. Set by the \var{examples} key in the \var{Target} section.
  5188. \item[TARGET\_EXAMPLEDIRS] the list of directories that make will descend
  5189. into when compiling examples. Set by the \var{exampledirs} key in the
  5190. \var{Target} section.
  5191. \item[TARGET\_LOADERS] is a list of space-separated names that identify
  5192. loaders to be compiled. This is mainly used in the compiler's RTL sources.
  5193. It is set by the \var{loaders} keyword in the \var{Targets} section.
  5194. \item[TARGET\_PROGRAMS] This is a list of executable names that will be compiled.
  5195. the makefile appends \mvar{EXEEXT} to these names. It is set by the
  5196. \var{programs} keyword in the \var{Target} section.
  5197. \item[TARGET\_UNITS] This is a list of unit names that will be compiled. The
  5198. makefile appends \mvar{PPUEXT} to each of these names to form the unit file
  5199. name. The sourcename is formed by adding \mvar{PASEXT}.
  5200. It is set by the \var{units} keyword in the \var{Target} section.
  5201. \item[ZIPNAME] is the name of the archive that will be created by the
  5202. makefile.
  5203. It is set by the \var{zipname} keyword in the \var{Zip} section.
  5204. \item[ZIPTARGET] is the target that is built before the archive is made.
  5205. this target is built first. If successful, the zip archive will be made.
  5206. It is set by the \var{ziptarget} keyword in the \var{Zip} section.
  5207. \end{description}
  5208. \subsection{Compiler command-line variables}
  5209. The following variables control the compiler command-line:
  5210. \begin{description}
  5211. \item[CPU\_SOURCE] the target CPU type is added as a define to the compiler
  5212. command line. This is determined by the Makefile itself.
  5213. \item[CPU\_TARGET] the target CPU type is added as a define to the compiler
  5214. command line. This is determined by the Makefile itself.
  5215. \item[OS\_SOURCE] What platform the makefile is used on. Detected
  5216. automatically.
  5217. \item[OS\_TARGET] What platform will be compiled for. Added to the
  5218. compiler command-line with a \var{-T} prepended.
  5219. \end{description}
  5220. \subsection{Program names}
  5221. The following variables are program names, used in makefile targets.
  5222. \begin{description}
  5223. \item[AS] The assembler. Default set to \file{as}.
  5224. \item[COPY] a file copy program. Default set to \file{cp -fp}.
  5225. \item[COPYTREE] a directory tree copy program. Default set to \file{cp -frp}.
  5226. \item[CMP] a program to compare files. Default set to \var{cmp}.
  5227. \item[DEL] a file removal program. Default set to \file{rm -f}.
  5228. \item[DELTREE] a directory removal program. Default set to \file{rm -rf}.
  5229. \item[DATE] a program to display the date.
  5230. \item[DIFF] a program to produce diff files.
  5231. \item[ECHO] an echo program.
  5232. \item[FPC] the Free Pascal compiler executable. Default set to
  5233. \var{ppc386.exe}
  5234. \item[INSTALL] a program to install files. Default set to \file{install -m
  5235. 644} on \linux.
  5236. \item[INSTALLEXE] a program to install executable files. Default set to \file{install -m
  5237. 755} on \linux.
  5238. \item[LD] The linker. Default set to \file{ld}.
  5239. \item[LDCONFIG] (\linux only) the program used to update the loader cache.
  5240. \item[MKDIR] a program to create directories if they don't exist yet. Default
  5241. set to \file{install -m 755 -d}
  5242. \item[MOVE] a file move program. Default set to \file{mv -f}
  5243. \item[PP] the Free Pascal compiler executable. Default set to
  5244. \var{ppc386.exe}
  5245. \item[PPAS] the name of the shell script created by the compiler if the
  5246. \var{-s} option is specified. This command will be executed after
  5247. compilation, if the \var{-s} option was detected among the options.
  5248. \item[PPUMOVE] the program to move units into one big unit library.
  5249. \item[PWD] the pwd program.
  5250. \item[SED] a stream-line editor program. Default set to \file{sed}.
  5251. \item[UPX] an executable packer to compress your executables into
  5252. self-extracting compressed executables.
  5253. \item[ZIPPROG] a zip program to compress files. zip targets are made with
  5254. this program
  5255. \end{description}
  5256. \subsection{File extensions}
  5257. The following variables denote extensions of files. These variables include
  5258. the \var{.} (dot) of the extension. They are appended to object names.
  5259. \begin{description}
  5260. \item[ASMEXT] is the extension of assembler files produced by the compiler.
  5261. \item[LOADEREXT] is the extension of the assembler files that make up the
  5262. executable startup code.
  5263. \item[OEXT] is the extension of the object files that the compiler creates.
  5264. \item[PACKAGESUFFIX] is a suffix that is appended to package names in zip
  5265. targets. This serves so packages can be made for different OSes.
  5266. \item[PPLEXT] is the extension of shared library unit files.
  5267. \item[PPUEXT] is the extension of default units.
  5268. \item[RSTEXT] is the extension of the \file{.rst} resource string files.
  5269. \item[SHAREDLIBEXT] is the extension of shared libraries.
  5270. \item[SMARTEXT] is the extension of smartlinked unit assembler files.
  5271. \item[STATICLIBEXT] is the extension of static libraries.
  5272. \end{description}
  5273. \subsection{Target files}
  5274. The following variables are defined to make targets and rules easier:
  5275. \begin{description}
  5276. \item[COMPILER] is the complete compiler commandline, with all options
  5277. added, after all \file{Makefile} variables have been examined.
  5278. \item[DATESTR] contains the date.
  5279. \item[UNITPPUFILES] a list of unit files that will be made. This is just
  5280. the list of unit objects, with the correct unit extension appended.
  5281. \end{description}
  5282. \section{Rules and targets created by \fpcmake{}}
  5283. The \var{makefile.fpc} defines a series of targets, which can be called by
  5284. your own targets. They have names that resemble default names (such as
  5285. 'all', 'clean'), only they have \var{fpc\_} prepended.
  5286. \subsection{Pattern rules}
  5287. The makefile makes the following pattern rules:
  5288. \begin{description}
  5289. \item[units] how to make a pascal unit form a pascal source file.
  5290. \item[executables] how to make an executable from a pascal source file.
  5291. \item[object file] how to make an object file from an assembler file.
  5292. \end{description}
  5293. \subsection{Build rules}
  5294. The following build targets are defined:
  5295. \begin{description}
  5296. \item[fpc\_all] target that builds all units and executables as well as
  5297. loaders. If \var{DEFAULTUNITS} is defined, executables are excluded from the
  5298. targets.
  5299. \item[fpc\_debug] the same as \var{fpc\_all}, only with debug information
  5300. included.
  5301. \item[fpc\_exes] target to make all executables in \var{EXEOBJECTS}.
  5302. \item[fpc\_loaders] target to make all files in \var{LOADEROBJECTS}.
  5303. \item[fpc\_packages] target to make all packages that are needed to make
  5304. the files.
  5305. \item[fpc\_shared] target that makes all units as dynamic libraries.
  5306. \item[fpc\_smart] target that makes all units as smartlinked units.
  5307. \item[fpc\_units] target to make all units in \var{UNITOBJECTS}.
  5308. \end{description}
  5309. \subsection{Cleaning rules}
  5310. The following cleaning targets are defined:
  5311. \begin{description}
  5312. \item[fpc\_clean] cleans all files that result when \var{fpc\_all} was made.
  5313. \item[fpc\_distclean] is the same as both previous target commands, but also
  5314. deletes all object, unit and assembler files that are present.
  5315. \end{description}
  5316. \subsection{archiving rules}
  5317. The following archiving targets are defined:
  5318. \begin{description}
  5319. \item[fpc\_zipdistinstall] Target to make a distribution install of the
  5320. package.
  5321. \item[fpc\_zipinstall] Target to make an install zip of the compiled units
  5322. of the package.
  5323. \item[fpc\_zipexampleinstall] Target to make a zip of the example files.
  5324. \item[fpc\_zipsourceinstall] Target to make a zip of the source files.
  5325. \end{description}
  5326. The zip is made uzing the \var{ZIPEXE} program. Under \linux, a
  5327. \file{.tar.gz} file is created.
  5328. \subsection{Installation rules}
  5329. \begin{description}
  5330. \item[fpc\_distinstall] target which calls the \var{install} and
  5331. \var{exampleinstall} targets.
  5332. \item[fpc\_install] target to install the units.
  5333. \item[fpc\_sourceinstall] target to install the sources (in case a
  5334. distribution is made)
  5335. \item[fpc\_exampleinstall] target to install the examples. (in case
  5336. a distribution is made)
  5337. \end{description}
  5338. \subsection{Informative rules}
  5339. There is only one target which produces information about the used
  5340. variables, rules and targets: \var{fpc\_info}.
  5341. The following information about the makefile is presented:
  5342. \begin{itemize}
  5343. \item general configuration information: the location of
  5344. the makefile, the compiler version, target OS, CPU.
  5345. \item the directories, used by the compiler.
  5346. \item all directories where files will be installed.
  5347. \item all objects that will be made.
  5348. \item all defined tools.
  5349. \end{itemize}
  5350. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5351. % Appendix F
  5352. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5353. \chapter{Compiling the compiler}
  5354. \label{ch:AppF}
  5355. \section{Introduction}
  5356. The \fpc team releases at intervals a completely prepared package, with
  5357. compiler and units all ready to use, the so-called releases. After a
  5358. release, work on the compiler continues, bugs are fixed and features are
  5359. added. The \fpc team doesn't make a new release whenever they change
  5360. something in the compiler, instead the sources are available for anyone to
  5361. use and compile. Compiled versions of RTL and compiler are also made daily,
  5362. and put on the web.
  5363. There are, nevertheless, circumstances when the compiler must be recompiled
  5364. manually. When changes are made to compiler code, or when the compiler is
  5365. downloaded through CVS.
  5366. There are essentially 2 ways of recompiling the compiler: by hand, or using
  5367. the makefiles. Each of these methods will be discussed.
  5368. \section{Before starting}
  5369. To compile the compiler easily, it is best to keep the following directory
  5370. structure (a base directory of \file{/pp/src} is supposed, but that may be
  5371. different):
  5372. \begin{verbatim}
  5373. /pp/src/Makefile
  5374. /makefile.fpc
  5375. /rtl/linux
  5376. /inc
  5377. /i386
  5378. /...
  5379. /compiler
  5380. \end{verbatim}
  5381. When the makefiles should be used, the above directory tree must be used.
  5382. The compiler and rtl source are zipped in such a way that when both are
  5383. unzipped in the same directory (\file{/pp/src} in the above) the above
  5384. directory tree results.
  5385. There are 2 ways to start compiling the compiler and RTL. Both ways must be
  5386. used, depending on the situation. Usually, the RTL must be compiled first,
  5387. before compiling the compiler, after which the compiler is compiled using
  5388. the current compiler. In some special cases the compiler must be compiled
  5389. first, with a previously compiled RTL.
  5390. How to decide which should be compiled first? In general, the answer is that
  5391. the RTL should be compiled first. There are 2 exceptions to this rule:
  5392. \begin{enumerate}
  5393. \item The first case is when some of the internal routines in the RTL
  5394. have changed, or if new internal routines appeared. Since the OLD compiler
  5395. doesn't know about these changed internal routines, it will emit function
  5396. calls that are based on the old compiled RTL, and hence are not correct.
  5397. Either the result will not link, or the binary will give errors.
  5398. \item The second case is when something is added to the RTL that the
  5399. compiler needs to know about (a new default assembler mechanism, for
  5400. example).
  5401. \end{enumerate}
  5402. How to know if one of these things has occurred? There is no way to know,
  5403. except by mailing the \fpc team. When the compiler cannot be recompiled
  5404. when first compiling the RTL, then try the other way.
  5405. \section{Compiling using \file{make}}
  5406. When compiling with \var{make} it is necessary to have the above directory
  5407. structure. Compiling the compiler is achieved with the target \var{cycle}.
  5408. Under normal circumstances, recompiling the compiler is limited to the
  5409. following instructions (assuming you start in directory \file{/pp/src}):
  5410. \begin{verbatim}
  5411. cd compiler
  5412. make cycle
  5413. \end{verbatim}
  5414. This will work only if the \file{makefile} is installed correctly and
  5415. if the needed tools are present in the \var{PATH}. Which tools must be
  5416. installed can be found in appendix \ref{ch:makefile}.
  5417. The above instructions will do the following:
  5418. \begin{enumerate}
  5419. \item Using the current compiler, the RTL is compiled in the correct
  5420. directory, which is determined by the OS. e.g. under \linux,
  5421. the RTL is compiled in directory \file{rtl/linux}.
  5422. \item The compiler is compiled using the newly compiled RTL. If successful,
  5423. the newly compiled compiler executable is copied to a temporary executable.
  5424. \item Using the temporary executable from the previous step, the RTL is
  5425. re-compiled.
  5426. \item Using the temporary executable and the newly compiled RTL from the
  5427. last step, the compiler is compiled again.
  5428. \end{enumerate}
  5429. The last two steps are repeated 3 times, until three passes have been made or
  5430. until the generated compiler binary is equal to the binary it was compiled
  5431. with. This process ensures that the compiler binary is correct.
  5432. Compiling for another target:
  5433. When compiling the compiler for another target, it is necessary to specify
  5434. the \var{OS\_TARGET} makefile variable. It can be set to the following
  5435. values: \var{win32}, \var{go32v2}, \var{os2} and \var{linux}.
  5436. As an example, cross-compilation for the go32v2 target from the win32 target
  5437. is chosen:
  5438. \begin{verbatim}
  5439. cd compiler
  5440. make cycle OS_TARGET=go32v2
  5441. \end{verbatim}
  5442. This will compile the go32v2 RTL, and compile a \var{go32v2} compiler.
  5443. When compiling a new compiler and the compiler should be compiled using an
  5444. existing compiled RTL, the \var{all} target must be used, and another RTL
  5445. directory than the default (which is the \file{../rtl/\$(OS\_TARGET)}
  5446. directory) must be indicated. For instance, assuming that the compiled RTL
  5447. units are in \var{/pp/rtl}, typing
  5448. \begin{verbatim}
  5449. cd compiler
  5450. make clean
  5451. make all UNITDIR=/pp/rtl
  5452. \end{verbatim}
  5453. should use the RTL from the \var{/pp/rtl} dirrectory.
  5454. This will then compile the compiler using the RTL units in \file{/pp/rtl}.
  5455. After this has been done, the 'make cycle' can be used, starting with this
  5456. compiler:
  5457. \begin{verbatim}
  5458. make cycle PP=./ppc386
  5459. \end{verbatim}
  5460. This will do the \var{make cycle} from above, but will start with the compiler
  5461. that was generated by the \var{make all} instruction.
  5462. In all cases, many options can be passed to \var{make} to influence the
  5463. compile process. In general, the makefiles add any needed compiler options
  5464. to the command-line, so that the RTL and compiler can be compiled.
  5465. Additional options (e.g. optimization options) can be specified by passing them in
  5466. \var{OPT}.
  5467. \section{Compiling by hand}
  5468. Compiling by hand is difficult and tedious, but can be done. The
  5469. compilation of RTL and compiler will be treated separately.
  5470. \subsection{Compiling the RTL}
  5471. To recompile the RTL, so a new compiler can be built, at least the following
  5472. units must be built, in the order specified:
  5473. \begin{enumerate}
  5474. \item[loaders] the program stubs, that are the startup code for each pascal
  5475. program. These files have the \file{.as} extension, because they are written
  5476. in assembler. They must be assembled with the \gnu \file{as} assembler. These stubs
  5477. are in the OS-dependent directory, except for \linux, where they are in a
  5478. processor dependent subdirectory of the \linux directory (\file{i386} or
  5479. \file{m68k}).
  5480. \item[system] the \file{system} unit. This unit is named differently on different
  5481. systems:
  5482. \begin{itemize}
  5483. \item Only on GO32v2, it's called \file{system}.
  5484. \item For \linux it's called \file{syslinux}.
  5485. \item For \windowsnt it's called \file{syswin32}.
  5486. \item For \ostwo it's called \file{sysos2}
  5487. \end{itemize}
  5488. This unit resides in the OS-dependent subdirectories of the RTL.
  5489. \item[strings] The strings unit. This unit resides in the \file{inc}
  5490. subdirectory of the RTL.
  5491. \item[dos] The \file{dos} unit. It resides in the OS-dependent subdirectory
  5492. of the RTL. Possibly other units will be compiled as a consequence of trying
  5493. to compile this unit (e.g. on \linux, the \file{linux} unit will be
  5494. compiled, on go32, the \file{go32} unit will be compiled).
  5495. \item[objects] the objects unit. It resides in the \file{inc} subdirectory
  5496. of the RTL.
  5497. \end{enumerate}
  5498. To compile these units on a i386, the following statements will do:
  5499. \begin{verbatim}
  5500. ppc386 -Tlinux -b- -Fi../inc -Fi../i386 -FE. -di386 -Us -Sg syslinux.pp
  5501. ppc386 -Tlinux -b- -Fi../inc -Fi../i386 -FE. -di386 ../inc/strings.pp
  5502. ppc386 -Tlinux -b- -Fi../inc -Fi../i386 -FE. -di386 dos.pp
  5503. ppc386 -Tlinux -b- -Fi../inc -Fi../i386 -FE. -di386 ../inc/objects.pp
  5504. \end{verbatim}
  5505. These are the minimum command-line options, needed to compile the RTL.
  5506. For another processor, the \var{i386} should be changed into the appropriate
  5507. processor. For another operating system (target) the
  5508. \file{syslinux} should be changed in the appropriate system unit file,
  5509. and the target OS setting (\var{-T}) must be set accordingly.
  5510. Depending on the target OS there are other units that can be
  5511. compiled, but which are not strictly needed to recompile the compiler.
  5512. The following units are available for all plaforms:
  5513. \begin{description}
  5514. \item[objpas] Needed for Delphi mode. Needs \var{-S2} as an option. Resides
  5515. in the \file{objpas} subdirectory.
  5516. \item[sysutils] many utility functions, like in Delphi. Resides in the
  5517. \file{objpas} directory, and needs \var{-S2} to compile.
  5518. \item[typinfo] functions to access RTTI information, like Delphi. Resides in
  5519. the \file{objpas} directory.
  5520. \item[math] math functions like in Delphi. Resides in the \file{objpas}
  5521. directory.
  5522. \item[mmx] extensions for MMX class Intel processors. Resides in
  5523. in the \file{i386} directory.
  5524. \item[getopts] a GNU compatible getopts unit. resides in the \file{inc}
  5525. directory.
  5526. \item[heaptrc] to debug the heap. resides in the \file{inc} directory.
  5527. \end{description}
  5528. \subsection{Compiling the compiler}
  5529. Compiling the compiler can be done with one statement. It's always best to
  5530. remove all units from the compiler directory first, so something like
  5531. \begin{verbatim}
  5532. rm *.ppu *.o
  5533. \end{verbatim}
  5534. on \linux, and on \dos
  5535. \begin{verbatim}
  5536. del *.ppu
  5537. del *.o
  5538. \end{verbatim}
  5539. After this, the compiler can be compiled with the following command-line:
  5540. \begin{verbatim}
  5541. ppc386 -Tlinux -Fu../rtl/linux -di386 -dGDB pp.pas
  5542. \end{verbatim}
  5543. So, the minimum options are:
  5544. \begin{enumerate}
  5545. \item The target OS. Can be skipped when compiling for the same target as
  5546. the compiler which is being used.
  5547. \item A path to an RTL. Can be skipped if a correct fpc.cfg configuration
  5548. is on the system. If the compiler should be compiled with the RTL that was
  5549. compiled first, this should be \file{../rtl/OS} (replace the OS with the
  5550. appropriate operating system subdirectory of the RTL).
  5551. \item A define with the processor for which the compiler is compiled for. Required.
  5552. \item \var{-dGDB}. Required.
  5553. \item \var{-Sg} is needed, some parts of the compiler use \var{goto}
  5554. statements (to be specific: the scanner).
  5555. \end{enumerate}
  5556. So the absolute minimal command line is
  5557. \begin{verbatim}
  5558. ppc386 -di386 -dGDB -Sg pp.pas
  5559. \end{verbatim}
  5560. Some other command-line options can be used, but the above are the
  5561. minimum. A list of recognised options can be found in \seet{FPCdefines}.
  5562. \begin{FPCltable}{ll}{Possible defines when compiling FPC}{FPCdefines}
  5563. Define & does what \\ \hline
  5564. TP & Needed to compile the compiler with Turbo or Borland Pascal. \\
  5565. GDB & Support of the GNU Debugger (required switch). \\
  5566. I386 & Generate a compiler for the Intel i386+ processor family. \\
  5567. M68K & Generate a compiler for the M680x0 processor family. \\
  5568. EXTDEBUG & Some extra debug code is executed. \\
  5569. MEMDEBUG & Some memory usage information is displayed. \\
  5570. SUPPORT\_MMX & only i386: enables the compiler switch \var{MMX} which \\
  5571. &allows the compiler to generate MMX instructions.\\
  5572. EXTERN\_MSG & Don't compile the msgfiles in the compiler, always use \\
  5573. & external messagefiles (default for TP).\\
  5574. LOGSECONDPASS & Write compiler node information in assembler output. \\
  5575. NOOPT & Do not include the optimizer in the compiler. \\
  5576. \hline
  5577. \end{FPCltable}
  5578. This list may be subject to change, the source file \file{pp.pas} always
  5579. contains an up-to-date list.
  5580. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5581. % Appendix G : Compiler defines
  5582. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5583. \chapter{Compiler defines during compilation}
  5584. \label{ch:AppG}
  5585. This appendix describes the possible defines when compiling programs
  5586. using \fpc. A brief explanation of the define, and when it is used
  5587. is also given.
  5588. \begin{FPCltable}{ll}{Possible defines when compiling using FPC}{FPCOutdefines}
  5589. Define & description \\ \hline
  5590. FPC\_LINK\_DYNAMIC & Defined when the output will be linked dynamically.\\
  5591. & This is defined when using the -XD compiler switch.\\
  5592. FPC\_LINK\_STATIC & Defined when the output will be linked statically.\\
  5593. & This is the default mode. \\
  5594. FPC\_LINK\_SMART & Defined when the output will be smartlinked.\\
  5595. & This is defined when using the -XX compiler switch.\\
  5596. FPC\_PROFILE & Defined when profiling code is added to program.\\
  5597. & This is defined when using the -pg compiler switch.\\
  5598. FPK & Always defined for \fpc. \\
  5599. FPC & Always defined for \fpc. \\
  5600. VER1 & Always defined for \fpc version 1.x.x. \\
  5601. VER1\_0 & Always defined for \fpc version 1.0.x. \\
  5602. ENDIAN\_LITTLE & Defined when the \fpc target is a little-endian processor \\
  5603. & (80x86, Alpha, ARM). \\
  5604. ENDIAN\_BIG & Defined when the \fpc target is a big-endian processor \\
  5605. & (680x0, PowerPC, SPARC, MIPS). \\
  5606. FPC\_DELPHI & \fpc is in Delphi mode, either using compiler switch -Sd or \\
  5607. & using the \var{\$MODE DELPHI} directive. \\
  5608. FPC\_OBJFPC & \fpc is in Delphi mode, either using compiler switch -S2 or \\
  5609. & using the \var{\$MODE OBJFPC} directive. \\
  5610. FPC\_TP & \fpc is in Turbo Pascal mode, either using compiler switch -So or \\
  5611. & using the \var{\$MODE TP} directive. \\
  5612. FPC\_GPC & \fpc is in GNU Pascal mode, either using compiler switch -Sp or \\
  5613. & using the \var{\$MODE GPC} directive. \\
  5614. \end{FPCltable}
  5615. \begin{remark}
  5616. The \var{ENDIAN\_LITTLE} and \var{ENDIAN\_BIG} defines were added
  5617. starting from \fpc version 1.0.5.
  5618. \end{remark}
  5619. \begin{FPCltable}{ll}{Possible CPU defines when compiling using FPC}{FPCCPUdefines}
  5620. Define & When defined? \\ \hline
  5621. CPU86 & \fpc target is an Intel 80x86 or compatible.\\
  5622. CPU87 & \fpc target is an Intel 80x86 or compatible.\\
  5623. CPUI386 & \fpc target is an Intel 80386 or later.\\
  5624. CPU68k & \fpc target is a Motorola 680x0 or compatible.\\
  5625. CPUM68020 & \fpc target is a Motorola 68020 or later.\\
  5626. CPU68 & \fpc target is a Motorola 680x0 or compatible.\\
  5627. CPUSPARC & \fpc target is a SPARC v7 or compatible.\\
  5628. CPUALPHA & \fpc target is an Alpha AXP or compatible.\\
  5629. CPUPOWERPC & \fpc target is a 32-bit PowerPC or compatible.\\
  5630. \end{FPCltable}
  5631. \begin{FPCltable}{ll}{Possible defines when compiling using target OS}{FPCOSdefines}
  5632. Target operating system & Defines \\ \hline
  5633. linux & LINUX, UNIX\\
  5634. freebsd & FREEBSD, BSD, UNIX\\
  5635. netbsd & NETBSD, BSD, UNIX\\
  5636. sunos & SUNOS, SOLARIS, UNIX\\
  5637. go32v2 & GO32V2, DPMI\\
  5638. os2 & OS2\\
  5639. Windows 32-bit & WIN32\\
  5640. Classic Amiga & AMIGA\\
  5641. Atari TOS & ATARI\\
  5642. Classic Macintosh & MAC\\
  5643. PalmOS & PALMOS\\
  5644. BeOS & BEOS, UNIX\\
  5645. QNX RTP & QNX, UNIX
  5646. \end{FPCltable}
  5647. \begin{remark}
  5648. The \unix define was added starting from \fpc version 1.0.5. The BSD
  5649. operating systems no longer define LINUX starting with version 1.0.7.
  5650. \end{remark}
  5651. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5652. % Appendix H : Operating system specific behavior
  5653. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5654. <<<<<<< prog.tex
  5655. \chapter{Stack configuration}
  5656. \label{ch:AppH}
  5657. This gives some important information on stack settings under
  5658. the different operating systems. It might be important when
  5659. porting applications to other operating systems.
  5660. \section{DOS}
  5661. Under the DOS targets, the default stack is set to 256 kB.
  5662. This can be modified with the GO32V2 target using a special
  5663. DJGPP utility \file{stubedit}. It is to note that the stack
  5664. size may be enlarged with the compiler switch (\var{-Cs}).
  5665. If the size specified with \var{-Cs} is \emph{greater}
  5666. than the default stack size, it will be used instead,
  5667. otherwise the default stack size is used.
  5668. \section{Linux}
  5669. Under \linux, stack size is only limited by the available memory of
  5670. the system.
  5671. \section{Netbsd}
  5672. Under \netbsd, stack size is only limited by the available memory of
  5673. the system.
  5674. \section{Freebsd}
  5675. Under \freebsd, stack size is only limited by the available memory of
  5676. the system.
  5677. \section{BeOS}
  5678. Under \beos, stack size is fixed at 256Kb. It currently
  5679. cannot be changed, it is recommended to turn on stack
  5680. checking when compiling for this target platform.
  5681. \section{Windows}
  5682. Under \windows, stack size is only limited by the available memory of
  5683. the system.
  5684. \section{OS/2}
  5685. Under \ostwo, stack size is specified at a default
  5686. value of 8 Mbytes. This currently cannot be changed
  5687. directly.
  5688. \section{Amiga}
  5689. Under AmigaOS, stack size is determined by the user, which sets this
  5690. value using the stack program. Typical sizes range from 4 kB to 40 kB.
  5691. The stack size currently cannot be changed, it is recommended to turn
  5692. on stack checking when compiling for this target platform.
  5693. \section{Atari}
  5694. Under Atari TOS, stack size is currently limited to 8 kB.
  5695. The stack size currently cannot be changed, it is recommended to turn
  5696. on stack checking when compiling for this target platform.
  5697. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5698. % Appendix I : Operating system specific behavior
  5699. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5700. =======
  5701. >>>>>>> 1.27
  5702. \chapter{Operating system specific behavior}
  5703. \label{ch:AppH}
  5704. This appendix describes some special behaviors which vary
  5705. from operating system to operating system. This is described
  5706. in \seet{OSBehave}. The GCC saved registers indicates what
  5707. registers are saved when certain declaration modifiers are used.
  5708. \begin{FPCltable}{lcr}{Operating system specific behavior}{OSBehave}
  5709. Operating systems & Min. param. stack align & GCC saved registers\\
  5710. \hline
  5711. Amiga & 2 & D2..D7,A2..A5\\
  5712. Atari & 2 & D2..D7,A2..A5\\
  5713. BeOS-x86 & 4 & ESI, EDI, EBX\\
  5714. DOS & 2 & ESI, EDI, EBX\\
  5715. FreeBSD & 4 & ESI, EDI, EBX\\
  5716. linux-m68k & & D2..D7,A2..A5\\
  5717. linux-x86 & 4 & ESI, EDI, EBX\\
  5718. MacOS-68k & & D2..D7,A2..A5\\
  5719. NetBSD-x86 & & ESI, EDI, EBX\\
  5720. NetBSD-m68k & & D2..D7,A2..A5\\
  5721. OS/2 & 4 & ESI, EDI, EBX\\
  5722. PalmOS & 2 & D2..D7,A2..A5\\
  5723. QNX-x86 & & ESI, EDI, EBX\\
  5724. Solaris-x86 & 4 & ESI, EDI, EBX\\
  5725. Win32 & 4 & ESI, EDI, EBX\\
  5726. \hline
  5727. \end{FPCltable}
  5728. \end{document}