dclib-basics.c 255 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036
  1. /***************************************************************************
  2. * *
  3. * _____ ____ *
  4. * | __ \ / __ \ _ _ _____ *
  5. * | | \ \ / / \_\ | | | | _ \ *
  6. * | | \ \| | | | | | |_| | *
  7. * | | | || | | | | | ___/ *
  8. * | | / /| | __ | | | | _ \ *
  9. * | |__/ / \ \__/ / | |___| | |_| | *
  10. * |_____/ \____/ |_____|_|_____/ *
  11. * *
  12. * Wiimms source code library *
  13. * *
  14. ***************************************************************************
  15. * *
  16. * Copyright (c) 2012-2022 by Dirk Clemens <wiimm@wiimm.de> *
  17. * *
  18. ***************************************************************************
  19. * *
  20. * This library is free software; you can redistribute it and/or modify *
  21. * it under the terms of the GNU General Public License as published by *
  22. * the Free Software Foundation; either version 2 of the License, or *
  23. * (at your option) any later version. *
  24. * *
  25. * This library is distributed in the hope that it will be useful, *
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of *
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
  28. * GNU General Public License for more details. *
  29. * *
  30. * See file gpl-2.0.txt or http://www.gnu.org/licenses/gpl-2.0.txt *
  31. * *
  32. ***************************************************************************/
  33. #define _GNU_SOURCE 1
  34. #include <string.h>
  35. #include <unistd.h>
  36. #include <time.h>
  37. #include <stdio.h>
  38. #include <stddef.h>
  39. #include <signal.h>
  40. #include <errno.h>
  41. #include <sys/time.h>
  42. #include <fcntl.h>
  43. #include <sys/ioctl.h>
  44. #include "dclib-basics.h"
  45. #include "dclib-debug.h"
  46. #include "dclib-file.h"
  47. #include "dclib-utf8.h"
  48. #include "dclib-network.h"
  49. //
  50. ///////////////////////////////////////////////////////////////////////////////
  51. /////////////// some basic string functions ///////////////
  52. ///////////////////////////////////////////////////////////////////////////////
  53. const char EmptyQuote[] = "\"\""; // Ignored by FreeString()
  54. const char EmptyString[4] = "\0\0\0"; // Ignored by FreeString()
  55. const char MinusString[4] = "-\0\0"; // Ignored by FreeString()
  56. const char LoDigits[0x41] =
  57. "0123456789"
  58. "abcdefghijklmnopqrstuvwxyz"
  59. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  60. ".+";
  61. const char HiDigits[0x41] =
  62. "0123456789"
  63. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  64. "abcdefghijklmnopqrstuvwxyz"
  65. ".+";
  66. const char Tabs20[21] = // 20 * TABS + NULL
  67. "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
  68. const char LF20[21] = // 20 * LF + NULL
  69. "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
  70. const char Space200[201] = // 200 * ' ' + NULL
  71. " "
  72. " "
  73. " "
  74. " ";
  75. const char Minus300[301] = // 300 * '-' + NULL
  76. "--------------------------------------------------"
  77. "--------------------------------------------------"
  78. "--------------------------------------------------"
  79. "--------------------------------------------------"
  80. "--------------------------------------------------"
  81. "--------------------------------------------------";
  82. const char Underline200[201] = // 200 * '_' + NULL
  83. "__________________________________________________"
  84. "__________________________________________________"
  85. "__________________________________________________"
  86. "__________________________________________________";
  87. const char Hash200[201] = // 200 * '#' + NULL
  88. "##################################################"
  89. "##################################################"
  90. "##################################################"
  91. "##################################################";
  92. const char Slash200[201] = // 200 * '/' + NULL
  93. "//////////////////////////////////////////////////"
  94. "//////////////////////////////////////////////////"
  95. "//////////////////////////////////////////////////"
  96. "//////////////////////////////////////////////////";
  97. // UTF-8 => 3 bytes per char
  98. const char ThinLine300_3[901] = // 300 * '─' (U+2500) + NULL
  99. "──────────────────────────────────────────────────"
  100. "──────────────────────────────────────────────────"
  101. "──────────────────────────────────────────────────"
  102. "──────────────────────────────────────────────────"
  103. "──────────────────────────────────────────────────"
  104. "──────────────────────────────────────────────────";
  105. const char DoubleLine300_3[901] = // 300 * '═' (U+2550) + NULL
  106. "══════════════════════════════════════════════════"
  107. "══════════════════════════════════════════════════"
  108. "══════════════════════════════════════════════════"
  109. "══════════════════════════════════════════════════"
  110. "══════════════════════════════════════════════════"
  111. "══════════════════════════════════════════════════";
  112. ///////////////////////////////////////////////////////////////////////////////
  113. ///////////////////////////////////////////////////////////////////////////////
  114. void PrintSettingsDCLIB ( FILE *f, int indent )
  115. {
  116. DASSERT(f);
  117. indent = NormalizeIndent(indent);
  118. MARK_USED(indent); // for the case, that all other conditions fail!
  119. #ifdef DCLIB_NETWORK
  120. fprintf(f,"%*s" "DCLIB_NETWORK\n",indent,"");
  121. #endif
  122. #ifdef DCLIB_TERMINAL
  123. fprintf(f,"%*s" "DCLIB_TERMINAL\n",indent,"");
  124. #endif
  125. #ifdef DCLIB_MYSQL
  126. fprintf(f,"%*s" "DCLIB_MYSQL\n",indent,"");
  127. #endif
  128. #ifdef DCLIB_HAVE_USABLE_SIZE
  129. fprintf(f,"%*s" "DCLIB_HAVE_USABLE_SIZE\n",indent,"");
  130. #endif
  131. }
  132. //
  133. ///////////////////////////////////////////////////////////////////////////////
  134. ///////////////////////////////////////////////////////////////////////////////
  135. void SetupMultiProcessing()
  136. {
  137. ProgInfo.multi_processing = true;
  138. }
  139. ///////////////////////////////////////////////////////////////////////////////
  140. void SetupProgname ( int argc, char ** argv, ccp tname, ccp tvers, ccp ttitle )
  141. {
  142. if (tname)
  143. ProgInfo.toolname = tname;
  144. if (tvers)
  145. ProgInfo.toolversion = tvers;
  146. if (ttitle)
  147. ProgInfo.tooltitle = ttitle;
  148. if (!ProgInfo.progpath)
  149. {
  150. char path[PATH_MAX];
  151. int res = GetProgramPath( path, sizeof(path), true, argc > 0 ? argv[0] : 0 );
  152. if ( res > 0 )
  153. ProgInfo.progpath = STRDUP(path);
  154. }
  155. if ( argc > 0 && *argv && **argv )
  156. {
  157. ccp slash = strrchr(*argv,'/');
  158. ProgInfo.progname = slash ? slash + 1 : *argv;
  159. }
  160. else
  161. ProgInfo.progname = ProgInfo.toolname && *ProgInfo.toolname
  162. ? ProgInfo.toolname : "?";
  163. }
  164. ///////////////////////////////////////////////////////////////////////////////
  165. ccp ProgramPath()
  166. {
  167. static bool done = false;
  168. if ( !ProgInfo.progpath && !done )
  169. {
  170. done = true;
  171. char path[PATH_MAX];
  172. int res = GetProgramPath( path, sizeof(path), true, 0 );
  173. if ( res > 0 )
  174. ProgInfo.progpath = STRDUP(path);
  175. }
  176. return ProgInfo.progpath;
  177. }
  178. ///////////////////////////////////////////////////////////////////////////////
  179. ccp ProgramDirectory()
  180. {
  181. if (!ProgInfo.progdir)
  182. {
  183. ccp path = ProgramPath();
  184. if (path)
  185. {
  186. ccp end = strrchr(path,'/');
  187. const uint len = end ? end - path : strlen(path);
  188. ProgInfo.progdir = MEMDUP(path,len);
  189. }
  190. }
  191. return ProgInfo.progdir;
  192. }
  193. ///////////////////////////////////////////////////////////////////////////////
  194. ///////////////////////////////////////////////////////////////////////////////
  195. void DefineLogDirectory ( ccp path0, bool force )
  196. {
  197. PRINT("DefineLogDirectory(%s,%d)\n",path0,force);
  198. if ( path0 && *path0 && ( force || !ProgInfo.logdir ))
  199. {
  200. char path[PATH_MAX];
  201. StringCopyS(path,sizeof(path),path0);
  202. if (!ExistDirectory(path,0))
  203. {
  204. char *slash = strrchr(path,'/');
  205. if (slash)
  206. *slash = 0;
  207. else
  208. {
  209. path[0] = '.';
  210. path[1] = 0;
  211. }
  212. if (!ExistDirectory(path,0))
  213. return;
  214. }
  215. int len = strlen(path);
  216. while ( len > 0 && path[len-1] == '/' )
  217. path[--len] = 0;
  218. if ( len > 0 )
  219. {
  220. FreeString(ProgInfo.logdir);
  221. ProgInfo.logdir = MEMDUP(path,len);
  222. PRINT("#LOG-DIR: %s\n",ProgInfo.logdir);
  223. }
  224. }
  225. }
  226. //-----------------------------------------------------------------------------
  227. ccp GetLogDirectory()
  228. {
  229. return ProgInfo.logdir ? ProgInfo.logdir : ".";
  230. }
  231. ///////////////////////////////////////////////////////////////////////////////
  232. #ifdef __CYGWIN__
  233. ccp ProgramPathNoExt()
  234. {
  235. static ccp res = 0;
  236. if (!res)
  237. {
  238. res = ProgramPath();
  239. if (res)
  240. {
  241. ccp slash = strrchr(res,'/');
  242. ccp ext = strrchr( slash ? slash + 1 : res, '.' );
  243. if (ext)
  244. res = MEMDUP(res,ext-res);
  245. }
  246. }
  247. return res;
  248. }
  249. #endif // __CYGWIN__
  250. ///////////////////////////////////////////////////////////////////////////////
  251. int GetProgramPath
  252. (
  253. // returns strlen(buf) on success, -1 on failure
  254. char *buf, // buffer for the result; empty string on failure.
  255. uint buf_size, // size of buffer
  256. bool check_proc, // true: read files of /proc/... to find path
  257. ccp argv0 // not NULL: analyse this argument (argv[0])
  258. )
  259. {
  260. char path[PATH_MAX], path2[PATH_MAX];
  261. #ifdef __APPLE__
  262. //--- read apple path of executable
  263. extern int _NSGetExecutablePath( char* buf, uint32_t * bufsize );
  264. uint32_t size = sizeof(path);
  265. if (!_NSGetExecutablePath(path,&size))
  266. {
  267. if ( realpath(path,path2) && *path2 )
  268. return StringCopyS(buf,buf_size,path2) - buf;
  269. return StringCopyS(buf,buf_size,path) - buf;
  270. }
  271. #else // !__APPLE__
  272. //--- read files of /proc/...
  273. if (check_proc)
  274. {
  275. static ccp tab[] =
  276. {
  277. "/proc/self/exe",
  278. "/proc/curproc/file",
  279. "/proc/self/path/a.out",
  280. 0
  281. };
  282. ccp *ptr;
  283. for ( ptr = tab; *ptr; ptr++ )
  284. if ( realpath(*ptr,path) && *path )
  285. return StringCopyS(buf,buf_size,path) - buf;
  286. }
  287. #endif // !__APPLE__
  288. //--- analyze argv0
  289. if (argv0)
  290. {
  291. if ( *argv0 == '/' )
  292. {
  293. // absolute path
  294. if ( realpath(argv0,path) && *path )
  295. return StringCopyS(buf,buf_size,path) - buf;
  296. }
  297. else if (strchr(argv0,'/'))
  298. {
  299. // relative path
  300. if ( getcwd(path2,sizeof(path2)) > 0 )
  301. {
  302. ccp p2 = PathCatPP(path2,sizeof(path2),path,argv0);
  303. if ( realpath(p2,path) && *path )
  304. return StringCopyS(buf,buf_size,path) - buf;
  305. }
  306. }
  307. else
  308. {
  309. // simple name => search in path environment
  310. uint arglen = strlen(argv0);
  311. if ( arglen < sizeof(path2) - 2 )
  312. {
  313. ccp dest_end = path2 + sizeof(path2) - 1 - arglen;
  314. ccp env = getenv("PATH");
  315. while ( env && *env )
  316. {
  317. while ( *env == ':' )
  318. env++;
  319. char *dest = path2;
  320. while ( *env && *env != ':' && dest < dest_end )
  321. *dest++ = *env++;
  322. *dest++ = '/';
  323. memcpy(dest,argv0,arglen+1);
  324. if ( realpath(path2,path) && *path )
  325. return StringCopyS(buf,buf_size,path) - buf;
  326. }
  327. }
  328. }
  329. }
  330. //--- failed
  331. *buf = 0;
  332. return -1;
  333. }
  334. ///////////////////////////////////////////////////////////////////////////////
  335. void FreeString ( ccp str )
  336. {
  337. noTRACE("FreeString(%p) EmptyString=%p MinusString=%p, IsCircBuf=%d\n",
  338. str, EmptyString, MinusString, IsCircBuf(str) );
  339. if ( str != EmptyString && str != EmptyQuote && str != MinusString && !IsCircBuf(str) )
  340. FREE((char*)str);
  341. }
  342. ///////////////////////////////////////////////////////////////////////////////
  343. ///////////////////////////////////////////////////////////////////////////////
  344. char * StringCopyS ( char * buf, ssize_t buf_size, ccp src )
  345. {
  346. DASSERT(buf);
  347. if ( !buf || buf_size <= 0 )
  348. return buf;
  349. if (src)
  350. {
  351. size_t slen = strlen(src);
  352. if ( slen >= buf_size )
  353. slen = buf_size-1;
  354. memcpy(buf,src,slen);
  355. buf += slen;
  356. }
  357. *buf = 0;
  358. return buf;
  359. }
  360. //-----------------------------------------------------------------------------
  361. char * StringCopySM ( char * buf, ssize_t buf_size, ccp src, ssize_t max_copy )
  362. {
  363. DASSERT(buf);
  364. if ( !buf || buf_size <= 0 )
  365. return buf;
  366. if (src)
  367. {
  368. size_t slen = strlen(src);
  369. if ( slen >= buf_size )
  370. slen = buf_size-1;
  371. if ( max_copy >= 0 && slen >= max_copy )
  372. slen = max_copy;
  373. memcpy(buf,src,slen);
  374. buf += slen;
  375. }
  376. *buf = 0;
  377. return buf;
  378. }
  379. //-----------------------------------------------------------------------------
  380. char * StringCopySL ( char * buf, ssize_t buf_size, ccp src, ssize_t src_len )
  381. {
  382. DASSERT(buf);
  383. if ( !buf || buf_size <= 0 )
  384. return buf;
  385. if (src)
  386. {
  387. if ( src_len < 0 )
  388. src_len = strlen(src);
  389. if ( src_len >= buf_size )
  390. src_len = buf_size-1;
  391. memcpy(buf,src,src_len);
  392. buf += src_len;
  393. }
  394. *buf = 0;
  395. return buf;
  396. }
  397. ///////////////////////////////////////////////////////////////////////////////
  398. char * StringCat2E ( char * buf, ccp buf_end, ccp src1, ccp src2 )
  399. {
  400. // RESULT: end of copied string pointing to NULL
  401. // 'src*' may be a NULL pointer.
  402. DASSERT(buf);
  403. DASSERT(buf<buf_end);
  404. buf_end--;
  405. if (src1)
  406. while( buf < buf_end && *src1 )
  407. *buf++ = *src1++;
  408. if (src2)
  409. while( buf < buf_end && *src2 )
  410. *buf++ = *src2++;
  411. *buf = 0;
  412. return buf;
  413. }
  414. //-----------------------------------------------------------------------------
  415. char * StringCat2S ( char * buf, ssize_t buf_size, ccp src1, ccp src2 )
  416. {
  417. return StringCat2E(buf,buf+buf_size,src1,src2);
  418. }
  419. ///////////////////////////////////////////////////////////////////////////////
  420. char * StringCatSep2E ( char * buf, ccp buf_end, ccp sep, ccp src1, ccp src2 )
  421. {
  422. // RESULT: end of copied string pointing to NULL
  423. // 'src*' may be a NULL pointer.
  424. DASSERT(buf);
  425. DASSERT(buf<buf_end);
  426. if ( !sep || !*sep )
  427. return StringCat2E(buf,buf_end,src1,src2);
  428. char *buf0 = buf;
  429. buf_end--;
  430. if (src1)
  431. while( buf < buf_end && *src1 )
  432. *buf++ = *src1++;
  433. if (src2)
  434. {
  435. if ( buf > buf0 )
  436. while ( buf < buf_end && *sep )
  437. *buf++ = *sep++;
  438. while( buf < buf_end && *src2 )
  439. *buf++ = *src2++;
  440. }
  441. *buf = 0;
  442. return buf;
  443. }
  444. //-----------------------------------------------------------------------------
  445. char * StringCatSep2S ( char * buf, ssize_t buf_size, ccp sep, ccp src1, ccp src2 )
  446. {
  447. return StringCatSep2E(buf,buf+buf_size,sep,src1,src2);
  448. }
  449. ///////////////////////////////////////////////////////////////////////////////
  450. char * StringCat3E ( char * buf, ccp buf_end, ccp src1, ccp src2, ccp src3 )
  451. {
  452. // RESULT: end of copied string pointing to NULL
  453. // 'src*' may be a NULL pointer.
  454. DASSERT(buf);
  455. DASSERT(buf<buf_end);
  456. buf_end--;
  457. if (src1)
  458. while( buf < buf_end && *src1 )
  459. *buf++ = *src1++;
  460. if (src2)
  461. while( buf < buf_end && *src2 )
  462. *buf++ = *src2++;
  463. if (src3)
  464. while( buf < buf_end && *src3 )
  465. *buf++ = *src3++;
  466. *buf = 0;
  467. return buf;
  468. }
  469. //-----------------------------------------------------------------------------
  470. char * StringCat3S ( char * buf, ssize_t buf_size, ccp src1, ccp src2, ccp src3 )
  471. {
  472. return StringCat3E(buf,buf+buf_size,src1,src2,src3);
  473. }
  474. ///////////////////////////////////////////////////////////////////////////////
  475. char * StringCatSep3E
  476. ( char * buf, ccp buf_end, ccp sep, ccp src1, ccp src2, ccp src3 )
  477. {
  478. // RESULT: end of copied string pointing to NULL
  479. // 'src*' may be a NULL pointer.
  480. DASSERT(buf);
  481. DASSERT(buf<buf_end);
  482. if ( !sep || !*sep )
  483. return StringCat3E(buf,buf_end,src1,src2,src3);
  484. buf_end--;
  485. char *buf0 = buf;
  486. if (src1)
  487. while( buf < buf_end && *src1 )
  488. *buf++ = *src1++;
  489. if (src2)
  490. {
  491. if ( buf > buf0 )
  492. {
  493. ccp ptr = sep;
  494. while ( buf < buf_end && *ptr )
  495. *buf++ = *ptr++;
  496. }
  497. while( buf < buf_end && *src2 )
  498. *buf++ = *src2++;
  499. }
  500. if (src3)
  501. {
  502. if ( buf > buf0 )
  503. while ( buf < buf_end && *sep )
  504. *buf++ = *sep++;
  505. while( buf < buf_end && *src3 )
  506. *buf++ = *src3++;
  507. }
  508. *buf = 0;
  509. return buf;
  510. }
  511. //-----------------------------------------------------------------------------
  512. char * StringCatSep3S
  513. ( char * buf, ssize_t buf_size, ccp sep, ccp src1, ccp src2, ccp src3 )
  514. {
  515. return StringCatSep3E(buf,buf+buf_size,sep,src1,src2,src3);
  516. }
  517. ///////////////////////////////////////////////////////////////////////////////
  518. char * StringCat2A ( ccp src1, ccp src2 )
  519. {
  520. mem_t mem = MemCat2A( MemByString0(src1), MemByString0(src2) );
  521. return (char*)mem.ptr;
  522. }
  523. //-----------------------------------------------------------------------------
  524. char * StringCat3A ( ccp src1, ccp src2, ccp src3 )
  525. {
  526. mem_t mem = MemCat3A( MemByString0(src1), MemByString0(src2), MemByString0(src3) );
  527. return (char*)mem.ptr;
  528. }
  529. ///////////////////////////////////////////////////////////////////////////////
  530. char * StringCatSep2A ( ccp sep, ccp src1, ccp src2 )
  531. {
  532. mem_t mem = MemCatSep2A( MemByString0(sep),
  533. MemByString0(src1),
  534. MemByString0(src2) );
  535. return (char*)mem.ptr;
  536. }
  537. //-----------------------------------------------------------------------------
  538. char * StringCatSep3A ( ccp sep, ccp src1, ccp src2, ccp src3 )
  539. {
  540. mem_t mem = MemCatSep3A( MemByString0(sep),
  541. MemByString0(src1),
  542. MemByString0(src2),
  543. MemByString0(src3) );
  544. return (char*)mem.ptr;
  545. }
  546. ///////////////////////////////////////////////////////////////////////////////
  547. ccp StringCenterE
  548. (
  549. char * buf, // result buffer; if NULL, circ-buf is used
  550. ccp buf_end, // end of 'buf', NULL if buf==NULL
  551. ccp src, // source string
  552. int width // wanted width
  553. )
  554. {
  555. if (!src)
  556. src = "";
  557. int n2 = strlen(src);
  558. if ( n2 >= width )
  559. {
  560. if (!buf)
  561. return CopyCircBuf(src,n2+1);
  562. StringCopyEM(buf,buf_end,src,n2);
  563. return buf;
  564. }
  565. n2 = width - n2;
  566. int n1 = n2/2;
  567. n2 -= n1;
  568. if (!buf)
  569. {
  570. buf = GetCircBuf(width+1);
  571. buf_end = buf + width;
  572. }
  573. else
  574. buf_end--;
  575. char *dest = buf;
  576. while ( n1-- > 0 && dest < buf_end )
  577. *dest++ = ' ';
  578. while ( *src && dest < buf_end )
  579. *dest++ = *src++;
  580. while ( n2-- > 0 && dest < buf_end )
  581. *dest++ = ' ';
  582. *dest = 0;
  583. return buf;
  584. };
  585. ///////////////////////////////////////////////////////////////////////////////
  586. char * StringLowerE ( char * buf, ccp buf_end, ccp src )
  587. {
  588. // RESULT: end of copied string pointing to NULL
  589. // 'src' may be a NULL pointer.
  590. if ( buf >= buf_end )
  591. return (char*)buf_end - 1;
  592. DASSERT(buf);
  593. DASSERT(buf<buf_end);
  594. buf_end--;
  595. if (src)
  596. while( buf < buf_end && *src )
  597. *buf++ = tolower((int)*src++);
  598. *buf = 0;
  599. return buf;
  600. }
  601. //-----------------------------------------------------------------------------
  602. char * StringLowerS ( char * buf, ssize_t buf_size, ccp src )
  603. {
  604. return StringLowerE(buf,buf+buf_size,src);
  605. }
  606. //-----------------------------------------------------------------------------
  607. char * MemLowerE ( char * buf, ccp buf_end, mem_t src )
  608. {
  609. // RESULT: end of copied string pointing to NULL
  610. // 'src.ptr' may be a NULL pointer.
  611. if ( buf >= buf_end )
  612. return (char*)buf_end - 1;
  613. DASSERT(buf);
  614. DASSERT(buf<buf_end);
  615. buf_end--;
  616. if ( src.ptr )
  617. {
  618. ccp src_end = src.ptr + src.len;
  619. while( buf < buf_end && src.ptr < src_end )
  620. *buf++ = tolower((int)*src.ptr++);
  621. }
  622. *buf = 0;
  623. return buf;
  624. }
  625. //-----------------------------------------------------------------------------
  626. char * MemLowerS ( char * buf, ssize_t buf_size, mem_t src )
  627. {
  628. return MemLowerE(buf,buf+buf_size,src);
  629. }
  630. ///////////////////////////////////////////////////////////////////////////////
  631. char * StringUpperE ( char * buf, ccp buf_end, ccp src )
  632. {
  633. // RESULT: end of copied string pointing to NULL
  634. // 'src' may be a NULL pointer.
  635. if ( buf >= buf_end )
  636. return (char*)buf_end - 1;
  637. DASSERT(buf);
  638. DASSERT(buf<buf_end);
  639. buf_end--;
  640. if (src)
  641. while( buf < buf_end && *src )
  642. *buf++ = toupper((int)*src++);
  643. *buf = 0;
  644. return buf;
  645. }
  646. //-----------------------------------------------------------------------------
  647. char * StringUpperS ( char * buf, ssize_t buf_size, ccp src )
  648. {
  649. return StringUpperE(buf,buf+buf_size,src);
  650. }
  651. //-----------------------------------------------------------------------------
  652. char * MemUpperE ( char * buf, ccp buf_end, mem_t src )
  653. {
  654. // RESULT: end of copied string pointing to NULL
  655. // 'src.ptr' may be a NULL pointer.
  656. if ( buf >= buf_end )
  657. return (char*)buf_end - 1;
  658. DASSERT(buf);
  659. DASSERT(buf<buf_end);
  660. buf_end--;
  661. if ( src.ptr )
  662. {
  663. ccp src_end = src.ptr + src.len;
  664. while( buf < buf_end && src.ptr < src_end )
  665. *buf++ = toupper((int)*src.ptr++);
  666. }
  667. *buf = 0;
  668. return buf;
  669. }
  670. //-----------------------------------------------------------------------------
  671. char * MemUpperS ( char * buf, ssize_t buf_size, mem_t src )
  672. {
  673. return MemUpperE(buf,buf+buf_size,src);
  674. }
  675. //
  676. ///////////////////////////////////////////////////////////////////////////////
  677. /////////////// Signals & Sleep ///////////////
  678. ///////////////////////////////////////////////////////////////////////////////
  679. volatile int SIGINT_level = 0;
  680. volatile int SIGHUP_level = 0;
  681. volatile int SIGALRM_level = 0;
  682. volatile int SIGCHLD_level = 0;
  683. volatile int SIGPIPE_level = 0;
  684. volatile int SIGUSR1_level = 0;
  685. volatile int SIGUSR2_level = 0;
  686. // no timout for SIGPIPE
  687. u_sec_t SIGINT_sec = 0;
  688. u_sec_t SIGHUP_sec = 0;
  689. u_sec_t SIGALRM_sec = 0;
  690. u_sec_t SIGCHLD_sec = 0;
  691. u_sec_t SIGUSR1_sec = 0;
  692. u_sec_t SIGUSR2_sec = 0;
  693. int SIGINT_level_max = 3;
  694. bool ignore_SIGINT = false;
  695. bool ignore_SIGHUP = false;
  696. int redirect_signal_pid = 0;
  697. LogFile_t log_signal_file = {0};
  698. ///////////////////////////////////////////////////////////////////////////////
  699. static void inc_sig_handler ( volatile int *level, volatile uint *sec )
  700. {
  701. DASSERT(level);
  702. DASSERT(sec);
  703. const uint now = GetTimeSec(false);
  704. if ( now - *sec > 30 )
  705. *level = 0;
  706. *sec = now;
  707. (*level)++;
  708. }
  709. ///////////////////////////////////////////////////////////////////////////////
  710. static void sig_handler ( int signum )
  711. {
  712. fflush(stdout);
  713. static bool had_sigpipe = false;
  714. if (redirect_signal_pid)
  715. {
  716. kill(redirect_signal_pid,signum);
  717. return;
  718. }
  719. switch(signum)
  720. {
  721. case SIGINT:
  722. if (ignore_SIGINT)
  723. break;
  724. // fall through
  725. case SIGTERM:
  726. inc_sig_handler(&SIGINT_level,&SIGINT_sec);
  727. ccp signame = signum == SIGINT ? "INT" : "TERM";
  728. if ( SIGINT_level > 1 )
  729. PrintLogFile(&log_signal_file,"#SIGNAL %s: level set to %d/%d\n",
  730. signame, SIGINT_level, SIGINT_level_max );
  731. if ( SIGINT_level >= SIGINT_level_max )
  732. {
  733. PrintLogFile(&log_signal_file,"#SIGNAL %s: TERMINATE IMMEDIATELY!\n",signame);
  734. exit(0);
  735. }
  736. break;
  737. case SIGHUP:
  738. if (!ignore_SIGHUP)
  739. {
  740. inc_sig_handler(&SIGHUP_level,&SIGHUP_sec);
  741. PrintLogFile(&log_signal_file,"#SIGNAL HUP: level set to %d\n",SIGHUP_level);
  742. }
  743. break;
  744. case SIGCHLD:
  745. SIGCHLD_level++;
  746. PrintLogFile(&log_signal_file,"#SIGNAL CHLD: level set to %d\n",SIGCHLD_level);
  747. break;
  748. case SIGALRM:
  749. inc_sig_handler(&SIGALRM_level,&SIGALRM_sec);
  750. PrintLogFile(&log_signal_file,"#SIGNAL ALRM: level set to %d\n",SIGALRM_level);
  751. break;
  752. case SIGUSR1:
  753. inc_sig_handler(&SIGUSR1_level,&SIGUSR1_sec);
  754. PrintLogFile(&log_signal_file,"#SIGNAL USR1: level set to %d\n",SIGUSR1_level);
  755. break;
  756. case SIGUSR2:
  757. inc_sig_handler(&SIGUSR2_level,&SIGUSR2_sec);
  758. PrintLogFile(&log_signal_file,"#SIGNAL USR2: level set to %d\n",SIGUSR2_level);
  759. break;
  760. case SIGPIPE:
  761. SIGPIPE_level++;
  762. if (!had_sigpipe)
  763. {
  764. PrintLogFile(&log_signal_file,"#SIGNAL SIGPIPE: %d\n",SIGPIPE_level);
  765. had_sigpipe = true;
  766. }
  767. if ( SIGPIPE_level >= 5 )
  768. {
  769. PrintLogFile(&log_signal_file,"#SIGNAL SIGPIPE: TERMINATE IMMEDIATELY!\n");
  770. exit(0);
  771. }
  772. break;
  773. default:
  774. PrintLogFile(&log_signal_file,"#SIGNAL: %d\n",signum);
  775. }
  776. fflush(stderr);
  777. }
  778. ///////////////////////////////////////////////////////////////////////////////
  779. void SetupSignalHandler ( int max_sigint_level, FILE *log_file )
  780. {
  781. SIGINT_level_max = max_sigint_level;
  782. if (log_file)
  783. {
  784. log_signal_file.log = log_file;
  785. log_signal_file.flush = true;
  786. }
  787. static const int sigtab[] = { SIGTERM, SIGINT, SIGHUP, SIGALRM, SIGPIPE, -1 };
  788. int i;
  789. for ( i = 0; sigtab[i] >= 0; i++ )
  790. {
  791. struct sigaction sa;
  792. memset(&sa,0,sizeof(sa));
  793. sa.sa_handler = &sig_handler;
  794. sigaction(sigtab[i],&sa,0);
  795. }
  796. }
  797. ///////////////////////////////////////////////////////////////////////////////
  798. int SleepNSec ( s_nsec_t nsec )
  799. {
  800. if ( nsec > 0 )
  801. {
  802. struct timespec ts;
  803. ts.tv_sec = nsec / NSEC_PER_SEC;
  804. ts.tv_nsec = nsec % NSEC_PER_SEC;
  805. return nanosleep(&ts,0);
  806. }
  807. return 0;
  808. }
  809. //
  810. ///////////////////////////////////////////////////////////////////////////////
  811. /////////////// PathCat*() ///////////////
  812. ///////////////////////////////////////////////////////////////////////////////
  813. char * PathCatBufPP ( char * buf, ssize_t bufsize, ccp path1, ccp path2 )
  814. {
  815. // concatenate path + path; returns buf
  816. DASSERT(buf);
  817. DASSERT(bufsize);
  818. if ( !path1 || !*path1 )
  819. {
  820. if (path2)
  821. StringCopyS(buf,bufsize,path2);
  822. else
  823. *buf = 0;
  824. return buf;
  825. }
  826. char * ptr = StringCopyS(buf,bufsize-1,path1);
  827. DASSERT( ptr > buf );
  828. if ( ptr[-1] != '/' )
  829. *ptr++ = '/';
  830. if (path2)
  831. {
  832. while ( *path2 == '/' )
  833. path2++;
  834. StringCopyE(ptr,buf+bufsize,path2);
  835. }
  836. return buf;
  837. }
  838. ///////////////////////////////////////////////////////////////////////////////
  839. ccp PathCatPP ( char * buf, ssize_t bufsize, ccp path1, ccp path2 )
  840. {
  841. // concatenate path + path; returns path1 | path2 | buf
  842. if ( !path1 || !*path1 )
  843. return path2 ? path2 : EmptyString;
  844. if ( !path2 || !*path2 )
  845. return path1;
  846. char * ptr = StringCopyS(buf,bufsize-1,path1);
  847. DASSERT( ptr > buf );
  848. if ( ptr[-1] != '/' )
  849. *ptr++ = '/';
  850. while ( *path2 == '/' )
  851. path2++;
  852. StringCopyE(ptr,buf+bufsize,path2);
  853. return buf;
  854. }
  855. ///////////////////////////////////////////////////////////////////////////////
  856. ccp PathCatDirP ( char * buf, ssize_t bufsize, ccp path1, ccp path2 )
  857. {
  858. // concatenate path + path; returns path1 | path2 | buf
  859. if ( !path1 || !*path1 )
  860. return path2 ? path2 : EmptyString;
  861. if ( !path2 || !*path2 || !IsDirectory(path1,0) )
  862. return path1;
  863. return PathCatPP(buf,bufsize,path1,path2);
  864. }
  865. ///////////////////////////////////////////////////////////////////////////////
  866. ccp PathAllocPP ( ccp path1, ccp path2 )
  867. {
  868. char buf[PATH_MAX];
  869. return STRDUP(PathCatPP(buf,sizeof(buf),path1,path2));
  870. }
  871. ///////////////////////////////////////////////////////////////////////////////
  872. ///////////////////////////////////////////////////////////////////////////////
  873. char * PathCatBufPPE ( char * buf, ssize_t bufsize, ccp path1, ccp path2, ccp ext )
  874. {
  875. // concatenate path + path; returns (by definition) path1 | path2 | buf
  876. DASSERT(buf);
  877. DASSERT(bufsize);
  878. char *ptr = path1 ? StringCopyS(buf,bufsize-1,path1) : buf;
  879. *ptr = 0;
  880. if (path2)
  881. {
  882. if ( ptr > buf && ptr[-1] != '/' )
  883. *ptr++ = '/';
  884. while ( *path2 == '/' )
  885. path2++;
  886. ptr = StringCopyE(ptr,buf+bufsize,path2);
  887. }
  888. if (ext)
  889. StringCopyE(ptr,buf+bufsize,ext);
  890. return buf;
  891. }
  892. ///////////////////////////////////////////////////////////////////////////////
  893. // PathCatPPE() is inline
  894. ///////////////////////////////////////////////////////////////////////////////
  895. ccp PathAllocPPE ( ccp path1, ccp path2, ccp ext )
  896. {
  897. char buf[PATH_MAX];
  898. return STRDUP(PathCatPPE(buf,sizeof(buf),path1,path2,ext));
  899. }
  900. ///////////////////////////////////////////////////////////////////////////////
  901. ///////////////////////////////////////////////////////////////////////////////
  902. char * PathCatBufBP ( char *buf, ssize_t bufsize, ccp base, ccp path )
  903. {
  904. // PathCatBP() is special: path can be part of buf
  905. if (!path)
  906. path = "";
  907. if ( *path == '/' || base && !*base )
  908. {
  909. // already absolute | no base to add
  910. StringCopyS(buf,bufsize,path);
  911. return buf;
  912. }
  913. //--- now copy base or cwd
  914. while ( path[0] == '.' && path[1] == '/' )
  915. path += 2;
  916. char buf2[PATH_MAX];
  917. StringCopyS(buf2,sizeof(buf2),path);
  918. char *dest;
  919. if (base)
  920. dest = StringCopyS(buf,bufsize,base);
  921. else
  922. {
  923. char *cwd = getcwd(buf,bufsize);
  924. if (cwd)
  925. dest = buf + strlen(buf);
  926. else
  927. {
  928. // on error: return fallback
  929. dest = StringCopyS(buf,bufsize,"./");
  930. }
  931. }
  932. StringCat2E(dest,buf+bufsize,"/",buf2);
  933. return buf;
  934. }
  935. ///////////////////////////////////////////////////////////////////////////////
  936. ccp PathCatBP ( char *buf, ssize_t bufsize, ccp base, ccp path )
  937. {
  938. // PathCatBP() is special: path can be part of buf
  939. if ( path && *path == '/' || base && !*base )
  940. return path; // already absolute | no base to add
  941. return PathCatBufBP(buf,bufsize,base,path);
  942. }
  943. ///////////////////////////////////////////////////////////////////////////////
  944. ccp PathAllocBP ( ccp base, ccp path )
  945. {
  946. char buf[PATH_MAX];
  947. return STRDUP(PathCatBP(buf,sizeof(buf),base,path));
  948. }
  949. ///////////////////////////////////////////////////////////////////////////////
  950. ///////////////////////////////////////////////////////////////////////////////
  951. char * PathCatBufBPP ( char * buf, ssize_t bufsize, ccp base, ccp path1, ccp path2 )
  952. {
  953. ccp path = PathCatPP(buf,bufsize,path1,path2);
  954. return PathCatBufBP(buf,bufsize,base,path);
  955. }
  956. ///////////////////////////////////////////////////////////////////////////////
  957. ccp PathCatBPP ( char * buf, ssize_t bufsize, ccp base, ccp path1, ccp path2 )
  958. {
  959. ccp path = PathCatPP(buf,bufsize,path1,path2);
  960. return PathCatBP(buf,bufsize,base,path);
  961. }
  962. ///////////////////////////////////////////////////////////////////////////////
  963. ccp PathAllocBPP ( ccp base, ccp path1, ccp path2 )
  964. {
  965. char buf[PATH_MAX];
  966. return STRDUP(PathCatBPP(buf,sizeof(buf),base,path1,path2));
  967. }
  968. ///////////////////////////////////////////////////////////////////////////////
  969. ///////////////////////////////////////////////////////////////////////////////
  970. char * PathCatBufBPPE ( char * buf, ssize_t bufsize, ccp base, ccp path1, ccp path2, ccp ext )
  971. {
  972. ccp path = PathCatPPE(buf,bufsize,path1,path2,ext);
  973. return PathCatBufBP(buf,bufsize,base,path);
  974. }
  975. ///////////////////////////////////////////////////////////////////////////////
  976. ccp PathCatBPPE ( char * buf, ssize_t bufsize, ccp base, ccp path1, ccp path2, ccp ext )
  977. {
  978. ccp path = PathCatPPE(buf,bufsize,path1,path2,ext);
  979. return PathCatBP(buf,bufsize,base,path);
  980. }
  981. ///////////////////////////////////////////////////////////////////////////////
  982. ccp PathAllocBPPE ( ccp base, ccp path1, ccp path2, ccp ext )
  983. {
  984. char buf[PATH_MAX];
  985. return STRDUP(PathCatBPPE(buf,sizeof(buf),base,path1,path2,ext));
  986. }
  987. ///////////////////////////////////////////////////////////////////////////////
  988. ///////////////////////////////////////////////////////////////////////////////
  989. char * PathCombine ( char *buf, uint buf_size, ccp path, ccp base_path )
  990. {
  991. DASSERT(buf);
  992. DASSERT( buf_size > 10 );
  993. if (!path)
  994. path = "";
  995. char *dest = buf;
  996. if ( base_path && *base_path && *path != '/' )
  997. {
  998. StringCopyS(buf,buf_size,base_path);
  999. char *p = strrchr(buf,'/');
  1000. if (p)
  1001. dest = p+1;
  1002. }
  1003. StringCopyE(dest,buf+buf_size,path);
  1004. return buf;
  1005. }
  1006. ///////////////////////////////////////////////////////////////////////////////
  1007. char * PathCombineFast ( char *buf, uint buf_size, ccp path, ccp base_path )
  1008. {
  1009. DASSERT(buf);
  1010. DASSERT( buf_size > 10 );
  1011. if (!path)
  1012. path = "";
  1013. if ( !base_path || !*base_path || *path == '/' )
  1014. return (char*)path;
  1015. StringCopyS(buf,buf_size,base_path);
  1016. char *p = strrchr(buf,'/');
  1017. if (!p)
  1018. return (char*)path;
  1019. StringCopyE(p+1,buf+buf_size,path);
  1020. return buf;
  1021. }
  1022. ///////////////////////////////////////////////////////////////////////////////
  1023. ///////////////////////////////////////////////////////////////////////////////
  1024. char * NewFileExtE ( char * buf, ccp buf_end, ccp path, ccp ext )
  1025. {
  1026. DASSERT( buf);
  1027. DASSERT( buf_end);
  1028. DASSERT( buf_end > buf );
  1029. char * end = path && path != buf
  1030. ? StringCopyE(buf,buf_end-1,path)
  1031. : buf + strlen(buf);
  1032. DASSERT( end < buf_end );
  1033. char * ptr = end;
  1034. while ( ptr > buf && *--ptr != '/' )
  1035. if ( *ptr == '.' )
  1036. {
  1037. end = ptr;
  1038. break;
  1039. }
  1040. if ( ext && *ext )
  1041. {
  1042. if ( *ext != '.' )
  1043. *end++ = '.';
  1044. end = StringCopyE(end,buf_end,ext);
  1045. }
  1046. *end = 0;
  1047. return end;
  1048. }
  1049. ///////////////////////////////////////////////////////////////////////////////
  1050. char * NewFileExtS ( char * buf, ssize_t bufsize, ccp path, ccp ext )
  1051. {
  1052. return NewFileExtE(buf,buf+bufsize,path,ext);
  1053. }
  1054. ///////////////////////////////////////////////////////////////////////////////
  1055. int StrPathCmp ( ccp path1, ccp path2 )
  1056. {
  1057. if ( path1[0] == '.' && path1[1] == '/' )
  1058. path1 += 2;
  1059. if ( path2[0] == '.' && path2[1] == '/' )
  1060. path2 += 2;
  1061. return strcmp(path1,path2);
  1062. }
  1063. ///////////////////////////////////////////////////////////////////////////////
  1064. ///////////////////////////////////////////////////////////////////////////////
  1065. int PathCmp
  1066. (
  1067. ccp path1, // NULL or first path
  1068. ccp path2, // NULL or second path
  1069. uint mode // bit field:
  1070. // 1: skip (multiple) leading './'
  1071. // 2: compare case insensitive
  1072. // 4: sort with respect for unsigned decimal numbers
  1073. )
  1074. {
  1075. if (!path2)
  1076. return path1 != 0;
  1077. if (!path1)
  1078. return -1;
  1079. noPRINT("PathCmp( | %s | %s | %u )\n",path1,path2,mode);
  1080. //--- skip './'
  1081. if ( mode & 1 )
  1082. {
  1083. while ( path1[0] == '.' && path1[1] == '/' )
  1084. path1 += 2;
  1085. while ( path2[0] == '.' && path2[1] == '/' )
  1086. path2 += 2;
  1087. }
  1088. //--- eliminate equal characters
  1089. while ( *path1 == *path2 )
  1090. {
  1091. if (!*path1)
  1092. return 0;
  1093. path1++;
  1094. path2++;
  1095. }
  1096. //--- start the case+path test
  1097. ccp p1 = path1;
  1098. ccp p2 = path2;
  1099. const uint ignore_case = mode & 2;
  1100. while ( *p1 || *p2 )
  1101. {
  1102. int ch1, ch2;
  1103. if (ignore_case)
  1104. {
  1105. ch1 = (uchar)tolower((int)*p1++);
  1106. ch2 = (uchar)tolower((int)*p2++);
  1107. }
  1108. else
  1109. {
  1110. ch1 = (uchar)*p1++;
  1111. ch2 = (uchar)*p2++;
  1112. }
  1113. int stat = ch1 - ch2;
  1114. noPRINT("%02x,%02x,%c %02x,%02x,%c -> %2d\n",
  1115. p1[-1], ch1, ch1, p2[-1], ch2, ch2, stat );
  1116. if (stat)
  1117. {
  1118. if ( mode & 4 )
  1119. {
  1120. p1--;
  1121. while ( *p1 == '0' )
  1122. p1++;
  1123. ccp q1 = p1;
  1124. while ( *q1 >= '0' && *q1 <= '9' )
  1125. q1++;
  1126. const int len1 = q1 - p1;
  1127. if (len1)
  1128. {
  1129. p2--;
  1130. while ( *p2 == '0' )
  1131. p2++;
  1132. ccp q2 = p2;
  1133. while ( *q2 >= '0' && *q2 <= '9' )
  1134. q2++;
  1135. const int len2 = q2 - p2;
  1136. if (len2)
  1137. {
  1138. int stat2 = len1 - len2;
  1139. if (!stat2)
  1140. stat2 = memcmp(p1,p2,len1);
  1141. if (stat2)
  1142. return stat2;
  1143. }
  1144. }
  1145. }
  1146. return ch1 == '/' ? -1 : ch2 == '/' ? 1 : stat;
  1147. }
  1148. if ( ch1 == '/' )
  1149. break;
  1150. }
  1151. return strcmp(path1,path2);
  1152. }
  1153. ///////////////////////////////////////////////////////////////////////////////
  1154. int StrNumCmp ( ccp a, ccp b )
  1155. {
  1156. if (!b)
  1157. return a != 0;
  1158. if (!a)
  1159. return -1;
  1160. for(;;)
  1161. {
  1162. const int va = *a++ & 0xff;
  1163. const int vb = *b++ & 0xff;
  1164. const int delta = va - vb;
  1165. if (delta)
  1166. {
  1167. if ( va < '0' || va > '9' || vb < '0' || vb > '9' )
  1168. return delta; // no number
  1169. //--- both are numbers
  1170. a--;
  1171. while ( *a == '0' )
  1172. a++;
  1173. ccp start_a = a;
  1174. while ( *a >= '0' && *a <= '9' )
  1175. a++;
  1176. b--;
  1177. while ( *b == '0' )
  1178. b++;
  1179. ccp start_b = b;
  1180. while ( *b >= '0' && *b <= '9' )
  1181. b++;
  1182. // compare num length
  1183. int num_delta = ( a - start_a ) - ( b - start_b );
  1184. if (num_delta)
  1185. return num_delta;
  1186. // compare numeric values
  1187. while ( start_a < a )
  1188. {
  1189. num_delta = *start_a++ - *start_b++;
  1190. if (num_delta)
  1191. return num_delta;
  1192. }
  1193. // number identical, but not string
  1194. return delta;
  1195. }
  1196. else if (!va)
  1197. return 0;
  1198. }
  1199. }
  1200. ///////////////////////////////////////////////////////////////////////////////
  1201. uint CountEqual ( cvp m1, cvp m2, uint size )
  1202. {
  1203. const u8 *p1 = m1;
  1204. const u8 *p2 = m2;
  1205. while ( size-- )
  1206. if ( *p1++ != *p2++ )
  1207. return p1 - (u8*)m1 - 1;
  1208. return p1 - (u8*)m1;
  1209. }
  1210. ///////////////////////////////////////////////////////////////////////////////
  1211. ///////////////////////////////////////////////////////////////////////////////
  1212. char * SkipEscapes ( ccp str )
  1213. {
  1214. if (str)
  1215. {
  1216. while ( *str == '\e' )
  1217. {
  1218. str++;
  1219. if ( *str == '[' )
  1220. str++;
  1221. while ( *str > 0 && *str < 0x40 )
  1222. str++;
  1223. if (*str)
  1224. str++;
  1225. }
  1226. }
  1227. return (char*)str;
  1228. }
  1229. //-----------------------------------------------------------------------------
  1230. char * SkipEscapesE ( ccp str, ccp end )
  1231. {
  1232. if (str)
  1233. {
  1234. if (!end)
  1235. return SkipEscapes(str);
  1236. while ( str < end && *str == '\e' )
  1237. {
  1238. str++;
  1239. if ( str < end && *str == '[' )
  1240. str++;
  1241. while ( str < end && *str > 0 && *str < 0x40 )
  1242. str++;
  1243. if ( str < end )
  1244. str++;
  1245. }
  1246. }
  1247. return (char*)str;
  1248. }
  1249. //-----------------------------------------------------------------------------
  1250. char * SkipEscapesS ( ccp str, int size )
  1251. {
  1252. return size < 0 ? SkipEscapes(str) : SkipEscapesE(str,str+strlen(str));
  1253. }
  1254. //-----------------------------------------------------------------------------
  1255. mem_t SkipEscapesM ( mem_t mem )
  1256. {
  1257. mem_t res;
  1258. res.ptr = SkipEscapesE(mem.ptr,mem.ptr+mem.len);
  1259. res.len = mem.ptr + mem.len - res.ptr;
  1260. return res;
  1261. }
  1262. ///////////////////////////////////////////////////////////////////////////////
  1263. ///////////////////////////////////////////////////////////////////////////////
  1264. int ReplaceToBuf
  1265. (
  1266. // returns -1 on error (buf to small) or the length of the resulting string.
  1267. // In the later case, a 0 byte is appended, but not counting for the length.
  1268. char *buf, // pointer to buf
  1269. uint buf_size, // size of 'buf'
  1270. ccp src1, // NULL or source, maybe part of 'buf'
  1271. int src1_len, // length of 'src1', if -1: determine by strlen()
  1272. int pos, // robust replace position, <0: relative to end
  1273. int rm_len, // robust num of chars to remove, <0: rm before 'pos'
  1274. ccp src2, // NULL or source to insert, must not be part of 'buf'
  1275. int src2_len // lengh of 'src2', if -1: determine by strlen()
  1276. )
  1277. {
  1278. DASSERT(buf);
  1279. //--- normalize source #2
  1280. if (!src2)
  1281. src2_len = 0;
  1282. else if ( src2_len < 0 )
  1283. src2_len = strlen(src2);
  1284. //--- if source #1 available
  1285. if (src1)
  1286. {
  1287. //--- check src1 length
  1288. if ( src1_len < 0 )
  1289. src1_len = strlen(src1);
  1290. if (!src1_len)
  1291. goto no_src1;
  1292. //--- normalize 'pos'
  1293. if ( pos < 0 )
  1294. {
  1295. pos += src1_len;
  1296. if ( pos < 0 )
  1297. {
  1298. if ( rm_len > 0 )
  1299. {
  1300. rm_len += pos;
  1301. if ( rm_len < 0 )
  1302. rm_len = 0;
  1303. }
  1304. pos = 0;
  1305. }
  1306. }
  1307. else if ( pos > src1_len )
  1308. pos = src1_len;
  1309. //--- normalize 'rm_len'
  1310. if ( rm_len < 0 )
  1311. {
  1312. rm_len = -rm_len;
  1313. if ( rm_len < pos )
  1314. pos -= rm_len;
  1315. else
  1316. {
  1317. rm_len = pos;
  1318. pos = 0;
  1319. }
  1320. }
  1321. else
  1322. {
  1323. const int max = src1_len - pos;
  1324. if ( rm_len > max )
  1325. rm_len = max;
  1326. }
  1327. const int res_len = src1_len + src2_len - rm_len;
  1328. if ( res_len >= buf_size )
  1329. return -1;
  1330. //--- copy src1
  1331. if ( src1 > buf )
  1332. {
  1333. memmove( buf, src1, pos );
  1334. const int pos2 = pos + rm_len;
  1335. memmove( buf+pos+src2_len, src1+pos2, src1_len-pos2 );
  1336. }
  1337. else
  1338. {
  1339. const int pos2 = pos + rm_len;
  1340. memmove( buf+pos+src2_len, src1+pos2, src1_len-pos2 );
  1341. memmove( buf, src1, pos );
  1342. }
  1343. //--- copy src2 & terminate
  1344. memcpy( buf+pos, src2, src2_len );
  1345. buf[res_len] = 0;
  1346. return res_len;
  1347. }
  1348. no_src1:
  1349. if ( src2_len < buf_size )
  1350. {
  1351. memcpy(buf,src2,src2_len);
  1352. buf[src2_len] = 0;
  1353. return src2_len;
  1354. }
  1355. return -1;
  1356. }
  1357. ///////////////////////////////////////////////////////////////////////////////
  1358. ///////////////////////////////////////////////////////////////////////////////
  1359. int NormalizeIndent ( int indent )
  1360. {
  1361. return indent < 0 ? 0 : indent < 50 ? indent : 50;
  1362. }
  1363. ///////////////////////////////////////////////////////////////////////////////
  1364. ///////////////////////////////////////////////////////////////////////////////
  1365. char * SkipControls ( ccp src )
  1366. {
  1367. // skips all character 1..SPACE
  1368. // 'src' can be NULL
  1369. if (src)
  1370. while ( *src > 0 && *src <= ' ' )
  1371. src++;
  1372. return (char*)src;
  1373. }
  1374. ///////////////////////////////////////////////////////////////////////////////
  1375. char * SkipControlsE ( ccp src, ccp end )
  1376. {
  1377. // skips all character 0..SPACE
  1378. // if end==NULL: Use SkipControls()
  1379. // 'src' can be NULL
  1380. if (!end)
  1381. return SkipControls(src);
  1382. if (src)
  1383. while ( src < end && (uchar)*src <= ' ' )
  1384. src++;
  1385. return (char*)src;
  1386. }
  1387. ///////////////////////////////////////////////////////////////////////////////
  1388. char * SkipControls1 ( ccp src, char ch1 )
  1389. {
  1390. // skips all character 1..SPACE and 'ch1'
  1391. // 'src' can be NULL
  1392. if (src)
  1393. while ( *src > 0 && *src <= ' ' || *src == ch1 )
  1394. src++;
  1395. return (char*)src;
  1396. }
  1397. ///////////////////////////////////////////////////////////////////////////////
  1398. char * SkipControlsE1 ( ccp src, ccp end, char ch1 )
  1399. {
  1400. // skips all character 0..SPACE and 'ch1'
  1401. // if end==NULL: Use SkipControls1()
  1402. // 'src' can be NULL
  1403. if (!end)
  1404. return SkipControls1(src,ch1);
  1405. if (src)
  1406. while ( src < end && ( (uchar)*src <= ' ' || *src == ch1 ))
  1407. src++;
  1408. return (char*)src;
  1409. }
  1410. ///////////////////////////////////////////////////////////////////////////////
  1411. char * SkipControls2 ( ccp src, char ch1, char ch2 )
  1412. {
  1413. // skips all character 1..SPACE and 'ch1' and 'ch2'
  1414. // 'src' can be NULL
  1415. if (src)
  1416. while ( *src > 0 && *src <= ' ' || *src == ch1 || *src == ch2 )
  1417. src++;
  1418. return (char*)src;
  1419. }
  1420. ///////////////////////////////////////////////////////////////////////////////
  1421. char * SkipControlsE2 ( ccp src, ccp end, char ch1, char ch2 )
  1422. {
  1423. // skips all character 0..SPACE and 'ch1' and 'ch2'
  1424. // if end==NULL: Use SkipControls2()
  1425. // 'src' can be NULL
  1426. if (!end)
  1427. return SkipControls2(src,ch1,ch2);
  1428. if (src)
  1429. while ( src < end && ( (uchar)*src <= ' ' || *src == ch1 || *src == ch2 ))
  1430. src++;
  1431. return (char*)src;
  1432. }
  1433. ///////////////////////////////////////////////////////////////////////////////
  1434. ///////////////////////////////////////////////////////////////////////////////
  1435. // return the number of chars until first EOL ( \0 | \r | \n );
  1436. // pointer are NULL save
  1437. uint LineLen ( ccp ptr )
  1438. {
  1439. if (!ptr)
  1440. return 0;
  1441. ccp p = ptr;
  1442. while ( *p && *p != '\n' && *p != '\r' )
  1443. p++;
  1444. return p - ptr;
  1445. }
  1446. ///////////////////////////////////////////////////////////////////////////////
  1447. uint LineLenE ( ccp ptr, ccp end )
  1448. {
  1449. if (!ptr)
  1450. return 0;
  1451. if (!end)
  1452. return LineLen(ptr);
  1453. ccp p = ptr;
  1454. while ( p < end && *p && *p != '\n' && *p != '\r' )
  1455. p++;
  1456. return p - ptr;
  1457. }
  1458. ///////////////////////////////////////////////////////////////////////////////
  1459. ///////////////////////////////////////////////////////////////////////////////
  1460. uint TrimBlanks
  1461. (
  1462. char *str, // pointer to string, modified
  1463. ccp end // NULL or end of string
  1464. )
  1465. {
  1466. char *src = str;
  1467. char *dest = str;
  1468. bool space = false;
  1469. while ( end ? src < end : *src )
  1470. {
  1471. DASSERT( dest <= src );
  1472. uchar ch = *src++;
  1473. if ( ch > ' ' )
  1474. {
  1475. if (space)
  1476. {
  1477. space = false;
  1478. if ( dest > str )
  1479. *dest++ = ' ';
  1480. }
  1481. *dest++ = ch;
  1482. }
  1483. else if ( ch == ' ' )
  1484. space = true;
  1485. }
  1486. if ( !end || dest < end )
  1487. *dest = 0;
  1488. return dest - str;
  1489. }
  1490. ///////////////////////////////////////////////////////////////////////////////
  1491. char * ScanName
  1492. (
  1493. // return a pointer to the first unused character
  1494. char *buf, // destination buffer, terminated with NULL
  1495. uint buf_size, // size of 'buf', must be >0
  1496. ccp str, // source string
  1497. ccp end, // NULL or end of 'str'
  1498. bool allow_signs // true: allow '-' and '+'
  1499. )
  1500. {
  1501. DASSERT(buf);
  1502. DASSERT(buf_size);
  1503. if (!str)
  1504. {
  1505. *buf = 0;
  1506. return 0;
  1507. }
  1508. //--- skip leading blanks
  1509. if (end)
  1510. while ( str < end && (uchar)*str <= ' ' )
  1511. str++;
  1512. else
  1513. while ( str < end && *str && (uchar)*str <= ' ' )
  1514. str++;
  1515. char *dest = buf, *dest_end = buf + buf_size - 1;
  1516. while ( end ? str < end : *str )
  1517. {
  1518. const int ch = *str;
  1519. if ( isalnum(ch) || ch == '_' || allow_signs && ( ch =='-' || ch == '+' ) )
  1520. {
  1521. str++;
  1522. if ( dest < dest_end )
  1523. *dest++ = toupper(ch);
  1524. }
  1525. else
  1526. break;
  1527. }
  1528. *dest = 0;
  1529. if (end)
  1530. while ( str < end && (uchar)*str <= ' ' )
  1531. str++;
  1532. else
  1533. while ( str < end && *str && (uchar)*str <= ' ' )
  1534. str++;
  1535. return (char*)str;
  1536. }
  1537. ///////////////////////////////////////////////////////////////////////////////
  1538. ///////////////////////////////////////////////////////////////////////////////
  1539. char * PrintVersion
  1540. (
  1541. char * buf, // result buffer
  1542. // If NULL, a local circulary static buffer is used
  1543. size_t buf_size, // size of 'buf', ignored if buf==NULL
  1544. u32 version // version number to print
  1545. )
  1546. {
  1547. if (!buf)
  1548. buf = GetCircBuf( buf_size = 20 );
  1549. version = htonl(version); // we use big endian here
  1550. const u8 * v = (const u8 *)&version;
  1551. if (v[2])
  1552. {
  1553. if ( !v[3] || v[3] == 0xff )
  1554. snprintf(buf,buf_size,"%u.%02x.%02x",v[0],v[1],v[2]);
  1555. else
  1556. snprintf(buf,buf_size,"%u.%02x.%02x.beta%u",v[0],v[1],v[2],v[3]);
  1557. }
  1558. else
  1559. {
  1560. if ( !v[3] || v[3] == 0xff )
  1561. snprintf(buf,buf_size,"%u.%02x",v[0],v[1]);
  1562. else
  1563. snprintf(buf,buf_size,"%u.%02x.beta%u",v[0],v[1],v[3]);
  1564. }
  1565. return buf;
  1566. }
  1567. ///////////////////////////////////////////////////////////////////////////////
  1568. char * PrintID
  1569. (
  1570. const void * id, // ID to convert in printable format
  1571. size_t id_len, // len of 'id'
  1572. void * buf // Pointer to buffer, size >= id_len + 1
  1573. // If NULL, a local circulary static buffer is used
  1574. )
  1575. {
  1576. if (!buf)
  1577. buf = GetCircBuf( id_len + 1 );
  1578. ccp src = id;
  1579. char * dest = buf;
  1580. while ( id_len-- > 0 )
  1581. {
  1582. const char ch = *src++;
  1583. *dest++ = ch >= ' ' && ch < 0x7f ? ch : '.';
  1584. }
  1585. *dest = 0;
  1586. return buf;
  1587. }
  1588. //
  1589. ///////////////////////////////////////////////////////////////////////////////
  1590. /////////////// circ buf ///////////////
  1591. ///////////////////////////////////////////////////////////////////////////////
  1592. // [[CircBuf]]
  1593. static __thread char circ_buf[CIRC_BUF_SIZE];
  1594. static __thread char *circ_ptr = 0;
  1595. ///////////////////////////////////////////////////////////////////////////////
  1596. bool IsCircBuf ( cvp ptr )
  1597. {
  1598. return ptr && (ccp)ptr >= circ_buf && (ccp)ptr < circ_buf + sizeof(circ_buf);
  1599. }
  1600. ///////////////////////////////////////////////////////////////////////////////
  1601. char * GetCircBuf
  1602. (
  1603. // Never returns NULL, but always ALIGN(4)
  1604. u32 buf_size // wanted buffer size, caller must add 1 for NULL-term
  1605. // if buf_size > CIRC_BUF_MAX_ALLOC:
  1606. // ==> ERROR0(ERR_OUT_OF_MEMORY)
  1607. )
  1608. {
  1609. if (!circ_ptr)
  1610. circ_ptr = circ_buf;
  1611. DASSERT( circ_ptr >= circ_buf && circ_ptr <= circ_buf + sizeof(circ_buf) );
  1612. buf_size = buf_size + 3 & ~3;
  1613. if ( buf_size > CIRC_BUF_MAX_ALLOC )
  1614. {
  1615. ERROR0(ERR_OUT_OF_MEMORY,
  1616. "Circulary buffer too small: needed=%u, half-size=%zu\n",
  1617. buf_size, sizeof(circ_buf)/2 );
  1618. ASSERT(0);
  1619. exit(ERR_OUT_OF_MEMORY);
  1620. }
  1621. if ( circ_buf + sizeof(circ_buf) - circ_ptr < buf_size )
  1622. circ_ptr = circ_buf;
  1623. char *result = circ_ptr;
  1624. circ_ptr = result + buf_size;
  1625. DASSERT( circ_ptr >= circ_buf && circ_ptr <= circ_buf + sizeof(circ_buf) );
  1626. noPRINT("CIRC-BUF: %3u -> %3zu / %3zu / %3zu\n",
  1627. buf_size, result-circ_buf, circ_ptr-circ_buf, sizeof(circ_buf) );
  1628. return result;
  1629. }
  1630. ///////////////////////////////////////////////////////////////////////////////
  1631. char * CopyCircBuf
  1632. (
  1633. // Never returns NULL, but always ALIGN(4)
  1634. cvp data, // source to copy
  1635. u32 data_size // see GetCircBuf()
  1636. )
  1637. {
  1638. char *dest = GetCircBuf(data_size);
  1639. memcpy(dest,data,data_size);
  1640. return dest;
  1641. }
  1642. ///////////////////////////////////////////////////////////////////////////////
  1643. char * CopyCircBuf0
  1644. (
  1645. // Like CopyCircBuf(), but an additional char is alloced and set to NULL
  1646. // Never returns NULL, but always ALIGN(4).
  1647. cvp data, // source to copy
  1648. u32 data_size // see GetCircBuf()
  1649. )
  1650. {
  1651. char *dest = GetCircBuf(data_size+1);
  1652. memcpy(dest,data,data_size);
  1653. dest[data_size] = 0;
  1654. return dest;
  1655. }
  1656. ///////////////////////////////////////////////////////////////////////////////
  1657. char * PrintCircBuf
  1658. (
  1659. // returns CopyCircBuf0() or EmptyString.
  1660. ccp format, // format string for vsnprintf()
  1661. ... // arguments for 'format'
  1662. )
  1663. {
  1664. char buf[CIRC_BUF_MAX_ALLOC-1];
  1665. va_list arg;
  1666. va_start(arg,format);
  1667. const int len = vsnprintf(buf,sizeof(buf),format,arg);
  1668. va_end(arg);
  1669. return len > 0 ? CopyCircBuf0(buf,len) : (char*)EmptyString;
  1670. }
  1671. ///////////////////////////////////////////////////////////////////////////////
  1672. char * AllocCircBuf
  1673. (
  1674. // Never returns NULL. Call FreeString(RESULT) to free possible alloced memory.
  1675. cvp src, // NULL or source
  1676. int src_len, // len of 'src'; if -1: use strlen(source)
  1677. bool try_circ // use circ-buffer, if result is small enough
  1678. )
  1679. {
  1680. if (!src)
  1681. return (char*)EmptyString;
  1682. if ( src_len < 0 )
  1683. src_len = strlen(src);
  1684. return try_circ && src_len <= CIRC_BUF_MAX_ALLOC
  1685. ? CopyCircBuf(src,src_len)
  1686. : MEMDUP(src,src_len);
  1687. }
  1688. ///////////////////////////////////////////////////////////////////////////////
  1689. char * AllocCircBuf0
  1690. (
  1691. // Never returns NULL. Call FreeString(RESULT) to free possible alloced memory.
  1692. // Like AllocCircBuf(), but an additional char is alloced and set to NULL
  1693. cvp src, // NULL or source
  1694. int src_len, // len of 'src'; if -1: use strlen(source)
  1695. bool try_circ // use circ-buffer, if result is small enough
  1696. )
  1697. {
  1698. if (!src)
  1699. return (char*)EmptyString;
  1700. if ( src_len < 0 )
  1701. src_len = strlen(src);
  1702. return try_circ && src_len < CIRC_BUF_MAX_ALLOC
  1703. ? CopyCircBuf0(src,src_len)
  1704. : MEMDUP(src,src_len); // MEMDUP() always add 0-term
  1705. }
  1706. ///////////////////////////////////////////////////////////////////////////////
  1707. void ReleaseCircBuf
  1708. (
  1709. ccp end_buf, // pointer to end of previous alloced buffer
  1710. uint release_size // number of bytes to give back from end
  1711. )
  1712. {
  1713. if (!circ_ptr)
  1714. circ_ptr = circ_buf;
  1715. DASSERT( circ_ptr >= circ_buf && circ_ptr <= circ_buf + sizeof(circ_buf) );
  1716. if ( end_buf == circ_ptr
  1717. && release_size <= CIRC_BUF_MAX_ALLOC
  1718. && circ_ptr >= circ_buf + release_size )
  1719. {
  1720. circ_ptr -= release_size;
  1721. DASSERT( circ_ptr >= circ_buf && circ_ptr <= circ_buf + sizeof(circ_buf) );
  1722. }
  1723. }
  1724. //
  1725. ///////////////////////////////////////////////////////////////////////////////
  1726. /////////////// PrintMode_t ///////////////
  1727. ///////////////////////////////////////////////////////////////////////////////
  1728. void SetupPrintMode ( PrintMode_t * pm )
  1729. {
  1730. DASSERT(pm);
  1731. //-- stdout
  1732. if (!pm->fout)
  1733. {
  1734. pm->fout = stdout;
  1735. pm->cout = colout;
  1736. }
  1737. if (!pm->cout)
  1738. pm->cout = GetColorSet0();
  1739. //-- stderr
  1740. //if (!pm->ferr) pm->ferr = stderr;
  1741. if (!pm->cerr)
  1742. pm->cerr = GetColorSet0();
  1743. //-- stdlog
  1744. if (pm->flog)
  1745. {
  1746. if (!pm->clog)
  1747. pm->clog = GetColorSet0();
  1748. }
  1749. else if (pm->ferr)
  1750. {
  1751. pm->flog = pm->ferr;
  1752. pm->clog = pm->cerr;
  1753. }
  1754. else
  1755. {
  1756. pm->flog = pm->fout;
  1757. pm->clog = pm->cout;
  1758. }
  1759. //-- misc
  1760. if (!pm->prefix) pm->prefix = EmptyString;
  1761. if (!pm->eol) pm->eol = "\n";
  1762. pm->indent = NormalizeIndent(pm->indent);
  1763. }
  1764. //
  1765. ///////////////////////////////////////////////////////////////////////////////
  1766. /////////////// get line by list ///////////////
  1767. ///////////////////////////////////////////////////////////////////////////////
  1768. ccp GetLineByListHelper ( const int *list, ccp beg, ccp mid, ccp end, ccp line )
  1769. {
  1770. DASSERT(list);
  1771. DASSERT(beg);
  1772. DASSERT(mid);
  1773. DASSERT(end);
  1774. DASSERT(line);
  1775. char buf[CIRC_BUF_MAX_ALLOC+20];
  1776. char *endbuf = buf + CIRC_BUF_MAX_ALLOC;
  1777. char *dest = buf;
  1778. for (;;)
  1779. {
  1780. int wd = *list++;
  1781. if ( wd < 0 )
  1782. break;
  1783. dest = StringCopyE(dest,endbuf,beg);
  1784. beg = mid;
  1785. while ( wd-- > 0 )
  1786. dest = StringCopyE(dest,endbuf,line);
  1787. }
  1788. dest = StringCopyE(dest,endbuf,end);
  1789. *dest++ = 0;
  1790. return dest <= endbuf ? CopyCircBuf(buf,dest-buf) : EmptyString;
  1791. }
  1792. //
  1793. ///////////////////////////////////////////////////////////////////////////////
  1794. /////////////// struct FastBuf_t ///////////////
  1795. ///////////////////////////////////////////////////////////////////////////////
  1796. FastBuf_t * InitializeFastBuf ( cvp mem, uint size )
  1797. {
  1798. DASSERT(mem);
  1799. DASSERT( size >= sizeof(FastBuf_t) );
  1800. FastBuf_t *fb = (FastBuf_t*)mem;
  1801. int buf_size = (int)size - offsetof(FastBuf_t,fast_buf);
  1802. if ( buf_size < sizeof(fb->fast_buf) )
  1803. {
  1804. PrintError(__FUNCTION__,__FILE__,__LINE__,0,ERR_OUT_OF_MEMORY,
  1805. "Out of memory, FastBuf_t is at least %zd bytes to short.",
  1806. sizeof(fb->fast_buf) - size );
  1807. ASSERT(0);
  1808. return 0;
  1809. }
  1810. fb->fast_buf_size = buf_size;
  1811. fb->buf = fb->ptr = fb->fast_buf;
  1812. fb->end = fb->buf + buf_size - 1;
  1813. DASSERT( fb->buf < fb->end );
  1814. return fb;
  1815. }
  1816. //-----------------------------------------------------------------------------
  1817. FastBuf_t * InitializeFastBufAlloc ( FastBuf_t *fb, uint size )
  1818. {
  1819. DASSERT(fb);
  1820. InitializeFastBuf(fb,sizeof(*fb));
  1821. const uint new_size = GetGoodAllocSize(size+10);
  1822. fb->buf = MALLOC(new_size);
  1823. fb->ptr = fb->buf;
  1824. fb->end = fb->buf + new_size - 1;
  1825. return fb;
  1826. }
  1827. ///////////////////////////////////////////////////////////////////////////////
  1828. #define RESET_FASTBUF(fb) fb->buf = fb->ptr = fb->fast_buf; \
  1829. fb->end = fb->buf + fb->fast_buf_size - 1;
  1830. void ResetFastBuf ( FastBuf_t *fb )
  1831. {
  1832. DASSERT(fb);
  1833. if ( fb->buf != fb->fast_buf )
  1834. FREE(fb->buf);
  1835. RESET_FASTBUF(fb)
  1836. }
  1837. ///////////////////////////////////////////////////////////////////////////////
  1838. ccp GetFastBufStatus ( const FastBuf_t *fb )
  1839. {
  1840. char info[100];
  1841. int len = snprintf(info,sizeof(info),"%s=%u/%u",
  1842. fb->buf == fb->fast_buf ? "FastBuf" : "Alloc",
  1843. (uint)(fb->ptr - fb->buf), (uint)(fb->end - fb->buf) );
  1844. return CopyCircBuf(info,len+1);
  1845. }
  1846. ///////////////////////////////////////////////////////////////////////////////
  1847. ///////////////////////////////////////////////////////////////////////////////
  1848. char * MoveFromFastBufString ( FastBuf_t *fb )
  1849. {
  1850. DASSERT(fb);
  1851. *fb->ptr = 0;
  1852. char *res;
  1853. if ( fb->buf == fb->fast_buf )
  1854. {
  1855. res = MEMDUP(fb->buf,fb->ptr-fb->buf);
  1856. fb->ptr = fb->buf;
  1857. }
  1858. else
  1859. {
  1860. res = fb->buf;
  1861. RESET_FASTBUF(fb)
  1862. }
  1863. return res;
  1864. }
  1865. ///////////////////////////////////////////////////////////////////////////////
  1866. mem_t MoveFromFastBufMem ( FastBuf_t *fb )
  1867. {
  1868. DASSERT(fb);
  1869. *fb->ptr = 0;
  1870. mem_t res;
  1871. res.len = fb->ptr - fb->buf;
  1872. if ( fb->buf == fb->fast_buf )
  1873. {
  1874. res.ptr = MEMDUP(fb->buf,res.len);
  1875. fb->ptr = fb->buf;
  1876. }
  1877. else
  1878. {
  1879. res.ptr = fb->buf;
  1880. RESET_FASTBUF(fb)
  1881. }
  1882. return res;
  1883. }
  1884. ///////////////////////////////////////////////////////////////////////////////
  1885. ///////////////////////////////////////////////////////////////////////////////
  1886. char * GetSpaceFastBuf ( FastBuf_t *fb, uint size )
  1887. {
  1888. DASSERT(fb);
  1889. if ( size > fb->end - fb->ptr )
  1890. {
  1891. const uint used = fb->ptr - fb->buf;
  1892. const uint new_size = GetGoodAllocSize( used + used/4 + size + 1000 );
  1893. if ( fb->buf == fb->fast_buf )
  1894. {
  1895. fb->buf = MALLOC(new_size);
  1896. memcpy(fb->buf,fb->fast_buf,used);
  1897. }
  1898. else
  1899. fb->buf = REALLOC(fb->buf,new_size);
  1900. fb->ptr = fb->buf + used;
  1901. fb->end = fb->buf + new_size - 1;
  1902. }
  1903. char *res = fb->ptr;
  1904. fb->ptr += size;
  1905. return res;
  1906. }
  1907. //-----------------------------------------------------------------------------
  1908. int ReserveSpaceFastBuf ( FastBuf_t *fb, uint size )
  1909. {
  1910. DASSERT(fb);
  1911. if ( size > 0 )
  1912. fb->ptr = GetSpaceFastBuf(fb,size);
  1913. return fb->end - fb->ptr;
  1914. }
  1915. ///////////////////////////////////////////////////////////////////////////////
  1916. uint InsertFastBuf ( FastBuf_t *fb, int index, cvp source, int size )
  1917. {
  1918. DASSERT(fb);
  1919. DASSERT(source||!size);
  1920. if ( size < 0 )
  1921. size = strlen(source);
  1922. const uint len = fb->ptr - fb->buf;
  1923. index = CheckIndex1(len,index);
  1924. noPRINT("index=%d/%d/%zd, size=%d\n",index,len,fb->end-fb->buf,size);
  1925. char *ptr = GetSpaceFastBuf(fb,size);
  1926. char *dest = fb->buf + index;
  1927. DASSERT( dest >= fb->buf );
  1928. DASSERT( dest + size + len <= fb->end );
  1929. memmove(dest+size,dest,ptr-dest);
  1930. memcpy(dest,source,size);
  1931. return index;
  1932. }
  1933. ///////////////////////////////////////////////////////////////////////////////
  1934. char * AppendFastBuf ( FastBuf_t *fb, cvp source, int size )
  1935. {
  1936. DASSERT(fb);
  1937. DASSERT(source||!size);
  1938. if ( size < 0 )
  1939. size = strlen(source);
  1940. char *dest = GetSpaceFastBuf(fb,size);
  1941. memcpy(dest,source,size);
  1942. return dest;
  1943. }
  1944. ///////////////////////////////////////////////////////////////////////////////
  1945. void AppendUTF8CharFastBuf ( FastBuf_t *fb, u32 code )
  1946. {
  1947. char buf[8];
  1948. const uint len = PrintUTF8Char(buf,code) - buf;
  1949. char *dest = GetSpaceFastBuf(fb,len);
  1950. memcpy(dest,buf,len);
  1951. }
  1952. ///////////////////////////////////////////////////////////////////////////////
  1953. void AppendBE16FastBuf ( FastBuf_t *fb, u16 num )
  1954. {
  1955. DASSERT(fb);
  1956. char *dest = GetSpaceFastBuf(fb,sizeof(num));
  1957. write_be16(dest,num);
  1958. }
  1959. //-----------------------------------------------------------------------------
  1960. void AppendBE32FastBuf ( FastBuf_t *fb, u32 num )
  1961. {
  1962. DASSERT(fb);
  1963. char *dest = GetSpaceFastBuf(fb,sizeof(num));
  1964. write_be32(dest,num);
  1965. }
  1966. ///////////////////////////////////////////////////////////////////////////////
  1967. void AppendInt64FastBuf ( FastBuf_t *fb, u64 val, IntMode_t mode )
  1968. {
  1969. DASSERT(fb);
  1970. switch(mode)
  1971. {
  1972. case IMD_UNSET:
  1973. AppendFastBuf(fb,&val,sizeof(val));
  1974. break;
  1975. case IMD_BE1:
  1976. case IMD_LE1: AppendCharFastBuf(fb,val); break;
  1977. case IMD_BE2: write_be16(GetSpaceFastBuf(fb,2),val); break;
  1978. case IMD_BE3: write_be24(GetSpaceFastBuf(fb,3),val); break;
  1979. case IMD_BE4: write_be32(GetSpaceFastBuf(fb,4),val); break;
  1980. case IMD_BE5: write_be40(GetSpaceFastBuf(fb,5),val); break;
  1981. case IMD_BE6: write_be48(GetSpaceFastBuf(fb,6),val); break;
  1982. case IMD_BE7: write_be56(GetSpaceFastBuf(fb,7),val); break;
  1983. case IMD_BE0:
  1984. case IMD_BE8: write_be64(GetSpaceFastBuf(fb,8),val); break;
  1985. case IMD_LE2: write_le16(GetSpaceFastBuf(fb,2),val); break;
  1986. case IMD_LE3: write_le24(GetSpaceFastBuf(fb,3),val); break;
  1987. case IMD_LE4: write_le32(GetSpaceFastBuf(fb,4),val); break;
  1988. case IMD_LE5: write_le40(GetSpaceFastBuf(fb,5),val); break;
  1989. case IMD_LE6: write_le48(GetSpaceFastBuf(fb,6),val); break;
  1990. case IMD_LE7: write_le56(GetSpaceFastBuf(fb,7),val); break;
  1991. case IMD_LE0:
  1992. case IMD_LE8: write_le64(GetSpaceFastBuf(fb,8),val); break;
  1993. }
  1994. }
  1995. ///////////////////////////////////////////////////////////////////////////////
  1996. char * WriteFastBuf ( FastBuf_t *fb, uint offset, cvp source, int size )
  1997. {
  1998. DASSERT(fb);
  1999. uint oldlen = fb->ptr - fb->buf;
  2000. uint minlen = offset + size;
  2001. if ( minlen > oldlen )
  2002. {
  2003. char *ptr = GetSpaceFastBuf(fb,minlen-oldlen);
  2004. memset(ptr,0,minlen-oldlen);
  2005. }
  2006. DASSERT( fb->ptr - fb->buf >= minlen );
  2007. char *dest = fb->buf + offset;
  2008. if (source)
  2009. memcpy( dest, source, size );
  2010. return dest;
  2011. }
  2012. ///////////////////////////////////////////////////////////////////////////////
  2013. uint AssignFastBuf ( FastBuf_t *fb, cvp source, int size )
  2014. {
  2015. DASSERT(fb);
  2016. if ( size < 0 )
  2017. size = strlen(source);
  2018. if ( source == fb->buf )
  2019. {
  2020. const uint used = fb->ptr - fb->buf;
  2021. if ( size < used )
  2022. fb->ptr = fb->buf + size;
  2023. else
  2024. size = used;
  2025. }
  2026. else
  2027. {
  2028. fb->ptr = fb->buf;
  2029. if (source)
  2030. AppendFastBuf(fb,source,size);
  2031. *fb->ptr = 0;
  2032. }
  2033. return size;
  2034. }
  2035. ///////////////////////////////////////////////////////////////////////////////
  2036. uint AlignFastBuf ( FastBuf_t *fb, uint align, u8 fill )
  2037. {
  2038. DASSERT(fb);
  2039. const uint len = fb->ptr - fb->buf;
  2040. const uint append = ALIGN32(len,align) - len;
  2041. if ( append > 0 )
  2042. {
  2043. char *dest = GetSpaceFastBuf(fb,append);
  2044. memset(dest,fill,append);
  2045. }
  2046. return fb->ptr - fb->buf;
  2047. }
  2048. ///////////////////////////////////////////////////////////////////////////////
  2049. uint DropFastBuf ( FastBuf_t *fb, int index, int size )
  2050. {
  2051. DASSERT(fb);
  2052. if (size)
  2053. {
  2054. const uint len = fb->ptr - fb->buf;
  2055. index = CheckIndex1(len,index);
  2056. if ( size < 0 )
  2057. {
  2058. size = -size;
  2059. if ( size > index )
  2060. size = index;
  2061. index -= size;
  2062. }
  2063. int index2 = CheckIndex1(len,index+size);
  2064. size = index2 - index;
  2065. if (size)
  2066. {
  2067. memmove(fb->buf+index,fb->buf+index2,len-index2+1);
  2068. fb->ptr -= size;
  2069. }
  2070. }
  2071. return size;
  2072. }
  2073. ///////////////////////////////////////////////////////////////////////////////
  2074. ///////////////////////////////////////////////////////////////////////////////
  2075. void CopyFastBuf ( FastBuf_t *dest, const FastBuf_t *src )
  2076. {
  2077. if ( dest && dest != src )
  2078. {
  2079. if (!src)
  2080. ClearFastBuf(dest);
  2081. else
  2082. AssignFastBuf( dest, src->buf, src->ptr - src->buf );
  2083. }
  2084. }
  2085. ///////////////////////////////////////////////////////////////////////////////
  2086. void MoveFastBuf ( FastBuf_t *dest, FastBuf_t *src )
  2087. {
  2088. if ( dest && src && dest != src )
  2089. {
  2090. if ( src->buf != src->fast_buf )
  2091. {
  2092. // src is allocated
  2093. if ( dest->buf != dest->fast_buf )
  2094. FREE(dest->buf);
  2095. dest->buf = src->buf;
  2096. dest->ptr = src->ptr;
  2097. dest->end = src->end;
  2098. InitializeFastBuf( src, offsetof(FastBuf_t,fast_buf) + src->fast_buf_size );
  2099. }
  2100. else
  2101. AssignFastBuf( dest, src->buf, src->ptr - src->buf );
  2102. }
  2103. }
  2104. //
  2105. ///////////////////////////////////////////////////////////////////////////////
  2106. /////////////// alloc info ///////////////
  2107. ///////////////////////////////////////////////////////////////////////////////
  2108. bool alloc_info_calced = false;
  2109. uint alloc_info_overhead = 8; // default values
  2110. uint alloc_info_block_size = 16;
  2111. uint alloc_info_add1 = 7;
  2112. uint alloc_info_add2 = 8;
  2113. uint alloc_info_mask = ~15;
  2114. ///////////////////////////////////////////////////////////////////////////////
  2115. uint SetupAllocInfo()
  2116. {
  2117. if (!alloc_info_calced)
  2118. {
  2119. alloc_info_calced = true;
  2120. enum { MAX = 200 };
  2121. char *alloc[MAX+1];
  2122. memset(alloc,0,sizeof(alloc));
  2123. uint i, mask_found = ~0;
  2124. for ( i = 1; i <= MAX; i++ )
  2125. {
  2126. alloc[i] = (char*)MALLOC(i);
  2127. noPRINT("%4x: %p [%zx]\n",i,alloc[i],alloc[i]-alloc[ i>0 ? i-1 : 0 ] );
  2128. if ( i > 1 )
  2129. {
  2130. const int diff = abs ( (int)(uintptr_t)(alloc[i-1])
  2131. - (int)(uintptr_t)(alloc[i]) );
  2132. mask_found &= diff - 1;
  2133. }
  2134. }
  2135. const int lo0 = FindLowest0Bit(&mask_found,1);
  2136. const int hi1 = FindHighest1Bit(&mask_found,1);
  2137. PRINT("mask: %08x, lo0=%d, hi1=%d\n",mask_found,lo0,hi1);
  2138. if ( hi1 + 1 == lo0 )
  2139. {
  2140. // -> maske besteht aus hi1 '1' gefolgt von ausnahmslos '0'
  2141. alloc_info_mask = ~mask_found;
  2142. alloc_info_block_size = mask_found + 1;
  2143. PRINT("alloc_info_block_size = %d, alloc_info_mask = 0x%x\n",
  2144. alloc_info_block_size, alloc_info_mask );
  2145. int found = 0x100;
  2146. for ( i = 2; i <= MAX; i++ )
  2147. {
  2148. const int diff = abs ( (int)(uintptr_t)(alloc[i-1])
  2149. - (int)(uintptr_t)(alloc[i]) ) - i;
  2150. if ( diff >= 0 && found > diff )
  2151. found = diff;
  2152. }
  2153. if ( found < MAX )
  2154. {
  2155. alloc_info_overhead = found;
  2156. found %= alloc_info_block_size;
  2157. alloc_info_add1 = found - 1;
  2158. alloc_info_add2 = alloc_info_block_size - found;
  2159. PRINT("alloc_info_overhead = %d, alloc_info_add = %d, %d\n",
  2160. alloc_info_overhead, alloc_info_add1, alloc_info_add2 );
  2161. }
  2162. }
  2163. for ( i = 1; i <= MAX; i++ )
  2164. FREE(alloc[i]);
  2165. }
  2166. return alloc_info_block_size;
  2167. }
  2168. //
  2169. ///////////////////////////////////////////////////////////////////////////////
  2170. /////////////// SplitArg_t ///////////////
  2171. ///////////////////////////////////////////////////////////////////////////////
  2172. void ResetSplitArg ( SplitArg_t *sa )
  2173. {
  2174. DASSERT(sa);
  2175. FREE(sa->argv);
  2176. FREE(sa->temp);
  2177. InitializeSplitArg(sa);
  2178. }
  2179. ///////////////////////////////////////////////////////////////////////////////
  2180. int ScanSplitArg
  2181. (
  2182. // returns arg->argc;
  2183. SplitArg_t *arg, // pointer to object
  2184. bool init_arg, // true: call InitializeSplitArg()
  2185. ccp src, // NULL or source string
  2186. ccp src_end, // end of 'src'; if NULL: calculated by strlen(src)
  2187. char *work_buf // pointer to a buffer for strings, may be 'src'
  2188. // size must be: length of 'src' + 1
  2189. // if NULL, a temporary buffer is alloced.
  2190. )
  2191. {
  2192. DASSERT(arg);
  2193. if (init_arg)
  2194. InitializeSplitArg(arg);
  2195. else
  2196. ResetSplitArg(arg);
  2197. if (!src)
  2198. src = EmptyString;
  2199. if (!src_end)
  2200. src_end = src + strlen(src);
  2201. #ifdef TEST0
  2202. enum { N_PREDEF = 5 };
  2203. #else
  2204. enum { N_PREDEF = 250 };
  2205. #endif
  2206. char *argv_predef[N_PREDEF+1],
  2207. **argv_buf = argv_predef,
  2208. **argv_dest = argv_predef,
  2209. **argv_end = argv_predef + N_PREDEF;
  2210. *argv_dest++ = ProgInfo.progname ? (char*)ProgInfo.progname : "";
  2211. uint argv_size = 0;
  2212. if (!work_buf)
  2213. {
  2214. arg->temp_size = src_end - src + 1;
  2215. arg->temp = work_buf = MALLOC(arg->temp_size);
  2216. }
  2217. char *dest = work_buf;
  2218. //--- main loop
  2219. for(;;)
  2220. {
  2221. while ( src < src_end
  2222. && ( !*src || *src == ' ' || *src == '\t' || *src == '\r' || *src == '\n' ))
  2223. {
  2224. src++;
  2225. }
  2226. if ( src == src_end )
  2227. break;
  2228. if ( argv_dest == argv_end )
  2229. {
  2230. PRINT("NEED MORE: %zu/%zu size=%u: |%s|\n",
  2231. argv_dest-argv_buf, argv_end-argv_buf, argv_size, src );
  2232. const uint idx = argv_dest - argv_buf;
  2233. if (argv_size)
  2234. {
  2235. argv_size += N_PREDEF;
  2236. argv_buf = REALLOC(argv_buf,(argv_size+1)*sizeof(*argv_buf));
  2237. }
  2238. else
  2239. {
  2240. argv_size = 2*N_PREDEF;
  2241. char **temp = MALLOC((argv_size+1)*sizeof(*argv_buf));
  2242. memcpy(temp,argv_buf,idx*sizeof(*argv_buf));
  2243. argv_buf = temp;
  2244. }
  2245. argv_dest = argv_buf + idx;
  2246. argv_end = argv_buf + argv_size;
  2247. }
  2248. *argv_dest++ = dest;
  2249. while ( src < src_end )
  2250. {
  2251. const char ch = *src;
  2252. if ( !ch || ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' )
  2253. break;
  2254. src++;
  2255. if ( ch == '\\' && src < src_end )
  2256. *dest++ = *src++;
  2257. else if ( ch == '\'' )
  2258. {
  2259. while ( src < src_end && *src != '\'' )
  2260. *dest++ = *src++;
  2261. if ( src < src_end )
  2262. src++;
  2263. }
  2264. else if ( ch == '"' )
  2265. {
  2266. while ( src < src_end && *src != '"' )
  2267. {
  2268. char ch = *src++;
  2269. if ( ch == '\\' )
  2270. {
  2271. uint code;
  2272. src = ScanEscape(&code,src,src_end);
  2273. ch = code;
  2274. }
  2275. *dest++ = ch;
  2276. }
  2277. if ( src < src_end )
  2278. src++;
  2279. }
  2280. else
  2281. *dest++ = ch;
  2282. }
  2283. *dest++ = 0;
  2284. }
  2285. *argv_dest = 0;
  2286. arg->argc = argv_dest - argv_buf;
  2287. if ( argv_size )
  2288. {
  2289. DASSERT( argv_buf != argv_predef );
  2290. arg->argv_size = argv_size;
  2291. arg->argv = argv_buf;
  2292. }
  2293. else
  2294. {
  2295. DASSERT( argv_buf == argv_predef );
  2296. arg->argv_size = arg->argc;
  2297. arg->argv = MEMDUP(argv_buf,(arg->argv_size+1)*sizeof(*argv_dest));
  2298. }
  2299. return arg->argc;
  2300. };
  2301. //
  2302. ///////////////////////////////////////////////////////////////////////////////
  2303. /////////////// PointerList_t ///////////////
  2304. ///////////////////////////////////////////////////////////////////////////////
  2305. void ResetPointerMgr ( PointerList_t *pl )
  2306. {
  2307. if (pl)
  2308. {
  2309. FREE(pl->list);
  2310. InitializePointerMgr(pl,pl->grow);
  2311. }
  2312. }
  2313. ///////////////////////////////////////////////////////////////////////////////
  2314. void AddToPointerMgr ( PointerList_t *pl, const void *info )
  2315. {
  2316. DASSERT(pl);
  2317. if (!info)
  2318. return;
  2319. // no duplicates!
  2320. for ( int i = 0; i < pl->used; i++ )
  2321. if ( pl->list[i] == info )
  2322. return;
  2323. if ( pl->used == pl->size )
  2324. {
  2325. if ( pl->grow < 10 )
  2326. pl->grow = 10;
  2327. pl->size += pl->size/2 + pl->grow;
  2328. pl->list = REALLOC ( pl->list, (pl->size+1) * sizeof(*pl->list) );
  2329. }
  2330. DASSERT( pl->used < pl->size );
  2331. void **dest = pl->list + pl->used++;
  2332. *dest++ = (void*)info;
  2333. *dest = 0;
  2334. }
  2335. ///////////////////////////////////////////////////////////////////////////////
  2336. void AddListToPointerMgr ( PointerList_t *pl, const void **list, int n_elem )
  2337. {
  2338. if (list)
  2339. {
  2340. if ( n_elem < 0 )
  2341. while (*list)
  2342. AddToPointerMgr(pl,*list++);
  2343. else
  2344. while( --n_elem >= 0 )
  2345. AddToPointerMgr(pl,*list++);
  2346. }
  2347. }
  2348. ///////////////////////////////////////////////////////////////////////////////
  2349. void ** DupPointerMgr ( PointerList_t *pl, bool reset )
  2350. {
  2351. DASSERT(pl);
  2352. void **dest = MEMDUP( pl->list, (pl->used+1) * sizeof(*dest) );
  2353. if (reset)
  2354. ResetPointerMgr(pl);
  2355. return dest;
  2356. }
  2357. ///////////////////////////////////////////////////////////////////////////////
  2358. void ** ReplacePointerMgr
  2359. ( PointerList_t *pl, bool reset, const PointerList_t **old_list )
  2360. {
  2361. FREE(old_list);
  2362. return DupPointerMgr(pl,reset);
  2363. }
  2364. //
  2365. ///////////////////////////////////////////////////////////////////////////////
  2366. /////////////// ArgManager_t ///////////////
  2367. ///////////////////////////////////////////////////////////////////////////////
  2368. void ResetArgManager ( ArgManager_t *am )
  2369. {
  2370. static char *null_list[] = {0};
  2371. if (am)
  2372. {
  2373. if (am->size)
  2374. {
  2375. uint i;
  2376. for ( i = 0; i < am->argc; i++ )
  2377. FreeString(am->argv[i]);
  2378. if ( am->argv != null_list )
  2379. FREE(am->argv);
  2380. }
  2381. const typeof(am->force_case) force_case = am->force_case;
  2382. memset(am,0,sizeof(*am));
  2383. am->force_case = force_case;
  2384. am->argv = null_list;
  2385. }
  2386. }
  2387. ///////////////////////////////////////////////////////////////////////////////
  2388. void SetupArgManager
  2389. ( ArgManager_t *am, LowerUpper_t force_case, int argc, char ** argv, bool clone )
  2390. {
  2391. DASSERT(am);
  2392. memset(am,0,sizeof(*am));
  2393. am->force_case = force_case;
  2394. if (clone)
  2395. CloneArgManager(am,argc,argv);
  2396. else
  2397. AttachArgManager(am,argc,argv);
  2398. }
  2399. ///////////////////////////////////////////////////////////////////////////////
  2400. void AttachArgManager ( ArgManager_t *am, int argc, char ** argv )
  2401. {
  2402. DASSERT(am);
  2403. ResetArgManager(am);
  2404. am->argc = argc;
  2405. am->argv = argv;
  2406. }
  2407. ///////////////////////////////////////////////////////////////////////////////
  2408. void CloneArgManager ( ArgManager_t *am, int argc, char ** argv )
  2409. {
  2410. DASSERT(am);
  2411. AttachArgManager(am,argc,argv);
  2412. PrepareEditArgManager(am,0);
  2413. }
  2414. ///////////////////////////////////////////////////////////////////////////////
  2415. void CopyArgManager ( ArgManager_t *dest, const ArgManager_t *src )
  2416. {
  2417. DASSERT(dest);
  2418. if (!src)
  2419. ResetArgManager(dest);
  2420. else if( dest != src )
  2421. AttachArgManager(dest,src->argc,src->argv);
  2422. }
  2423. ///////////////////////////////////////////////////////////////////////////////
  2424. void MoveArgManager ( ArgManager_t *dest, ArgManager_t *src )
  2425. {
  2426. DASSERT(dest);
  2427. ResetArgManager(dest);
  2428. if (src)
  2429. {
  2430. dest->argv = src->argv;
  2431. dest->argc = src->argc;
  2432. dest->size = src->size;
  2433. memset(src,0,sizeof(*src));
  2434. }
  2435. }
  2436. ///////////////////////////////////////////////////////////////////////////////
  2437. void PrepareEditArgManager ( ArgManager_t *am, int needed_space )
  2438. {
  2439. DASSERT(am);
  2440. uint new_size = am->argc;
  2441. if ( needed_space > 0 )
  2442. new_size += needed_space;
  2443. new_size = GetGoodAllocSize2(new_size+(new_size>>4)+10,sizeof(*am->argv));
  2444. PRINT("PrepareEditArgManager(,%d) n=%d, size: %d -> %d\n",
  2445. needed_space, am->argc, am->size, new_size );
  2446. if (am->size)
  2447. am->argv = REALLOC(am->argv,sizeof(*am->argv)*new_size);
  2448. else
  2449. {
  2450. char **old = am->argv;
  2451. am->argv = MALLOC(sizeof(*am->argv)*new_size);
  2452. uint i;
  2453. for ( i = 0; i < am->argc; i++ )
  2454. am->argv[i] = old[i] ? STRDUP(old[i]) : 0;
  2455. }
  2456. am->size = new_size - 1;
  2457. DASSERT( am->argc <= am->size );
  2458. am->argv[am->argc] = 0;
  2459. }
  2460. ///////////////////////////////////////////////////////////////////////////////
  2461. uint AppendArgManager ( ArgManager_t *am, ccp arg1, ccp arg2, bool move_arg )
  2462. {
  2463. DASSERT(am);
  2464. PRINT("AppendArgManager(,%s,%s,%d)\n",arg1,arg2,move_arg);
  2465. return InsertArgManager(am,am->argc,arg1,arg2,move_arg);
  2466. }
  2467. ///////////////////////////////////////////////////////////////////////////////
  2468. static char ** insert_arg_manager
  2469. ( ArgManager_t *am, char **dest, ccp p_arg, bool move_arg )
  2470. {
  2471. DASSERT(am);
  2472. if (p_arg)
  2473. {
  2474. char *arg = (char*)p_arg;
  2475. if (!move_arg)
  2476. arg = STRDUP(arg);
  2477. if ( am->force_case == LOUP_LOWER || am->force_case == LOUP_UPPER )
  2478. {
  2479. char * end = arg + strlen(arg) + 1;
  2480. if (am->force_case == LOUP_LOWER)
  2481. StringLowerE(arg,end,arg);
  2482. else
  2483. StringUpperE(arg,end,arg);
  2484. }
  2485. *dest++ = arg;
  2486. }
  2487. return dest;
  2488. }
  2489. //-----------------------------------------------------------------------------
  2490. uint InsertArgManager
  2491. ( ArgManager_t *am, int pos, ccp arg1, ccp arg2, bool move_arg )
  2492. {
  2493. DASSERT(am);
  2494. PRINT("InsertArgManager(,%d,%s,%s,%d)\n",pos,arg1,arg2,move_arg);
  2495. pos = CheckIndex1(am->argc,pos);
  2496. const int n = (arg1!=0) + (arg2!=0);
  2497. if (n)
  2498. {
  2499. PrepareEditArgManager(am,n);
  2500. DASSERT( pos>=0 && pos <= am->argc );
  2501. char **dest = am->argv + pos;
  2502. if ( pos < am->argc )
  2503. memmove( dest+n, dest, (u8*)(am->argv+am->argc) - (u8*)dest );
  2504. dest = insert_arg_manager(am,dest,arg1,move_arg);
  2505. dest = insert_arg_manager(am,dest,arg2,move_arg);
  2506. am->argc += n;
  2507. am->argv[am->argc] = 0;
  2508. }
  2509. return pos+n;
  2510. }
  2511. //-----------------------------------------------------------------------------
  2512. uint InsertListArgManager
  2513. ( ArgManager_t *am, int pos, int argc, char ** argv, bool move_arg )
  2514. {
  2515. DASSERT(am);
  2516. pos = CheckIndex1(am->argc,pos);
  2517. if ( argc > 0 )
  2518. {
  2519. PrepareEditArgManager(am,argc);
  2520. DASSERT( pos>=0 && pos <= am->argc );
  2521. char **dest = am->argv + pos;
  2522. if ( pos < am->argc )
  2523. memmove( dest+argc, dest, (u8*)(am->argv+am->argc) - (u8*)dest );
  2524. pos += argc;
  2525. am->argc += argc;
  2526. am->argv[am->argc] = 0;
  2527. if ( move_arg && am->force_case == LOUP_AUTO )
  2528. memcpy( dest, argv, argc*sizeof(*dest) );
  2529. else
  2530. while ( argc-- > 0 )
  2531. dest = insert_arg_manager(am,dest,*argv++,move_arg);
  2532. }
  2533. return pos;
  2534. }
  2535. ///////////////////////////////////////////////////////////////////////////////
  2536. uint ReplaceArgManager
  2537. ( ArgManager_t *am, int pos, ccp arg1, ccp arg2, bool move_arg )
  2538. {
  2539. PRINT("ReplaceArgManager(,%d,%s,%s,%d)\n",pos,arg1,arg2,move_arg);
  2540. pos = CheckIndex1(am->argc,pos);
  2541. const int n = (arg1!=0) + (arg2!=0);
  2542. if (n)
  2543. {
  2544. PrepareEditArgManager(am,n);
  2545. DASSERT( pos>=0 && pos <= am->argc );
  2546. char **dest = am->argv + pos;
  2547. if (arg1)
  2548. {
  2549. if ( pos++ < am->argc )
  2550. FreeString(*dest);
  2551. *dest++ = move_arg ? (char*)arg1 : STRDUP(arg1);
  2552. }
  2553. if (arg2)
  2554. {
  2555. if ( pos++ < am->argc )
  2556. FreeString(*dest);
  2557. *dest++ = move_arg ? (char*)arg2 : STRDUP(arg2);
  2558. }
  2559. if ( pos > am->argc )
  2560. {
  2561. am->argc = pos;
  2562. am->argv[am->argc] = 0;
  2563. }
  2564. }
  2565. return pos;
  2566. }
  2567. ///////////////////////////////////////////////////////////////////////////////
  2568. uint RemoveArgManager ( ArgManager_t *am, int pos, int count )
  2569. {
  2570. DASSERT(am);
  2571. #if HAVE_PRINT
  2572. const int oldpos = pos;
  2573. #endif
  2574. const int n = CheckIndexC(am->argc,&pos,count);
  2575. PRINT("RemoveArgManager(,%d,%d) : remove n=%d: %d..%d\n",
  2576. oldpos, count, n, pos, pos+n );
  2577. DASSERT( pos >= 0 && pos <= am->argc );
  2578. DASSERT( n >= 0 && pos+n <= am->argc );
  2579. if ( n > 0 )
  2580. {
  2581. PrepareEditArgManager(am,0);
  2582. char **dest = am->argv + pos;
  2583. uint i;
  2584. for ( i = 0; i <n; i++ )
  2585. FreeString(dest[i]);
  2586. am->argc -= n;
  2587. memmove( dest, dest+n, (u8*)(am->argv+am->argc) - (u8*)dest );
  2588. am->argv[am->argc] = 0;
  2589. }
  2590. return pos;
  2591. }
  2592. ///////////////////////////////////////////////////////////////////////////////
  2593. uint ScanSimpleArgManager ( ArgManager_t *am, ccp src )
  2594. {
  2595. uint count = 0;
  2596. if (src)
  2597. {
  2598. for(;;)
  2599. {
  2600. while ( *src == ' ' || *src == '\t' )
  2601. src++;
  2602. if (!*src)
  2603. break;
  2604. ccp start = src;
  2605. while ( *src && *src != ' ' && *src != '\t' )
  2606. src++;
  2607. ccp arg = MEMDUP(start,src-start);
  2608. AppendArgManager(am,arg,0,true);
  2609. }
  2610. }
  2611. return count;
  2612. }
  2613. ///////////////////////////////////////////////////////////////////////////////
  2614. uint ScanQuotedArgManager ( ArgManager_t *am, ccp src, bool is_utf8 )
  2615. {
  2616. uint count = 0;
  2617. if (src)
  2618. {
  2619. char buf[10000], *bufend = buf + sizeof(buf) - 2;
  2620. for(;;)
  2621. {
  2622. while (isspace(*src))
  2623. src++;
  2624. if (!*src)
  2625. break;
  2626. char *dest = buf;
  2627. while ( dest < bufend )
  2628. {
  2629. if ( *src == '\'' || *src == '\"' )
  2630. {
  2631. uint scanned;
  2632. dest += ScanEscapedString(dest,bufend-dest,src,-1,is_utf8,-1,&scanned);
  2633. src += scanned;
  2634. }
  2635. else
  2636. {
  2637. while ( dest < bufend && *src && !isspace(*src) && *src != '\'' && *src != '\"' )
  2638. {
  2639. if ( *src == '\\' && src[1] )
  2640. src++;
  2641. *dest++ = *src++;
  2642. }
  2643. }
  2644. if ( !*src || isspace(*src) )
  2645. break;
  2646. }
  2647. ccp arg = MEMDUP(buf,dest-buf);
  2648. AppendArgManager(am,arg,0,true);
  2649. }
  2650. }
  2651. return count;
  2652. }
  2653. ///////////////////////////////////////////////////////////////////////////////
  2654. enumError ScanFileArgManager
  2655. (
  2656. ArgManager_t *am, // valid arg-manager
  2657. int pos, // insert position, relative to end if <0
  2658. ccp fname, // filename to open
  2659. int silent, // 0: print all error messages
  2660. // 1: suppress file size warning
  2661. // 2: suppress all error messages
  2662. int *n_added
  2663. )
  2664. {
  2665. if (n_added)
  2666. *n_added = 0;
  2667. pos = CheckIndex1(am->argc,pos);
  2668. u8 *data;
  2669. size_t size;
  2670. enumError err = LoadFileAlloc(fname,0,0,&data,&size,0,silent,0,0);
  2671. if (!err)
  2672. {
  2673. if (memchr(data,0,size))
  2674. {
  2675. if ( silent < 2 )
  2676. ERROR0(ERR_WARNING,"Binary file ignored: %s\n",fname);
  2677. err = ERR_WARNING;
  2678. }
  2679. else
  2680. {
  2681. ArgManager_t temp = { .force_case = am->force_case };
  2682. ScanQuotedArgManager(&temp,(ccp)data,true);
  2683. uint newpos = InsertListArgManager(am,pos,temp.argc,temp.argv,true);
  2684. if (n_added)
  2685. *n_added = newpos - pos;
  2686. FREE(temp.argv);
  2687. }
  2688. }
  2689. FREE(data);
  2690. return err;
  2691. }
  2692. ///////////////////////////////////////////////////////////////////////////////
  2693. enumError ExpandAtArgManager
  2694. (
  2695. ArgManager_t *am, // valid arg-manager
  2696. arg_expand_mode_t expand_mode, // objects to be replaced
  2697. int recursion, // maximum recursion depth
  2698. int silent // 0: print all error messages
  2699. // 1: suppress file size warning
  2700. // 2: suppress all error messages
  2701. )
  2702. {
  2703. if (!am)
  2704. return ERR_MISSING_PARAM;
  2705. expand_mode &= AMXM_ALL;
  2706. if (!expand_mode)
  2707. return ERR_OK;
  2708. enumError max_err = ERR_OK;
  2709. for ( int try = 0;; try++ )
  2710. {
  2711. bool dirty = false;
  2712. int pos = 0;
  2713. while ( pos < am->argc )
  2714. {
  2715. ccp arg = am->argv[pos];
  2716. if (arg)
  2717. {
  2718. int n_rm = 0;
  2719. ccp fname = 0;
  2720. int len = strlen(arg);
  2721. if ( len >= 1 && *arg == '@' )
  2722. {
  2723. if ( len > 1 && expand_mode & AMXM_P1 )
  2724. {
  2725. n_rm = 1;
  2726. fname = arg+1;
  2727. }
  2728. else if ( len == 1 && expand_mode & AMXM_P2 && pos+1 < am->argc )
  2729. {
  2730. n_rm = 2;
  2731. fname = am->argv[pos+1];
  2732. }
  2733. }
  2734. else if ( len >= 2 && !memcmp(arg,"-@",2) )
  2735. {
  2736. if ( len > 2 && expand_mode & AMXM_S1 )
  2737. {
  2738. n_rm = 1;
  2739. fname = arg+2;
  2740. }
  2741. else if ( len == 2 && expand_mode & AMXM_S2 && pos+1 < am->argc )
  2742. {
  2743. n_rm = 2;
  2744. fname = am->argv[pos+1];
  2745. }
  2746. }
  2747. else if ( len >= 3 && !memcmp(arg,"--@",3) )
  2748. {
  2749. if ( len > 3 && arg[3] == '=' && expand_mode & AMXM_L1 )
  2750. {
  2751. n_rm = 1;
  2752. fname = arg+4;
  2753. }
  2754. else if ( len == 3 && expand_mode & AMXM_L2 && pos+1 < am->argc )
  2755. {
  2756. n_rm = 2;
  2757. fname = am->argv[pos+1];
  2758. }
  2759. }
  2760. if (n_rm)
  2761. {
  2762. PRINT0("rm @%u %d, file=%s\n",pos,n_rm,fname);
  2763. int n_added;
  2764. enumError err = ScanFileArgManager(am,pos,fname,silent,&n_added);
  2765. if ( max_err < err )
  2766. max_err = err;
  2767. if (n_added)
  2768. {
  2769. pos += n_added;
  2770. dirty = true;
  2771. }
  2772. // remove after insert to keep fname valid!
  2773. PRINT0("rm @%u %d\n",pos,n_rm);
  2774. RemoveArgManager(am,pos,n_rm);
  2775. }
  2776. else
  2777. pos++;
  2778. } // if (arg)
  2779. } // while
  2780. if ( !dirty || try >= recursion )
  2781. break;
  2782. }
  2783. return max_err;
  2784. }
  2785. ///////////////////////////////////////////////////////////////////////////////
  2786. bool CheckFilterArgManager ( const ArgManager_t *filter, ccp name )
  2787. {
  2788. if ( !name || !*name )
  2789. return false;
  2790. if (!filter->argc)
  2791. return true;
  2792. char buf[200];
  2793. if ( filter->force_case == LOUP_LOWER )
  2794. {
  2795. StringLowerS(buf,sizeof(buf),name);
  2796. name = buf;
  2797. }
  2798. else if ( filter->force_case == LOUP_UPPER )
  2799. {
  2800. StringUpperS(buf,sizeof(buf),name);
  2801. name = buf;
  2802. }
  2803. bool fallback_status = true;
  2804. for ( int i = 0; i < filter->argc; i++ )
  2805. {
  2806. ccp arg = filter->argv[i];
  2807. const bool status = *arg != '/';
  2808. if (status)
  2809. fallback_status = false;
  2810. else
  2811. arg++;
  2812. const uint len = strlen(arg);
  2813. if ( *arg == '=' )
  2814. {
  2815. if ( !strcmp(arg+1,name) )
  2816. return status;
  2817. }
  2818. else if ( *arg == '^' )
  2819. {
  2820. if ( len > 1 && !strncmp(arg+1,name,len-1) )
  2821. return status;
  2822. }
  2823. else
  2824. if ( len && strstr(name,arg) )
  2825. return status;
  2826. }
  2827. return fallback_status;
  2828. }
  2829. ///////////////////////////////////////////////////////////////////////////////
  2830. void DumpArgManager ( FILE *f, int indent, const ArgManager_t *am, ccp title )
  2831. {
  2832. if ( !f || !am )
  2833. return;
  2834. indent = NormalizeIndent(indent);
  2835. if (title)
  2836. fprintf(f,"%*s" "ArgManager[%s]: N=%d",
  2837. indent,"", title, am->argc );
  2838. else
  2839. fprintf(f,"%*s" "ArgManager: N=%d", indent,"", am->argc );
  2840. if (am->size)
  2841. fprintf(f,"/%u\n",am->size);
  2842. else
  2843. fputc('\n',f);
  2844. if (am->argc)
  2845. {
  2846. char buf[10];
  2847. int fw = snprintf(buf,sizeof(buf),"%u",am->argc-1)+2;
  2848. uint i;
  2849. for ( i = 0; i < am->argc; i++ )
  2850. fprintf(f,"%*s%*u: |%s|\n", indent,"", fw,i, am->argv[i] );
  2851. }
  2852. }
  2853. //
  2854. ///////////////////////////////////////////////////////////////////////////////
  2855. /////////////// struct mem_t ///////////////
  2856. ///////////////////////////////////////////////////////////////////////////////
  2857. mem_t EmptyMem = {EmptyString,0};
  2858. mem_t NullMem = {0,0};
  2859. ///////////////////////////////////////////////////////////////////////////////
  2860. mem_t MidMem ( const mem_t src, int begin, int count )
  2861. {
  2862. begin = CheckIndex1(src.len,begin);
  2863. if ( count < 0 )
  2864. {
  2865. count = -count;
  2866. begin -= count;
  2867. if ( begin < 0 )
  2868. {
  2869. count += begin;
  2870. begin = 0;
  2871. }
  2872. }
  2873. mem_t res;
  2874. res.ptr = src.ptr + begin;
  2875. const int max = src.len - begin;
  2876. res.len = count < max ? count : max;
  2877. return res;
  2878. }
  2879. ///////////////////////////////////////////////////////////////////////////////
  2880. mem_t BeforeMem ( const mem_t src, ccp ref )
  2881. {
  2882. mem_t res;
  2883. res.ptr = src.ptr;
  2884. res.len = ref < src.ptr ? 0
  2885. : ref <= src.ptr + src.len ? ref - src.ptr
  2886. : src.len;
  2887. return res;
  2888. }
  2889. ///////////////////////////////////////////////////////////////////////////////
  2890. mem_t BehindMem ( const mem_t src, ccp ref )
  2891. {
  2892. mem_t res;
  2893. if ( ref <= src.ptr )
  2894. res = src;
  2895. else if ( ref <= src.ptr + src.len )
  2896. {
  2897. res.ptr = ref;
  2898. res.len = src.ptr + src.len - ref;
  2899. }
  2900. else
  2901. {
  2902. res.ptr = src.ptr + src.len;
  2903. res.len = 0;
  2904. }
  2905. return res;
  2906. }
  2907. ///////////////////////////////////////////////////////////////////////////////
  2908. int CmpMem ( const mem_t s1, const mem_t s2 )
  2909. {
  2910. if ( s1.len < s2.len )
  2911. {
  2912. const int stat = memcmp(s1.ptr,s2.ptr,s1.len);
  2913. return stat ? stat : -1;
  2914. }
  2915. const int stat = memcmp(s1.ptr,s2.ptr,s2.len);
  2916. return stat ? stat : s1.len > s2.len;
  2917. }
  2918. ///////////////////////////////////////////////////////////////////////////////
  2919. int StrCmpMem ( const mem_t mem, ccp str )
  2920. {
  2921. const uint slen = str ? strlen(str) : 0;
  2922. if ( mem.len < slen )
  2923. {
  2924. const int stat = memcmp(mem.ptr,str,mem.len);
  2925. return stat ? stat : -1;
  2926. }
  2927. const int stat = memcmp(mem.ptr,str,slen);
  2928. return stat ? stat : mem.len > slen;
  2929. }
  2930. ///////////////////////////////////////////////////////////////////////////////
  2931. bool LeftStrCmpMemEQ ( const mem_t mem, ccp str )
  2932. {
  2933. const uint slen = str ? strlen(str) : 0;
  2934. return mem.len <= slen && !memcmp(mem.ptr,str,mem.len);
  2935. }
  2936. ///////////////////////////////////////////////////////////////////////////////
  2937. mem_t MemCat2A ( const mem_t m1, const mem_t m2 )
  2938. {
  2939. const uint len1 = m1.len >= 0 ? m1.len : strlen(m1.ptr);
  2940. const uint len2 = m2.len >= 0 ? m2.len : strlen(m2.ptr);
  2941. char *dest;
  2942. mem_t res;
  2943. res.len = len1 + len2;
  2944. res.ptr = dest = MALLOC(res.len+1);
  2945. dest[res.len] = 0;
  2946. if (len1)
  2947. memcpy(dest,m1.ptr,len1);
  2948. if (len2)
  2949. memcpy(dest+len1,m2.ptr,len2);
  2950. return res;
  2951. }
  2952. //-----------------------------------------------------------------------------
  2953. mem_t MemCat3A ( const mem_t m1, const mem_t m2, const mem_t m3 )
  2954. {
  2955. const uint len1 = m1.len >= 0 ? m1.len : strlen(m1.ptr);
  2956. const uint len2 = m2.len >= 0 ? m2.len : strlen(m2.ptr);
  2957. const uint len3 = m3.len >= 0 ? m3.len : strlen(m3.ptr);
  2958. char *dest;
  2959. mem_t res;
  2960. res.len = len1 + len2 + len3;
  2961. res.ptr = dest = MALLOC(res.len+1);
  2962. dest[res.len] = 0;
  2963. if (len1)
  2964. memcpy(dest,m1.ptr,len1);
  2965. if (len2)
  2966. memcpy(dest+len1,m2.ptr,len2);
  2967. if (len3)
  2968. memcpy(dest+len1+len2,m3.ptr,len3);
  2969. return res;
  2970. }
  2971. ///////////////////////////////////////////////////////////////////////////////
  2972. mem_t MemCatSep2A ( const mem_t sep, const mem_t m1, const mem_t m2 )
  2973. {
  2974. const uint slen = sep.len >= 0 ? sep.len : strlen(sep.ptr);
  2975. if (!slen)
  2976. return MemCat2A(m1,m2);
  2977. const uint len1 = m1.len >= 0 ? m1.len : strlen(m1.ptr);
  2978. const uint len2 = m2.len >= 0 ? m2.len : strlen(m2.ptr);
  2979. char *dest;
  2980. mem_t res;
  2981. res.len = len1 + len2;
  2982. if ( len1 && len2 )
  2983. res.len += slen;
  2984. res.ptr = dest = MALLOC(res.len+1);
  2985. dest[res.len] = 0;
  2986. if (len1)
  2987. {
  2988. memcpy(dest,m1.ptr,len1);
  2989. dest += len1;
  2990. }
  2991. if (len2)
  2992. {
  2993. if (len1)
  2994. {
  2995. memcpy(dest,sep.ptr,slen);
  2996. dest += slen;
  2997. }
  2998. memcpy(dest,m2.ptr,len2);
  2999. }
  3000. return res;
  3001. }
  3002. //-----------------------------------------------------------------------------
  3003. mem_t MemCatSep3A ( const mem_t sep, const mem_t m1, const mem_t m2, const mem_t m3 )
  3004. {
  3005. const uint slen = sep.len >= 0 ? sep.len : strlen(sep.ptr);
  3006. if (!slen)
  3007. return MemCat3A(m1,m2,m3);
  3008. const uint len1 = m1.len >= 0 ? m1.len : strlen(m1.ptr);
  3009. const uint len2 = m2.len >= 0 ? m2.len : strlen(m2.ptr);
  3010. const uint len3 = m3.len >= 0 ? m3.len : strlen(m3.ptr);
  3011. char *dest;
  3012. mem_t res;
  3013. res.len = len1 + len2 + len3
  3014. + ( (len1>0) + (len2>0) + (len3>0) - 1 ) * slen;
  3015. res.ptr = dest = MALLOC(res.len+1);
  3016. if (len1)
  3017. {
  3018. memcpy(dest,m1.ptr,len1);
  3019. dest += len1;
  3020. }
  3021. if (len2)
  3022. {
  3023. if ( dest > res.ptr )
  3024. {
  3025. memcpy(dest,sep.ptr,slen);
  3026. dest += slen;
  3027. }
  3028. memcpy(dest,m2.ptr,len2);
  3029. dest += len2;
  3030. }
  3031. if (len3)
  3032. {
  3033. if ( dest > res.ptr )
  3034. {
  3035. memcpy(dest,sep.ptr,slen);
  3036. dest += slen;
  3037. }
  3038. memcpy(dest,m3.ptr,len3);
  3039. dest += len3;
  3040. }
  3041. *dest = 0;
  3042. ASSERT( dest == res.ptr + res.len );
  3043. return res;
  3044. }
  3045. ///////////////////////////////////////////////////////////////////////////////
  3046. // UTF8 support
  3047. mem_t MidMem8 ( const mem_t src, int begin, int count )
  3048. {
  3049. if ( !src.ptr || !src.len )
  3050. return src;
  3051. ccp src_end = src.ptr + src.len;
  3052. const int u8len = ScanUTF8LengthE(src.ptr,src_end);
  3053. begin = CheckIndex1(u8len,begin);
  3054. if ( count < 0 )
  3055. {
  3056. count = -count;
  3057. begin -= count;
  3058. if ( begin < 0 )
  3059. {
  3060. count += begin;
  3061. begin = 0;
  3062. }
  3063. }
  3064. mem_t res;
  3065. res.ptr = SkipUTF8CharE(src.ptr,src_end,begin);
  3066. const int max = u8len - begin;
  3067. res.len = SkipUTF8CharE( res.ptr, src_end, count < max ? count : max ) - res.ptr;
  3068. return res;
  3069. }
  3070. ///////////////////////////////////////////////////////////////////////////////
  3071. mem_t ExtractMem8 ( const mem_t src, int begin, int end )
  3072. {
  3073. if ( !src.ptr || !src.len )
  3074. return src;
  3075. ccp src_end = src.ptr + src.len;
  3076. const int u8len = ScanUTF8LengthE(src.ptr,src_end);
  3077. const int count = CheckIndex2(u8len,&begin,&end);
  3078. mem_t res;
  3079. res.ptr = SkipUTF8CharE( src.ptr, src_end, begin );
  3080. res.len = SkipUTF8CharE( res.ptr, src_end, count ) - res.ptr;
  3081. return res;
  3082. }
  3083. ///////////////////////////////////////////////////////////////////////////////
  3084. mem_t ExtractEndMem8 ( const mem_t src, int begin, int end )
  3085. {
  3086. if ( !src.ptr || !src.len )
  3087. return src;
  3088. ccp src_end = src.ptr + src.len;
  3089. const int u8len = ScanUTF8LengthE(src.ptr,src_end);
  3090. const int count = CheckIndex2End(u8len,&begin,&end);
  3091. mem_t res;
  3092. res.ptr = SkipUTF8CharE( src.ptr, src_end, begin );
  3093. res.len = SkipUTF8CharE( res.ptr, src_end, count ) - res.ptr;
  3094. return res;
  3095. }
  3096. //
  3097. ///////////////////////////////////////////////////////////////////////////////
  3098. /////////////// struct exmem_t ///////////////
  3099. ///////////////////////////////////////////////////////////////////////////////
  3100. exmem_t EmptyExMem = {{EmptyString,0},0,false,false,false,false};
  3101. exmem_t NullExMem = {{0,0},0,false,false,false,false};
  3102. ///////////////////////////////////////////////////////////////////////////////
  3103. void ResetExMem ( const exmem_t *em )
  3104. {
  3105. if (em)
  3106. {
  3107. if (em->is_alloced)
  3108. FreeString(em->data.ptr);
  3109. memset((exmem_t*)em,0,sizeof(*em));
  3110. }
  3111. }
  3112. ///////////////////////////////////////////////////////////////////////////////
  3113. void FreeExMem ( const exmem_t *em )
  3114. {
  3115. if (em)
  3116. {
  3117. if (em->is_alloced)
  3118. {
  3119. exmem_t *em2 = (exmem_t*)em;
  3120. FreeString(em2->data.ptr);
  3121. em2->data.ptr = 0;
  3122. em2->data.len = 0;
  3123. em2->is_alloced = false;
  3124. }
  3125. }
  3126. }
  3127. ///////////////////////////////////////////////////////////////////////////////
  3128. void FreeExMemCM ( const exmem_t *em, CopyMode_t copy_mode )
  3129. {
  3130. if ( em && copy_mode == CPM_MOVE )
  3131. {
  3132. if (em->is_alloced)
  3133. FreeString(em->data.ptr);
  3134. memset((exmem_t*)em,0,sizeof(*em));
  3135. }
  3136. }
  3137. ///////////////////////////////////////////////////////////////////////////////
  3138. exmem_t AllocExMemS
  3139. (
  3140. cvp src, // NULL or source
  3141. int src_len, // len of 'src'; if -1: use strlen(source)
  3142. bool try_circ, // use circ-buffer, if result is small enough
  3143. cvp orig, // NULL or data to compare
  3144. int orig_len // len of 'orig'; if -1: use strlen(source)
  3145. )
  3146. {
  3147. exmem_t em = {{0}};
  3148. if (src)
  3149. {
  3150. if ( src_len < 0 )
  3151. src_len = strlen(src);
  3152. if (!src_len)
  3153. em.data.ptr = EmptyString;
  3154. else
  3155. {
  3156. em.data.len = src_len;
  3157. if ( orig
  3158. && src_len == ( orig_len < 0 ? strlen(orig) : orig_len )
  3159. && !memcmp(src,orig,src_len)
  3160. )
  3161. {
  3162. em.data.ptr = orig;
  3163. em.is_original = true;
  3164. }
  3165. else if ( try_circ && src_len <= CIRC_BUF_MAX_ALLOC )
  3166. {
  3167. em.data.ptr = CopyCircBuf(src,src_len);
  3168. em.is_circ_buf = true;
  3169. }
  3170. else
  3171. {
  3172. em.data.ptr = MEMDUP(src,src_len);
  3173. em.is_alloced = true;
  3174. }
  3175. }
  3176. }
  3177. return em;
  3178. }
  3179. ///////////////////////////////////////////////////////////////////////////////
  3180. void AssignExMem ( exmem_t *dest, const exmem_t *source, CopyMode_t copy_mode )
  3181. {
  3182. if ( dest && dest != source )
  3183. {
  3184. if (dest->is_alloced)
  3185. FreeString(dest->data.ptr);
  3186. const bool dest_key_alloced = dest->is_key_alloced;
  3187. if (source)
  3188. {
  3189. switch (copy_mode)
  3190. {
  3191. case CPM_COPY:
  3192. memset(dest,0,sizeof(*dest));
  3193. dest->data.len = source->data.len;
  3194. dest->data.ptr = MEMDUP(source->data.ptr,source->data.len);
  3195. dest->is_alloced = true;
  3196. dest->attrib = source->attrib;
  3197. break;
  3198. case CPM_MOVE:
  3199. *dest = *source;
  3200. memset((exmem_t*)source,0,sizeof(*source));
  3201. break;
  3202. case CPM_LINK:
  3203. *dest = *source;
  3204. dest->is_original = false;
  3205. dest->is_alloced = false;
  3206. break;
  3207. }
  3208. }
  3209. else
  3210. memset(dest,0,sizeof(*dest));
  3211. dest->is_key_alloced = dest_key_alloced;
  3212. }
  3213. }
  3214. ///////////////////////////////////////////////////////////////////////////////
  3215. void AssignExMemS ( exmem_t *dest, cvp source, int slen, CopyMode_t copy_mode )
  3216. {
  3217. if (dest)
  3218. {
  3219. ccp free_str = dest->is_alloced ? dest->data.ptr : 0;
  3220. const bool dest_key_alloced = dest->is_key_alloced;
  3221. memset(dest,0,sizeof(*dest));
  3222. dest->is_key_alloced = dest_key_alloced;
  3223. if (source)
  3224. {
  3225. dest->data.len = slen < 0 ? strlen(source) : slen;
  3226. switch (copy_mode)
  3227. {
  3228. case CPM_COPY:
  3229. dest->data.ptr = MEMDUP(source,dest->data.len);
  3230. dest->is_alloced = true;
  3231. break;
  3232. case CPM_MOVE:
  3233. dest->is_alloced = true;
  3234. // fall through
  3235. case CPM_LINK:
  3236. dest->data.ptr = source;
  3237. break;
  3238. }
  3239. }
  3240. FreeString(free_str);
  3241. }
  3242. }
  3243. ///////////////////////////////////////////////////////////////////////////////
  3244. #if 0 // [[obsolete]] since 2021-11
  3245. exmem_t CopyExMemS ( cvp string, int slen, CopyMode_t copy_mode )
  3246. {
  3247. exmem_t em = {{0}};
  3248. if (string)
  3249. {
  3250. em.data.len = slen < 0 ? strlen(string) : slen;
  3251. switch (copy_mode)
  3252. {
  3253. case CPM_COPY:
  3254. em.data.ptr = MEMDUP(string,em.data.len);
  3255. em.is_alloced = true;
  3256. break;
  3257. case CPM_MOVE:
  3258. em.is_alloced = true;
  3259. // fall through
  3260. case CPM_LINK:
  3261. em.data.ptr = string;
  3262. break;
  3263. }
  3264. }
  3265. return em;
  3266. }
  3267. #endif
  3268. ///////////////////////////////////////////////////////////////////////////////
  3269. ccp PrintExMem ( const exmem_t * em ) // print to circ-buf
  3270. {
  3271. if (!em)
  3272. return MinusString;
  3273. char ebuf[60];
  3274. uint len;
  3275. PrintEscapedString(ebuf,sizeof(ebuf),em->data.ptr,em->data.len,CHMD__MODERN,'"',&len);
  3276. return PrintCircBuf(
  3277. "[%c%c%c%c:%x] %u/%u %s",
  3278. em->is_key_alloced ? 'a' : '-', // flags: same as in DumpEML()
  3279. em->is_alloced ? 'A' : '-',
  3280. em->is_circ_buf ? 'C' : '-',
  3281. em->is_original ? 'O' : '-',
  3282. em->attrib,
  3283. len, em->data.len, ebuf );
  3284. }
  3285. //
  3286. ///////////////////////////////////////////////////////////////////////////////
  3287. ///////////////////////////////////////////////////////////////////////////////
  3288. uint GetMemSrcN ( const mem_src_t *src )
  3289. {
  3290. if (!src)
  3291. return 0;
  3292. if ( src->n_src >= 0 )
  3293. return src->n_src;
  3294. const mem_t *ptr = src->src;
  3295. while ( ptr->ptr )
  3296. ptr++;
  3297. const uint n_src = ptr - src->src;
  3298. if ( src->allow_write )
  3299. *(uint*)&src->n_src = n_src;
  3300. return n_src;
  3301. }
  3302. ///////////////////////////////////////////////////////////////////////////////
  3303. uint GetMemSrcLen ( mem_t sep, const mem_src_t *src )
  3304. {
  3305. if ( !src || src->n_src <= 0 )
  3306. return 0;
  3307. int n_valid_src = 0, sum_len = 0;
  3308. int n_src = GetMemSrcN(src);
  3309. for ( const mem_t *ptr = src->src; n_src > 0; ptr++, n_src-- )
  3310. {
  3311. int slen = ptr->len;
  3312. if ( slen < 0 )
  3313. {
  3314. slen = ptr->ptr ? strlen(ptr->ptr) : 0;
  3315. if (src->allow_write)
  3316. *(int*)&ptr->len = slen;
  3317. }
  3318. if ( slen > 0 )
  3319. {
  3320. n_valid_src++;
  3321. sum_len += slen;
  3322. }
  3323. }
  3324. if ( n_valid_src > 1 )
  3325. sum_len += (n_valid_src-1)*sep.len;
  3326. return sum_len;
  3327. }
  3328. ///////////////////////////////////////////////////////////////////////////////
  3329. exmem_t GetExmemDestBuf ( const exmem_dest_t * dest, uint len )
  3330. {
  3331. exmem_t res = { .data.len = len };
  3332. len++; // for additional 0-term
  3333. if (!dest)
  3334. goto malloc;
  3335. else if ( dest->buf && len <= dest->buf_size )
  3336. {
  3337. res.data.ptr = dest->buf;
  3338. }
  3339. else if ( dest->try_circ && len <= CIRC_BUF_MAX_ALLOC )
  3340. {
  3341. res.is_circ_buf = true;
  3342. res.data.ptr = GetCircBuf(len);
  3343. }
  3344. else
  3345. {
  3346. malloc:;
  3347. res.is_alloced = true;
  3348. res.data.ptr = MALLOC(len);
  3349. }
  3350. return res;
  3351. }
  3352. ///////////////////////////////////////////////////////////////////////////////
  3353. ///////////////////////////////////////////////////////////////////////////////
  3354. exmem_t ExMemCat
  3355. (
  3356. exmem_dest_t *dest, // kind of destination, if NULL then MALLOC()
  3357. mem_t sep, // insert separators between sources with len>0
  3358. const mem_src_t *src // sources. NULL allowed
  3359. )
  3360. {
  3361. const uint total_size = GetMemSrcLen(sep,src);
  3362. exmem_t res = GetExmemDestBuf(dest,total_size);
  3363. char *bufdest = (char*)res.data.ptr;
  3364. int n_src = GetMemSrcN(src);
  3365. for ( const mem_t *ptr = src->src; n_src > 0; ptr++, n_src-- )
  3366. {
  3367. int slen = ptr->len;
  3368. if ( slen < 0 )
  3369. slen = ptr->ptr ? strlen(ptr->ptr) : 0;
  3370. if ( slen > 0 )
  3371. {
  3372. if ( sep.len && bufdest > res.data.ptr )
  3373. {
  3374. memcpy(bufdest,sep.ptr,sep.len);
  3375. bufdest += sep.len;
  3376. }
  3377. memcpy(bufdest,ptr->ptr,slen);
  3378. bufdest += slen;
  3379. ASSERT( bufdest <= res.data.ptr + res.data.len );
  3380. }
  3381. }
  3382. ASSERT( bufdest == res.data.ptr + res.data.len );
  3383. *bufdest = 0;
  3384. return res;
  3385. }
  3386. ///////////////////////////////////////////////////////////////////////////////
  3387. exmem_t ExMemCat2
  3388. (
  3389. exmem_dest_t *dest, // kind of destination, if NULL then MALLOC()
  3390. mem_t sep, // insert separators between sources with len>0
  3391. mem_t src1, // first source
  3392. mem_t src2 // second source
  3393. )
  3394. {
  3395. mem_t list[] = { src1, src2 };
  3396. mem_src_t src = { .src = list, .n_src = 2, true };
  3397. return ExMemCat(dest,sep,&src);
  3398. }
  3399. ///////////////////////////////////////////////////////////////////////////////
  3400. exmem_t ExMemCat3
  3401. (
  3402. exmem_dest_t *dest, // kind of destination, if NULL then MALLOC()
  3403. mem_t sep, // insert separators between sources with len>0
  3404. mem_t src1, // first source
  3405. mem_t src2, // second source
  3406. mem_t src3 // third source
  3407. )
  3408. {
  3409. mem_t list[] = { src1, src2, src3 };
  3410. mem_src_t src = { .src = list, .n_src = 3, true };
  3411. return ExMemCat(dest,sep,&src);
  3412. }
  3413. //
  3414. ///////////////////////////////////////////////////////////////////////////////
  3415. /////////////// struct mem_list_t ///////////////
  3416. ///////////////////////////////////////////////////////////////////////////////
  3417. void ResetMemList ( mem_list_t *ml )
  3418. {
  3419. if (ml)
  3420. {
  3421. FREE(ml->list);
  3422. FREE(ml->buf);
  3423. memset(ml,0,sizeof(*ml));
  3424. }
  3425. }
  3426. ///////////////////////////////////////////////////////////////////////////////
  3427. // [[?]]
  3428. void MoveMemList ( mem_list_t *dest, mem_list_t *src )
  3429. {
  3430. if ( dest != src )
  3431. {
  3432. if (!dest)
  3433. ResetMemList(src);
  3434. else
  3435. {
  3436. ResetMemList(dest);
  3437. if (src)
  3438. {
  3439. memcpy(dest,src,sizeof(*dest));
  3440. memset(src,0,sizeof(*src));
  3441. }
  3442. }
  3443. }
  3444. }
  3445. ///////////////////////////////////////////////////////////////////////////////
  3446. // [[?]]
  3447. void NeedBufMemList ( mem_list_t *ml, uint need_size, uint extra_size )
  3448. {
  3449. need_size += ml->buf_used;
  3450. if ( ml->buf_size < need_size )
  3451. {
  3452. need_size = GetGoodAllocSize(need_size+extra_size);
  3453. PRINT("MEM-LIST: MALLOC/BUF(%u/%u>%u)\n",ml->buf_used,ml->buf_size,need_size);
  3454. char *new_buf = MALLOC(need_size);
  3455. //--- copy existing strings
  3456. char *bufptr = new_buf;
  3457. mem_t *dest = ml->list;
  3458. uint i;
  3459. for ( i = 0; i < ml->used; i++, dest++ )
  3460. if (dest->len)
  3461. {
  3462. memcpy(bufptr,dest->ptr,dest->len);
  3463. dest->ptr = bufptr;
  3464. bufptr += dest->len;
  3465. *bufptr++ = 0;
  3466. DASSERT( bufptr <= new_buf + need_size );
  3467. }
  3468. FREE(ml->buf);
  3469. ml->buf = new_buf;
  3470. ml->buf_used = bufptr - new_buf;
  3471. ml->buf_size = need_size;
  3472. }
  3473. }
  3474. ///////////////////////////////////////////////////////////////////////////////
  3475. // [[?]]
  3476. void NeedElemMemList ( mem_list_t *ml, uint need_elem, uint need_size )
  3477. {
  3478. DASSERT(ml);
  3479. need_elem += ml->used;
  3480. if ( ml->size < need_elem )
  3481. {
  3482. ml->size = GetGoodAllocSize2(need_elem,sizeof(*ml->list));
  3483. PRINT("MEM-LIST: REALLOC/LIST(%u)\n",ml->size);
  3484. ml->list = REALLOC(ml->list,sizeof(*ml->list)*ml->size);
  3485. }
  3486. NeedBufMemList(ml,need_size,0);
  3487. }
  3488. ///////////////////////////////////////////////////////////////////////////////
  3489. ///////////////////////////////////////////////////////////////////////////////
  3490. // [[?]]
  3491. void InsertMemListN
  3492. (
  3493. mem_list_t *ml, // valid destination mem_list
  3494. int pos, // insert position => CheckIndex1()
  3495. const mem_t *src, // source list
  3496. uint src_len, // number of elements in source list
  3497. mem_list_mode_t src_ignore // how to manage NULL and empty strings
  3498. )
  3499. {
  3500. DASSERT(ml);
  3501. DASSERT( src || !src_len );
  3502. //--- count needed size and elements
  3503. const mem_t *sptr, *src_end = src + src_len;
  3504. uint need_size = 0, add_elem = 0;
  3505. for ( sptr = src; sptr < src_end; sptr++ )
  3506. {
  3507. if ( sptr->len )
  3508. {
  3509. need_size += sptr->len + 1; // always terminate with NULL
  3510. add_elem++;
  3511. }
  3512. else if ( src_ignore == MEMLM_ALL
  3513. || src_ignore == MEMLM_IGN_NULL && sptr->ptr
  3514. || src_ignore == MEMLM_REPL_NULL
  3515. )
  3516. {
  3517. add_elem++;
  3518. }
  3519. }
  3520. if (!add_elem)
  3521. return;
  3522. //--- string pool management
  3523. if (!ml->used)
  3524. ml->buf_used = 0;
  3525. char *new_buf, *bufptr;
  3526. if ( ml->buf_used + need_size <= ml->buf_size )
  3527. {
  3528. new_buf = 0;
  3529. bufptr = ml->buf + ml->buf_used;
  3530. ml->buf_used += need_size;
  3531. }
  3532. else
  3533. {
  3534. need_size += ml->buf_used + 20;
  3535. need_size += need_size/10;
  3536. // don't use NeedBufMemList() here, because the old buffer is needed
  3537. // BUT POSSIBLE: char old_buf = ml->buf; ml->buf = 0; GrowBufMemList(ml,need_size)
  3538. PRINT("MEM-LIST: MALLOC/BUF(%u)\n",need_size);
  3539. bufptr = new_buf = MALLOC(need_size);
  3540. //--- copy existing strings
  3541. mem_t *dest = ml->list;
  3542. uint i;
  3543. for ( i = 0; i < ml->used; i++, dest++ )
  3544. if ( dest->len )
  3545. {
  3546. memcpy(bufptr,dest->ptr,dest->len);
  3547. dest->ptr = bufptr;
  3548. bufptr += dest->len;
  3549. *bufptr++ = 0;
  3550. DASSERT( bufptr <= new_buf+need_size );
  3551. noPRINT("OLD: %p,%u\n",dest->ptr,dest->len);
  3552. }
  3553. }
  3554. //--- realloc list if necessary
  3555. const uint need_elem = ml->used + add_elem;
  3556. if ( need_elem > ml->size )
  3557. {
  3558. ml->size = need_elem + 5 + need_elem/10;
  3559. PRINT("MEM-LIST: REALLOC/LIST(%u)\n",ml->size);
  3560. ml->list = REALLOC(ml->list,sizeof(*ml->list)*ml->size);
  3561. }
  3562. pos = CheckIndex1(ml->used,pos);
  3563. mem_t *dest = ml->list + pos;
  3564. if ( pos < ml->used )
  3565. memmove(dest+add_elem,dest,sizeof(*dest)*(ml->used-pos));
  3566. ml->used += add_elem;
  3567. //--- iterate source list
  3568. for ( sptr = src; sptr < src_end; sptr++ )
  3569. {
  3570. if (sptr->len)
  3571. {
  3572. dest->ptr = bufptr;
  3573. memcpy(bufptr,sptr->ptr,sptr->len);
  3574. dest->len = sptr->len;
  3575. bufptr += sptr->len;
  3576. *bufptr++ = 0;
  3577. DASSERT( bufptr <= ( new_buf ? new_buf+need_size : ml->buf + ml->buf_size ) );
  3578. noPRINT("NEW: %p,%u\n",dest->ptr,dest->len);
  3579. dest++;
  3580. DASSERT( dest <= ml->list + ml->used );
  3581. }
  3582. else if ( src_ignore == MEMLM_ALL || src_ignore == MEMLM_IGN_NULL && sptr->ptr )
  3583. {
  3584. dest->ptr = sptr->ptr ? EmptyString : NULL;
  3585. dest->len = 0;
  3586. dest++;
  3587. DASSERT( dest <= ml->list + ml->used );
  3588. }
  3589. else if ( src_ignore == MEMLM_REPL_NULL )
  3590. {
  3591. dest->ptr = EmptyString;
  3592. dest->len = 0;
  3593. dest++;
  3594. DASSERT( dest <= ml->list + ml->used );
  3595. }
  3596. }
  3597. DASSERT_MSG( dest == ml->list + pos + add_elem,
  3598. "DEST= %zu != %u+%u == %u",
  3599. dest-ml->list, pos, add_elem, pos+add_elem );
  3600. //--- clean
  3601. if (new_buf)
  3602. {
  3603. DASSERT(ml->buf != new_buf);
  3604. FREE(ml->buf);
  3605. ml->buf = new_buf;
  3606. ml->buf_size = need_size;
  3607. }
  3608. ml->buf_used = bufptr - ml->buf;
  3609. DASSERT( ml->buf_used <= ml->buf_size );
  3610. }
  3611. ///////////////////////////////////////////////////////////////////////////////
  3612. ///////////////////////////////////////////////////////////////////////////////
  3613. // [[?]]
  3614. void CatMemListN
  3615. (
  3616. mem_list_t *dest, // valid destination mem_list
  3617. const mem_list_t **src_list, // list with mem lists, element may be NULL
  3618. uint n_src_list, // number of elements in 'src'
  3619. mem_list_mode_t src_ignore // how to manage NULL and empty strings
  3620. )
  3621. {
  3622. DASSERT(dest);
  3623. DASSERT( src_list || !n_src_list );
  3624. //--- count needed size and elements
  3625. uint need_size = 0, need_elem = 0;
  3626. bool dest_is_source = false;
  3627. const mem_list_t **list_ptr, **src_list_end = src_list + n_src_list;
  3628. for ( list_ptr = src_list; list_ptr < src_list_end; list_ptr++ )
  3629. {
  3630. if (!*list_ptr)
  3631. continue;
  3632. if ( *list_ptr == dest )
  3633. dest_is_source = true;
  3634. const mem_t *sptr = (*list_ptr)->list, *send = sptr + (*list_ptr)->used;
  3635. for ( ; sptr < send; sptr++ )
  3636. {
  3637. if ( sptr->len )
  3638. {
  3639. need_size += sptr->len + 1; // always terminate with NULL
  3640. need_elem++;
  3641. }
  3642. else if ( src_ignore == MEMLM_ALL
  3643. || src_ignore == MEMLM_IGN_NULL && sptr->ptr
  3644. || src_ignore == MEMLM_REPL_NULL
  3645. )
  3646. {
  3647. need_elem++;
  3648. }
  3649. }
  3650. }
  3651. PRINT("CatMemList(N=%u) n_elem=%u, size=%u, dest_is_source=%d\n",
  3652. n_src_list,need_elem,need_size,dest_is_source);
  3653. if (!need_elem)
  3654. {
  3655. dest->used = 0;
  3656. return;
  3657. }
  3658. //--- setup dest buffers
  3659. char *new_buf = dest_is_source || need_size > dest->buf_size
  3660. ? MALLOC(need_size) : dest->buf;
  3661. mem_t *new_list = dest_is_source || need_elem > dest->size
  3662. ? MALLOC(sizeof(*new_list)*need_elem) : dest->list;
  3663. //--- assign values
  3664. char *bufptr = new_buf;
  3665. mem_t *listptr = new_list;
  3666. for ( list_ptr = src_list; list_ptr < src_list_end; list_ptr++ )
  3667. {
  3668. if (!*list_ptr)
  3669. continue;
  3670. const mem_t *sptr = (*list_ptr)->list, *send = sptr + (*list_ptr)->used;
  3671. for ( ; sptr < send; sptr++ )
  3672. {
  3673. if (sptr->len)
  3674. {
  3675. listptr->ptr = bufptr;
  3676. memcpy(bufptr,sptr->ptr,sptr->len);
  3677. listptr->len = sptr->len;
  3678. bufptr += sptr->len;
  3679. *bufptr++ = 0;
  3680. DASSERT( bufptr <= new_buf + need_size );
  3681. noPRINT("NEW: %p,%u\n",dest->ptr,dest->len);
  3682. listptr++;
  3683. DASSERT( listptr <= new_list + need_elem );
  3684. }
  3685. else if ( src_ignore == MEMLM_ALL || src_ignore == MEMLM_IGN_NULL && sptr->ptr )
  3686. {
  3687. listptr->ptr = sptr->ptr ? EmptyString : NULL;
  3688. listptr->len = 0;
  3689. listptr++;
  3690. DASSERT( listptr <= new_list + need_elem );
  3691. }
  3692. else if ( src_ignore == MEMLM_REPL_NULL )
  3693. {
  3694. listptr->ptr = EmptyString;
  3695. listptr->len = 0;
  3696. listptr++;
  3697. DASSERT( listptr <= new_list + need_elem );
  3698. }
  3699. }
  3700. }
  3701. DASSERT( bufptr == new_buf + need_size );
  3702. DASSERT( listptr == new_list + need_elem );
  3703. //--- terminate
  3704. dest->buf_used = need_size;
  3705. if ( new_buf != dest->buf )
  3706. {
  3707. FREE(dest->buf);
  3708. dest->buf = new_buf;
  3709. dest->buf_size = need_size;
  3710. }
  3711. dest->used = need_elem;
  3712. if ( new_list != dest->list )
  3713. {
  3714. FREE(dest->list);
  3715. dest->list = new_list;
  3716. dest->size = need_elem;
  3717. }
  3718. }
  3719. ///////////////////////////////////////////////////////////////////////////////
  3720. ///////////////////////////////////////////////////////////////////////////////
  3721. // [[?]]
  3722. uint LeftMemList ( mem_list_t *ml, int count )
  3723. {
  3724. DASSERT(ml);
  3725. return ml->used = CheckIndex1(ml->used,count);
  3726. }
  3727. ///////////////////////////////////////////////////////////////////////////////
  3728. // [[?]]
  3729. uint RightMemList ( mem_list_t *ml, int count )
  3730. {
  3731. DASSERT(ml);
  3732. const uint begin = CheckIndex1End(ml->used,-count);
  3733. if (begin)
  3734. {
  3735. ml->used -= begin;
  3736. memmove( ml->list, ml->list + begin, ml->used * sizeof(*ml->list) );
  3737. }
  3738. return ml->used;
  3739. }
  3740. ///////////////////////////////////////////////////////////////////////////////
  3741. // [[?]]
  3742. uint MidMemList ( mem_list_t *ml, int begin, int count )
  3743. {
  3744. DASSERT(ml);
  3745. begin = CheckIndex1(ml->used,begin);
  3746. if ( count < 0 )
  3747. {
  3748. count = -count;
  3749. begin -= count;
  3750. if ( begin < 0 )
  3751. {
  3752. count += begin;
  3753. begin = 0;
  3754. }
  3755. }
  3756. const uint max = ml->used - begin;
  3757. if ( count > max )
  3758. count = max;
  3759. memmove( ml->list, ml->list + begin, count * sizeof(*ml->list) );
  3760. return ml->used = count;
  3761. }
  3762. ///////////////////////////////////////////////////////////////////////////////
  3763. // [[?]]
  3764. uint ExtractMemList ( mem_list_t *ml, int begin, int end )
  3765. {
  3766. DASSERT(ml);
  3767. ml->used = CheckIndex2(ml->used,&begin,&end);
  3768. memmove( ml->list, ml->list + begin, ml->used * sizeof(*ml->list) );
  3769. return ml->used;
  3770. }
  3771. ///////////////////////////////////////////////////////////////////////////////
  3772. // [[?]]
  3773. uint ExtractEndMemList ( mem_list_t *ml, int begin, int end )
  3774. {
  3775. DASSERT(ml);
  3776. ml->used = CheckIndex2End(ml->used,&begin,&end);
  3777. memmove( ml->list, ml->list + begin, ml->used * sizeof(*ml->list) );
  3778. return ml->used;
  3779. }
  3780. ///////////////////////////////////////////////////////////////////////////////
  3781. // [[?]]
  3782. uint RemoveMemList ( mem_list_t *ml, int begin, int end )
  3783. {
  3784. DASSERT(ml);
  3785. const uint sub = CheckIndex2(ml->used,&begin,&end);
  3786. memmove( ml->list + begin, ml->list + end, ( ml->used - end ) * sizeof(*ml->list) );
  3787. return ml->used -= sub;
  3788. }
  3789. ///////////////////////////////////////////////////////////////////////////////
  3790. // [[?]]
  3791. uint RemoveEndMemList ( mem_list_t *ml, int begin, int end )
  3792. {
  3793. DASSERT(ml);
  3794. const uint sub = CheckIndex2End(ml->used,&begin,&end);
  3795. memmove( ml->list + begin, ml->list + end, ( ml->used - end ) * sizeof(*ml->list) );
  3796. return ml->used -= sub;
  3797. }
  3798. //
  3799. ///////////////////////////////////////////////////////////////////////////////
  3800. /////////////// MemPool_t ///////////////
  3801. ///////////////////////////////////////////////////////////////////////////////
  3802. void ResetMemPool ( MemPool_t *mp )
  3803. {
  3804. DASSERT(mp);
  3805. MemPoolChunk_t *ptr = mp->chunk;
  3806. while (ptr)
  3807. {
  3808. MemPoolChunk_t *next = ptr->next;
  3809. FREE(ptr);
  3810. ptr = next;
  3811. }
  3812. InitializeMemPool(mp,mp->chunk_size);
  3813. }
  3814. ///////////////////////////////////////////////////////////////////////////////
  3815. void * MallocMemPool ( MemPool_t *mp, uint size )
  3816. {
  3817. DASSERT(mp);
  3818. if (!size)
  3819. return (char*)EmptyString;
  3820. if ( size > mp->space )
  3821. {
  3822. uint data_size = size > mp->chunk_size ? size : mp->chunk_size;
  3823. if ( data_size < 0x400 )
  3824. data_size = 0x400;
  3825. MemPoolChunk_t *chunk = MALLOC(sizeof(MemPoolChunk_t)+data_size);
  3826. DASSERT(chunk);
  3827. chunk->next = mp->chunk;
  3828. mp->chunk = chunk;
  3829. mp->space = data_size;
  3830. }
  3831. DASSERT(mp->chunk);
  3832. DASSERT(mp->space >= size );
  3833. mp->space -= size;
  3834. return mp->chunk->data + mp->space;
  3835. }
  3836. ///////////////////////////////////////////////////////////////////////////////
  3837. void * CallocMemPool ( MemPool_t *mp, uint size )
  3838. {
  3839. DASSERT(mp);
  3840. void *res = MallocMemPool(mp,size);
  3841. DASSERT(res);
  3842. memset(res,0,size);
  3843. return res;
  3844. }
  3845. ///////////////////////////////////////////////////////////////////////////////
  3846. void * MallocMemPoolA ( MemPool_t *mp, uint size, uint align )
  3847. {
  3848. DASSERT(mp);
  3849. char *res = MallocMemPool(mp,size);
  3850. DASSERT(res);
  3851. const uint fix = mp->space - mp->space / align * align;
  3852. res -= fix;
  3853. mp->space -= fix;
  3854. return res;
  3855. }
  3856. ///////////////////////////////////////////////////////////////////////////////
  3857. void * CallocMemPoolA ( MemPool_t *mp, uint size, uint align )
  3858. {
  3859. DASSERT(mp);
  3860. void *res = MallocMemPoolA(mp,size,align);
  3861. DASSERT(res);
  3862. memset(res,0,size);
  3863. return res;
  3864. }
  3865. ///////////////////////////////////////////////////////////////////////////////
  3866. void * MemDupMemPool ( MemPool_t *mp, cvp source, uint size )
  3867. {
  3868. DASSERT(mp);
  3869. DASSERT(source||!size);
  3870. char *res = MallocMemPool(mp,size+1);
  3871. memcpy(res,source,size);
  3872. res[size] = 0;
  3873. return res;
  3874. }
  3875. //
  3876. ///////////////////////////////////////////////////////////////////////////////
  3877. /////////////// CircBuf_t ///////////////
  3878. ///////////////////////////////////////////////////////////////////////////////
  3879. void InitializeCircBuf ( CircBuf_t *cb, uint size )
  3880. {
  3881. DASSERT(cb);
  3882. memset(cb,0,sizeof(*cb));
  3883. cb->size = size; //data is alloced on first insertion
  3884. }
  3885. ///////////////////////////////////////////////////////////////////////////////
  3886. void ResetCircBuf ( CircBuf_t *cb )
  3887. {
  3888. DASSERT(cb);
  3889. FREE(cb->buf);
  3890. cb->buf = 0;
  3891. cb->used = cb->pos = 0;
  3892. }
  3893. ///////////////////////////////////////////////////////////////////////////////
  3894. uint WriteCircBuf ( CircBuf_t *cb, cvp data, uint size )
  3895. {
  3896. DASSERT(cb);
  3897. DASSERT(data||!size);
  3898. if ( !size || !cb->size )
  3899. return 0;
  3900. if (!cb->buf)
  3901. {
  3902. cb->buf = MALLOC(cb->size);
  3903. DASSERT(cb->buf);
  3904. cb->used = cb->pos = 0;
  3905. }
  3906. ccp d = data;
  3907. if ( size >= cb->size )
  3908. {
  3909. cb->used = cb->size;
  3910. cb->pos = 0;
  3911. memcpy( cb->buf, d + (size-cb->size), cb->size );
  3912. //fprintf(stderr,"INS*: %d+%d = %d / %d\n",cb->pos,cb->used,cb->pos+cb->used,cb->size);
  3913. return cb->size;
  3914. }
  3915. const int ins_count = size;
  3916. int ins_pos = cb->pos + cb->used;
  3917. if ( ins_pos >= cb->size )
  3918. ins_pos -= cb->size;
  3919. if ( ins_pos + size > cb->size )
  3920. {
  3921. const uint copy_len = cb->size - ins_pos;
  3922. //fprintf(stderr,"COPY %u..%u\n",ins_pos,ins_pos+copy_len);
  3923. memcpy( cb->buf + ins_pos, d, copy_len );
  3924. size -= copy_len;
  3925. d += copy_len;
  3926. ins_pos = 0;
  3927. }
  3928. DASSERT( size > 0 );
  3929. DASSERT( ins_pos <= cb->size );
  3930. DASSERT( ins_pos + size <= cb->size );
  3931. //fprintf(stderr,"COPY %u..%u\n",ins_pos,ins_pos+size);
  3932. memcpy( cb->buf + ins_pos, d, size );
  3933. cb->used += ins_count;
  3934. if ( cb->used > cb->size )
  3935. {
  3936. cb->pos += cb->used - cb->size;
  3937. if ( cb->pos >= cb->size )
  3938. cb->pos -= cb->size;
  3939. cb->used = cb->size;
  3940. }
  3941. //fprintf(stderr,"INS: %d+%d = %d / %d\n",cb->pos,cb->used,cb->pos+cb->used,cb->size);
  3942. return ins_count;
  3943. }
  3944. ///////////////////////////////////////////////////////////////////////////////
  3945. uint PeakCircBuf ( CircBuf_t *cb, char *buf, uint buf_size )
  3946. {
  3947. DASSERT(cb);
  3948. DASSERT(buf||!buf_size);
  3949. if ( !cb->size || !buf_size )
  3950. return 0;
  3951. if ( buf_size > cb->used )
  3952. buf_size = cb->used;
  3953. uint count = cb->size - cb->pos;
  3954. if ( count > buf_size )
  3955. count -= buf_size;
  3956. memcpy( buf, cb->buf + cb->pos, count );
  3957. if ( count < buf_size )
  3958. {
  3959. const uint copy_len = buf_size - count;
  3960. memcpy( buf+count, cb->buf, copy_len );
  3961. count += copy_len;
  3962. }
  3963. return count;
  3964. }
  3965. ///////////////////////////////////////////////////////////////////////////////
  3966. uint ReadCircBuf ( CircBuf_t *cb, char *buf, uint buf_size )
  3967. {
  3968. DASSERT(cb);
  3969. const uint count = PeakCircBuf(cb,buf,buf_size);
  3970. return DropCircBuf(cb,count);
  3971. }
  3972. ///////////////////////////////////////////////////////////////////////////////
  3973. uint DropCircBuf ( CircBuf_t *cb, uint size )
  3974. {
  3975. DASSERT(cb);
  3976. if ( size >= cb->used )
  3977. {
  3978. const uint res = cb->used;
  3979. cb->pos = cb->used = 0;
  3980. return res;
  3981. }
  3982. cb->used -= size;
  3983. cb->pos += size;
  3984. if ( cb->pos >= cb->size )
  3985. cb->pos -= cb->size;
  3986. return size;
  3987. }
  3988. ///////////////////////////////////////////////////////////////////////////////
  3989. void ClearCircBuf ( CircBuf_t *cb )
  3990. {
  3991. DASSERT(cb);
  3992. cb->used = cb->pos = 0;
  3993. }
  3994. ///////////////////////////////////////////////////////////////////////////////
  3995. uint PurgeCircBuf ( CircBuf_t *cb )
  3996. {
  3997. DASSERT(cb);
  3998. if ( cb->used && cb->pos )
  3999. {
  4000. char *temp = MALLOC(cb->size);
  4001. PeakCircBuf(cb,temp,cb->used);
  4002. FREE(cb->buf);
  4003. cb->buf = temp;
  4004. }
  4005. cb->pos = 0;
  4006. return cb->used;
  4007. }
  4008. //
  4009. ///////////////////////////////////////////////////////////////////////////////
  4010. /////////////// enum CopyMode_t interface ///////////////
  4011. ///////////////////////////////////////////////////////////////////////////////
  4012. void * CopyData
  4013. (
  4014. const void *data, // data to copy/move/link
  4015. uint size, // size of 'data'
  4016. CopyMode_t mode, // copy mode
  4017. bool *res_alloced // not NULL:
  4018. // store true, if data must be freed
  4019. // otherwise store false
  4020. )
  4021. {
  4022. DASSERT( data || !size );
  4023. DASSERT( mode == CPM_COPY || mode == CPM_MOVE || mode == CPM_LINK );
  4024. if ( !data || !size )
  4025. {
  4026. if (res_alloced)
  4027. *res_alloced = false;
  4028. return (void*)EmptyString;
  4029. }
  4030. if (res_alloced)
  4031. *res_alloced = mode != CPM_LINK;
  4032. return mode == CPM_COPY ? MEMDUP(data,size) : (void*)data;
  4033. }
  4034. ///////////////////////////////////////////////////////////////////////////////
  4035. char * CopyString
  4036. (
  4037. ccp string, // string to copy/move/link
  4038. CopyMode_t mode, // copy mode
  4039. bool *res_alloced // not NULL:
  4040. // store true, if data must be freed
  4041. // otherwise store false
  4042. )
  4043. {
  4044. DASSERT( mode == CPM_COPY || mode == CPM_MOVE || mode == CPM_LINK );
  4045. if ( !string || !*string )
  4046. {
  4047. if (res_alloced)
  4048. *res_alloced = false;
  4049. return string ? (char*)EmptyString : 0;
  4050. }
  4051. if (res_alloced)
  4052. *res_alloced = mode != CPM_LINK;
  4053. return mode == CPM_COPY ? STRDUP(string) : (char*)string;
  4054. }
  4055. //
  4056. ///////////////////////////////////////////////////////////////////////////////
  4057. /////////////// ContainerData_t, Container_t ///////////////
  4058. ///////////////////////////////////////////////////////////////////////////////
  4059. Container_t * CreateContainer
  4060. (
  4061. // returns 'c' or the alloced container
  4062. // 'c' is always initialized
  4063. Container_t *c, // valid container, alloc one if NULL
  4064. int protect, // initial value for protection
  4065. const void *data, // data to copy/move/link
  4066. uint size, // size of 'data'
  4067. CopyMode_t mode // copy mode on creation
  4068. )
  4069. {
  4070. if (!c)
  4071. c = MALLOC(sizeof(*c));
  4072. memset(c,0,sizeof(*c));
  4073. c->protect_level = protect;
  4074. ContainerData_t *cdata = CALLOC(sizeof(*cdata),1);
  4075. c->cdata = cdata;
  4076. cdata->data = CopyData(data,size,mode,&cdata->data_alloced);
  4077. cdata->size = size;
  4078. cdata->ref_count = 1;
  4079. if ( protect > 0 )
  4080. cdata->protect_count++;
  4081. return c;
  4082. }
  4083. ///////////////////////////////////////////////////////////////////////////////
  4084. Container_t * InheritContainer
  4085. (
  4086. // returns 'c' or the alloced container
  4087. Container_t *c, // valid container, alloc one if NULL
  4088. int protect, // initial value for protection
  4089. const Container_t *parent, // NULL or valid parent container
  4090. const void *data, // data to copy/move/link
  4091. uint size // size of 'data'
  4092. )
  4093. {
  4094. if (!c)
  4095. c = CALLOC(sizeof(*c),1);
  4096. if ( InContainerS(parent,data,size) || !InContainerS(c,data,size) )
  4097. {
  4098. UnlinkContainerData(c);
  4099. UseContainerData(c,protect,parent);
  4100. }
  4101. return c;
  4102. }
  4103. ///////////////////////////////////////////////////////////////////////////////
  4104. bool AssignContainer
  4105. (
  4106. // return TRUE on new ContainerData_t
  4107. Container_t *c, // valid container; if NULL: only FREE(data)
  4108. int protect, // new protection level
  4109. const void *data, // data to copy/move/link
  4110. uint size, // size of 'data'
  4111. CopyMode_t mode // copy mode on creation
  4112. )
  4113. {
  4114. if (c)
  4115. {
  4116. SetProtectContainer(c,protect);
  4117. if (!InContainerS(c,data,size))
  4118. {
  4119. UnlinkContainerData(c);
  4120. ContainerData_t *cdata = CALLOC(sizeof(*cdata),1);
  4121. c->cdata = cdata;
  4122. cdata->data = CopyData(data,size,mode,&cdata->data_alloced);
  4123. cdata->size = size;
  4124. cdata->ref_count = 1;
  4125. if ( protect > 0 )
  4126. cdata->protect_count++;
  4127. return true;
  4128. }
  4129. }
  4130. if ( mode == CPM_MOVE )
  4131. FREE((void*)data);
  4132. return false;
  4133. }
  4134. ///////////////////////////////////////////////////////////////////////////////
  4135. void ResetContainer
  4136. (
  4137. Container_t *c // container to reset => no data
  4138. )
  4139. {
  4140. if (c)
  4141. {
  4142. UnlinkContainerData(c);
  4143. memset(c,0,sizeof(*c));
  4144. }
  4145. }
  4146. ///////////////////////////////////////////////////////////////////////////////
  4147. void DeleteContainer
  4148. (
  4149. Container_t *c // container to reset and to free => no data
  4150. )
  4151. {
  4152. if (c)
  4153. {
  4154. UnlinkContainerData(c);
  4155. FREE(c);
  4156. }
  4157. }
  4158. ///////////////////////////////////////////////////////////////////////////////
  4159. void UnlinkContainerData
  4160. (
  4161. Container_t *c // container to reset => no data
  4162. )
  4163. {
  4164. if ( c && c->cdata )
  4165. {
  4166. ContainerData_t *cdata = c->cdata;
  4167. if ( c->protect_level > 0 )
  4168. cdata->protect_count--;
  4169. c->cdata = 0;
  4170. if ( !--cdata->ref_count )
  4171. {
  4172. if (cdata->data_alloced)
  4173. FREE((void*)cdata->data);
  4174. FREE(cdata);
  4175. }
  4176. }
  4177. }
  4178. ///////////////////////////////////////////////////////////////////////////////
  4179. ///////////////////////////////////////////////////////////////////////////////
  4180. ContainerData_t * LinkContainerData
  4181. (
  4182. // increment 'ref_count' and return NULL or current container-data
  4183. // => use CatchContainerData() to complete operation
  4184. const Container_t *c // NULL or valid container
  4185. )
  4186. {
  4187. if ( !c || !c->cdata )
  4188. return 0;
  4189. c->cdata->ref_count++;
  4190. return c->cdata;
  4191. }
  4192. //-----------------------------------------------------------------------------
  4193. ContainerData_t * MoveContainerData
  4194. (
  4195. // return NULL or unlinked current container-data
  4196. // => use CatchContainerData() to complete operation
  4197. Container_t *c // NULL or valid container
  4198. )
  4199. {
  4200. if ( !c || !c->cdata )
  4201. return 0;
  4202. ContainerData_t *cdata = c->cdata;
  4203. cdata->ref_count++;
  4204. UnlinkContainerData(c);
  4205. return cdata;
  4206. }
  4207. //-----------------------------------------------------------------------------
  4208. Container_t * CatchContainerData
  4209. (
  4210. // returns 'c' or the alloced container
  4211. // 'c' is always initialized
  4212. Container_t *c, // valid container, alloc one if NULL
  4213. int protect, // initial value for protection
  4214. ContainerData_t *cdata // if not NULL: catch this
  4215. )
  4216. {
  4217. if (!c)
  4218. c = MALLOC(sizeof(*c));
  4219. memset(c,0,sizeof(*c));
  4220. c->protect_level = protect;
  4221. if (cdata)
  4222. {
  4223. c->cdata = cdata;
  4224. if ( protect > 0 )
  4225. cdata->protect_count++;
  4226. }
  4227. return c;
  4228. }
  4229. ///////////////////////////////////////////////////////////////////////////////
  4230. ///////////////////////////////////////////////////////////////////////////////
  4231. ContainerData_t * DisjoinContainerData
  4232. (
  4233. // Disjoin data container date without freeing it. Call either
  4234. // JoinContainerData() or FreeContainerData() to finish operation.
  4235. // Reference counters are not modified.
  4236. // Return the data container or NULL
  4237. Container_t *c // NULL or valid container
  4238. )
  4239. {
  4240. ContainerData_t *res = 0;
  4241. if ( c && c->cdata )
  4242. {
  4243. const int old_protect = SetProtectContainer(c,0);
  4244. res = c->cdata;
  4245. c->cdata = 0;
  4246. SetProtectContainer(c,old_protect);
  4247. }
  4248. return res;
  4249. }
  4250. ///////////////////////////////////////////////////////////////////////////////
  4251. void JoinContainerData
  4252. (
  4253. // Join a data container, that was diosjoined by DisjoinContainerData()
  4254. // Reference counters are not modified.
  4255. Container_t *c, // container to reset => no data
  4256. ContainerData_t *cdata // NULL or container-data to join
  4257. )
  4258. {
  4259. if (c)
  4260. {
  4261. UnlinkContainerData(c);
  4262. DASSERT(!c->cdata);
  4263. if (cdata)
  4264. {
  4265. const int old_protect = SetProtectContainer(c,0);
  4266. c->cdata = cdata;
  4267. SetProtectContainer(c,old_protect);
  4268. }
  4269. }
  4270. else
  4271. FreeContainerData(cdata);
  4272. }
  4273. ///////////////////////////////////////////////////////////////////////////////
  4274. void FreeContainerData
  4275. (
  4276. // Decrement the reference counter of an already disjoined data container
  4277. // and free it if unused.
  4278. ContainerData_t *cdata // NULL or container-data to free
  4279. )
  4280. {
  4281. if ( cdata && !--cdata->ref_count )
  4282. {
  4283. if (cdata->data_alloced)
  4284. FREE((void*)cdata->data);
  4285. FREE(cdata);
  4286. }
  4287. }
  4288. ///////////////////////////////////////////////////////////////////////////////
  4289. ///////////////////////////////////////////////////////////////////////////////
  4290. bool ModifyAllContainer
  4291. (
  4292. // prepare modification of container-data, create a copy if necessary
  4293. // return true, if a new container-data is used
  4294. Container_t *c // NULL or valid container
  4295. )
  4296. {
  4297. if ( c && c->cdata && !ModificationAllowed(c) )
  4298. {
  4299. ContainerData_t *oldcd = c->cdata;
  4300. ContainerData_t *newcd = CALLOC(sizeof(*newcd),1);
  4301. newcd->data = MEMDUP(oldcd->data,oldcd->size);
  4302. newcd->size = oldcd->size;
  4303. newcd->data_alloced = true;
  4304. newcd->ref_count = 1;
  4305. if ( c->protect_level > 0 )
  4306. newcd->protect_count++;
  4307. UnlinkContainerData(c);
  4308. c->cdata = newcd;
  4309. return true;
  4310. }
  4311. return false;
  4312. }
  4313. //-----------------------------------------------------------------------------
  4314. bool ModifyContainer
  4315. (
  4316. // prepare modification of container-data, create an extract if necessary
  4317. // return true, if a new container-data is used
  4318. Container_t *c, // NULL or valid container
  4319. const void *data, // data to copy/move/link
  4320. uint size, // size of 'data'
  4321. CopyMode_t mode // copy mode on creation
  4322. )
  4323. {
  4324. if ( c && c->cdata && ( !ModificationAllowed(c) || !InContainerS(c,data,size) ))
  4325. {
  4326. ContainerData_t *newcd = CALLOC(sizeof(*newcd),1);
  4327. newcd->data = CopyData(data,size,mode,&newcd->data_alloced);
  4328. newcd->size = size;
  4329. newcd->ref_count = 1;
  4330. if ( c->protect_level > 0 )
  4331. newcd->protect_count++;
  4332. UnlinkContainerData(c);
  4333. c->cdata = newcd;
  4334. return true;
  4335. }
  4336. if ( mode == CPM_MOVE )
  4337. FREE((void*)data);
  4338. return false;
  4339. }
  4340. ///////////////////////////////////////////////////////////////////////////////
  4341. int SetProtectContainer
  4342. (
  4343. // returns 'c' new protection level
  4344. Container_t *c, // valid container, alloc one if NULL
  4345. int new_protect // new protection value
  4346. )
  4347. {
  4348. DASSERT(c);
  4349. if (c->cdata)
  4350. {
  4351. if ( new_protect > 0 )
  4352. {
  4353. if ( c->protect_level <= 0 )
  4354. c->cdata->protect_count++;
  4355. }
  4356. else
  4357. {
  4358. if ( c->protect_level > 0 )
  4359. c->cdata->protect_count--;
  4360. }
  4361. }
  4362. return c->protect_level = new_protect;
  4363. }
  4364. ///////////////////////////////////////////////////////////////////////////////
  4365. ///////////////////////////////////////////////////////////////////////////////
  4366. uint DumpInfoContainer
  4367. (
  4368. // return the number of printed lines
  4369. FILE *f, // valid output file
  4370. const ColorSet_t *colset, // NULL or color set
  4371. int indent, // indent the output
  4372. ccp prefix, // not NULL: use it as prefix behind indention
  4373. const Container_t *c, // dump infos for this container, NULL allowed
  4374. uint hexdump_len // max number of bytes used for a hexdump
  4375. )
  4376. {
  4377. DASSERT(f);
  4378. if (!c)
  4379. return 0;
  4380. indent = NormalizeIndent(indent);
  4381. if (!colset)
  4382. colset = GetColorSet0();
  4383. fprintf(f,"%*s%s%s%smod=%d, PL=%d, ",
  4384. indent,"",
  4385. colset->caption, prefix ? prefix : "",
  4386. colset->status, ModificationAllowed(c), c->protect_level );
  4387. uint line_count = DumpInfoContainerData(f,0,0,0,c->cdata,hexdump_len,indent+2);
  4388. if (!line_count)
  4389. {
  4390. fputs("<no-data>",f);
  4391. line_count++;
  4392. }
  4393. fprintf(f,"%s\n",colset->reset);
  4394. return line_count;
  4395. }
  4396. ///////////////////////////////////////////////////////////////////////////////
  4397. uint DumpInfoContainerData
  4398. (
  4399. // return the number of printed lines
  4400. FILE *f, // valid output file
  4401. const ColorSet_t *colset, // NULL or color set
  4402. int indent, // indent of output
  4403. ccp prefix, // not NULL: use it as prefix behind indention
  4404. const
  4405. ContainerData_t *cdata, // dump infos for this container-data, NULL allowed
  4406. uint hexdump_len, // max number of bytes used for a hexdump
  4407. int hexdump_indent // indent of hexdump
  4408. )
  4409. {
  4410. DASSERT(f);
  4411. if (!cdata)
  4412. return 0;
  4413. indent = NormalizeIndent(indent);
  4414. if (!colset)
  4415. colset = GetColorSet0();
  4416. fprintf(f,"%*s%s%s%sPC=%d, RC=%d, alloc=%d, size=%u=0x%x, addr=%p\n",
  4417. indent,"",
  4418. colset->caption, prefix ? prefix : "", colset->status,
  4419. cdata->protect_count, cdata->ref_count, cdata->data_alloced,
  4420. cdata->size, cdata->size, cdata->data );
  4421. if ( hexdump_len > 0 && cdata->data && cdata->size )
  4422. {
  4423. if ( hexdump_len > cdata->size )
  4424. hexdump_len = cdata->size;
  4425. return 1 + HexDump16(f,hexdump_indent,0,cdata->data,hexdump_len);
  4426. }
  4427. return 1;
  4428. }
  4429. //
  4430. ///////////////////////////////////////////////////////////////////////////////
  4431. /////////////// split strings ///////////////
  4432. ///////////////////////////////////////////////////////////////////////////////
  4433. uint SplitByCharMem
  4434. (
  4435. // 'mem_list' will be padded with {EmptyString,0}
  4436. mem_t *mem_list, // array of mem_t
  4437. uint n_mem, // number of elements of 'mem_list'
  4438. mem_t source, // source string
  4439. char sep // separator character
  4440. )
  4441. {
  4442. DASSERT(mem_list);
  4443. DASSERT(n_mem>1);
  4444. ccp src = source.ptr;
  4445. ccp end = src + source.len;
  4446. mem_t *mem = mem_list;
  4447. mem_t *last = mem + n_mem - 1;
  4448. while ( mem < last )
  4449. {
  4450. mem->ptr = src;
  4451. while ( src < end && *src != sep )
  4452. src++;
  4453. mem->len = src - mem->ptr;
  4454. mem++;
  4455. if ( ++src > end )
  4456. break;
  4457. }
  4458. if ( src <= end )
  4459. {
  4460. mem->ptr = src;
  4461. mem->len = end - src;
  4462. mem++;
  4463. }
  4464. const uint result = mem - mem_list;
  4465. while ( mem <= last )
  4466. {
  4467. mem->ptr = EmptyString;
  4468. mem->len = 0;
  4469. mem++;
  4470. }
  4471. return result;
  4472. }
  4473. ///////////////////////////////////////////////////////////////////////////////
  4474. uint SplitByTextMem
  4475. (
  4476. // 'mem_list' will be padded with {EmptyString,0}
  4477. mem_t *mem_list, // array of mem_t
  4478. uint n_mem, // number of elements of 'mem_list'
  4479. mem_t source, // source string
  4480. mem_t sep // separator text
  4481. )
  4482. {
  4483. DASSERT(mem_list);
  4484. DASSERT(n_mem>0);
  4485. ccp src = source.ptr;
  4486. ccp end = src + source.len;
  4487. mem_t *mem = mem_list;
  4488. mem_t *last = mem + n_mem - 1;
  4489. if ( sep.len > 0 && sep.len <= source.len )
  4490. {
  4491. ccp cmp_max = end - sep.len;
  4492. while ( mem < last )
  4493. {
  4494. mem->ptr = src;
  4495. while ( src <= cmp_max && memcmp(src,sep.ptr,sep.len) )
  4496. src++;
  4497. if ( src > cmp_max )
  4498. {
  4499. mem->len = end - mem->ptr;
  4500. mem++;
  4501. src = end + 1;
  4502. break;
  4503. }
  4504. mem->len = src - mem->ptr;
  4505. mem++;
  4506. src += sep.len;
  4507. }
  4508. }
  4509. if ( src <= end )
  4510. {
  4511. mem->ptr = src;
  4512. mem->len = end - src;
  4513. mem++;
  4514. }
  4515. const uint result = mem - mem_list;
  4516. while ( mem <= last )
  4517. {
  4518. mem->ptr = EmptyString;
  4519. mem->len = 0;
  4520. mem++;
  4521. }
  4522. return result;
  4523. }
  4524. ///////////////////////////////////////////////////////////////////////////////
  4525. uint SplitByCharMemList
  4526. (
  4527. mem_list_t *ml, // valid destination mem_list
  4528. bool init_ml, // true: initialize 'ml' first
  4529. mem_t source, // source string
  4530. char sep, // separator character
  4531. int max_fields // >0: max number of result fields
  4532. )
  4533. {
  4534. DASSERT(ml);
  4535. if (init_ml)
  4536. InitializeMemList(ml);
  4537. ml->used = 0;
  4538. ml->buf_used = 0;
  4539. NeedBufMemList(ml,source.len+1,0);
  4540. if ( max_fields <= 0 )
  4541. max_fields = INT_MAX;
  4542. ccp src = source.ptr;
  4543. ccp end = src + source.len;
  4544. while ( max_fields-- > 1 )
  4545. {
  4546. mem_t mem;
  4547. mem.ptr = src;
  4548. while ( src < end && *src != sep )
  4549. src++;
  4550. mem.len = src - mem.ptr;
  4551. AppendMemListN(ml,&mem,1,0);
  4552. if ( ++src > end )
  4553. break;
  4554. }
  4555. if ( src <= end )
  4556. {
  4557. mem_t mem = { src, end - src };
  4558. AppendMemListN(ml,&mem,1,0);
  4559. }
  4560. return ml->used;
  4561. }
  4562. ///////////////////////////////////////////////////////////////////////////////
  4563. uint SplitByTextMemList
  4564. (
  4565. mem_list_t *ml, // valid destination mem_list
  4566. bool init_ml, // true: initialize 'ml' first
  4567. mem_t source, // source string
  4568. mem_t sep, // separator text
  4569. int max_fields // >0: max number of result fields
  4570. )
  4571. {
  4572. DASSERT(ml);
  4573. if (init_ml)
  4574. InitializeMemList(ml);
  4575. ml->used = 0;
  4576. ml->buf_used = 0;
  4577. NeedBufMemList(ml,source.len+1,0);
  4578. if ( max_fields <= 0 )
  4579. max_fields = INT_MAX;
  4580. ccp src = source.ptr;
  4581. ccp end = src + source.len;
  4582. if ( sep.len > 0 && sep.len <= source.len )
  4583. {
  4584. ccp cmp_max = end - sep.len;
  4585. while ( max_fields-- > 1 )
  4586. {
  4587. mem_t mem;
  4588. mem.ptr = src;
  4589. while ( src <= cmp_max && memcmp(src,sep.ptr,sep.len) )
  4590. src++;
  4591. if ( src > cmp_max )
  4592. {
  4593. mem.len = end - mem.ptr;
  4594. AppendMemListN(ml,&mem,1,0);
  4595. src = end + 1;
  4596. break;
  4597. }
  4598. mem.len = src - mem.ptr;
  4599. AppendMemListN(ml,&mem,1,0);
  4600. src += sep.len;
  4601. }
  4602. }
  4603. if ( src <= end )
  4604. {
  4605. mem_t mem = { src, end - src };
  4606. AppendMemListN(ml,&mem,1,0);
  4607. }
  4608. return ml->used;
  4609. }
  4610. //
  4611. ///////////////////////////////////////////////////////////////////////////////
  4612. /////////////// MatchPattern() ///////////////
  4613. ///////////////////////////////////////////////////////////////////////////////
  4614. bool HaveWildcards ( mem_t str )
  4615. {
  4616. if (!str.ptr)
  4617. return false;
  4618. if ( str.len < 0 )
  4619. str.len = strlen(str.ptr);
  4620. for ( ccp w = PATTERN_WILDCARDS; *w; w++ )
  4621. if (memchr(str.ptr,*w,str.len))
  4622. return true;
  4623. return false;
  4624. }
  4625. ///////////////////////////////////////////////////////////////////////////////
  4626. char * FindFirstWildcard ( mem_t str )
  4627. {
  4628. if (!str.len)
  4629. return 0;
  4630. ccp end = str.ptr + str.len;
  4631. for ( ccp ptr = str.ptr; ptr < end; ptr++ )
  4632. if (strchr(PATTERN_WILDCARDS,*ptr))
  4633. return (char*)ptr;
  4634. return 0;
  4635. }
  4636. ///////////////////////////////////////////////////////////////////////////////
  4637. static ccp AnalyseBrackets
  4638. (
  4639. ccp pattern,
  4640. ccp * p_start,
  4641. bool * p_negate,
  4642. int * p_multiple
  4643. )
  4644. {
  4645. ASSERT(pattern);
  4646. bool negate = false;
  4647. if ( *pattern == '^' )
  4648. {
  4649. pattern++;
  4650. negate = true;
  4651. }
  4652. if (p_negate)
  4653. *p_negate = negate;
  4654. int multiple = 0;
  4655. if ( *pattern == '+' )
  4656. {
  4657. pattern++;
  4658. multiple = 1;
  4659. }
  4660. else if ( *pattern == '*' )
  4661. {
  4662. pattern++;
  4663. multiple = 2;
  4664. }
  4665. if (p_multiple)
  4666. *p_multiple = multiple;
  4667. if (p_start)
  4668. *p_start = pattern;
  4669. if (*pattern) // ']' allowed in first position
  4670. pattern++;
  4671. while ( *pattern && *pattern++ != ']' ) // find end
  4672. ;
  4673. return pattern;
  4674. }
  4675. ///////////////////////////////////////////////////////////////////////////////
  4676. static bool MatchBracktes
  4677. (
  4678. char ch,
  4679. ccp pattern,
  4680. bool negate
  4681. )
  4682. {
  4683. if (!ch)
  4684. return false;
  4685. bool ok = false;
  4686. ccp p = pattern;
  4687. for (; !ok && *p && ( p == pattern || *p != ']' ); p++ )
  4688. {
  4689. if ( *p == '-' )
  4690. {
  4691. if ( ch <= *++p && ch >= p[-2] )
  4692. {
  4693. if (negate)
  4694. return false;
  4695. ok = true;
  4696. }
  4697. }
  4698. else
  4699. {
  4700. if ( *p == '\\' )
  4701. p++;
  4702. if ( *p == ch )
  4703. {
  4704. if (negate)
  4705. return false;
  4706. ok = true;
  4707. }
  4708. }
  4709. }
  4710. return ok || negate;
  4711. }
  4712. ///////////////////////////////////////////////////////////////////////////////
  4713. static bool MatchPatternHelper
  4714. (
  4715. ccp pattern,
  4716. ccp text,
  4717. bool skip_end,
  4718. int alt_depth,
  4719. char path_sep // path separator character, standard is '/'
  4720. )
  4721. {
  4722. ASSERT(pattern);
  4723. ASSERT(text);
  4724. noTRACE(" - %d,%d |%s|%s|\n",skip_end,alt_depth,pattern,text);
  4725. char ch;
  4726. while ( ( ch = *pattern++ ) != 0 )
  4727. {
  4728. switch (ch)
  4729. {
  4730. case '*':
  4731. if ( *pattern == '*' )
  4732. {
  4733. pattern++;
  4734. if (*pattern)
  4735. while (!MatchPatternHelper(pattern,text,skip_end,alt_depth,path_sep))
  4736. if (!*text++)
  4737. return false;
  4738. }
  4739. else
  4740. {
  4741. while (!MatchPatternHelper(pattern,text,skip_end,alt_depth,path_sep))
  4742. if ( *text == path_sep || !*text++ )
  4743. return false;
  4744. }
  4745. return true;
  4746. case '#':
  4747. if ( *text < '0' || *text > '9' )
  4748. return false;
  4749. while ( *text >= '0' && *text <= '9' )
  4750. if (MatchPatternHelper(pattern,++text,skip_end,alt_depth,path_sep))
  4751. return true;
  4752. return false;
  4753. case '\t':
  4754. if ( *text < 1 || * text > ' ' )
  4755. return false;
  4756. text++;
  4757. break;
  4758. case '?':
  4759. if ( !*text || *text == path_sep )
  4760. return false;
  4761. text++;
  4762. break;
  4763. case '[':
  4764. {
  4765. ccp start;
  4766. bool negate;
  4767. int multiple;
  4768. TRACELINE;
  4769. pattern = AnalyseBrackets(pattern,&start,&negate,&multiple);
  4770. TRACELINE;
  4771. if ( multiple < 2 && !MatchBracktes(*text++,start,negate) )
  4772. return false;
  4773. if (multiple)
  4774. {
  4775. while (!MatchPatternHelper(pattern,text,skip_end,alt_depth,path_sep))
  4776. if (!MatchBracktes(*text++,start,negate))
  4777. return false;
  4778. return true;
  4779. }
  4780. }
  4781. break;
  4782. case '{':
  4783. for(;;)
  4784. {
  4785. if (MatchPatternHelper(pattern,text,skip_end,alt_depth+1,path_sep))
  4786. return true;
  4787. // skip until next ',' || '}'
  4788. int skip_depth = 1;
  4789. while ( skip_depth > 0 )
  4790. {
  4791. ch = *pattern++;
  4792. switch(ch)
  4793. {
  4794. case 0:
  4795. return false;
  4796. case '\\':
  4797. if (!*pattern)
  4798. return false;
  4799. pattern++;
  4800. break;
  4801. case '{':
  4802. skip_depth++;
  4803. break;
  4804. case ',':
  4805. if ( skip_depth == 1 )
  4806. skip_depth--;
  4807. break;
  4808. case '}':
  4809. if (!--skip_depth)
  4810. return false;
  4811. break;
  4812. case '[': // [2do] forgotten marker?
  4813. pattern = AnalyseBrackets(pattern,0,0,0);
  4814. break;
  4815. }
  4816. }
  4817. }
  4818. case ',':
  4819. if (alt_depth)
  4820. {
  4821. alt_depth--;
  4822. int skip_depth = 1;
  4823. while ( skip_depth > 0 )
  4824. {
  4825. ch = *pattern++;
  4826. switch(ch)
  4827. {
  4828. case 0:
  4829. return false;
  4830. case '\\':
  4831. if (!*pattern)
  4832. return false;
  4833. pattern++;
  4834. break;
  4835. case '{':
  4836. skip_depth++;
  4837. break;
  4838. case '}':
  4839. skip_depth--;
  4840. break;
  4841. case '[': // [2do] forgotten marker?
  4842. pattern = AnalyseBrackets(pattern,0,0,0);
  4843. break;
  4844. }
  4845. }
  4846. }
  4847. else if ( *text++ != ch )
  4848. return false;
  4849. break;
  4850. case '}':
  4851. if ( !alt_depth && *text++ != ch )
  4852. return false;
  4853. break;
  4854. case '$':
  4855. if ( !*pattern && !*text )
  4856. return true;
  4857. if ( *text++ != ch )
  4858. return false;
  4859. break;
  4860. case '\\':
  4861. ch = *pattern++;
  4862. // fall through
  4863. default:
  4864. if ( *text++ != ch )
  4865. return false;
  4866. break;
  4867. }
  4868. }
  4869. return skip_end || *text == 0;
  4870. }
  4871. ///////////////////////////////////////////////////////////////////////////////
  4872. bool MatchPatternFull
  4873. (
  4874. ccp pattern, // pattern text
  4875. ccp text // raw text
  4876. )
  4877. {
  4878. TRACE("MatchPattern(|%s|%s|)\n",pattern,text);
  4879. if ( !pattern || !*pattern )
  4880. return true;
  4881. if (!text)
  4882. text = "";
  4883. if ( *pattern == '^' )
  4884. pattern++;
  4885. return MatchPatternHelper(pattern,text,false,0,'/');
  4886. }
  4887. ///////////////////////////////////////////////////////////////////////////////
  4888. bool MatchPattern
  4889. (
  4890. ccp pattern, // pattern text
  4891. ccp text, // raw text
  4892. char path_sep // path separator character, standard is '/'
  4893. )
  4894. {
  4895. TRACE("MatchPattern(|%s|%s|%c|)\n",pattern,text,path_sep);
  4896. if ( !pattern || !*pattern )
  4897. return true;
  4898. if (!text)
  4899. text = "";
  4900. const size_t plen = strlen(pattern);
  4901. ccp last = pattern + plen - 1;
  4902. char last_ch = *last;
  4903. int count = 0;
  4904. while ( last > pattern && *--last == '\\' )
  4905. count++;
  4906. if ( count & 1 )
  4907. last_ch = 0; // no special char!
  4908. if ( *pattern == path_sep || *pattern == '^' )
  4909. {
  4910. pattern++;
  4911. return MatchPatternHelper(pattern,text,last_ch!='$',0,path_sep);
  4912. }
  4913. while (*text)
  4914. if (MatchPatternHelper(pattern,text++,last_ch!='$',0,path_sep))
  4915. return true;
  4916. return false;
  4917. }
  4918. ///////////////////////////////////////////////////////////////////////////////
  4919. ///////////////////////////////////////////////////////////////////////////////
  4920. ccp MatchStringField ( const StringField_t * sf, ccp key )
  4921. {
  4922. DASSERT(sf);
  4923. DASSERT(key);
  4924. ccp *ptr = sf->field, *end;
  4925. for ( end = ptr + sf->used; ptr < end; ptr++ )
  4926. if (MatchPattern(*ptr,key,'/'))
  4927. return *ptr;
  4928. return 0;
  4929. }
  4930. ///////////////////////////////////////////////////////////////////////////////
  4931. ParamFieldItem_t * MatchParamField ( const ParamField_t * pf, ccp key )
  4932. {
  4933. DASSERT(pf);
  4934. DASSERT(key);
  4935. ParamFieldItem_t *ptr = pf->field, *end;
  4936. for ( end = ptr + pf->used; ptr < end; ptr++ )
  4937. if (MatchPattern(ptr->key,key,'/'))
  4938. return ptr;
  4939. return 0;
  4940. }
  4941. ///////////////////////////////////////////////////////////////////////////////
  4942. ///////////////////////////////////////////////////////////////////////////////
  4943. char * MatchRuleLine
  4944. (
  4945. // returns a pointer to the first non scanned char
  4946. int *status, // not NULL: return match status here
  4947. // -2: no prefix found (no rule found)
  4948. // -1: empty line (no rule found)
  4949. // 0: rule found, but don't match
  4950. // 1: rule found and match
  4951. ccp src, // source line, scanned until CONTROL
  4952. char rule_prefix, // NULL or a rule-beginning-char'
  4953. ccp path, // path to verify
  4954. char path_sep // path separator character, standard is '/'
  4955. )
  4956. {
  4957. int local_status;
  4958. if (!status)
  4959. status = &local_status;
  4960. while ( *src > 0 && *src <= ' ' && *src != '\n' )
  4961. src++;
  4962. if (rule_prefix)
  4963. {
  4964. if ( *src != rule_prefix )
  4965. {
  4966. *status = -2;
  4967. return (char*)src;
  4968. }
  4969. src++;
  4970. while ( *src > 0 && *src <= ' ' && *src != '\n' )
  4971. src++;
  4972. }
  4973. ccp start = src;
  4974. while ( (uchar)*src >= ' ' )
  4975. src++;
  4976. char buf[1000];
  4977. uint len = src - start;
  4978. if (!len)
  4979. {
  4980. *status = -1;
  4981. return (char*)src;
  4982. }
  4983. if ( len > sizeof(buf)-1 )
  4984. len = sizeof(buf)-1;
  4985. memcpy(buf,start,len);
  4986. buf[len] = 0;
  4987. *status = MatchPattern(buf,path,path_sep);
  4988. return (char*)src;
  4989. }
  4990. //
  4991. ///////////////////////////////////////////////////////////////////////////////
  4992. /////////////// scan keywords ///////////////
  4993. ///////////////////////////////////////////////////////////////////////////////
  4994. const KeywordTab_t *GetKewordById
  4995. (
  4996. const KeywordTab_t *key_tab, // NULL or pointer to command table
  4997. s64 id // id to search
  4998. )
  4999. {
  5000. if (key_tab)
  5001. {
  5002. const KeywordTab_t *key;
  5003. for ( key = key_tab; *key->name1; key++ )
  5004. if ( key->id == id )
  5005. return key;
  5006. }
  5007. return 0;
  5008. }
  5009. ///////////////////////////////////////////////////////////////////////////////
  5010. const KeywordTab_t *GetKewordByIdAndOpt
  5011. (
  5012. const KeywordTab_t *key_tab, // NULL or pointer to command table
  5013. s64 id, // id to search
  5014. s64 opt // opt to search
  5015. )
  5016. {
  5017. if (key_tab)
  5018. {
  5019. const KeywordTab_t *key;
  5020. for ( key = key_tab; *key->name1; key++ )
  5021. if ( key->id == id && key->opt == opt )
  5022. return key;
  5023. }
  5024. return 0;
  5025. }
  5026. ///////////////////////////////////////////////////////////////////////////////
  5027. ///////////////////////////////////////////////////////////////////////////////
  5028. const KeywordTab_t * ScanKeyword
  5029. (
  5030. int * res_abbrev, // NULL or pointer to result 'abbrev_count'
  5031. ccp arg, // argument to scan
  5032. const KeywordTab_t * key_tab // valid pointer to command table
  5033. )
  5034. {
  5035. DASSERT(arg);
  5036. char key_buf[KEYWORD_NAME_MAX];
  5037. char *dest = key_buf;
  5038. char *end = key_buf + sizeof(key_buf) - 1;
  5039. while ( *arg && *arg != ',' && *arg != ';' && dest < end )
  5040. *dest++ = toupper((int)*arg++);
  5041. *dest = 0;
  5042. const int key_len = dest - key_buf;
  5043. int favor_count = 0, abbrev_count = 0;
  5044. const KeywordTab_t *ct, *key_ct = 0;
  5045. const KeywordTab_t *favor_ct = 0, *favor_prev = 0, *abbrev_ct = 0, *abbrev_prev = 0;
  5046. for ( ct = key_tab; ct->name1; ct++ )
  5047. {
  5048. if ( !strcmp(ct->name1,key_buf) )
  5049. {
  5050. key_ct = ct;
  5051. break;
  5052. }
  5053. bool name2_abbrev = false;
  5054. if (ct->name2)
  5055. {
  5056. if (!strcmp(ct->name2,key_buf))
  5057. {
  5058. key_ct = ct;
  5059. break;
  5060. }
  5061. name2_abbrev = !memcmp(ct->name2,key_buf,key_len);
  5062. }
  5063. if ( name2_abbrev && !memcmp(ct->name1,key_buf,strlen(ct->name1)) )
  5064. {
  5065. if (!favor_ct)
  5066. {
  5067. favor_prev = favor_ct = ct;
  5068. favor_count++;
  5069. }
  5070. else if ( favor_prev->id != ct->id || favor_prev->opt != ct->opt )
  5071. {
  5072. favor_prev = ct;
  5073. favor_count++;
  5074. }
  5075. }
  5076. if ( *key_buf == '_' ) // no abbreviations for commands beginning with '_'
  5077. continue;
  5078. if ( name2_abbrev || !memcmp(ct->name1,key_buf,key_len) )
  5079. {
  5080. if (!abbrev_ct)
  5081. {
  5082. abbrev_prev = abbrev_ct = ct;
  5083. abbrev_count++;
  5084. }
  5085. else if ( abbrev_prev->id != ct->id || abbrev_prev->opt != ct->opt )
  5086. {
  5087. abbrev_prev = ct;
  5088. abbrev_count++;
  5089. }
  5090. }
  5091. }
  5092. if (key_ct)
  5093. abbrev_count = 0;
  5094. else if ( favor_count == 1 )
  5095. {
  5096. key_ct = favor_ct;
  5097. abbrev_count = 0;
  5098. }
  5099. else if ( abbrev_count == 1 )
  5100. key_ct = abbrev_ct;
  5101. else if (!abbrev_count)
  5102. abbrev_count = -1;
  5103. if (res_abbrev)
  5104. *res_abbrev = abbrev_count;
  5105. return key_ct;
  5106. }
  5107. ///////////////////////////////////////////////////////////////////////////////
  5108. s64 ScanKeywordListEx
  5109. (
  5110. ccp arg, // argument to scan
  5111. const KeywordTab_t * key_tab, // valid pointer to command table
  5112. KeywordCallbackFunc func, // NULL or calculation function
  5113. bool allow_prefix, // allow '-' | '+' | '=' as prefix
  5114. u32 max_number, // allow numbers < 'max_number' (0=disabled)
  5115. s64 result, // start value for result
  5116. uint err_mode, // bit field:
  5117. // 1: continue on error
  5118. ccp err_msg, // not NULL: print a warning message:
  5119. // "<ERR_MSG>: Unknown keyword: <KEY>"
  5120. enumError err_code, // use 'err_code' for the 'err_msg'
  5121. uint *err_count // not NULL: store errors here
  5122. )
  5123. {
  5124. ASSERT(arg);
  5125. char key_buf[KEYWORD_NAME_MAX];
  5126. char *end = key_buf + sizeof(key_buf) - 1;
  5127. uint err_cnt = 0;
  5128. for(;;)
  5129. {
  5130. while ( *arg > 0 && *arg <= ' ' || *arg == ',' || *arg == '.' )
  5131. arg++;
  5132. if ( !*arg || *arg == '#' )
  5133. break;
  5134. char *dest = key_buf;
  5135. while ( *arg > ' ' && *arg != ',' && *arg != '.' && *arg != '#'
  5136. && ( *arg != '+' || dest == key_buf ) && dest < end )
  5137. *dest++ = *arg++;
  5138. *dest = 0;
  5139. char prefix = 0;
  5140. int abbrev_count;
  5141. const KeywordTab_t * cptr = ScanKeyword(&abbrev_count,key_buf,key_tab);
  5142. if ( !cptr && allow_prefix && key_buf[1]
  5143. && ( *key_buf == '+' || *key_buf == '-'
  5144. || *key_buf == '/' || *key_buf == '=' ))
  5145. {
  5146. prefix = *key_buf == '/' ? '-' : *key_buf;
  5147. cptr = ScanKeyword(&abbrev_count,key_buf+1,key_tab);
  5148. }
  5149. KeywordTab_t ct_num = { 0, key_buf, 0, 0 };
  5150. if ( max_number && abbrev_count )
  5151. {
  5152. char * start = key_buf + (prefix!=0);
  5153. ulong num = str2l(start,&dest,10);
  5154. if ( num < max_number && dest > start && !*dest )
  5155. {
  5156. ct_num.id = num;
  5157. cptr = &ct_num;
  5158. }
  5159. }
  5160. noPRINT("cptr=%p [%s], opt=%llx, prefix=%02x\n",
  5161. cptr, cptr ? cptr->name1 : "", cptr ? cptr->opt : 0, prefix );
  5162. if ( !cptr || cptr->opt && prefix && prefix != '+' )
  5163. {
  5164. if (err_msg)
  5165. {
  5166. if ( abbrev_count > 1 )
  5167. ERROR0(err_code,"%s: Ambiguous keyword: %s\n",err_msg,key_buf);
  5168. else
  5169. ERROR0(err_code,"%s: Unknown keyword: %s\n",err_msg,key_buf);
  5170. }
  5171. err_cnt++;
  5172. if ( err_mode & 1 )
  5173. continue;
  5174. result = M1(result);
  5175. break;
  5176. }
  5177. if (func)
  5178. {
  5179. const s64 res = func(0,key_buf,key_tab,cptr,prefix,result);
  5180. if ( res == M1(res) )
  5181. {
  5182. if ( !(err_mode & 1) )
  5183. {
  5184. result = res;
  5185. break;
  5186. }
  5187. }
  5188. else
  5189. result = res;
  5190. }
  5191. else
  5192. {
  5193. switch (prefix)
  5194. {
  5195. case 0:
  5196. case '+': result = result & ~cptr->opt | cptr->id; break;
  5197. case '-': result &= ~cptr->id; break;
  5198. case '=': result = cptr->id; break;
  5199. }
  5200. }
  5201. }
  5202. if (err_count)
  5203. *err_count = err_cnt;
  5204. return result;
  5205. }
  5206. ///////////////////////////////////////////////////////////////////////////////
  5207. enumError ScanKeywordListFunc
  5208. (
  5209. ccp arg, // argument to scan
  5210. const KeywordTab_t * key_tab, // valid pointer to command table
  5211. KeywordCallbackFunc func, // calculation function
  5212. void * param, // used define parameter for 'func'
  5213. bool allow_prefix // allow '-' | '+' | '=' as prefix
  5214. )
  5215. {
  5216. ASSERT(arg);
  5217. ASSERT(func);
  5218. char key_buf[KEYWORD_NAME_MAX];
  5219. char *end = key_buf + sizeof(key_buf) - 1;
  5220. for(;;)
  5221. {
  5222. while ( *arg > 0 && *arg <= ' ' || *arg == ',' || *arg == '.' )
  5223. arg++;
  5224. if (!*arg)
  5225. return ERR_OK;
  5226. char *dest = key_buf;
  5227. while ( *arg > ' ' && *arg != ',' && *arg != '.'
  5228. && ( *arg != '+' || dest == key_buf ) && dest < end )
  5229. *dest++ = *arg++;
  5230. *dest = 0;
  5231. char prefix = 0;
  5232. int abbrev_count;
  5233. const KeywordTab_t * cptr = ScanKeyword(&abbrev_count,key_buf,key_tab);
  5234. if ( !cptr && allow_prefix && key_buf[1]
  5235. && ( *key_buf == '+' || *key_buf == '-' || *key_buf == '/' || *key_buf == '=' ))
  5236. {
  5237. prefix = *key_buf == '/' ? '-' : *key_buf;
  5238. cptr = ScanKeyword(&abbrev_count,key_buf+1,key_tab);
  5239. }
  5240. const enumError err = func(param,key_buf,key_tab,cptr,prefix,0);
  5241. if (err)
  5242. return err;
  5243. }
  5244. }
  5245. ///////////////////////////////////////////////////////////////////////////////
  5246. static s64 ScanKeywordListMaskHelper
  5247. (
  5248. void * param, // NULL or user defined parameter
  5249. ccp name, // normalized name of option
  5250. const KeywordTab_t * key_tab, // valid pointer to command table
  5251. const KeywordTab_t * key, // valid pointer to found command
  5252. char prefix, // 0 | '-' | '+' | '='
  5253. s64 result // current value of result
  5254. )
  5255. {
  5256. return key->opt
  5257. ? result & ~key->opt | key->id
  5258. : key->id;
  5259. }
  5260. //-----------------------------------------------------------------------------
  5261. s64 ScanKeywordListMask
  5262. (
  5263. ccp arg, // argument to scan
  5264. const KeywordTab_t * key_tab // valid pointer to command table
  5265. )
  5266. {
  5267. return ScanKeywordList(arg,key_tab,ScanKeywordListMaskHelper,false,0,0,0,0);
  5268. }
  5269. ///////////////////////////////////////////////////////////////////////////////
  5270. uint CollectAmbiguousKeywords
  5271. (
  5272. char *buf, // destination buffer, 200 bytes are good
  5273. uint buf_size, // size of buffer
  5274. const KeywordTab_t * key_tab, // NULL or pointer to command table
  5275. ccp key_arg // analyzed command
  5276. )
  5277. {
  5278. DASSERT(buf);
  5279. DASSERT(buf_size>10);
  5280. DASSERT(key_tab);
  5281. DASSERT(key_arg);
  5282. int n = 0;
  5283. char *dest = buf, *buf_end = buf + buf_size - 2;
  5284. const int arg_len = strlen(key_arg);
  5285. int last_id = -1;
  5286. const KeywordTab_t *ct;
  5287. for ( ct = key_tab; ct->name1 && dest < buf_end; ct++ )
  5288. {
  5289. if ( ct->id != last_id )
  5290. {
  5291. ccp ok = 0;
  5292. if (!strncasecmp(key_arg,ct->name1,arg_len))
  5293. ok = ct->name1;
  5294. else if ( ct->name2 && !strncasecmp(key_arg,ct->name2,arg_len))
  5295. ok = ct->name2;
  5296. if (ok)
  5297. {
  5298. if (!n++)
  5299. {
  5300. *dest++ = ' ';
  5301. *dest++ = '[';
  5302. }
  5303. else if ( n > 5 )
  5304. {
  5305. dest = StringCopyE(dest,buf_end,",...");
  5306. break;
  5307. }
  5308. else
  5309. *dest++ = ',';
  5310. dest = StringCopyE(dest,buf_end,ok);
  5311. last_id = ct->id;
  5312. }
  5313. }
  5314. }
  5315. if ( dest > buf+1 )
  5316. *dest++ = ']';
  5317. else
  5318. dest = buf;
  5319. *dest = 0;
  5320. return dest - buf;
  5321. }
  5322. ///////////////////////////////////////////////////////////////////////////////
  5323. ccp GetKeywordError
  5324. (
  5325. const KeywordTab_t * key_tab, // NULL or pointer to command table
  5326. ccp key_arg, // analyzed command
  5327. int key_stat, // status of ScanKeyword()
  5328. ccp object // NULL or object for error messages
  5329. // default= 'command'
  5330. )
  5331. {
  5332. DASSERT(key_arg);
  5333. if ( !object || !*object )
  5334. object = "command";
  5335. if ( key_stat <= 0 )
  5336. return PrintCircBuf("Unknown %s: %s",object,key_arg);
  5337. char buf[1000], *dest = buf;
  5338. if (key_tab)
  5339. {
  5340. int n = 0;
  5341. char *buf_end = buf + sizeof(buf) - 2;
  5342. const int arg_len = strlen(key_arg);
  5343. const KeywordTab_t *ct;
  5344. int last_id = -1;
  5345. for ( ct = key_tab; ct->name1 && dest < buf_end; ct++ )
  5346. {
  5347. if ( ct->id != last_id )
  5348. {
  5349. ccp ok = 0;
  5350. if (!strncasecmp(key_arg,ct->name1,arg_len))
  5351. ok = ct->name1;
  5352. else if ( ct->name2 && !strncasecmp(key_arg,ct->name2,arg_len))
  5353. ok = ct->name2;
  5354. if (ok)
  5355. {
  5356. if (!n++)
  5357. {
  5358. *dest++ = ' ';
  5359. *dest++ = '[';
  5360. }
  5361. else if ( n > 5 )
  5362. {
  5363. dest = StringCopyE(dest,buf_end,",...");
  5364. break;
  5365. }
  5366. else
  5367. *dest++ = ',';
  5368. dest = StringCopyE(dest,buf_end,ok);
  5369. last_id = ct->id;
  5370. }
  5371. }
  5372. }
  5373. if ( dest > buf+1 )
  5374. *dest++ = ']';
  5375. else
  5376. dest = buf;
  5377. }
  5378. *dest = 0;
  5379. return PrintCircBuf("%c%s abbreviation is ambiguous: %s%s",
  5380. toupper((int)*object), object+1, key_arg, buf );
  5381. }
  5382. ///////////////////////////////////////////////////////////////////////////////
  5383. enumError PrintKeywordError
  5384. (
  5385. const KeywordTab_t * key_tab, // NULL or pointer to command table
  5386. ccp key_arg, // analyzed command
  5387. int key_stat, // status of ScanKeyword()
  5388. ccp prefix, // NULL or first prefix for messages
  5389. ccp object // NULL or object for error messages
  5390. // default= 'command'
  5391. )
  5392. {
  5393. DASSERT(key_arg);
  5394. if ( !object || !*object )
  5395. object = "command";
  5396. if ( key_stat <= 0 )
  5397. return ERROR0(ERR_SYNTAX,"%sUnknown %s: %s\n",
  5398. prefix ? prefix : "", object, key_arg );
  5399. char buf[1000], *dest = buf;
  5400. if (key_tab)
  5401. {
  5402. int n = 0;
  5403. char *buf_end = buf + sizeof(buf) - 2;
  5404. const int arg_len = strlen(key_arg);
  5405. const KeywordTab_t *ct;
  5406. int last_id = -1;
  5407. for ( ct = key_tab; ct->name1 && dest < buf_end; ct++ )
  5408. {
  5409. if ( ct->id != last_id )
  5410. {
  5411. ccp ok = 0;
  5412. if (!strncasecmp(key_arg,ct->name1,arg_len))
  5413. ok = ct->name1;
  5414. else if ( ct->name2 && !strncasecmp(key_arg,ct->name2,arg_len))
  5415. ok = ct->name2;
  5416. if (ok)
  5417. {
  5418. if (!n++)
  5419. {
  5420. *dest++ = ' ';
  5421. *dest++ = '[';
  5422. }
  5423. else if ( n > 5 )
  5424. {
  5425. dest = StringCopyE(dest,buf_end,",...");
  5426. break;
  5427. }
  5428. else
  5429. *dest++ = ',';
  5430. dest = StringCopyE(dest,buf_end,ok);
  5431. last_id = ct->id;
  5432. }
  5433. }
  5434. }
  5435. if ( dest > buf+1 )
  5436. *dest++ = ']';
  5437. else
  5438. dest = buf;
  5439. }
  5440. *dest = 0;
  5441. return ERROR0(ERR_SYNTAX,"%s%c%s abbreviation is ambiguous: %s%s\n",
  5442. prefix ? prefix : "",
  5443. toupper((int)*object), object+1, key_arg, buf );
  5444. }
  5445. ///////////////////////////////////////////////////////////////////////////////
  5446. char * PrintKeywordList
  5447. (
  5448. // returns a pointer to the result buffer
  5449. char *buf, // result buffer
  5450. // If NULL, a local circulary static buffer
  5451. // with max CIRC_BUF_MAX_ALLOC bytes is used
  5452. uint buf_size, // size of 'buf', at least 10 bytes if buf is set
  5453. uint *ret_length, // not NULL: store result length here
  5454. const KeywordTab_t *tab, // related keyword table
  5455. u64 mode, // mode to print
  5456. u64 default_mode, // NULL or default mode
  5457. u64 hide_mode // bit field to hide parameters
  5458. )
  5459. {
  5460. DASSERT( !buf || buf_size >= 10 );
  5461. char temp[CIRC_BUF_MAX_ALLOC];
  5462. if (!buf)
  5463. {
  5464. buf = temp;
  5465. buf_size = sizeof(temp);
  5466. }
  5467. char *dest = buf;
  5468. char *end = buf + buf_size - 1;
  5469. mode = mode | hide_mode;
  5470. u64 mode1 = mode;
  5471. for ( ; tab->name1 && dest < end; tab++ )
  5472. {
  5473. if ( !tab->id || tab->opt & hide_mode )
  5474. continue;
  5475. if ( tab->opt ? (mode & tab->opt) == tab->id : mode & tab->id )
  5476. {
  5477. if ( dest > buf )
  5478. *dest++ = ',';
  5479. dest = StringCopyE(dest,end,tab->name1);
  5480. mode &= ~(tab->id|tab->opt);
  5481. }
  5482. }
  5483. if ( default_mode && mode1 == (default_mode|hide_mode) )
  5484. dest = StringCopyE(dest,end," (default)");
  5485. else if (!mode1)
  5486. dest = StringCopyE(dest,end,"(none)");
  5487. *dest = 0;
  5488. const uint len = dest - buf;
  5489. if (ret_length)
  5490. *ret_length = len;
  5491. return buf == temp ? CopyCircBuf(temp,len+1) : buf;
  5492. }
  5493. ///////////////////////////////////////////////////////////////////////////////
  5494. int ScanKeywordOffOn
  5495. (
  5496. // returns 0 for '0|OFF'; 1 for '1|ON; -1 for empty; -2 on error
  5497. ccp arg, // argument to scan
  5498. uint max_num, // >0: additionally accept+return number <= max_num
  5499. ccp object // NULL (silent) or object for error messages
  5500. )
  5501. {
  5502. if (!arg||!*arg)
  5503. return -1;
  5504. static const KeywordTab_t keytab[] =
  5505. {
  5506. { 0, "OFF", "0", 0 },
  5507. { 1, "ON", "1", 0 },
  5508. {0,0,0,0}
  5509. };
  5510. int status;
  5511. const KeywordTab_t *key = ScanKeyword(&status,arg,keytab);
  5512. if (key)
  5513. return key->id;
  5514. if ( max_num > 0 )
  5515. {
  5516. char *end;
  5517. const uint num = str2ul(arg,&end,10);
  5518. if ( !*end && num <= max_num )
  5519. return num;
  5520. }
  5521. if (object)
  5522. PrintKeywordError(keytab,arg,status,0,object);
  5523. return -2;
  5524. }
  5525. //
  5526. ///////////////////////////////////////////////////////////////////////////////
  5527. /////////////// OFF/AUTO/ON/FORCE ///////////////
  5528. ///////////////////////////////////////////////////////////////////////////////
  5529. const KeywordTab_t KeyTab_OFF_AUTO_ON[] =
  5530. {
  5531. { OFFON_OFF, "OFF", "-1", 0 },
  5532. { OFFON_OFF, "DISABLED", "NO", 0 },
  5533. { OFFON_AUTO, "AUTO", "0", 0 },
  5534. { OFFON_ON, "ON", "1", 0 },
  5535. { OFFON_ON, "ENABLED", "YES", 0 },
  5536. { OFFON_FORCE, "FORCE", "2", 0 },
  5537. { 0,0,0,0 }
  5538. };
  5539. //-----------------------------------------------------------------------------
  5540. int ScanKeywordOffAutoOnEx
  5541. (
  5542. // returns one of OFFON_*
  5543. const KeywordTab_t *keytab, // Keyword table. If NULL, then use KeyTab_OFF_AUTO_ON[]
  5544. ccp arg, // argument to scan
  5545. int on_empty, // return this value on empty
  5546. uint max_num, // >0: additionally accept+return number <= max_num
  5547. ccp object // NULL (silent) or object for error messages
  5548. )
  5549. {
  5550. if ( !arg || !*arg )
  5551. return on_empty;
  5552. if (!keytab)
  5553. keytab = KeyTab_OFF_AUTO_ON;
  5554. int status;
  5555. const KeywordTab_t *key = ScanKeyword(&status,arg,keytab);
  5556. if (key)
  5557. return key->id;
  5558. if ( max_num > 0 )
  5559. {
  5560. char *end;
  5561. const int num = str2l(arg,&end,10);
  5562. if ( !*end && num >= OFFON_OFF && num <= max_num )
  5563. return num;
  5564. }
  5565. if (object)
  5566. PrintKeywordError(keytab,arg,status,0,object);
  5567. return OFFON_ERROR;
  5568. }
  5569. //-----------------------------------------------------------------------------
  5570. ccp GetKeywordOffAutoOn ( OffOn_t value )
  5571. {
  5572. const KeywordTab_t *key = GetKewordById(KeyTab_OFF_AUTO_ON,value);
  5573. return key ? key->name1 : "?";
  5574. }
  5575. //
  5576. ///////////////////////////////////////////////////////////////////////////////
  5577. /////////////// LOWER/AUTO/UPPER ///////////////
  5578. ///////////////////////////////////////////////////////////////////////////////
  5579. const KeywordTab_t KeyTab_LOWER_AUTO_UPPER[] =
  5580. {
  5581. { LOUP_LOWER, "LOWER", "LOWERCASE", 0 },
  5582. { LOUP_LOWER, "LOCASE", "-1", 0 },
  5583. { LOUP_AUTO, "AUTO", "0", 0 },
  5584. { LOUP_UPPER, "UPPER", "UPPERCASE", 0 },
  5585. { LOUP_UPPER, "UPCASE", "1", 0 },
  5586. { 0,0,0,0 }
  5587. };
  5588. //-----------------------------------------------------------------------------
  5589. int ScanKeywordLowerAutoUpper
  5590. (
  5591. // returns one of LOUP_*
  5592. ccp arg, // argument to scan
  5593. int on_empty, // return this value on empty
  5594. uint max_num, // >0: additionally accept+return number <= max_num
  5595. ccp object // NULL (silent) or object for error messages
  5596. )
  5597. {
  5598. if ( !arg || !*arg )
  5599. return on_empty;
  5600. int status;
  5601. const KeywordTab_t *key = ScanKeyword(&status,arg,KeyTab_LOWER_AUTO_UPPER);
  5602. if (key)
  5603. return key->id;
  5604. if ( max_num > 0 )
  5605. {
  5606. char *end;
  5607. const int num = str2l(arg,&end,10);
  5608. if ( !*end && num >= LOUP_LOWER && num <= max_num )
  5609. return num;
  5610. }
  5611. if (object)
  5612. PrintKeywordError(KeyTab_LOWER_AUTO_UPPER,arg,status,0,object);
  5613. return LOUP_ERROR;
  5614. }
  5615. //-----------------------------------------------------------------------------
  5616. ccp GetKeywordLowerAutoUpper ( LowerUpper_t value )
  5617. {
  5618. const KeywordTab_t *key = GetKewordById(KeyTab_OFF_AUTO_ON,value);
  5619. return key ? key->name1 : "?";
  5620. }
  5621. //
  5622. ///////////////////////////////////////////////////////////////////////////////
  5623. /////////////// scan command lists ///////////////
  5624. ///////////////////////////////////////////////////////////////////////////////
  5625. int ExecCommandOfList ( CommandList_t *cli )
  5626. {
  5627. DASSERT(cli);
  5628. if ( cli->n_bin )
  5629. {
  5630. printf("%3u. %s [n_bin=%u] = |%.*s|\n",
  5631. cli->cmd_count, cli->cmd, cli->n_bin, cli->param_len, cli->param );
  5632. uint i;
  5633. for ( i = 0; i < cli->n_bin; i++ )
  5634. {
  5635. printf(" > binary #%u, len=%u\n",i,cli->bin[0].len);
  5636. HexDump16( stdout,5,0, cli->bin[i].ptr,
  5637. cli->bin[i].len < 0x20 ? cli->bin[i].len : 0x20 );
  5638. }
  5639. }
  5640. else
  5641. printf("%3u. %s = |%.*s|\n",
  5642. cli->cmd_count, cli->cmd, cli->param_len, cli->param );
  5643. return 0;
  5644. }
  5645. ///////////////////////////////////////////////////////////////////////////////
  5646. int ScanCommandList
  5647. (
  5648. // returns -1 on 'cli->fail_count'; otherwise 'cli->cmd_count'
  5649. CommandList_t *cli, // valid command list
  5650. CommandListFunc func // NULL or function for each command
  5651. )
  5652. {
  5653. DASSERT(cli);
  5654. static uint log_pid = 0;
  5655. static uint log_seq = 0;
  5656. static FILE *log = 0;
  5657. if ( cli->log_fname && cli->log_level && !log_pid )
  5658. {
  5659. log_pid = getpid();
  5660. log = fopen(cli->log_fname,"ab");
  5661. if (log)
  5662. {
  5663. fcntl(fileno(log),F_SETFD,FD_CLOEXEC);
  5664. fprintf(log,"\n#\f\n#OPEN %s, pid=%d\n\n",
  5665. PrintTimeByFormat("%F %T %z",time(0)), log_pid );
  5666. }
  5667. }
  5668. uint log_level = log ? cli->log_level : 0;
  5669. cli->read_cmd_len = 0;
  5670. const char sep = cli->command_sep ? cli->command_sep : ';';
  5671. ccp cmd = cli->command, end = cmd + cli->command_len;
  5672. if ( log_level > 0 )
  5673. {
  5674. fprintf(log,"\n++ %u.%u len=%u\n",
  5675. log_pid, ++log_seq, cli->command_len );
  5676. fflush(log);
  5677. }
  5678. for(;;)
  5679. {
  5680. cli->n_bin = 0;
  5681. memset(cli->bin,0,sizeof(cli->bin));
  5682. //--- skip blanks and terminators => find begin of record
  5683. while ( cmd < end && ( (uchar)*cmd <= ' ' || *cmd == sep ))
  5684. cmd++;
  5685. cli->read_cmd_len = cmd - cli->command; // definitley scanned!
  5686. if ( cmd >= end )
  5687. break;
  5688. cli->record = (u8*)cmd;
  5689. //--- find end of command+param
  5690. ccp endcmd = memchr(cmd,sep,end-cmd);
  5691. if (!endcmd)
  5692. {
  5693. if (!cli->is_terminated)
  5694. goto abort;
  5695. endcmd = end;
  5696. }
  5697. //--- scan and copy command
  5698. ccp param = cmd;
  5699. while ( param < endcmd && ( isalnum((int)*param) || *param == '-' || *param == '_' ) )
  5700. param++;
  5701. cli->cmd_len = param - cmd;
  5702. if ( cli->cmd_len > sizeof(cli->cmd)-1 )
  5703. cli->cmd_len = sizeof(cli->cmd)-1;
  5704. if ( log_level > 1 )
  5705. {
  5706. fprintf(log,">%.*s\n",cli->cmd_len,cmd);
  5707. fflush(log);
  5708. }
  5709. if (cli->change_case)
  5710. {
  5711. char *dest = cli->cmd;
  5712. uint count = cli->cmd_len;
  5713. if ( cli->change_case == 1 )
  5714. while ( count-- > 0 )
  5715. *dest++ = tolower((int)*cmd++);
  5716. else
  5717. while ( count-- > 0 )
  5718. *dest++ = toupper((int)*cmd++);
  5719. *dest = 0;
  5720. }
  5721. else
  5722. {
  5723. memcpy(cli->cmd,cmd,cli->cmd_len);
  5724. cli->cmd[cli->cmd_len] = 0;
  5725. }
  5726. //--- scan binary
  5727. while ( cli->n_bin < COMMAND_LIST_N_BIN )
  5728. {
  5729. while ( param < endcmd && ( *param == ' ' || *param == '\t' ))
  5730. param++;
  5731. if ( param == endcmd || *param != '\1' )
  5732. break; // no binary!
  5733. //-- From now on for binary examintation, only 'end' is relevant,
  5734. //-- because binary data may contain the separator character.
  5735. if ( param+3 > end )
  5736. {
  5737. if ( log_level > 1 )
  5738. {
  5739. fprintf(log,"bin incomplete\n");
  5740. fflush(log);
  5741. }
  5742. if (cli->is_terminated)
  5743. {
  5744. // now we have a conflict:
  5745. fprintf(stderr,
  5746. "#WARN: Conflict in ExecCommandOfList():"
  5747. " Stream is terminated, but binary not: %s\n",
  5748. cli->user_ts ? cli->user_ts->info : "" );
  5749. if (log)
  5750. {
  5751. fprintf(log,"#WARN: Conflict: Stream is terminated, but binary not!\n");
  5752. fflush(log);
  5753. }
  5754. }
  5755. goto abort; // incomplete
  5756. }
  5757. const uint bin_len = be16(++param);
  5758. param += 2;
  5759. if ( log_level > 2 )
  5760. {
  5761. fprintf(log,"bin %u,%u..%u/%u%s\n",
  5762. bin_len,
  5763. (uint)(param - cli->command),
  5764. (uint)(param - cli->command + bin_len),
  5765. cli->command_len,
  5766. param + bin_len > end ? " incomplete" : "" );
  5767. fflush(log);
  5768. }
  5769. if ( param + bin_len > end )
  5770. goto abort; // incomplete
  5771. cli->bin[cli->n_bin].ptr = param;
  5772. cli->bin[cli->n_bin].len = bin_len;
  5773. param += bin_len;
  5774. cli->n_bin++;
  5775. //-- rescan 'endcmd' after binary block
  5776. endcmd = memchr(param,sep,end-param);
  5777. if (!endcmd)
  5778. {
  5779. if (!cli->is_terminated)
  5780. goto abort; // incomplete
  5781. endcmd = end;
  5782. }
  5783. }
  5784. //--- calc record length
  5785. cli->input_len = (u8*)endcmd - cli->record;
  5786. if ( endcmd < end )
  5787. cli->input_len++;
  5788. //--- scan param
  5789. while ( param < endcmd && (uchar)*param <= ' ' )
  5790. param++;
  5791. if ( param < endcmd && *param == '=' )
  5792. {
  5793. param++;
  5794. while ( param < endcmd && (uchar)*param <= ' ' )
  5795. param++;
  5796. }
  5797. ccp endparam = endcmd-1;
  5798. while ( endparam > param && (uchar)*endparam <= ' ' )
  5799. endparam--;
  5800. endparam++;
  5801. if ( log_level > 2 && endparam > param )
  5802. {
  5803. const uint plen = endparam - param, max = 25;
  5804. if ( plen <= max )
  5805. fprintf(log,"par %.*s\n",plen,param);
  5806. else
  5807. fprintf(log,"par %.*s…+%u\n",max,param,plen-max);
  5808. fflush(log);
  5809. }
  5810. if (cli->term_param)
  5811. {
  5812. if ( cli->term_param > 1 )
  5813. {
  5814. ((char*)endparam)[0] = sep;
  5815. endparam++;
  5816. }
  5817. else
  5818. ((char*)endparam)[0] = 0;
  5819. }
  5820. cli->param = param;
  5821. cli->param_len = endparam - param;
  5822. cli->record_len = endparam - (ccp)cli->record;
  5823. cli->read_cmd_len = endcmd - (ccp)cli->command;
  5824. cmd = endcmd;
  5825. //--- execute command
  5826. if ( log_level > 3 )
  5827. {
  5828. fprintf(log,"func\n");
  5829. fflush(log);
  5830. const int stat = func(cli);
  5831. fprintf(log,"s=%d\n",stat);
  5832. fflush(log);
  5833. if ( stat < 0 )
  5834. break;
  5835. }
  5836. else if ( func && func(cli) < 0 )
  5837. break;
  5838. cli->cmd_count++;
  5839. }
  5840. abort:;
  5841. if ( log_level > 1 || log && cli->read_cmd_len > cli->command_len )
  5842. {
  5843. fprintf(log,"-- %u,%u/%u%s\n",
  5844. cli->cmd_count,
  5845. cli->read_cmd_len, cli->command_len,
  5846. cli->read_cmd_len > cli->command_len ? " #FAIL!" : "" );
  5847. fflush(log);
  5848. }
  5849. // should never happen
  5850. if ( cli->read_cmd_len > cli->command_len )
  5851. cli->read_cmd_len = cli->command_len;
  5852. return cli->fail_count ? -1 : cli->cmd_count;
  5853. }
  5854. //
  5855. ///////////////////////////////////////////////////////////////////////////////
  5856. /////////////// dynamic data support ///////////////
  5857. ///////////////////////////////////////////////////////////////////////////////
  5858. void ResetDD ( DynData_t *dd )
  5859. {
  5860. if (dd)
  5861. {
  5862. FREE(dd->data);
  5863. dd->data = 0;
  5864. dd->len = dd->size = 0;
  5865. }
  5866. }
  5867. ///////////////////////////////////////////////////////////////////////////////
  5868. void InsertDD ( DynData_t *dd, const void *data, uint data_size )
  5869. {
  5870. DASSERT(dd);
  5871. DASSERT( !dd->data == !dd->size );
  5872. DASSERT( dd->len <= dd->size );
  5873. if ( !data || !data_size )
  5874. dd->len = 0;
  5875. else
  5876. {
  5877. if ( data_size > dd->size )
  5878. {
  5879. FREE(dd->data);
  5880. dd->data = MALLOC(data_size);
  5881. dd->size = data_size;
  5882. }
  5883. memcpy(dd->data,data,data_size);
  5884. dd->len = data_size;
  5885. }
  5886. }
  5887. ///////////////////////////////////////////////////////////////////////////////
  5888. ///////////////////////////////////////////////////////////////////////////////
  5889. void ResetDDL ( DynDataList_t *ddl )
  5890. {
  5891. if (ddl)
  5892. {
  5893. DynData_t *dd = ddl->list;
  5894. DynData_t *end = dd + ddl->used;
  5895. for ( ; dd < end; dd++ )
  5896. FREE(dd->data);
  5897. FREE(ddl->list);
  5898. ddl->list = 0;
  5899. ddl->used = ddl->size = 0;
  5900. }
  5901. }
  5902. ///////////////////////////////////////////////////////////////////////////////
  5903. DynData_t *InsertDDL
  5904. (
  5905. DynDataList_t *ddl, // valid dynamic data list
  5906. uint index, // element index to change
  5907. const void *data, // NULL or data to assign
  5908. uint data_size // size of data
  5909. )
  5910. {
  5911. DASSERT(ddl);
  5912. DASSERT( !ddl->list == !ddl->size );
  5913. DASSERT( ddl->used <= ddl->size );
  5914. if ( index >= ddl->size )
  5915. {
  5916. const uint new_size = 11 * index / 10 + 10;
  5917. ddl->list = REALLOC( ddl->list, sizeof(*ddl->list) * new_size );
  5918. memset( ddl->list + ddl->size, 0, (new_size - ddl->size) * sizeof(*ddl->list) );
  5919. ddl->size = new_size;
  5920. }
  5921. if ( ddl->used <= index )
  5922. {
  5923. uint idx;
  5924. for ( idx = ddl->used; idx < index; idx++ )
  5925. ddl->list[idx].len = 0;
  5926. ddl->used = index+1;
  5927. }
  5928. DynData_t *dd = ddl->list + index;
  5929. InsertDD(dd,data,data_size);
  5930. return dd;
  5931. }
  5932. ///////////////////////////////////////////////////////////////////////////////
  5933. DynData_t *GetDDL
  5934. (
  5935. DynDataList_t *ddl, // valid dynamic data list
  5936. uint index, // element index to get
  5937. uint create // create an empty element if not exist
  5938. )
  5939. {
  5940. DASSERT(ddl);
  5941. DASSERT( !ddl->list == !ddl->size );
  5942. DASSERT( ddl->used <= ddl->size );
  5943. return index < ddl->used
  5944. ? ddl->list + ddl->used
  5945. : create
  5946. ? InsertDDL(ddl, index >= create ? index : create-1, 0,0)
  5947. : 0;
  5948. }
  5949. //
  5950. ///////////////////////////////////////////////////////////////////////////////
  5951. /////////////// StringField_t ///////////////
  5952. ///////////////////////////////////////////////////////////////////////////////
  5953. void ResetStringField ( StringField_t * sf )
  5954. {
  5955. DASSERT(sf);
  5956. if (sf)
  5957. {
  5958. if ( sf->used > 0 )
  5959. {
  5960. DASSERT(sf->field);
  5961. ccp *ptr = sf->field, *end;
  5962. for ( end = ptr + sf->used; ptr < end; ptr++ )
  5963. FreeString(*ptr);
  5964. }
  5965. FREE(sf->field);
  5966. int (*func_cmp)( ccp s1, ccp s2 ) = sf->func_cmp;
  5967. InitializeStringField(sf);
  5968. sf->func_cmp = func_cmp;
  5969. }
  5970. }
  5971. ///////////////////////////////////////////////////////////////////////////////
  5972. void MoveStringField ( StringField_t * dest, StringField_t * src )
  5973. {
  5974. DASSERT(src);
  5975. DASSERT(dest);
  5976. if ( src != dest )
  5977. {
  5978. ResetStringField(dest);
  5979. dest->field = src->field;
  5980. dest->used = src->used;
  5981. dest->size = src->size;
  5982. dest->func_cmp = src->func_cmp;
  5983. InitializeStringField(src);
  5984. src->func_cmp = dest->func_cmp;
  5985. }
  5986. }
  5987. ///////////////////////////////////////////////////////////////////////////////
  5988. int FindStringFieldIndex ( const StringField_t * sf, ccp key, int not_found_value )
  5989. {
  5990. bool found;
  5991. const int idx = FindStringFieldHelper(sf,&found,key);
  5992. return found ? idx : not_found_value;
  5993. }
  5994. ///////////////////////////////////////////////////////////////////////////////
  5995. ccp FindStringField ( const StringField_t * sf, ccp key )
  5996. {
  5997. bool found;
  5998. const int idx = FindStringFieldHelper(sf,&found,key);
  5999. return found ? sf->field[idx] : 0;
  6000. }
  6001. ///////////////////////////////////////////////////////////////////////////////
  6002. ccp * InsertStringFieldHelper ( StringField_t * sf, int idx )
  6003. {
  6004. DASSERT(sf);
  6005. DASSERT( sf->used <= sf->size );
  6006. noPRINT("+SF: %u/%u/%u\n",idx,sf->used,sf->size);
  6007. if ( sf->used == sf->size )
  6008. {
  6009. sf->size += 0x100;
  6010. sf->field = REALLOC(sf->field,sf->size*sizeof(*sf->field));
  6011. }
  6012. DASSERT( idx <= sf->used );
  6013. ccp * dest = sf->field + idx;
  6014. memmove(dest+1,dest,(sf->used-idx)*sizeof(*dest));
  6015. sf->used++;
  6016. return dest;
  6017. }
  6018. ///////////////////////////////////////////////////////////////////////////////
  6019. bool InsertStringField ( StringField_t * sf, ccp key, bool move_key )
  6020. {
  6021. if (!key)
  6022. return 0;
  6023. bool found;
  6024. int idx = FindStringFieldHelper(sf,&found,key);
  6025. if (found)
  6026. {
  6027. if (move_key)
  6028. FreeString(key);
  6029. }
  6030. else
  6031. {
  6032. ccp * dest = InsertStringFieldHelper(sf,idx);
  6033. *dest = move_key ? key : STRDUP(key);
  6034. }
  6035. return !found;
  6036. }
  6037. ///////////////////////////////////////////////////////////////////////////////
  6038. bool RemoveStringField ( StringField_t * sf, ccp key )
  6039. {
  6040. bool found;
  6041. uint idx = FindStringFieldHelper(sf,&found,key);
  6042. if (found)
  6043. {
  6044. sf->used--;
  6045. ASSERT( idx <= sf->used );
  6046. ccp * dest = sf->field + idx;
  6047. FreeString(*dest);
  6048. memmove(dest,dest+1,(sf->used-idx)*sizeof(*dest));
  6049. }
  6050. return found;
  6051. }
  6052. ///////////////////////////////////////////////////////////////////////////////
  6053. uint RemoveStringFieldByIndex ( StringField_t * sf, int index, int n )
  6054. {
  6055. DASSERT(sf);
  6056. if ( index < 0 )
  6057. index += sf->used;
  6058. if ( n < 0 )
  6059. {
  6060. index += n;
  6061. n -= n;
  6062. }
  6063. if ( index < 0 )
  6064. index = 0;
  6065. int last = index + n;
  6066. if ( last > sf->used )
  6067. last = sf->used;
  6068. if ( index >= last )
  6069. return 0;
  6070. ccp * src = sf->field + index;
  6071. ccp * end = sf->field + last;
  6072. while ( src < end )
  6073. FreeString(*src++);
  6074. memmove( sf->field + index, src, ( sf->used - last) * sizeof(*sf->field) );
  6075. const uint rm = last - index;
  6076. sf->used -= rm;
  6077. return rm;
  6078. }
  6079. ///////////////////////////////////////////////////////////////////////////////
  6080. void AppendStringField ( StringField_t * sf, ccp key, bool move_key )
  6081. {
  6082. DASSERT(sf);
  6083. if (key)
  6084. {
  6085. DASSERT( sf->used <= sf->size );
  6086. noPRINT(">SF: %u/%u\n",sf->used,sf->size);
  6087. if ( sf->used == sf->size )
  6088. {
  6089. sf->size += 0x100;
  6090. sf->field = REALLOC(sf->field,sf->size*sizeof(*sf->field));
  6091. }
  6092. TRACE("AppendStringField(%s,%d) %d/%d\n",key,move_key,sf->used,sf->size);
  6093. ccp *dest = sf->field + sf->used++;
  6094. *dest = move_key ? key : STRDUP(key);
  6095. }
  6096. }
  6097. ///////////////////////////////////////////////////////////////////////////////
  6098. void AppendUniqueStringField ( StringField_t * sf, ccp key, bool move_key )
  6099. {
  6100. DASSERT(sf);
  6101. if (!key)
  6102. return;
  6103. ccp * src = sf->field;
  6104. ccp * end = src + sf->used;
  6105. while ( src < end )
  6106. if (!strcmp(*src++,key))
  6107. {
  6108. if (move_key)
  6109. FreeString(key);
  6110. return;
  6111. }
  6112. AppendStringField(sf,key,move_key);
  6113. }
  6114. ///////////////////////////////////////////////////////////////////////////////
  6115. void SortStringField ( StringField_t * sf )
  6116. {
  6117. DASSERT(sf);
  6118. if ( sf->used > 1 )
  6119. {
  6120. StringField_t temp;
  6121. InitializeStringField(&temp);
  6122. temp.func_cmp = sf->func_cmp;
  6123. uint i;
  6124. for ( i = 0; i < sf->used; i++ )
  6125. InsertStringField(&temp,sf->field[i],true);
  6126. sf->used = 0;
  6127. MoveStringField(sf,&temp);
  6128. }
  6129. }
  6130. ///////////////////////////////////////////////////////////////////////////////
  6131. uint FindStringFieldHelper ( const StringField_t * sf, bool * p_found, ccp key )
  6132. {
  6133. DASSERT(sf);
  6134. int (*cmp)( ccp s1, ccp s2 ) = sf->func_cmp ? sf->func_cmp : strcmp;
  6135. int beg = 0;
  6136. if ( sf && key )
  6137. {
  6138. int end = sf->used - 1;
  6139. while ( beg <= end )
  6140. {
  6141. const uint idx = (beg+end)/2;
  6142. const int stat = cmp(key,sf->field[idx]);
  6143. if ( stat < 0 )
  6144. end = idx - 1;
  6145. else if ( stat > 0 )
  6146. beg = idx + 1;
  6147. else
  6148. {
  6149. noTRACE("FindStringFieldHelper(%s) FOUND=%d/%d/%d\n",
  6150. key, idx, sf->used, sf->size );
  6151. if (p_found)
  6152. *p_found = true;
  6153. return idx;
  6154. }
  6155. }
  6156. }
  6157. noTRACE("FindStringFieldHelper(%s) failed=%d/%d/%d\n",
  6158. key, beg, sf->used, sf->size );
  6159. if (p_found)
  6160. *p_found = false;
  6161. return beg;
  6162. }
  6163. ///////////////////////////////////////////////////////////////////////////////
  6164. ///////////////////////////////////////////////////////////////////////////////
  6165. enumError LoadStringField
  6166. (
  6167. StringField_t * sf, // string field
  6168. bool init_sf, // true: initialize 'sf' first
  6169. bool sort, // true: sort 'sf'
  6170. ccp filename, // filename of source file
  6171. bool silent // true: don't print open/read errors
  6172. )
  6173. {
  6174. ASSERT(sf);
  6175. DASSERT(filename);
  6176. DASSERT(*filename);
  6177. TRACE("LoadStringField(%p,%d,%d,%s,%d)\n",sf,init_sf,sort,filename,silent);
  6178. if (init_sf)
  6179. InitializeStringField(sf);
  6180. FILE * f = fopen(filename,"rb");
  6181. if (!f)
  6182. {
  6183. if (!silent)
  6184. ERROR1(ERR_CANT_OPEN,"Can't open file: %s\n",filename);
  6185. return ERR_CANT_OPEN;
  6186. }
  6187. char iobuf[10000];
  6188. while (fgets(iobuf,sizeof(iobuf)-1,f))
  6189. {
  6190. char *ptr = iobuf;
  6191. while (*ptr)
  6192. ptr++;
  6193. if ( ptr > iobuf && ptr[-1] == '\n' )
  6194. {
  6195. ptr--;
  6196. if ( ptr > iobuf && ptr[-1] == '\r' )
  6197. ptr--;
  6198. }
  6199. if ( ptr > iobuf )
  6200. {
  6201. *ptr++ = 0;
  6202. const size_t len = ptr-iobuf;
  6203. ptr = MALLOC(len);
  6204. memcpy(ptr,iobuf,len);
  6205. if (sort)
  6206. InsertStringField(sf,ptr,true);
  6207. else
  6208. AppendStringField(sf,ptr,true);
  6209. }
  6210. }
  6211. fclose(f);
  6212. return ERR_OK;
  6213. }
  6214. ///////////////////////////////////////////////////////////////////////////////
  6215. enumError SaveStringField
  6216. (
  6217. StringField_t * sf, // valid string field
  6218. ccp filename, // filename of dest file
  6219. bool rm_if_empty // true: rm dest file if 'sf' is empty
  6220. )
  6221. {
  6222. ASSERT(sf);
  6223. ASSERT(filename);
  6224. ASSERT(*filename);
  6225. TRACE("SaveStringField(%p,%s,%d)\n",sf,filename,rm_if_empty);
  6226. if ( !sf->used && rm_if_empty )
  6227. {
  6228. unlink(filename);
  6229. return ERR_OK;
  6230. }
  6231. FILE * f = fopen(filename,"wb");
  6232. if (!f)
  6233. return ERROR1(ERR_CANT_CREATE,"Can't create file: %s\n",filename);
  6234. enumError err = WriteStringField(f,filename,sf,0,0);
  6235. fclose(f);
  6236. return err;
  6237. }
  6238. ///////////////////////////////////////////////////////////////////////////////
  6239. enumError WriteStringField
  6240. (
  6241. FILE * f, // open destination file
  6242. ccp filename, // NULL or filename (needed on write error)
  6243. StringField_t * sf, // valid string field
  6244. ccp prefix, // not NULL: insert prefix before each line
  6245. ccp eol // end of line text (if NULL: use LF)
  6246. )
  6247. {
  6248. if (!prefix)
  6249. prefix = "";
  6250. if (!eol)
  6251. eol = "\n";
  6252. ccp *ptr = sf->field, *end;
  6253. for ( end = ptr + sf->used; ptr < end; ptr++ )
  6254. if ( fprintf(f,"%s%s%s",prefix,*ptr,eol) < 0 )
  6255. return ERROR1(ERR_WRITE_FAILED,
  6256. "Error while writing string list: %s\n",
  6257. filename ? filename : "?" );
  6258. return ERR_OK;
  6259. }
  6260. ///////////////////////////////////////////////////////////////////////////////
  6261. ///////////////////////////////////////////////////////////////////////////////
  6262. void SaveCurrentStateStringField
  6263. (
  6264. FILE *f, // output file
  6265. ccp name_prefix, // NULL or prefix of name, up to 40 chars
  6266. uint tab_pos, // tab pos of '='
  6267. const StringField_t *sf, // valid string field
  6268. EncodeMode_t emode // encoding mode
  6269. )
  6270. {
  6271. DASSERT(f);
  6272. DASSERT(sf);
  6273. if (!name_prefix)
  6274. name_prefix = EmptyString;
  6275. int base = 8*tab_pos + 7 - strlen(name_prefix);
  6276. fprintf(f,"%sn%.*s= %u\n", name_prefix, (base-1)/8, Tabs20, sf->used );
  6277. char buf[5000], name[10];
  6278. uint i;
  6279. for ( i = 0; i < sf->used; i++ )
  6280. {
  6281. const uint len = snprintf(name,sizeof(name),"%u",i);
  6282. mem_t mem = EncodeByModeMem(buf,sizeof(buf),sf->field[i],-1,emode);
  6283. fprintf(f, "%s%s%.*s= %s\n",
  6284. name_prefix, name, (base-len)/8, Tabs20, mem.ptr );
  6285. if ( mem.ptr != buf )
  6286. FreeMem(&mem);
  6287. }
  6288. }
  6289. ///////////////////////////////////////////////////////////////////////////////
  6290. void RestoreStateStringField
  6291. (
  6292. RestoreState_t *rs, // info data, may be modified
  6293. ccp name_prefix, // NULL or prefix of name, up to 40 chars
  6294. StringField_t *sf, // string field
  6295. bool init_sf, // true: initialize 'sf', otherwise reset
  6296. EncodeMode_t emode // encoding mode
  6297. )
  6298. {
  6299. DASSERT(rs);
  6300. DASSERT(sf);
  6301. if (init_sf)
  6302. InitializeStringField(sf);
  6303. else
  6304. ResetStringField(sf);
  6305. if (!name_prefix)
  6306. name_prefix = EmptyString;
  6307. char name[50];
  6308. snprintf(name,sizeof(name),"%sn",name_prefix);
  6309. int n = GetParamFieldINT(rs,name,0);
  6310. PRINT("RestoreStateStringField(), N=%d\n",n);
  6311. if ( n > 0 )
  6312. {
  6313. sf->size = n;
  6314. sf->field = MALLOC(sf->size*sizeof(*sf->field));
  6315. uint i;
  6316. for ( i = 0; i < n; i++ )
  6317. {
  6318. snprintf(name,sizeof(name),"%s%u",name_prefix,i);
  6319. ParamFieldItem_t *pfi = GetParamField(rs,name);
  6320. if (pfi)
  6321. {
  6322. mem_t mem = DecodeByModeMem(0,0,pfi->data,-1,emode,0);
  6323. AppendStringField(sf,mem.ptr,true);
  6324. }
  6325. }
  6326. }
  6327. }
  6328. //
  6329. ///////////////////////////////////////////////////////////////////////////////
  6330. /////////////// ParamField_t ///////////////
  6331. ///////////////////////////////////////////////////////////////////////////////
  6332. #undef PARAM_FIELD_GROW
  6333. #define PARAM_FIELD_GROW(s) (s)/4+100
  6334. ///////////////////////////////////////////////////////////////////////////////
  6335. void ResetParamField ( ParamField_t * pf )
  6336. {
  6337. DASSERT(pf);
  6338. if (pf)
  6339. {
  6340. if ( pf->used > 0 )
  6341. {
  6342. DASSERT(pf->field);
  6343. ParamFieldItem_t *ptr = pf->field, *end;
  6344. for ( end = ptr + pf->used; ptr < end; ptr++ )
  6345. {
  6346. FreeString(ptr->key);
  6347. if (pf->free_data)
  6348. FREE(ptr->data);
  6349. }
  6350. }
  6351. FREE(pf->field);
  6352. const bool free_data = pf->free_data;
  6353. int (*func_cmp)( ccp s1, ccp s2 ) = pf->func_cmp;
  6354. InitializeParamField(pf);
  6355. pf->free_data = free_data;
  6356. pf->func_cmp = func_cmp;
  6357. }
  6358. }
  6359. ///////////////////////////////////////////////////////////////////////////////
  6360. void MoveParamField ( ParamField_t * dest, ParamField_t * src )
  6361. {
  6362. DASSERT(src);
  6363. DASSERT(dest);
  6364. if ( src != dest )
  6365. {
  6366. ResetParamField(dest);
  6367. dest->field = src->field;
  6368. dest->used = src->used;
  6369. dest->size = src->size;
  6370. dest->free_data = src->free_data;
  6371. InitializeParamField(src);
  6372. src->free_data = dest->free_data;
  6373. }
  6374. }
  6375. ///////////////////////////////////////////////////////////////////////////////
  6376. int FindParamFieldIndex ( const ParamField_t * pf, ccp key, int not_found_value )
  6377. {
  6378. bool found;
  6379. const int idx = FindParamFieldHelper(pf,&found,key);
  6380. return found ? idx : not_found_value;
  6381. }
  6382. ///////////////////////////////////////////////////////////////////////////////
  6383. ParamFieldItem_t * FindParamField ( const ParamField_t * pf, ccp key )
  6384. {
  6385. bool found;
  6386. const int idx = FindParamFieldHelper(pf,&found,key);
  6387. return found ? pf->field + idx : 0;
  6388. }
  6389. ///////////////////////////////////////////////////////////////////////////////
  6390. ParamFieldItem_t * FindParamFieldByNum ( const ParamField_t * pf, uint num )
  6391. {
  6392. DASSERT(pf);
  6393. noTRACE("FindParamFieldByNum(%x)\n",num);
  6394. ParamFieldItem_t *ptr = pf->field, *end;
  6395. for ( end = ptr + pf->used; ptr < end; ptr++ )
  6396. if ( ptr->num == num )
  6397. return ptr;
  6398. return 0;
  6399. }
  6400. ///////////////////////////////////////////////////////////////////////////////
  6401. static ParamFieldItem_t * InsertParamFieldHelper ( ParamField_t * pf, int idx )
  6402. {
  6403. DASSERT(pf);
  6404. DASSERT( pf->used <= pf->size );
  6405. noPRINT("+SF: %u/%u/%u\n",idx,pf->used,pf->size);
  6406. if ( pf->used == pf->size )
  6407. {
  6408. pf->size += PARAM_FIELD_GROW(pf->size);
  6409. pf->field = REALLOC(pf->field,pf->size*sizeof(*pf->field));
  6410. }
  6411. DASSERT( idx <= pf->used );
  6412. ParamFieldItem_t * dest = pf->field + idx;
  6413. memmove(dest+1,dest,(pf->used-idx)*sizeof(*dest));
  6414. pf->used++;
  6415. return dest;
  6416. }
  6417. ///////////////////////////////////////////////////////////////////////////////
  6418. ParamFieldItem_t * FindInsertParamField
  6419. ( ParamField_t * pf, ccp key, bool move_key, uint num, bool *old_found )
  6420. {
  6421. if (!key)
  6422. return 0;
  6423. bool found;
  6424. int idx = FindParamFieldHelper(pf,&found,key);
  6425. ParamFieldItem_t *item;
  6426. if (found)
  6427. {
  6428. if (move_key)
  6429. FreeString(key);
  6430. item = pf->field + idx;
  6431. }
  6432. else
  6433. {
  6434. item = InsertParamFieldHelper(pf,idx);
  6435. item->key = move_key ? key : STRDUP(key);
  6436. item->num = num;
  6437. item->data = 0;
  6438. }
  6439. if (old_found)
  6440. *old_found = found;
  6441. return item;
  6442. }
  6443. ///////////////////////////////////////////////////////////////////////////////
  6444. ParamFieldItem_t * IncrementParamField ( ParamField_t * pf, ccp key, bool move_key )
  6445. {
  6446. ParamFieldItem_t *item = FindInsertParamField(pf,key,move_key,0,0);
  6447. if (item)
  6448. item->num++;
  6449. return item;
  6450. }
  6451. ///////////////////////////////////////////////////////////////////////////////
  6452. bool InsertParamField
  6453. ( ParamField_t * pf, ccp key, bool move_key, uint num, cvp data )
  6454. {
  6455. if (!key)
  6456. return 0;
  6457. noTRACE("InsertParamField(%s,%x)\n",key,num);
  6458. bool found;
  6459. int idx = FindParamFieldHelper(pf,&found,key);
  6460. if (found)
  6461. {
  6462. if (move_key)
  6463. FreeString(key);
  6464. if (pf->free_data)
  6465. FREE((void*)data);
  6466. }
  6467. else
  6468. {
  6469. ParamFieldItem_t * dest = InsertParamFieldHelper(pf,idx);
  6470. dest->key = move_key ? key : STRDUP(key);
  6471. dest->num = num;
  6472. dest->data = (void*)data;
  6473. }
  6474. return !found;
  6475. }
  6476. ///////////////////////////////////////////////////////////////////////////////
  6477. bool ReplaceParamField
  6478. ( ParamField_t * pf, ccp key, bool move_key, uint num, cvp data )
  6479. {
  6480. if (!key)
  6481. return 0;
  6482. noTRACE("InsertParamField(%s,%x)\n",key,num);
  6483. bool found;
  6484. int idx = FindParamFieldHelper(pf,&found,key);
  6485. if (found)
  6486. {
  6487. if (move_key)
  6488. FreeString(key);
  6489. ParamFieldItem_t * dest = pf->field + idx;
  6490. dest->num = num;
  6491. FREE(dest->data);
  6492. dest->data = (void*)data;
  6493. }
  6494. else
  6495. {
  6496. ParamFieldItem_t * dest = InsertParamFieldHelper(pf,idx);
  6497. dest->key = move_key ? key : STRDUP(key);
  6498. dest->num = num;
  6499. dest->data = (void*)data;
  6500. }
  6501. return !found;
  6502. }
  6503. ///////////////////////////////////////////////////////////////////////////////
  6504. bool RemoveParamField ( ParamField_t * pf, ccp key )
  6505. {
  6506. bool found;
  6507. uint idx = FindParamFieldHelper(pf,&found,key);
  6508. if (found)
  6509. {
  6510. pf->used--;
  6511. ASSERT( idx <= pf->used );
  6512. ParamFieldItem_t * dest = pf->field + idx;
  6513. FreeString(dest->key);
  6514. if (pf->free_data)
  6515. FREE(dest->data);
  6516. memmove(dest,dest+1,(pf->used-idx)*sizeof(*dest));
  6517. }
  6518. return found;
  6519. }
  6520. ///////////////////////////////////////////////////////////////////////////////
  6521. ParamFieldItem_t * AppendParamField
  6522. ( ParamField_t * pf, ccp key, bool move_key, uint num, cvp data )
  6523. {
  6524. DASSERT(pf);
  6525. if (key)
  6526. {
  6527. DASSERT( pf->used <= pf->size );
  6528. noPRINT(">SF: %u/%u\n",pf->used,pf->size);
  6529. if ( pf->used == pf->size )
  6530. {
  6531. pf->size += PARAM_FIELD_GROW(pf->size);
  6532. pf->field = REALLOC(pf->field,pf->size*sizeof(*pf->field));
  6533. }
  6534. TRACE("AppendParamField(%s,%d) %d/%d\n",key,move_key,pf->used,pf->size);
  6535. ParamFieldItem_t * dest = pf->field + pf->used++;
  6536. dest->key = move_key ? key : STRDUP(key);
  6537. dest->num = num;
  6538. dest->data = (void*)data;
  6539. return dest;
  6540. }
  6541. if (pf->free_data)
  6542. FREE((void*)data);
  6543. return 0;
  6544. }
  6545. ///////////////////////////////////////////////////////////////////////////////
  6546. uint FindParamFieldHelper ( const ParamField_t * pf, bool * p_found, ccp key )
  6547. {
  6548. DASSERT(pf);
  6549. int (*cmp)( ccp s1, ccp s2 ) = pf->func_cmp ? pf->func_cmp : strcmp;
  6550. int beg = 0;
  6551. if ( pf && key )
  6552. {
  6553. int end = pf->used - 1;
  6554. while ( beg <= end )
  6555. {
  6556. uint idx = (beg+end)/2;
  6557. int stat = cmp(key,pf->field[idx].key);
  6558. if ( stat < 0 )
  6559. end = idx - 1 ;
  6560. else if ( stat > 0 )
  6561. beg = idx + 1;
  6562. else
  6563. {
  6564. noTRACE("FindParamFieldHelper(%s) FOUND=%d/%d/%d\n",
  6565. key, idx, pf->used, pf->size );
  6566. if (p_found)
  6567. *p_found = true;
  6568. return idx;
  6569. }
  6570. }
  6571. }
  6572. noTRACE("FindParamFieldHelper(%s) failed=%d/%d/%d\n",
  6573. key, beg, pf->used, pf->size );
  6574. if (p_found)
  6575. *p_found = false;
  6576. return beg;
  6577. }
  6578. ///////////////////////////////////////////////////////////////////////////////
  6579. ///////////////////////////////////////////////////////////////////////////////
  6580. ccp GetParamFieldStr ( ParamField_t *pf, uint mark, ccp key, ccp def )
  6581. {
  6582. DASSERT(pf);
  6583. DASSERT(key);
  6584. ParamFieldItem_t *it = FindParamField(pf,key);
  6585. if ( it && it->data )
  6586. {
  6587. it->num |= mark;
  6588. return (ccp)it->data;
  6589. }
  6590. return def;
  6591. }
  6592. ///////////////////////////////////////////////////////////////////////////////
  6593. int GetParamFieldInt ( ParamField_t *pf, uint mark, ccp key, int def )
  6594. {
  6595. DASSERT(pf);
  6596. DASSERT(key);
  6597. ParamFieldItem_t *it = FindParamField(pf,key);
  6598. if ( it && it->data )
  6599. {
  6600. it->num |= mark;
  6601. char *end;
  6602. const int num = str2l((ccp)it->data,&end,10);
  6603. if (!*end)
  6604. return num;
  6605. }
  6606. return def;
  6607. }
  6608. ///////////////////////////////////////////////////////////////////////////////
  6609. int GetParamFieldIntMM
  6610. ( ParamField_t *pf, uint mark, ccp key, int def, int min, int max )
  6611. {
  6612. const int num = GetParamFieldInt(pf,mark,key,def);
  6613. return num >= min && num <= max ? num : def;
  6614. }
  6615. //
  6616. ///////////////////////////////////////////////////////////////////////////////
  6617. /////////////// exmem_list_t ///////////////
  6618. ///////////////////////////////////////////////////////////////////////////////
  6619. #undef EXMEM_LIST_GROW
  6620. #define EXMEM_LIST_GROW(s) (s)/2+50
  6621. //-----------------------------------------------------------------------------
  6622. void ResetEML ( exmem_list_t * eml )
  6623. {
  6624. if (eml)
  6625. {
  6626. if ( eml->used > 0 )
  6627. {
  6628. DASSERT(eml->list);
  6629. exmem_key_t *ptr = eml->list, *end;
  6630. for ( end = ptr + eml->used; ptr < end; ptr++ )
  6631. {
  6632. if (ptr->data.is_key_alloced)
  6633. FreeString(ptr->key);
  6634. if (ptr->data.is_alloced)
  6635. FreeString(ptr->data.data.ptr);
  6636. }
  6637. }
  6638. FREE(eml->list);
  6639. int (*func_cmp)( ccp s1, ccp s2 ) = eml->func_cmp;
  6640. InitializeEML(eml);
  6641. eml->func_cmp = func_cmp;
  6642. }
  6643. }
  6644. ///////////////////////////////////////////////////////////////////////////////
  6645. void MoveEML ( exmem_list_t * dest, exmem_list_t * src )
  6646. {
  6647. DASSERT(dest);
  6648. if ( src != dest )
  6649. {
  6650. ResetEML(dest);
  6651. if (src)
  6652. {
  6653. *dest = *src;
  6654. InitializeEML(src);
  6655. }
  6656. }
  6657. }
  6658. ///////////////////////////////////////////////////////////////////////////////
  6659. uint FindHelperEML ( const exmem_list_t * eml, ccp key, bool * p_found )
  6660. {
  6661. DASSERT(eml);
  6662. int (*cmp)( ccp s1, ccp s2 ) = eml->func_cmp ? eml->func_cmp : strcmp;
  6663. if ( eml->is_unsorted )
  6664. {
  6665. uint i;
  6666. exmem_key_t *ptr = eml->list;
  6667. for ( i = 0; i < eml->used; i++, ptr++ )
  6668. if (!cmp(key,ptr->key))
  6669. {
  6670. if (p_found)
  6671. *p_found = true;
  6672. return i;
  6673. }
  6674. if (p_found)
  6675. *p_found = false;
  6676. return eml->used;
  6677. }
  6678. int beg = 0;
  6679. if (key)
  6680. {
  6681. int end = eml->used - 1;
  6682. while ( beg <= end )
  6683. {
  6684. const uint idx = (beg+end)/2;
  6685. const int stat = cmp(key,eml->list[idx].key);
  6686. if ( stat < 0 )
  6687. end = idx - 1 ;
  6688. else if ( stat > 0 )
  6689. beg = idx + 1;
  6690. else
  6691. {
  6692. noTRACE("FindHelperEML(%s) FOUND=%d/%d/%d\n",
  6693. key, idx, eml->used, eml->size );
  6694. if (p_found)
  6695. *p_found = true;
  6696. return idx;
  6697. }
  6698. }
  6699. }
  6700. noTRACE("FindHelperEML(%s) failed=%d/%d/%d\n",
  6701. key, beg, eml->used, eml->size );
  6702. if (p_found)
  6703. *p_found = false;
  6704. return beg;
  6705. }
  6706. ///////////////////////////////////////////////////////////////////////////////
  6707. int FindIndexEML ( const exmem_list_t * eml, ccp key, int not_found_value )
  6708. {
  6709. bool found;
  6710. const int idx = FindHelperEML(eml,key,&found);
  6711. return found ? idx : not_found_value;
  6712. }
  6713. ///////////////////////////////////////////////////////////////////////////////
  6714. exmem_key_t * FindEML ( const exmem_list_t * eml, ccp key )
  6715. {
  6716. bool found;
  6717. const int idx = FindHelperEML(eml,key,&found);
  6718. return found ? eml->list + idx : 0;
  6719. }
  6720. ///////////////////////////////////////////////////////////////////////////////
  6721. exmem_key_t * FindAttribEML ( const exmem_list_t * eml, u32 attrib )
  6722. {
  6723. DASSERT(eml);
  6724. noTRACE("FindAttribEML(%x)\n",attrib);
  6725. exmem_key_t *ptr = eml->list, *end;
  6726. for ( end = ptr + eml->used; ptr < end; ptr++ )
  6727. if ( ptr->data.attrib == attrib )
  6728. return ptr;
  6729. return 0;
  6730. }
  6731. ///////////////////////////////////////////////////////////////////////////////
  6732. static exmem_key_t * InsertHelperEML
  6733. ( exmem_list_t * eml, int idx,
  6734. ccp key, CopyMode_t cm_key,
  6735. const exmem_t *data, CopyMode_t cm_data )
  6736. {
  6737. DASSERT(eml);
  6738. DASSERT( eml->used <= eml->size );
  6739. noPRINT("+SF: %u/%u/%u\n",idx,eml->used,eml->size);
  6740. if ( eml->used == eml->size )
  6741. {
  6742. eml->size += EXMEM_LIST_GROW(eml->size);
  6743. eml->list = REALLOC(eml->list,eml->size*sizeof(*eml->list));
  6744. }
  6745. DASSERT( idx <= eml->used );
  6746. exmem_key_t * dest = eml->list + idx;
  6747. memmove(dest+1,dest,(eml->used-idx)*sizeof(*dest));
  6748. eml->used++;
  6749. dest->data = CopyExMem(data,cm_data);
  6750. dest->key = cm_key == CPM_COPY ? STRDUP(key) : key;
  6751. dest->data.is_key_alloced = cm_key != CPM_LINK;
  6752. return dest;
  6753. }
  6754. ///////////////////////////////////////////////////////////////////////////////
  6755. exmem_key_t * FindInsertEML
  6756. ( exmem_list_t * eml, ccp key, CopyMode_t cm_key, bool *old_found )
  6757. {
  6758. if (!key)
  6759. return 0;
  6760. bool found;
  6761. int idx = FindHelperEML(eml,key,&found);
  6762. exmem_key_t *item;
  6763. if (found)
  6764. {
  6765. if ( cm_key == CPM_MOVE )
  6766. FreeString(key);
  6767. item = eml->list + idx;
  6768. }
  6769. else
  6770. item = InsertHelperEML(eml,idx,key,cm_key,0,0);
  6771. if (old_found)
  6772. *old_found = found;
  6773. return item;
  6774. }
  6775. ///////////////////////////////////////////////////////////////////////////////
  6776. bool InsertEML ( exmem_list_t * eml, ccp key, CopyMode_t cm_key,
  6777. const exmem_t *data, CopyMode_t cm_data )
  6778. {
  6779. DASSERT(eml);
  6780. if (!key)
  6781. {
  6782. FreeExMemCM(data,cm_data);
  6783. return 0;
  6784. }
  6785. bool found;
  6786. int idx = FindHelperEML(eml,key,&found);
  6787. if (found)
  6788. {
  6789. if ( cm_key == CPM_MOVE )
  6790. FreeString(key);
  6791. FreeExMemCM(data,cm_data);
  6792. }
  6793. else
  6794. InsertHelperEML(eml,idx,key,cm_key,data,cm_data);
  6795. return !found;
  6796. }
  6797. ///////////////////////////////////////////////////////////////////////////////
  6798. bool ReplaceEML ( exmem_list_t * eml, ccp key, CopyMode_t cm_key,
  6799. const exmem_t *data, CopyMode_t cm_data )
  6800. {
  6801. DASSERT(eml);
  6802. if (!key)
  6803. {
  6804. FreeExMemCM(data,cm_data);
  6805. return 0;
  6806. }
  6807. bool found;
  6808. int idx = FindHelperEML(eml,key,&found);
  6809. if (found)
  6810. {
  6811. if ( cm_key == CPM_MOVE )
  6812. FreeString(key);
  6813. exmem_key_t * dest = eml->list + idx;
  6814. AssignExMem(&dest->data,data,cm_data);
  6815. }
  6816. else
  6817. InsertHelperEML(eml,idx,key,cm_key,data,cm_data);
  6818. return !found;
  6819. }
  6820. ///////////////////////////////////////////////////////////////////////////////
  6821. bool OverwriteEML ( exmem_list_t * eml, ccp key, CopyMode_t cm_key,
  6822. const exmem_t *data, CopyMode_t cm_data )
  6823. {
  6824. DASSERT(eml);
  6825. if (!key)
  6826. {
  6827. FreeExMemCM(data,cm_data);
  6828. return 0;
  6829. }
  6830. bool found;
  6831. int idx = FindHelperEML(eml,key,&found);
  6832. if (found)
  6833. {
  6834. if ( cm_key == CPM_MOVE )
  6835. FreeString(key);
  6836. exmem_key_t * dest = eml->list + idx;
  6837. AssignExMem(&dest->data,data,cm_data);
  6838. }
  6839. return found;
  6840. }
  6841. ///////////////////////////////////////////////////////////////////////////////
  6842. exmem_key_t * AppendEML ( exmem_list_t * eml, ccp key, CopyMode_t cm_key,
  6843. const exmem_t *data, CopyMode_t cm_data )
  6844. {
  6845. DASSERT(eml);
  6846. if (!key)
  6847. {
  6848. FreeExMemCM(data,cm_data);
  6849. return 0;
  6850. }
  6851. if ( eml->used == eml->size )
  6852. {
  6853. eml->size += EXMEM_LIST_GROW(eml->size);
  6854. eml->list = REALLOC(eml->list,eml->size*sizeof(*eml->list));
  6855. }
  6856. TRACE("AppendEML(%s,%d) %d/%d\n",key,cm_key,eml->used,eml->size);
  6857. exmem_key_t * dest = eml->list + eml->used++;
  6858. dest->data = CopyExMem(data,cm_data);
  6859. dest->key = cm_key == CPM_COPY ? STRDUP(key) : key;
  6860. dest->data.is_key_alloced = cm_key != CPM_LINK;
  6861. eml->is_unsorted = true;
  6862. return dest;
  6863. }
  6864. ///////////////////////////////////////////////////////////////////////////////
  6865. bool RemoveByIndexEML ( exmem_list_t * eml, int index )
  6866. {
  6867. if ( index < 0 )
  6868. index += eml->used;
  6869. if ( index >= 0 && index < eml->used )
  6870. {
  6871. DASSERT( eml->used > 0 );
  6872. eml->used--;
  6873. exmem_key_t * dest = eml->list + index;
  6874. if (dest->data.is_key_alloced)
  6875. FreeString(dest->key);
  6876. FreeExMem(&dest->data);
  6877. if (eml->used)
  6878. memmove(dest,dest+1,(eml->used-index)*sizeof(*dest));
  6879. else
  6880. eml->is_unsorted = false;
  6881. return true;
  6882. }
  6883. return false;
  6884. }
  6885. ///////////////////////////////////////////////////////////////////////////////
  6886. bool RemoveByKeyEML ( exmem_list_t * eml, ccp key )
  6887. {
  6888. bool found;
  6889. const uint index = FindHelperEML(eml,key,&found);
  6890. #if 1
  6891. return found && RemoveByIndexEML(eml,index);
  6892. #else // [[obsolete]] 2021-11
  6893. if (found)
  6894. {
  6895. DASSERT(eml->used);
  6896. eml->used--;
  6897. DASSERT( index <= eml->used );
  6898. exmem_key_t * dest = eml->list + index;
  6899. if (dest->data.is_key_alloced)
  6900. FreeString(dest->key);
  6901. FreeExMem(&dest->data);
  6902. if (eml->used)
  6903. memmove(dest,dest+1,(eml->used-idx)*sizeof(*dest));
  6904. else
  6905. eml->is_unsorted = false;
  6906. }
  6907. return found;
  6908. #endif
  6909. }
  6910. ///////////////////////////////////////////////////////////////////////////////
  6911. exmem_key_t * MatchEML ( const exmem_list_t * eml, ccp key )
  6912. {
  6913. DASSERT(eml);
  6914. if (key)
  6915. {
  6916. exmem_key_t *ptr = eml->list, *end;
  6917. for ( end = ptr + eml->used; ptr < end; ptr++ )
  6918. if (MatchPattern(ptr->key,key,'/'))
  6919. return ptr;
  6920. }
  6921. return 0;
  6922. }
  6923. ///////////////////////////////////////////////////////////////////////////////
  6924. void DumpEML ( FILE *f, int indent, const exmem_list_t * eml, ccp info )
  6925. {
  6926. if ( f && eml && eml->used )
  6927. {
  6928. indent = NormalizeIndent(indent);
  6929. fprintf(f,"%*s%s%s" "exmem list %p, N=%u/%u%s\n",
  6930. indent,"", info ? info : "", info ? " : " : "",
  6931. eml, eml->used, eml->size, eml->is_unsorted ? ", not sorted" : "" );
  6932. char buf[20];
  6933. const int fw_idx = indent + snprintf(buf,sizeof(buf),"%d",eml->used-1) + 1;
  6934. exmem_key_t *ptr, *end = eml->list + eml->used;
  6935. int fw_key = 0;
  6936. for ( ptr = eml->list; ptr < end; ptr++ )
  6937. {
  6938. if (ptr->key)
  6939. {
  6940. const int klen = strlen(ptr->key);
  6941. if ( fw_key < klen )
  6942. fw_key = klen;
  6943. }
  6944. }
  6945. if ( fw_key > 30 )
  6946. fw_key = 30;
  6947. uint idx = 0;
  6948. for ( ptr = eml->list; ptr < end; ptr++, idx++ )
  6949. fprintf(f,"%*d [%c%c%c%c] %-*s = [%x] %s\n",
  6950. fw_idx, idx,
  6951. ptr->data.is_key_alloced? 'a' : '-', // flags: same as in PrintExMem()
  6952. ptr->data.is_alloced ? 'A' : '-',
  6953. ptr->data.is_circ_buf ? 'C' : '-',
  6954. ptr->data.is_original ? 'O' : '-',
  6955. fw_key, ptr->key ? ptr->key : "",
  6956. ptr->data.attrib, ptr->data.data.ptr );
  6957. }
  6958. }
  6959. ///////////////////////////////////////////////////////////////////////////////
  6960. ///////////////////////////////////////////////////////////////////////////////
  6961. exmem_t ResolveSymbolsEML ( const exmem_list_t * eml, ccp source )
  6962. {
  6963. exmem_t em = {{0}};
  6964. if (source)
  6965. {
  6966. char name[100];
  6967. int try;
  6968. for ( try = 0; try < 50; try++ )
  6969. {
  6970. ccp p1 = strstr(source,"$(");
  6971. if (!p1)
  6972. continue;
  6973. ccp p2 = strchr(p1,')');
  6974. if (!p2)
  6975. break;
  6976. const int plen = p2 - p1 - 2;
  6977. DASSERT(plen>=0);
  6978. StringCopySM(name,sizeof(name),p1+2,plen);
  6979. const exmem_key_t *ref = FindEML(eml,name);
  6980. mem_t replace = ref ? ref->data.data : NullMem;
  6981. char *temp = MEMDUP3(source, p1-source,
  6982. replace.ptr, replace.len,
  6983. p2+1, strlen(p2+1) );
  6984. if (em.is_alloced)
  6985. FreeString(source);
  6986. source = temp;
  6987. em.is_alloced = true;
  6988. }
  6989. }
  6990. em.data.ptr = source;
  6991. em.data.len = strlen(source);
  6992. em.is_original = !em.is_alloced;
  6993. return em;
  6994. }
  6995. ///////////////////////////////////////////////////////////////////////////////
  6996. uint ResolveAllSymbolsEML ( exmem_list_t * eml )
  6997. {
  6998. ASSERT(eml);
  6999. int try, count = 0;
  7000. char name[100];
  7001. exmem_key_t *ptr, *end = eml->list + eml->used;
  7002. for ( try = 0; try < 20; try++ )
  7003. {
  7004. int try_again = 0;
  7005. for ( ptr = eml->list; ptr < end; ptr++ )
  7006. {
  7007. for( int try2 = 0; try2 < 10; try2++ )
  7008. {
  7009. ccp str = ptr->data.data.ptr;
  7010. if (!str)
  7011. break;
  7012. ccp p1 = strstr(str,"$(");
  7013. if (!p1)
  7014. break;
  7015. ccp p2 = strchr(p1,')');
  7016. if (!p2)
  7017. break;
  7018. const int plen = p2 - p1 - 2;
  7019. ASSERT(plen>=0);
  7020. StringCopySM(name,sizeof(name),p1+2,plen);
  7021. const exmem_key_t *ref = FindEML(eml,name);
  7022. mem_t replace = ref && ref != ptr ? ref->data.data : NullMem;
  7023. char *temp = MEMDUP3( str, p1-str,
  7024. replace.ptr, replace.len,
  7025. p2+1, strlen(p2+1) );
  7026. if (ptr->data.is_alloced)
  7027. FreeString(str);
  7028. ASSERT(temp);
  7029. ptr->data.data.ptr = temp;
  7030. ptr->data.data.len = strlen(temp);
  7031. ptr->data.is_alloced = true;
  7032. ptr->data.is_original = ptr->data.is_circ_buf = false;
  7033. try_again++;
  7034. count++;
  7035. }
  7036. }
  7037. if (!try_again)
  7038. break;
  7039. }
  7040. return count;
  7041. }
  7042. ///////////////////////////////////////////////////////////////////////////////
  7043. // add symbols 'home', 'etc', 'install' = 'prog' and 'cwd'
  7044. void AddStandardSymbolsEML ( exmem_list_t * eml, bool overwrite )
  7045. {
  7046. DASSERT(eml);
  7047. char buf[PATH_MAX];
  7048. bool (*func)(exmem_list_t*,ccp,CopyMode_t,const exmem_t*,CopyMode_t)
  7049. = overwrite ? ReplaceEML : InsertEML;
  7050. PRINT0("overwrite=%d, func=%p, ins=%p, repl=%p\n",overwrite,func,InsertEML,ReplaceEML);
  7051. exmem_t temp = ExMemByString("/etc");
  7052. func(eml,"etc",CPM_LINK,&temp,CPM_LINK);
  7053. ccp home = getenv("HOME");
  7054. temp = ExMemByString0(home);
  7055. func(eml,"home",CPM_LINK,&temp,CPM_COPY);
  7056. // https://wiki.archlinux.org/index.php/XDG_Base_Directory
  7057. ccp xdg = getenv("XDG_CONFIG_HOME");
  7058. if ( xdg && *xdg )
  7059. {
  7060. temp = ExMemByString0(xdg);
  7061. ccp colon = strchr(xdg,':');
  7062. if (colon)
  7063. {
  7064. if ( colon == xdg )
  7065. goto xdg_home;
  7066. temp.data.len = colon - xdg;
  7067. }
  7068. func(eml,"xdg_home",CPM_LINK,&temp,CPM_COPY);
  7069. }
  7070. else if (home)
  7071. {
  7072. xdg_home:;
  7073. xdg = PathCatPP(buf,sizeof(buf),home,".config");
  7074. temp = ExMemByString0(xdg);
  7075. func(eml,"xdg_home",CPM_LINK,&temp,CPM_COPY);
  7076. }
  7077. xdg = getenv("XDG_CONFIG_DIRS");
  7078. if ( xdg && *xdg )
  7079. {
  7080. temp = ExMemByString0(xdg);
  7081. ccp colon = strchr(xdg,':');
  7082. if (colon)
  7083. {
  7084. if ( colon == xdg )
  7085. goto xdg_etc;
  7086. temp.data.len = colon - xdg;
  7087. }
  7088. func(eml,"xdg_etc",CPM_LINK,&temp,CPM_COPY);
  7089. }
  7090. else
  7091. {
  7092. xdg_etc:;
  7093. temp = ExMemByString("/etc/xdg");
  7094. func(eml,"xdg_etc",CPM_LINK,&temp,CPM_LINK);
  7095. }
  7096. ccp install = ProgramDirectory();
  7097. temp = ExMemByString0(install);
  7098. func(eml,"install",CPM_LINK,&temp,CPM_COPY);
  7099. func(eml,"prog",CPM_LINK,&temp,CPM_COPY);
  7100. if (getcwd(buf,sizeof(buf)))
  7101. {
  7102. temp = ExMemByString0(buf);
  7103. func(eml,"cwd",CPM_LINK,&temp,CPM_COPY);
  7104. }
  7105. #ifdef __CYGWIN__
  7106. ccp prog_files = getenv("PROGRAMFILES");
  7107. if ( !prog_files || !*prog_files )
  7108. prog_files = "C:/Program Files";
  7109. temp = GetNormalizeFilenameCygwin(prog_files,true);
  7110. func(eml,"programfiles",CPM_LINK,&temp,CPM_COPY);
  7111. FreeExMem(&temp);
  7112. #endif
  7113. }
  7114. //
  7115. ///////////////////////////////////////////////////////////////////////////////
  7116. /////////////// MultiColumn ///////////////
  7117. ///////////////////////////////////////////////////////////////////////////////
  7118. void ResetMultiColumn ( MultiColumn_t *mc )
  7119. {
  7120. if (mc)
  7121. {
  7122. ResetEML(&mc->list);
  7123. memset(mc,0,sizeof(*mc));
  7124. }
  7125. }
  7126. ///////////////////////////////////////////////////////////////////////////////
  7127. exmem_key_t * PutLineMC
  7128. ( MultiColumn_t *mc, uint opt, ccp key, ccp value, CopyMode_t cm_value )
  7129. {
  7130. DASSERT(mc);
  7131. DASSERT(key);
  7132. DASSERT(value);
  7133. exmem_t data = ExMemByString(value);
  7134. exmem_key_t *res = AppendEML( &mc->list, key, CPM_LINK, &data, cm_value );
  7135. res->data.attrib = opt;
  7136. return res;
  7137. }
  7138. ///////////////////////////////////////////////////////////////////////////////
  7139. exmem_key_t * PrintLineMC
  7140. ( MultiColumn_t *mc, uint opt, ccp key, ccp format, ... )
  7141. {
  7142. char buf[1000];
  7143. va_list arg;
  7144. va_start(arg,format);
  7145. vsnprintf(buf,sizeof(buf),format,arg);
  7146. va_end(arg);
  7147. return PutLineMC(mc,opt,key,buf,CPM_COPY);
  7148. }
  7149. ///////////////////////////////////////////////////////////////////////////////
  7150. // [[mc_len_t]]
  7151. typedef struct mc_len_t
  7152. {
  7153. int key; // key length
  7154. int val; // val length
  7155. }
  7156. mc_len_t;
  7157. //-----------------------------------------------------------------------------
  7158. // [[mc_param_t]]
  7159. #define MULTI_COLUMN_MAX_COLS 100
  7160. typedef struct mc_param_t
  7161. {
  7162. FILE *f; // output file
  7163. const ColorSet_t
  7164. *colset; // color set for the frame
  7165. int debug; // debug level: 0..2
  7166. int frame_mode; // 0:ASCII, 1:single line, 2:double line
  7167. ccp prefix; // line prefix
  7168. int prefix_fw; // field width of 'prefix'
  7169. int indent; // indention excluding prefix
  7170. ccp sep; // separator for frame_mode 0 and 1
  7171. int sep_fw; // field width of 'sep'
  7172. ccp eol; // end-of-line string
  7173. int fw; // total field width
  7174. ccp head_key; // header string for key column
  7175. int head_key_fw; // field width of 'head_key'
  7176. ccp head_val; // header string for value column
  7177. int head_val_fw; // field width of 'head_val'
  7178. int row_size; // additional size for a row
  7179. int col_size; // additional size for a column
  7180. int n_rows; // number of rows
  7181. int n_cols; // number of columns
  7182. mc_len_t *len_list; // list of estimatest lengths
  7183. mc_len_t fw_col[MULTI_COLUMN_MAX_COLS];
  7184. // field width for each column
  7185. }
  7186. mc_param_t;
  7187. //-----------------------------------------------------------------------------
  7188. static void mc_print_sep ( const mc_param_t *p )
  7189. {
  7190. fprintf(p->f,"%s%*s",p->prefix,p->indent,"");
  7191. const mc_len_t *fw = p->fw_col;
  7192. for ( int col = 0; col < p->n_cols; col++, fw++ )
  7193. {
  7194. if (col)
  7195. fputs("-+-",p->f);
  7196. fprintf(p->f,"%.*s",fw->key+fw->val+p->sep_fw,Minus300);
  7197. }
  7198. fputs(p->eol,p->f);
  7199. }
  7200. //-----------------------------------------------------------------------------
  7201. static void mc_print_line1 ( const mc_param_t *p, ccp template )
  7202. {
  7203. fprintf(p->f,"%s%*s%s%.3s",
  7204. p->prefix, p->indent,"",
  7205. p->colset->heading, template );
  7206. const mc_len_t *fw = p->fw_col;
  7207. for ( int col = 0; col < p->n_cols; col++, fw++ )
  7208. {
  7209. if (col)
  7210. fprintf(p->f,"%.3s",template+3);
  7211. fprintf(p->f,"%.*s", 3*(fw->key+fw->val+p->sep_fw+2), ThinLine300_3 );
  7212. }
  7213. fprintf(p->f,"%.3s%s%s",template+6,p->colset->reset,p->eol);
  7214. }
  7215. //-----------------------------------------------------------------------------
  7216. static void mc_print_line2 ( const mc_param_t *p, ccp template )
  7217. {
  7218. fprintf(p->f,"%s%*s%s%.3s",
  7219. p->prefix, p->indent,"",
  7220. p->colset->heading, template );
  7221. const mc_len_t *fw = p->fw_col;
  7222. for ( int col = 0; col < p->n_cols; col++, fw++ )
  7223. {
  7224. if (col)
  7225. fprintf(p->f,"%.3s",template+6);
  7226. fprintf(p->f,"%.*s%.3s%.*s",
  7227. 3*(fw->key+2), DoubleLine300_3,
  7228. template+3,
  7229. 3*(fw->val+2), DoubleLine300_3 );
  7230. }
  7231. fprintf(p->f,"%.3s%s%s",template+9,p->colset->reset,p->eol);
  7232. }
  7233. //-----------------------------------------------------------------------------
  7234. int PrintMultiColumn ( const MultiColumn_t *mc )
  7235. {
  7236. const u_usec_t start_time = GetTimerUSec();
  7237. if ( !mc || !mc->list.used )
  7238. return -1;
  7239. //--- setup
  7240. mc_param_t p = {0};
  7241. p.f = mc->f ? mc->f : stdout;
  7242. p.colset = mc->colset ? mc->colset : GetColorSet0();
  7243. p.debug = mc->debug;
  7244. p.indent = NormalizeIndent(mc->indent);
  7245. p.prefix = mc->prefix;
  7246. if (p.prefix)
  7247. p.prefix_fw = ScanEUTF8Length(p.prefix);
  7248. else
  7249. {
  7250. p.prefix = EmptyString;
  7251. p.prefix_fw = 0;
  7252. }
  7253. p.sep = mc->sep ? mc->sep : " ";
  7254. p.sep_fw = ScanEUTF8Length(p.sep);
  7255. p.eol = mc->eol ? mc->eol : "\n";
  7256. p.fw = !mc->fw ? 79 : mc->fw > 10 ? mc->fw : 10;
  7257. if ( mc->print_header )
  7258. {
  7259. p.head_key = mc->head_key ? mc->head_key : "Name";
  7260. p.head_key_fw = strlene8(p.head_key);
  7261. p.head_val = mc->head_val ? mc->head_val : "Value";
  7262. p.head_val_fw = strlene8(p.head_val);
  7263. }
  7264. else
  7265. {
  7266. p.head_key = p.head_val = EmptyString;
  7267. // p.head_key_fw = p.head_val_fw = 0; // initial value
  7268. }
  7269. switch (mc->frame_mode)
  7270. {
  7271. case 0:
  7272. p.frame_mode = 0;
  7273. p.row_size = -3;
  7274. p.col_size = 3 + p.sep_fw;
  7275. break;
  7276. case 1:
  7277. p.frame_mode = 1;
  7278. p.row_size = 1;
  7279. p.col_size = 3 + p.sep_fw;
  7280. break;
  7281. default:
  7282. p.frame_mode = 2;
  7283. p.row_size = 1;
  7284. p.col_size = 6;
  7285. break;
  7286. }
  7287. if ( p.debug > 1 )
  7288. fprintf(p.f,
  7289. "#> debug=%d, pre=%s, indent=%d, eol=%s, fw=%d,"
  7290. " print[Fhf]=%d%d%d, min_rows=%d, max_cols=%d%s",
  7291. p.debug, QuoteStringS(p.prefix,0,CHMD__MODERN),
  7292. p.indent, QuoteStringS(p.eol,0,CHMD__MODERN), p.fw,
  7293. p.frame_mode, mc->print_header, mc->print_footer,
  7294. mc->min_rows, mc->max_cols, p.eol );
  7295. //--- find min width
  7296. p.len_list = MALLOC( mc->list.used * sizeof(*p.len_list) );
  7297. mc_len_t *len_ptr = p.len_list;
  7298. int min_fw = INT_MAX;
  7299. const exmem_key_t *list_end = mc->list.list + mc->list.used;
  7300. for ( const exmem_key_t *ptr = mc->list.list; ptr < list_end; ptr++ )
  7301. {
  7302. len_ptr->key = strlene8(ptr->key);
  7303. len_ptr->val = strlene8(ptr->data.data.ptr);
  7304. const int len = len_ptr->key + len_ptr->val;
  7305. if ( min_fw > len )
  7306. min_fw = len;
  7307. len_ptr++;
  7308. }
  7309. min_fw += p.col_size;
  7310. const int avail_chars = p.fw - p.prefix_fw - p.indent - p.row_size;
  7311. int max_cols = ( avail_chars + p.col_size - 1 ) / min_fw;
  7312. if ( max_cols > MULTI_COLUMN_MAX_COLS )
  7313. max_cols = MULTI_COLUMN_MAX_COLS;
  7314. const int min_rows = mc->min_rows > 1 ? mc->min_rows : 1;
  7315. const int temp = ( mc->list.used + min_rows - 1 ) / min_rows + 1;
  7316. if ( temp > 0 && max_cols > temp )
  7317. max_cols = temp;
  7318. if ( p.debug > 1 )
  7319. fprintf(p.f,
  7320. "#> src-lines=%d, min-fw=%d, min-rows=%d, max-cols=%d/%d%s",
  7321. mc->list.used, min_fw,
  7322. min_rows, max_cols, MULTI_COLUMN_MAX_COLS, p.eol );
  7323. //--- evaluate number of columns
  7324. for ( p.n_cols = max_cols; p.n_cols > 0; p.n_cols-- )
  7325. {
  7326. memset(p.fw_col,0,sizeof(p.fw_col));
  7327. mc_len_t len = { p.head_key_fw, p.head_val_fw };
  7328. p.n_rows = ( mc->list.used - 1 ) / p.n_cols + 1;
  7329. p.n_cols = ( mc->list.used - 1 ) / p.n_rows + 1;
  7330. if ( p.debug > 1 )
  7331. fprintf(p.f, "#> … try %2u columns and %3u rows, %3u cells total%s",
  7332. p.n_cols, p.n_rows, p.n_cols*p.n_rows, p.eol );
  7333. int idx, row, col, total_fw = 0;
  7334. len_ptr = p.len_list;
  7335. for ( idx = row = col = 0; idx < mc->list.used; idx++, len_ptr++ )
  7336. {
  7337. if ( len.key < len_ptr->key )
  7338. len.key = len_ptr->key;
  7339. if ( len.val < len_ptr->val )
  7340. len.val = len_ptr->val;
  7341. if ( ++row >= p.n_rows )
  7342. {
  7343. total_fw += len.key + len.val + p.col_size;
  7344. if ( total_fw > avail_chars )
  7345. break;
  7346. p.fw_col[col] = len;
  7347. len.key = p.head_key_fw;
  7348. len.val = p.head_val_fw;
  7349. row = 0;
  7350. col++;
  7351. }
  7352. }
  7353. if ( col < p.n_cols )
  7354. {
  7355. p.fw_col[col] = len;
  7356. total_fw += len.key + len.val + p.col_size;
  7357. }
  7358. if ( total_fw <= avail_chars )
  7359. break;
  7360. }
  7361. if ( p.n_cols < 1 )
  7362. {
  7363. p.n_rows = mc->list.used;
  7364. p.n_cols = 1;
  7365. }
  7366. if ( p.debug > 1 )
  7367. {
  7368. fprintf(p.f,"#> cols=%d, rows=%d, fw", p.n_cols, p.n_rows );
  7369. int total = 0;
  7370. const mc_len_t *fw = p.fw_col;
  7371. for ( int col = 0; col < p.n_cols; col++, fw++ )
  7372. {
  7373. fprintf( p.f, "%c%u+%u", col ? ',' : '=', fw->key, fw->val );
  7374. total += fw->key + fw->val + p.col_size;
  7375. }
  7376. fprintf(p.f," = %d/%d%s",total,avail_chars,p.eol);
  7377. }
  7378. //--- print columns
  7379. const u_usec_t output_time = GetTimerUSec();
  7380. uint out_lines = p.n_rows;
  7381. //----------------------
  7382. if ( p.frame_mode >= 2 )
  7383. //----------------------
  7384. {
  7385. mc_print_line2(&p,"╔╤╦╗");
  7386. out_lines++;
  7387. if (mc->print_header)
  7388. {
  7389. fprintf(p.f,"%s%*s%s║%s",p.prefix,p.indent,"",p.colset->heading,p.colset->reset);
  7390. const mc_len_t *fw = p.fw_col;
  7391. for ( int col = 0; col < p.n_cols; col++, fw++ )
  7392. fprintf(p.f," %s %s│%s %s %s║%s",
  7393. AlignEUTF8ToCircBuf(p.head_key,-fw->key,fw->key),
  7394. p.colset->heading, p.colset->reset,
  7395. AlignEUTF8ToCircBuf(p.head_val,-fw->val,fw->val),
  7396. p.colset->heading, p.colset->reset );
  7397. fputs(p.eol,p.f);
  7398. mc_print_line2(&p,"╠╪╬╣");
  7399. out_lines += 2;
  7400. }
  7401. for ( int row = 0; row < p.n_rows; row++ )
  7402. {
  7403. fprintf(p.f,"%s%*s%s║%s",p.prefix,p.indent,"",p.colset->heading,p.colset->reset);
  7404. const exmem_key_t *ptr = mc->list.list + row;
  7405. const mc_len_t *fw = p.fw_col;
  7406. for ( int col = 0; col < p.n_cols; col++, ptr += p.n_rows, fw++ )
  7407. {
  7408. if ( ptr < list_end )
  7409. {
  7410. fprintf(p.f," %s %s│%s ",
  7411. AlignEUTF8ToCircBuf(ptr->key,-fw->key,fw->key),
  7412. p.colset->heading, p.colset->reset );
  7413. if ( ptr->data.attrib > 1 )
  7414. {
  7415. const int fw_attrib = ptr->data.attrib < fw->val ? ptr->data.attrib : fw->val;
  7416. const int fw_val = p.len_list[ptr-mc->list.list].val;
  7417. if ( fw_attrib <= fw_val )
  7418. goto std2;
  7419. fprintf(p.f,"%s%*s %s║%s",
  7420. AlignEUTF8ToCircBuf(ptr->data.data.ptr,fw_attrib,fw_attrib),
  7421. fw_attrib - fw->val, "",
  7422. p.colset->heading, p.colset->reset );
  7423. }
  7424. else
  7425. {
  7426. std2:;
  7427. const int fw_val = ptr->data.attrib ? -fw->val : fw->val;
  7428. fprintf(p.f,"%s %s║%s",
  7429. AlignEUTF8ToCircBuf(ptr->data.data.ptr,fw_val,fw->val),
  7430. p.colset->heading, p.colset->reset );
  7431. }
  7432. }
  7433. else
  7434. fprintf(p.f," %*s %s│%s %*s %s║%s",
  7435. fw->key, "", p.colset->heading, p.colset->reset,
  7436. fw->val, "", p.colset->heading, p.colset->reset );
  7437. }
  7438. fputs(p.eol,p.f);
  7439. }
  7440. mc_print_line2(&p,"╚╧╩╝");
  7441. out_lines++;
  7442. }
  7443. //---------------------------
  7444. else if ( p.frame_mode >= 1 )
  7445. //---------------------------
  7446. {
  7447. mc_print_line1(&p,"┌┬┐");
  7448. out_lines++;
  7449. if (mc->print_header)
  7450. {
  7451. fprintf(p.f,"%s%*s%s│%s",p.prefix,p.indent,"",p.colset->heading,p.colset->reset);
  7452. const mc_len_t *fw = p.fw_col;
  7453. for ( int col = 0; col < p.n_cols; col++, fw++ )
  7454. fprintf(p.f," %s%s%s %s│%s",
  7455. AlignEUTF8ToCircBuf(p.head_key,-fw->key,fw->key),
  7456. p.sep,
  7457. AlignEUTF8ToCircBuf(p.head_val,-fw->val,fw->val),
  7458. p.colset->heading, p.colset->reset );
  7459. fputs(p.eol,p.f);
  7460. mc_print_line1(&p,"├┼┤");
  7461. out_lines += 2;
  7462. }
  7463. for ( int row = 0; row < p.n_rows; row++ )
  7464. {
  7465. fprintf(p.f,"%s%*s%s│%s",p.prefix,p.indent,"",p.colset->heading,p.colset->reset);
  7466. const exmem_key_t *ptr = mc->list.list + row;
  7467. const mc_len_t *fw = p.fw_col;
  7468. for ( int col = 0; col < p.n_cols; col++, ptr += p.n_rows, fw++ )
  7469. {
  7470. if ( ptr < list_end )
  7471. {
  7472. fprintf(p.f," %s%s",
  7473. AlignEUTF8ToCircBuf(ptr->key,-fw->key,fw->key),
  7474. p.sep );
  7475. if ( ptr->data.attrib > 1 )
  7476. {
  7477. const int fw_attrib = ptr->data.attrib < fw->val ? ptr->data.attrib : fw->val;
  7478. const int fw_val = p.len_list[ptr-mc->list.list].val;
  7479. if ( fw_attrib <= fw_val )
  7480. goto std1;
  7481. fprintf(p.f,"%s%*s %s│%s",
  7482. AlignEUTF8ToCircBuf(ptr->data.data.ptr,fw_attrib,fw_attrib),
  7483. fw_attrib - fw->val, "",
  7484. p.colset->heading, p.colset->reset );
  7485. }
  7486. else
  7487. {
  7488. std1:;
  7489. const int fw_val = ptr->data.attrib ? -fw->val : fw->val;
  7490. fprintf(p.f,"%s %s│%s",
  7491. AlignEUTF8ToCircBuf(ptr->data.data.ptr,fw_val,fw->val),
  7492. p.colset->heading, p.colset->reset );
  7493. }
  7494. }
  7495. else
  7496. fprintf(p.f," %*s %s│%s",
  7497. fw->key + fw->val + p.sep_fw, "",
  7498. p.colset->heading, p.colset->reset );
  7499. }
  7500. fputs(p.eol,p.f);
  7501. }
  7502. mc_print_line1(&p,"└┴┘");
  7503. out_lines++;
  7504. }
  7505. //-------------------
  7506. else // !p.frame_mode
  7507. //-------------------
  7508. {
  7509. if (mc->print_header)
  7510. {
  7511. mc_print_sep(&p);
  7512. fprintf(p.f,"%s%*s",p.prefix,p.indent,"");
  7513. const mc_len_t *fw = p.fw_col;
  7514. for ( int col = 0; col < p.n_cols; col++, fw++ )
  7515. {
  7516. if (col)
  7517. fputs(" | ",p.f);
  7518. fprintf(p.f,"%s%s%s",
  7519. AlignEUTF8ToCircBuf(p.head_key,-fw->key,fw->key),
  7520. p.sep,
  7521. AlignEUTF8ToCircBuf(p.head_val,-fw->val,fw->val) );
  7522. }
  7523. fputs(p.eol,p.f);
  7524. out_lines += 2;
  7525. }
  7526. if ( mc->print_header || mc->print_footer )
  7527. {
  7528. mc_print_sep(&p);
  7529. out_lines++;
  7530. }
  7531. for ( int row = 0; row < p.n_rows; row++ )
  7532. {
  7533. fprintf(p.f,"%s%*s",p.prefix,p.indent,"");
  7534. const exmem_key_t *ptr = mc->list.list + row;
  7535. const mc_len_t *fw = p.fw_col;
  7536. for ( int col = 0; col < p.n_cols; col++, ptr += p.n_rows, fw++ )
  7537. {
  7538. if (col)
  7539. fputs(" | ",p.f);
  7540. if ( ptr < list_end )
  7541. {
  7542. fprintf(p.f,"%s%s",
  7543. AlignEUTF8ToCircBuf(ptr->key,-fw->key,fw->key),
  7544. p.sep );
  7545. if ( ptr->data.attrib > 1 )
  7546. {
  7547. const int fw_attrib = ptr->data.attrib < fw->val ? ptr->data.attrib : fw->val;
  7548. const int fw_val = p.len_list[ptr-mc->list.list].val;
  7549. if ( fw_attrib <= fw_val )
  7550. goto std0;
  7551. fprintf(p.f,"%s%*s",
  7552. AlignEUTF8ToCircBuf(ptr->data.data.ptr,fw_attrib,fw_attrib),
  7553. fw_attrib - fw->val, "" );
  7554. }
  7555. else
  7556. {
  7557. std0:;
  7558. const int fw_val = ptr->data.attrib ? -fw->val : fw->val;
  7559. fputs(AlignEUTF8ToCircBuf(ptr->data.data.ptr,fw_val,fw->val),p.f);
  7560. }
  7561. }
  7562. }
  7563. fputs(p.eol,p.f);
  7564. }
  7565. if (mc->print_footer)
  7566. {
  7567. mc_print_sep(&p);
  7568. out_lines++;
  7569. }
  7570. }
  7571. //---------------------
  7572. // end-if !p.frame_mode
  7573. //---------------------
  7574. //--- terminate
  7575. if ( p.debug > 0 )
  7576. {
  7577. const u_usec_t now = GetTimerUSec();
  7578. fprintf(p.f,"#> setup in %llu us, %u ouput lines in %llu us, total %llu us%s",
  7579. output_time - start_time,
  7580. out_lines, now - output_time,
  7581. now - start_time,
  7582. p.eol );
  7583. }
  7584. FREE(p.len_list);
  7585. return out_lines;
  7586. }
  7587. //
  7588. ///////////////////////////////////////////////////////////////////////////////
  7589. /////////////// Memory Maps ///////////////
  7590. ///////////////////////////////////////////////////////////////////////////////
  7591. void InitializeMemMap ( MemMap_t * mm )
  7592. {
  7593. DASSERT(mm);
  7594. memset(mm,0,sizeof(*mm));
  7595. }
  7596. ///////////////////////////////////////////////////////////////////////////////
  7597. void ResetMemMap ( MemMap_t * mm )
  7598. {
  7599. DASSERT(mm);
  7600. uint i;
  7601. if (mm->field)
  7602. {
  7603. for ( i = 0; i < mm->used; i++ )
  7604. FREE(mm->field[i]);
  7605. FREE(mm->field);
  7606. }
  7607. memset(mm,0,sizeof(*mm));
  7608. }
  7609. ///////////////////////////////////////////////////////////////////////////////
  7610. void CopyMemMap
  7611. (
  7612. MemMap_t * mm1, // merged mem map, not NULL, cleared
  7613. const MemMap_t * mm2, // NULL or second mem map
  7614. bool use_tie // TRUE: use InsertMemMapTie()
  7615. )
  7616. {
  7617. DASSERT(mm1);
  7618. ResetMemMap(mm1);
  7619. MergeMemMap(mm1,mm2,use_tie);
  7620. }
  7621. ///////////////////////////////////////////////////////////////////////////////
  7622. void MergeMemMap
  7623. (
  7624. MemMap_t * mm1, // merged mem map, not NULL, not cleared
  7625. const MemMap_t * mm2, // NULL or second mem map
  7626. bool use_tie // TRUE: use InsertMemMapTie()
  7627. )
  7628. {
  7629. DASSERT(mm1);
  7630. if (mm2)
  7631. {
  7632. uint i;
  7633. for ( i = 0; i < mm2->used; i++ )
  7634. {
  7635. const MemMapItem_t *src = mm2->field[i];
  7636. if (src)
  7637. {
  7638. MemMapItem_t *it = use_tie
  7639. ? InsertMemMapTie(mm1,src->off,src->size)
  7640. : InsertMemMap(mm1,src->off,src->size);
  7641. if (it)
  7642. StringCopyS(it->info,sizeof(it->info),src->info);
  7643. }
  7644. }
  7645. }
  7646. }
  7647. ///////////////////////////////////////////////////////////////////////////////
  7648. MemMapItem_t * FindMemMap ( MemMap_t * mm, off_t off, off_t size )
  7649. {
  7650. DASSERT(mm);
  7651. off_t off_end = off + size;
  7652. int beg = 0;
  7653. int end = mm->used - 1;
  7654. while ( beg <= end )
  7655. {
  7656. uint idx = (beg+end)/2;
  7657. MemMapItem_t * mi = mm->field[idx];
  7658. if ( off_end <= mi->off )
  7659. end = idx - 1 ;
  7660. else if ( off >= mi->off + mi->size )
  7661. beg = idx + 1;
  7662. else
  7663. return mi;
  7664. }
  7665. return 0;
  7666. }
  7667. ///////////////////////////////////////////////////////////////////////////////
  7668. uint InsertMemMapIndex
  7669. (
  7670. // returns the index of the new item
  7671. MemMap_t * mm, // mem map pointer
  7672. off_t off, // offset of area
  7673. off_t size // size of area
  7674. )
  7675. {
  7676. DASSERT(mm);
  7677. uint idx = FindMemMapHelper(mm,off,size);
  7678. DASSERT( mm->used <= mm->size );
  7679. if ( mm->used == mm->size )
  7680. {
  7681. mm->size += 64;
  7682. mm->field = REALLOC(mm->field,mm->size*sizeof(*mm->field));
  7683. }
  7684. DASSERT( idx <= mm->used );
  7685. MemMapItem_t ** dest = mm->field + idx;
  7686. memmove(dest+1,dest,(mm->used-idx)*sizeof(*dest));
  7687. mm->used++;
  7688. MemMapItem_t * mi = MALLOC(sizeof(MemMapItem_t));
  7689. mi->off = off;
  7690. mi->size = size;
  7691. mi->overlap = 0;
  7692. *dest = mi;
  7693. return idx;
  7694. }
  7695. ///////////////////////////////////////////////////////////////////////////////
  7696. MemMapItem_t * InsertMemMap
  7697. (
  7698. // returns a pointer to a new item (never NULL)
  7699. MemMap_t * mm, // mem map pointer
  7700. off_t off, // offset of area
  7701. off_t size // size of area
  7702. )
  7703. {
  7704. const uint idx = InsertMemMapIndex(mm,off,size);
  7705. // a C sequence point is important here
  7706. return mm->field[idx];
  7707. }
  7708. ///////////////////////////////////////////////////////////////////////////////
  7709. static bool TieMemMap
  7710. (
  7711. // returns true if element are tied togehther
  7712. MemMap_t * mm, // mem map pointer
  7713. uint idx, // tie element 'idx' and 'idx+1'
  7714. bool force // always tie and not only if overlapped
  7715. )
  7716. {
  7717. DASSERT(mm);
  7718. DASSERT( idx+1 < mm->used );
  7719. MemMapItem_t * i1 = mm->field[idx];
  7720. MemMapItem_t * i2 = mm->field[idx+1];
  7721. if ( force || i1->off + i1->size >= i2->off )
  7722. {
  7723. const off_t new_size = i2->off + i2->size - i1->off;
  7724. if ( i1->size < new_size )
  7725. i1->size = new_size;
  7726. FREE(i2);
  7727. idx++;
  7728. mm->used--;
  7729. memmove( mm->field + idx,
  7730. mm->field + idx + 1,
  7731. ( mm->used - idx ) * sizeof(MemMapItem_t*) );
  7732. return true;
  7733. }
  7734. return false;
  7735. }
  7736. ///////////////////////////////////////////////////////////////////////////////
  7737. MemMapItem_t * InsertMemMapTie
  7738. (
  7739. // returns a pointer to a new or existing item (never NULL)
  7740. MemMap_t * mm, // mem map pointer
  7741. off_t off, // offset of area
  7742. off_t size // size of area
  7743. )
  7744. {
  7745. uint idx = InsertMemMapIndex(mm,off,size);
  7746. if ( idx > 0 && TieMemMap(mm,idx-1,false) )
  7747. idx--;
  7748. while ( idx + 1 < mm->used && TieMemMap(mm,idx,false) )
  7749. ;
  7750. return mm->field[idx];
  7751. }
  7752. ///////////////////////////////////////////////////////////////////////////////
  7753. void InsertMemMapWrapper
  7754. (
  7755. void * param, // user defined parameter
  7756. u64 offset, // offset of object
  7757. u64 size, // size of object
  7758. ccp info // info about object
  7759. )
  7760. {
  7761. noTRACE("InsertMemMapWrapper(%p,%llx,%llx,%s)\n",param,offset,size,info);
  7762. DASSERT(param);
  7763. MemMapItem_t * mi = InsertMemMap(param,offset,size);
  7764. StringCopyS(mi->info,sizeof(mi->info),info);
  7765. }
  7766. ///////////////////////////////////////////////////////////////////////////////
  7767. uint FindMemMapHelper ( MemMap_t * mm, off_t off, off_t size )
  7768. {
  7769. DASSERT(mm);
  7770. int beg = 0;
  7771. int end = mm->used - 1;
  7772. while ( beg <= end )
  7773. {
  7774. uint idx = (beg+end)/2;
  7775. MemMapItem_t * mi = mm->field[idx];
  7776. if ( off < mi->off )
  7777. end = idx - 1 ;
  7778. else if ( off > mi->off )
  7779. beg = idx + 1;
  7780. else if ( size < mi->size )
  7781. end = idx - 1 ;
  7782. else if ( size > mi->size )
  7783. beg = idx + 1;
  7784. else
  7785. {
  7786. TRACE("FindMemMapHelper(%llx,%llx) FOUND=%d/%d/%d\n",
  7787. (u64)off, (u64)size, idx, mm->used, mm->size );
  7788. return idx;
  7789. }
  7790. }
  7791. TRACE("FindStringFieldHelper(%llx,%llx) failed=%d/%d/%d\n",
  7792. (u64)off, (u64)size, beg, mm->used, mm->size );
  7793. return beg;
  7794. }
  7795. ///////////////////////////////////////////////////////////////////////////////
  7796. uint CalcOverlapMemMap ( MemMap_t * mm )
  7797. {
  7798. DASSERT(mm);
  7799. uint i, count = 0;
  7800. MemMapItem_t * prev = 0;
  7801. for ( i = 0; i < mm->used; i++ )
  7802. {
  7803. MemMapItem_t * ptr = mm->field[i];
  7804. ptr->overlap = 0;
  7805. if ( prev && ptr->off < prev->off + prev->size )
  7806. {
  7807. ptr ->overlap |= 1;
  7808. prev->overlap |= 2;
  7809. count++;
  7810. }
  7811. prev = ptr;
  7812. }
  7813. return count;
  7814. }
  7815. ///////////////////////////////////////////////////////////////////////////////
  7816. u64 FindFreeSpaceMemMap
  7817. (
  7818. // return address or NULL on not-found
  7819. const MemMap_t * mm,
  7820. u64 addr_beg, // first possible address
  7821. u64 addr_end, // last possible address
  7822. u64 size, // minimal size
  7823. u64 align, // aligning
  7824. u64 *space // not NULL: store available space here
  7825. )
  7826. {
  7827. DASSERT(mm);
  7828. if (!size)
  7829. goto term;
  7830. if (!align)
  7831. align = 1;
  7832. addr_beg = ALIGN64(addr_beg,align);
  7833. uint i;
  7834. for ( i = 0; i < mm->used; i++ )
  7835. {
  7836. MemMapItem_t *mi = mm->field[i];
  7837. const u64 end = ALIGN64( mi->off + mi->size, align );
  7838. if ( mi->off > addr_beg )
  7839. {
  7840. u64 found_space = ALIGNOFF64(mi->off,align) - addr_beg;
  7841. if ( size <= found_space )
  7842. {
  7843. if (space)
  7844. *space = found_space;
  7845. return addr_beg;
  7846. }
  7847. }
  7848. if ( addr_beg < end )
  7849. addr_beg = end;
  7850. }
  7851. u64 found_space = ALIGNOFF64(addr_end,align) - addr_beg;
  7852. if ( size <= found_space )
  7853. {
  7854. if (space)
  7855. *space = found_space;
  7856. return addr_beg;
  7857. }
  7858. term:
  7859. if (space)
  7860. *space = 0;
  7861. return 0;
  7862. }
  7863. ///////////////////////////////////////////////////////////////////////////////
  7864. void PrintMemMap ( MemMap_t * mm, FILE * f, int indent, ccp info_head )
  7865. {
  7866. DASSERT(mm);
  7867. if ( !f || !mm->used )
  7868. return;
  7869. CalcOverlapMemMap(mm);
  7870. indent = NormalizeIndent(indent);
  7871. static char ovl[][3] = { " ", "!.", ".!", "!!" };
  7872. if (!info_head)
  7873. info_head = "info";
  7874. int i, max_ilen = strlen(info_head);
  7875. for ( i = 0; i < mm->used; i++ )
  7876. {
  7877. MemMapItem_t * ptr = mm->field[i];
  7878. ptr->info[sizeof(ptr->info)-1] = 0;
  7879. const int ilen = strlen(ptr->info);
  7880. if ( max_ilen < ilen )
  7881. max_ilen = ilen;
  7882. }
  7883. fprintf(f,"%*s unused : off(beg) .. off(end) : size : %s\n%*s%.*s\n",
  7884. indent, "", info_head,
  7885. indent, "", max_ilen+52, Minus300 );
  7886. off_t max_end = mm->begin;
  7887. for ( i = 0; i < mm->used; i++ )
  7888. {
  7889. MemMapItem_t * ptr = mm->field[i];
  7890. if ( !i && max_end > ptr->off )
  7891. max_end = ptr->off;
  7892. const off_t end = ptr->off + ptr->size;
  7893. if ( ptr->off > max_end )
  7894. fprintf(f,"%*s%s%10llx :%10llx ..%10llx :%10llx : %s\n",
  7895. indent, "", ovl[ptr->overlap&3], (u64)( ptr->off - max_end ),
  7896. (u64)ptr->off, (u64)end, (u64)ptr->size, ptr->info );
  7897. else
  7898. fprintf(f,"%*s%s :%10llx ..%10llx :%10llx : %s\n",
  7899. indent, "", ovl[ptr->overlap&3],
  7900. (u64)ptr->off, (u64)end, (u64)ptr->size, ptr->info );
  7901. if ( max_end < end )
  7902. max_end = end;
  7903. }
  7904. }
  7905. //
  7906. ///////////////////////////////////////////////////////////////////////////////
  7907. /////////////// Memory Map: Scan addresses ///////////////
  7908. ///////////////////////////////////////////////////////////////////////////////
  7909. char * ScanAddress
  7910. (
  7911. // returns first not scanned char of 'arg'
  7912. ScanAddr_t * result, // result, initialized by ScanAddress()
  7913. ccp arg, // format: ADDR | ADDR:END | ADDR#SIZE
  7914. uint default_base // base for numbers without '0x' prefix
  7915. // 0: C like with octal support
  7916. // 10: standard value for decimal numbers
  7917. // 16: standard value for hex numbers
  7918. )
  7919. {
  7920. DASSERT(result);
  7921. memset(result,0,sizeof(*result));
  7922. if (!arg)
  7923. return 0;
  7924. ccp end = ScanUINT(&result->addr,arg,default_base);
  7925. if ( end == arg )
  7926. return (char*)arg;
  7927. arg = end;
  7928. while ( *arg == ' ' || *arg == '\t' )
  7929. arg++;
  7930. result->size = 1;
  7931. result->stat = 1;
  7932. if ( *arg == ':' )
  7933. {
  7934. uint addr2;
  7935. end = ScanUINT(&addr2,++arg,default_base);
  7936. if ( end == arg )
  7937. return(char*) arg-1;
  7938. result->size = addr2 > result->addr ? addr2 - result->addr : 0;
  7939. result->stat = 2;
  7940. }
  7941. else if ( *arg == '#' )
  7942. {
  7943. end = ScanUINT(&result->size,++arg,default_base);
  7944. result->stat = 2;
  7945. }
  7946. return (char*)end;
  7947. }
  7948. ///////////////////////////////////////////////////////////////////////////////
  7949. uint InsertAddressMemMap
  7950. (
  7951. // returns the number of added addresses
  7952. MemMap_t * mm, // mem map pointer
  7953. bool use_tie, // TRUE: use InsertMemMapTie()
  7954. ccp arg, // comma separated list of addresses
  7955. // formats: ADDR | ADDR:END | ADDR#SIZE
  7956. uint default_base // base for numbers without '0x' prefix
  7957. // 0: C like with octal support
  7958. // 10: standard value for decimal numbers
  7959. // 16: standard value for hex numbers
  7960. )
  7961. {
  7962. DASSERT(mm);
  7963. if (!arg)
  7964. return 0;
  7965. uint count = 0;
  7966. while (*arg)
  7967. {
  7968. ScanAddr_t addr;
  7969. arg = ScanAddress(&addr,arg,default_base);
  7970. if (addr.stat)
  7971. {
  7972. if (use_tie)
  7973. InsertMemMapTie(mm,addr.addr,addr.size);
  7974. else
  7975. InsertMemMap(mm,addr.addr,addr.size);
  7976. count++;
  7977. }
  7978. while ( *arg && *arg != ' ' && *arg != '\t' && *arg != ',' )
  7979. arg++;
  7980. while ( *arg == ' ' || *arg == '\t' || *arg == ',' )
  7981. arg++;
  7982. }
  7983. return count;
  7984. }
  7985. //
  7986. ///////////////////////////////////////////////////////////////////////////////
  7987. /////////////// DataBuf_t ///////////////
  7988. ///////////////////////////////////////////////////////////////////////////////
  7989. void InitializeDataBuf
  7990. ( DataBuf_t *db, uint buf_size, DataBufFill_t func, void *user_data )
  7991. {
  7992. DASSERT(db);
  7993. memset(db,0,sizeof(*db));
  7994. if (buf_size)
  7995. {
  7996. db->size = buf_size;
  7997. db->buf = MALLOC(buf_size);
  7998. db->buf_end = db->buf + buf_size;
  7999. db->data = db->data_end = db->buf;
  8000. }
  8001. db->fill_func = func;
  8002. db->user_data = user_data;
  8003. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8004. }
  8005. ///////////////////////////////////////////////////////////////////////////////
  8006. void ResetDataBuf ( DataBuf_t *db )
  8007. {
  8008. if (db)
  8009. {
  8010. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8011. FREE(db->buf);
  8012. memset(db,0,sizeof(*db));
  8013. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8014. }
  8015. }
  8016. ///////////////////////////////////////////////////////////////////////////////
  8017. void ResizeDataBuf ( DataBuf_t *db, uint new_buf_size )
  8018. {
  8019. DASSERT(db);
  8020. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8021. DASSERT(new_buf_size>0);
  8022. if (!db->buf)
  8023. return;
  8024. PackDataBuf(db);
  8025. db->buf = REALLOC(db->buf,new_buf_size);
  8026. db->buf_end = db->buf + new_buf_size;
  8027. db->size = new_buf_size;
  8028. if ( db->used > new_buf_size )
  8029. db->used = new_buf_size;
  8030. db->data = db->buf;
  8031. db->data_end = db->data + db->used;
  8032. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8033. }
  8034. ///////////////////////////////////////////////////////////////////////////////
  8035. void ClearDataBuf ( DataBuf_t *db, uint new_buf_size_if_not_null )
  8036. {
  8037. DASSERT(db);
  8038. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8039. db->offset = 0;
  8040. db->data = db->data_end = db->buf;
  8041. db->used = 0;
  8042. db->offset = 0;
  8043. if (new_buf_size_if_not_null)
  8044. ResizeDataBuf(db,new_buf_size_if_not_null);
  8045. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8046. }
  8047. ///////////////////////////////////////////////////////////////////////////////
  8048. void EmptyDataBuf ( DataBuf_t *db )
  8049. {
  8050. DASSERT(db);
  8051. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8052. db->data = db->data_end = db->buf;
  8053. db->used = 0;
  8054. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8055. }
  8056. ///////////////////////////////////////////////////////////////////////////////
  8057. void PackDataBuf ( DataBuf_t *db )
  8058. {
  8059. DASSERT(db);
  8060. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8061. if ( !db->used || !db->buf )
  8062. {
  8063. db->data = db->data_end = db->buf;
  8064. }
  8065. else if ( db->data > db->buf )
  8066. {
  8067. if ( db->data < db->data_end )
  8068. {
  8069. // easy case: FREE1 DATA FREE2
  8070. memmove(db->buf,db->data,db->used);
  8071. }
  8072. else
  8073. {
  8074. // case: DATA2 FREE DATA1
  8075. uint d1len = db->buf_end - db->data;
  8076. uint d2len = db->data_end - db->buf;
  8077. DASSERT( d1len + d2len == db->used );
  8078. #ifdef TEST0
  8079. u8 temp[10];
  8080. #else
  8081. u8 temp[0x8000];
  8082. #endif
  8083. if ( d2len <= sizeof(temp) && d2len < d1len )
  8084. {
  8085. memcpy(temp,db->buf,d2len);
  8086. memmove(db->buf,db->data,d1len);
  8087. memcpy(db->buf+d1len,temp,d2len);
  8088. }
  8089. else if ( d1len <= sizeof(temp) )
  8090. {
  8091. memcpy(temp,db->data,d1len);
  8092. memmove(db->buf+d1len,db->buf,d2len);
  8093. memcpy(db->buf,temp,d1len);
  8094. }
  8095. else
  8096. {
  8097. noPRINT("PACK %u+%u/%u, temp=%zu\n",d2len,d1len,db->size,sizeof(temp));
  8098. // use a dynamic buffer => [2do]] optimize later
  8099. u8 *temp = MEMDUP(db->buf,d2len);
  8100. memmove(db->buf,db->data,d1len);
  8101. memcpy(db->buf+d1len,temp,d2len);
  8102. FREE(temp);
  8103. }
  8104. }
  8105. db->data = db->buf;
  8106. db->data_end = db->data + db->used;
  8107. }
  8108. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8109. }
  8110. ///////////////////////////////////////////////////////////////////////////////
  8111. ///////////////////////////////////////////////////////////////////////////////
  8112. // debugging
  8113. bool IsValidDataBuf ( DataBuf_t *db )
  8114. {
  8115. if ( !db || db->used > db->size )
  8116. return false;
  8117. if (db->buf)
  8118. {
  8119. if ( db->buf_end != db->buf + db->size
  8120. || db->data < db->buf || db->data >= db->buf_end )
  8121. return false;
  8122. u8 *end = db->data + db->used;
  8123. if ( end > db->buf_end )
  8124. end -= db->size;
  8125. return end == db->data_end;
  8126. }
  8127. return !db->size && !db->buf_end && !db->data && !db->data_end;
  8128. }
  8129. ///////////////////////////////////////////////////////////////////////////////
  8130. bool DumpDataBuf ( FILE *f, uint indent, DataBuf_t *db, bool if_invalid )
  8131. {
  8132. DASSERT(f);
  8133. DASSERT(db);
  8134. if ( if_invalid && IsValidDataBuf(db) )
  8135. return false;
  8136. fflush(stdout);
  8137. fflush(stderr);
  8138. indent = NormalizeIndent(indent);
  8139. if (!db)
  8140. {
  8141. fprintf(f,"%*sdata_buf_t: NULL\n",indent,"");
  8142. return true;
  8143. }
  8144. if (!db->buf)
  8145. {
  8146. fprintf(f,"%*sdata_buf_t buf: Invalid buf\n",indent,"");
  8147. return true;
  8148. }
  8149. fprintf(f,"%*sdata_buf_t %p .. %d, data %d .. %d, used %u/%u, off=%llu\n",
  8150. indent,"", db->buf, (int)(db->buf_end - db->buf),
  8151. (int)(db->data - db->buf), (int)(db->data_end - db->buf),
  8152. db->used, db->size, db->offset );
  8153. return true;
  8154. }
  8155. ///////////////////////////////////////////////////////////////////////////////
  8156. void FillPatternDataBuf ( DataBuf_t *db )
  8157. {
  8158. // fill the buffer with a test pattern:
  8159. // '-' for unused bytes
  8160. // ">0123456789<" in a longer or shorter form for used bytes
  8161. DASSERT(db);
  8162. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8163. memset(db->buf,'-',db->size);
  8164. if ( db->used <= 1 )
  8165. {
  8166. if ( db->used == 1 )
  8167. *db->data = '+';
  8168. return;
  8169. }
  8170. u8 *ptr = db->data;
  8171. u8 *end = ptr + db->used - 1;
  8172. if ( end >= db->buf_end )
  8173. end -= db->size;
  8174. *ptr++ = '>';
  8175. *end = '<';
  8176. uint i = 0, len = end - ptr;
  8177. if ( len > db->size )
  8178. len += db->size;
  8179. for(;;)
  8180. {
  8181. if ( ptr == db->buf_end )
  8182. ptr = db->buf;
  8183. if ( ptr == end )
  8184. break;
  8185. *ptr++ = 'a' + i/len;
  8186. i += 26;
  8187. }
  8188. }
  8189. ///////////////////////////////////////////////////////////////////////////////
  8190. ///////////////////////////////////////////////////////////////////////////////
  8191. uint InsertDataBuf
  8192. (
  8193. // Insert at top of buffer.
  8194. // Return the number of inserted bytes
  8195. DataBuf_t *db, // valid pointer to data buffer
  8196. const void *data, // data to insert
  8197. uint data_size, // size of 'data'
  8198. bool all_or_none // true: insert complete data or nothing
  8199. )
  8200. {
  8201. DASSERT(db);
  8202. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8203. uint space = db->size - db->used;
  8204. if ( data_size > space )
  8205. {
  8206. if (all_or_none)
  8207. return 0;
  8208. data_size = space;
  8209. }
  8210. if (!db->used)
  8211. db->data = db->data_end = db->buf + data_size;
  8212. db->used += data_size;
  8213. uint copy_len = db->data - db->buf;
  8214. if ( copy_len > data_size )
  8215. copy_len = data_size;
  8216. memcpy(db->data-copy_len,data,copy_len);
  8217. db->data -= copy_len;
  8218. if ( data_size > copy_len )
  8219. {
  8220. const uint copy_len2 = data_size - copy_len;
  8221. memcpy(db->buf_end-copy_len2,(u8*)data+copy_len,copy_len2);
  8222. db->data = db->buf_end - copy_len2;
  8223. }
  8224. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8225. return data_size;
  8226. }
  8227. ///////////////////////////////////////////////////////////////////////////////
  8228. uint AppendDataBuf
  8229. (
  8230. // Append data at end of buffer
  8231. // Return the number of inserted bytes
  8232. DataBuf_t *db, // valid pointer to data buffer
  8233. const void *data, // data to insert
  8234. uint data_size, // size of 'data'
  8235. bool all_or_none // true: insert complete data or nothing
  8236. )
  8237. {
  8238. DASSERT(db);
  8239. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8240. uint space = db->size - db->used;
  8241. noPRINT("APPEND %u/%u [%u/%u]\n",data_size,space,db->used,db->size);
  8242. if ( data_size > space )
  8243. {
  8244. if (all_or_none)
  8245. return 0;
  8246. data_size = space;
  8247. }
  8248. if (!db->used)
  8249. db->data = db->data_end = db->buf;
  8250. db->used += data_size;
  8251. uint copy_len = db->buf_end - db->data_end;
  8252. if ( copy_len > data_size )
  8253. copy_len = data_size;
  8254. memcpy(db->data_end,data,copy_len);
  8255. db->data_end += copy_len;
  8256. if ( data_size > copy_len )
  8257. {
  8258. const uint copy_len2 = data_size - copy_len;
  8259. memcpy(db->buf,(u8*)data+copy_len,copy_len2);
  8260. db->data_end = db->buf + copy_len2;
  8261. }
  8262. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8263. return data_size;
  8264. }
  8265. ///////////////////////////////////////////////////////////////////////////////
  8266. ///////////////////////////////////////////////////////////////////////////////
  8267. void * GetPtrDataBuf
  8268. (
  8269. // Return a pointer to the data and make sure,
  8270. // that the data is not wrapped. Return NULL if failed.
  8271. DataBuf_t *db, // valid pointer to data buffer
  8272. uint data_size, // number of needed bytes
  8273. uint align, // >1: Data alignment is also needed.
  8274. // Only 2,4,8,16,... are allowed, but not verified.
  8275. // Begin of buffer is always well aligned.
  8276. bool drop // true: On success, drop data from buffer
  8277. // In real, the data is available and only
  8278. // the pointers and counters are updated.
  8279. )
  8280. {
  8281. DASSERT(db);
  8282. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8283. if (!data_size)
  8284. return db->data;
  8285. if ( data_size > db->used )
  8286. {
  8287. if ( data_size <= db->size && db->fill_func )
  8288. db->fill_func(db,data_size-db->used,0);
  8289. if ( data_size > db->used )
  8290. return 0;
  8291. }
  8292. if ( db->data + data_size > db->buf_end )
  8293. PackDataBuf(db);
  8294. else if ( align > 1 )
  8295. {
  8296. const uint offset = db->data - db->buf;
  8297. if ( offset & (align-1) )
  8298. PackDataBuf(db);
  8299. }
  8300. u8 *res = db->data;
  8301. if (drop)
  8302. {
  8303. db->data += data_size;
  8304. db->used -= data_size;
  8305. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8306. }
  8307. return res;
  8308. }
  8309. ///////////////////////////////////////////////////////////////////////////////
  8310. uint CopyDataBuf
  8311. (
  8312. // Copy data from buffer, but don't remove it
  8313. // Return the number of copied bytes
  8314. DataBuf_t *db, // valid pointer to data buffer
  8315. void *dest, // destination buffer wit at least 'max_size' space
  8316. uint min_read, // return with 0 read bytes if less bytes available
  8317. // if 'min_read' > 'size', NULL is returned
  8318. uint max_read // try to read upto 'max_read' bytes
  8319. )
  8320. {
  8321. DASSERT(db);
  8322. DASSERT(dest);
  8323. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8324. if ( min_read > db->used )
  8325. {
  8326. if ( min_read <= db->size && db->fill_func )
  8327. db->fill_func(db,min_read-db->used,0);
  8328. if ( min_read > db->used )
  8329. return 0;
  8330. }
  8331. if ( max_read > db->used )
  8332. max_read = db->used;
  8333. uint copy_len1 = db->buf_end - db->data;
  8334. if ( copy_len1 >= max_read )
  8335. memcpy(dest,db->data,max_read);
  8336. else
  8337. {
  8338. memcpy(dest,db->data,copy_len1);
  8339. memcpy((u8*)dest+copy_len1,db->buf,max_read-copy_len1);
  8340. }
  8341. return max_read;
  8342. }
  8343. ///////////////////////////////////////////////////////////////////////////////
  8344. uint GetDataBuf
  8345. (
  8346. // Copy data from buffer and remove it
  8347. // Return the number of copied bytes
  8348. DataBuf_t *db, // valid pointer to data buffer
  8349. void *dest, // destination buffer wit at least 'max_size' space
  8350. uint min_read, // return with 0 read bytes if less bytes available
  8351. uint max_read // try to read upto 'max_read' bytes
  8352. )
  8353. {
  8354. DASSERT(db);
  8355. DASSERT(dest);
  8356. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8357. if ( min_read > db->used )
  8358. {
  8359. if ( min_read <= db->size && db->fill_func )
  8360. db->fill_func(db,min_read-db->used,0);
  8361. if ( min_read > db->used )
  8362. return 0;
  8363. }
  8364. if ( max_read > db->used )
  8365. max_read = db->used;
  8366. uint copy_len1 = db->buf_end - db->data;
  8367. if ( copy_len1 >= max_read )
  8368. memcpy(dest,db->data,max_read);
  8369. else
  8370. {
  8371. memcpy(dest,db->data,copy_len1);
  8372. memcpy((u8*)dest+copy_len1,db->buf,max_read-copy_len1);
  8373. }
  8374. db->used -= max_read;
  8375. if (db->used)
  8376. {
  8377. db->data += max_read;
  8378. if ( db->data >= db->buf_end )
  8379. db->data -= db->size;
  8380. }
  8381. else
  8382. db->data = db->data_end = db->buf;
  8383. db->offset += max_read;
  8384. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8385. return max_read;
  8386. }
  8387. ///////////////////////////////////////////////////////////////////////////////
  8388. uint SkipDataBuf
  8389. (
  8390. // Skip 'skip_size' from input stream. Read more data if needed.
  8391. // Return the number of really skiped bytes
  8392. // If <skip_size is returned, no more data is available.
  8393. DataBuf_t *db, // valid pointer to data buffer
  8394. uint skip_size // number of bytes to drop
  8395. )
  8396. {
  8397. DASSERT(db);
  8398. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8399. uint skipped = 0;
  8400. for(;;)
  8401. {
  8402. uint stat = DropDataBuf(db,skip_size);
  8403. skipped += stat;
  8404. skip_size -= stat;
  8405. if (!skip_size)
  8406. break;
  8407. if (db->fill_func)
  8408. {
  8409. const uint max_fill = skip_size < db->size ? skip_size : db->size;
  8410. db->fill_func(db,max_fill,0);
  8411. }
  8412. if (!db->used)
  8413. break;
  8414. }
  8415. db->offset += skipped;
  8416. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8417. return skipped;
  8418. }
  8419. ///////////////////////////////////////////////////////////////////////////////
  8420. uint DropDataBuf
  8421. (
  8422. // Remove upto 'drop_size' bytes from buffer.
  8423. // Return the number of dropped bytes.
  8424. DataBuf_t *db, // valid pointer to data buffer
  8425. uint drop_size // number of bytes to drop
  8426. )
  8427. {
  8428. DASSERT(db);
  8429. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8430. if ( drop_size >= db->used )
  8431. {
  8432. drop_size = db->used;
  8433. db->used = 0;
  8434. db->data = db->data_end = db->buf;
  8435. }
  8436. else
  8437. {
  8438. db->data += drop_size;
  8439. if ( db->data >= db->buf_end )
  8440. db->data -= db->size;
  8441. db->used -= drop_size;
  8442. }
  8443. db->offset += drop_size;
  8444. DASSERT(!DumpDataBuf(stderr,0,db,true));
  8445. return drop_size;
  8446. }
  8447. //
  8448. ///////////////////////////////////////////////////////////////////////////////
  8449. /////////////// ResizeElement_t, ResizeHelper_t ///////////////
  8450. ///////////////////////////////////////////////////////////////////////////////
  8451. void InitializeResize
  8452. (
  8453. ResizeHelper_t *r, // data structure
  8454. uint s_size, // size of source
  8455. uint d_size // size of dest
  8456. )
  8457. {
  8458. DASSERT(r);
  8459. memset(r,0,sizeof(*r));
  8460. r->src_size = s_size;
  8461. r->dest_size= d_size;
  8462. if ( !s_size || !d_size )
  8463. return;
  8464. const uint divisor = gcd(s_size,d_size);
  8465. s_size /= divisor;
  8466. d_size /= divisor;
  8467. r->sum_factor = s_size;
  8468. r->half_factor = r->sum_factor/2;
  8469. r->idx_inc = s_size / d_size;
  8470. r->frac_inc = s_size % d_size;
  8471. r->frac_next = d_size;
  8472. }
  8473. ///////////////////////////////////////////////////////////////////////////////
  8474. static bool CalcResize ( ResizeHelper_t *r )
  8475. {
  8476. DASSERT(r);
  8477. ResizeElement_t *re = r->elem;
  8478. re[0].n_elem = re[1].n_elem = re[2].n_elem = 0;
  8479. DASSERT(!re[3].n_elem);
  8480. if ( r->src_idx >= r->src_size || r->dest_idx >= r->dest_size )
  8481. return false;
  8482. uint sum = r->sum_factor;
  8483. if (r->src_frac)
  8484. {
  8485. uint max = r->frac_next - r->src_frac;
  8486. if ( max > sum )
  8487. max = sum;
  8488. re->n_elem = 1;
  8489. re->factor = max;
  8490. re++;
  8491. sum -= max;
  8492. }
  8493. if ( sum >= r->frac_next )
  8494. {
  8495. const uint n = sum / r->frac_next;
  8496. re->n_elem = n;
  8497. re->factor = r->frac_next;
  8498. re++;
  8499. sum -= n * r->frac_next;
  8500. }
  8501. if ( sum > 0 )
  8502. {
  8503. re->n_elem = 1;
  8504. re->factor = sum;
  8505. re++;
  8506. }
  8507. return true;
  8508. }
  8509. ///////////////////////////////////////////////////////////////////////////////
  8510. bool FirstResize ( ResizeHelper_t *r )
  8511. {
  8512. DASSERT(r);
  8513. r->dest_idx = r->src_idx = r->src_frac = 0;
  8514. memset(r->elem,0,sizeof(r->elem));
  8515. return CalcResize(r);
  8516. }
  8517. ///////////////////////////////////////////////////////////////////////////////
  8518. bool NextResize ( ResizeHelper_t *r )
  8519. {
  8520. DASSERT(r);
  8521. r->dest_idx++;
  8522. r->src_idx += r->idx_inc;
  8523. r->src_frac += r->frac_inc;
  8524. if ( r->src_frac >= r->frac_next )
  8525. {
  8526. r->src_frac -= r->frac_next;
  8527. r->src_idx++;
  8528. }
  8529. return CalcResize(r);
  8530. }
  8531. //
  8532. ///////////////////////////////////////////////////////////////////////////////
  8533. /////////////// GrowBuffer_t ///////////////
  8534. ///////////////////////////////////////////////////////////////////////////////
  8535. static const uint grow_buffer_size_factor = 0x100;
  8536. ///////////////////////////////////////////////////////////////////////////////
  8537. void InitializeGrowBuffer ( GrowBuffer_t *gb, uint max_buf_size )
  8538. {
  8539. DASSERT(gb);
  8540. memset(gb,0,sizeof(*gb));
  8541. gb->grow_size = grow_buffer_size_factor;
  8542. gb->max_size = ( max_buf_size + grow_buffer_size_factor - 1 )
  8543. / grow_buffer_size_factor * grow_buffer_size_factor;
  8544. }
  8545. ///////////////////////////////////////////////////////////////////////////////
  8546. void ResetGrowBuffer ( GrowBuffer_t *gb )
  8547. {
  8548. DASSERT(gb);
  8549. FREE(gb->buf);
  8550. const uint grow_size = gb->grow_size;
  8551. InitializeGrowBuffer(gb,gb->max_size);
  8552. gb->grow_size = grow_size;
  8553. }
  8554. ///////////////////////////////////////////////////////////////////////////////
  8555. uint GetSpaceGrowBuffer
  8556. (
  8557. // returns the maximal possible space
  8558. const GrowBuffer_t *gb // valid grow-buffer object
  8559. )
  8560. {
  8561. DASSERT(gb);
  8562. const uint max = gb->max_size > gb->size ? gb->max_size : gb->size;
  8563. return max - gb->used;
  8564. }
  8565. ///////////////////////////////////////////////////////////////////////////////
  8566. uint PrepareGrowBuffer
  8567. (
  8568. // returns the number of available space, smaller than or equal 'size'
  8569. GrowBuffer_t *gb, // valid grow-buffer object
  8570. uint size, // needed size
  8571. bool force // always alloc enough space and return 'size'
  8572. )
  8573. {
  8574. #if HAVE_DASSERT
  8575. DASSERT(gb);
  8576. if (gb->buf)
  8577. {
  8578. DASSERT( gb->used <= gb->size );
  8579. DASSERT( gb->ptr >= gb->buf );
  8580. DASSERT( gb->ptr + gb->used <= gb->buf + gb->size );
  8581. }
  8582. else
  8583. {
  8584. DASSERT(!gb->ptr);
  8585. DASSERT(!gb->size);
  8586. DASSERT(!gb->used);
  8587. }
  8588. #endif
  8589. if (!gb->buf)
  8590. {
  8591. //--- initial setup of buffer
  8592. if ( gb->grow_size < grow_buffer_size_factor )
  8593. gb->grow_size = grow_buffer_size_factor;
  8594. else
  8595. gb->grow_size = gb->grow_size
  8596. / grow_buffer_size_factor * grow_buffer_size_factor;
  8597. gb->size = ( size / gb->grow_size + 1 ) * gb->grow_size;
  8598. if ( gb->max_size < grow_buffer_size_factor )
  8599. gb->max_size = grow_buffer_size_factor;
  8600. else
  8601. gb->max_size = gb->max_size
  8602. / grow_buffer_size_factor * grow_buffer_size_factor;
  8603. if ( gb->size > gb->max_size )
  8604. gb->size = gb->max_size;
  8605. if ( gb->size < size && force )
  8606. gb->size = ( size + gb->grow_size )
  8607. / gb->grow_size * gb->grow_size - 1;
  8608. gb->buf = gb->ptr = MALLOC(gb->size+1); // 1 extra byte for NULL-TERM
  8609. gb->used = 0;
  8610. }
  8611. else
  8612. {
  8613. if (!gb->grow_size)
  8614. gb->grow_size = grow_buffer_size_factor;
  8615. if (!gb->used)
  8616. gb->ptr = gb->buf;
  8617. }
  8618. DASSERT(gb->grow_size);
  8619. uint avail = gb->size - gb->used;
  8620. if ( size > avail && ( force || gb->size < gb->max_size ) )
  8621. {
  8622. //--- grow buffer
  8623. gb->size = ( size + gb->used + gb->grow_size )
  8624. / gb->grow_size * gb->grow_size - 1;
  8625. DASSERT( gb->used <= gb->size );
  8626. u8 *newbuf = MALLOC(gb->size+1); // 1 extra byte for NULL-TERM
  8627. memcpy(newbuf,gb->ptr,gb->used);
  8628. FREE(gb->buf);
  8629. gb->buf = gb->ptr = newbuf;
  8630. }
  8631. uint space = ( gb->buf + gb->size ) - ( gb->ptr + gb->used );
  8632. if ( space < size && gb->buf != gb->ptr )
  8633. {
  8634. memmove(gb->buf,gb->ptr,gb->used);
  8635. gb->ptr = gb->buf;
  8636. space = gb->size - gb->used;
  8637. }
  8638. DASSERT( gb->used <= gb->size );
  8639. DASSERT( gb->ptr >= gb->buf );
  8640. DASSERT( gb->ptr + gb->used <= gb->buf + gb->size );
  8641. return size < space ? size : space;
  8642. }
  8643. ///////////////////////////////////////////////////////////////////////////////
  8644. uint InsertGrowBuffer
  8645. (
  8646. // returns the number of inserted bytes
  8647. GrowBuffer_t *gb, // valid grow-buffer object
  8648. const void *data, // data to insert
  8649. uint size // size of 'data'
  8650. )
  8651. {
  8652. DASSERT(gb);
  8653. size = PrepareGrowBuffer(gb,size,false);
  8654. DASSERT( gb->ptr + gb->used + size <= gb->buf + gb->size );
  8655. memcpy( gb->ptr + gb->used, data, size );
  8656. gb->used += size;
  8657. gb->ptr[gb->used] = 0;
  8658. if ( gb->max_used < gb->used )
  8659. gb->max_used = gb->used;
  8660. DASSERT( gb->used <= gb->size );
  8661. DASSERT( gb->ptr >= gb->buf );
  8662. DASSERT( gb->ptr + gb->used <= gb->buf + gb->size );
  8663. return size;
  8664. }
  8665. ///////////////////////////////////////////////////////////////////////////////
  8666. char *tiparm ( ccp str, ... );
  8667. uint InsertCapNGrowBuffer
  8668. (
  8669. // insert 'cap_1' or 'cap_n' depending of 'n' and the existence of 'cap_*'
  8670. // returns the number of inserted bytes
  8671. GrowBuffer_t *gb, // valid grow-buffer object
  8672. int n, // repeat number; if <1: insert nothing
  8673. mem_t cap_1, // default for N=1
  8674. mem_t cap_n // default for N>1
  8675. )
  8676. {
  8677. DASSERT(gb);
  8678. if ( n <= 0 )
  8679. return 0;
  8680. if ( n == 1 && cap_1.len )
  8681. return InsertMemGrowBuffer(gb,cap_1);
  8682. #if DCLIB_TERMINAL
  8683. if (cap_n.len)
  8684. {
  8685. ccp str = tiparm(cap_n.ptr,n);
  8686. if (str)
  8687. return InsertGrowBuffer(gb,str,strlen(str));
  8688. }
  8689. #endif
  8690. if (!cap_1.len)
  8691. return 0;
  8692. const uint total = cap_1.len * n;
  8693. PrepareGrowBuffer(gb,total,true);
  8694. u8 *ptr = gb->ptr + gb->used;
  8695. while ( n-- > 0 )
  8696. {
  8697. memcpy(ptr,cap_1.ptr,cap_1.len);
  8698. ptr += cap_1.len;
  8699. }
  8700. gb->used += total;
  8701. gb->ptr[gb->used] = 0;
  8702. if ( gb->max_used < gb->used )
  8703. gb->max_used = gb->used;
  8704. return total;
  8705. }
  8706. ///////////////////////////////////////////////////////////////////////////////
  8707. uint WriteCapN
  8708. (
  8709. // print 'cap_1' or 'cap_n' depending of 'n' and the existence of 'cap_*'
  8710. // returns the number of printed bytes
  8711. FILE *f, // valid FILE
  8712. int n, // repeat number; if <1: insert nothing
  8713. mem_t cap_1, // default for N=1
  8714. mem_t cap_n // default for N>1
  8715. )
  8716. {
  8717. DASSERT(f);
  8718. if ( n <= 0 )
  8719. return 0;
  8720. if ( n == 1 && cap_1.len )
  8721. return fwrite(cap_1.ptr,cap_1.len,1,f);
  8722. #if DCLIB_TERMINAL
  8723. if (cap_n.len)
  8724. {
  8725. ccp str = tiparm(cap_n.ptr,n);
  8726. if (str)
  8727. return fwrite(str,strlen(str),1,f);
  8728. }
  8729. #endif
  8730. if (!cap_1.len)
  8731. return 0;
  8732. const uint total = cap_1.len * n;
  8733. while ( n-- > 0 )
  8734. fwrite(cap_1.ptr,cap_1.len,1,f);
  8735. return total;
  8736. }
  8737. ///////////////////////////////////////////////////////////////////////////////
  8738. uint InsertCatchedGrowBuffer
  8739. (
  8740. // returns the number of inserted bytes
  8741. GrowBuffer_t *gb, // valid grow-buffer object
  8742. SavedStdFiles_t *ssf // saved output and catched data
  8743. )
  8744. {
  8745. DASSERT(gb);
  8746. DASSERT(ssf);
  8747. TermCatchStdFiles(ssf);
  8748. uint stat = 0;
  8749. if (ssf->data)
  8750. {
  8751. PrepareGrowBuffer(gb,ssf->size,true);
  8752. stat = InsertGrowBuffer(gb,ssf->data,ssf->size);
  8753. XFREE(ssf->data);
  8754. ssf->data = 0;
  8755. ssf->size = 0;
  8756. }
  8757. return stat;
  8758. }
  8759. //
  8760. ///////////////////////////////////////////////////////////////////////////////
  8761. ///////////////////////////////////////////////////////////////////////////////
  8762. uint PrintArgGrowBuffer
  8763. (
  8764. // returns the number of inserted bytes
  8765. GrowBuffer_t *gb, // valid grow-buffer object
  8766. ccp format, // format string for vfprintf()
  8767. va_list arg // parameters for 'format'
  8768. )
  8769. {
  8770. DASSERT(gb);
  8771. DASSERT(format);
  8772. char buf[10000];
  8773. va_list arg2;
  8774. va_copy(arg2,arg);
  8775. int stat = vsnprintf(buf,sizeof(buf),format,arg2);
  8776. va_end(arg2);
  8777. if ( stat < sizeof(buf) )
  8778. return InsertGrowBuffer(gb,buf,stat);
  8779. //--- buffer too small, use dynamic memory
  8780. noPRINT("PrintArgGrowBuffer() -> MALLOC(%u)\n",stat+1);
  8781. char *dest = MALLOC(stat+1);
  8782. stat = vsnprintf(dest,stat+1,format,arg);
  8783. const uint res = InsertGrowBuffer(gb,dest,stat);
  8784. FREE(dest);
  8785. return res;
  8786. }
  8787. ///////////////////////////////////////////////////////////////////////////////
  8788. uint PrintGrowBuffer
  8789. (
  8790. // returns the number of inserted bytes
  8791. GrowBuffer_t *gb, // valid grow-buffer object
  8792. ccp format, // format string for vfprintf()
  8793. ... // arguments for 'vsnprintf(format,...)'
  8794. )
  8795. {
  8796. DASSERT(gb);
  8797. DASSERT(format);
  8798. va_list arg;
  8799. va_start(arg,format);
  8800. enumError err = PrintArgGrowBuffer(gb,format,arg);
  8801. va_end(arg);
  8802. return err;
  8803. }
  8804. ///////////////////////////////////////////////////////////////////////////////
  8805. uint ConvertToCrLfGrowBuffer
  8806. (
  8807. // returns the number of inserted CR bytes
  8808. GrowBuffer_t *gb, // valid grow-buffer object
  8809. uint begin // index to begin with conversion
  8810. )
  8811. {
  8812. DASSERT(gb);
  8813. uint count = 0;
  8814. if ( begin < gb->used )
  8815. {
  8816. //--- count LF without CR
  8817. u8 *ptr = gb->ptr + begin;
  8818. u8 *end = gb->ptr + gb->used;
  8819. for ( ; ptr < end; ptr++ )
  8820. {
  8821. if ( *ptr == '\r' )
  8822. ptr++;
  8823. else if ( *ptr == '\n' )
  8824. count++;
  8825. }
  8826. if ( count > 0 )
  8827. {
  8828. PrepareGrowBuffer(gb,count,true);
  8829. u8 *src = gb->ptr + gb->used;
  8830. u8 *dest = src + count;
  8831. u8 *beg = gb->ptr + begin;
  8832. while ( src > beg )
  8833. {
  8834. const char ch = *--src;
  8835. *--dest = ch;
  8836. if ( ch == '\n' && src[-1] != '\r' )
  8837. *--dest = '\r';
  8838. }
  8839. DASSERT( src == dest );
  8840. gb->used += count;
  8841. gb->ptr[gb->used] = 0;
  8842. if ( gb->max_used < gb->used )
  8843. gb->max_used = gb->used;
  8844. }
  8845. }
  8846. return count;
  8847. }
  8848. ///////////////////////////////////////////////////////////////////////////////
  8849. uint ClearGrowBuffer ( GrowBuffer_t *gb )
  8850. {
  8851. DASSERT(gb);
  8852. gb->ptr = gb->buf;
  8853. if (gb->ptr)
  8854. *gb->ptr = 0;
  8855. gb->used = 0;
  8856. return gb->size;
  8857. }
  8858. ///////////////////////////////////////////////////////////////////////////////
  8859. uint PurgeGrowBuffer ( GrowBuffer_t *gb )
  8860. {
  8861. if (!gb->used)
  8862. return ClearGrowBuffer(gb);
  8863. if ( gb->ptr > gb->buf )
  8864. {
  8865. memmove(gb->buf,gb->ptr,gb->used);
  8866. gb->ptr = gb->buf;
  8867. }
  8868. return gb->size - gb->used;
  8869. }
  8870. ///////////////////////////////////////////////////////////////////////////////
  8871. uint DropGrowBuffer
  8872. (
  8873. // returns the number of dropped bytes
  8874. GrowBuffer_t *gb, // valid grow-buffer object
  8875. uint size // number of bytes to drop
  8876. )
  8877. {
  8878. #if HAVE_DASSERT
  8879. DASSERT(gb);
  8880. if (gb->buf)
  8881. {
  8882. DASSERT_MSG( gb->used < gb->size, "%d/%d\n",gb->used,gb->size);
  8883. DASSERT( gb->ptr >= gb->buf );
  8884. DASSERT( gb->ptr + gb->used <= gb->buf + gb->size );
  8885. }
  8886. else
  8887. {
  8888. DASSERT(!gb->ptr);
  8889. DASSERT(!gb->size);
  8890. DASSERT(!gb->used);
  8891. }
  8892. #endif
  8893. if (!gb->buf)
  8894. return 0;
  8895. if ( size >= gb->used )
  8896. {
  8897. size = gb->used;
  8898. gb->used = 0;
  8899. gb->ptr = gb->buf;
  8900. *gb->ptr = 0;
  8901. return size;
  8902. }
  8903. gb->ptr += size;
  8904. gb->used -= size;
  8905. return size;
  8906. }
  8907. ///////////////////////////////////////////////////////////////////////////////
  8908. ///////////////////////////////////////////////////////////////////////////////
  8909. void LogGrowBuffer
  8910. (
  8911. FILE *f, // output file
  8912. int indent, // indention
  8913. const GrowBuffer_t *gb, // valid grow-buffer
  8914. ccp format, // format string for vfprintf()
  8915. ... // arguments for 'vfprintf(format,...)'
  8916. )
  8917. {
  8918. DASSERT(f);
  8919. DASSERT(gb);
  8920. indent = NormalizeIndent(indent);
  8921. fprintf(f,"%*sTB: size=%s/%s/%s idx=%s grow=%s/%s disabled=%d",
  8922. indent,"",
  8923. PrintSize1024(0,0,gb->used,DC_SFORM_TINY|DC_SFORM_ALIGN),
  8924. PrintSize1024(0,0,gb->max_used,DC_SFORM_TINY|DC_SFORM_ALIGN),
  8925. PrintSize1024(0,0,gb->size,DC_SFORM_TINY|DC_SFORM_ALIGN),
  8926. PrintNumberU6(0,0,gb->ptr-gb->buf,DC_SFORM_ALIGN),
  8927. PrintSize1024(0,0,gb->grow_size,DC_SFORM_TINY|DC_SFORM_ALIGN),
  8928. PrintSize1024(0,0,gb->max_size,DC_SFORM_TINY|DC_SFORM_ALIGN),
  8929. gb->disabled );
  8930. if (format)
  8931. {
  8932. fputs(" : ",f);
  8933. va_list arg;
  8934. va_start(arg,format);
  8935. vfprintf(f,format,arg);
  8936. va_end(arg);
  8937. }
  8938. fputc('\n',f);
  8939. }
  8940. ///////////////////////////////////////////////////////////////////////////////
  8941. ///////////////////////////////////////////////////////////////////////////////
  8942. #ifndef __APPLE__
  8943. FILE * OpenFileGrowBuffer
  8944. (
  8945. // returns a FILE opened by fmemopen() => call CloseFileGrowBuffer()
  8946. GrowBuffer_t *gb, // valid grow-buffer object
  8947. uint size // needed size
  8948. )
  8949. {
  8950. DASSERT(gb);
  8951. uint space = PurgeGrowBuffer(gb);
  8952. if ( space < size )
  8953. space = PrepareGrowBuffer(gb,size,true);
  8954. return fmemopen( gb->ptr + gb->used, space, "w" );
  8955. }
  8956. ///////////////////////////////////////////////////////////////////////////////
  8957. int CloseFileGrowBuffer
  8958. (
  8959. // returns the number of wirtten bytes, or -1 on error
  8960. GrowBuffer_t *gb, // valid grow-buffer object
  8961. FILE *f // FILE returned by OpenFileGrowBuffer()
  8962. )
  8963. {
  8964. DASSERT(gb);
  8965. if (!f)
  8966. return -1;
  8967. const int stat = ftell(f);
  8968. if ( stat >= 0 && gb->ptr + gb->used + stat <= gb->buf + gb->size )
  8969. gb->used += stat;
  8970. fclose(f);
  8971. return stat;
  8972. }
  8973. #endif // !__APPLE__
  8974. ///////////////////////////////////////////////////////////////////////////////
  8975. ///////////////////////////////////////////////////////////////////////////////
  8976. #define GROW_BUFFER_CHUNK_SIZE 3*1024 // multiple of 3 because of BASE64 (3->4)
  8977. void SaveCurrentStateGrowBuffer
  8978. (
  8979. FILE *f, // output file
  8980. ccp name_prefix, // NULL or prefix of name
  8981. uint tab_pos, // tab pos of '='
  8982. const GrowBuffer_t *gb // valid grow-buffer
  8983. )
  8984. {
  8985. DASSERT(f);
  8986. DASSERT(gb);
  8987. if (!name_prefix)
  8988. name_prefix = EmptyString;
  8989. const int base = 8*tab_pos + 7 - strlen(name_prefix);
  8990. fprintf(f,
  8991. "%s" "disabled%.*s= %u\n"
  8992. "%s" "used%.*s= %u\n"
  8993. "%s" "size%.*s= %u\n"
  8994. "%s" "grow-size%.*s= %u\n"
  8995. "%s" "max-size%.*s= %u\n"
  8996. ,name_prefix, (base-8)/8, Tabs20, gb->disabled
  8997. ,name_prefix, (base-4)/8, Tabs20, gb->used
  8998. ,name_prefix, (base-4)/8, Tabs20, gb->size
  8999. ,name_prefix, (base-9)/8, Tabs20, gb->grow_size
  9000. ,name_prefix, (base-8)/8, Tabs20, gb->max_size
  9001. );
  9002. char buf[4*GROW_BUFFER_CHUNK_SIZE/3+10], name[20];
  9003. uint start,i;
  9004. for ( start = i = 0; start < gb->used; i++ )
  9005. {
  9006. uint size = gb->used - start;
  9007. if ( size > GROW_BUFFER_CHUNK_SIZE )
  9008. size = GROW_BUFFER_CHUNK_SIZE;
  9009. const uint len = snprintf(name,sizeof(name),"data-%u",i);
  9010. EncodeBase64(buf,sizeof(buf),(ccp)gb->ptr+start,size,0,true,0,0);
  9011. fprintf(f, "%s%s%.*s= %s\n",
  9012. name_prefix, name, (base-len)/8, Tabs20, buf );
  9013. start += size;
  9014. }
  9015. }
  9016. ///////////////////////////////////////////////////////////////////////////////
  9017. void RestoreStateGrowBuffer
  9018. (
  9019. GrowBuffer_t *gb, // valid grow-buffer
  9020. ccp name_prefix, // NULL or prefix of name
  9021. RestoreState_t *rs // info data, can be modified (cleaned after call)
  9022. )
  9023. {
  9024. DASSERT(gb);
  9025. DASSERT(rs);
  9026. ResetGrowBuffer(gb);
  9027. if (!name_prefix)
  9028. name_prefix = EmptyString;
  9029. char name[200]; // name buf
  9030. snprintf(name,sizeof(name),"%sused",name_prefix);
  9031. int size = GetParamFieldUINT(rs,name,0);
  9032. snprintf(name,sizeof(name),"%sdisabled",name_prefix);
  9033. gb->disabled = GetParamFieldINT(rs,name,gb->disabled) > 0;
  9034. if ( size > 0 )
  9035. {
  9036. char buf[2*GROW_BUFFER_CHUNK_SIZE];
  9037. PrepareGrowBuffer(gb,size,true);
  9038. uint index = 0;
  9039. while ( size > 0 )
  9040. {
  9041. snprintf(name,sizeof(name),"%sdata-%u",name_prefix,index++);
  9042. int res = GetParamFieldBUF(buf,sizeof(buf),rs,name,ENCODE_BASE64URL,0);
  9043. if ( res < 0 )
  9044. break;
  9045. InsertGrowBuffer(gb,buf,res);
  9046. size -= res;
  9047. }
  9048. #ifdef TEST0
  9049. if ( gb->used > 10000 )
  9050. {
  9051. fprintf(stderr,"--- ResetGrowBuffer() size = %d\n",gb->used);
  9052. fwrite(gb->ptr,1,gb->used,stderr);
  9053. fprintf(stderr,"--- ResetGrowBuffer() size = %d\n",gb->used);
  9054. }
  9055. #endif
  9056. }
  9057. //--- known as 'unused'
  9058. if ( rs->log_mode & RSL_UNUSED_NAMES )
  9059. {
  9060. static ccp name_tab[] =
  9061. {
  9062. "size",
  9063. "grow-size",
  9064. "max-size",
  9065. 0
  9066. };
  9067. ccp *np;
  9068. for ( np = name_tab; *np; np++ )
  9069. {
  9070. StringCat2S(name,sizeof(name),name_prefix,*np);
  9071. GetParamField(rs,name);
  9072. }
  9073. }
  9074. }
  9075. //
  9076. ///////////////////////////////////////////////////////////////////////////////
  9077. /////////////// misc ///////////////
  9078. ///////////////////////////////////////////////////////////////////////////////
  9079. int opt_new = 0;
  9080. ///////////////////////////////////////////////////////////////////////////////
  9081. ccp GetIpModeName ( IpMode_t ipm )
  9082. {
  9083. switch (ipm)
  9084. {
  9085. case IPV4_ONLY: return "IPv4 only";
  9086. case IPV6_ONLY: return "IPv6 only";
  9087. case IPV4_FIRST: return "IPv4 first";
  9088. case IPV6_FIRST: return "IPv6 first";
  9089. }
  9090. return 0;
  9091. }
  9092. ///////////////////////////////////////////////////////////////////////////////
  9093. ipv4_t GetIP4Mask ( int bits )
  9094. {
  9095. return bits > 0 && bits < 32
  9096. ? htonl( 0xffffffffu << (32-bits) )
  9097. : bits ? 0xffffffffu : 0;
  9098. }
  9099. ///////////////////////////////////////////////////////////////////////////////
  9100. ipv6_t GetIP6Mask ( int bits )
  9101. {
  9102. ipv6_t ip6;
  9103. memset(&ip6,~0,sizeof(ip6));
  9104. if ( bits >= 0 && bits < 128 )
  9105. {
  9106. int idx = bits/32;
  9107. bits -= idx*32;
  9108. const u32 mask = htonl( bits ? 0xffffffffu << (32-bits) : 0 );
  9109. ip6.v32[idx++] &= mask;
  9110. while ( idx < 4 )
  9111. ip6.v32[idx++] = 0;
  9112. }
  9113. return ip6;
  9114. }
  9115. ///////////////////////////////////////////////////////////////////////////////
  9116. int GetBitsByMask4 ( ipv4_t ip4_nbo )
  9117. {
  9118. const int res = FindHighest0BitBE(&ip4_nbo,4);
  9119. return 31-res;
  9120. }
  9121. ///////////////////////////////////////////////////////////////////////////////
  9122. int GetBitsByMask6 ( ipv6_t ip6_nbo )
  9123. {
  9124. const int res = FindHighest0BitBE(&ip6_nbo,16);
  9125. return 127-res;
  9126. }
  9127. ///////////////////////////////////////////////////////////////////////////////
  9128. int GetBitsBySA ( sockaddr_t *sa, int return_on_error )
  9129. {
  9130. if (sa)
  9131. {
  9132. if ( sa->sa_family == AF_INET )
  9133. {
  9134. sockaddr_in4_t *sa4 = (sockaddr_in4_t*)sa;
  9135. return GetBitsByMask4(sa4->sin_addr.s_addr);
  9136. }
  9137. if ( sa->sa_family == AF_INET6 )
  9138. {
  9139. sockaddr_in6_t *sa6 = (sockaddr_in6_t*)sa;
  9140. return GetBitsByMask6(*(ipv6_t*)&sa6->sin6_addr);
  9141. }
  9142. }
  9143. return return_on_error;
  9144. }
  9145. ///////////////////////////////////////////////////////////////////////////////
  9146. uint CreateUniqueIdN ( int range )
  9147. {
  9148. static uint unique_id = 1;
  9149. if ( range <= 0 )
  9150. return unique_id;
  9151. uint ret = unique_id;
  9152. unique_id += range;
  9153. if ( unique_id < ret ) // overflow
  9154. {
  9155. ret = 1;
  9156. unique_id = ret + range;
  9157. }
  9158. return ret;
  9159. }
  9160. ///////////////////////////////////////////////////////////////////////////////
  9161. void Sha1Hex2Bin ( sha1_hash_t bin, ccp src, ccp end )
  9162. {
  9163. DASSERT(bin);
  9164. DASSERT(src);
  9165. uint i;
  9166. for ( i = 0; i < 20; i++ )
  9167. bin[i] = ScanDigits(&src,end,16,2,0);
  9168. }
  9169. //-----------------------------------------------------------------------------
  9170. void Sha1Bin2Hex ( sha1_hex_t hex, cvp bin )
  9171. {
  9172. DASSERT(hex);
  9173. DASSERT(bin);
  9174. snprintf(hex,sizeof(sha1_hex_t),"%08x%08x%08x%08x%08x",
  9175. be32(bin), be32(bin+4), be32(bin+8), be32(bin+12), be32(bin+16) );
  9176. }
  9177. //-----------------------------------------------------------------------------
  9178. ccp GetSha1Hex ( cvp bin )
  9179. {
  9180. DASSERT(bin);
  9181. char *hex = GetCircBuf(sizeof(sha1_hex_t));
  9182. Sha1Bin2Hex(hex,bin);
  9183. return hex;
  9184. }
  9185. ///////////////////////////////////////////////////////////////////////////////
  9186. void * dc_memrchr ( cvp src, int ch, size_t size )
  9187. {
  9188. if ( !src || !size )
  9189. return 0;
  9190. ccp ptr = src + size;
  9191. while ( ptr > (ccp)src )
  9192. if ( *--ptr == ch )
  9193. return (void*)ptr;
  9194. return 0;
  9195. }
  9196. ///////////////////////////////////////////////////////////////////////////////
  9197. bool IsMemConst ( cvp mem, uint size, u8 val )
  9198. {
  9199. if (!size)
  9200. return true;
  9201. const u8 *src = (u8*)mem;
  9202. return *src == val && !memcmp(src,src+1,size-1);
  9203. }
  9204. //
  9205. ///////////////////////////////////////////////////////////////////////////////
  9206. /////////////// END ///////////////
  9207. ///////////////////////////////////////////////////////////////////////////////