ff.c 207 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140
  1. /*----------------------------------------------------------------------------/
  2. / FatFs - Generic FAT file system module R0.12c /
  3. /-----------------------------------------------------------------------------/
  4. /
  5. / Copyright (C) 2017, ChaN, all right reserved.
  6. /
  7. / FatFs module is an open source software. Redistribution and use of FatFs in
  8. / source and binary forms, with or without modification, are permitted provided
  9. / that the following condition is met:
  10. /
  11. / 1. Redistributions of source code must retain the above copyright notice,
  12. / this condition and the following disclaimer.
  13. /
  14. / This software is provided by the copyright holder and contributors "AS IS"
  15. / and any warranties related to this software are DISCLAIMED.
  16. / The copyright owner or contributors be NOT LIABLE for any damages caused
  17. / by use of this software.
  18. /----------------------------------------------------------------------------*/
  19. #include "ff.h" /* Declarations of FatFs API */
  20. #include "diskio.h" /* Declarations of device I/O functions */
  21. /*--------------------------------------------------------------------------
  22. Module Private Definitions
  23. ---------------------------------------------------------------------------*/
  24. #if _FATFS != 68300 /* Revision ID */
  25. #error Wrong include file (ff.h).
  26. #endif
  27. /* DBCS code ranges and SBCS upper conversion tables */
  28. #if _CODE_PAGE == 932 /* Japanese Shift-JIS */
  29. #define _DF1S 0x81 /* DBC 1st byte range 1 start */
  30. #define _DF1E 0x9F /* DBC 1st byte range 1 end */
  31. #define _DF2S 0xE0 /* DBC 1st byte range 2 start */
  32. #define _DF2E 0xFC /* DBC 1st byte range 2 end */
  33. #define _DS1S 0x40 /* DBC 2nd byte range 1 start */
  34. #define _DS1E 0x7E /* DBC 2nd byte range 1 end */
  35. #define _DS2S 0x80 /* DBC 2nd byte range 2 start */
  36. #define _DS2E 0xFC /* DBC 2nd byte range 2 end */
  37. #elif _CODE_PAGE == 936 /* Simplified Chinese GBK */
  38. #define _DF1S 0x81
  39. #define _DF1E 0xFE
  40. #define _DS1S 0x40
  41. #define _DS1E 0x7E
  42. #define _DS2S 0x80
  43. #define _DS2E 0xFE
  44. #elif _CODE_PAGE == 949 /* Korean */
  45. #define _DF1S 0x81
  46. #define _DF1E 0xFE
  47. #define _DS1S 0x41
  48. #define _DS1E 0x5A
  49. #define _DS2S 0x61
  50. #define _DS2E 0x7A
  51. #define _DS3S 0x81
  52. #define _DS3E 0xFE
  53. #elif _CODE_PAGE == 950 /* Traditional Chinese Big5 */
  54. #define _DF1S 0x81
  55. #define _DF1E 0xFE
  56. #define _DS1S 0x40
  57. #define _DS1E 0x7E
  58. #define _DS2S 0xA1
  59. #define _DS2E 0xFE
  60. #elif _CODE_PAGE == 437 /* U.S. */
  61. #define _DF1S 0
  62. #define _EXCVT {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  63. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  64. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  65. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  66. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  67. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  68. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  69. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  70. #elif _CODE_PAGE == 720 /* Arabic */
  71. #define _DF1S 0
  72. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  73. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  74. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  75. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  76. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  77. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  78. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  79. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  80. #elif _CODE_PAGE == 737 /* Greek */
  81. #define _DF1S 0
  82. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  83. 0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \
  84. 0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96, \
  85. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  86. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  87. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  88. 0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xEF,0xF5,0xF0,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  89. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  90. #elif _CODE_PAGE == 771 /* KBL */
  91. #define _DF1S 0
  92. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  93. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  94. 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  95. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  96. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  97. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDC,0xDE,0xDE, \
  98. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  99. 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFE,0xFF}
  100. #elif _CODE_PAGE == 775 /* Baltic */
  101. #define _DF1S 0
  102. #define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F, \
  103. 0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  104. 0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  105. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  106. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  107. 0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  108. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF, \
  109. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  110. #elif _CODE_PAGE == 850 /* Latin 1 */
  111. #define _DF1S 0
  112. #define _EXCVT {0x43,0x55,0x45,0x41,0x41,0x41,0x41,0x43,0x45,0x45,0x45,0x49,0x49,0x49,0x41,0x41, \
  113. 0x45,0x92,0x92,0x4F,0x4F,0x4F,0x55,0x55,0x59,0x4F,0x55,0x4F,0x9C,0x4F,0x9E,0x9F, \
  114. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  115. 0xB0,0xB1,0xB2,0xB3,0xB4,0x41,0x41,0x41,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  116. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0x41,0x41,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  117. 0xD1,0xD1,0x45,0x45,0x45,0x49,0x49,0x49,0x49,0xD9,0xDA,0xDB,0xDC,0xDD,0x49,0xDF, \
  118. 0x4F,0xE1,0x4F,0x4F,0x4F,0x4F,0xE6,0xE8,0xE8,0x55,0x55,0x55,0x59,0x59,0xEE,0xEF, \
  119. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  120. #elif _CODE_PAGE == 852 /* Latin 2 */
  121. #define _DF1S 0
  122. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F, \
  123. 0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0xAC, \
  124. 0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF, \
  125. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \
  126. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  127. 0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  128. 0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF, \
  129. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF}
  130. #elif _CODE_PAGE == 855 /* Cyrillic */
  131. #define _DF1S 0
  132. #define _EXCVT {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F, \
  133. 0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \
  134. 0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF, \
  135. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \
  136. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  137. 0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \
  138. 0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF, \
  139. 0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF}
  140. #elif _CODE_PAGE == 857 /* Turkish */
  141. #define _DF1S 0
  142. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x49,0x8E,0x8F, \
  143. 0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \
  144. 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  145. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  146. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  147. 0xD0,0xD1,0xD2,0xD3,0xD4,0x49,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  148. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0xED,0xEE,0xEF, \
  149. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  150. #elif _CODE_PAGE == 860 /* Portuguese */
  151. #define _DF1S 0
  152. #define _EXCVT {0x80,0x9A,0x90,0x8F,0x8E,0x91,0x86,0x80,0x89,0x89,0x92,0x8B,0x8C,0x98,0x8E,0x8F, \
  153. 0x90,0x91,0x92,0x8C,0x99,0xA9,0x96,0x9D,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  154. 0x86,0x8B,0x9F,0x96,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  155. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  156. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  157. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  158. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  159. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  160. #elif _CODE_PAGE == 861 /* Icelandic */
  161. #define _DF1S 0
  162. #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x8B,0x8B,0x8D,0x8E,0x8F, \
  163. 0x90,0x92,0x92,0x4F,0x99,0x8D,0x55,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  164. 0xA4,0xA5,0xA6,0xA7,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  165. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  166. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  167. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  168. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  169. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  170. #elif _CODE_PAGE == 862 /* Hebrew */
  171. #define _DF1S 0
  172. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  173. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  174. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  175. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  176. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  177. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  178. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  179. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  180. #elif _CODE_PAGE == 863 /* Canadian-French */
  181. #define _DF1S 0
  182. #define _EXCVT {0x43,0x55,0x45,0x41,0x41,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x41,0x8F, \
  183. 0x45,0x45,0x45,0x4F,0x45,0x49,0x55,0x55,0x98,0x4F,0x55,0x9B,0x9C,0x55,0x55,0x9F, \
  184. 0xA0,0xA1,0x4F,0x55,0xA4,0xA5,0xA6,0xA7,0x49,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  185. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  186. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  187. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  188. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  189. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  190. #elif _CODE_PAGE == 864 /* Arabic */
  191. #define _DF1S 0
  192. #define _EXCVT {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  193. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  194. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  195. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  196. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  197. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  198. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  199. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  200. #elif _CODE_PAGE == 865 /* Nordic */
  201. #define _DF1S 0
  202. #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  203. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  204. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  205. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  206. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  207. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  208. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  209. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  210. #elif _CODE_PAGE == 866 /* Russian */
  211. #define _DF1S 0
  212. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  213. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  214. 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  215. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  216. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  217. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  218. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  219. 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  220. #elif _CODE_PAGE == 869 /* Greek 2 */
  221. #define _DF1S 0
  222. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  223. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x86,0x9C,0x8D,0x8F,0x90, \
  224. 0x91,0x90,0x92,0x95,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  225. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  226. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  227. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xA4,0xA5,0xA6,0xD9,0xDA,0xDB,0xDC,0xA7,0xA8,0xDF, \
  228. 0xA9,0xAA,0xAC,0xAD,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xCF,0xCF,0xD0,0xEF, \
  229. 0xF0,0xF1,0xD1,0xD2,0xD3,0xF5,0xD4,0xF7,0xF8,0xF9,0xD5,0x96,0x95,0x98,0xFE,0xFF}
  230. #elif _CODE_PAGE == 1 /* ASCII (for only non-LFN cfg) */
  231. #if _USE_LFN != 0
  232. #error Cannot enable LFN without valid code page.
  233. #endif
  234. #define _DF1S 0
  235. #else
  236. #error Unknown code page
  237. #endif
  238. /* Character code support macros */
  239. #define IsUpper(c) (((c)>='A')&&((c)<='Z'))
  240. #define IsLower(c) (((c)>='a')&&((c)<='z'))
  241. #define IsDigit(c) (((c)>='0')&&((c)<='9'))
  242. #if _DF1S != 0 /* Code page is DBCS */
  243. #ifdef _DF2S /* Two 1st byte areas */
  244. #define IsDBCS1(c) (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E))
  245. #else /* One 1st byte area */
  246. #define IsDBCS1(c) ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E)
  247. #endif
  248. #ifdef _DS3S /* Three 2nd byte areas */
  249. #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E))
  250. #else /* Two 2nd byte areas */
  251. #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E))
  252. #endif
  253. #else /* Code page is SBCS */
  254. #define IsDBCS1(c) 0
  255. #define IsDBCS2(c) 0
  256. #endif /* _DF1S */
  257. /* Additional file attribute bits for internal use */
  258. #define AM_VOL 0x08 /* Volume label */
  259. #define AM_LFN 0x0F /* LFN entry */
  260. #define AM_MASK 0x3F /* Mask of defined bits */
  261. /* Additional file access control and file status flags for internal use */
  262. #define FA_SEEKEND 0x20 /* Seek to end of the file on file open */
  263. #define FA_MODIFIED 0x40 /* File has been modified */
  264. #define FA_DIRTY 0x80 /* FIL.buf[] needs to be written-back */
  265. /* Name status flags in fn[] */
  266. #define NSFLAG 11 /* Index of the name status byte */
  267. #define NS_LOSS 0x01 /* Out of 8.3 format */
  268. #define NS_LFN 0x02 /* Force to create LFN entry */
  269. #define NS_LAST 0x04 /* Last segment */
  270. #define NS_BODY 0x08 /* Lower case flag (body) */
  271. #define NS_EXT 0x10 /* Lower case flag (ext) */
  272. #define NS_DOT 0x20 /* Dot entry */
  273. #define NS_NOLFN 0x40 /* Do not find LFN */
  274. #define NS_NONAME 0x80 /* Not followed */
  275. /* Limits and boundaries */
  276. #define MAX_DIR 0x200000 /* Max size of FAT directory */
  277. #define MAX_DIR_EX 0x10000000 /* Max size of exFAT directory */
  278. #define MAX_FAT12 0xFF5 /* Max FAT12 clusters (differs from specs, but correct for real DOS/Windows behavior) */
  279. #define MAX_FAT16 0xFFF5 /* Max FAT16 clusters (differs from specs, but correct for real DOS/Windows behavior) */
  280. #define MAX_FAT32 0x0FFFFFF5 /* Max FAT32 clusters (not specified, practical limit) */
  281. #define MAX_EXFAT 0x7FFFFFFD /* Max exFAT clusters (differs from specs, implementation limit) */
  282. /* FatFs refers the FAT structure as simple byte array instead of structure member
  283. / because the C structure is not binary compatible between different platforms */
  284. #define BS_JmpBoot 0 /* x86 jump instruction (3-byte) */
  285. #define BS_OEMName 3 /* OEM name (8-byte) */
  286. #define BPB_BytsPerSec 11 /* Sector size [byte] (WORD) */
  287. #define BPB_SecPerClus 13 /* Cluster size [sector] (BYTE) */
  288. #define BPB_RsvdSecCnt 14 /* Size of reserved area [sector] (WORD) */
  289. #define BPB_NumFATs 16 /* Number of FATs (BYTE) */
  290. #define BPB_RootEntCnt 17 /* Size of root directory area for FAT12/16 [entry] (WORD) */
  291. #define BPB_TotSec16 19 /* Volume size (16-bit) [sector] (WORD) */
  292. #define BPB_Media 21 /* Media descriptor byte (BYTE) */
  293. #define BPB_FATSz16 22 /* FAT size (16-bit) [sector] (WORD) */
  294. #define BPB_SecPerTrk 24 /* Track size for int13h [sector] (WORD) */
  295. #define BPB_NumHeads 26 /* Number of heads for int13h (WORD) */
  296. #define BPB_HiddSec 28 /* Volume offset from top of the drive (DWORD) */
  297. #define BPB_TotSec32 32 /* Volume size (32-bit) [sector] (DWORD) */
  298. #define BS_DrvNum 36 /* Physical drive number for int13h (BYTE) */
  299. #define BS_NTres 37 /* Error flag (BYTE) */
  300. #define BS_BootSig 38 /* Extended boot signature (BYTE) */
  301. #define BS_VolID 39 /* Volume serial number (DWORD) */
  302. #define BS_VolLab 43 /* Volume label string (8-byte) */
  303. #define BS_FilSysType 54 /* File system type string (8-byte) */
  304. #define BS_BootCode 62 /* Boot code (448-byte) */
  305. #define BS_55AA 510 /* Signature word (WORD) */
  306. #define BPB_FATSz32 36 /* FAT32: FAT size [sector] (DWORD) */
  307. #define BPB_ExtFlags32 40 /* FAT32: Extended flags (WORD) */
  308. #define BPB_FSVer32 42 /* FAT32: File system version (WORD) */
  309. #define BPB_RootClus32 44 /* FAT32: Root directory cluster (DWORD) */
  310. #define BPB_FSInfo32 48 /* FAT32: Offset of FSINFO sector (WORD) */
  311. #define BPB_BkBootSec32 50 /* FAT32: Offset of backup boot sector (WORD) */
  312. #define BS_DrvNum32 64 /* FAT32: Physical drive number for int13h (BYTE) */
  313. #define BS_NTres32 65 /* FAT32: Error flag (BYTE) */
  314. #define BS_BootSig32 66 /* FAT32: Extended boot signature (BYTE) */
  315. #define BS_VolID32 67 /* FAT32: Volume serial number (DWORD) */
  316. #define BS_VolLab32 71 /* FAT32: Volume label string (8-byte) */
  317. #define BS_FilSysType32 82 /* FAT32: File system type string (8-byte) */
  318. #define BS_BootCode32 90 /* FAT32: Boot code (420-byte) */
  319. #define BPB_ZeroedEx 11 /* exFAT: MBZ field (53-byte) */
  320. #define BPB_VolOfsEx 64 /* exFAT: Volume offset from top of the drive [sector] (QWORD) */
  321. #define BPB_TotSecEx 72 /* exFAT: Volume size [sector] (QWORD) */
  322. #define BPB_FatOfsEx 80 /* exFAT: FAT offset from top of the volume [sector] (DWORD) */
  323. #define BPB_FatSzEx 84 /* exFAT: FAT size [sector] (DWORD) */
  324. #define BPB_DataOfsEx 88 /* exFAT: Data offset from top of the volume [sector] (DWORD) */
  325. #define BPB_NumClusEx 92 /* exFAT: Number of clusters (DWORD) */
  326. #define BPB_RootClusEx 96 /* exFAT: Root directory start cluster (DWORD) */
  327. #define BPB_VolIDEx 100 /* exFAT: Volume serial number (DWORD) */
  328. #define BPB_FSVerEx 104 /* exFAT: File system version (WORD) */
  329. #define BPB_VolFlagEx 106 /* exFAT: Volume flags (BYTE) */
  330. #define BPB_ActFatEx 107 /* exFAT: Active FAT flags (BYTE) */
  331. #define BPB_BytsPerSecEx 108 /* exFAT: Log2 of sector size in unit of byte (BYTE) */
  332. #define BPB_SecPerClusEx 109 /* exFAT: Log2 of cluster size in unit of sector (BYTE) */
  333. #define BPB_NumFATsEx 110 /* exFAT: Number of FATs (BYTE) */
  334. #define BPB_DrvNumEx 111 /* exFAT: Physical drive number for int13h (BYTE) */
  335. #define BPB_PercInUseEx 112 /* exFAT: Percent in use (BYTE) */
  336. #define BPB_RsvdEx 113 /* exFAT: Reserved (7-byte) */
  337. #define BS_BootCodeEx 120 /* exFAT: Boot code (390-byte) */
  338. #define DIR_Name 0 /* Short file name (11-byte) */
  339. #define DIR_Attr 11 /* Attribute (BYTE) */
  340. #define DIR_NTres 12 /* Lower case flag (BYTE) */
  341. #define DIR_CrtTime10 13 /* Created time sub-second (BYTE) */
  342. #define DIR_CrtTime 14 /* Created time (DWORD) */
  343. #define DIR_LstAccDate 18 /* Last accessed date (WORD) */
  344. #define DIR_FstClusHI 20 /* Higher 16-bit of first cluster (WORD) */
  345. #define DIR_ModTime 22 /* Modified time (DWORD) */
  346. #define DIR_FstClusLO 26 /* Lower 16-bit of first cluster (WORD) */
  347. #define DIR_FileSize 28 /* File size (DWORD) */
  348. #define LDIR_Ord 0 /* LFN: LFN order and LLE flag (BYTE) */
  349. #define LDIR_Attr 11 /* LFN: LFN attribute (BYTE) */
  350. #define LDIR_Type 12 /* LFN: Entry type (BYTE) */
  351. #define LDIR_Chksum 13 /* LFN: Checksum of the SFN (BYTE) */
  352. #define LDIR_FstClusLO 26 /* LFN: MBZ field (WORD) */
  353. #define XDIR_Type 0 /* exFAT: Type of exFAT directory entry (BYTE) */
  354. #define XDIR_NumLabel 1 /* exFAT: Number of volume label characters (BYTE) */
  355. #define XDIR_Label 2 /* exFAT: Volume label (11-WORD) */
  356. #define XDIR_CaseSum 4 /* exFAT: Sum of case conversion table (DWORD) */
  357. #define XDIR_NumSec 1 /* exFAT: Number of secondary entries (BYTE) */
  358. #define XDIR_SetSum 2 /* exFAT: Sum of the set of directory entries (WORD) */
  359. #define XDIR_Attr 4 /* exFAT: File attribute (WORD) */
  360. #define XDIR_CrtTime 8 /* exFAT: Created time (DWORD) */
  361. #define XDIR_ModTime 12 /* exFAT: Modified time (DWORD) */
  362. #define XDIR_AccTime 16 /* exFAT: Last accessed time (DWORD) */
  363. #define XDIR_CrtTime10 20 /* exFAT: Created time subsecond (BYTE) */
  364. #define XDIR_ModTime10 21 /* exFAT: Modified time subsecond (BYTE) */
  365. #define XDIR_CrtTZ 22 /* exFAT: Created timezone (BYTE) */
  366. #define XDIR_ModTZ 23 /* exFAT: Modified timezone (BYTE) */
  367. #define XDIR_AccTZ 24 /* exFAT: Last accessed timezone (BYTE) */
  368. #define XDIR_GenFlags 33 /* exFAT: General secondary flags (WORD) */
  369. #define XDIR_NumName 35 /* exFAT: Number of file name characters (BYTE) */
  370. #define XDIR_NameHash 36 /* exFAT: Hash of file name (WORD) */
  371. #define XDIR_ValidFileSize 40 /* exFAT: Valid file size (QWORD) */
  372. #define XDIR_FstClus 52 /* exFAT: First cluster of the file data (DWORD) */
  373. #define XDIR_FileSize 56 /* exFAT: File/Directory size (QWORD) */
  374. #define SZDIRE 32 /* Size of a directory entry */
  375. #define DDEM 0xE5 /* Deleted directory entry mark set to DIR_Name[0] */
  376. #define RDDEM 0x05 /* Replacement of the character collides with DDEM */
  377. #define LLEF 0x40 /* Last long entry flag in LDIR_Ord */
  378. #define FSI_LeadSig 0 /* FAT32 FSI: Leading signature (DWORD) */
  379. #define FSI_StrucSig 484 /* FAT32 FSI: Structure signature (DWORD) */
  380. #define FSI_Free_Count 488 /* FAT32 FSI: Number of free clusters (DWORD) */
  381. #define FSI_Nxt_Free 492 /* FAT32 FSI: Last allocated cluster (DWORD) */
  382. #define MBR_Table 446 /* MBR: Offset of partition table in the MBR */
  383. #define SZ_PTE 16 /* MBR: Size of a partition table entry */
  384. #define PTE_Boot 0 /* MBR PTE: Boot indicator */
  385. #define PTE_StHead 1 /* MBR PTE: Start head */
  386. #define PTE_StSec 2 /* MBR PTE: Start sector */
  387. #define PTE_StCyl 3 /* MBR PTE: Start cylinder */
  388. #define PTE_System 4 /* MBR PTE: System ID */
  389. #define PTE_EdHead 5 /* MBR PTE: End head */
  390. #define PTE_EdSec 6 /* MBR PTE: End sector */
  391. #define PTE_EdCyl 7 /* MBR PTE: End cylinder */
  392. #define PTE_StLba 8 /* MBR PTE: Start in LBA */
  393. #define PTE_SizLba 12 /* MBR PTE: Size in LBA */
  394. /* Post process after fatal error on file operation */
  395. #define ABORT(fs, res) { fp->err = (BYTE)(res); LEAVE_FF(fs, res); }
  396. /* Reentrancy related */
  397. #if _FS_REENTRANT
  398. #if _USE_LFN == 1
  399. #error Static LFN work area cannot be used at thread-safe configuration
  400. #endif
  401. #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; }
  402. #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
  403. #else
  404. #define ENTER_FF(fs)
  405. #define LEAVE_FF(fs, res) return res
  406. #endif
  407. /* Definitions of volume - partition conversion */
  408. #if _MULTI_PARTITION
  409. #define LD2PD(vol) VolToPart[vol].pd /* Get physical drive number */
  410. #define LD2PT(vol) VolToPart[vol].pt /* Get partition index */
  411. #else
  412. #define LD2PD(vol) (BYTE)(vol) /* Each logical drive is bound to the same physical drive number */
  413. #define LD2PT(vol) 0 /* Find first valid partition or in SFD */
  414. #endif
  415. /* Definitions of sector size */
  416. #if (_MAX_SS < _MIN_SS) || (_MAX_SS != 512 && _MAX_SS != 1024 && _MAX_SS != 2048 && _MAX_SS != 4096) || (_MIN_SS != 512 && _MIN_SS != 1024 && _MIN_SS != 2048 && _MIN_SS != 4096)
  417. #error Wrong sector size configuration
  418. #endif
  419. #if _MAX_SS == _MIN_SS
  420. #define SS(fs) ((UINT)_MAX_SS) /* Fixed sector size */
  421. #else
  422. #define SS(fs) ((fs)->ssize) /* Variable sector size */
  423. #endif
  424. /* Timestamp */
  425. #if _FS_NORTC == 1
  426. #if _NORTC_YEAR < 1980 || _NORTC_YEAR > 2107 || _NORTC_MON < 1 || _NORTC_MON > 12 || _NORTC_MDAY < 1 || _NORTC_MDAY > 31
  427. #error Invalid _FS_NORTC settings
  428. #endif
  429. #define GET_FATTIME() ((DWORD)(_NORTC_YEAR - 1980) << 25 | (DWORD)_NORTC_MON << 21 | (DWORD)_NORTC_MDAY << 16)
  430. #else
  431. #define GET_FATTIME() get_fattime()
  432. #endif
  433. /* File lock controls */
  434. #if _FS_LOCK != 0
  435. #if _FS_READONLY
  436. #error _FS_LOCK must be 0 at read-only configuration
  437. #endif
  438. typedef struct {
  439. FATFS *fs; /* Object ID 1, volume (NULL:blank entry) */
  440. DWORD clu; /* Object ID 2, containing directory (0:root) */
  441. DWORD ofs; /* Object ID 3, offset in the directory */
  442. WORD ctr; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */
  443. } FILESEM;
  444. #endif
  445. /*--------------------------------------------------------------------------
  446. Module Private Work Area
  447. ---------------------------------------------------------------------------*/
  448. /* Remark: Variables defined here without initial value shall be guaranteed
  449. / zero/null at start-up. If not, the linker option or start-up routine is
  450. / not compliance with C standard. */
  451. #if _VOLUMES < 1 || _VOLUMES > 10
  452. #error Wrong _VOLUMES setting
  453. #endif
  454. static FATFS *FatFs[_VOLUMES]; /* Pointer to the file system objects (logical drives) */
  455. static WORD Fsid; /* File system mount ID */
  456. #if _FS_RPATH != 0 && _VOLUMES >= 2
  457. static BYTE CurrVol; /* Current drive */
  458. #endif
  459. #if _FS_LOCK != 0
  460. static FILESEM Files[_FS_LOCK]; /* Open object lock semaphores */
  461. #endif
  462. #if _USE_LFN == 0 /* Non-LFN configuration */
  463. #define DEF_NAMBUF
  464. #define INIT_NAMBUF(fs)
  465. #define FREE_NAMBUF()
  466. #else /* LFN configuration */
  467. #if _MAX_LFN < 12 || _MAX_LFN > 255
  468. #error Wrong _MAX_LFN value
  469. #endif
  470. #define MAXDIRB(nc) ((nc + 44U) / 15 * SZDIRE)
  471. #if _USE_LFN == 1 /* LFN enabled with static working buffer */
  472. #if _FS_EXFAT
  473. static BYTE DirBuf[MAXDIRB(_MAX_LFN)]; /* Directory entry block scratchpad buffer */
  474. #endif
  475. static WCHAR LfnBuf[_MAX_LFN + 1]; /* LFN enabled with static working buffer */
  476. #define DEF_NAMBUF
  477. #define INIT_NAMBUF(fs)
  478. #define FREE_NAMBUF()
  479. #elif _USE_LFN == 2 /* LFN enabled with dynamic working buffer on the stack */
  480. #if _FS_EXFAT
  481. #define DEF_NAMBUF WCHAR lbuf[_MAX_LFN+1]; BYTE dbuf[MAXDIRB(_MAX_LFN)];
  482. #define INIT_NAMBUF(fs) { (fs)->lfnbuf = lbuf; (fs)->dirbuf = dbuf; }
  483. #define FREE_NAMBUF()
  484. #else
  485. #define DEF_NAMBUF WCHAR lbuf[_MAX_LFN+1];
  486. #define INIT_NAMBUF(fs) { (fs)->lfnbuf = lbuf; }
  487. #define FREE_NAMBUF()
  488. #endif
  489. #elif _USE_LFN == 3 /* LFN enabled with dynamic working buffer on the heap */
  490. #if _FS_EXFAT
  491. #define DEF_NAMBUF WCHAR *lfn;
  492. #define INIT_NAMBUF(fs) { lfn = ff_memalloc((_MAX_LFN+1)*2 + MAXDIRB(_MAX_LFN)); if (!lfn) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); (fs)->lfnbuf = lfn; (fs)->dirbuf = (BYTE*)(lfn+_MAX_LFN+1); }
  493. #define FREE_NAMBUF() ff_memfree(lfn)
  494. #else
  495. #define DEF_NAMBUF WCHAR *lfn;
  496. #define INIT_NAMBUF(fs) { lfn = ff_memalloc((_MAX_LFN+1)*2); if (!lfn) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); (fs)->lfnbuf = lfn; }
  497. #define FREE_NAMBUF() ff_memfree(lfn)
  498. #endif
  499. #else
  500. #error Wrong _USE_LFN setting
  501. #endif
  502. #endif /* else _USE_LFN == 0 */
  503. #ifdef _EXCVT
  504. static const BYTE ExCvt[] = _EXCVT; /* Upper conversion table for SBCS extended characters */
  505. #endif
  506. /*--------------------------------------------------------------------------
  507. Module Private Functions
  508. ---------------------------------------------------------------------------*/
  509. /*-----------------------------------------------------------------------*/
  510. /* Load/Store multi-byte word in the FAT structure */
  511. /*-----------------------------------------------------------------------*/
  512. static
  513. WORD ld_word (const BYTE* ptr) /* Load a 2-byte little-endian word */
  514. {
  515. WORD rv;
  516. rv = ptr[1];
  517. rv = rv << 8 | ptr[0];
  518. return rv;
  519. }
  520. static
  521. DWORD ld_dword (const BYTE* ptr) /* Load a 4-byte little-endian word */
  522. {
  523. DWORD rv;
  524. rv = ptr[3];
  525. rv = rv << 8 | ptr[2];
  526. rv = rv << 8 | ptr[1];
  527. rv = rv << 8 | ptr[0];
  528. return rv;
  529. }
  530. #if _FS_EXFAT
  531. static
  532. QWORD ld_qword (const BYTE* ptr) /* Load an 8-byte little-endian word */
  533. {
  534. QWORD rv;
  535. rv = ptr[7];
  536. rv = rv << 8 | ptr[6];
  537. rv = rv << 8 | ptr[5];
  538. rv = rv << 8 | ptr[4];
  539. rv = rv << 8 | ptr[3];
  540. rv = rv << 8 | ptr[2];
  541. rv = rv << 8 | ptr[1];
  542. rv = rv << 8 | ptr[0];
  543. return rv;
  544. }
  545. #endif
  546. #if !_FS_READONLY
  547. static
  548. void st_word (BYTE* ptr, WORD val) /* Store a 2-byte word in little-endian */
  549. {
  550. *ptr++ = (BYTE)val; val >>= 8;
  551. *ptr++ = (BYTE)val;
  552. }
  553. static
  554. void st_dword (BYTE* ptr, DWORD val) /* Store a 4-byte word in little-endian */
  555. {
  556. *ptr++ = (BYTE)val; val >>= 8;
  557. *ptr++ = (BYTE)val; val >>= 8;
  558. *ptr++ = (BYTE)val; val >>= 8;
  559. *ptr++ = (BYTE)val;
  560. }
  561. #if _FS_EXFAT
  562. static
  563. void st_qword (BYTE* ptr, QWORD val) /* Store an 8-byte word in little-endian */
  564. {
  565. *ptr++ = (BYTE)val; val >>= 8;
  566. *ptr++ = (BYTE)val; val >>= 8;
  567. *ptr++ = (BYTE)val; val >>= 8;
  568. *ptr++ = (BYTE)val; val >>= 8;
  569. *ptr++ = (BYTE)val; val >>= 8;
  570. *ptr++ = (BYTE)val; val >>= 8;
  571. *ptr++ = (BYTE)val; val >>= 8;
  572. *ptr++ = (BYTE)val;
  573. }
  574. #endif
  575. #endif /* !_FS_READONLY */
  576. /*-----------------------------------------------------------------------*/
  577. /* String functions */
  578. /*-----------------------------------------------------------------------*/
  579. /* Copy memory to memory */
  580. static
  581. void mem_cpy (void* dst, const void* src, UINT cnt) {
  582. BYTE *d = (BYTE*)dst;
  583. const BYTE *s = (const BYTE*)src;
  584. if (cnt) {
  585. do {
  586. *d++ = *s++;
  587. } while (--cnt);
  588. }
  589. }
  590. /* Fill memory block */
  591. static
  592. void mem_set (void* dst, int val, UINT cnt) {
  593. BYTE *d = (BYTE*)dst;
  594. do {
  595. *d++ = (BYTE)val;
  596. } while (--cnt);
  597. }
  598. /* Compare memory block */
  599. static
  600. int mem_cmp (const void* dst, const void* src, UINT cnt) { /* ZR:same, NZ:different */
  601. const BYTE *d = (const BYTE *)dst, *s = (const BYTE *)src;
  602. int r = 0;
  603. do {
  604. r = *d++ - *s++;
  605. } while (--cnt && r == 0);
  606. return r;
  607. }
  608. /* Check if chr is contained in the string */
  609. static
  610. int chk_chr (const char* str, int chr) { /* NZ:contained, ZR:not contained */
  611. while (*str && *str != chr) str++;
  612. return *str;
  613. }
  614. #if _FS_REENTRANT
  615. /*-----------------------------------------------------------------------*/
  616. /* Request/Release grant to access the volume */
  617. /*-----------------------------------------------------------------------*/
  618. static
  619. int lock_fs (
  620. FATFS* fs /* File system object */
  621. )
  622. {
  623. return (fs && ff_req_grant(fs->sobj)) ? 1 : 0;
  624. }
  625. static
  626. void unlock_fs (
  627. FATFS* fs, /* File system object */
  628. FRESULT res /* Result code to be returned */
  629. )
  630. {
  631. if (fs && res != FR_NOT_ENABLED && res != FR_INVALID_DRIVE && res != FR_TIMEOUT) {
  632. ff_rel_grant(fs->sobj);
  633. }
  634. }
  635. #endif
  636. #if _FS_LOCK != 0
  637. /*-----------------------------------------------------------------------*/
  638. /* File lock control functions */
  639. /*-----------------------------------------------------------------------*/
  640. static
  641. FRESULT chk_lock ( /* Check if the file can be accessed */
  642. DIR* dp, /* Directory object pointing the file to be checked */
  643. int acc /* Desired access type (0:Read, 1:Write, 2:Delete/Rename) */
  644. )
  645. {
  646. UINT i, be;
  647. /* Search file semaphore table */
  648. for (i = be = 0; i < _FS_LOCK; i++) {
  649. if (Files[i].fs) { /* Existing entry */
  650. if (Files[i].fs == dp->obj.fs && /* Check if the object matched with an open object */
  651. Files[i].clu == dp->obj.sclust &&
  652. Files[i].ofs == dp->dptr) break;
  653. } else { /* Blank entry */
  654. be = 1;
  655. }
  656. }
  657. if (i == _FS_LOCK) { /* The object is not opened */
  658. return (be || acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES; /* Is there a blank entry for new object? */
  659. }
  660. /* The object has been opened. Reject any open against writing file and all write mode open */
  661. return (acc || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK;
  662. }
  663. static
  664. int enq_lock (void) /* Check if an entry is available for a new object */
  665. {
  666. UINT i;
  667. for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
  668. return (i == _FS_LOCK) ? 0 : 1;
  669. }
  670. static
  671. UINT inc_lock ( /* Increment object open counter and returns its index (0:Internal error) */
  672. DIR* dp, /* Directory object pointing the file to register or increment */
  673. int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */
  674. )
  675. {
  676. UINT i;
  677. for (i = 0; i < _FS_LOCK; i++) { /* Find the object */
  678. if (Files[i].fs == dp->obj.fs &&
  679. Files[i].clu == dp->obj.sclust &&
  680. Files[i].ofs == dp->dptr) break;
  681. }
  682. if (i == _FS_LOCK) { /* Not opened. Register it as new. */
  683. for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
  684. if (i == _FS_LOCK) return 0; /* No free entry to register (int err) */
  685. Files[i].fs = dp->obj.fs;
  686. Files[i].clu = dp->obj.sclust;
  687. Files[i].ofs = dp->dptr;
  688. Files[i].ctr = 0;
  689. }
  690. if (acc && Files[i].ctr) return 0; /* Access violation (int err) */
  691. Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1; /* Set semaphore value */
  692. return i + 1;
  693. }
  694. static
  695. FRESULT dec_lock ( /* Decrement object open counter */
  696. UINT i /* Semaphore index (1..) */
  697. )
  698. {
  699. WORD n;
  700. FRESULT res;
  701. if (--i < _FS_LOCK) { /* Shift index number origin from 0 */
  702. n = Files[i].ctr;
  703. if (n == 0x100) n = 0; /* If write mode open, delete the entry */
  704. if (n > 0) n--; /* Decrement read mode open count */
  705. Files[i].ctr = n;
  706. if (n == 0) Files[i].fs = 0; /* Delete the entry if open count gets zero */
  707. res = FR_OK;
  708. } else {
  709. res = FR_INT_ERR; /* Invalid index nunber */
  710. }
  711. return res;
  712. }
  713. static
  714. void clear_lock ( /* Clear lock entries of the volume */
  715. FATFS *fs
  716. )
  717. {
  718. UINT i;
  719. for (i = 0; i < _FS_LOCK; i++) {
  720. if (Files[i].fs == fs) Files[i].fs = 0;
  721. }
  722. }
  723. #endif /* _FS_LOCK != 0 */
  724. /*-----------------------------------------------------------------------*/
  725. /* Move/Flush disk access window in the file system object */
  726. /*-----------------------------------------------------------------------*/
  727. #if !_FS_READONLY
  728. static
  729. FRESULT sync_window ( /* Returns FR_OK or FR_DISK_ERROR */
  730. FATFS* fs /* File system object */
  731. )
  732. {
  733. DWORD wsect;
  734. UINT nf;
  735. FRESULT res = FR_OK;
  736. if (fs->wflag) { /* Write back the sector if it is dirty */
  737. wsect = fs->winsect; /* Current sector number */
  738. if (disk_write(fs->drv, fs->win, wsect, 1) != RES_OK) {
  739. res = FR_DISK_ERR;
  740. } else {
  741. fs->wflag = 0;
  742. if (wsect - fs->fatbase < fs->fsize) { /* Is it in the FAT area? */
  743. for (nf = fs->n_fats; nf >= 2; nf--) { /* Reflect the change to all FAT copies */
  744. wsect += fs->fsize;
  745. disk_write(fs->drv, fs->win, wsect, 1);
  746. }
  747. }
  748. }
  749. }
  750. return res;
  751. }
  752. #endif
  753. static
  754. FRESULT move_window ( /* Returns FR_OK or FR_DISK_ERROR */
  755. FATFS* fs, /* File system object */
  756. DWORD sector /* Sector number to make appearance in the fs->win[] */
  757. )
  758. {
  759. FRESULT res = FR_OK;
  760. if (sector != fs->winsect) { /* Window offset changed? */
  761. #if !_FS_READONLY
  762. res = sync_window(fs); /* Write-back changes */
  763. #endif
  764. if (res == FR_OK) { /* Fill sector window with new data */
  765. if (disk_read(fs->drv, fs->win, sector, 1) != RES_OK) {
  766. sector = 0xFFFFFFFF; /* Invalidate window if data is not reliable */
  767. res = FR_DISK_ERR;
  768. }
  769. fs->winsect = sector;
  770. }
  771. }
  772. return res;
  773. }
  774. #if !_FS_READONLY
  775. /*-----------------------------------------------------------------------*/
  776. /* Synchronize file system and strage device */
  777. /*-----------------------------------------------------------------------*/
  778. static
  779. FRESULT sync_fs ( /* FR_OK:succeeded, !=0:error */
  780. FATFS* fs /* File system object */
  781. )
  782. {
  783. FRESULT res;
  784. res = sync_window(fs);
  785. if (res == FR_OK) {
  786. /* Update FSInfo sector if needed */
  787. if (fs->fs_type == FS_FAT32 && fs->fsi_flag == 1) {
  788. /* Create FSInfo structure */
  789. mem_set(fs->win, 0, SS(fs));
  790. st_word(fs->win + BS_55AA, 0xAA55);
  791. st_dword(fs->win + FSI_LeadSig, 0x41615252);
  792. st_dword(fs->win + FSI_StrucSig, 0x61417272);
  793. st_dword(fs->win + FSI_Free_Count, fs->free_clst);
  794. st_dword(fs->win + FSI_Nxt_Free, fs->last_clst);
  795. /* Write it into the FSInfo sector */
  796. fs->winsect = fs->volbase + 1;
  797. disk_write(fs->drv, fs->win, fs->winsect, 1);
  798. fs->fsi_flag = 0;
  799. }
  800. /* Make sure that no pending write process in the physical drive */
  801. if (disk_ioctl(fs->drv, CTRL_SYNC, 0) != RES_OK) res = FR_DISK_ERR;
  802. }
  803. return res;
  804. }
  805. #endif
  806. /*-----------------------------------------------------------------------*/
  807. /* Get sector# from cluster# */
  808. /*-----------------------------------------------------------------------*/
  809. static
  810. DWORD clust2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */
  811. FATFS* fs, /* File system object */
  812. DWORD clst /* Cluster# to be converted */
  813. )
  814. {
  815. clst -= 2;
  816. if (clst >= fs->n_fatent - 2) return 0; /* Invalid cluster# */
  817. return clst * fs->csize + fs->database;
  818. }
  819. /*-----------------------------------------------------------------------*/
  820. /* FAT access - Read value of a FAT entry */
  821. /*-----------------------------------------------------------------------*/
  822. static
  823. DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x7FFFFFFF:Cluster status */
  824. _FDID* obj, /* Corresponding object */
  825. DWORD clst /* Cluster number to get the value */
  826. )
  827. {
  828. UINT wc, bc;
  829. DWORD val;
  830. FATFS *fs = obj->fs;
  831. if (clst < 2 || clst >= fs->n_fatent) { /* Check if in valid range */
  832. val = 1; /* Internal error */
  833. } else {
  834. val = 0xFFFFFFFF; /* Default value falls on disk error */
  835. switch (fs->fs_type) {
  836. case FS_FAT12 :
  837. bc = (UINT)clst; bc += bc / 2;
  838. if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
  839. wc = fs->win[bc++ % SS(fs)];
  840. if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
  841. wc |= fs->win[bc % SS(fs)] << 8;
  842. val = (clst & 1) ? (wc >> 4) : (wc & 0xFFF);
  843. break;
  844. case FS_FAT16 :
  845. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2))) != FR_OK) break;
  846. val = ld_word(fs->win + clst * 2 % SS(fs));
  847. break;
  848. case FS_FAT32 :
  849. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
  850. val = ld_dword(fs->win + clst * 4 % SS(fs)) & 0x0FFFFFFF;
  851. break;
  852. #if _FS_EXFAT
  853. case FS_EXFAT :
  854. if (obj->objsize) {
  855. DWORD cofs = clst - obj->sclust; /* Offset from start cluster */
  856. DWORD clen = (DWORD)((obj->objsize - 1) / SS(fs)) / fs->csize; /* Number of clusters - 1 */
  857. if (obj->stat == 2) { /* Is there no valid chain on the FAT? */
  858. if (cofs <= clen) {
  859. val = (cofs == clen) ? 0x7FFFFFFF : clst + 1; /* Generate the value */
  860. break;
  861. }
  862. }
  863. if (obj->stat == 3 && cofs < obj->n_cont) { /* Is it in the 1st fragment? */
  864. val = clst + 1; /* Generate the value */
  865. break;
  866. }
  867. if (obj->stat != 2) { /* Get value from FAT if FAT chain is valid */
  868. if (obj->n_frag != 0) { /* Is it on the growing edge? */
  869. val = 0x7FFFFFFF; /* Generate EOC */
  870. } else {
  871. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
  872. val = ld_dword(fs->win + clst * 4 % SS(fs)) & 0x7FFFFFFF;
  873. }
  874. break;
  875. }
  876. }
  877. /* go to default */
  878. #endif
  879. default:
  880. val = 1; /* Internal error */
  881. }
  882. }
  883. return val;
  884. }
  885. #if !_FS_READONLY
  886. /*-----------------------------------------------------------------------*/
  887. /* FAT access - Change value of a FAT entry */
  888. /*-----------------------------------------------------------------------*/
  889. static
  890. FRESULT put_fat ( /* FR_OK(0):succeeded, !=0:error */
  891. FATFS* fs, /* Corresponding file system object */
  892. DWORD clst, /* FAT index number (cluster number) to be changed */
  893. DWORD val /* New value to be set to the entry */
  894. )
  895. {
  896. UINT bc;
  897. BYTE *p;
  898. FRESULT res = FR_INT_ERR;
  899. if (clst >= 2 && clst < fs->n_fatent) { /* Check if in valid range */
  900. switch (fs->fs_type) {
  901. case FS_FAT12 : /* Bitfield items */
  902. bc = (UINT)clst; bc += bc / 2;
  903. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  904. if (res != FR_OK) break;
  905. p = fs->win + bc++ % SS(fs);
  906. *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
  907. fs->wflag = 1;
  908. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  909. if (res != FR_OK) break;
  910. p = fs->win + bc % SS(fs);
  911. *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
  912. fs->wflag = 1;
  913. break;
  914. case FS_FAT16 : /* WORD aligned items */
  915. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)));
  916. if (res != FR_OK) break;
  917. st_word(fs->win + clst * 2 % SS(fs), (WORD)val);
  918. fs->wflag = 1;
  919. break;
  920. case FS_FAT32 : /* DWORD aligned items */
  921. #if _FS_EXFAT
  922. case FS_EXFAT :
  923. #endif
  924. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)));
  925. if (res != FR_OK) break;
  926. if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
  927. val = (val & 0x0FFFFFFF) | (ld_dword(fs->win + clst * 4 % SS(fs)) & 0xF0000000);
  928. }
  929. st_dword(fs->win + clst * 4 % SS(fs), val);
  930. fs->wflag = 1;
  931. break;
  932. }
  933. }
  934. return res;
  935. }
  936. #endif /* !_FS_READONLY */
  937. #if _FS_EXFAT && !_FS_READONLY
  938. /*-----------------------------------------------------------------------*/
  939. /* exFAT: Accessing FAT and Allocation Bitmap */
  940. /*-----------------------------------------------------------------------*/
  941. /*--------------------------------------*/
  942. /* Find a contiguous free cluster block */
  943. /*--------------------------------------*/
  944. static
  945. DWORD find_bitmap ( /* 0:Not found, 2..:Cluster block found, 0xFFFFFFFF:Disk error */
  946. FATFS* fs, /* File system object */
  947. DWORD clst, /* Cluster number to scan from */
  948. DWORD ncl /* Number of contiguous clusters to find (1..) */
  949. )
  950. {
  951. BYTE bm, bv;
  952. UINT i;
  953. DWORD val, scl, ctr;
  954. clst -= 2; /* The first bit in the bitmap corresponds to cluster #2 */
  955. if (clst >= fs->n_fatent - 2) clst = 0;
  956. scl = val = clst; ctr = 0;
  957. for (;;) {
  958. if (move_window(fs, fs->database + val / 8 / SS(fs)) != FR_OK) return 0xFFFFFFFF; /* (assuming bitmap is located top of the cluster heap) */
  959. i = val / 8 % SS(fs); bm = 1 << (val % 8);
  960. do {
  961. do {
  962. bv = fs->win[i] & bm; bm <<= 1; /* Get bit value */
  963. if (++val >= fs->n_fatent - 2) { /* Next cluster (with wrap-around) */
  964. val = 0; bm = 0; i = SS(fs);
  965. }
  966. if (!bv) { /* Is it a free cluster? */
  967. if (++ctr == ncl) return scl + 2; /* Check if run length is sufficient for required */
  968. } else {
  969. scl = val; ctr = 0; /* Encountered a cluster in-use, restart to scan */
  970. }
  971. if (val == clst) return 0; /* All cluster scanned? */
  972. } while (bm);
  973. bm = 1;
  974. } while (++i < SS(fs));
  975. }
  976. }
  977. /*----------------------------------------*/
  978. /* Set/Clear a block of allocation bitmap */
  979. /*----------------------------------------*/
  980. static
  981. FRESULT change_bitmap (
  982. FATFS* fs, /* File system object */
  983. DWORD clst, /* Cluster number to change from */
  984. DWORD ncl, /* Number of clusters to be changed */
  985. int bv /* bit value to be set (0 or 1) */
  986. )
  987. {
  988. BYTE bm;
  989. UINT i;
  990. DWORD sect;
  991. clst -= 2; /* The first bit corresponds to cluster #2 */
  992. sect = fs->database + clst / 8 / SS(fs); /* Sector address (assuming bitmap is located top of the cluster heap) */
  993. i = clst / 8 % SS(fs); /* Byte offset in the sector */
  994. bm = 1 << (clst % 8); /* Bit mask in the byte */
  995. for (;;) {
  996. if (move_window(fs, sect++) != FR_OK) return FR_DISK_ERR;
  997. do {
  998. do {
  999. if (bv == (int)((fs->win[i] & bm) != 0)) return FR_INT_ERR; /* Is the bit expected value? */
  1000. fs->win[i] ^= bm; /* Flip the bit */
  1001. fs->wflag = 1;
  1002. if (--ncl == 0) return FR_OK; /* All bits processed? */
  1003. } while (bm <<= 1); /* Next bit */
  1004. bm = 1;
  1005. } while (++i < SS(fs)); /* Next byte */
  1006. i = 0;
  1007. }
  1008. }
  1009. /*---------------------------------------------*/
  1010. /* Fill the first fragment of the FAT chain */
  1011. /*---------------------------------------------*/
  1012. static
  1013. FRESULT fill_first_frag (
  1014. _FDID* obj /* Pointer to the corresponding object */
  1015. )
  1016. {
  1017. FRESULT res;
  1018. DWORD cl, n;
  1019. if (obj->stat == 3) { /* Has the object been changed 'fragmented'? */
  1020. for (cl = obj->sclust, n = obj->n_cont; n; cl++, n--) { /* Create cluster chain on the FAT */
  1021. res = put_fat(obj->fs, cl, cl + 1);
  1022. if (res != FR_OK) return res;
  1023. }
  1024. obj->stat = 0; /* Change status 'FAT chain is valid' */
  1025. }
  1026. return FR_OK;
  1027. }
  1028. /*---------------------------------------------*/
  1029. /* Fill the last fragment of the FAT chain */
  1030. /*---------------------------------------------*/
  1031. static
  1032. FRESULT fill_last_frag (
  1033. _FDID* obj, /* Pointer to the corresponding object */
  1034. DWORD lcl, /* Last cluster of the fragment */
  1035. DWORD term /* Value to set the last FAT entry */
  1036. )
  1037. {
  1038. FRESULT res;
  1039. while (obj->n_frag > 0) { /* Create the last chain on the FAT */
  1040. res = put_fat(obj->fs, lcl - obj->n_frag + 1, (obj->n_frag > 1) ? lcl - obj->n_frag + 2 : term);
  1041. if (res != FR_OK) return res;
  1042. obj->n_frag--;
  1043. }
  1044. return FR_OK;
  1045. }
  1046. #endif /* _FS_EXFAT && !_FS_READONLY */
  1047. #if !_FS_READONLY
  1048. /*-----------------------------------------------------------------------*/
  1049. /* FAT handling - Remove a cluster chain */
  1050. /*-----------------------------------------------------------------------*/
  1051. static
  1052. FRESULT remove_chain ( /* FR_OK(0):succeeded, !=0:error */
  1053. _FDID* obj, /* Corresponding object */
  1054. DWORD clst, /* Cluster to remove a chain from */
  1055. DWORD pclst /* Previous cluster of clst (0:an entire chain) */
  1056. )
  1057. {
  1058. FRESULT res = FR_OK;
  1059. DWORD nxt;
  1060. FATFS *fs = obj->fs;
  1061. #if _FS_EXFAT || _USE_TRIM
  1062. DWORD scl = clst, ecl = clst;
  1063. #endif
  1064. #if _USE_TRIM
  1065. DWORD rt[2];
  1066. #endif
  1067. if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Check if in valid range */
  1068. /* Mark the previous cluster 'EOC' on the FAT if it exists */
  1069. if (pclst && (!_FS_EXFAT || fs->fs_type != FS_EXFAT || obj->stat != 2)) {
  1070. res = put_fat(fs, pclst, 0xFFFFFFFF);
  1071. if (res != FR_OK) return res;
  1072. }
  1073. /* Remove the chain */
  1074. do {
  1075. nxt = get_fat(obj, clst); /* Get cluster status */
  1076. if (nxt == 0) break; /* Empty cluster? */
  1077. if (nxt == 1) return FR_INT_ERR; /* Internal error? */
  1078. if (nxt == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error? */
  1079. if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
  1080. res = put_fat(fs, clst, 0); /* Mark the cluster 'free' on the FAT */
  1081. if (res != FR_OK) return res;
  1082. }
  1083. if (fs->free_clst < fs->n_fatent - 2) { /* Update FSINFO */
  1084. fs->free_clst++;
  1085. fs->fsi_flag |= 1;
  1086. }
  1087. #if _FS_EXFAT || _USE_TRIM
  1088. if (ecl + 1 == nxt) { /* Is next cluster contiguous? */
  1089. ecl = nxt;
  1090. } else { /* End of contiguous cluster block */
  1091. #if _FS_EXFAT
  1092. if (fs->fs_type == FS_EXFAT) {
  1093. res = change_bitmap(fs, scl, ecl - scl + 1, 0); /* Mark the cluster block 'free' on the bitmap */
  1094. if (res != FR_OK) return res;
  1095. }
  1096. #endif
  1097. #if _USE_TRIM
  1098. rt[0] = clust2sect(fs, scl); /* Start sector */
  1099. rt[1] = clust2sect(fs, ecl) + fs->csize - 1; /* End sector */
  1100. disk_ioctl(fs->drv, CTRL_TRIM, rt); /* Inform device the block can be erased */
  1101. #endif
  1102. scl = ecl = nxt;
  1103. }
  1104. #endif
  1105. clst = nxt; /* Next cluster */
  1106. } while (clst < fs->n_fatent); /* Repeat while not the last link */
  1107. #if _FS_EXFAT
  1108. if (fs->fs_type == FS_EXFAT) {
  1109. if (pclst == 0) { /* Does the object have no chain? */
  1110. obj->stat = 0; /* Change the object status 'initial' */
  1111. } else {
  1112. if (obj->stat == 3 && pclst >= obj->sclust && pclst <= obj->sclust + obj->n_cont) { /* Did the chain get contiguous? */
  1113. obj->stat = 2; /* Change the object status 'contiguous' */
  1114. }
  1115. }
  1116. }
  1117. #endif
  1118. return FR_OK;
  1119. }
  1120. /*-----------------------------------------------------------------------*/
  1121. /* FAT handling - Stretch a chain or Create a new chain */
  1122. /*-----------------------------------------------------------------------*/
  1123. static
  1124. DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
  1125. _FDID* obj, /* Corresponding object */
  1126. DWORD clst /* Cluster# to stretch, 0:Create a new chain */
  1127. )
  1128. {
  1129. DWORD cs, ncl, scl;
  1130. FRESULT res;
  1131. FATFS *fs = obj->fs;
  1132. if (clst == 0) { /* Create a new chain */
  1133. scl = fs->last_clst; /* Get suggested cluster to start from */
  1134. if (scl == 0 || scl >= fs->n_fatent) scl = 1;
  1135. }
  1136. else { /* Stretch current chain */
  1137. cs = get_fat(obj, clst); /* Check the cluster status */
  1138. if (cs < 2) return 1; /* Invalid FAT value */
  1139. if (cs == 0xFFFFFFFF) return cs; /* A disk error occurred */
  1140. if (cs < fs->n_fatent) return cs; /* It is already followed by next cluster */
  1141. scl = clst;
  1142. }
  1143. #if _FS_EXFAT
  1144. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1145. ncl = find_bitmap(fs, scl, 1); /* Find a free cluster */
  1146. if (ncl == 0 || ncl == 0xFFFFFFFF) return ncl; /* No free cluster or hard error? */
  1147. res = change_bitmap(fs, ncl, 1, 1); /* Mark the cluster 'in use' */
  1148. if (res == FR_INT_ERR) return 1;
  1149. if (res == FR_DISK_ERR) return 0xFFFFFFFF;
  1150. if (clst == 0) { /* Is it a new chain? */
  1151. obj->stat = 2; /* Set status 'contiguous' */
  1152. } else { /* It is a stretched chain */
  1153. if (obj->stat == 2 && ncl != scl + 1) { /* Is the chain got fragmented? */
  1154. obj->n_cont = scl - obj->sclust; /* Set size of the contiguous part */
  1155. obj->stat = 3; /* Change status 'just fragmented' */
  1156. }
  1157. }
  1158. if (obj->stat != 2) { /* Is the file non-contiguous? */
  1159. if (ncl == clst + 1) { /* Is the cluster next to previous one? */
  1160. obj->n_frag = obj->n_frag ? obj->n_frag + 1 : 2; /* Increment size of last framgent */
  1161. } else { /* New fragment */
  1162. if (obj->n_frag == 0) obj->n_frag = 1;
  1163. res = fill_last_frag(obj, clst, ncl); /* Fill last fragment on the FAT and link it to new one */
  1164. if (res == FR_OK) obj->n_frag = 1;
  1165. }
  1166. }
  1167. } else
  1168. #endif
  1169. { /* On the FAT12/16/32 volume */
  1170. ncl = scl; /* Start cluster */
  1171. for (;;) {
  1172. ncl++; /* Next cluster */
  1173. if (ncl >= fs->n_fatent) { /* Check wrap-around */
  1174. ncl = 2;
  1175. if (ncl > scl) return 0; /* No free cluster */
  1176. }
  1177. cs = get_fat(obj, ncl); /* Get the cluster status */
  1178. if (cs == 0) break; /* Found a free cluster */
  1179. if (cs == 1 || cs == 0xFFFFFFFF) return cs; /* An error occurred */
  1180. if (ncl == scl) return 0; /* No free cluster */
  1181. }
  1182. res = put_fat(fs, ncl, 0xFFFFFFFF); /* Mark the new cluster 'EOC' */
  1183. if (res == FR_OK && clst != 0) {
  1184. res = put_fat(fs, clst, ncl); /* Link it from the previous one if needed */
  1185. }
  1186. }
  1187. if (res == FR_OK) { /* Update FSINFO if function succeeded. */
  1188. fs->last_clst = ncl;
  1189. if (fs->free_clst <= fs->n_fatent - 2) fs->free_clst--;
  1190. fs->fsi_flag |= 1;
  1191. } else {
  1192. ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1; /* Failed. Generate error status */
  1193. }
  1194. return ncl; /* Return new cluster number or error status */
  1195. }
  1196. #endif /* !_FS_READONLY */
  1197. #if _USE_FASTSEEK
  1198. /*-----------------------------------------------------------------------*/
  1199. /* FAT handling - Convert offset into cluster with link map table */
  1200. /*-----------------------------------------------------------------------*/
  1201. static
  1202. DWORD clmt_clust ( /* <2:Error, >=2:Cluster number */
  1203. FIL* fp, /* Pointer to the file object */
  1204. FSIZE_t ofs /* File offset to be converted to cluster# */
  1205. )
  1206. {
  1207. DWORD cl, ncl, *tbl;
  1208. FATFS *fs = fp->obj.fs;
  1209. tbl = fp->cltbl + 1; /* Top of CLMT */
  1210. cl = (DWORD)(ofs / SS(fs) / fs->csize); /* Cluster order from top of the file */
  1211. for (;;) {
  1212. ncl = *tbl++; /* Number of cluters in the fragment */
  1213. if (ncl == 0) return 0; /* End of table? (error) */
  1214. if (cl < ncl) break; /* In this fragment? */
  1215. cl -= ncl; tbl++; /* Next fragment */
  1216. }
  1217. return cl + *tbl; /* Return the cluster number */
  1218. }
  1219. #endif /* _USE_FASTSEEK */
  1220. /*-----------------------------------------------------------------------*/
  1221. /* Directory handling - Set directory index */
  1222. /*-----------------------------------------------------------------------*/
  1223. static
  1224. FRESULT dir_sdi ( /* FR_OK(0):succeeded, !=0:error */
  1225. DIR* dp, /* Pointer to directory object */
  1226. DWORD ofs /* Offset of directory table */
  1227. )
  1228. {
  1229. DWORD csz, clst;
  1230. FATFS *fs = dp->obj.fs;
  1231. if (ofs >= (DWORD)((_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR) || ofs % SZDIRE) { /* Check range of offset and alignment */
  1232. return FR_INT_ERR;
  1233. }
  1234. dp->dptr = ofs; /* Set current offset */
  1235. clst = dp->obj.sclust; /* Table start cluster (0:root) */
  1236. if (clst == 0 && fs->fs_type >= FS_FAT32) { /* Replace cluster# 0 with root cluster# */
  1237. clst = fs->dirbase;
  1238. if (_FS_EXFAT) dp->obj.stat = 0; /* exFAT: Root dir has an FAT chain */
  1239. }
  1240. if (clst == 0) { /* Static table (root-directory in FAT12/16) */
  1241. if (ofs / SZDIRE >= fs->n_rootdir) return FR_INT_ERR; /* Is index out of range? */
  1242. dp->sect = fs->dirbase;
  1243. } else { /* Dynamic table (sub-directory or root-directory in FAT32+) */
  1244. csz = (DWORD)fs->csize * SS(fs); /* Bytes per cluster */
  1245. while (ofs >= csz) { /* Follow cluster chain */
  1246. clst = get_fat(&dp->obj, clst); /* Get next cluster */
  1247. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1248. if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Reached to end of table or internal error */
  1249. ofs -= csz;
  1250. }
  1251. dp->sect = clust2sect(fs, clst);
  1252. }
  1253. dp->clust = clst; /* Current cluster# */
  1254. if (!dp->sect) return FR_INT_ERR;
  1255. dp->sect += ofs / SS(fs); /* Sector# of the directory entry */
  1256. dp->dir = fs->win + (ofs % SS(fs)); /* Pointer to the entry in the win[] */
  1257. return FR_OK;
  1258. }
  1259. /*-----------------------------------------------------------------------*/
  1260. /* Directory handling - Move directory table index next */
  1261. /*-----------------------------------------------------------------------*/
  1262. static
  1263. FRESULT dir_next ( /* FR_OK(0):succeeded, FR_NO_FILE:End of table, FR_DENIED:Could not stretch */
  1264. DIR* dp, /* Pointer to the directory object */
  1265. int stretch /* 0: Do not stretch table, 1: Stretch table if needed */
  1266. )
  1267. {
  1268. DWORD ofs, clst;
  1269. FATFS *fs = dp->obj.fs;
  1270. #if !_FS_READONLY
  1271. UINT n;
  1272. #endif
  1273. ofs = dp->dptr + SZDIRE; /* Next entry */
  1274. if (!dp->sect || ofs >= (DWORD)((_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR)) return FR_NO_FILE; /* Report EOT when offset has reached max value */
  1275. if (ofs % SS(fs) == 0) { /* Sector changed? */
  1276. dp->sect++; /* Next sector */
  1277. if (!dp->clust) { /* Static table */
  1278. if (ofs / SZDIRE >= fs->n_rootdir) { /* Report EOT if it reached end of static table */
  1279. dp->sect = 0; return FR_NO_FILE;
  1280. }
  1281. }
  1282. else { /* Dynamic table */
  1283. if ((ofs / SS(fs) & (fs->csize - 1)) == 0) { /* Cluster changed? */
  1284. clst = get_fat(&dp->obj, dp->clust); /* Get next cluster */
  1285. if (clst <= 1) return FR_INT_ERR; /* Internal error */
  1286. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1287. if (clst >= fs->n_fatent) { /* Reached end of dynamic table */
  1288. #if !_FS_READONLY
  1289. if (!stretch) { /* If no stretch, report EOT */
  1290. dp->sect = 0; return FR_NO_FILE;
  1291. }
  1292. clst = create_chain(&dp->obj, dp->clust); /* Allocate a cluster */
  1293. if (clst == 0) return FR_DENIED; /* No free cluster */
  1294. if (clst == 1) return FR_INT_ERR; /* Internal error */
  1295. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1296. /* Clean-up the stretched table */
  1297. if (_FS_EXFAT) dp->obj.stat |= 4; /* The directory needs to be updated */
  1298. if (sync_window(fs) != FR_OK) return FR_DISK_ERR; /* Flush disk access window */
  1299. mem_set(fs->win, 0, SS(fs)); /* Clear window buffer */
  1300. for (n = 0, fs->winsect = clust2sect(fs, clst); n < fs->csize; n++, fs->winsect++) { /* Fill the new cluster with 0 */
  1301. fs->wflag = 1;
  1302. if (sync_window(fs) != FR_OK) return FR_DISK_ERR;
  1303. }
  1304. fs->winsect -= n; /* Restore window offset */
  1305. #else
  1306. if (!stretch) dp->sect = 0; /* (this line is to suppress compiler warning) */
  1307. dp->sect = 0; return FR_NO_FILE; /* Report EOT */
  1308. #endif
  1309. }
  1310. dp->clust = clst; /* Initialize data for new cluster */
  1311. dp->sect = clust2sect(fs, clst);
  1312. }
  1313. }
  1314. }
  1315. dp->dptr = ofs; /* Current entry */
  1316. dp->dir = fs->win + ofs % SS(fs); /* Pointer to the entry in the win[] */
  1317. return FR_OK;
  1318. }
  1319. #if !_FS_READONLY
  1320. /*-----------------------------------------------------------------------*/
  1321. /* Directory handling - Reserve a block of directory entries */
  1322. /*-----------------------------------------------------------------------*/
  1323. static
  1324. FRESULT dir_alloc ( /* FR_OK(0):succeeded, !=0:error */
  1325. DIR* dp, /* Pointer to the directory object */
  1326. UINT nent /* Number of contiguous entries to allocate */
  1327. )
  1328. {
  1329. FRESULT res;
  1330. UINT n;
  1331. FATFS *fs = dp->obj.fs;
  1332. res = dir_sdi(dp, 0);
  1333. if (res == FR_OK) {
  1334. n = 0;
  1335. do {
  1336. res = move_window(fs, dp->sect);
  1337. if (res != FR_OK) break;
  1338. #if _FS_EXFAT
  1339. if ((fs->fs_type == FS_EXFAT) ? (int)((dp->dir[XDIR_Type] & 0x80) == 0) : (int)(dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0)) {
  1340. #else
  1341. if (dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0) {
  1342. #endif
  1343. if (++n == nent) break; /* A block of contiguous free entries is found */
  1344. } else {
  1345. n = 0; /* Not a blank entry. Restart to search */
  1346. }
  1347. res = dir_next(dp, 1);
  1348. } while (res == FR_OK); /* Next entry with table stretch enabled */
  1349. }
  1350. if (res == FR_NO_FILE) res = FR_DENIED; /* No directory entry to allocate */
  1351. return res;
  1352. }
  1353. #endif /* !_FS_READONLY */
  1354. /*-----------------------------------------------------------------------*/
  1355. /* FAT: Directory handling - Load/Store start cluster number */
  1356. /*-----------------------------------------------------------------------*/
  1357. static
  1358. DWORD ld_clust ( /* Returns the top cluster value of the SFN entry */
  1359. FATFS* fs, /* Pointer to the fs object */
  1360. const BYTE* dir /* Pointer to the key entry */
  1361. )
  1362. {
  1363. DWORD cl;
  1364. cl = ld_word(dir + DIR_FstClusLO);
  1365. if (fs->fs_type == FS_FAT32) {
  1366. cl |= (DWORD)ld_word(dir + DIR_FstClusHI) << 16;
  1367. }
  1368. return cl;
  1369. }
  1370. #if !_FS_READONLY
  1371. static
  1372. void st_clust (
  1373. FATFS* fs, /* Pointer to the fs object */
  1374. BYTE* dir, /* Pointer to the key entry */
  1375. DWORD cl /* Value to be set */
  1376. )
  1377. {
  1378. st_word(dir + DIR_FstClusLO, (WORD)cl);
  1379. if (fs->fs_type == FS_FAT32) {
  1380. st_word(dir + DIR_FstClusHI, (WORD)(cl >> 16));
  1381. }
  1382. }
  1383. #endif
  1384. #if _USE_LFN != 0
  1385. /*------------------------------------------------------------------------*/
  1386. /* FAT-LFN: LFN handling */
  1387. /*------------------------------------------------------------------------*/
  1388. static
  1389. const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN characters in the directory entry */
  1390. /*--------------------------------------------------------*/
  1391. /* FAT-LFN: Compare a part of file name with an LFN entry */
  1392. /*--------------------------------------------------------*/
  1393. static
  1394. int cmp_lfn ( /* 1:matched, 0:not matched */
  1395. const WCHAR* lfnbuf, /* Pointer to the LFN working buffer to be compared */
  1396. BYTE* dir /* Pointer to the directory entry containing the part of LFN */
  1397. )
  1398. {
  1399. UINT i, s;
  1400. WCHAR wc, uc;
  1401. if (ld_word(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO */
  1402. i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
  1403. for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */
  1404. uc = ld_word(dir + LfnOfs[s]); /* Pick an LFN character */
  1405. if (wc) {
  1406. if (i >= _MAX_LFN || ff_wtoupper(uc) != ff_wtoupper(lfnbuf[i++])) { /* Compare it */
  1407. return 0; /* Not matched */
  1408. }
  1409. wc = uc;
  1410. } else {
  1411. if (uc != 0xFFFF) return 0; /* Check filler */
  1412. }
  1413. }
  1414. if ((dir[LDIR_Ord] & LLEF) && wc && lfnbuf[i]) return 0; /* Last segment matched but different length */
  1415. return 1; /* The part of LFN matched */
  1416. }
  1417. #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 || _USE_LABEL || _FS_EXFAT
  1418. /*-----------------------------------------------------*/
  1419. /* FAT-LFN: Pick a part of file name from an LFN entry */
  1420. /*-----------------------------------------------------*/
  1421. static
  1422. int pick_lfn ( /* 1:succeeded, 0:buffer overflow or invalid LFN entry */
  1423. WCHAR* lfnbuf, /* Pointer to the LFN working buffer */
  1424. BYTE* dir /* Pointer to the LFN entry */
  1425. )
  1426. {
  1427. UINT i, s;
  1428. WCHAR wc, uc;
  1429. if (ld_word(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO is 0 */
  1430. i = ((dir[LDIR_Ord] & ~LLEF) - 1) * 13; /* Offset in the LFN buffer */
  1431. for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */
  1432. uc = ld_word(dir + LfnOfs[s]); /* Pick an LFN character */
  1433. if (wc) {
  1434. if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
  1435. lfnbuf[i++] = wc = uc; /* Store it */
  1436. } else {
  1437. if (uc != 0xFFFF) return 0; /* Check filler */
  1438. }
  1439. }
  1440. if (dir[LDIR_Ord] & LLEF) { /* Put terminator if it is the last LFN part */
  1441. if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
  1442. lfnbuf[i] = 0;
  1443. }
  1444. return 1; /* The part of LFN is valid */
  1445. }
  1446. #endif
  1447. #if !_FS_READONLY
  1448. /*-----------------------------------------*/
  1449. /* FAT-LFN: Create an entry of LFN entries */
  1450. /*-----------------------------------------*/
  1451. static
  1452. void put_lfn (
  1453. const WCHAR* lfn, /* Pointer to the LFN */
  1454. BYTE* dir, /* Pointer to the LFN entry to be created */
  1455. BYTE ord, /* LFN order (1-20) */
  1456. BYTE sum /* Checksum of the corresponding SFN */
  1457. )
  1458. {
  1459. UINT i, s;
  1460. WCHAR wc;
  1461. dir[LDIR_Chksum] = sum; /* Set checksum */
  1462. dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */
  1463. dir[LDIR_Type] = 0;
  1464. st_word(dir + LDIR_FstClusLO, 0);
  1465. i = (ord - 1) * 13; /* Get offset in the LFN working buffer */
  1466. s = wc = 0;
  1467. do {
  1468. if (wc != 0xFFFF) wc = lfn[i++]; /* Get an effective character */
  1469. st_word(dir + LfnOfs[s], wc); /* Put it */
  1470. if (wc == 0) wc = 0xFFFF; /* Padding characters for left locations */
  1471. } while (++s < 13);
  1472. if (wc == 0xFFFF || !lfn[i]) ord |= LLEF; /* Last LFN part is the start of LFN sequence */
  1473. dir[LDIR_Ord] = ord; /* Set the LFN order */
  1474. }
  1475. #endif /* !_FS_READONLY */
  1476. #endif /* _USE_LFN != 0 */
  1477. #if _USE_LFN != 0 && !_FS_READONLY
  1478. /*-----------------------------------------------------------------------*/
  1479. /* FAT-LFN: Create a Numbered SFN */
  1480. /*-----------------------------------------------------------------------*/
  1481. static
  1482. void gen_numname (
  1483. BYTE* dst, /* Pointer to the buffer to store numbered SFN */
  1484. const BYTE* src, /* Pointer to SFN */
  1485. const WCHAR* lfn, /* Pointer to LFN */
  1486. UINT seq /* Sequence number */
  1487. )
  1488. {
  1489. BYTE ns[8], c;
  1490. UINT i, j;
  1491. WCHAR wc;
  1492. DWORD sr;
  1493. mem_cpy(dst, src, 11);
  1494. if (seq > 5) { /* In case of many collisions, generate a hash number instead of sequential number */
  1495. sr = seq;
  1496. while (*lfn) { /* Create a CRC */
  1497. wc = *lfn++;
  1498. for (i = 0; i < 16; i++) {
  1499. sr = (sr << 1) + (wc & 1);
  1500. wc >>= 1;
  1501. if (sr & 0x10000) sr ^= 0x11021;
  1502. }
  1503. }
  1504. seq = (UINT)sr;
  1505. }
  1506. /* itoa (hexdecimal) */
  1507. i = 7;
  1508. do {
  1509. c = (BYTE)((seq % 16) + '0');
  1510. if (c > '9') c += 7;
  1511. ns[i--] = c;
  1512. seq /= 16;
  1513. } while (seq);
  1514. ns[i] = '~';
  1515. /* Append the number */
  1516. for (j = 0; j < i && dst[j] != ' '; j++) {
  1517. if (IsDBCS1(dst[j])) {
  1518. if (j == i - 1) break;
  1519. j++;
  1520. }
  1521. }
  1522. do {
  1523. dst[j++] = (i < 8) ? ns[i++] : ' ';
  1524. } while (j < 8);
  1525. }
  1526. #endif /* _USE_LFN != 0 && !_FS_READONLY */
  1527. #if _USE_LFN != 0
  1528. /*-----------------------------------------------------------------------*/
  1529. /* FAT-LFN: Calculate checksum of an SFN entry */
  1530. /*-----------------------------------------------------------------------*/
  1531. static
  1532. BYTE sum_sfn (
  1533. const BYTE* dir /* Pointer to the SFN entry */
  1534. )
  1535. {
  1536. BYTE sum = 0;
  1537. UINT n = 11;
  1538. do {
  1539. sum = (sum >> 1) + (sum << 7) + *dir++;
  1540. } while (--n);
  1541. return sum;
  1542. }
  1543. #endif /* _USE_LFN != 0 */
  1544. #if _FS_EXFAT
  1545. /*-----------------------------------------------------------------------*/
  1546. /* exFAT: Checksum */
  1547. /*-----------------------------------------------------------------------*/
  1548. static
  1549. WORD xdir_sum ( /* Get checksum of the directoly block */
  1550. const BYTE* dir /* Directory entry block to be calculated */
  1551. )
  1552. {
  1553. UINT i, szblk;
  1554. WORD sum;
  1555. szblk = (dir[XDIR_NumSec] + 1) * SZDIRE;
  1556. for (i = sum = 0; i < szblk; i++) {
  1557. if (i == XDIR_SetSum) { /* Skip sum field */
  1558. i++;
  1559. } else {
  1560. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + dir[i];
  1561. }
  1562. }
  1563. return sum;
  1564. }
  1565. static
  1566. WORD xname_sum ( /* Get check sum (to be used as hash) of the name */
  1567. const WCHAR* name /* File name to be calculated */
  1568. )
  1569. {
  1570. WCHAR chr;
  1571. WORD sum = 0;
  1572. while ((chr = *name++) != 0) {
  1573. chr = ff_wtoupper(chr); /* File name needs to be ignored case */
  1574. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + (chr & 0xFF);
  1575. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + (chr >> 8);
  1576. }
  1577. return sum;
  1578. }
  1579. #if !_FS_READONLY && _USE_MKFS
  1580. static
  1581. DWORD xsum32 (
  1582. BYTE dat, /* Data to be sumed */
  1583. DWORD sum /* Previous value */
  1584. )
  1585. {
  1586. sum = ((sum & 1) ? 0x80000000 : 0) + (sum >> 1) + dat;
  1587. return sum;
  1588. }
  1589. #endif
  1590. #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2
  1591. /*------------------------------------------------------*/
  1592. /* exFAT: Get object information from a directory block */
  1593. /*------------------------------------------------------*/
  1594. static
  1595. void get_xdir_info (
  1596. BYTE* dirb, /* Pointer to the direcotry entry block 85+C0+C1s */
  1597. FILINFO* fno /* Buffer to store the extracted file information */
  1598. )
  1599. {
  1600. UINT di, si;
  1601. WCHAR w;
  1602. #if !_LFN_UNICODE
  1603. UINT nc;
  1604. #endif
  1605. /* Get file name */
  1606. di = 0;
  1607. #if _LFN_UNICODE
  1608. for (si = SZDIRE * 2; di < dirb[XDIR_NumName]; si += 2, di++) {
  1609. if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */
  1610. w = ld_word(dirb + si); /* Get a character */
  1611. if (di >= _MAX_LFN) { di = 0; break; } /* Buffer overflow --> inaccessible object name */
  1612. fno->fname[di] = w; /* Store it */
  1613. }
  1614. #else
  1615. for (si = SZDIRE * 2, nc = 0; nc < dirb[XDIR_NumName]; si += 2, nc++) {
  1616. if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */
  1617. w = ff_convert(ld_word(dirb + si), 0); /* Get a character and Unicode -> OEM */
  1618. if (_DF1S && w >= 0x100) { /* Is it a double byte char? (always false at SBCS cfg) */
  1619. fno->fname[di++] = (char)(w >> 8); /* Put 1st byte of the DBC */
  1620. }
  1621. if (w == 0 || di >= _MAX_LFN) { di = 0; break; } /* Invalid char or buffer overflow --> inaccessible object name */
  1622. fno->fname[di++] = (char)w;
  1623. }
  1624. #endif
  1625. if (di == 0) fno->fname[di++] = '?'; /* Inaccessible object name? */
  1626. fno->fname[di] = 0; /* Terminate file name */
  1627. fno->altname[0] = 0; /* No SFN */
  1628. fno->fattrib = dirb[XDIR_Attr]; /* Attribute */
  1629. fno->fsize = (fno->fattrib & AM_DIR) ? 0 : ld_qword(dirb + XDIR_FileSize); /* Size */
  1630. fno->ftime = ld_word(dirb + XDIR_ModTime + 0); /* Time */
  1631. fno->fdate = ld_word(dirb + XDIR_ModTime + 2); /* Date */
  1632. }
  1633. #endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */
  1634. /*-----------------------------------*/
  1635. /* exFAT: Get a directry entry block */
  1636. /*-----------------------------------*/
  1637. static
  1638. FRESULT load_xdir ( /* FR_INT_ERR: invalid entry block */
  1639. DIR* dp /* Pointer to the reading direcotry object pointing the 85 entry */
  1640. )
  1641. {
  1642. FRESULT res;
  1643. UINT i, sz_ent;
  1644. BYTE* dirb = dp->obj.fs->dirbuf; /* Pointer to the on-memory direcotry entry block 85+C0+C1s */
  1645. /* Load 85 entry */
  1646. res = move_window(dp->obj.fs, dp->sect);
  1647. if (res != FR_OK) return res;
  1648. if (dp->dir[XDIR_Type] != 0x85) return FR_INT_ERR;
  1649. mem_cpy(dirb + 0, dp->dir, SZDIRE);
  1650. sz_ent = (dirb[XDIR_NumSec] + 1) * SZDIRE;
  1651. if (sz_ent < 3 * SZDIRE || sz_ent > 19 * SZDIRE) return FR_INT_ERR;
  1652. /* Load C0 entry */
  1653. res = dir_next(dp, 0);
  1654. if (res != FR_OK) return res;
  1655. res = move_window(dp->obj.fs, dp->sect);
  1656. if (res != FR_OK) return res;
  1657. if (dp->dir[XDIR_Type] != 0xC0) return FR_INT_ERR;
  1658. mem_cpy(dirb + SZDIRE, dp->dir, SZDIRE);
  1659. if (MAXDIRB(dirb[XDIR_NumName]) > sz_ent) return FR_INT_ERR;
  1660. /* Load C1 entries */
  1661. i = SZDIRE * 2; /* C1 offset */
  1662. do {
  1663. res = dir_next(dp, 0);
  1664. if (res != FR_OK) return res;
  1665. res = move_window(dp->obj.fs, dp->sect);
  1666. if (res != FR_OK) return res;
  1667. if (dp->dir[XDIR_Type] != 0xC1) return FR_INT_ERR;
  1668. if (i < MAXDIRB(_MAX_LFN)) mem_cpy(dirb + i, dp->dir, SZDIRE);
  1669. } while ((i += SZDIRE) < sz_ent);
  1670. /* Sanity check (do it when accessible object name) */
  1671. if (i <= MAXDIRB(_MAX_LFN)) {
  1672. if (xdir_sum(dirb) != ld_word(dirb + XDIR_SetSum)) return FR_INT_ERR;
  1673. }
  1674. return FR_OK;
  1675. }
  1676. #if !_FS_READONLY || _FS_RPATH != 0
  1677. /*------------------------------------------------*/
  1678. /* exFAT: Load the object's directory entry block */
  1679. /*------------------------------------------------*/
  1680. static
  1681. FRESULT load_obj_dir (
  1682. DIR* dp, /* Blank directory object to be used to access containing direcotry */
  1683. const _FDID* obj /* Object with its containing directory information */
  1684. )
  1685. {
  1686. FRESULT res;
  1687. /* Open object containing directory */
  1688. dp->obj.fs = obj->fs;
  1689. dp->obj.sclust = obj->c_scl;
  1690. dp->obj.stat = (BYTE)obj->c_size;
  1691. dp->obj.objsize = obj->c_size & 0xFFFFFF00;
  1692. dp->blk_ofs = obj->c_ofs;
  1693. res = dir_sdi(dp, dp->blk_ofs); /* Goto object's entry block */
  1694. if (res == FR_OK) {
  1695. res = load_xdir(dp); /* Load the object's entry block */
  1696. }
  1697. return res;
  1698. }
  1699. #endif
  1700. #if !_FS_READONLY
  1701. /*-----------------------------------------------*/
  1702. /* exFAT: Store the directory block to the media */
  1703. /*-----------------------------------------------*/
  1704. static
  1705. FRESULT store_xdir (
  1706. DIR* dp /* Pointer to the direcotry object */
  1707. )
  1708. {
  1709. FRESULT res;
  1710. UINT nent;
  1711. BYTE* dirb = dp->obj.fs->dirbuf; /* Pointer to the direcotry entry block 85+C0+C1s */
  1712. /* Create set sum */
  1713. st_word(dirb + XDIR_SetSum, xdir_sum(dirb));
  1714. nent = dirb[XDIR_NumSec] + 1;
  1715. /* Store the set of directory to the volume */
  1716. res = dir_sdi(dp, dp->blk_ofs);
  1717. while (res == FR_OK) {
  1718. res = move_window(dp->obj.fs, dp->sect);
  1719. if (res != FR_OK) break;
  1720. mem_cpy(dp->dir, dirb, SZDIRE);
  1721. dp->obj.fs->wflag = 1;
  1722. if (--nent == 0) break;
  1723. dirb += SZDIRE;
  1724. res = dir_next(dp, 0);
  1725. }
  1726. return (res == FR_OK || res == FR_DISK_ERR) ? res : FR_INT_ERR;
  1727. }
  1728. /*-------------------------------------------*/
  1729. /* exFAT: Create a new directory enrty block */
  1730. /*-------------------------------------------*/
  1731. static
  1732. void create_xdir (
  1733. BYTE* dirb, /* Pointer to the direcotry entry block buffer */
  1734. const WCHAR* lfn /* Pointer to the nul terminated file name */
  1735. )
  1736. {
  1737. UINT i;
  1738. BYTE nb, nc;
  1739. WCHAR chr;
  1740. /* Create 85+C0 entry */
  1741. mem_set(dirb, 0, 2 * SZDIRE);
  1742. dirb[XDIR_Type] = 0x85;
  1743. dirb[XDIR_Type + SZDIRE] = 0xC0;
  1744. /* Create C1 entries */
  1745. nc = 0; nb = 1; chr = 1; i = SZDIRE * 2;
  1746. do {
  1747. dirb[i++] = 0xC1; dirb[i++] = 0; /* Entry type C1 */
  1748. do { /* Fill name field */
  1749. if (chr && (chr = lfn[nc]) != 0) nc++; /* Get a character if exist */
  1750. st_word(dirb + i, chr); /* Store it */
  1751. } while ((i += 2) % SZDIRE != 0);
  1752. nb++;
  1753. } while (lfn[nc]); /* Fill next entry if any char follows */
  1754. dirb[XDIR_NumName] = nc; /* Set name length */
  1755. dirb[XDIR_NumSec] = nb; /* Set block length */
  1756. st_word(dirb + XDIR_NameHash, xname_sum(lfn)); /* Set name hash */
  1757. }
  1758. #endif /* !_FS_READONLY */
  1759. #endif /* _FS_EXFAT */
  1760. #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 || _USE_LABEL || _FS_EXFAT
  1761. /*-----------------------------------------------------------------------*/
  1762. /* Read an object from the directory */
  1763. /*-----------------------------------------------------------------------*/
  1764. static
  1765. FRESULT dir_read (
  1766. DIR* dp, /* Pointer to the directory object */
  1767. int vol /* Filtered by 0:file/directory or 1:volume label */
  1768. )
  1769. {
  1770. FRESULT res = FR_NO_FILE;
  1771. FATFS *fs = dp->obj.fs;
  1772. BYTE a, c;
  1773. #if _USE_LFN != 0
  1774. BYTE ord = 0xFF, sum = 0xFF;
  1775. #endif
  1776. while (dp->sect) {
  1777. res = move_window(fs, dp->sect);
  1778. if (res != FR_OK) break;
  1779. c = dp->dir[DIR_Name]; /* Test for the entry type */
  1780. if (c == 0) {
  1781. res = FR_NO_FILE; break; /* Reached to end of the directory */
  1782. }
  1783. #if _FS_EXFAT
  1784. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1785. if (_USE_LABEL && vol) {
  1786. if (c == 0x83) break; /* Volume label entry? */
  1787. } else {
  1788. if (c == 0x85) { /* Start of the file entry block? */
  1789. dp->blk_ofs = dp->dptr; /* Get location of the block */
  1790. res = load_xdir(dp); /* Load the entry block */
  1791. if (res == FR_OK) {
  1792. dp->obj.attr = fs->dirbuf[XDIR_Attr] & AM_MASK; /* Get attribute */
  1793. }
  1794. break;
  1795. }
  1796. }
  1797. } else
  1798. #endif
  1799. { /* On the FAT12/16/32 volume */
  1800. dp->obj.attr = a = dp->dir[DIR_Attr] & AM_MASK; /* Get attribute */
  1801. #if _USE_LFN != 0 /* LFN configuration */
  1802. if (c == DDEM || c == '.' || (int)((a & ~AM_ARC) == AM_VOL) != vol) { /* An entry without valid data */
  1803. ord = 0xFF;
  1804. } else {
  1805. if (a == AM_LFN) { /* An LFN entry is found */
  1806. if (c & LLEF) { /* Is it start of an LFN sequence? */
  1807. sum = dp->dir[LDIR_Chksum];
  1808. c &= (BYTE)~LLEF; ord = c;
  1809. dp->blk_ofs = dp->dptr;
  1810. }
  1811. /* Check LFN validity and capture it */
  1812. ord = (c == ord && sum == dp->dir[LDIR_Chksum] && pick_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF;
  1813. } else { /* An SFN entry is found */
  1814. if (ord || sum != sum_sfn(dp->dir)) { /* Is there a valid LFN? */
  1815. dp->blk_ofs = 0xFFFFFFFF; /* It has no LFN. */
  1816. }
  1817. break;
  1818. }
  1819. }
  1820. #else /* Non LFN configuration */
  1821. if (c != DDEM && c != '.' && a != AM_LFN && (int)((a & ~AM_ARC) == AM_VOL) == vol) { /* Is it a valid entry? */
  1822. break;
  1823. }
  1824. #endif
  1825. }
  1826. res = dir_next(dp, 0); /* Next entry */
  1827. if (res != FR_OK) break;
  1828. }
  1829. if (res != FR_OK) dp->sect = 0; /* Terminate the read operation on error or EOT */
  1830. return res;
  1831. }
  1832. #endif /* _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2 */
  1833. /*-----------------------------------------------------------------------*/
  1834. /* Directory handling - Find an object in the directory */
  1835. /*-----------------------------------------------------------------------*/
  1836. static
  1837. FRESULT dir_find ( /* FR_OK(0):succeeded, !=0:error */
  1838. DIR* dp /* Pointer to the directory object with the file name */
  1839. )
  1840. {
  1841. FRESULT res;
  1842. FATFS *fs = dp->obj.fs;
  1843. BYTE c;
  1844. #if _USE_LFN != 0
  1845. BYTE a, ord, sum;
  1846. #endif
  1847. res = dir_sdi(dp, 0); /* Rewind directory object */
  1848. if (res != FR_OK) return res;
  1849. #if _FS_EXFAT
  1850. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1851. BYTE nc;
  1852. UINT di, ni;
  1853. WORD hash = xname_sum(fs->lfnbuf); /* Hash value of the name to find */
  1854. while ((res = dir_read(dp, 0)) == FR_OK) { /* Read an item */
  1855. #if _MAX_LFN < 255
  1856. if (fs->dirbuf[XDIR_NumName] > _MAX_LFN) continue; /* Skip comparison if inaccessible object name */
  1857. #endif
  1858. if (ld_word(fs->dirbuf + XDIR_NameHash) != hash) continue; /* Skip comparison if hash mismatched */
  1859. for (nc = fs->dirbuf[XDIR_NumName], di = SZDIRE * 2, ni = 0; nc; nc--, di += 2, ni++) { /* Compare the name */
  1860. if ((di % SZDIRE) == 0) di += 2;
  1861. if (ff_wtoupper(ld_word(fs->dirbuf + di)) != ff_wtoupper(fs->lfnbuf[ni])) break;
  1862. }
  1863. if (nc == 0 && !fs->lfnbuf[ni]) break; /* Name matched? */
  1864. }
  1865. return res;
  1866. }
  1867. #endif
  1868. /* On the FAT12/16/32 volume */
  1869. #if _USE_LFN != 0
  1870. ord = sum = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
  1871. #endif
  1872. do {
  1873. res = move_window(fs, dp->sect);
  1874. if (res != FR_OK) break;
  1875. c = dp->dir[DIR_Name];
  1876. if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
  1877. #if _USE_LFN != 0 /* LFN configuration */
  1878. dp->obj.attr = a = dp->dir[DIR_Attr] & AM_MASK;
  1879. if (c == DDEM || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
  1880. ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
  1881. } else {
  1882. if (a == AM_LFN) { /* An LFN entry is found */
  1883. if (!(dp->fn[NSFLAG] & NS_NOLFN)) {
  1884. if (c & LLEF) { /* Is it start of LFN sequence? */
  1885. sum = dp->dir[LDIR_Chksum];
  1886. c &= (BYTE)~LLEF; ord = c; /* LFN start order */
  1887. dp->blk_ofs = dp->dptr; /* Start offset of LFN */
  1888. }
  1889. /* Check validity of the LFN entry and compare it with given name */
  1890. ord = (c == ord && sum == dp->dir[LDIR_Chksum] && cmp_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF;
  1891. }
  1892. } else { /* An SFN entry is found */
  1893. if (!ord && sum == sum_sfn(dp->dir)) break; /* LFN matched? */
  1894. if (!(dp->fn[NSFLAG] & NS_LOSS) && !mem_cmp(dp->dir, dp->fn, 11)) break; /* SFN matched? */
  1895. ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
  1896. }
  1897. }
  1898. #else /* Non LFN configuration */
  1899. dp->obj.attr = dp->dir[DIR_Attr] & AM_MASK;
  1900. if (!(dp->dir[DIR_Attr] & AM_VOL) && !mem_cmp(dp->dir, dp->fn, 11)) break; /* Is it a valid entry? */
  1901. #endif
  1902. res = dir_next(dp, 0); /* Next entry */
  1903. } while (res == FR_OK);
  1904. return res;
  1905. }
  1906. #if !_FS_READONLY
  1907. /*-----------------------------------------------------------------------*/
  1908. /* Register an object to the directory */
  1909. /*-----------------------------------------------------------------------*/
  1910. static
  1911. FRESULT dir_register ( /* FR_OK:succeeded, FR_DENIED:no free entry or too many SFN collision, FR_DISK_ERR:disk error */
  1912. DIR* dp /* Target directory with object name to be created */
  1913. )
  1914. {
  1915. FRESULT res;
  1916. FATFS *fs = dp->obj.fs;
  1917. #if _USE_LFN != 0 /* LFN configuration */
  1918. UINT n, nlen, nent;
  1919. BYTE sn[12], sum;
  1920. if (dp->fn[NSFLAG] & (NS_DOT | NS_NONAME)) return FR_INVALID_NAME; /* Check name validity */
  1921. for (nlen = 0; fs->lfnbuf[nlen]; nlen++) ; /* Get lfn length */
  1922. #if _FS_EXFAT
  1923. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1924. DIR dj;
  1925. nent = (nlen + 14) / 15 + 2; /* Number of entries to allocate (85+C0+C1s) */
  1926. res = dir_alloc(dp, nent); /* Allocate entries */
  1927. if (res != FR_OK) return res;
  1928. dp->blk_ofs = dp->dptr - SZDIRE * (nent - 1); /* Set the allocated entry block offset */
  1929. if (dp->obj.sclust != 0 && (dp->obj.stat & 4)) { /* Has the sub-directory been stretched? */
  1930. dp->obj.objsize += (DWORD)fs->csize * SS(fs); /* Increase the directory size by cluster size */
  1931. res = fill_first_frag(&dp->obj); /* Fill first fragment on the FAT if needed */
  1932. if (res != FR_OK) return res;
  1933. res = fill_last_frag(&dp->obj, dp->clust, 0xFFFFFFFF); /* Fill last fragment on the FAT if needed */
  1934. if (res != FR_OK) return res;
  1935. res = load_obj_dir(&dj, &dp->obj); /* Load the object status */
  1936. if (res != FR_OK) return res;
  1937. st_qword(fs->dirbuf + XDIR_FileSize, dp->obj.objsize); /* Update the allocation status */
  1938. st_qword(fs->dirbuf + XDIR_ValidFileSize, dp->obj.objsize);
  1939. fs->dirbuf[XDIR_GenFlags] = dp->obj.stat | 1;
  1940. res = store_xdir(&dj); /* Store the object status */
  1941. if (res != FR_OK) return res;
  1942. }
  1943. create_xdir(fs->dirbuf, fs->lfnbuf); /* Create on-memory directory block to be written later */
  1944. return FR_OK;
  1945. }
  1946. #endif
  1947. /* On the FAT12/16/32 volume */
  1948. mem_cpy(sn, dp->fn, 12);
  1949. if (sn[NSFLAG] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */
  1950. dp->fn[NSFLAG] = NS_NOLFN; /* Find only SFN */
  1951. for (n = 1; n < 100; n++) {
  1952. gen_numname(dp->fn, sn, fs->lfnbuf, n); /* Generate a numbered name */
  1953. res = dir_find(dp); /* Check if the name collides with existing SFN */
  1954. if (res != FR_OK) break;
  1955. }
  1956. if (n == 100) return FR_DENIED; /* Abort if too many collisions */
  1957. if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */
  1958. dp->fn[NSFLAG] = sn[NSFLAG];
  1959. }
  1960. /* Create an SFN with/without LFNs. */
  1961. nent = (sn[NSFLAG] & NS_LFN) ? (nlen + 12) / 13 + 1 : 1; /* Number of entries to allocate */
  1962. res = dir_alloc(dp, nent); /* Allocate entries */
  1963. if (res == FR_OK && --nent) { /* Set LFN entry if needed */
  1964. res = dir_sdi(dp, dp->dptr - nent * SZDIRE);
  1965. if (res == FR_OK) {
  1966. sum = sum_sfn(dp->fn); /* Checksum value of the SFN tied to the LFN */
  1967. do { /* Store LFN entries in bottom first */
  1968. res = move_window(fs, dp->sect);
  1969. if (res != FR_OK) break;
  1970. put_lfn(fs->lfnbuf, dp->dir, (BYTE)nent, sum);
  1971. fs->wflag = 1;
  1972. res = dir_next(dp, 0); /* Next entry */
  1973. } while (res == FR_OK && --nent);
  1974. }
  1975. }
  1976. #else /* Non LFN configuration */
  1977. res = dir_alloc(dp, 1); /* Allocate an entry for SFN */
  1978. #endif
  1979. /* Set SFN entry */
  1980. if (res == FR_OK) {
  1981. res = move_window(fs, dp->sect);
  1982. if (res == FR_OK) {
  1983. mem_set(dp->dir, 0, SZDIRE); /* Clean the entry */
  1984. mem_cpy(dp->dir + DIR_Name, dp->fn, 11); /* Put SFN */
  1985. #if _USE_LFN != 0
  1986. dp->dir[DIR_NTres] = dp->fn[NSFLAG] & (NS_BODY | NS_EXT); /* Put NT flag */
  1987. #endif
  1988. fs->wflag = 1;
  1989. }
  1990. }
  1991. return res;
  1992. }
  1993. #endif /* !_FS_READONLY */
  1994. #if !_FS_READONLY && _FS_MINIMIZE == 0
  1995. /*-----------------------------------------------------------------------*/
  1996. /* Remove an object from the directory */
  1997. /*-----------------------------------------------------------------------*/
  1998. static
  1999. FRESULT dir_remove ( /* FR_OK:Succeeded, FR_DISK_ERR:A disk error */
  2000. DIR* dp /* Directory object pointing the entry to be removed */
  2001. )
  2002. {
  2003. FRESULT res;
  2004. FATFS *fs = dp->obj.fs;
  2005. #if _USE_LFN != 0 /* LFN configuration */
  2006. DWORD last = dp->dptr;
  2007. res = (dp->blk_ofs == 0xFFFFFFFF) ? FR_OK : dir_sdi(dp, dp->blk_ofs); /* Goto top of the entry block if LFN is exist */
  2008. if (res == FR_OK) {
  2009. do {
  2010. res = move_window(fs, dp->sect);
  2011. if (res != FR_OK) break;
  2012. /* Mark an entry 'deleted' */
  2013. if (_FS_EXFAT && fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  2014. dp->dir[XDIR_Type] &= 0x7F;
  2015. } else { /* On the FAT12/16/32 volume */
  2016. dp->dir[DIR_Name] = DDEM;
  2017. }
  2018. fs->wflag = 1;
  2019. if (dp->dptr >= last) break; /* If reached last entry then all entries of the object has been deleted. */
  2020. res = dir_next(dp, 0); /* Next entry */
  2021. } while (res == FR_OK);
  2022. if (res == FR_NO_FILE) res = FR_INT_ERR;
  2023. }
  2024. #else /* Non LFN configuration */
  2025. res = move_window(fs, dp->sect);
  2026. if (res == FR_OK) {
  2027. dp->dir[DIR_Name] = DDEM;
  2028. fs->wflag = 1;
  2029. }
  2030. #endif
  2031. return res;
  2032. }
  2033. #endif /* !_FS_READONLY && _FS_MINIMIZE == 0 */
  2034. #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2
  2035. /*-----------------------------------------------------------------------*/
  2036. /* Get file information from directory entry */
  2037. /*-----------------------------------------------------------------------*/
  2038. static
  2039. void get_fileinfo ( /* No return code */
  2040. DIR* dp, /* Pointer to the directory object */
  2041. FILINFO* fno /* Pointer to the file information to be filled */
  2042. )
  2043. {
  2044. UINT i, j;
  2045. TCHAR c;
  2046. DWORD tm;
  2047. #if _USE_LFN != 0
  2048. WCHAR w, lfv;
  2049. FATFS *fs = dp->obj.fs;
  2050. #endif
  2051. fno->fname[0] = 0; /* Invaidate file info */
  2052. if (!dp->sect) return; /* Exit if read pointer has reached end of directory */
  2053. #if _USE_LFN != 0 /* LFN configuration */
  2054. #if _FS_EXFAT
  2055. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  2056. get_xdir_info(fs->dirbuf, fno);
  2057. return;
  2058. } else
  2059. #endif
  2060. { /* On the FAT12/16/32 volume */
  2061. if (dp->blk_ofs != 0xFFFFFFFF) { /* Get LFN if available */
  2062. i = j = 0;
  2063. while ((w = fs->lfnbuf[j++]) != 0) { /* Get an LFN character */
  2064. #if !_LFN_UNICODE
  2065. w = ff_convert(w, 0); /* Unicode -> OEM */
  2066. if (w == 0) { i = 0; break; } /* No LFN if it could not be converted */
  2067. if (_DF1S && w >= 0x100) { /* Put 1st byte if it is a DBC (always false at SBCS cfg) */
  2068. fno->fname[i++] = (char)(w >> 8);
  2069. }
  2070. #endif
  2071. if (i >= _MAX_LFN) { i = 0; break; } /* No LFN if buffer overflow */
  2072. fno->fname[i++] = (TCHAR)w;
  2073. }
  2074. fno->fname[i] = 0; /* Terminate the LFN */
  2075. }
  2076. }
  2077. i = j = 0;
  2078. lfv = fno->fname[i]; /* LFN is exist if non-zero */
  2079. while (i < 11) { /* Copy name body and extension */
  2080. c = (TCHAR)dp->dir[i++];
  2081. if (c == ' ') continue; /* Skip padding spaces */
  2082. if (c == RDDEM) c = (TCHAR)DDEM; /* Restore replaced DDEM character */
  2083. if (i == 9) { /* Insert a . if extension is exist */
  2084. if (!lfv) fno->fname[j] = '.';
  2085. fno->altname[j++] = '.';
  2086. }
  2087. #if _LFN_UNICODE
  2088. if (IsDBCS1(c) && i != 8 && i != 11 && IsDBCS2(dp->dir[i])) {
  2089. c = c << 8 | dp->dir[i++];
  2090. }
  2091. c = ff_convert(c, 1); /* OEM -> Unicode */
  2092. if (!c) c = '?';
  2093. #endif
  2094. fno->altname[j] = c;
  2095. if (!lfv) {
  2096. if (IsUpper(c) && (dp->dir[DIR_NTres] & ((i >= 9) ? NS_EXT : NS_BODY))) {
  2097. c += 0x20; /* To lower */
  2098. }
  2099. fno->fname[j] = c;
  2100. }
  2101. j++;
  2102. }
  2103. if (!lfv) {
  2104. fno->fname[j] = 0;
  2105. if (!dp->dir[DIR_NTres]) j = 0; /* Altname is no longer needed if neither LFN nor case info is exist. */
  2106. }
  2107. fno->altname[j] = 0; /* Terminate the SFN */
  2108. #else /* Non-LFN configuration */
  2109. i = j = 0;
  2110. while (i < 11) { /* Copy name body and extension */
  2111. c = (TCHAR)dp->dir[i++];
  2112. if (c == ' ') continue; /* Skip padding spaces */
  2113. if (c == RDDEM) c = (TCHAR)DDEM; /* Restore replaced DDEM character */
  2114. if (i == 9) fno->fname[j++] = '.'; /* Insert a . if extension is exist */
  2115. fno->fname[j++] = c;
  2116. }
  2117. fno->fname[j] = 0;
  2118. #endif
  2119. fno->fattrib = dp->dir[DIR_Attr]; /* Attribute */
  2120. fno->fsize = ld_dword(dp->dir + DIR_FileSize); /* Size */
  2121. tm = ld_dword(dp->dir + DIR_ModTime); /* Timestamp */
  2122. fno->ftime = (WORD)tm; fno->fdate = (WORD)(tm >> 16);
  2123. }
  2124. #endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */
  2125. #if _USE_FIND && _FS_MINIMIZE <= 1
  2126. /*-----------------------------------------------------------------------*/
  2127. /* Pattern matching */
  2128. /*-----------------------------------------------------------------------*/
  2129. static
  2130. WCHAR get_achar ( /* Get a character and advances ptr 1 or 2 */
  2131. const TCHAR** ptr /* Pointer to pointer to the SBCS/DBCS/Unicode string */
  2132. )
  2133. {
  2134. #if !_LFN_UNICODE
  2135. WCHAR chr;
  2136. chr = (BYTE)*(*ptr)++; /* Get a byte */
  2137. if (IsLower(chr)) chr -= 0x20; /* To upper ASCII char */
  2138. #ifdef _EXCVT
  2139. if (chr >= 0x80) chr = ExCvt[chr - 0x80]; /* To upper SBCS extended char */
  2140. #else
  2141. if (IsDBCS1(chr) && IsDBCS2(**ptr)) { /* Get DBC 2nd byte if needed */
  2142. chr = chr << 8 | (BYTE)*(*ptr)++;
  2143. }
  2144. #endif
  2145. return chr;
  2146. #else
  2147. return ff_wtoupper(*(*ptr)++); /* Get a word and to upper */
  2148. #endif
  2149. }
  2150. static
  2151. int pattern_matching ( /* 0:not matched, 1:matched */
  2152. const TCHAR* pat, /* Matching pattern */
  2153. const TCHAR* nam, /* String to be tested */
  2154. int skip, /* Number of pre-skip chars (number of ?s) */
  2155. int inf /* Infinite search (* specified) */
  2156. )
  2157. {
  2158. const TCHAR *pp, *np;
  2159. WCHAR pc, nc;
  2160. int nm, nx;
  2161. while (skip--) { /* Pre-skip name chars */
  2162. if (!get_achar(&nam)) return 0; /* Branch mismatched if less name chars */
  2163. }
  2164. if (!*pat && inf) return 1; /* (short circuit) */
  2165. do {
  2166. pp = pat; np = nam; /* Top of pattern and name to match */
  2167. for (;;) {
  2168. if (*pp == '?' || *pp == '*') { /* Wildcard? */
  2169. nm = nx = 0;
  2170. do { /* Analyze the wildcard chars */
  2171. if (*pp++ == '?') nm++; else nx = 1;
  2172. } while (*pp == '?' || *pp == '*');
  2173. if (pattern_matching(pp, np, nm, nx)) return 1; /* Test new branch (recurs upto number of wildcard blocks in the pattern) */
  2174. nc = *np; break; /* Branch mismatched */
  2175. }
  2176. pc = get_achar(&pp); /* Get a pattern char */
  2177. nc = get_achar(&np); /* Get a name char */
  2178. if (pc != nc) break; /* Branch mismatched? */
  2179. if (pc == 0) return 1; /* Branch matched? (matched at end of both strings) */
  2180. }
  2181. get_achar(&nam); /* nam++ */
  2182. } while (inf && nc); /* Retry until end of name if infinite search is specified */
  2183. return 0;
  2184. }
  2185. #endif /* _USE_FIND && _FS_MINIMIZE <= 1 */
  2186. /*-----------------------------------------------------------------------*/
  2187. /* Pick a top segment and create the object name in directory form */
  2188. /*-----------------------------------------------------------------------*/
  2189. static
  2190. FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not create */
  2191. DIR* dp, /* Pointer to the directory object */
  2192. const TCHAR** path /* Pointer to pointer to the segment in the path string */
  2193. )
  2194. {
  2195. #if _USE_LFN != 0 /* LFN configuration */
  2196. BYTE b, cf;
  2197. WCHAR w, *lfn;
  2198. UINT i, ni, si, di;
  2199. const TCHAR *p;
  2200. /* Create LFN in Unicode */
  2201. p = *path; lfn = dp->obj.fs->lfnbuf; si = di = 0;
  2202. for (;;) {
  2203. w = p[si++]; /* Get a character */
  2204. if (w < ' ') break; /* Break if end of the path name */
  2205. if (w == '/' || w == '\\') { /* Break if a separator is found */
  2206. while (p[si] == '/' || p[si] == '\\') si++; /* Skip duplicated separator if exist */
  2207. break;
  2208. }
  2209. if (di >= _MAX_LFN) return FR_INVALID_NAME; /* Reject too long name */
  2210. #if !_LFN_UNICODE
  2211. w &= 0xFF;
  2212. if (IsDBCS1(w)) { /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
  2213. b = (BYTE)p[si++]; /* Get 2nd byte */
  2214. w = (w << 8) + b; /* Create a DBC */
  2215. if (!IsDBCS2(b)) return FR_INVALID_NAME; /* Reject invalid sequence */
  2216. }
  2217. w = ff_convert(w, 1); /* Convert ANSI/OEM to Unicode */
  2218. if (!w) return FR_INVALID_NAME; /* Reject invalid code */
  2219. #endif
  2220. if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) return FR_INVALID_NAME; /* Reject illegal characters for LFN */
  2221. lfn[di++] = w; /* Store the Unicode character */
  2222. }
  2223. *path = &p[si]; /* Return pointer to the next segment */
  2224. cf = (w < ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */
  2225. #if _FS_RPATH != 0
  2226. if ((di == 1 && lfn[di - 1] == '.') ||
  2227. (di == 2 && lfn[di - 1] == '.' && lfn[di - 2] == '.')) { /* Is this segment a dot name? */
  2228. lfn[di] = 0;
  2229. for (i = 0; i < 11; i++) /* Create dot name for SFN entry */
  2230. dp->fn[i] = (i < di) ? '.' : ' ';
  2231. dp->fn[i] = cf | NS_DOT; /* This is a dot entry */
  2232. return FR_OK;
  2233. }
  2234. #endif
  2235. while (di) { /* Snip off trailing spaces and dots if exist */
  2236. w = lfn[di - 1];
  2237. if (w != ' ' && w != '.') break;
  2238. di--;
  2239. }
  2240. lfn[di] = 0; /* LFN is created */
  2241. if (di == 0) return FR_INVALID_NAME; /* Reject nul name */
  2242. /* Create SFN in directory form */
  2243. mem_set(dp->fn, ' ', 11);
  2244. for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ; /* Strip leading spaces and dots */
  2245. if (si) cf |= NS_LOSS | NS_LFN;
  2246. while (di && lfn[di - 1] != '.') di--; /* Find extension (di<=si: no extension) */
  2247. i = b = 0; ni = 8;
  2248. for (;;) {
  2249. w = lfn[si++]; /* Get an LFN character */
  2250. if (!w) break; /* Break on end of the LFN */
  2251. if (w == ' ' || (w == '.' && si != di)) { /* Remove spaces and dots */
  2252. cf |= NS_LOSS | NS_LFN; continue;
  2253. }
  2254. if (i >= ni || si == di) { /* Extension or end of SFN */
  2255. if (ni == 11) { /* Long extension */
  2256. cf |= NS_LOSS | NS_LFN; break;
  2257. }
  2258. if (si != di) cf |= NS_LOSS | NS_LFN; /* Out of 8.3 format */
  2259. if (si > di) break; /* No extension */
  2260. si = di; i = 8; ni = 11; /* Enter extension section */
  2261. b <<= 2; continue;
  2262. }
  2263. if (w >= 0x80) { /* Non ASCII character */
  2264. #ifdef _EXCVT
  2265. w = ff_convert(w, 0); /* Unicode -> OEM code */
  2266. if (w) w = ExCvt[w - 0x80]; /* Convert extended character to upper (SBCS) */
  2267. #else
  2268. w = ff_convert(ff_wtoupper(w), 0); /* Upper converted Unicode -> OEM code */
  2269. #endif
  2270. cf |= NS_LFN; /* Force create LFN entry */
  2271. }
  2272. if (_DF1S && w >= 0x100) { /* Is this DBC? (always false at SBCS cfg) */
  2273. if (i >= ni - 1) {
  2274. cf |= NS_LOSS | NS_LFN; i = ni; continue;
  2275. }
  2276. dp->fn[i++] = (BYTE)(w >> 8);
  2277. } else { /* SBC */
  2278. if (!w || chk_chr("+,;=[]", w)) { /* Replace illegal characters for SFN */
  2279. w = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */
  2280. } else {
  2281. if (IsUpper(w)) { /* ASCII large capital */
  2282. b |= 2;
  2283. } else {
  2284. if (IsLower(w)) { /* ASCII small capital */
  2285. b |= 1; w -= 0x20;
  2286. }
  2287. }
  2288. }
  2289. }
  2290. dp->fn[i++] = (BYTE)w;
  2291. }
  2292. if (dp->fn[0] == DDEM) dp->fn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */
  2293. if (ni == 8) b <<= 2;
  2294. if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03) cf |= NS_LFN; /* Create LFN entry when there are composite capitals */
  2295. if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended character, NT flags are created */
  2296. if ((b & 0x03) == 0x01) cf |= NS_EXT; /* NT flag (Extension has only small capital) */
  2297. if ((b & 0x0C) == 0x04) cf |= NS_BODY; /* NT flag (Filename has only small capital) */
  2298. }
  2299. dp->fn[NSFLAG] = cf; /* SFN is created */
  2300. return FR_OK;
  2301. #else /* _USE_LFN != 0 : Non-LFN configuration */
  2302. BYTE c, d, *sfn;
  2303. UINT ni, si, i;
  2304. const char *p;
  2305. /* Create file name in directory form */
  2306. p = *path; sfn = dp->fn;
  2307. mem_set(sfn, ' ', 11);
  2308. si = i = 0; ni = 8;
  2309. #if _FS_RPATH != 0
  2310. if (p[si] == '.') { /* Is this a dot entry? */
  2311. for (;;) {
  2312. c = (BYTE)p[si++];
  2313. if (c != '.' || si >= 3) break;
  2314. sfn[i++] = c;
  2315. }
  2316. if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME;
  2317. *path = p + si; /* Return pointer to the next segment */
  2318. sfn[NSFLAG] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT; /* Set last segment flag if end of the path */
  2319. return FR_OK;
  2320. }
  2321. #endif
  2322. for (;;) {
  2323. c = (BYTE)p[si++];
  2324. if (c <= ' ') break; /* Break if end of the path name */
  2325. if (c == '/' || c == '\\') { /* Break if a separator is found */
  2326. while (p[si] == '/' || p[si] == '\\') si++; /* Skip duplicated separator if exist */
  2327. break;
  2328. }
  2329. if (c == '.' || i >= ni) { /* End of body or over size? */
  2330. if (ni == 11 || c != '.') return FR_INVALID_NAME; /* Over size or invalid dot */
  2331. i = 8; ni = 11; /* Goto extension */
  2332. continue;
  2333. }
  2334. if (c >= 0x80) { /* Extended character? */
  2335. #ifdef _EXCVT
  2336. c = ExCvt[c - 0x80]; /* To upper extended characters (SBCS cfg) */
  2337. #else
  2338. #if !_DF1S
  2339. return FR_INVALID_NAME; /* Reject extended characters (ASCII only cfg) */
  2340. #endif
  2341. #endif
  2342. }
  2343. if (IsDBCS1(c)) { /* Check if it is a DBC 1st byte (always false at SBCS cfg.) */
  2344. d = (BYTE)p[si++]; /* Get 2nd byte */
  2345. if (!IsDBCS2(d) || i >= ni - 1) return FR_INVALID_NAME; /* Reject invalid DBC */
  2346. sfn[i++] = c;
  2347. sfn[i++] = d;
  2348. } else { /* SBC */
  2349. if (chk_chr("\"*+,:;<=>\?[]|\x7F", c)) return FR_INVALID_NAME; /* Reject illegal chrs for SFN */
  2350. if (IsLower(c)) c -= 0x20; /* To upper */
  2351. sfn[i++] = c;
  2352. }
  2353. }
  2354. *path = p + si; /* Return pointer to the next segment */
  2355. if (i == 0) return FR_INVALID_NAME; /* Reject nul string */
  2356. if (sfn[0] == DDEM) sfn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */
  2357. sfn[NSFLAG] = (c <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */
  2358. return FR_OK;
  2359. #endif /* _USE_LFN != 0 */
  2360. }
  2361. /*-----------------------------------------------------------------------*/
  2362. /* Follow a file path */
  2363. /*-----------------------------------------------------------------------*/
  2364. static
  2365. FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */
  2366. DIR* dp, /* Directory object to return last directory and found object */
  2367. const TCHAR* path /* Full-path string to find a file or directory */
  2368. )
  2369. {
  2370. FRESULT res;
  2371. BYTE ns;
  2372. _FDID *obj = &dp->obj;
  2373. FATFS *fs = obj->fs;
  2374. #if _FS_RPATH != 0
  2375. if (*path != '/' && *path != '\\') { /* Without heading separator */
  2376. obj->sclust = fs->cdir; /* Start from current directory */
  2377. } else
  2378. #endif
  2379. { /* With heading separator */
  2380. while (*path == '/' || *path == '\\') path++; /* Strip heading separator */
  2381. obj->sclust = 0; /* Start from root directory */
  2382. }
  2383. #if _FS_EXFAT
  2384. obj->n_frag = 0; /* Invalidate last fragment counter of the object */
  2385. #if _FS_RPATH != 0
  2386. if (fs->fs_type == FS_EXFAT && obj->sclust) { /* Retrieve the sub-directory status if needed */
  2387. DIR dj;
  2388. obj->c_scl = fs->cdc_scl;
  2389. obj->c_size = fs->cdc_size;
  2390. obj->c_ofs = fs->cdc_ofs;
  2391. res = load_obj_dir(&dj, obj);
  2392. if (res != FR_OK) return res;
  2393. obj->objsize = ld_dword(fs->dirbuf + XDIR_FileSize);
  2394. obj->stat = fs->dirbuf[XDIR_GenFlags] & 2;
  2395. }
  2396. #endif
  2397. #endif
  2398. if ((UINT)*path < ' ') { /* Null path name is the origin directory itself */
  2399. dp->fn[NSFLAG] = NS_NONAME;
  2400. res = dir_sdi(dp, 0);
  2401. } else { /* Follow path */
  2402. for (;;) {
  2403. res = create_name(dp, &path); /* Get a segment name of the path */
  2404. if (res != FR_OK) break;
  2405. res = dir_find(dp); /* Find an object with the segment name */
  2406. ns = dp->fn[NSFLAG];
  2407. if (res != FR_OK) { /* Failed to find the object */
  2408. if (res == FR_NO_FILE) { /* Object is not found */
  2409. if (_FS_RPATH && (ns & NS_DOT)) { /* If dot entry is not exist, stay there */
  2410. if (!(ns & NS_LAST)) continue; /* Continue to follow if not last segment */
  2411. dp->fn[NSFLAG] = NS_NONAME;
  2412. res = FR_OK;
  2413. } else { /* Could not find the object */
  2414. if (!(ns & NS_LAST)) res = FR_NO_PATH; /* Adjust error code if not last segment */
  2415. }
  2416. }
  2417. break;
  2418. }
  2419. if (ns & NS_LAST) break; /* Last segment matched. Function completed. */
  2420. /* Get into the sub-directory */
  2421. if (!(obj->attr & AM_DIR)) { /* It is not a sub-directory and cannot follow */
  2422. res = FR_NO_PATH; break;
  2423. }
  2424. #if _FS_EXFAT
  2425. if (fs->fs_type == FS_EXFAT) { /* Save containing directory information for next dir */
  2426. obj->c_scl = obj->sclust;
  2427. obj->c_size = ((DWORD)obj->objsize & 0xFFFFFF00) | obj->stat;
  2428. obj->c_ofs = dp->blk_ofs;
  2429. obj->sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Open next directory */
  2430. obj->stat = fs->dirbuf[XDIR_GenFlags] & 2;
  2431. obj->objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  2432. } else
  2433. #endif
  2434. {
  2435. obj->sclust = ld_clust(fs, fs->win + dp->dptr % SS(fs)); /* Open next directory */
  2436. }
  2437. }
  2438. }
  2439. return res;
  2440. }
  2441. /*-----------------------------------------------------------------------*/
  2442. /* Get logical drive number from path name */
  2443. /*-----------------------------------------------------------------------*/
  2444. static
  2445. int get_ldnumber ( /* Returns logical drive number (-1:invalid drive) */
  2446. const TCHAR** path /* Pointer to pointer to the path name */
  2447. )
  2448. {
  2449. const TCHAR *tp, *tt;
  2450. UINT i;
  2451. int vol = -1;
  2452. #if _STR_VOLUME_ID /* Find string drive id */
  2453. static const char* const volid[] = {_VOLUME_STRS};
  2454. const char *sp;
  2455. char c;
  2456. TCHAR tc;
  2457. #endif
  2458. if (*path) { /* If the pointer is not a null */
  2459. for (tt = *path; (UINT)*tt >= (_USE_LFN ? ' ' : '!') && *tt != ':'; tt++) ; /* Find ':' in the path */
  2460. if (*tt == ':') { /* If a ':' is exist in the path name */
  2461. tp = *path;
  2462. i = *tp++ - '0';
  2463. if (i < 10 && tp == tt) { /* Is there a numeric drive id? */
  2464. if (i < _VOLUMES) { /* If a drive id is found, get the value and strip it */
  2465. vol = (int)i;
  2466. *path = ++tt;
  2467. }
  2468. }
  2469. #if _STR_VOLUME_ID
  2470. else { /* No numeric drive number, find string drive id */
  2471. i = 0; tt++;
  2472. do {
  2473. sp = volid[i]; tp = *path;
  2474. do { /* Compare a string drive id with path name */
  2475. c = *sp++; tc = *tp++;
  2476. if (IsLower(tc)) tc -= 0x20;
  2477. } while (c && (TCHAR)c == tc);
  2478. } while ((c || tp != tt) && ++i < _VOLUMES); /* Repeat for each id until pattern match */
  2479. if (i < _VOLUMES) { /* If a drive id is found, get the value and strip it */
  2480. vol = (int)i;
  2481. *path = tt;
  2482. }
  2483. }
  2484. #endif
  2485. return vol;
  2486. }
  2487. #if _FS_RPATH != 0 && _VOLUMES >= 2
  2488. vol = CurrVol; /* Current drive */
  2489. #else
  2490. vol = 0; /* Drive 0 */
  2491. #endif
  2492. }
  2493. return vol;
  2494. }
  2495. /*-----------------------------------------------------------------------*/
  2496. /* Load a sector and check if it is an FAT boot sector */
  2497. /*-----------------------------------------------------------------------*/
  2498. static
  2499. BYTE check_fs ( /* 0:FAT, 1:exFAT, 2:Valid BS but not FAT, 3:Not a BS, 4:Disk error */
  2500. FATFS* fs, /* File system object */
  2501. DWORD sect /* Sector# (lba) to load and check if it is an FAT-VBR or not */
  2502. )
  2503. {
  2504. fs->wflag = 0; fs->winsect = 0xFFFFFFFF; /* Invaidate window */
  2505. if (move_window(fs, sect) != FR_OK) return 4; /* Load boot record */
  2506. if (ld_word(fs->win + BS_55AA) != 0xAA55) return 3; /* Check boot record signature (always placed here even if the sector size is >512) */
  2507. if (fs->win[BS_JmpBoot] == 0xE9 || (fs->win[BS_JmpBoot] == 0xEB && fs->win[BS_JmpBoot + 2] == 0x90)) {
  2508. if ((ld_dword(fs->win + BS_FilSysType) & 0xFFFFFF) == 0x544146) return 0; /* Check "FAT" string */
  2509. if (ld_dword(fs->win + BS_FilSysType32) == 0x33544146) return 0; /* Check "FAT3" string */
  2510. }
  2511. #if _FS_EXFAT
  2512. if (!mem_cmp(fs->win + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11)) return 1;
  2513. #endif
  2514. return 2;
  2515. }
  2516. /*-----------------------------------------------------------------------*/
  2517. /* Find logical drive and check if the volume is mounted */
  2518. /*-----------------------------------------------------------------------*/
  2519. static
  2520. FRESULT find_volume ( /* FR_OK(0): successful, !=0: any error occurred */
  2521. const TCHAR** path, /* Pointer to pointer to the path name (drive number) */
  2522. FATFS** rfs, /* Pointer to pointer to the found file system object */
  2523. BYTE mode /* !=0: Check write protection for write access */
  2524. )
  2525. {
  2526. BYTE fmt, *pt;
  2527. int vol;
  2528. DSTATUS stat;
  2529. DWORD bsect, fasize, tsect, sysect, nclst, szbfat, br[4];
  2530. WORD nrsv;
  2531. FATFS *fs;
  2532. UINT i;
  2533. /* Get logical drive number */
  2534. *rfs = 0;
  2535. vol = get_ldnumber(path);
  2536. if (vol < 0) return FR_INVALID_DRIVE;
  2537. /* Check if the file system object is valid or not */
  2538. fs = FatFs[vol]; /* Get pointer to the file system object */
  2539. if (!fs) return FR_NOT_ENABLED; /* Is the file system object available? */
  2540. ENTER_FF(fs); /* Lock the volume */
  2541. *rfs = fs; /* Return pointer to the file system object */
  2542. mode &= (BYTE)~FA_READ; /* Desired access mode, write access or not */
  2543. if (fs->fs_type) { /* If the volume has been mounted */
  2544. stat = disk_status(fs->drv);
  2545. if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized */
  2546. if (!_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check write protection if needed */
  2547. return FR_WRITE_PROTECTED;
  2548. }
  2549. return FR_OK; /* The file system object is valid */
  2550. }
  2551. }
  2552. /* The file system object is not valid. */
  2553. /* Following code attempts to mount the volume. (analyze BPB and initialize the fs object) */
  2554. fs->fs_type = 0; /* Clear the file system object */
  2555. fs->drv = LD2PD(vol); /* Bind the logical drive and a physical drive */
  2556. stat = disk_initialize(fs->drv); /* Initialize the physical drive */
  2557. if (stat & STA_NOINIT) { /* Check if the initialization succeeded */
  2558. return FR_NOT_READY; /* Failed to initialize due to no medium or hard error */
  2559. }
  2560. if (!_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check disk write protection if needed */
  2561. return FR_WRITE_PROTECTED;
  2562. }
  2563. #if _MAX_SS != _MIN_SS /* Get sector size (multiple sector size cfg only) */
  2564. if (disk_ioctl(fs->drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK) return FR_DISK_ERR;
  2565. if (SS(fs) > _MAX_SS || SS(fs) < _MIN_SS || (SS(fs) & (SS(fs) - 1))) return FR_DISK_ERR;
  2566. #endif
  2567. /* Find an FAT partition on the drive. Supports only generic partitioning rules, FDISK and SFD. */
  2568. bsect = 0;
  2569. fmt = check_fs(fs, bsect); /* Load sector 0 and check if it is an FAT-VBR as SFD */
  2570. if (fmt == 2 || (fmt < 2 && LD2PT(vol) != 0)) { /* Not an FAT-VBR or forced partition number */
  2571. for (i = 0; i < 4; i++) { /* Get partition offset */
  2572. pt = fs->win + (MBR_Table + i * SZ_PTE);
  2573. br[i] = pt[PTE_System] ? ld_dword(pt + PTE_StLba) : 0;
  2574. }
  2575. i = LD2PT(vol); /* Partition number: 0:auto, 1-4:forced */
  2576. if (i) i--;
  2577. do { /* Find an FAT volume */
  2578. bsect = br[i];
  2579. fmt = bsect ? check_fs(fs, bsect) : 3; /* Check the partition */
  2580. } while (LD2PT(vol) == 0 && fmt >= 2 && ++i < 4);
  2581. }
  2582. if (fmt == 4) return FR_DISK_ERR; /* An error occured in the disk I/O layer */
  2583. if (fmt >= 2) return FR_NO_FILESYSTEM; /* No FAT volume is found */
  2584. /* An FAT volume is found (bsect). Following code initializes the file system object */
  2585. #if _FS_EXFAT
  2586. if (fmt == 1) {
  2587. QWORD maxlba;
  2588. for (i = BPB_ZeroedEx; i < BPB_ZeroedEx + 53 && fs->win[i] == 0; i++) ; /* Check zero filler */
  2589. if (i < BPB_ZeroedEx + 53) return FR_NO_FILESYSTEM;
  2590. if (ld_word(fs->win + BPB_FSVerEx) != 0x100) return FR_NO_FILESYSTEM; /* Check exFAT revision (Must be 1.0) */
  2591. if (1 << fs->win[BPB_BytsPerSecEx] != SS(fs)) { /* (BPB_BytsPerSecEx must be equal to the physical sector size) */
  2592. return FR_NO_FILESYSTEM;
  2593. }
  2594. maxlba = ld_qword(fs->win + BPB_TotSecEx) + bsect; /* Last LBA + 1 of the volume */
  2595. if (maxlba >= 0x100000000) return FR_NO_FILESYSTEM; /* (It cannot be handled in 32-bit LBA) */
  2596. fs->fsize = ld_dword(fs->win + BPB_FatSzEx); /* Number of sectors per FAT */
  2597. fs->n_fats = fs->win[BPB_NumFATsEx]; /* Number of FATs */
  2598. if (fs->n_fats != 1) return FR_NO_FILESYSTEM; /* (Supports only 1 FAT) */
  2599. fs->csize = 1 << fs->win[BPB_SecPerClusEx]; /* Cluster size */
  2600. if (fs->csize == 0) return FR_NO_FILESYSTEM; /* (Must be 1..32768) */
  2601. nclst = ld_dword(fs->win + BPB_NumClusEx); /* Number of clusters */
  2602. if (nclst > MAX_EXFAT) return FR_NO_FILESYSTEM; /* (Too many clusters) */
  2603. fs->n_fatent = nclst + 2;
  2604. /* Boundaries and Limits */
  2605. fs->volbase = bsect;
  2606. fs->database = bsect + ld_dword(fs->win + BPB_DataOfsEx);
  2607. fs->fatbase = bsect + ld_dword(fs->win + BPB_FatOfsEx);
  2608. if (maxlba < (QWORD)fs->database + nclst * fs->csize) return FR_NO_FILESYSTEM; /* (Volume size must not be smaller than the size requiered) */
  2609. fs->dirbase = ld_dword(fs->win + BPB_RootClusEx);
  2610. /* Check if bitmap location is in assumption (at the first cluster) */
  2611. if (move_window(fs, clust2sect(fs, fs->dirbase)) != FR_OK) return FR_DISK_ERR;
  2612. for (i = 0; i < SS(fs); i += SZDIRE) {
  2613. if (fs->win[i] == 0x81 && ld_dword(fs->win + i + 20) == 2) break; /* 81 entry with cluster #2? */
  2614. }
  2615. if (i == SS(fs)) return FR_NO_FILESYSTEM;
  2616. #if !_FS_READONLY
  2617. fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Initialize cluster allocation information */
  2618. #endif
  2619. fmt = FS_EXFAT; /* FAT sub-type */
  2620. } else
  2621. #endif /* _FS_EXFAT */
  2622. {
  2623. if (ld_word(fs->win + BPB_BytsPerSec) != SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_BytsPerSec must be equal to the physical sector size) */
  2624. fasize = ld_word(fs->win + BPB_FATSz16); /* Number of sectors per FAT */
  2625. if (fasize == 0) fasize = ld_dword(fs->win + BPB_FATSz32);
  2626. fs->fsize = fasize;
  2627. fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FATs */
  2628. if (fs->n_fats != 1 && fs->n_fats != 2) return FR_NO_FILESYSTEM; /* (Must be 1 or 2) */
  2629. fasize *= fs->n_fats; /* Number of sectors for FAT area */
  2630. fs->csize = fs->win[BPB_SecPerClus]; /* Cluster size */
  2631. if (fs->csize == 0 || (fs->csize & (fs->csize - 1))) return FR_NO_FILESYSTEM; /* (Must be power of 2) */
  2632. fs->n_rootdir = ld_word(fs->win + BPB_RootEntCnt); /* Number of root directory entries */
  2633. if (fs->n_rootdir % (SS(fs) / SZDIRE)) return FR_NO_FILESYSTEM; /* (Must be sector aligned) */
  2634. tsect = ld_word(fs->win + BPB_TotSec16); /* Number of sectors on the volume */
  2635. if (tsect == 0) tsect = ld_dword(fs->win + BPB_TotSec32);
  2636. nrsv = ld_word(fs->win + BPB_RsvdSecCnt); /* Number of reserved sectors */
  2637. if (nrsv == 0) return FR_NO_FILESYSTEM; /* (Must not be 0) */
  2638. /* Determine the FAT sub type */
  2639. sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZDIRE); /* RSV + FAT + DIR */
  2640. if (tsect < sysect) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  2641. nclst = (tsect - sysect) / fs->csize; /* Number of clusters */
  2642. if (nclst == 0) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  2643. fmt = FS_FAT32;
  2644. if (nclst <= MAX_FAT16) fmt = FS_FAT16;
  2645. if (nclst <= MAX_FAT12) fmt = FS_FAT12;
  2646. /* Boundaries and Limits */
  2647. fs->n_fatent = nclst + 2; /* Number of FAT entries */
  2648. fs->volbase = bsect; /* Volume start sector */
  2649. fs->fatbase = bsect + nrsv; /* FAT start sector */
  2650. fs->database = bsect + sysect; /* Data start sector */
  2651. if (fmt == FS_FAT32) {
  2652. if (ld_word(fs->win + BPB_FSVer32) != 0) return FR_NO_FILESYSTEM; /* (Must be FAT32 revision 0.0) */
  2653. if (fs->n_rootdir) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be 0) */
  2654. fs->dirbase = ld_dword(fs->win + BPB_RootClus32); /* Root directory start cluster */
  2655. szbfat = fs->n_fatent * 4; /* (Needed FAT size) */
  2656. } else {
  2657. if (fs->n_rootdir == 0) return FR_NO_FILESYSTEM;/* (BPB_RootEntCnt must not be 0) */
  2658. fs->dirbase = fs->fatbase + fasize; /* Root directory start sector */
  2659. szbfat = (fmt == FS_FAT16) ? /* (Needed FAT size) */
  2660. fs->n_fatent * 2 : fs->n_fatent * 3 / 2 + (fs->n_fatent & 1);
  2661. }
  2662. if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_FATSz must not be less than the size needed) */
  2663. #if !_FS_READONLY
  2664. /* Get FSINFO if available */
  2665. fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Initialize cluster allocation information */
  2666. fs->fsi_flag = 0x80;
  2667. #if (_FS_NOFSINFO & 3) != 3
  2668. if (fmt == FS_FAT32 /* Enable FSINFO only if FAT32 and BPB_FSInfo32 == 1 */
  2669. && ld_word(fs->win + BPB_FSInfo32) == 1
  2670. && move_window(fs, bsect + 1) == FR_OK)
  2671. {
  2672. fs->fsi_flag = 0;
  2673. if (ld_word(fs->win + BS_55AA) == 0xAA55 /* Load FSINFO data if available */
  2674. && ld_dword(fs->win + FSI_LeadSig) == 0x41615252
  2675. && ld_dword(fs->win + FSI_StrucSig) == 0x61417272)
  2676. {
  2677. #if (_FS_NOFSINFO & 1) == 0
  2678. fs->free_clst = ld_dword(fs->win + FSI_Free_Count);
  2679. #endif
  2680. #if (_FS_NOFSINFO & 2) == 0
  2681. fs->last_clst = ld_dword(fs->win + FSI_Nxt_Free);
  2682. #endif
  2683. }
  2684. }
  2685. #endif /* (_FS_NOFSINFO & 3) != 3 */
  2686. #endif /* !_FS_READONLY */
  2687. }
  2688. fs->fs_type = fmt; /* FAT sub-type */
  2689. fs->id = ++Fsid; /* File system mount ID */
  2690. #if _USE_LFN == 1
  2691. fs->lfnbuf = LfnBuf; /* Static LFN working buffer */
  2692. #if _FS_EXFAT
  2693. fs->dirbuf = DirBuf; /* Static directory block scratchpad buuffer */
  2694. #endif
  2695. #endif
  2696. #if _FS_RPATH != 0
  2697. fs->cdir = 0; /* Initialize current directory */
  2698. #endif
  2699. #if _FS_LOCK != 0 /* Clear file lock semaphores */
  2700. clear_lock(fs);
  2701. #endif
  2702. return FR_OK;
  2703. }
  2704. /*-----------------------------------------------------------------------*/
  2705. /* Check if the file/directory object is valid or not */
  2706. /*-----------------------------------------------------------------------*/
  2707. static
  2708. FRESULT validate ( /* Returns FR_OK or FR_INVALID_OBJECT */
  2709. _FDID* obj, /* Pointer to the _OBJ, the 1st member in the FIL/DIR object, to check validity */
  2710. FATFS** fs /* Pointer to pointer to the owner file system object to return */
  2711. )
  2712. {
  2713. FRESULT res = FR_INVALID_OBJECT;
  2714. if (obj && obj->fs && obj->fs->fs_type && obj->id == obj->fs->id) { /* Test if the object is valid */
  2715. #if _FS_REENTRANT
  2716. if (lock_fs(obj->fs)) { /* Obtain the filesystem object */
  2717. if (!(disk_status(obj->fs->drv) & STA_NOINIT)) { /* Test if the phsical drive is kept initialized */
  2718. res = FR_OK;
  2719. } else {
  2720. unlock_fs(obj->fs, FR_OK);
  2721. }
  2722. } else {
  2723. res = FR_TIMEOUT;
  2724. }
  2725. #else
  2726. if (!(disk_status(obj->fs->drv) & STA_NOINIT)) { /* Test if the phsical drive is kept initialized */
  2727. res = FR_OK;
  2728. }
  2729. #endif
  2730. }
  2731. *fs = (res == FR_OK) ? obj->fs : 0; /* Corresponding filesystem object */
  2732. return res;
  2733. }
  2734. /*---------------------------------------------------------------------------
  2735. Public Functions (FatFs API)
  2736. ----------------------------------------------------------------------------*/
  2737. /*-----------------------------------------------------------------------*/
  2738. /* Mount/Unmount a Logical Drive */
  2739. /*-----------------------------------------------------------------------*/
  2740. FRESULT f_mount (
  2741. FATFS* fs, /* Pointer to the file system object (NULL:unmount)*/
  2742. const TCHAR* path, /* Logical drive number to be mounted/unmounted */
  2743. BYTE opt /* Mode option 0:Do not mount (delayed mount), 1:Mount immediately */
  2744. )
  2745. {
  2746. FATFS *cfs;
  2747. int vol;
  2748. FRESULT res;
  2749. const TCHAR *rp = path;
  2750. /* Get logical drive number */
  2751. vol = get_ldnumber(&rp);
  2752. if (vol < 0) return FR_INVALID_DRIVE;
  2753. cfs = FatFs[vol]; /* Pointer to fs object */
  2754. if (cfs) {
  2755. #if _FS_LOCK != 0
  2756. clear_lock(cfs);
  2757. #endif
  2758. #if _FS_REENTRANT /* Discard sync object of the current volume */
  2759. if (!ff_del_syncobj(cfs->sobj)) return FR_INT_ERR;
  2760. #endif
  2761. cfs->fs_type = 0; /* Clear old fs object */
  2762. }
  2763. if (fs) {
  2764. fs->fs_type = 0; /* Clear new fs object */
  2765. #if _FS_REENTRANT /* Create sync object for the new volume */
  2766. if (!ff_cre_syncobj((BYTE)vol, &fs->sobj)) return FR_INT_ERR;
  2767. #endif
  2768. }
  2769. FatFs[vol] = fs; /* Register new fs object */
  2770. if (!fs || opt != 1) return FR_OK; /* Do not mount now, it will be mounted later */
  2771. res = find_volume(&path, &fs, 0); /* Force mounted the volume */
  2772. LEAVE_FF(fs, res);
  2773. }
  2774. /*-----------------------------------------------------------------------*/
  2775. /* Open or Create a File */
  2776. /*-----------------------------------------------------------------------*/
  2777. FRESULT f_open (
  2778. FIL* fp, /* Pointer to the blank file object */
  2779. const TCHAR* path, /* Pointer to the file name */
  2780. BYTE mode /* Access mode and file open mode flags */
  2781. )
  2782. {
  2783. FRESULT res;
  2784. DIR dj;
  2785. FATFS *fs;
  2786. #if !_FS_READONLY
  2787. DWORD dw, cl, bcs, clst, sc;
  2788. FSIZE_t ofs;
  2789. #endif
  2790. DEF_NAMBUF
  2791. if (!fp) return FR_INVALID_OBJECT;
  2792. /* Get logical drive */
  2793. mode &= _FS_READONLY ? FA_READ : FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_CREATE_NEW | FA_OPEN_ALWAYS | FA_OPEN_APPEND | FA_SEEKEND;
  2794. res = find_volume(&path, &fs, mode);
  2795. if (res == FR_OK) {
  2796. dj.obj.fs = fs;
  2797. INIT_NAMBUF(fs);
  2798. res = follow_path(&dj, path); /* Follow the file path */
  2799. #if !_FS_READONLY /* R/W configuration */
  2800. if (res == FR_OK) {
  2801. if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */
  2802. res = FR_INVALID_NAME;
  2803. }
  2804. #if _FS_LOCK != 0
  2805. else {
  2806. res = chk_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
  2807. }
  2808. #endif
  2809. }
  2810. /* Create or Open a file */
  2811. if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
  2812. if (res != FR_OK) { /* No file, create new */
  2813. if (res == FR_NO_FILE) { /* There is no file to open, create a new entry */
  2814. #if _FS_LOCK != 0
  2815. res = enq_lock() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;
  2816. #else
  2817. res = dir_register(&dj);
  2818. #endif
  2819. }
  2820. mode |= FA_CREATE_ALWAYS; /* File is created */
  2821. }
  2822. else { /* Any object is already existing */
  2823. if (dj.obj.attr & (AM_RDO | AM_DIR)) { /* Cannot overwrite it (R/O or DIR) */
  2824. res = FR_DENIED;
  2825. } else {
  2826. if (mode & FA_CREATE_NEW) res = FR_EXIST; /* Cannot create as new file */
  2827. }
  2828. }
  2829. if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) { /* Truncate it if overwrite mode */
  2830. dw = GET_FATTIME();
  2831. #if _FS_EXFAT
  2832. if (fs->fs_type == FS_EXFAT) {
  2833. /* Get current allocation info */
  2834. fp->obj.fs = fs;
  2835. fp->obj.sclust = ld_dword(fs->dirbuf + XDIR_FstClus);
  2836. fp->obj.objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  2837. fp->obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
  2838. fp->obj.n_frag = 0;
  2839. /* Initialize directory entry block */
  2840. st_dword(fs->dirbuf + XDIR_CrtTime, dw); /* Set created time */
  2841. fs->dirbuf[XDIR_CrtTime10] = 0;
  2842. st_dword(fs->dirbuf + XDIR_ModTime, dw); /* Set modified time */
  2843. fs->dirbuf[XDIR_ModTime10] = 0;
  2844. fs->dirbuf[XDIR_Attr] = AM_ARC; /* Reset attribute */
  2845. st_dword(fs->dirbuf + XDIR_FstClus, 0); /* Reset file allocation info */
  2846. st_qword(fs->dirbuf + XDIR_FileSize, 0);
  2847. st_qword(fs->dirbuf + XDIR_ValidFileSize, 0);
  2848. fs->dirbuf[XDIR_GenFlags] = 1;
  2849. res = store_xdir(&dj);
  2850. if (res == FR_OK && fp->obj.sclust) { /* Remove the cluster chain if exist */
  2851. res = remove_chain(&fp->obj, fp->obj.sclust, 0);
  2852. fs->last_clst = fp->obj.sclust - 1; /* Reuse the cluster hole */
  2853. }
  2854. } else
  2855. #endif
  2856. {
  2857. /* Clean directory info */
  2858. st_dword(dj.dir + DIR_CrtTime, dw); /* Set created time */
  2859. st_dword(dj.dir + DIR_ModTime, dw); /* Set modified time */
  2860. dj.dir[DIR_Attr] = AM_ARC; /* Reset attribute */
  2861. cl = ld_clust(fs, dj.dir); /* Get cluster chain */
  2862. st_clust(fs, dj.dir, 0); /* Reset file allocation info */
  2863. st_dword(dj.dir + DIR_FileSize, 0);
  2864. fs->wflag = 1;
  2865. if (cl) { /* Remove the cluster chain if exist */
  2866. dw = fs->winsect;
  2867. res = remove_chain(&dj.obj, cl, 0);
  2868. if (res == FR_OK) {
  2869. res = move_window(fs, dw);
  2870. fs->last_clst = cl - 1; /* Reuse the cluster hole */
  2871. }
  2872. }
  2873. }
  2874. }
  2875. }
  2876. else { /* Open an existing file */
  2877. if (res == FR_OK) { /* Following succeeded */
  2878. if (dj.obj.attr & AM_DIR) { /* It is a directory */
  2879. res = FR_NO_FILE;
  2880. } else {
  2881. if ((mode & FA_WRITE) && (dj.obj.attr & AM_RDO)) { /* R/O violation */
  2882. res = FR_DENIED;
  2883. }
  2884. }
  2885. }
  2886. }
  2887. if (res == FR_OK) {
  2888. if (mode & FA_CREATE_ALWAYS) /* Set file change flag if created or overwritten */
  2889. mode |= FA_MODIFIED;
  2890. fp->dir_sect = fs->winsect; /* Pointer to the directory entry */
  2891. fp->dir_ptr = dj.dir;
  2892. #if _FS_LOCK != 0
  2893. fp->obj.lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
  2894. if (!fp->obj.lockid) res = FR_INT_ERR;
  2895. #endif
  2896. }
  2897. #else /* R/O configuration */
  2898. if (res == FR_OK) {
  2899. if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */
  2900. res = FR_INVALID_NAME;
  2901. } else {
  2902. if (dj.obj.attr & AM_DIR) { /* It is a directory */
  2903. res = FR_NO_FILE;
  2904. }
  2905. }
  2906. }
  2907. #endif
  2908. if (res == FR_OK) {
  2909. #if _FS_EXFAT
  2910. if (fs->fs_type == FS_EXFAT) {
  2911. fp->obj.c_scl = dj.obj.sclust; /* Get containing directory info */
  2912. fp->obj.c_size = ((DWORD)dj.obj.objsize & 0xFFFFFF00) | dj.obj.stat;
  2913. fp->obj.c_ofs = dj.blk_ofs;
  2914. fp->obj.sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Get object allocation info */
  2915. fp->obj.objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  2916. fp->obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
  2917. } else
  2918. #endif
  2919. {
  2920. fp->obj.sclust = ld_clust(fs, dj.dir); /* Get object allocation info */
  2921. fp->obj.objsize = ld_dword(dj.dir + DIR_FileSize);
  2922. }
  2923. #if _USE_FASTSEEK
  2924. fp->cltbl = 0; /* Disable fast seek mode */
  2925. #endif
  2926. fp->obj.fs = fs; /* Validate the file object */
  2927. fp->obj.id = fs->id;
  2928. fp->flag = mode; /* Set file access mode */
  2929. fp->err = 0; /* Clear error flag */
  2930. fp->sect = 0; /* Invalidate current data sector */
  2931. fp->fptr = 0; /* Set file pointer top of the file */
  2932. #if !_FS_READONLY
  2933. #if !_FS_TINY
  2934. mem_set(fp->buf, 0, _MAX_SS); /* Clear sector buffer */
  2935. #endif
  2936. if ((mode & FA_SEEKEND) && fp->obj.objsize > 0) { /* Seek to end of file if FA_OPEN_APPEND is specified */
  2937. fp->fptr = fp->obj.objsize; /* Offset to seek */
  2938. bcs = (DWORD)fs->csize * SS(fs); /* Cluster size in byte */
  2939. clst = fp->obj.sclust; /* Follow the cluster chain */
  2940. for (ofs = fp->obj.objsize; res == FR_OK && ofs > bcs; ofs -= bcs) {
  2941. clst = get_fat(&fp->obj, clst);
  2942. if (clst <= 1) res = FR_INT_ERR;
  2943. if (clst == 0xFFFFFFFF) res = FR_DISK_ERR;
  2944. }
  2945. fp->clust = clst;
  2946. if (res == FR_OK && ofs % SS(fs)) { /* Fill sector buffer if not on the sector boundary */
  2947. if ((sc = clust2sect(fs, clst)) == 0) {
  2948. res = FR_INT_ERR;
  2949. } else {
  2950. fp->sect = sc + (DWORD)(ofs / SS(fs));
  2951. #if !_FS_TINY
  2952. if (disk_read(fs->drv, fp->buf, fp->sect, 1) != RES_OK) res = FR_DISK_ERR;
  2953. #endif
  2954. }
  2955. }
  2956. }
  2957. #endif
  2958. }
  2959. FREE_NAMBUF();
  2960. }
  2961. if (res != FR_OK) fp->obj.fs = 0; /* Invalidate file object on error */
  2962. LEAVE_FF(fs, res);
  2963. }
  2964. /*-----------------------------------------------------------------------*/
  2965. /* Read File */
  2966. /*-----------------------------------------------------------------------*/
  2967. FRESULT f_read (
  2968. FIL* fp, /* Pointer to the file object */
  2969. void* buff, /* Pointer to data buffer */
  2970. UINT btr, /* Number of bytes to read */
  2971. UINT* br /* Pointer to number of bytes read */
  2972. )
  2973. {
  2974. FRESULT res;
  2975. FATFS *fs;
  2976. DWORD clst, sect;
  2977. FSIZE_t remain;
  2978. UINT rcnt, cc, csect;
  2979. BYTE *rbuff = (BYTE*)buff;
  2980. *br = 0; /* Clear read byte counter */
  2981. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  2982. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
  2983. if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  2984. remain = fp->obj.objsize - fp->fptr;
  2985. if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
  2986. for ( ; btr; /* Repeat until all data read */
  2987. rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
  2988. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  2989. csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
  2990. if (csect == 0) { /* On the cluster boundary? */
  2991. if (fp->fptr == 0) { /* On the top of the file? */
  2992. clst = fp->obj.sclust; /* Follow cluster chain from the origin */
  2993. } else { /* Middle or end of the file */
  2994. #if _USE_FASTSEEK
  2995. if (fp->cltbl) {
  2996. clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
  2997. } else
  2998. #endif
  2999. {
  3000. clst = get_fat(&fp->obj, fp->clust); /* Follow cluster chain on the FAT */
  3001. }
  3002. }
  3003. if (clst < 2) ABORT(fs, FR_INT_ERR);
  3004. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3005. fp->clust = clst; /* Update current cluster */
  3006. }
  3007. sect = clust2sect(fs, fp->clust); /* Get current sector */
  3008. if (!sect) ABORT(fs, FR_INT_ERR);
  3009. sect += csect;
  3010. cc = btr / SS(fs); /* When remaining bytes >= sector size, */
  3011. if (cc) { /* Read maximum contiguous sectors directly */
  3012. if (csect + cc > fs->csize) { /* Clip at cluster boundary */
  3013. cc = fs->csize - csect;
  3014. }
  3015. if (disk_read(fs->drv, rbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3016. #if !_FS_READONLY && _FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */
  3017. #if _FS_TINY
  3018. if (fs->wflag && fs->winsect - sect < cc) {
  3019. mem_cpy(rbuff + ((fs->winsect - sect) * SS(fs)), fs->win, SS(fs));
  3020. }
  3021. #else
  3022. if ((fp->flag & FA_DIRTY) && fp->sect - sect < cc) {
  3023. mem_cpy(rbuff + ((fp->sect - sect) * SS(fs)), fp->buf, SS(fs));
  3024. }
  3025. #endif
  3026. #endif
  3027. rcnt = SS(fs) * cc; /* Number of bytes transferred */
  3028. continue;
  3029. }
  3030. #if !_FS_TINY
  3031. if (fp->sect != sect) { /* Load data sector if not in cache */
  3032. #if !_FS_READONLY
  3033. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  3034. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3035. fp->flag &= (BYTE)~FA_DIRTY;
  3036. }
  3037. #endif
  3038. if (disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
  3039. }
  3040. #endif
  3041. fp->sect = sect;
  3042. }
  3043. rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */
  3044. if (rcnt > btr) rcnt = btr; /* Clip it by btr if needed */
  3045. #if _FS_TINY
  3046. if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */
  3047. mem_cpy(rbuff, fs->win + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
  3048. #else
  3049. mem_cpy(rbuff, fp->buf + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
  3050. #endif
  3051. }
  3052. LEAVE_FF(fs, FR_OK);
  3053. }
  3054. #if !_FS_READONLY
  3055. /*-----------------------------------------------------------------------*/
  3056. /* Write File */
  3057. /*-----------------------------------------------------------------------*/
  3058. FRESULT f_write (
  3059. FIL* fp, /* Pointer to the file object */
  3060. const void* buff, /* Pointer to the data to be written */
  3061. UINT btw, /* Number of bytes to write */
  3062. UINT* bw /* Pointer to number of bytes written */
  3063. )
  3064. {
  3065. FRESULT res;
  3066. FATFS *fs;
  3067. DWORD clst, sect;
  3068. UINT wcnt, cc, csect;
  3069. const BYTE *wbuff = (const BYTE*)buff;
  3070. *bw = 0; /* Clear write byte counter */
  3071. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3072. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
  3073. if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  3074. /* Check fptr wrap-around (file size cannot reach 4GiB on FATxx) */
  3075. if ((!_FS_EXFAT || fs->fs_type != FS_EXFAT) && (DWORD)(fp->fptr + btw) < (DWORD)fp->fptr) {
  3076. btw = (UINT)(0xFFFFFFFF - (DWORD)fp->fptr);
  3077. }
  3078. for ( ; btw; /* Repeat until all data written */
  3079. wbuff += wcnt, fp->fptr += wcnt, fp->obj.objsize = (fp->fptr > fp->obj.objsize) ? fp->fptr : fp->obj.objsize, *bw += wcnt, btw -= wcnt) {
  3080. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  3081. csect = (UINT)(fp->fptr / SS(fs)) & (fs->csize - 1); /* Sector offset in the cluster */
  3082. if (csect == 0) { /* On the cluster boundary? */
  3083. if (fp->fptr == 0) { /* On the top of the file? */
  3084. clst = fp->obj.sclust; /* Follow from the origin */
  3085. if (clst == 0) { /* If no cluster is allocated, */
  3086. clst = create_chain(&fp->obj, 0); /* create a new cluster chain */
  3087. }
  3088. } else { /* On the middle or end of the file */
  3089. #if _USE_FASTSEEK
  3090. if (fp->cltbl) {
  3091. clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
  3092. } else
  3093. #endif
  3094. {
  3095. clst = create_chain(&fp->obj, fp->clust); /* Follow or stretch cluster chain on the FAT */
  3096. }
  3097. }
  3098. if (clst == 0) break; /* Could not allocate a new cluster (disk full) */
  3099. if (clst == 1) ABORT(fs, FR_INT_ERR);
  3100. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3101. fp->clust = clst; /* Update current cluster */
  3102. if (fp->obj.sclust == 0) fp->obj.sclust = clst; /* Set start cluster if the first write */
  3103. }
  3104. #if _FS_TINY
  3105. if (fs->winsect == fp->sect && sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Write-back sector cache */
  3106. #else
  3107. if (fp->flag & FA_DIRTY) { /* Write-back sector cache */
  3108. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3109. fp->flag &= (BYTE)~FA_DIRTY;
  3110. }
  3111. #endif
  3112. sect = clust2sect(fs, fp->clust); /* Get current sector */
  3113. if (!sect) ABORT(fs, FR_INT_ERR);
  3114. sect += csect;
  3115. cc = btw / SS(fs); /* When remaining bytes >= sector size, */
  3116. if (cc) { /* Write maximum contiguous sectors directly */
  3117. if (csect + cc > fs->csize) { /* Clip at cluster boundary */
  3118. cc = fs->csize - csect;
  3119. }
  3120. if (disk_write(fs->drv, wbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3121. #if _FS_MINIMIZE <= 2
  3122. #if _FS_TINY
  3123. if (fs->winsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  3124. mem_cpy(fs->win, wbuff + ((fs->winsect - sect) * SS(fs)), SS(fs));
  3125. fs->wflag = 0;
  3126. }
  3127. #else
  3128. if (fp->sect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  3129. mem_cpy(fp->buf, wbuff + ((fp->sect - sect) * SS(fs)), SS(fs));
  3130. fp->flag &= (BYTE)~FA_DIRTY;
  3131. }
  3132. #endif
  3133. #endif
  3134. wcnt = SS(fs) * cc; /* Number of bytes transferred */
  3135. continue;
  3136. }
  3137. #if _FS_TINY
  3138. if (fp->fptr >= fp->obj.objsize) { /* Avoid silly cache filling on the growing edge */
  3139. if (sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR);
  3140. fs->winsect = sect;
  3141. }
  3142. #else
  3143. if (fp->sect != sect && /* Fill sector cache with file data */
  3144. fp->fptr < fp->obj.objsize &&
  3145. disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) {
  3146. ABORT(fs, FR_DISK_ERR);
  3147. }
  3148. #endif
  3149. fp->sect = sect;
  3150. }
  3151. wcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */
  3152. if (wcnt > btw) wcnt = btw; /* Clip it by btw if needed */
  3153. #if _FS_TINY
  3154. if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */
  3155. mem_cpy(fs->win + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
  3156. fs->wflag = 1;
  3157. #else
  3158. mem_cpy(fp->buf + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
  3159. fp->flag |= FA_DIRTY;
  3160. #endif
  3161. }
  3162. fp->flag |= FA_MODIFIED; /* Set file change flag */
  3163. LEAVE_FF(fs, FR_OK);
  3164. }
  3165. /*-----------------------------------------------------------------------*/
  3166. /* Synchronize the File */
  3167. /*-----------------------------------------------------------------------*/
  3168. FRESULT f_sync (
  3169. FIL* fp /* Pointer to the file object */
  3170. )
  3171. {
  3172. FRESULT res;
  3173. FATFS *fs;
  3174. DWORD tm;
  3175. BYTE *dir;
  3176. #if _FS_EXFAT
  3177. DIR dj;
  3178. DEF_NAMBUF
  3179. #endif
  3180. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3181. if (res == FR_OK) {
  3182. if (fp->flag & FA_MODIFIED) { /* Is there any change to the file? */
  3183. #if !_FS_TINY
  3184. if (fp->flag & FA_DIRTY) { /* Write-back cached data if needed */
  3185. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) LEAVE_FF(fs, FR_DISK_ERR);
  3186. fp->flag &= (BYTE)~FA_DIRTY;
  3187. }
  3188. #endif
  3189. /* Update the directory entry */
  3190. tm = GET_FATTIME(); /* Modified time */
  3191. #if _FS_EXFAT
  3192. if (fs->fs_type == FS_EXFAT) {
  3193. res = fill_first_frag(&fp->obj); /* Fill first fragment on the FAT if needed */
  3194. if (res == FR_OK) {
  3195. res = fill_last_frag(&fp->obj, fp->clust, 0xFFFFFFFF); /* Fill last fragment on the FAT if needed */
  3196. }
  3197. if (res == FR_OK) {
  3198. INIT_NAMBUF(fs);
  3199. res = load_obj_dir(&dj, &fp->obj); /* Load directory entry block */
  3200. if (res == FR_OK) {
  3201. fs->dirbuf[XDIR_Attr] |= AM_ARC; /* Set archive bit */
  3202. fs->dirbuf[XDIR_GenFlags] = fp->obj.stat | 1; /* Update file allocation info */
  3203. st_dword(fs->dirbuf + XDIR_FstClus, fp->obj.sclust);
  3204. st_qword(fs->dirbuf + XDIR_FileSize, fp->obj.objsize);
  3205. st_qword(fs->dirbuf + XDIR_ValidFileSize, fp->obj.objsize);
  3206. st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Update modified time */
  3207. fs->dirbuf[XDIR_ModTime10] = 0;
  3208. st_dword(fs->dirbuf + XDIR_AccTime, 0);
  3209. res = store_xdir(&dj); /* Restore it to the directory */
  3210. if (res == FR_OK) {
  3211. res = sync_fs(fs);
  3212. fp->flag &= (BYTE)~FA_MODIFIED;
  3213. }
  3214. }
  3215. FREE_NAMBUF();
  3216. }
  3217. } else
  3218. #endif
  3219. {
  3220. res = move_window(fs, fp->dir_sect);
  3221. if (res == FR_OK) {
  3222. dir = fp->dir_ptr;
  3223. dir[DIR_Attr] |= AM_ARC; /* Set archive bit */
  3224. st_clust(fp->obj.fs, dir, fp->obj.sclust); /* Update file allocation info */
  3225. st_dword(dir + DIR_FileSize, (DWORD)fp->obj.objsize); /* Update file size */
  3226. st_dword(dir + DIR_ModTime, tm); /* Update modified time */
  3227. st_word(dir + DIR_LstAccDate, 0);
  3228. fs->wflag = 1;
  3229. res = sync_fs(fs); /* Restore it to the directory */
  3230. fp->flag &= (BYTE)~FA_MODIFIED;
  3231. }
  3232. }
  3233. }
  3234. }
  3235. LEAVE_FF(fs, res);
  3236. }
  3237. #endif /* !_FS_READONLY */
  3238. /*-----------------------------------------------------------------------*/
  3239. /* Close File */
  3240. /*-----------------------------------------------------------------------*/
  3241. FRESULT f_close (
  3242. FIL* fp /* Pointer to the file object to be closed */
  3243. )
  3244. {
  3245. FRESULT res;
  3246. FATFS *fs;
  3247. #if !_FS_READONLY
  3248. res = f_sync(fp); /* Flush cached data */
  3249. if (res == FR_OK)
  3250. #endif
  3251. {
  3252. res = validate(&fp->obj, &fs); /* Lock volume */
  3253. if (res == FR_OK) {
  3254. #if _FS_LOCK != 0
  3255. res = dec_lock(fp->obj.lockid); /* Decrement file open counter */
  3256. if (res == FR_OK)
  3257. #endif
  3258. {
  3259. fp->obj.fs = 0; /* Invalidate file object */
  3260. }
  3261. #if _FS_REENTRANT
  3262. unlock_fs(fs, FR_OK); /* Unlock volume */
  3263. #endif
  3264. }
  3265. }
  3266. return res;
  3267. }
  3268. #if _FS_RPATH >= 1
  3269. /*-----------------------------------------------------------------------*/
  3270. /* Change Current Directory or Current Drive, Get Current Directory */
  3271. /*-----------------------------------------------------------------------*/
  3272. #if _VOLUMES >= 2
  3273. FRESULT f_chdrive (
  3274. const TCHAR* path /* Drive number */
  3275. )
  3276. {
  3277. int vol;
  3278. /* Get logical drive number */
  3279. vol = get_ldnumber(&path);
  3280. if (vol < 0) return FR_INVALID_DRIVE;
  3281. CurrVol = (BYTE)vol; /* Set it as current volume */
  3282. return FR_OK;
  3283. }
  3284. #endif
  3285. FRESULT f_chdir (
  3286. const TCHAR* path /* Pointer to the directory path */
  3287. )
  3288. {
  3289. FRESULT res;
  3290. DIR dj;
  3291. FATFS *fs;
  3292. DEF_NAMBUF
  3293. /* Get logical drive */
  3294. res = find_volume(&path, &fs, 0);
  3295. if (res == FR_OK) {
  3296. dj.obj.fs = fs;
  3297. INIT_NAMBUF(fs);
  3298. res = follow_path(&dj, path); /* Follow the path */
  3299. if (res == FR_OK) { /* Follow completed */
  3300. if (dj.fn[NSFLAG] & NS_NONAME) {
  3301. fs->cdir = dj.obj.sclust; /* It is the start directory itself */
  3302. #if _FS_EXFAT
  3303. if (fs->fs_type == FS_EXFAT) {
  3304. fs->cdc_scl = dj.obj.c_scl;
  3305. fs->cdc_size = dj.obj.c_size;
  3306. fs->cdc_ofs = dj.obj.c_ofs;
  3307. }
  3308. #endif
  3309. } else {
  3310. if (dj.obj.attr & AM_DIR) { /* It is a sub-directory */
  3311. #if _FS_EXFAT
  3312. if (fs->fs_type == FS_EXFAT) {
  3313. fs->cdir = ld_dword(fs->dirbuf + XDIR_FstClus); /* Sub-directory cluster */
  3314. fs->cdc_scl = dj.obj.sclust; /* Save containing directory information */
  3315. fs->cdc_size = ((DWORD)dj.obj.objsize & 0xFFFFFF00) | dj.obj.stat;
  3316. fs->cdc_ofs = dj.blk_ofs;
  3317. } else
  3318. #endif
  3319. {
  3320. fs->cdir = ld_clust(fs, dj.dir); /* Sub-directory cluster */
  3321. }
  3322. } else {
  3323. res = FR_NO_PATH; /* Reached but a file */
  3324. }
  3325. }
  3326. }
  3327. FREE_NAMBUF();
  3328. if (res == FR_NO_FILE) res = FR_NO_PATH;
  3329. }
  3330. LEAVE_FF(fs, res);
  3331. }
  3332. #if _FS_RPATH >= 2
  3333. FRESULT f_getcwd (
  3334. TCHAR* buff, /* Pointer to the directory path */
  3335. UINT len /* Size of path */
  3336. )
  3337. {
  3338. FRESULT res;
  3339. DIR dj;
  3340. FATFS *fs;
  3341. UINT i, n;
  3342. DWORD ccl;
  3343. TCHAR *tp;
  3344. FILINFO fno;
  3345. DEF_NAMBUF
  3346. *buff = 0;
  3347. /* Get logical drive */
  3348. res = find_volume((const TCHAR**)&buff, &fs, 0); /* Get current volume */
  3349. if (res == FR_OK) {
  3350. dj.obj.fs = fs;
  3351. INIT_NAMBUF(fs);
  3352. i = len; /* Bottom of buffer (directory stack base) */
  3353. if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) { /* (Cannot do getcwd on exFAT and returns root path) */
  3354. dj.obj.sclust = fs->cdir; /* Start to follow upper directory from current directory */
  3355. while ((ccl = dj.obj.sclust) != 0) { /* Repeat while current directory is a sub-directory */
  3356. res = dir_sdi(&dj, 1 * SZDIRE); /* Get parent directory */
  3357. if (res != FR_OK) break;
  3358. res = move_window(fs, dj.sect);
  3359. if (res != FR_OK) break;
  3360. dj.obj.sclust = ld_clust(fs, dj.dir); /* Goto parent directory */
  3361. res = dir_sdi(&dj, 0);
  3362. if (res != FR_OK) break;
  3363. do { /* Find the entry links to the child directory */
  3364. res = dir_read(&dj, 0);
  3365. if (res != FR_OK) break;
  3366. if (ccl == ld_clust(fs, dj.dir)) break; /* Found the entry */
  3367. res = dir_next(&dj, 0);
  3368. } while (res == FR_OK);
  3369. if (res == FR_NO_FILE) res = FR_INT_ERR;/* It cannot be 'not found'. */
  3370. if (res != FR_OK) break;
  3371. get_fileinfo(&dj, &fno); /* Get the directory name and push it to the buffer */
  3372. for (n = 0; fno.fname[n]; n++) ;
  3373. if (i < n + 3) {
  3374. res = FR_NOT_ENOUGH_CORE; break;
  3375. }
  3376. while (n) buff[--i] = fno.fname[--n];
  3377. buff[--i] = '/';
  3378. }
  3379. }
  3380. tp = buff;
  3381. if (res == FR_OK) {
  3382. #if _VOLUMES >= 2
  3383. *tp++ = '0' + CurrVol; /* Put drive number */
  3384. *tp++ = ':';
  3385. #endif
  3386. if (i == len) { /* Root-directory */
  3387. *tp++ = '/';
  3388. } else { /* Sub-directroy */
  3389. do /* Add stacked path str */
  3390. *tp++ = buff[i++];
  3391. while (i < len);
  3392. }
  3393. }
  3394. *tp = 0;
  3395. FREE_NAMBUF();
  3396. }
  3397. LEAVE_FF(fs, res);
  3398. }
  3399. #endif /* _FS_RPATH >= 2 */
  3400. #endif /* _FS_RPATH >= 1 */
  3401. #if _FS_MINIMIZE <= 2
  3402. /*-----------------------------------------------------------------------*/
  3403. /* Seek File R/W Pointer */
  3404. /*-----------------------------------------------------------------------*/
  3405. FRESULT f_lseek (
  3406. FIL* fp, /* Pointer to the file object */
  3407. FSIZE_t ofs /* File pointer from top of file */
  3408. )
  3409. {
  3410. FRESULT res;
  3411. FATFS *fs;
  3412. DWORD clst, bcs, nsect;
  3413. FSIZE_t ifptr;
  3414. #if _USE_FASTSEEK
  3415. DWORD cl, pcl, ncl, tcl, dsc, tlen, ulen, *tbl;
  3416. #endif
  3417. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3418. if (res == FR_OK) res = (FRESULT)fp->err;
  3419. #if _FS_EXFAT && !_FS_READONLY
  3420. if (res == FR_OK && fs->fs_type == FS_EXFAT) {
  3421. res = fill_last_frag(&fp->obj, fp->clust, 0xFFFFFFFF); /* Fill last fragment on the FAT if needed */
  3422. }
  3423. #endif
  3424. if (res != FR_OK) LEAVE_FF(fs, res);
  3425. #if _USE_FASTSEEK
  3426. if (fp->cltbl) { /* Fast seek */
  3427. if (ofs == CREATE_LINKMAP) { /* Create CLMT */
  3428. tbl = fp->cltbl;
  3429. tlen = *tbl++; ulen = 2; /* Given table size and required table size */
  3430. cl = fp->obj.sclust; /* Origin of the chain */
  3431. if (cl) {
  3432. do {
  3433. /* Get a fragment */
  3434. tcl = cl; ncl = 0; ulen += 2; /* Top, length and used items */
  3435. do {
  3436. pcl = cl; ncl++;
  3437. cl = get_fat(&fp->obj, cl);
  3438. if (cl <= 1) ABORT(fs, FR_INT_ERR);
  3439. if (cl == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3440. } while (cl == pcl + 1);
  3441. if (ulen <= tlen) { /* Store the length and top of the fragment */
  3442. *tbl++ = ncl; *tbl++ = tcl;
  3443. }
  3444. } while (cl < fs->n_fatent); /* Repeat until end of chain */
  3445. }
  3446. *fp->cltbl = ulen; /* Number of items used */
  3447. if (ulen <= tlen) {
  3448. *tbl = 0; /* Terminate table */
  3449. } else {
  3450. res = FR_NOT_ENOUGH_CORE; /* Given table size is smaller than required */
  3451. }
  3452. } else { /* Fast seek */
  3453. if (ofs > fp->obj.objsize) ofs = fp->obj.objsize; /* Clip offset at the file size */
  3454. fp->fptr = ofs; /* Set file pointer */
  3455. if (ofs) {
  3456. fp->clust = clmt_clust(fp, ofs - 1);
  3457. dsc = clust2sect(fs, fp->clust);
  3458. if (!dsc) ABORT(fs, FR_INT_ERR);
  3459. dsc += (DWORD)((ofs - 1) / SS(fs)) & (fs->csize - 1);
  3460. if (fp->fptr % SS(fs) && dsc != fp->sect) { /* Refill sector cache if needed */
  3461. #if !_FS_TINY
  3462. #if !_FS_READONLY
  3463. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  3464. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3465. fp->flag &= (BYTE)~FA_DIRTY;
  3466. }
  3467. #endif
  3468. if (disk_read(fs->drv, fp->buf, dsc, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Load current sector */
  3469. #endif
  3470. fp->sect = dsc;
  3471. }
  3472. }
  3473. }
  3474. } else
  3475. #endif
  3476. /* Normal Seek */
  3477. {
  3478. #if _FS_EXFAT
  3479. if (fs->fs_type != FS_EXFAT && ofs >= 0x100000000) ofs = 0xFFFFFFFF; /* Clip at 4GiB-1 if at FATxx */
  3480. #endif
  3481. if (ofs > fp->obj.objsize && (_FS_READONLY || !(fp->flag & FA_WRITE))) { /* In read-only mode, clip offset with the file size */
  3482. ofs = fp->obj.objsize;
  3483. }
  3484. ifptr = fp->fptr;
  3485. fp->fptr = nsect = 0;
  3486. if (ofs) {
  3487. bcs = (DWORD)fs->csize * SS(fs); /* Cluster size (byte) */
  3488. if (ifptr > 0 &&
  3489. (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
  3490. fp->fptr = (ifptr - 1) & ~(FSIZE_t)(bcs - 1); /* start from the current cluster */
  3491. ofs -= fp->fptr;
  3492. clst = fp->clust;
  3493. } else { /* When seek to back cluster, */
  3494. clst = fp->obj.sclust; /* start from the first cluster */
  3495. #if !_FS_READONLY
  3496. if (clst == 0) { /* If no cluster chain, create a new chain */
  3497. clst = create_chain(&fp->obj, 0);
  3498. if (clst == 1) ABORT(fs, FR_INT_ERR);
  3499. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3500. fp->obj.sclust = clst;
  3501. }
  3502. #endif
  3503. fp->clust = clst;
  3504. }
  3505. if (clst != 0) {
  3506. while (ofs > bcs) { /* Cluster following loop */
  3507. ofs -= bcs; fp->fptr += bcs;
  3508. #if !_FS_READONLY
  3509. if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
  3510. if (_FS_EXFAT && fp->fptr > fp->obj.objsize) { /* No FAT chain object needs correct objsize to generate FAT value */
  3511. fp->obj.objsize = fp->fptr;
  3512. fp->flag |= FA_MODIFIED;
  3513. }
  3514. clst = create_chain(&fp->obj, clst); /* Follow chain with forceed stretch */
  3515. if (clst == 0) { /* Clip file size in case of disk full */
  3516. ofs = 0; break;
  3517. }
  3518. } else
  3519. #endif
  3520. {
  3521. clst = get_fat(&fp->obj, clst); /* Follow cluster chain if not in write mode */
  3522. }
  3523. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3524. if (clst <= 1 || clst >= fs->n_fatent) ABORT(fs, FR_INT_ERR);
  3525. fp->clust = clst;
  3526. }
  3527. fp->fptr += ofs;
  3528. if (ofs % SS(fs)) {
  3529. nsect = clust2sect(fs, clst); /* Current sector */
  3530. if (!nsect) ABORT(fs, FR_INT_ERR);
  3531. nsect += (DWORD)(ofs / SS(fs));
  3532. }
  3533. }
  3534. }
  3535. if (!_FS_READONLY && fp->fptr > fp->obj.objsize) { /* Set file change flag if the file size is extended */
  3536. fp->obj.objsize = fp->fptr;
  3537. fp->flag |= FA_MODIFIED;
  3538. }
  3539. if (fp->fptr % SS(fs) && nsect != fp->sect) { /* Fill sector cache if needed */
  3540. #if !_FS_TINY
  3541. #if !_FS_READONLY
  3542. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  3543. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3544. fp->flag &= (BYTE)~FA_DIRTY;
  3545. }
  3546. #endif
  3547. if (disk_read(fs->drv, fp->buf, nsect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
  3548. #endif
  3549. fp->sect = nsect;
  3550. }
  3551. }
  3552. LEAVE_FF(fs, res);
  3553. }
  3554. #if _FS_MINIMIZE <= 1
  3555. /*-----------------------------------------------------------------------*/
  3556. /* Create a Directory Object */
  3557. /*-----------------------------------------------------------------------*/
  3558. FRESULT f_opendir (
  3559. DIR* dp, /* Pointer to directory object to create */
  3560. const TCHAR* path /* Pointer to the directory path */
  3561. )
  3562. {
  3563. FRESULT res;
  3564. FATFS *fs;
  3565. _FDID *obj;
  3566. DEF_NAMBUF
  3567. if (!dp) return FR_INVALID_OBJECT;
  3568. /* Get logical drive */
  3569. obj = &dp->obj;
  3570. res = find_volume(&path, &fs, 0);
  3571. if (res == FR_OK) {
  3572. obj->fs = fs;
  3573. INIT_NAMBUF(fs);
  3574. res = follow_path(dp, path); /* Follow the path to the directory */
  3575. if (res == FR_OK) { /* Follow completed */
  3576. if (!(dp->fn[NSFLAG] & NS_NONAME)) { /* It is not the origin directory itself */
  3577. if (obj->attr & AM_DIR) { /* This object is a sub-directory */
  3578. #if _FS_EXFAT
  3579. if (fs->fs_type == FS_EXFAT) {
  3580. obj->c_scl = obj->sclust; /* Get containing directory inforamation */
  3581. obj->c_size = ((DWORD)obj->objsize & 0xFFFFFF00) | obj->stat;
  3582. obj->c_ofs = dp->blk_ofs;
  3583. obj->sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Get object allocation info */
  3584. obj->objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  3585. obj->stat = fs->dirbuf[XDIR_GenFlags] & 2;
  3586. } else
  3587. #endif
  3588. {
  3589. obj->sclust = ld_clust(fs, dp->dir); /* Get object allocation info */
  3590. }
  3591. } else { /* This object is a file */
  3592. res = FR_NO_PATH;
  3593. }
  3594. }
  3595. if (res == FR_OK) {
  3596. obj->id = fs->id;
  3597. res = dir_sdi(dp, 0); /* Rewind directory */
  3598. #if _FS_LOCK != 0
  3599. if (res == FR_OK) {
  3600. if (obj->sclust) {
  3601. obj->lockid = inc_lock(dp, 0); /* Lock the sub directory */
  3602. if (!obj->lockid) res = FR_TOO_MANY_OPEN_FILES;
  3603. } else {
  3604. obj->lockid = 0; /* Root directory need not to be locked */
  3605. }
  3606. }
  3607. #endif
  3608. }
  3609. }
  3610. FREE_NAMBUF();
  3611. if (res == FR_NO_FILE) res = FR_NO_PATH;
  3612. }
  3613. if (res != FR_OK) obj->fs = 0; /* Invalidate the directory object if function faild */
  3614. LEAVE_FF(fs, res);
  3615. }
  3616. /*-----------------------------------------------------------------------*/
  3617. /* Close Directory */
  3618. /*-----------------------------------------------------------------------*/
  3619. FRESULT f_closedir (
  3620. DIR *dp /* Pointer to the directory object to be closed */
  3621. )
  3622. {
  3623. FRESULT res;
  3624. FATFS *fs;
  3625. res = validate(&dp->obj, &fs); /* Check validity of the file object */
  3626. if (res == FR_OK) {
  3627. #if _FS_LOCK != 0
  3628. if (dp->obj.lockid) { /* Decrement sub-directory open counter */
  3629. res = dec_lock(dp->obj.lockid);
  3630. }
  3631. if (res == FR_OK)
  3632. #endif
  3633. {
  3634. dp->obj.fs = 0; /* Invalidate directory object */
  3635. }
  3636. #if _FS_REENTRANT
  3637. unlock_fs(fs, FR_OK); /* Unlock volume */
  3638. #endif
  3639. }
  3640. return res;
  3641. }
  3642. /*-----------------------------------------------------------------------*/
  3643. /* Read Directory Entries in Sequence */
  3644. /*-----------------------------------------------------------------------*/
  3645. FRESULT f_readdir (
  3646. DIR* dp, /* Pointer to the open directory object */
  3647. FILINFO* fno /* Pointer to file information to return */
  3648. )
  3649. {
  3650. FRESULT res;
  3651. FATFS *fs;
  3652. DEF_NAMBUF
  3653. res = validate(&dp->obj, &fs); /* Check validity of the directory object */
  3654. if (res == FR_OK) {
  3655. if (!fno) {
  3656. res = dir_sdi(dp, 0); /* Rewind the directory object */
  3657. } else {
  3658. INIT_NAMBUF(fs);
  3659. res = dir_read(dp, 0); /* Read an item */
  3660. if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory */
  3661. if (res == FR_OK) { /* A valid entry is found */
  3662. get_fileinfo(dp, fno); /* Get the object information */
  3663. res = dir_next(dp, 0); /* Increment index for next */
  3664. if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory now */
  3665. }
  3666. FREE_NAMBUF();
  3667. }
  3668. }
  3669. LEAVE_FF(fs, res);
  3670. }
  3671. #if _USE_FIND
  3672. /*-----------------------------------------------------------------------*/
  3673. /* Find Next File */
  3674. /*-----------------------------------------------------------------------*/
  3675. FRESULT f_findnext (
  3676. DIR* dp, /* Pointer to the open directory object */
  3677. FILINFO* fno /* Pointer to the file information structure */
  3678. )
  3679. {
  3680. FRESULT res;
  3681. for (;;) {
  3682. res = f_readdir(dp, fno); /* Get a directory item */
  3683. if (res != FR_OK || !fno || !fno->fname[0]) break; /* Terminate if any error or end of directory */
  3684. if (pattern_matching(dp->pat, fno->fname, 0, 0)) break; /* Test for the file name */
  3685. #if _USE_LFN != 0 && _USE_FIND == 2
  3686. if (pattern_matching(dp->pat, fno->altname, 0, 0)) break; /* Test for alternative name if exist */
  3687. #endif
  3688. }
  3689. return res;
  3690. }
  3691. /*-----------------------------------------------------------------------*/
  3692. /* Find First File */
  3693. /*-----------------------------------------------------------------------*/
  3694. FRESULT f_findfirst (
  3695. DIR* dp, /* Pointer to the blank directory object */
  3696. FILINFO* fno, /* Pointer to the file information structure */
  3697. const TCHAR* path, /* Pointer to the directory to open */
  3698. const TCHAR* pattern /* Pointer to the matching pattern */
  3699. )
  3700. {
  3701. FRESULT res;
  3702. dp->pat = pattern; /* Save pointer to pattern string */
  3703. res = f_opendir(dp, path); /* Open the target directory */
  3704. if (res == FR_OK) {
  3705. res = f_findnext(dp, fno); /* Find the first item */
  3706. }
  3707. return res;
  3708. }
  3709. #endif /* _USE_FIND */
  3710. #if _FS_MINIMIZE == 0
  3711. /*-----------------------------------------------------------------------*/
  3712. /* Get File Status */
  3713. /*-----------------------------------------------------------------------*/
  3714. FRESULT f_stat (
  3715. const TCHAR* path, /* Pointer to the file path */
  3716. FILINFO* fno /* Pointer to file information to return */
  3717. )
  3718. {
  3719. FRESULT res;
  3720. DIR dj;
  3721. DEF_NAMBUF
  3722. /* Get logical drive */
  3723. res = find_volume(&path, &dj.obj.fs, 0);
  3724. if (res == FR_OK) {
  3725. INIT_NAMBUF(dj.obj.fs);
  3726. res = follow_path(&dj, path); /* Follow the file path */
  3727. if (res == FR_OK) { /* Follow completed */
  3728. if (dj.fn[NSFLAG] & NS_NONAME) { /* It is origin directory */
  3729. res = FR_INVALID_NAME;
  3730. } else { /* Found an object */
  3731. if (fno) get_fileinfo(&dj, fno);
  3732. }
  3733. }
  3734. FREE_NAMBUF();
  3735. }
  3736. LEAVE_FF(dj.obj.fs, res);
  3737. }
  3738. #if !_FS_READONLY
  3739. /*-----------------------------------------------------------------------*/
  3740. /* Get Number of Free Clusters */
  3741. /*-----------------------------------------------------------------------*/
  3742. FRESULT f_getfree (
  3743. const TCHAR* path, /* Path name of the logical drive number */
  3744. DWORD* nclst, /* Pointer to a variable to return number of free clusters */
  3745. FATFS** fatfs /* Pointer to return pointer to corresponding file system object */
  3746. )
  3747. {
  3748. FRESULT res;
  3749. FATFS *fs;
  3750. DWORD nfree, clst, sect, stat;
  3751. UINT i;
  3752. BYTE *p;
  3753. _FDID obj;
  3754. /* Get logical drive */
  3755. res = find_volume(&path, &fs, 0);
  3756. if (res == FR_OK) {
  3757. *fatfs = fs; /* Return ptr to the fs object */
  3758. /* If free_clst is valid, return it without full cluster scan */
  3759. if (fs->free_clst <= fs->n_fatent - 2) {
  3760. *nclst = fs->free_clst;
  3761. } else {
  3762. /* Get number of free clusters */
  3763. nfree = 0;
  3764. if (fs->fs_type == FS_FAT12) { /* FAT12: Sector unalighed FAT entries */
  3765. clst = 2; obj.fs = fs;
  3766. do {
  3767. stat = get_fat(&obj, clst);
  3768. if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
  3769. if (stat == 1) { res = FR_INT_ERR; break; }
  3770. if (stat == 0) nfree++;
  3771. } while (++clst < fs->n_fatent);
  3772. } else {
  3773. #if _FS_EXFAT
  3774. if (fs->fs_type == FS_EXFAT) { /* exFAT: Scan bitmap table */
  3775. BYTE bm;
  3776. UINT b;
  3777. clst = fs->n_fatent - 2;
  3778. sect = fs->database;
  3779. i = 0;
  3780. do {
  3781. if (i == 0 && (res = move_window(fs, sect++)) != FR_OK) break;
  3782. for (b = 8, bm = fs->win[i]; b && clst; b--, clst--) {
  3783. if (!(bm & 1)) nfree++;
  3784. bm >>= 1;
  3785. }
  3786. i = (i + 1) % SS(fs);
  3787. } while (clst);
  3788. } else
  3789. #endif
  3790. { /* FAT16/32: Sector alighed FAT entries */
  3791. clst = fs->n_fatent; sect = fs->fatbase;
  3792. i = 0; p = 0;
  3793. do {
  3794. if (i == 0) {
  3795. res = move_window(fs, sect++);
  3796. if (res != FR_OK) break;
  3797. p = fs->win;
  3798. i = SS(fs);
  3799. }
  3800. if (fs->fs_type == FS_FAT16) {
  3801. if (ld_word(p) == 0) nfree++;
  3802. p += 2; i -= 2;
  3803. } else {
  3804. if ((ld_dword(p) & 0x0FFFFFFF) == 0) nfree++;
  3805. p += 4; i -= 4;
  3806. }
  3807. } while (--clst);
  3808. }
  3809. }
  3810. *nclst = nfree; /* Return the free clusters */
  3811. fs->free_clst = nfree; /* Now free_clst is valid */
  3812. fs->fsi_flag |= 1; /* FSInfo is to be updated */
  3813. }
  3814. }
  3815. LEAVE_FF(fs, res);
  3816. }
  3817. /*-----------------------------------------------------------------------*/
  3818. /* Truncate File */
  3819. /*-----------------------------------------------------------------------*/
  3820. FRESULT f_truncate (
  3821. FIL* fp /* Pointer to the file object */
  3822. )
  3823. {
  3824. FRESULT res;
  3825. FATFS *fs;
  3826. DWORD ncl;
  3827. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3828. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  3829. if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  3830. if (fp->fptr < fp->obj.objsize) { /* Process when fptr is not on the eof */
  3831. if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
  3832. res = remove_chain(&fp->obj, fp->obj.sclust, 0);
  3833. fp->obj.sclust = 0;
  3834. } else { /* When truncate a part of the file, remove remaining clusters */
  3835. ncl = get_fat(&fp->obj, fp->clust);
  3836. res = FR_OK;
  3837. if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
  3838. if (ncl == 1) res = FR_INT_ERR;
  3839. if (res == FR_OK && ncl < fs->n_fatent) {
  3840. res = remove_chain(&fp->obj, ncl, fp->clust);
  3841. }
  3842. }
  3843. fp->obj.objsize = fp->fptr; /* Set file size to current R/W point */
  3844. fp->flag |= FA_MODIFIED;
  3845. #if !_FS_TINY
  3846. if (res == FR_OK && (fp->flag & FA_DIRTY)) {
  3847. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) {
  3848. res = FR_DISK_ERR;
  3849. } else {
  3850. fp->flag &= (BYTE)~FA_DIRTY;
  3851. }
  3852. }
  3853. #endif
  3854. if (res != FR_OK) ABORT(fs, res);
  3855. }
  3856. LEAVE_FF(fs, res);
  3857. }
  3858. /*-----------------------------------------------------------------------*/
  3859. /* Delete a File/Directory */
  3860. /*-----------------------------------------------------------------------*/
  3861. FRESULT f_unlink (
  3862. const TCHAR* path /* Pointer to the file or directory path */
  3863. )
  3864. {
  3865. FRESULT res;
  3866. DIR dj, sdj;
  3867. DWORD dclst = 0;
  3868. FATFS *fs;
  3869. #if _FS_EXFAT
  3870. _FDID obj;
  3871. #endif
  3872. DEF_NAMBUF
  3873. /* Get logical drive */
  3874. res = find_volume(&path, &fs, FA_WRITE);
  3875. dj.obj.fs = fs;
  3876. if (res == FR_OK) {
  3877. INIT_NAMBUF(fs);
  3878. res = follow_path(&dj, path); /* Follow the file path */
  3879. if (_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT)) {
  3880. res = FR_INVALID_NAME; /* Cannot remove dot entry */
  3881. }
  3882. #if _FS_LOCK != 0
  3883. if (res == FR_OK) res = chk_lock(&dj, 2); /* Check if it is an open object */
  3884. #endif
  3885. if (res == FR_OK) { /* The object is accessible */
  3886. if (dj.fn[NSFLAG] & NS_NONAME) {
  3887. res = FR_INVALID_NAME; /* Cannot remove the origin directory */
  3888. } else {
  3889. if (dj.obj.attr & AM_RDO) {
  3890. res = FR_DENIED; /* Cannot remove R/O object */
  3891. }
  3892. }
  3893. if (res == FR_OK) {
  3894. #if _FS_EXFAT
  3895. obj.fs = fs;
  3896. if (fs->fs_type == FS_EXFAT) {
  3897. obj.sclust = dclst = ld_dword(fs->dirbuf + XDIR_FstClus);
  3898. obj.objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  3899. obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
  3900. } else
  3901. #endif
  3902. {
  3903. dclst = ld_clust(fs, dj.dir);
  3904. }
  3905. if (dj.obj.attr & AM_DIR) { /* Is it a sub-directory? */
  3906. #if _FS_RPATH != 0
  3907. if (dclst == fs->cdir) { /* Is it the current directory? */
  3908. res = FR_DENIED;
  3909. } else
  3910. #endif
  3911. {
  3912. sdj.obj.fs = fs; /* Open the sub-directory */
  3913. sdj.obj.sclust = dclst;
  3914. #if _FS_EXFAT
  3915. if (fs->fs_type == FS_EXFAT) {
  3916. sdj.obj.objsize = obj.objsize;
  3917. sdj.obj.stat = obj.stat;
  3918. }
  3919. #endif
  3920. res = dir_sdi(&sdj, 0);
  3921. if (res == FR_OK) {
  3922. res = dir_read(&sdj, 0); /* Read an item */
  3923. if (res == FR_OK) res = FR_DENIED; /* Not empty? */
  3924. if (res == FR_NO_FILE) res = FR_OK; /* Empty? */
  3925. }
  3926. }
  3927. }
  3928. }
  3929. if (res == FR_OK) {
  3930. res = dir_remove(&dj); /* Remove the directory entry */
  3931. if (res == FR_OK && dclst) { /* Remove the cluster chain if exist */
  3932. #if _FS_EXFAT
  3933. res = remove_chain(&obj, dclst, 0);
  3934. #else
  3935. res = remove_chain(&dj.obj, dclst, 0);
  3936. #endif
  3937. }
  3938. if (res == FR_OK) res = sync_fs(fs);
  3939. }
  3940. }
  3941. FREE_NAMBUF();
  3942. }
  3943. LEAVE_FF(fs, res);
  3944. }
  3945. /*-----------------------------------------------------------------------*/
  3946. /* Create a Directory */
  3947. /*-----------------------------------------------------------------------*/
  3948. FRESULT f_mkdir (
  3949. const TCHAR* path /* Pointer to the directory path */
  3950. )
  3951. {
  3952. FRESULT res;
  3953. DIR dj;
  3954. FATFS *fs;
  3955. BYTE *dir;
  3956. UINT n;
  3957. DWORD dsc, dcl, pcl, tm;
  3958. DEF_NAMBUF
  3959. /* Get logical drive */
  3960. res = find_volume(&path, &fs, FA_WRITE);
  3961. dj.obj.fs = fs;
  3962. if (res == FR_OK) {
  3963. INIT_NAMBUF(fs);
  3964. res = follow_path(&dj, path); /* Follow the file path */
  3965. if (res == FR_OK) res = FR_EXIST; /* Any object with same name is already existing */
  3966. if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[NSFLAG] & NS_DOT)) {
  3967. res = FR_INVALID_NAME;
  3968. }
  3969. if (res == FR_NO_FILE) { /* Can create a new directory */
  3970. dcl = create_chain(&dj.obj, 0); /* Allocate a cluster for the new directory table */
  3971. dj.obj.objsize = (DWORD)fs->csize * SS(fs);
  3972. res = FR_OK;
  3973. if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster */
  3974. if (dcl == 1) res = FR_INT_ERR;
  3975. if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR;
  3976. if (res == FR_OK) res = sync_window(fs); /* Flush FAT */
  3977. tm = GET_FATTIME();
  3978. if (res == FR_OK) { /* Initialize the new directory table */
  3979. dsc = clust2sect(fs, dcl);
  3980. dir = fs->win;
  3981. mem_set(dir, 0, SS(fs));
  3982. if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
  3983. mem_set(dir + DIR_Name, ' ', 11); /* Create "." entry */
  3984. dir[DIR_Name] = '.';
  3985. dir[DIR_Attr] = AM_DIR;
  3986. st_dword(dir + DIR_ModTime, tm);
  3987. st_clust(fs, dir, dcl);
  3988. mem_cpy(dir + SZDIRE, dir, SZDIRE); /* Create ".." entry */
  3989. dir[SZDIRE + 1] = '.'; pcl = dj.obj.sclust;
  3990. if (fs->fs_type == FS_FAT32 && pcl == fs->dirbase) pcl = 0;
  3991. st_clust(fs, dir + SZDIRE, pcl);
  3992. }
  3993. for (n = fs->csize; n; n--) { /* Write dot entries and clear following sectors */
  3994. fs->winsect = dsc++;
  3995. fs->wflag = 1;
  3996. res = sync_window(fs);
  3997. if (res != FR_OK) break;
  3998. mem_set(dir, 0, SS(fs));
  3999. }
  4000. }
  4001. if (res == FR_OK) {
  4002. res = dir_register(&dj); /* Register the object to the directoy */
  4003. }
  4004. if (res == FR_OK) {
  4005. #if _FS_EXFAT
  4006. if (fs->fs_type == FS_EXFAT) { /* Initialize directory entry block */
  4007. st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Created time */
  4008. st_dword(fs->dirbuf + XDIR_FstClus, dcl); /* Table start cluster */
  4009. st_dword(fs->dirbuf + XDIR_FileSize, (DWORD)dj.obj.objsize); /* File size needs to be valid */
  4010. st_dword(fs->dirbuf + XDIR_ValidFileSize, (DWORD)dj.obj.objsize);
  4011. fs->dirbuf[XDIR_GenFlags] = 3; /* Initialize the object flag (contiguous) */
  4012. fs->dirbuf[XDIR_Attr] = AM_DIR; /* Attribute */
  4013. res = store_xdir(&dj);
  4014. } else
  4015. #endif
  4016. {
  4017. dir = dj.dir;
  4018. st_dword(dir + DIR_ModTime, tm); /* Created time */
  4019. st_clust(fs, dir, dcl); /* Table start cluster */
  4020. dir[DIR_Attr] = AM_DIR; /* Attribute */
  4021. fs->wflag = 1;
  4022. }
  4023. if (res == FR_OK) {
  4024. res = sync_fs(fs);
  4025. }
  4026. } else {
  4027. remove_chain(&dj.obj, dcl, 0); /* Could not register, remove cluster chain */
  4028. }
  4029. }
  4030. FREE_NAMBUF();
  4031. }
  4032. LEAVE_FF(fs, res);
  4033. }
  4034. /*-----------------------------------------------------------------------*/
  4035. /* Rename a File/Directory */
  4036. /*-----------------------------------------------------------------------*/
  4037. FRESULT f_rename (
  4038. const TCHAR* path_old, /* Pointer to the object name to be renamed */
  4039. const TCHAR* path_new /* Pointer to the new name */
  4040. )
  4041. {
  4042. FRESULT res;
  4043. DIR djo, djn;
  4044. FATFS *fs;
  4045. BYTE buf[_FS_EXFAT ? SZDIRE * 2 : 24], *dir;
  4046. DWORD dw;
  4047. DEF_NAMBUF
  4048. get_ldnumber(&path_new); /* Snip drive number of new name off */
  4049. res = find_volume(&path_old, &fs, FA_WRITE); /* Get logical drive of the old object */
  4050. if (res == FR_OK) {
  4051. djo.obj.fs = fs;
  4052. INIT_NAMBUF(fs);
  4053. res = follow_path(&djo, path_old); /* Check old object */
  4054. if (res == FR_OK && (djo.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check validity of name */
  4055. #if _FS_LOCK != 0
  4056. if (res == FR_OK) {
  4057. res = chk_lock(&djo, 2);
  4058. }
  4059. #endif
  4060. if (res == FR_OK) { /* Object to be renamed is found */
  4061. #if _FS_EXFAT
  4062. if (fs->fs_type == FS_EXFAT) { /* At exFAT */
  4063. BYTE nf, nn;
  4064. WORD nh;
  4065. mem_cpy(buf, fs->dirbuf, SZDIRE * 2); /* Save 85+C0 entry of old object */
  4066. mem_cpy(&djn, &djo, sizeof djo);
  4067. res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
  4068. if (res == FR_OK) { /* Is new name already in use by any other object? */
  4069. res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
  4070. }
  4071. if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
  4072. res = dir_register(&djn); /* Register the new entry */
  4073. if (res == FR_OK) {
  4074. nf = fs->dirbuf[XDIR_NumSec]; nn = fs->dirbuf[XDIR_NumName];
  4075. nh = ld_word(fs->dirbuf + XDIR_NameHash);
  4076. mem_cpy(fs->dirbuf, buf, SZDIRE * 2);
  4077. fs->dirbuf[XDIR_NumSec] = nf; fs->dirbuf[XDIR_NumName] = nn;
  4078. st_word(fs->dirbuf + XDIR_NameHash, nh);
  4079. /* Start of critical section where an interruption can cause a cross-link */
  4080. res = store_xdir(&djn);
  4081. }
  4082. }
  4083. } else
  4084. #endif
  4085. { /* At FAT12/FAT16/FAT32 */
  4086. mem_cpy(buf, djo.dir + DIR_Attr, 21); /* Save information about the object except name */
  4087. mem_cpy(&djn, &djo, sizeof (DIR)); /* Duplicate the directory object */
  4088. res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
  4089. if (res == FR_OK) { /* Is new name already in use by any other object? */
  4090. res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
  4091. }
  4092. if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
  4093. res = dir_register(&djn); /* Register the new entry */
  4094. if (res == FR_OK) {
  4095. dir = djn.dir; /* Copy information about object except name */
  4096. mem_cpy(dir + 13, buf + 2, 19);
  4097. dir[DIR_Attr] = buf[0] | AM_ARC;
  4098. fs->wflag = 1;
  4099. if ((dir[DIR_Attr] & AM_DIR) && djo.obj.sclust != djn.obj.sclust) { /* Update .. entry in the sub-directory if needed */
  4100. dw = clust2sect(fs, ld_clust(fs, dir));
  4101. if (!dw) {
  4102. res = FR_INT_ERR;
  4103. } else {
  4104. /* Start of critical section where an interruption can cause a cross-link */
  4105. res = move_window(fs, dw);
  4106. dir = fs->win + SZDIRE * 1; /* Ptr to .. entry */
  4107. if (res == FR_OK && dir[1] == '.') {
  4108. st_clust(fs, dir, djn.obj.sclust);
  4109. fs->wflag = 1;
  4110. }
  4111. }
  4112. }
  4113. }
  4114. }
  4115. }
  4116. if (res == FR_OK) {
  4117. res = dir_remove(&djo); /* Remove old entry */
  4118. if (res == FR_OK) {
  4119. res = sync_fs(fs);
  4120. }
  4121. }
  4122. /* End of the critical section */
  4123. }
  4124. FREE_NAMBUF();
  4125. }
  4126. LEAVE_FF(fs, res);
  4127. }
  4128. #endif /* !_FS_READONLY */
  4129. #endif /* _FS_MINIMIZE == 0 */
  4130. #endif /* _FS_MINIMIZE <= 1 */
  4131. #endif /* _FS_MINIMIZE <= 2 */
  4132. #if _USE_CHMOD && !_FS_READONLY
  4133. /*-----------------------------------------------------------------------*/
  4134. /* Change Attribute */
  4135. /*-----------------------------------------------------------------------*/
  4136. FRESULT f_chmod (
  4137. const TCHAR* path, /* Pointer to the file path */
  4138. BYTE attr, /* Attribute bits */
  4139. BYTE mask /* Attribute mask to change */
  4140. )
  4141. {
  4142. FRESULT res;
  4143. DIR dj;
  4144. FATFS *fs;
  4145. DEF_NAMBUF
  4146. res = find_volume(&path, &fs, FA_WRITE); /* Get logical drive */
  4147. dj.obj.fs = fs;
  4148. if (res == FR_OK) {
  4149. INIT_NAMBUF(fs);
  4150. res = follow_path(&dj, path); /* Follow the file path */
  4151. if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
  4152. if (res == FR_OK) {
  4153. mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
  4154. #if _FS_EXFAT
  4155. if (fs->fs_type == FS_EXFAT) {
  4156. fs->dirbuf[XDIR_Attr] = (attr & mask) | (fs->dirbuf[XDIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  4157. res = store_xdir(&dj);
  4158. } else
  4159. #endif
  4160. {
  4161. dj.dir[DIR_Attr] = (attr & mask) | (dj.dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  4162. fs->wflag = 1;
  4163. }
  4164. if (res == FR_OK) {
  4165. res = sync_fs(fs);
  4166. }
  4167. }
  4168. FREE_NAMBUF();
  4169. }
  4170. LEAVE_FF(fs, res);
  4171. }
  4172. /*-----------------------------------------------------------------------*/
  4173. /* Change Timestamp */
  4174. /*-----------------------------------------------------------------------*/
  4175. FRESULT f_utime (
  4176. const TCHAR* path, /* Pointer to the file/directory name */
  4177. const FILINFO* fno /* Pointer to the time stamp to be set */
  4178. )
  4179. {
  4180. FRESULT res;
  4181. DIR dj;
  4182. FATFS *fs;
  4183. DEF_NAMBUF
  4184. res = find_volume(&path, &fs, FA_WRITE); /* Get logical drive */
  4185. dj.obj.fs = fs;
  4186. if (res == FR_OK) {
  4187. INIT_NAMBUF(fs);
  4188. res = follow_path(&dj, path); /* Follow the file path */
  4189. if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
  4190. if (res == FR_OK) {
  4191. #if _FS_EXFAT
  4192. if (fs->fs_type == FS_EXFAT) {
  4193. st_dword(fs->dirbuf + XDIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
  4194. res = store_xdir(&dj);
  4195. } else
  4196. #endif
  4197. {
  4198. st_dword(dj.dir + DIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
  4199. fs->wflag = 1;
  4200. }
  4201. if (res == FR_OK) {
  4202. res = sync_fs(fs);
  4203. }
  4204. }
  4205. FREE_NAMBUF();
  4206. }
  4207. LEAVE_FF(fs, res);
  4208. }
  4209. #endif /* _USE_CHMOD && !_FS_READONLY */
  4210. #if _USE_LABEL
  4211. /*-----------------------------------------------------------------------*/
  4212. /* Get Volume Label */
  4213. /*-----------------------------------------------------------------------*/
  4214. FRESULT f_getlabel (
  4215. const TCHAR* path, /* Path name of the logical drive number */
  4216. TCHAR* label, /* Pointer to a buffer to return the volume label */
  4217. DWORD* vsn /* Pointer to a variable to return the volume serial number */
  4218. )
  4219. {
  4220. FRESULT res;
  4221. DIR dj;
  4222. FATFS *fs;
  4223. UINT si, di;
  4224. #if _LFN_UNICODE || _FS_EXFAT
  4225. WCHAR w;
  4226. #endif
  4227. /* Get logical drive */
  4228. res = find_volume(&path, &fs, 0);
  4229. /* Get volume label */
  4230. if (res == FR_OK && label) {
  4231. dj.obj.fs = fs; dj.obj.sclust = 0; /* Open root directory */
  4232. res = dir_sdi(&dj, 0);
  4233. if (res == FR_OK) {
  4234. res = dir_read(&dj, 1); /* Find a volume label entry */
  4235. if (res == FR_OK) {
  4236. #if _FS_EXFAT
  4237. if (fs->fs_type == FS_EXFAT) {
  4238. for (si = di = 0; si < dj.dir[XDIR_NumLabel]; si++) { /* Extract volume label from 83 entry */
  4239. w = ld_word(dj.dir + XDIR_Label + si * 2);
  4240. #if _LFN_UNICODE
  4241. label[di++] = w;
  4242. #else
  4243. w = ff_convert(w, 0); /* Unicode -> OEM */
  4244. if (w == 0) w = '?'; /* Replace wrong character */
  4245. if (_DF1S && w >= 0x100) label[di++] = (char)(w >> 8);
  4246. label[di++] = (char)w;
  4247. #endif
  4248. }
  4249. label[di] = 0;
  4250. } else
  4251. #endif
  4252. {
  4253. si = di = 0; /* Extract volume label from AM_VOL entry with code comversion */
  4254. do {
  4255. #if _LFN_UNICODE
  4256. w = (si < 11) ? dj.dir[si++] : ' ';
  4257. if (IsDBCS1(w) && si < 11 && IsDBCS2(dj.dir[si])) {
  4258. w = w << 8 | dj.dir[si++];
  4259. }
  4260. label[di++] = ff_convert(w, 1); /* OEM -> Unicode */
  4261. #else
  4262. label[di++] = dj.dir[si++];
  4263. #endif
  4264. } while (di < 11);
  4265. do { /* Truncate trailing spaces */
  4266. label[di] = 0;
  4267. if (di == 0) break;
  4268. } while (label[--di] == ' ');
  4269. }
  4270. }
  4271. }
  4272. if (res == FR_NO_FILE) { /* No label entry and return nul string */
  4273. label[0] = 0;
  4274. res = FR_OK;
  4275. }
  4276. }
  4277. /* Get volume serial number */
  4278. if (res == FR_OK && vsn) {
  4279. res = move_window(fs, fs->volbase);
  4280. if (res == FR_OK) {
  4281. switch (fs->fs_type) {
  4282. case FS_EXFAT:
  4283. di = BPB_VolIDEx; break;
  4284. case FS_FAT32:
  4285. di = BS_VolID32; break;
  4286. default:
  4287. di = BS_VolID;
  4288. }
  4289. *vsn = ld_dword(fs->win + di);
  4290. }
  4291. }
  4292. LEAVE_FF(fs, res);
  4293. }
  4294. #if !_FS_READONLY
  4295. /*-----------------------------------------------------------------------*/
  4296. /* Set Volume Label */
  4297. /*-----------------------------------------------------------------------*/
  4298. FRESULT f_setlabel (
  4299. const TCHAR* label /* Pointer to the volume label to set */
  4300. )
  4301. {
  4302. FRESULT res;
  4303. DIR dj;
  4304. FATFS *fs;
  4305. BYTE dirvn[22];
  4306. UINT i, j, slen;
  4307. WCHAR w;
  4308. static const char badchr[] = "\"*+,.:;<=>\?[]|\x7F";
  4309. /* Get logical drive */
  4310. res = find_volume(&label, &fs, FA_WRITE);
  4311. if (res != FR_OK) LEAVE_FF(fs, res);
  4312. dj.obj.fs = fs;
  4313. /* Get length of given volume label */
  4314. for (slen = 0; (UINT)label[slen] >= ' '; slen++) ; /* Get name length */
  4315. #if _FS_EXFAT
  4316. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  4317. for (i = j = 0; i < slen; ) { /* Create volume label in directory form */
  4318. w = label[i++];
  4319. #if !_LFN_UNICODE
  4320. if (IsDBCS1(w)) {
  4321. w = (i < slen && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0;
  4322. }
  4323. w = ff_convert(w, 1);
  4324. #endif
  4325. if (w == 0 || chk_chr(badchr, w) || j == 22) { /* Check validity check validity of the volume label */
  4326. LEAVE_FF(fs, FR_INVALID_NAME);
  4327. }
  4328. st_word(dirvn + j, w); j += 2;
  4329. }
  4330. slen = j;
  4331. } else
  4332. #endif
  4333. { /* On the FAT12/16/32 volume */
  4334. for ( ; slen && label[slen - 1] == ' '; slen--) ; /* Remove trailing spaces */
  4335. if (slen) { /* Is there a volume label to be set? */
  4336. dirvn[0] = 0; i = j = 0; /* Create volume label in directory form */
  4337. do {
  4338. #if _LFN_UNICODE
  4339. w = ff_convert(ff_wtoupper(label[i++]), 0);
  4340. #else
  4341. w = (BYTE)label[i++];
  4342. if (IsDBCS1(w)) {
  4343. w = (j < 10 && i < slen && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0;
  4344. }
  4345. #if _USE_LFN != 0
  4346. w = ff_convert(ff_wtoupper(ff_convert(w, 1)), 0);
  4347. #else
  4348. if (IsLower(w)) w -= 0x20; /* To upper ASCII characters */
  4349. #ifdef _EXCVT
  4350. if (w >= 0x80) w = ExCvt[w - 0x80]; /* To upper extended characters (SBCS cfg) */
  4351. #else
  4352. if (!_DF1S && w >= 0x80) w = 0; /* Reject extended characters (ASCII cfg) */
  4353. #endif
  4354. #endif
  4355. #endif
  4356. if (w == 0 || chk_chr(badchr, w) || j >= (UINT)((w >= 0x100) ? 10 : 11)) { /* Reject invalid characters for volume label */
  4357. LEAVE_FF(fs, FR_INVALID_NAME);
  4358. }
  4359. if (w >= 0x100) dirvn[j++] = (BYTE)(w >> 8);
  4360. dirvn[j++] = (BYTE)w;
  4361. } while (i < slen);
  4362. while (j < 11) dirvn[j++] = ' '; /* Fill remaining name field */
  4363. if (dirvn[0] == DDEM) LEAVE_FF(fs, FR_INVALID_NAME); /* Reject illegal name (heading DDEM) */
  4364. }
  4365. }
  4366. /* Set volume label */
  4367. dj.obj.sclust = 0; /* Open root directory */
  4368. res = dir_sdi(&dj, 0);
  4369. if (res == FR_OK) {
  4370. res = dir_read(&dj, 1); /* Get volume label entry */
  4371. if (res == FR_OK) {
  4372. if (_FS_EXFAT && fs->fs_type == FS_EXFAT) {
  4373. dj.dir[XDIR_NumLabel] = (BYTE)(slen / 2); /* Change the volume label */
  4374. mem_cpy(dj.dir + XDIR_Label, dirvn, slen);
  4375. } else {
  4376. if (slen) {
  4377. mem_cpy(dj.dir, dirvn, 11); /* Change the volume label */
  4378. } else {
  4379. dj.dir[DIR_Name] = DDEM; /* Remove the volume label */
  4380. }
  4381. }
  4382. fs->wflag = 1;
  4383. res = sync_fs(fs);
  4384. } else { /* No volume label entry is found or error */
  4385. if (res == FR_NO_FILE) {
  4386. res = FR_OK;
  4387. if (slen) { /* Create a volume label entry */
  4388. res = dir_alloc(&dj, 1); /* Allocate an entry */
  4389. if (res == FR_OK) {
  4390. mem_set(dj.dir, 0, SZDIRE); /* Clear the entry */
  4391. if (_FS_EXFAT && fs->fs_type == FS_EXFAT) {
  4392. dj.dir[XDIR_Type] = 0x83; /* Create 83 entry */
  4393. dj.dir[XDIR_NumLabel] = (BYTE)(slen / 2);
  4394. mem_cpy(dj.dir + XDIR_Label, dirvn, slen);
  4395. } else {
  4396. dj.dir[DIR_Attr] = AM_VOL; /* Create volume label entry */
  4397. mem_cpy(dj.dir, dirvn, 11);
  4398. }
  4399. fs->wflag = 1;
  4400. res = sync_fs(fs);
  4401. }
  4402. }
  4403. }
  4404. }
  4405. }
  4406. LEAVE_FF(fs, res);
  4407. }
  4408. #endif /* !_FS_READONLY */
  4409. #endif /* _USE_LABEL */
  4410. #if _USE_EXPAND && !_FS_READONLY
  4411. /*-----------------------------------------------------------------------*/
  4412. /* Allocate a Contiguous Blocks to the File */
  4413. /*-----------------------------------------------------------------------*/
  4414. FRESULT f_expand (
  4415. FIL* fp, /* Pointer to the file object */
  4416. FSIZE_t fsz, /* File size to be expanded to */
  4417. BYTE opt /* Operation mode 0:Find and prepare or 1:Find and allocate */
  4418. )
  4419. {
  4420. FRESULT res;
  4421. FATFS *fs;
  4422. DWORD n, clst, stcl, scl, ncl, tcl, lclst;
  4423. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  4424. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  4425. if (fsz == 0 || fp->obj.objsize != 0 || !(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED);
  4426. #if _FS_EXFAT
  4427. if (fs->fs_type != FS_EXFAT && fsz >= 0x100000000) LEAVE_FF(fs, FR_DENIED); /* Check if in size limit */
  4428. #endif
  4429. n = (DWORD)fs->csize * SS(fs); /* Cluster size */
  4430. tcl = (DWORD)(fsz / n) + ((fsz & (n - 1)) ? 1 : 0); /* Number of clusters required */
  4431. stcl = fs->last_clst; lclst = 0;
  4432. if (stcl < 2 || stcl >= fs->n_fatent) stcl = 2;
  4433. #if _FS_EXFAT
  4434. if (fs->fs_type == FS_EXFAT) {
  4435. scl = find_bitmap(fs, stcl, tcl); /* Find a contiguous cluster block */
  4436. if (scl == 0) res = FR_DENIED; /* No contiguous cluster block was found */
  4437. if (scl == 0xFFFFFFFF) res = FR_DISK_ERR;
  4438. if (res == FR_OK) { /* A contiguous free area is found */
  4439. if (opt) { /* Allocate it now */
  4440. res = change_bitmap(fs, scl, tcl, 1); /* Mark the cluster block 'in use' */
  4441. lclst = scl + tcl - 1;
  4442. } else { /* Set it as suggested point for next allocation */
  4443. lclst = scl - 1;
  4444. }
  4445. }
  4446. } else
  4447. #endif
  4448. {
  4449. scl = clst = stcl; ncl = 0;
  4450. for (;;) { /* Find a contiguous cluster block */
  4451. n = get_fat(&fp->obj, clst);
  4452. if (++clst >= fs->n_fatent) clst = 2;
  4453. if (n == 1) { res = FR_INT_ERR; break; }
  4454. if (n == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
  4455. if (n == 0) { /* Is it a free cluster? */
  4456. if (++ncl == tcl) break; /* Break if a contiguous cluster block is found */
  4457. } else {
  4458. scl = clst; ncl = 0; /* Not a free cluster */
  4459. }
  4460. if (clst == stcl) { res = FR_DENIED; break; } /* No contiguous cluster? */
  4461. }
  4462. if (res == FR_OK) { /* A contiguous free area is found */
  4463. if (opt) { /* Allocate it now */
  4464. for (clst = scl, n = tcl; n; clst++, n--) { /* Create a cluster chain on the FAT */
  4465. res = put_fat(fs, clst, (n == 1) ? 0xFFFFFFFF : clst + 1);
  4466. if (res != FR_OK) break;
  4467. lclst = clst;
  4468. }
  4469. } else { /* Set it as suggested point for next allocation */
  4470. lclst = scl - 1;
  4471. }
  4472. }
  4473. }
  4474. if (res == FR_OK) {
  4475. fs->last_clst = lclst; /* Set suggested start cluster to start next */
  4476. if (opt) { /* Is it allocated now? */
  4477. fp->obj.sclust = scl; /* Update object allocation information */
  4478. fp->obj.objsize = fsz;
  4479. if (_FS_EXFAT) fp->obj.stat = 2; /* Set status 'contiguous chain' */
  4480. fp->flag |= FA_MODIFIED;
  4481. if (fs->free_clst <= fs->n_fatent - 2) { /* Update FSINFO */
  4482. fs->free_clst -= tcl;
  4483. fs->fsi_flag |= 1;
  4484. }
  4485. }
  4486. }
  4487. LEAVE_FF(fs, res);
  4488. }
  4489. #endif /* _USE_EXPAND && !_FS_READONLY */
  4490. #if _USE_FORWARD
  4491. /*-----------------------------------------------------------------------*/
  4492. /* Forward data to the stream directly */
  4493. /*-----------------------------------------------------------------------*/
  4494. FRESULT f_forward (
  4495. FIL* fp, /* Pointer to the file object */
  4496. UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
  4497. UINT btf, /* Number of bytes to forward */
  4498. UINT* bf /* Pointer to number of bytes forwarded */
  4499. )
  4500. {
  4501. FRESULT res;
  4502. FATFS *fs;
  4503. DWORD clst, sect;
  4504. FSIZE_t remain;
  4505. UINT rcnt, csect;
  4506. BYTE *dbuf;
  4507. *bf = 0; /* Clear transfer byte counter */
  4508. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  4509. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  4510. if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  4511. remain = fp->obj.objsize - fp->fptr;
  4512. if (btf > remain) btf = (UINT)remain; /* Truncate btf by remaining bytes */
  4513. for ( ; btf && (*func)(0, 0); /* Repeat until all data transferred or stream goes busy */
  4514. fp->fptr += rcnt, *bf += rcnt, btf -= rcnt) {
  4515. csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
  4516. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  4517. if (csect == 0) { /* On the cluster boundary? */
  4518. clst = (fp->fptr == 0) ? /* On the top of the file? */
  4519. fp->obj.sclust : get_fat(&fp->obj, fp->clust);
  4520. if (clst <= 1) ABORT(fs, FR_INT_ERR);
  4521. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  4522. fp->clust = clst; /* Update current cluster */
  4523. }
  4524. }
  4525. sect = clust2sect(fs, fp->clust); /* Get current data sector */
  4526. if (!sect) ABORT(fs, FR_INT_ERR);
  4527. sect += csect;
  4528. #if _FS_TINY
  4529. if (move_window(fs, sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window to the file data */
  4530. dbuf = fs->win;
  4531. #else
  4532. if (fp->sect != sect) { /* Fill sector cache with file data */
  4533. #if !_FS_READONLY
  4534. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  4535. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  4536. fp->flag &= (BYTE)~FA_DIRTY;
  4537. }
  4538. #endif
  4539. if (disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  4540. }
  4541. dbuf = fp->buf;
  4542. #endif
  4543. fp->sect = sect;
  4544. rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */
  4545. if (rcnt > btf) rcnt = btf; /* Clip it by btr if needed */
  4546. rcnt = (*func)(dbuf + ((UINT)fp->fptr % SS(fs)), rcnt); /* Forward the file data */
  4547. if (!rcnt) ABORT(fs, FR_INT_ERR);
  4548. }
  4549. LEAVE_FF(fs, FR_OK);
  4550. }
  4551. #endif /* _USE_FORWARD */
  4552. #if _USE_MKFS && !_FS_READONLY
  4553. /*-----------------------------------------------------------------------*/
  4554. /* Create an FAT/exFAT volume */
  4555. /*-----------------------------------------------------------------------*/
  4556. FRESULT f_mkfs (
  4557. const TCHAR* path, /* Logical drive number */
  4558. BYTE opt, /* Format option */
  4559. DWORD au, /* Size of allocation unit (cluster) [byte] */
  4560. void* work, /* Pointer to working buffer */
  4561. UINT len /* Size of working buffer */
  4562. )
  4563. {
  4564. const UINT n_fats = 1; /* Number of FATs for FAT12/16/32 volume (1 or 2) */
  4565. const UINT n_rootdir = 512; /* Number of root directory entries for FAT12/16 volume */
  4566. static const WORD cst[] = {1, 4, 16, 64, 256, 512, 0}; /* Cluster size boundary for FAT12/16 volume (4Ks unit) */
  4567. static const WORD cst32[] = {1, 2, 4, 8, 16, 32, 0}; /* Cluster size boundary for FAT32 volume (128Ks unit) */
  4568. BYTE fmt, sys, *buf, *pte, pdrv, part;
  4569. WORD ss;
  4570. DWORD szb_buf, sz_buf, sz_blk, n_clst, pau, sect, nsect, n;
  4571. DWORD b_vol, b_fat, b_data; /* Base LBA for volume, fat, data */
  4572. DWORD sz_vol, sz_rsv, sz_fat, sz_dir; /* Size for volume, fat, dir, data */
  4573. UINT i;
  4574. int vol;
  4575. DSTATUS stat;
  4576. #if _USE_TRIM || _FS_EXFAT
  4577. DWORD tbl[3];
  4578. #endif
  4579. /* Check mounted drive and clear work area */
  4580. vol = get_ldnumber(&path); /* Get target logical drive */
  4581. if (vol < 0) return FR_INVALID_DRIVE;
  4582. if (FatFs[vol]) FatFs[vol]->fs_type = 0; /* Clear the volume */
  4583. pdrv = LD2PD(vol); /* Physical drive */
  4584. part = LD2PT(vol); /* Partition (0:create as new, 1-4:get from partition table) */
  4585. /* Check physical drive status */
  4586. stat = disk_initialize(pdrv);
  4587. if (stat & STA_NOINIT) return FR_NOT_READY;
  4588. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  4589. if (disk_ioctl(pdrv, GET_BLOCK_SIZE, &sz_blk) != RES_OK || !sz_blk || sz_blk > 32768 || (sz_blk & (sz_blk - 1))) sz_blk = 1; /* Erase block to align data area */
  4590. #if _MAX_SS != _MIN_SS /* Get sector size of the medium if variable sector size cfg. */
  4591. if (disk_ioctl(pdrv, GET_SECTOR_SIZE, &ss) != RES_OK) return FR_DISK_ERR;
  4592. if (ss > _MAX_SS || ss < _MIN_SS || (ss & (ss - 1))) return FR_DISK_ERR;
  4593. #else
  4594. ss = _MAX_SS;
  4595. #endif
  4596. if ((au != 0 && au < ss) || au > 0x1000000 || (au & (au - 1))) return FR_INVALID_PARAMETER; /* Check if au is valid */
  4597. au /= ss; /* Cluster size in unit of sector */
  4598. /* Get working buffer */
  4599. buf = (BYTE*)work; /* Working buffer */
  4600. sz_buf = len / ss; /* Size of working buffer (sector) */
  4601. szb_buf = sz_buf * ss; /* Size of working buffer (byte) */
  4602. if (!szb_buf) return FR_MKFS_ABORTED;
  4603. /* Determine where the volume to be located (b_vol, sz_vol) */
  4604. if (_MULTI_PARTITION && part != 0) {
  4605. /* Get partition information from partition table in the MBR */
  4606. if (disk_read(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Load MBR */
  4607. if (ld_word(buf + BS_55AA) != 0xAA55) return FR_MKFS_ABORTED; /* Check if MBR is valid */
  4608. pte = buf + (MBR_Table + (part - 1) * SZ_PTE);
  4609. if (!pte[PTE_System]) return FR_MKFS_ABORTED; /* No partition? */
  4610. b_vol = ld_dword(pte + PTE_StLba); /* Get volume start sector */
  4611. sz_vol = ld_dword(pte + PTE_SizLba); /* Get volume size */
  4612. } else {
  4613. /* Create a single-partition in this function */
  4614. if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_vol) != RES_OK) return FR_DISK_ERR;
  4615. b_vol = (opt & FM_SFD) ? 0 : 63; /* Volume start sector */
  4616. if (sz_vol < b_vol) return FR_MKFS_ABORTED;
  4617. sz_vol -= b_vol; /* Volume size */
  4618. }
  4619. if (sz_vol < 128) return FR_MKFS_ABORTED; /* Check if volume size is >=128s */
  4620. /* Pre-determine the FAT type */
  4621. do {
  4622. if (_FS_EXFAT && (opt & FM_EXFAT)) { /* exFAT possible? */
  4623. if ((opt & FM_ANY) == FM_EXFAT || sz_vol >= 0x4000000 || au > 128) { /* exFAT only, vol >= 64Ms or au > 128s ? */
  4624. fmt = FS_EXFAT; break;
  4625. }
  4626. }
  4627. if (au > 128) return FR_INVALID_PARAMETER; /* Too large au for FAT/FAT32 */
  4628. if (opt & FM_FAT32) { /* FAT32 possible? */
  4629. if ((opt & FM_ANY) == FM_FAT32 || !(opt & FM_FAT)) { /* FAT32 only or no-FAT? */
  4630. fmt = FS_FAT32; break;
  4631. }
  4632. }
  4633. if (!(opt & FM_FAT)) return FR_INVALID_PARAMETER; /* no-FAT? */
  4634. fmt = FS_FAT16;
  4635. } while (0);
  4636. #if _FS_EXFAT
  4637. if (fmt == FS_EXFAT) { /* Create an exFAT volume */
  4638. DWORD szb_bit, szb_case, sum, nb, cl;
  4639. WCHAR ch, si;
  4640. UINT j, st;
  4641. BYTE b;
  4642. if (sz_vol < 0x1000) return FR_MKFS_ABORTED; /* Too small volume? */
  4643. #if _USE_TRIM
  4644. tbl[0] = b_vol; tbl[1] = b_vol + sz_vol - 1; /* Inform the device the volume area may be erased */
  4645. disk_ioctl(pdrv, CTRL_TRIM, tbl);
  4646. #endif
  4647. /* Determine FAT location, data location and number of clusters */
  4648. if (!au) { /* au auto-selection */
  4649. au = 8;
  4650. if (sz_vol >= 0x80000) au = 64; /* >= 512Ks */
  4651. if (sz_vol >= 0x4000000) au = 256; /* >= 64Ms */
  4652. }
  4653. b_fat = b_vol + 32; /* FAT start at offset 32 */
  4654. sz_fat = ((sz_vol / au + 2) * 4 + ss - 1) / ss; /* Number of FAT sectors */
  4655. b_data = (b_fat + sz_fat + sz_blk - 1) & ~(sz_blk - 1); /* Align data area to the erase block boundary */
  4656. if (b_data >= sz_vol / 2) return FR_MKFS_ABORTED; /* Too small volume? */
  4657. n_clst = (sz_vol - (b_data - b_vol)) / au; /* Number of clusters */
  4658. if (n_clst <16) return FR_MKFS_ABORTED; /* Too few clusters? */
  4659. if (n_clst > MAX_EXFAT) return FR_MKFS_ABORTED; /* Too many clusters? */
  4660. szb_bit = (n_clst + 7) / 8; /* Size of allocation bitmap */
  4661. tbl[0] = (szb_bit + au * ss - 1) / (au * ss); /* Number of allocation bitmap clusters */
  4662. /* Create a compressed up-case table */
  4663. sect = b_data + au * tbl[0]; /* Table start sector */
  4664. sum = 0; /* Table checksum to be stored in the 82 entry */
  4665. st = si = i = j = szb_case = 0;
  4666. do {
  4667. switch (st) {
  4668. case 0:
  4669. ch = ff_wtoupper(si); /* Get an up-case char */
  4670. if (ch != si) {
  4671. si++; break; /* Store the up-case char if exist */
  4672. }
  4673. for (j = 1; (WCHAR)(si + j) && (WCHAR)(si + j) == ff_wtoupper((WCHAR)(si + j)); j++) ; /* Get run length of no-case block */
  4674. if (j >= 128) {
  4675. ch = 0xFFFF; st = 2; break; /* Compress the no-case block if run is >= 128 */
  4676. }
  4677. st = 1; /* Do not compress short run */
  4678. /* go to next case */
  4679. case 1:
  4680. ch = si++; /* Fill the short run */
  4681. if (--j == 0) st = 0;
  4682. break;
  4683. default:
  4684. ch = (WCHAR)j; si += j; /* Number of chars to skip */
  4685. st = 0;
  4686. }
  4687. sum = xsum32(buf[i + 0] = (BYTE)ch, sum); /* Put it into the write buffer */
  4688. sum = xsum32(buf[i + 1] = (BYTE)(ch >> 8), sum);
  4689. i += 2; szb_case += 2;
  4690. if (!si || i == szb_buf) { /* Write buffered data when buffer full or end of process */
  4691. n = (i + ss - 1) / ss;
  4692. if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
  4693. sect += n; i = 0;
  4694. }
  4695. } while (si);
  4696. tbl[1] = (szb_case + au * ss - 1) / (au * ss); /* Number of up-case table clusters */
  4697. tbl[2] = 1; /* Number of root dir clusters */
  4698. /* Initialize the allocation bitmap */
  4699. sect = b_data; nsect = (szb_bit + ss - 1) / ss; /* Start of bitmap and number of sectors */
  4700. nb = tbl[0] + tbl[1] + tbl[2]; /* Number of clusters in-use by system */
  4701. do {
  4702. mem_set(buf, 0, szb_buf);
  4703. for (i = 0; nb >= 8 && i < szb_buf; buf[i++] = 0xFF, nb -= 8) ;
  4704. for (b = 1; nb && i < szb_buf; buf[i] |= b, b <<= 1, nb--) ;
  4705. n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
  4706. if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
  4707. sect += n; nsect -= n;
  4708. } while (nsect);
  4709. /* Initialize the FAT */
  4710. sect = b_fat; nsect = sz_fat; /* Start of FAT and number of FAT sectors */
  4711. j = nb = cl = 0;
  4712. do {
  4713. mem_set(buf, 0, szb_buf); i = 0; /* Clear work area and reset write index */
  4714. if (cl == 0) { /* Set entry 0 and 1 */
  4715. st_dword(buf + i, 0xFFFFFFF8); i += 4; cl++;
  4716. st_dword(buf + i, 0xFFFFFFFF); i += 4; cl++;
  4717. }
  4718. do { /* Create chains of bitmap, up-case and root dir */
  4719. while (nb && i < szb_buf) { /* Create a chain */
  4720. st_dword(buf + i, (nb > 1) ? cl + 1 : 0xFFFFFFFF);
  4721. i += 4; cl++; nb--;
  4722. }
  4723. if (!nb && j < 3) nb = tbl[j++]; /* Next chain */
  4724. } while (nb && i < szb_buf);
  4725. n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
  4726. if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
  4727. sect += n; nsect -= n;
  4728. } while (nsect);
  4729. /* Initialize the root directory */
  4730. mem_set(buf, 0, szb_buf);
  4731. buf[SZDIRE * 0 + 0] = 0x83; /* 83 entry (volume label) */
  4732. buf[SZDIRE * 1 + 0] = 0x81; /* 81 entry (allocation bitmap) */
  4733. st_dword(buf + SZDIRE * 1 + 20, 2);
  4734. st_dword(buf + SZDIRE * 1 + 24, szb_bit);
  4735. buf[SZDIRE * 2 + 0] = 0x82; /* 82 entry (up-case table) */
  4736. st_dword(buf + SZDIRE * 2 + 4, sum);
  4737. st_dword(buf + SZDIRE * 2 + 20, 2 + tbl[0]);
  4738. st_dword(buf + SZDIRE * 2 + 24, szb_case);
  4739. sect = b_data + au * (tbl[0] + tbl[1]); nsect = au; /* Start of the root directory and number of sectors */
  4740. do { /* Fill root directory sectors */
  4741. n = (nsect > sz_buf) ? sz_buf : nsect;
  4742. if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
  4743. mem_set(buf, 0, ss);
  4744. sect += n; nsect -= n;
  4745. } while (nsect);
  4746. /* Create two set of the exFAT VBR blocks */
  4747. sect = b_vol;
  4748. for (n = 0; n < 2; n++) {
  4749. /* Main record (+0) */
  4750. mem_set(buf, 0, ss);
  4751. mem_cpy(buf + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11); /* Boot jump code (x86), OEM name */
  4752. st_dword(buf + BPB_VolOfsEx, b_vol); /* Volume offset in the physical drive [sector] */
  4753. st_dword(buf + BPB_TotSecEx, sz_vol); /* Volume size [sector] */
  4754. st_dword(buf + BPB_FatOfsEx, b_fat - b_vol); /* FAT offset [sector] */
  4755. st_dword(buf + BPB_FatSzEx, sz_fat); /* FAT size [sector] */
  4756. st_dword(buf + BPB_DataOfsEx, b_data - b_vol); /* Data offset [sector] */
  4757. st_dword(buf + BPB_NumClusEx, n_clst); /* Number of clusters */
  4758. st_dword(buf + BPB_RootClusEx, 2 + tbl[0] + tbl[1]); /* Root dir cluster # */
  4759. st_dword(buf + BPB_VolIDEx, GET_FATTIME()); /* VSN */
  4760. st_word(buf + BPB_FSVerEx, 0x100); /* File system version (1.00) */
  4761. for (buf[BPB_BytsPerSecEx] = 0, i = ss; i >>= 1; buf[BPB_BytsPerSecEx]++) ; /* Log2 of sector size [byte] */
  4762. for (buf[BPB_SecPerClusEx] = 0, i = au; i >>= 1; buf[BPB_SecPerClusEx]++) ; /* Log2 of cluster size [sector] */
  4763. buf[BPB_NumFATsEx] = 1; /* Number of FATs */
  4764. buf[BPB_DrvNumEx] = 0x80; /* Drive number (for int13) */
  4765. st_word(buf + BS_BootCodeEx, 0xFEEB); /* Boot code (x86) */
  4766. st_word(buf + BS_55AA, 0xAA55); /* Signature (placed here regardless of sector size) */
  4767. for (i = sum = 0; i < ss; i++) { /* VBR checksum */
  4768. if (i != BPB_VolFlagEx && i != BPB_VolFlagEx + 1 && i != BPB_PercInUseEx) sum = xsum32(buf[i], sum);
  4769. }
  4770. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
  4771. /* Extended bootstrap record (+1..+8) */
  4772. mem_set(buf, 0, ss);
  4773. st_word(buf + ss - 2, 0xAA55); /* Signature (placed at end of sector) */
  4774. for (j = 1; j < 9; j++) {
  4775. for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
  4776. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
  4777. }
  4778. /* OEM/Reserved record (+9..+10) */
  4779. mem_set(buf, 0, ss);
  4780. for ( ; j < 11; j++) {
  4781. for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
  4782. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
  4783. }
  4784. /* Sum record (+11) */
  4785. for (i = 0; i < ss; i += 4) st_dword(buf + i, sum); /* Fill with checksum value */
  4786. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
  4787. }
  4788. } else
  4789. #endif /* _FS_EXFAT */
  4790. { /* Create an FAT12/16/32 volume */
  4791. do {
  4792. pau = au;
  4793. /* Pre-determine number of clusters and FAT sub-type */
  4794. if (fmt == FS_FAT32) { /* FAT32 volume */
  4795. if (!pau) { /* au auto-selection */
  4796. n = sz_vol / 0x20000; /* Volume size in unit of 128KS */
  4797. for (i = 0, pau = 1; cst32[i] && cst32[i] <= n; i++, pau <<= 1) ; /* Get from table */
  4798. }
  4799. n_clst = sz_vol / pau; /* Number of clusters */
  4800. sz_fat = (n_clst * 4 + 8 + ss - 1) / ss; /* FAT size [sector] */
  4801. sz_rsv = 32; /* Number of reserved sectors */
  4802. sz_dir = 0; /* No static directory */
  4803. if (n_clst <= MAX_FAT16 || n_clst > MAX_FAT32) return FR_MKFS_ABORTED;
  4804. } else { /* FAT12/16 volume */
  4805. if (!pau) { /* au auto-selection */
  4806. n = sz_vol / 0x1000; /* Volume size in unit of 4KS */
  4807. for (i = 0, pau = 1; cst[i] && cst[i] <= n; i++, pau <<= 1) ; /* Get from table */
  4808. }
  4809. n_clst = sz_vol / pau;
  4810. if (n_clst > MAX_FAT12) {
  4811. n = n_clst * 2 + 4; /* FAT size [byte] */
  4812. } else {
  4813. fmt = FS_FAT12;
  4814. n = (n_clst * 3 + 1) / 2 + 3; /* FAT size [byte] */
  4815. }
  4816. sz_fat = (n + ss - 1) / ss; /* FAT size [sector] */
  4817. sz_rsv = 1; /* Number of reserved sectors */
  4818. sz_dir = (DWORD)n_rootdir * SZDIRE / ss; /* Rootdir size [sector] */
  4819. }
  4820. b_fat = b_vol + sz_rsv; /* FAT base */
  4821. b_data = b_fat + sz_fat * n_fats + sz_dir; /* Data base */
  4822. /* Align data base to erase block boundary (for flash memory media) */
  4823. n = ((b_data + sz_blk - 1) & ~(sz_blk - 1)) - b_data; /* Next nearest erase block from current data base */
  4824. if (fmt == FS_FAT32) { /* FAT32: Move FAT base */
  4825. sz_rsv += n; b_fat += n;
  4826. } else { /* FAT12/16: Expand FAT size */
  4827. sz_fat += n / n_fats;
  4828. }
  4829. /* Determine number of clusters and final check of validity of the FAT sub-type */
  4830. if (sz_vol < b_data + pau * 16 - b_vol) return FR_MKFS_ABORTED; /* Too small volume */
  4831. n_clst = (sz_vol - sz_rsv - sz_fat * n_fats - sz_dir) / pau;
  4832. if (fmt == FS_FAT32) {
  4833. if (n_clst <= MAX_FAT16) { /* Too few clusters for FAT32 */
  4834. if (!au && (au = pau / 2) != 0) continue; /* Adjust cluster size and retry */
  4835. return FR_MKFS_ABORTED;
  4836. }
  4837. }
  4838. if (fmt == FS_FAT16) {
  4839. if (n_clst > MAX_FAT16) { /* Too many clusters for FAT16 */
  4840. if (!au && (pau * 2) <= 64) {
  4841. au = pau * 2; continue; /* Adjust cluster size and retry */
  4842. }
  4843. if ((opt & FM_FAT32)) {
  4844. fmt = FS_FAT32; continue; /* Switch type to FAT32 and retry */
  4845. }
  4846. if (!au && (au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
  4847. return FR_MKFS_ABORTED;
  4848. }
  4849. if (n_clst <= MAX_FAT12) { /* Too few clusters for FAT16 */
  4850. if (!au && (au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
  4851. return FR_MKFS_ABORTED;
  4852. }
  4853. }
  4854. if (fmt == FS_FAT12 && n_clst > MAX_FAT12) return FR_MKFS_ABORTED; /* Too many clusters for FAT12 */
  4855. /* Ok, it is the valid cluster configuration */
  4856. break;
  4857. } while (1);
  4858. #if _USE_TRIM
  4859. tbl[0] = b_vol; tbl[1] = b_vol + sz_vol - 1; /* Inform the device the volume area can be erased */
  4860. disk_ioctl(pdrv, CTRL_TRIM, tbl);
  4861. #endif
  4862. /* Create FAT VBR */
  4863. mem_set(buf, 0, ss);
  4864. mem_cpy(buf + BS_JmpBoot, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code (x86), OEM name */
  4865. st_word(buf + BPB_BytsPerSec, ss); /* Sector size [byte] */
  4866. buf[BPB_SecPerClus] = (BYTE)pau; /* Cluster size [sector] */
  4867. st_word(buf + BPB_RsvdSecCnt, (WORD)sz_rsv); /* Size of reserved area */
  4868. buf[BPB_NumFATs] = (BYTE)n_fats; /* Number of FATs */
  4869. st_word(buf + BPB_RootEntCnt, (WORD)((fmt == FS_FAT32) ? 0 : n_rootdir)); /* Number of root directory entries */
  4870. if (sz_vol < 0x10000) {
  4871. st_word(buf + BPB_TotSec16, (WORD)sz_vol); /* Volume size in 16-bit LBA */
  4872. } else {
  4873. st_dword(buf + BPB_TotSec32, sz_vol); /* Volume size in 32-bit LBA */
  4874. }
  4875. buf[BPB_Media] = 0xF8; /* Media descriptor byte */
  4876. st_word(buf + BPB_SecPerTrk, 63); /* Number of sectors per track (for int13) */
  4877. st_word(buf + BPB_NumHeads, 255); /* Number of heads (for int13) */
  4878. st_dword(buf + BPB_HiddSec, b_vol); /* Volume offset in the physical drive [sector] */
  4879. if (fmt == FS_FAT32) {
  4880. st_dword(buf + BS_VolID32, GET_FATTIME()); /* VSN */
  4881. st_dword(buf + BPB_FATSz32, sz_fat); /* FAT size [sector] */
  4882. st_dword(buf + BPB_RootClus32, 2); /* Root directory cluster # (2) */
  4883. st_word(buf + BPB_FSInfo32, 1); /* Offset of FSINFO sector (VBR + 1) */
  4884. st_word(buf + BPB_BkBootSec32, 6); /* Offset of backup VBR (VBR + 6) */
  4885. buf[BS_DrvNum32] = 0x80; /* Drive number (for int13) */
  4886. buf[BS_BootSig32] = 0x29; /* Extended boot signature */
  4887. mem_cpy(buf + BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */
  4888. } else {
  4889. st_dword(buf + BS_VolID, GET_FATTIME()); /* VSN */
  4890. st_word(buf + BPB_FATSz16, (WORD)sz_fat); /* FAT size [sector] */
  4891. buf[BS_DrvNum] = 0x80; /* Drive number (for int13) */
  4892. buf[BS_BootSig] = 0x29; /* Extended boot signature */
  4893. mem_cpy(buf + BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */
  4894. }
  4895. st_word(buf + BS_55AA, 0xAA55); /* Signature (offset is fixed here regardless of sector size) */
  4896. if (disk_write(pdrv, buf, b_vol, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the VBR sector */
  4897. /* Create FSINFO record if needed */
  4898. if (fmt == FS_FAT32) {
  4899. disk_write(pdrv, buf, b_vol + 6, 1); /* Write backup VBR (VBR + 6) */
  4900. mem_set(buf, 0, ss);
  4901. st_dword(buf + FSI_LeadSig, 0x41615252);
  4902. st_dword(buf + FSI_StrucSig, 0x61417272);
  4903. st_dword(buf + FSI_Free_Count, n_clst - 1); /* Number of free clusters */
  4904. st_dword(buf + FSI_Nxt_Free, 2); /* Last allocated cluster# */
  4905. st_word(buf + BS_55AA, 0xAA55);
  4906. disk_write(pdrv, buf, b_vol + 7, 1); /* Write backup FSINFO (VBR + 7) */
  4907. disk_write(pdrv, buf, b_vol + 1, 1); /* Write original FSINFO (VBR + 1) */
  4908. }
  4909. /* Initialize FAT area */
  4910. mem_set(buf, 0, (UINT)szb_buf);
  4911. sect = b_fat; /* FAT start sector */
  4912. for (i = 0; i < n_fats; i++) { /* Initialize FATs each */
  4913. if (fmt == FS_FAT32) {
  4914. st_dword(buf + 0, 0xFFFFFFF8); /* Entry 0 */
  4915. st_dword(buf + 4, 0xFFFFFFFF); /* Entry 1 */
  4916. st_dword(buf + 8, 0x0FFFFFFF); /* Entry 2 (root directory) */
  4917. } else {
  4918. st_dword(buf + 0, (fmt == FS_FAT12) ? 0xFFFFF8 : 0xFFFFFFF8); /* Entry 0 and 1 */
  4919. }
  4920. nsect = sz_fat; /* Number of FAT sectors */
  4921. do { /* Fill FAT sectors */
  4922. n = (nsect > sz_buf) ? sz_buf : nsect;
  4923. if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) return FR_DISK_ERR;
  4924. mem_set(buf, 0, ss);
  4925. sect += n; nsect -= n;
  4926. } while (nsect);
  4927. }
  4928. /* Initialize root directory (fill with zero) */
  4929. nsect = (fmt == FS_FAT32) ? pau : sz_dir; /* Number of root directory sectors */
  4930. do {
  4931. n = (nsect > sz_buf) ? sz_buf : nsect;
  4932. if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) return FR_DISK_ERR;
  4933. sect += n; nsect -= n;
  4934. } while (nsect);
  4935. }
  4936. /* Determine system ID in the partition table */
  4937. if (_FS_EXFAT && fmt == FS_EXFAT) {
  4938. sys = 0x07; /* HPFS/NTFS/exFAT */
  4939. } else {
  4940. if (fmt == FS_FAT32) {
  4941. sys = 0x0C; /* FAT32X */
  4942. } else {
  4943. if (sz_vol >= 0x10000) {
  4944. sys = 0x06; /* FAT12/16 (>=64KS) */
  4945. } else {
  4946. sys = (fmt == FS_FAT16) ? 0x04 : 0x01; /* FAT16 (<64KS) : FAT12 (<64KS) */
  4947. }
  4948. }
  4949. }
  4950. /* Update partition information */
  4951. if (_MULTI_PARTITION && part != 0) { /* Created in the existing partition */
  4952. /* Update system ID in the partition table */
  4953. if (disk_read(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Read the MBR */
  4954. buf[MBR_Table + (part - 1) * SZ_PTE + PTE_System] = sys; /* Set system ID */
  4955. if (disk_write(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it back to the MBR */
  4956. } else { /* Created as a new single partition */
  4957. if (!(opt & FM_SFD)) { /* Create partition table if in FDISK format */
  4958. mem_set(buf, 0, ss);
  4959. st_word(buf + BS_55AA, 0xAA55); /* MBR signature */
  4960. pte = buf + MBR_Table; /* Create partition table for single partition in the drive */
  4961. pte[PTE_Boot] = 0; /* Boot indicator */
  4962. pte[PTE_StHead] = 1; /* Start head */
  4963. pte[PTE_StSec] = 1; /* Start sector */
  4964. pte[PTE_StCyl] = 0; /* Start cylinder */
  4965. pte[PTE_System] = sys; /* System type */
  4966. n = (b_vol + sz_vol) / (63 * 255); /* (End CHS may be invalid) */
  4967. pte[PTE_EdHead] = 254; /* End head */
  4968. pte[PTE_EdSec] = (BYTE)(n >> 2 | 63); /* End sector */
  4969. pte[PTE_EdCyl] = (BYTE)n; /* End cylinder */
  4970. st_dword(pte + PTE_StLba, b_vol); /* Start offset in LBA */
  4971. st_dword(pte + PTE_SizLba, sz_vol); /* Size in sectors */
  4972. if (disk_write(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the MBR */
  4973. }
  4974. }
  4975. if (disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) return FR_DISK_ERR;
  4976. return FR_OK;
  4977. }
  4978. #if _MULTI_PARTITION
  4979. /*-----------------------------------------------------------------------*/
  4980. /* Create partition table on the physical drive */
  4981. /*-----------------------------------------------------------------------*/
  4982. FRESULT f_fdisk (
  4983. BYTE pdrv, /* Physical drive number */
  4984. const DWORD* szt, /* Pointer to the size table for each partitions */
  4985. void* work /* Pointer to the working buffer */
  4986. )
  4987. {
  4988. UINT i, n, sz_cyl, tot_cyl, b_cyl, e_cyl, p_cyl;
  4989. BYTE s_hd, e_hd, *p, *buf = (BYTE*)work;
  4990. DSTATUS stat;
  4991. DWORD sz_disk, sz_part, s_part;
  4992. stat = disk_initialize(pdrv);
  4993. if (stat & STA_NOINIT) return FR_NOT_READY;
  4994. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  4995. if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_disk)) return FR_DISK_ERR;
  4996. /* Determine the CHS without any consideration of the drive geometry */
  4997. for (n = 16; n < 256 && sz_disk / n / 63 > 1024; n *= 2) ;
  4998. if (n == 256) n--;
  4999. e_hd = n - 1;
  5000. sz_cyl = 63 * n;
  5001. tot_cyl = sz_disk / sz_cyl;
  5002. /* Create partition table */
  5003. mem_set(buf, 0, _MAX_SS);
  5004. p = buf + MBR_Table; b_cyl = 0;
  5005. for (i = 0; i < 4; i++, p += SZ_PTE) {
  5006. p_cyl = (szt[i] <= 100U) ? (DWORD)tot_cyl * szt[i] / 100 : szt[i] / sz_cyl; /* Number of cylinders */
  5007. if (!p_cyl) continue;
  5008. s_part = (DWORD)sz_cyl * b_cyl;
  5009. sz_part = (DWORD)sz_cyl * p_cyl;
  5010. if (i == 0) { /* Exclude first track of cylinder 0 */
  5011. s_hd = 1;
  5012. s_part += 63; sz_part -= 63;
  5013. } else {
  5014. s_hd = 0;
  5015. }
  5016. e_cyl = b_cyl + p_cyl - 1; /* End cylinder */
  5017. if (e_cyl >= tot_cyl) return FR_INVALID_PARAMETER;
  5018. /* Set partition table */
  5019. p[1] = s_hd; /* Start head */
  5020. p[2] = (BYTE)((b_cyl >> 2) + 1); /* Start sector */
  5021. p[3] = (BYTE)b_cyl; /* Start cylinder */
  5022. p[4] = 0x07; /* System type (temporary setting) */
  5023. p[5] = e_hd; /* End head */
  5024. p[6] = (BYTE)((e_cyl >> 2) + 63); /* End sector */
  5025. p[7] = (BYTE)e_cyl; /* End cylinder */
  5026. st_dword(p + 8, s_part); /* Start sector in LBA */
  5027. st_dword(p + 12, sz_part); /* Number of sectors */
  5028. /* Next partition */
  5029. b_cyl += p_cyl;
  5030. }
  5031. st_word(p, 0xAA55);
  5032. /* Write it to the MBR */
  5033. return (disk_write(pdrv, buf, 0, 1) != RES_OK || disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) ? FR_DISK_ERR : FR_OK;
  5034. }
  5035. #endif /* _MULTI_PARTITION */
  5036. #endif /* _USE_MKFS && !_FS_READONLY */
  5037. #if _USE_STRFUNC
  5038. /*-----------------------------------------------------------------------*/
  5039. /* Get a string from the file */
  5040. /*-----------------------------------------------------------------------*/
  5041. TCHAR* f_gets (
  5042. TCHAR* buff, /* Pointer to the string buffer to read */
  5043. int len, /* Size of string buffer (characters) */
  5044. FIL* fp /* Pointer to the file object */
  5045. )
  5046. {
  5047. int n = 0;
  5048. TCHAR c, *p = buff;
  5049. BYTE s[2];
  5050. UINT rc;
  5051. while (n < len - 1) { /* Read characters until buffer gets filled */
  5052. #if _LFN_UNICODE
  5053. #if _STRF_ENCODE == 3 /* Read a character in UTF-8 */
  5054. f_read(fp, s, 1, &rc);
  5055. if (rc != 1) break;
  5056. c = s[0];
  5057. if (c >= 0x80) {
  5058. if (c < 0xC0) continue; /* Skip stray trailer */
  5059. if (c < 0xE0) { /* Two-byte sequence (0x80-0x7FF) */
  5060. f_read(fp, s, 1, &rc);
  5061. if (rc != 1) break;
  5062. c = (c & 0x1F) << 6 | (s[0] & 0x3F);
  5063. if (c < 0x80) c = '?'; /* Reject invalid code range */
  5064. } else {
  5065. if (c < 0xF0) { /* Three-byte sequence (0x800-0xFFFF) */
  5066. f_read(fp, s, 2, &rc);
  5067. if (rc != 2) break;
  5068. c = c << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F);
  5069. if (c < 0x800) c = '?'; /* Reject invalid code range */
  5070. } else { /* Reject four-byte sequence */
  5071. c = '?';
  5072. }
  5073. }
  5074. }
  5075. #elif _STRF_ENCODE == 2 /* Read a character in UTF-16BE */
  5076. f_read(fp, s, 2, &rc);
  5077. if (rc != 2) break;
  5078. c = s[1] + (s[0] << 8);
  5079. #elif _STRF_ENCODE == 1 /* Read a character in UTF-16LE */
  5080. f_read(fp, s, 2, &rc);
  5081. if (rc != 2) break;
  5082. c = s[0] + (s[1] << 8);
  5083. #else /* Read a character in ANSI/OEM */
  5084. f_read(fp, s, 1, &rc);
  5085. if (rc != 1) break;
  5086. c = s[0];
  5087. if (IsDBCS1(c)) {
  5088. f_read(fp, s, 1, &rc);
  5089. if (rc != 1) break;
  5090. c = (c << 8) + s[0];
  5091. }
  5092. c = ff_convert(c, 1); /* OEM -> Unicode */
  5093. if (!c) c = '?';
  5094. #endif
  5095. #else /* Read a character without conversion */
  5096. f_read(fp, s, 1, &rc);
  5097. if (rc != 1) break;
  5098. c = s[0];
  5099. #endif
  5100. if (_USE_STRFUNC == 2 && c == '\r') continue; /* Strip '\r' */
  5101. *p++ = c;
  5102. n++;
  5103. if (c == '\n') break; /* Break on EOL */
  5104. }
  5105. *p = 0;
  5106. return n ? buff : 0; /* When no data read (eof or error), return with error. */
  5107. }
  5108. #if !_FS_READONLY
  5109. #include <stdarg.h>
  5110. /*-----------------------------------------------------------------------*/
  5111. /* Put a character to the file */
  5112. /*-----------------------------------------------------------------------*/
  5113. typedef struct {
  5114. FIL *fp; /* Ptr to the writing file */
  5115. int idx, nchr; /* Write index of buf[] (-1:error), number of chars written */
  5116. BYTE buf[64]; /* Write buffer */
  5117. } putbuff;
  5118. static
  5119. void putc_bfd ( /* Buffered write with code conversion */
  5120. putbuff* pb,
  5121. TCHAR c
  5122. )
  5123. {
  5124. UINT bw;
  5125. int i;
  5126. if (_USE_STRFUNC == 2 && c == '\n') { /* LF -> CRLF conversion */
  5127. putc_bfd(pb, '\r');
  5128. }
  5129. i = pb->idx; /* Write index of pb->buf[] */
  5130. if (i < 0) return;
  5131. #if _LFN_UNICODE
  5132. #if _STRF_ENCODE == 3 /* Write a character in UTF-8 */
  5133. if (c < 0x80) { /* 7-bit */
  5134. pb->buf[i++] = (BYTE)c;
  5135. } else {
  5136. if (c < 0x800) { /* 11-bit */
  5137. pb->buf[i++] = (BYTE)(0xC0 | c >> 6);
  5138. } else { /* 16-bit */
  5139. pb->buf[i++] = (BYTE)(0xE0 | c >> 12);
  5140. pb->buf[i++] = (BYTE)(0x80 | (c >> 6 & 0x3F));
  5141. }
  5142. pb->buf[i++] = (BYTE)(0x80 | (c & 0x3F));
  5143. }
  5144. #elif _STRF_ENCODE == 2 /* Write a character in UTF-16BE */
  5145. pb->buf[i++] = (BYTE)(c >> 8);
  5146. pb->buf[i++] = (BYTE)c;
  5147. #elif _STRF_ENCODE == 1 /* Write a character in UTF-16LE */
  5148. pb->buf[i++] = (BYTE)c;
  5149. pb->buf[i++] = (BYTE)(c >> 8);
  5150. #else /* Write a character in ANSI/OEM */
  5151. c = ff_convert(c, 0); /* Unicode -> OEM */
  5152. if (!c) c = '?';
  5153. if (c >= 0x100)
  5154. pb->buf[i++] = (BYTE)(c >> 8);
  5155. pb->buf[i++] = (BYTE)c;
  5156. #endif
  5157. #else /* Write a character without conversion */
  5158. pb->buf[i++] = (BYTE)c;
  5159. #endif
  5160. if (i >= (int)(sizeof pb->buf) - 3) { /* Write buffered characters to the file */
  5161. f_write(pb->fp, pb->buf, (UINT)i, &bw);
  5162. i = (bw == (UINT)i) ? 0 : -1;
  5163. }
  5164. pb->idx = i;
  5165. pb->nchr++;
  5166. }
  5167. static
  5168. int putc_flush ( /* Flush left characters in the buffer */
  5169. putbuff* pb
  5170. )
  5171. {
  5172. UINT nw;
  5173. if ( pb->idx >= 0 /* Flush buffered characters to the file */
  5174. && f_write(pb->fp, pb->buf, (UINT)pb->idx, &nw) == FR_OK
  5175. && (UINT)pb->idx == nw) return pb->nchr;
  5176. return EOF;
  5177. }
  5178. static
  5179. void putc_init ( /* Initialize write buffer */
  5180. putbuff* pb,
  5181. FIL* fp
  5182. )
  5183. {
  5184. pb->fp = fp;
  5185. pb->nchr = pb->idx = 0;
  5186. }
  5187. int f_putc (
  5188. TCHAR c, /* A character to be output */
  5189. FIL* fp /* Pointer to the file object */
  5190. )
  5191. {
  5192. putbuff pb;
  5193. putc_init(&pb, fp);
  5194. putc_bfd(&pb, c); /* Put the character */
  5195. return putc_flush(&pb);
  5196. }
  5197. /*-----------------------------------------------------------------------*/
  5198. /* Put a string to the file */
  5199. /*-----------------------------------------------------------------------*/
  5200. int f_puts (
  5201. const TCHAR* str, /* Pointer to the string to be output */
  5202. FIL* fp /* Pointer to the file object */
  5203. )
  5204. {
  5205. putbuff pb;
  5206. putc_init(&pb, fp);
  5207. while (*str) putc_bfd(&pb, *str++); /* Put the string */
  5208. return putc_flush(&pb);
  5209. }
  5210. /*-----------------------------------------------------------------------*/
  5211. /* Put a formatted string to the file */
  5212. /*-----------------------------------------------------------------------*/
  5213. int f_printf (
  5214. FIL* fp, /* Pointer to the file object */
  5215. const TCHAR* fmt, /* Pointer to the format string */
  5216. ... /* Optional arguments... */
  5217. )
  5218. {
  5219. va_list arp;
  5220. putbuff pb;
  5221. BYTE f, r;
  5222. UINT i, j, w;
  5223. DWORD v;
  5224. TCHAR c, d, str[32], *p;
  5225. putc_init(&pb, fp);
  5226. va_start(arp, fmt);
  5227. for (;;) {
  5228. c = *fmt++;
  5229. if (c == 0) break; /* End of string */
  5230. if (c != '%') { /* Non escape character */
  5231. putc_bfd(&pb, c);
  5232. continue;
  5233. }
  5234. w = f = 0;
  5235. c = *fmt++;
  5236. if (c == '0') { /* Flag: '0' padding */
  5237. f = 1; c = *fmt++;
  5238. } else {
  5239. if (c == '-') { /* Flag: left justified */
  5240. f = 2; c = *fmt++;
  5241. }
  5242. }
  5243. while (IsDigit(c)) { /* Precision */
  5244. w = w * 10 + c - '0';
  5245. c = *fmt++;
  5246. }
  5247. if (c == 'l' || c == 'L') { /* Prefix: Size is long int */
  5248. f |= 4; c = *fmt++;
  5249. }
  5250. if (!c) break;
  5251. d = c;
  5252. if (IsLower(d)) d -= 0x20;
  5253. switch (d) { /* Type is... */
  5254. case 'S' : /* String */
  5255. p = va_arg(arp, TCHAR*);
  5256. for (j = 0; p[j]; j++) ;
  5257. if (!(f & 2)) {
  5258. while (j++ < w) putc_bfd(&pb, ' ');
  5259. }
  5260. while (*p) putc_bfd(&pb, *p++);
  5261. while (j++ < w) putc_bfd(&pb, ' ');
  5262. continue;
  5263. case 'C' : /* Character */
  5264. putc_bfd(&pb, (TCHAR)va_arg(arp, int)); continue;
  5265. case 'B' : /* Binary */
  5266. r = 2; break;
  5267. case 'O' : /* Octal */
  5268. r = 8; break;
  5269. case 'D' : /* Signed decimal */
  5270. case 'U' : /* Unsigned decimal */
  5271. r = 10; break;
  5272. case 'X' : /* Hexdecimal */
  5273. r = 16; break;
  5274. default: /* Unknown type (pass-through) */
  5275. putc_bfd(&pb, c); continue;
  5276. }
  5277. /* Get an argument and put it in numeral */
  5278. v = (f & 4) ? (DWORD)va_arg(arp, long) : ((d == 'D') ? (DWORD)(long)va_arg(arp, int) : (DWORD)va_arg(arp, unsigned int));
  5279. if (d == 'D' && (v & 0x80000000)) {
  5280. v = 0 - v;
  5281. f |= 8;
  5282. }
  5283. i = 0;
  5284. do {
  5285. d = (TCHAR)(v % r); v /= r;
  5286. if (d > 9) d += (c == 'x') ? 0x27 : 0x07;
  5287. str[i++] = d + '0';
  5288. } while (v && i < sizeof str / sizeof str[0]);
  5289. if (f & 8) str[i++] = '-';
  5290. j = i; d = (f & 1) ? '0' : ' ';
  5291. while (!(f & 2) && j++ < w) putc_bfd(&pb, d);
  5292. do {
  5293. putc_bfd(&pb, str[--i]);
  5294. } while (i);
  5295. while (j++ < w) putc_bfd(&pb, d);
  5296. }
  5297. va_end(arp);
  5298. return putc_flush(&pb);
  5299. }
  5300. #endif /* !_FS_READONLY */
  5301. #endif /* _USE_STRFUNC */