vsprintf.c 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * linux/lib/vsprintf.c
  4. *
  5. * Copyright (C) 1991, 1992 Linus Torvalds
  6. */
  7. /* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */
  8. /*
  9. * Wirzenius wrote this portably, Torvalds fucked it up :-)
  10. */
  11. /*
  12. * Fri Jul 13 2001 Crutcher Dunnavant <crutcher+kernel@datastacks.com>
  13. * - changed to provide snprintf and vsnprintf functions
  14. * So Feb 1 16:51:32 CET 2004 Juergen Quade <quade@hsnr.de>
  15. * - scnprintf and vscnprintf
  16. */
  17. #include <linux/stdarg.h>
  18. #include <linux/build_bug.h>
  19. #include <linux/clk.h>
  20. #include <linux/clk-provider.h>
  21. #include <linux/errname.h>
  22. #include <linux/module.h> /* for KSYM_SYMBOL_LEN */
  23. #include <linux/types.h>
  24. #include <linux/string.h>
  25. #include <linux/ctype.h>
  26. #include <linux/hex.h>
  27. #include <linux/kernel.h>
  28. #include <linux/kallsyms.h>
  29. #include <linux/math64.h>
  30. #include <linux/uaccess.h>
  31. #include <linux/ioport.h>
  32. #include <linux/dcache.h>
  33. #include <linux/cred.h>
  34. #include <linux/rtc.h>
  35. #include <linux/sprintf.h>
  36. #include <linux/time.h>
  37. #include <linux/uuid.h>
  38. #include <linux/of.h>
  39. #include <net/addrconf.h>
  40. #include <linux/siphash.h>
  41. #include <linux/compiler.h>
  42. #include <linux/property.h>
  43. #include <linux/notifier.h>
  44. #ifdef CONFIG_BLOCK
  45. #include <linux/blkdev.h>
  46. #endif
  47. #include "../mm/internal.h" /* For the trace_print_flags arrays */
  48. #include <asm/page.h> /* for PAGE_SIZE */
  49. #include <asm/byteorder.h> /* cpu_to_le16 */
  50. #include <linux/unaligned.h>
  51. #include <linux/string_helpers.h>
  52. #include "kstrtox.h"
  53. /* Disable pointer hashing if requested */
  54. bool no_hash_pointers __ro_after_init;
  55. EXPORT_SYMBOL_GPL(no_hash_pointers);
  56. /*
  57. * Hashed pointers policy selected by "hash_pointers=..." boot param
  58. *
  59. * `auto` - Hashed pointers enabled unless disabled by slub_debug_enabled=true
  60. * `always` - Hashed pointers enabled unconditionally
  61. * `never` - Hashed pointers disabled unconditionally
  62. */
  63. enum hash_pointers_policy {
  64. HASH_PTR_AUTO = 0,
  65. HASH_PTR_ALWAYS,
  66. HASH_PTR_NEVER
  67. };
  68. static enum hash_pointers_policy hash_pointers_mode __initdata;
  69. noinline
  70. static unsigned long long simple_strntoull(const char *startp, char **endp, unsigned int base, size_t max_chars)
  71. {
  72. const char *cp;
  73. unsigned long long result = 0ULL;
  74. size_t prefix_chars;
  75. unsigned int rv;
  76. cp = _parse_integer_fixup_radix(startp, &base);
  77. prefix_chars = cp - startp;
  78. if (prefix_chars < max_chars) {
  79. rv = _parse_integer_limit(cp, base, &result, max_chars - prefix_chars);
  80. /* FIXME */
  81. cp += (rv & ~KSTRTOX_OVERFLOW);
  82. } else {
  83. /* Field too short for prefix + digit, skip over without converting */
  84. cp = startp + max_chars;
  85. }
  86. if (endp)
  87. *endp = (char *)cp;
  88. return result;
  89. }
  90. /**
  91. * simple_strtoull - convert a string to an unsigned long long
  92. * @cp: The start of the string
  93. * @endp: A pointer to the end of the parsed string will be placed here
  94. * @base: The number base to use
  95. *
  96. * This function has caveats. Please use kstrtoull instead.
  97. */
  98. noinline
  99. unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
  100. {
  101. return simple_strntoull(cp, endp, base, INT_MAX);
  102. }
  103. EXPORT_SYMBOL(simple_strtoull);
  104. /**
  105. * simple_strtoul - convert a string to an unsigned long
  106. * @cp: The start of the string
  107. * @endp: A pointer to the end of the parsed string will be placed here
  108. * @base: The number base to use
  109. *
  110. * This function has caveats. Please use kstrtoul instead.
  111. */
  112. unsigned long simple_strtoul(const char *cp, char **endp, unsigned int base)
  113. {
  114. return simple_strtoull(cp, endp, base);
  115. }
  116. EXPORT_SYMBOL(simple_strtoul);
  117. unsigned long simple_strntoul(const char *cp, char **endp, unsigned int base,
  118. size_t max_chars)
  119. {
  120. return simple_strntoull(cp, endp, base, max_chars);
  121. }
  122. EXPORT_SYMBOL(simple_strntoul);
  123. /**
  124. * simple_strtol - convert a string to a signed long
  125. * @cp: The start of the string
  126. * @endp: A pointer to the end of the parsed string will be placed here
  127. * @base: The number base to use
  128. *
  129. * This function has caveats. Please use kstrtol instead.
  130. */
  131. long simple_strtol(const char *cp, char **endp, unsigned int base)
  132. {
  133. if (*cp == '-')
  134. return -simple_strtoul(cp + 1, endp, base);
  135. return simple_strtoul(cp, endp, base);
  136. }
  137. EXPORT_SYMBOL(simple_strtol);
  138. noinline
  139. static long long simple_strntoll(const char *cp, char **endp, unsigned int base, size_t max_chars)
  140. {
  141. /*
  142. * simple_strntoull() safely handles receiving max_chars==0 in the
  143. * case cp[0] == '-' && max_chars == 1.
  144. * If max_chars == 0 we can drop through and pass it to simple_strntoull()
  145. * and the content of *cp is irrelevant.
  146. */
  147. if (*cp == '-' && max_chars > 0)
  148. return -simple_strntoull(cp + 1, endp, base, max_chars - 1);
  149. return simple_strntoull(cp, endp, base, max_chars);
  150. }
  151. /**
  152. * simple_strtoll - convert a string to a signed long long
  153. * @cp: The start of the string
  154. * @endp: A pointer to the end of the parsed string will be placed here
  155. * @base: The number base to use
  156. *
  157. * This function has caveats. Please use kstrtoll instead.
  158. */
  159. long long simple_strtoll(const char *cp, char **endp, unsigned int base)
  160. {
  161. return simple_strntoll(cp, endp, base, INT_MAX);
  162. }
  163. EXPORT_SYMBOL(simple_strtoll);
  164. static inline int skip_atoi(const char **s)
  165. {
  166. int i = 0;
  167. do {
  168. i = i*10 + *((*s)++) - '0';
  169. } while (isdigit(**s));
  170. return i;
  171. }
  172. /*
  173. * Decimal conversion is by far the most typical, and is used for
  174. * /proc and /sys data. This directly impacts e.g. top performance
  175. * with many processes running. We optimize it for speed by emitting
  176. * two characters at a time, using a 200 byte lookup table. This
  177. * roughly halves the number of multiplications compared to computing
  178. * the digits one at a time. Implementation strongly inspired by the
  179. * previous version, which in turn used ideas described at
  180. * <http://www.cs.uiowa.edu/~jones/bcd/divide.html> (with permission
  181. * from the author, Douglas W. Jones).
  182. *
  183. * It turns out there is precisely one 26 bit fixed-point
  184. * approximation a of 64/100 for which x/100 == (x * (u64)a) >> 32
  185. * holds for all x in [0, 10^8-1], namely a = 0x28f5c29. The actual
  186. * range happens to be somewhat larger (x <= 1073741898), but that's
  187. * irrelevant for our purpose.
  188. *
  189. * For dividing a number in the range [10^4, 10^6-1] by 100, we still
  190. * need a 32x32->64 bit multiply, so we simply use the same constant.
  191. *
  192. * For dividing a number in the range [100, 10^4-1] by 100, there are
  193. * several options. The simplest is (x * 0x147b) >> 19, which is valid
  194. * for all x <= 43698.
  195. */
  196. static const u16 decpair[100] = {
  197. #define _(x) (__force u16) cpu_to_le16(((x % 10) | ((x / 10) << 8)) + 0x3030)
  198. _( 0), _( 1), _( 2), _( 3), _( 4), _( 5), _( 6), _( 7), _( 8), _( 9),
  199. _(10), _(11), _(12), _(13), _(14), _(15), _(16), _(17), _(18), _(19),
  200. _(20), _(21), _(22), _(23), _(24), _(25), _(26), _(27), _(28), _(29),
  201. _(30), _(31), _(32), _(33), _(34), _(35), _(36), _(37), _(38), _(39),
  202. _(40), _(41), _(42), _(43), _(44), _(45), _(46), _(47), _(48), _(49),
  203. _(50), _(51), _(52), _(53), _(54), _(55), _(56), _(57), _(58), _(59),
  204. _(60), _(61), _(62), _(63), _(64), _(65), _(66), _(67), _(68), _(69),
  205. _(70), _(71), _(72), _(73), _(74), _(75), _(76), _(77), _(78), _(79),
  206. _(80), _(81), _(82), _(83), _(84), _(85), _(86), _(87), _(88), _(89),
  207. _(90), _(91), _(92), _(93), _(94), _(95), _(96), _(97), _(98), _(99),
  208. #undef _
  209. };
  210. /*
  211. * This will print a single '0' even if r == 0, since we would
  212. * immediately jump to out_r where two 0s would be written but only
  213. * one of them accounted for in buf. This is needed by ip4_string
  214. * below. All other callers pass a non-zero value of r.
  215. */
  216. static noinline_for_stack
  217. char *put_dec_trunc8(char *buf, unsigned r)
  218. {
  219. unsigned q;
  220. /* 1 <= r < 10^8 */
  221. if (r < 100)
  222. goto out_r;
  223. /* 100 <= r < 10^8 */
  224. q = (r * (u64)0x28f5c29) >> 32;
  225. *((u16 *)buf) = decpair[r - 100*q];
  226. buf += 2;
  227. /* 1 <= q < 10^6 */
  228. if (q < 100)
  229. goto out_q;
  230. /* 100 <= q < 10^6 */
  231. r = (q * (u64)0x28f5c29) >> 32;
  232. *((u16 *)buf) = decpair[q - 100*r];
  233. buf += 2;
  234. /* 1 <= r < 10^4 */
  235. if (r < 100)
  236. goto out_r;
  237. /* 100 <= r < 10^4 */
  238. q = (r * 0x147b) >> 19;
  239. *((u16 *)buf) = decpair[r - 100*q];
  240. buf += 2;
  241. out_q:
  242. /* 1 <= q < 100 */
  243. r = q;
  244. out_r:
  245. /* 1 <= r < 100 */
  246. *((u16 *)buf) = decpair[r];
  247. buf += r < 10 ? 1 : 2;
  248. return buf;
  249. }
  250. #if BITS_PER_LONG == 64 && BITS_PER_LONG_LONG == 64
  251. static noinline_for_stack
  252. char *put_dec_full8(char *buf, unsigned r)
  253. {
  254. unsigned q;
  255. /* 0 <= r < 10^8 */
  256. q = (r * (u64)0x28f5c29) >> 32;
  257. *((u16 *)buf) = decpair[r - 100*q];
  258. buf += 2;
  259. /* 0 <= q < 10^6 */
  260. r = (q * (u64)0x28f5c29) >> 32;
  261. *((u16 *)buf) = decpair[q - 100*r];
  262. buf += 2;
  263. /* 0 <= r < 10^4 */
  264. q = (r * 0x147b) >> 19;
  265. *((u16 *)buf) = decpair[r - 100*q];
  266. buf += 2;
  267. /* 0 <= q < 100 */
  268. *((u16 *)buf) = decpair[q];
  269. buf += 2;
  270. return buf;
  271. }
  272. static noinline_for_stack
  273. char *put_dec(char *buf, unsigned long long n)
  274. {
  275. if (n >= 100*1000*1000)
  276. buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
  277. /* 1 <= n <= 1.6e11 */
  278. if (n >= 100*1000*1000)
  279. buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
  280. /* 1 <= n < 1e8 */
  281. return put_dec_trunc8(buf, n);
  282. }
  283. #elif BITS_PER_LONG == 32 && BITS_PER_LONG_LONG == 64
  284. static void
  285. put_dec_full4(char *buf, unsigned r)
  286. {
  287. unsigned q;
  288. /* 0 <= r < 10^4 */
  289. q = (r * 0x147b) >> 19;
  290. *((u16 *)buf) = decpair[r - 100*q];
  291. buf += 2;
  292. /* 0 <= q < 100 */
  293. *((u16 *)buf) = decpair[q];
  294. }
  295. /*
  296. * Call put_dec_full4 on x % 10000, return x / 10000.
  297. * The approximation x/10000 == (x * 0x346DC5D7) >> 43
  298. * holds for all x < 1,128,869,999. The largest value this
  299. * helper will ever be asked to convert is 1,125,520,955.
  300. * (second call in the put_dec code, assuming n is all-ones).
  301. */
  302. static noinline_for_stack
  303. unsigned put_dec_helper4(char *buf, unsigned x)
  304. {
  305. uint32_t q = (x * (uint64_t)0x346DC5D7) >> 43;
  306. put_dec_full4(buf, x - q * 10000);
  307. return q;
  308. }
  309. /* Based on code by Douglas W. Jones found at
  310. * <http://www.cs.uiowa.edu/~jones/bcd/decimal.html#sixtyfour>
  311. * (with permission from the author).
  312. * Performs no 64-bit division and hence should be fast on 32-bit machines.
  313. */
  314. static
  315. char *put_dec(char *buf, unsigned long long n)
  316. {
  317. uint32_t d3, d2, d1, q, h;
  318. if (n < 100*1000*1000)
  319. return put_dec_trunc8(buf, n);
  320. d1 = ((uint32_t)n >> 16); /* implicit "& 0xffff" */
  321. h = (n >> 32);
  322. d2 = (h ) & 0xffff;
  323. d3 = (h >> 16); /* implicit "& 0xffff" */
  324. /* n = 2^48 d3 + 2^32 d2 + 2^16 d1 + d0
  325. = 281_4749_7671_0656 d3 + 42_9496_7296 d2 + 6_5536 d1 + d0 */
  326. q = 656 * d3 + 7296 * d2 + 5536 * d1 + ((uint32_t)n & 0xffff);
  327. q = put_dec_helper4(buf, q);
  328. q += 7671 * d3 + 9496 * d2 + 6 * d1;
  329. q = put_dec_helper4(buf+4, q);
  330. q += 4749 * d3 + 42 * d2;
  331. q = put_dec_helper4(buf+8, q);
  332. q += 281 * d3;
  333. buf += 12;
  334. if (q)
  335. buf = put_dec_trunc8(buf, q);
  336. else while (buf[-1] == '0')
  337. --buf;
  338. return buf;
  339. }
  340. #endif
  341. /*
  342. * Convert passed number to decimal string.
  343. * Returns the length of string. On buffer overflow, returns 0.
  344. *
  345. * If speed is not important, use snprintf(). It's easy to read the code.
  346. */
  347. int num_to_str(char *buf, int size, unsigned long long num, unsigned int width)
  348. {
  349. /* put_dec requires 2-byte alignment of the buffer. */
  350. char tmp[sizeof(num) * 3] __aligned(2);
  351. int idx, len;
  352. /* put_dec() may work incorrectly for num = 0 (generate "", not "0") */
  353. if (num <= 9) {
  354. tmp[0] = '0' + num;
  355. len = 1;
  356. } else {
  357. len = put_dec(tmp, num) - tmp;
  358. }
  359. if (len > size || width > size)
  360. return 0;
  361. if (width > len) {
  362. width = width - len;
  363. for (idx = 0; idx < width; idx++)
  364. buf[idx] = ' ';
  365. } else {
  366. width = 0;
  367. }
  368. for (idx = 0; idx < len; ++idx)
  369. buf[idx + width] = tmp[len - idx - 1];
  370. return len + width;
  371. }
  372. #define SIGN 1 /* unsigned/signed */
  373. #define LEFT 2 /* left justified */
  374. #define PLUS 4 /* show plus */
  375. #define SPACE 8 /* space if plus */
  376. #define ZEROPAD 16 /* pad with zero, must be 16 == '0' - ' ' */
  377. #define SMALL 32 /* use lowercase in hex (must be 32 == 0x20) */
  378. #define SPECIAL 64 /* prefix hex with "0x", octal with "0" */
  379. static_assert(ZEROPAD == ('0' - ' '));
  380. static_assert(SMALL == ('a' ^ 'A'));
  381. enum format_state {
  382. FORMAT_STATE_NONE, /* Just a string part */
  383. FORMAT_STATE_NUM,
  384. FORMAT_STATE_WIDTH,
  385. FORMAT_STATE_PRECISION,
  386. FORMAT_STATE_CHAR,
  387. FORMAT_STATE_STR,
  388. FORMAT_STATE_PTR,
  389. FORMAT_STATE_PERCENT_CHAR,
  390. FORMAT_STATE_INVALID,
  391. };
  392. struct printf_spec {
  393. unsigned char flags; /* flags to number() */
  394. unsigned char base; /* number base, 8, 10 or 16 only */
  395. short precision; /* # of digits/chars */
  396. int field_width; /* width of output field */
  397. } __packed;
  398. static_assert(sizeof(struct printf_spec) == 8);
  399. #define FIELD_WIDTH_MAX ((1 << 23) - 1)
  400. #define PRECISION_MAX ((1 << 15) - 1)
  401. static noinline_for_stack
  402. char *number(char *buf, char *end, unsigned long long num,
  403. struct printf_spec spec)
  404. {
  405. /* put_dec requires 2-byte alignment of the buffer. */
  406. char tmp[3 * sizeof(num)] __aligned(2);
  407. char sign;
  408. char locase;
  409. int need_pfx = ((spec.flags & SPECIAL) && spec.base != 10);
  410. int i;
  411. bool is_zero = num == 0LL;
  412. int field_width = spec.field_width;
  413. int precision = spec.precision;
  414. /* locase = 0 or 0x20. ORing digits or letters with 'locase'
  415. * produces same digits or (maybe lowercased) letters */
  416. locase = (spec.flags & SMALL);
  417. if (spec.flags & LEFT)
  418. spec.flags &= ~ZEROPAD;
  419. sign = 0;
  420. if (spec.flags & SIGN) {
  421. if ((signed long long)num < 0) {
  422. sign = '-';
  423. num = -(signed long long)num;
  424. field_width--;
  425. } else if (spec.flags & PLUS) {
  426. sign = '+';
  427. field_width--;
  428. } else if (spec.flags & SPACE) {
  429. sign = ' ';
  430. field_width--;
  431. }
  432. }
  433. if (need_pfx) {
  434. if (spec.base == 16)
  435. field_width -= 2;
  436. else if (!is_zero)
  437. field_width--;
  438. }
  439. /* generate full string in tmp[], in reverse order */
  440. i = 0;
  441. if (num < spec.base)
  442. tmp[i++] = hex_asc_upper[num] | locase;
  443. else if (spec.base != 10) { /* 8 or 16 */
  444. int mask = spec.base - 1;
  445. int shift = 3;
  446. if (spec.base == 16)
  447. shift = 4;
  448. do {
  449. tmp[i++] = (hex_asc_upper[((unsigned char)num) & mask] | locase);
  450. num >>= shift;
  451. } while (num);
  452. } else { /* base 10 */
  453. i = put_dec(tmp, num) - tmp;
  454. }
  455. /* printing 100 using %2d gives "100", not "00" */
  456. if (i > precision)
  457. precision = i;
  458. /* leading space padding */
  459. field_width -= precision;
  460. if (!(spec.flags & (ZEROPAD | LEFT))) {
  461. while (--field_width >= 0) {
  462. if (buf < end)
  463. *buf = ' ';
  464. ++buf;
  465. }
  466. }
  467. /* sign */
  468. if (sign) {
  469. if (buf < end)
  470. *buf = sign;
  471. ++buf;
  472. }
  473. /* "0x" / "0" prefix */
  474. if (need_pfx) {
  475. if (spec.base == 16 || !is_zero) {
  476. if (buf < end)
  477. *buf = '0';
  478. ++buf;
  479. }
  480. if (spec.base == 16) {
  481. if (buf < end)
  482. *buf = ('X' | locase);
  483. ++buf;
  484. }
  485. }
  486. /* zero or space padding */
  487. if (!(spec.flags & LEFT)) {
  488. char c = ' ' + (spec.flags & ZEROPAD);
  489. while (--field_width >= 0) {
  490. if (buf < end)
  491. *buf = c;
  492. ++buf;
  493. }
  494. }
  495. /* hmm even more zero padding? */
  496. while (i <= --precision) {
  497. if (buf < end)
  498. *buf = '0';
  499. ++buf;
  500. }
  501. /* actual digits of result */
  502. while (--i >= 0) {
  503. if (buf < end)
  504. *buf = tmp[i];
  505. ++buf;
  506. }
  507. /* trailing space padding */
  508. while (--field_width >= 0) {
  509. if (buf < end)
  510. *buf = ' ';
  511. ++buf;
  512. }
  513. return buf;
  514. }
  515. #define special_hex_spec(size) \
  516. (struct printf_spec) { \
  517. .field_width = 2 + 2 * (size), /* 0x + hex */ \
  518. .flags = SPECIAL | SMALL | ZEROPAD, \
  519. .base = 16, \
  520. .precision = -1, \
  521. }
  522. static noinline_for_stack
  523. char *special_hex_number(char *buf, char *end, unsigned long long num, int size)
  524. {
  525. return number(buf, end, num, special_hex_spec(size));
  526. }
  527. static void move_right(char *buf, char *end, unsigned len, unsigned spaces)
  528. {
  529. size_t size;
  530. if (buf >= end) /* nowhere to put anything */
  531. return;
  532. size = end - buf;
  533. if (size <= spaces) {
  534. memset(buf, ' ', size);
  535. return;
  536. }
  537. if (len) {
  538. if (len > size - spaces)
  539. len = size - spaces;
  540. memmove(buf + spaces, buf, len);
  541. }
  542. memset(buf, ' ', spaces);
  543. }
  544. /*
  545. * Handle field width padding for a string.
  546. * @buf: current buffer position
  547. * @n: length of string
  548. * @end: end of output buffer
  549. * @spec: for field width and flags
  550. * Returns: new buffer position after padding.
  551. */
  552. static noinline_for_stack
  553. char *widen_string(char *buf, int n, char *end, struct printf_spec spec)
  554. {
  555. unsigned spaces;
  556. if (likely(n >= spec.field_width))
  557. return buf;
  558. /* we want to pad the sucker */
  559. spaces = spec.field_width - n;
  560. if (!(spec.flags & LEFT)) {
  561. move_right(buf - n, end, n, spaces);
  562. return buf + spaces;
  563. }
  564. while (spaces--) {
  565. if (buf < end)
  566. *buf = ' ';
  567. ++buf;
  568. }
  569. return buf;
  570. }
  571. /* Handle string from a well known address. */
  572. static char *string_nocheck(char *buf, char *end, const char *s,
  573. struct printf_spec spec)
  574. {
  575. int len = 0;
  576. int lim = spec.precision;
  577. while (lim--) {
  578. char c = *s++;
  579. if (!c)
  580. break;
  581. if (buf < end)
  582. *buf = c;
  583. ++buf;
  584. ++len;
  585. }
  586. return widen_string(buf, len, end, spec);
  587. }
  588. static char *err_ptr(char *buf, char *end, void *ptr,
  589. struct printf_spec spec)
  590. {
  591. int err = PTR_ERR(ptr);
  592. const char *sym = errname(err);
  593. if (sym)
  594. return string_nocheck(buf, end, sym, spec);
  595. /*
  596. * Somebody passed ERR_PTR(-1234) or some other non-existing
  597. * Efoo - or perhaps CONFIG_SYMBOLIC_ERRNAME=n. Fall back to
  598. * printing it as its decimal representation.
  599. */
  600. spec.flags |= SIGN;
  601. spec.base = 10;
  602. return number(buf, end, err, spec);
  603. }
  604. /* Be careful: error messages must fit into the given buffer. */
  605. static char *error_string(char *buf, char *end, const char *s,
  606. struct printf_spec spec)
  607. {
  608. /*
  609. * Hard limit to avoid a completely insane messages. It actually
  610. * works pretty well because most error messages are in
  611. * the many pointer format modifiers.
  612. */
  613. if (spec.precision == -1)
  614. spec.precision = 2 * sizeof(void *);
  615. return string_nocheck(buf, end, s, spec);
  616. }
  617. /*
  618. * Do not call any complex external code here. Nested printk()/vsprintf()
  619. * might cause infinite loops. Failures might break printk() and would
  620. * be hard to debug.
  621. */
  622. static const char *check_pointer_msg(const void *ptr)
  623. {
  624. if (!ptr)
  625. return "(null)";
  626. if ((unsigned long)ptr < PAGE_SIZE || IS_ERR_VALUE(ptr))
  627. return "(efault)";
  628. return NULL;
  629. }
  630. static int check_pointer(char **buf, char *end, const void *ptr,
  631. struct printf_spec spec)
  632. {
  633. const char *err_msg;
  634. err_msg = check_pointer_msg(ptr);
  635. if (err_msg) {
  636. *buf = error_string(*buf, end, err_msg, spec);
  637. return -EFAULT;
  638. }
  639. return 0;
  640. }
  641. static noinline_for_stack
  642. char *string(char *buf, char *end, const char *s,
  643. struct printf_spec spec)
  644. {
  645. if (check_pointer(&buf, end, s, spec))
  646. return buf;
  647. return string_nocheck(buf, end, s, spec);
  648. }
  649. static char *pointer_string(char *buf, char *end,
  650. const void *ptr,
  651. struct printf_spec spec)
  652. {
  653. spec.base = 16;
  654. spec.flags |= SMALL;
  655. if (spec.field_width == -1) {
  656. spec.field_width = 2 * sizeof(ptr);
  657. spec.flags |= ZEROPAD;
  658. }
  659. return number(buf, end, (unsigned long int)ptr, spec);
  660. }
  661. /* Make pointers available for printing early in the boot sequence. */
  662. static int debug_boot_weak_hash __ro_after_init;
  663. static int __init debug_boot_weak_hash_enable(char *str)
  664. {
  665. debug_boot_weak_hash = 1;
  666. pr_info("debug_boot_weak_hash enabled\n");
  667. return 0;
  668. }
  669. early_param("debug_boot_weak_hash", debug_boot_weak_hash_enable);
  670. static bool filled_random_ptr_key __read_mostly;
  671. static siphash_key_t ptr_key __read_mostly;
  672. static int fill_ptr_key(struct notifier_block *nb, unsigned long action, void *data)
  673. {
  674. get_random_bytes(&ptr_key, sizeof(ptr_key));
  675. /* Pairs with smp_rmb() before reading ptr_key. */
  676. smp_wmb();
  677. WRITE_ONCE(filled_random_ptr_key, true);
  678. return NOTIFY_DONE;
  679. }
  680. static int __init vsprintf_init_hashval(void)
  681. {
  682. static struct notifier_block fill_ptr_key_nb = { .notifier_call = fill_ptr_key };
  683. execute_with_initialized_rng(&fill_ptr_key_nb);
  684. return 0;
  685. }
  686. subsys_initcall(vsprintf_init_hashval)
  687. /* Maps a pointer to a 32 bit unique identifier. */
  688. static inline int __ptr_to_hashval(const void *ptr, unsigned long *hashval_out)
  689. {
  690. unsigned long hashval;
  691. if (!READ_ONCE(filled_random_ptr_key))
  692. return -EBUSY;
  693. /* Pairs with smp_wmb() after writing ptr_key. */
  694. smp_rmb();
  695. #ifdef CONFIG_64BIT
  696. hashval = (unsigned long)siphash_1u64((u64)ptr, &ptr_key);
  697. /*
  698. * Mask off the first 32 bits, this makes explicit that we have
  699. * modified the address (and 32 bits is plenty for a unique ID).
  700. */
  701. hashval = hashval & 0xffffffff;
  702. #else
  703. hashval = (unsigned long)siphash_1u32((u32)ptr, &ptr_key);
  704. #endif
  705. *hashval_out = hashval;
  706. return 0;
  707. }
  708. int ptr_to_hashval(const void *ptr, unsigned long *hashval_out)
  709. {
  710. return __ptr_to_hashval(ptr, hashval_out);
  711. }
  712. static char *ptr_to_id(char *buf, char *end, const void *ptr,
  713. struct printf_spec spec)
  714. {
  715. const char *str = sizeof(ptr) == 8 ? "(____ptrval____)" : "(ptrval)";
  716. unsigned long hashval;
  717. int ret;
  718. /*
  719. * Print the real pointer value for NULL and error pointers,
  720. * as they are not actual addresses.
  721. */
  722. if (IS_ERR_OR_NULL(ptr))
  723. return pointer_string(buf, end, ptr, spec);
  724. /* When debugging early boot use non-cryptographically secure hash. */
  725. if (unlikely(debug_boot_weak_hash)) {
  726. hashval = hash_long((unsigned long)ptr, 32);
  727. return pointer_string(buf, end, (const void *)hashval, spec);
  728. }
  729. ret = __ptr_to_hashval(ptr, &hashval);
  730. if (ret) {
  731. spec.field_width = 2 * sizeof(ptr);
  732. /* string length must be less than default_width */
  733. return error_string(buf, end, str, spec);
  734. }
  735. return pointer_string(buf, end, (const void *)hashval, spec);
  736. }
  737. static char *default_pointer(char *buf, char *end, const void *ptr,
  738. struct printf_spec spec)
  739. {
  740. /*
  741. * default is to _not_ leak addresses, so hash before printing,
  742. * unless no_hash_pointers is specified on the command line.
  743. */
  744. if (unlikely(no_hash_pointers))
  745. return pointer_string(buf, end, ptr, spec);
  746. return ptr_to_id(buf, end, ptr, spec);
  747. }
  748. int kptr_restrict __read_mostly;
  749. static noinline_for_stack
  750. char *restricted_pointer(char *buf, char *end, const void *ptr,
  751. struct printf_spec spec)
  752. {
  753. switch (kptr_restrict) {
  754. case 0:
  755. /* Handle as %p, hash and do _not_ leak addresses. */
  756. return default_pointer(buf, end, ptr, spec);
  757. case 1: {
  758. const struct cred *cred;
  759. /*
  760. * kptr_restrict==1 cannot be used in IRQ context
  761. * because its test for CAP_SYSLOG would be meaningless.
  762. */
  763. if (in_hardirq() || in_serving_softirq() || in_nmi()) {
  764. if (spec.field_width == -1)
  765. spec.field_width = 2 * sizeof(ptr);
  766. return error_string(buf, end, "pK-error", spec);
  767. }
  768. /*
  769. * Only print the real pointer value if the current
  770. * process has CAP_SYSLOG and is running with the
  771. * same credentials it started with. This is because
  772. * access to files is checked at open() time, but %pK
  773. * checks permission at read() time. We don't want to
  774. * leak pointer values if a binary opens a file using
  775. * %pK and then elevates privileges before reading it.
  776. */
  777. cred = current_cred();
  778. if (!has_capability_noaudit(current, CAP_SYSLOG) ||
  779. !uid_eq(cred->euid, cred->uid) ||
  780. !gid_eq(cred->egid, cred->gid))
  781. ptr = NULL;
  782. break;
  783. }
  784. case 2:
  785. default:
  786. /* Always print 0's for %pK */
  787. ptr = NULL;
  788. break;
  789. }
  790. return pointer_string(buf, end, ptr, spec);
  791. }
  792. static noinline_for_stack
  793. char *dentry_name(char *buf, char *end, const struct dentry *d, struct printf_spec spec,
  794. const char *fmt)
  795. {
  796. const char *array[4], *s;
  797. const struct dentry *p;
  798. int depth;
  799. int i, n;
  800. switch (fmt[1]) {
  801. case '2': case '3': case '4':
  802. depth = fmt[1] - '0';
  803. break;
  804. default:
  805. depth = 1;
  806. }
  807. rcu_read_lock();
  808. for (i = 0; i < depth; i++, d = p) {
  809. if (check_pointer(&buf, end, d, spec)) {
  810. rcu_read_unlock();
  811. return buf;
  812. }
  813. p = READ_ONCE(d->d_parent);
  814. array[i] = READ_ONCE(d->d_name.name);
  815. if (p == d) {
  816. if (i)
  817. array[i] = "";
  818. i++;
  819. break;
  820. }
  821. }
  822. s = array[--i];
  823. for (n = 0; n != spec.precision; n++, buf++) {
  824. char c = *s++;
  825. if (!c) {
  826. if (!i)
  827. break;
  828. c = '/';
  829. s = array[--i];
  830. }
  831. if (buf < end)
  832. *buf = c;
  833. }
  834. rcu_read_unlock();
  835. return widen_string(buf, n, end, spec);
  836. }
  837. static noinline_for_stack
  838. char *file_dentry_name(char *buf, char *end, const struct file *f,
  839. struct printf_spec spec, const char *fmt)
  840. {
  841. if (check_pointer(&buf, end, f, spec))
  842. return buf;
  843. return dentry_name(buf, end, f->f_path.dentry, spec, fmt);
  844. }
  845. #ifdef CONFIG_BLOCK
  846. static noinline_for_stack
  847. char *bdev_name(char *buf, char *end, struct block_device *bdev,
  848. struct printf_spec spec, const char *fmt)
  849. {
  850. struct gendisk *hd;
  851. if (check_pointer(&buf, end, bdev, spec))
  852. return buf;
  853. hd = bdev->bd_disk;
  854. buf = string(buf, end, hd->disk_name, spec);
  855. if (bdev_is_partition(bdev)) {
  856. if (isdigit(hd->disk_name[strlen(hd->disk_name)-1])) {
  857. if (buf < end)
  858. *buf = 'p';
  859. buf++;
  860. }
  861. buf = number(buf, end, bdev_partno(bdev), spec);
  862. }
  863. return buf;
  864. }
  865. #endif
  866. static noinline_for_stack
  867. char *symbol_string(char *buf, char *end, void *ptr,
  868. struct printf_spec spec, const char *fmt)
  869. {
  870. unsigned long value;
  871. #ifdef CONFIG_KALLSYMS
  872. char sym[KSYM_SYMBOL_LEN];
  873. #endif
  874. if (fmt[1] == 'R')
  875. ptr = __builtin_extract_return_addr(ptr);
  876. value = (unsigned long)ptr;
  877. #ifdef CONFIG_KALLSYMS
  878. if (*fmt == 'B' && fmt[1] == 'b')
  879. sprint_backtrace_build_id(sym, value);
  880. else if (*fmt == 'B')
  881. sprint_backtrace(sym, value);
  882. else if (*fmt == 'S' && (fmt[1] == 'b' || (fmt[1] == 'R' && fmt[2] == 'b')))
  883. sprint_symbol_build_id(sym, value);
  884. else if (*fmt != 's')
  885. sprint_symbol(sym, value);
  886. else
  887. sprint_symbol_no_offset(sym, value);
  888. return string_nocheck(buf, end, sym, spec);
  889. #else
  890. return special_hex_number(buf, end, value, sizeof(void *));
  891. #endif
  892. }
  893. static const struct printf_spec default_str_spec = {
  894. .field_width = -1,
  895. .precision = -1,
  896. };
  897. static const struct printf_spec default_flag_spec = {
  898. .base = 16,
  899. .precision = -1,
  900. .flags = SPECIAL | SMALL,
  901. };
  902. static const struct printf_spec default_dec_spec = {
  903. .base = 10,
  904. .precision = -1,
  905. };
  906. static const struct printf_spec default_dec02_spec = {
  907. .base = 10,
  908. .field_width = 2,
  909. .precision = -1,
  910. .flags = ZEROPAD,
  911. };
  912. static const struct printf_spec default_dec04_spec = {
  913. .base = 10,
  914. .field_width = 4,
  915. .precision = -1,
  916. .flags = ZEROPAD,
  917. };
  918. static noinline_for_stack
  919. char *hex_range(char *buf, char *end, u64 start_val, u64 end_val,
  920. struct printf_spec spec)
  921. {
  922. buf = number(buf, end, start_val, spec);
  923. if (start_val == end_val)
  924. return buf;
  925. if (buf < end)
  926. *buf = '-';
  927. ++buf;
  928. return number(buf, end, end_val, spec);
  929. }
  930. static noinline_for_stack
  931. char *resource_string(char *buf, char *end, struct resource *res,
  932. struct printf_spec spec, const char *fmt)
  933. {
  934. #ifndef IO_RSRC_PRINTK_SIZE
  935. #define IO_RSRC_PRINTK_SIZE 6
  936. #endif
  937. #ifndef MEM_RSRC_PRINTK_SIZE
  938. #define MEM_RSRC_PRINTK_SIZE 10
  939. #endif
  940. static const struct printf_spec io_spec = {
  941. .base = 16,
  942. .field_width = IO_RSRC_PRINTK_SIZE,
  943. .precision = -1,
  944. .flags = SPECIAL | SMALL | ZEROPAD,
  945. };
  946. static const struct printf_spec mem_spec = {
  947. .base = 16,
  948. .field_width = MEM_RSRC_PRINTK_SIZE,
  949. .precision = -1,
  950. .flags = SPECIAL | SMALL | ZEROPAD,
  951. };
  952. static const struct printf_spec bus_spec = {
  953. .base = 16,
  954. .field_width = 2,
  955. .precision = -1,
  956. .flags = SMALL | ZEROPAD,
  957. };
  958. static const struct printf_spec str_spec = {
  959. .field_width = -1,
  960. .precision = 10,
  961. .flags = LEFT,
  962. };
  963. /* 32-bit res (sizeof==4): 10 chars in dec, 10 in hex ("0x" + 8)
  964. * 64-bit res (sizeof==8): 20 chars in dec, 18 in hex ("0x" + 16) */
  965. #define RSRC_BUF_SIZE ((2 * sizeof(resource_size_t)) + 4)
  966. #define FLAG_BUF_SIZE (2 * sizeof(res->flags))
  967. #define DECODED_BUF_SIZE sizeof("[mem - 64bit pref window disabled]")
  968. #define RAW_BUF_SIZE sizeof("[mem - flags 0x]")
  969. char sym[MAX(2*RSRC_BUF_SIZE + DECODED_BUF_SIZE,
  970. 2*RSRC_BUF_SIZE + FLAG_BUF_SIZE + RAW_BUF_SIZE)];
  971. char *p = sym, *pend = sym + sizeof(sym);
  972. int decode = (fmt[0] == 'R') ? 1 : 0;
  973. const struct printf_spec *specp;
  974. if (check_pointer(&buf, end, res, spec))
  975. return buf;
  976. *p++ = '[';
  977. if (res->flags & IORESOURCE_IO) {
  978. p = string_nocheck(p, pend, "io ", str_spec);
  979. specp = &io_spec;
  980. } else if (res->flags & IORESOURCE_MEM) {
  981. p = string_nocheck(p, pend, "mem ", str_spec);
  982. specp = &mem_spec;
  983. } else if (res->flags & IORESOURCE_IRQ) {
  984. p = string_nocheck(p, pend, "irq ", str_spec);
  985. specp = &default_dec_spec;
  986. } else if (res->flags & IORESOURCE_DMA) {
  987. p = string_nocheck(p, pend, "dma ", str_spec);
  988. specp = &default_dec_spec;
  989. } else if (res->flags & IORESOURCE_BUS) {
  990. p = string_nocheck(p, pend, "bus ", str_spec);
  991. specp = &bus_spec;
  992. } else {
  993. p = string_nocheck(p, pend, "??? ", str_spec);
  994. specp = &mem_spec;
  995. decode = 0;
  996. }
  997. if (decode && res->flags & IORESOURCE_UNSET) {
  998. p = string_nocheck(p, pend, "size ", str_spec);
  999. p = number(p, pend, resource_size(res), *specp);
  1000. } else {
  1001. p = hex_range(p, pend, res->start, res->end, *specp);
  1002. }
  1003. if (decode) {
  1004. if (res->flags & IORESOURCE_MEM_64)
  1005. p = string_nocheck(p, pend, " 64bit", str_spec);
  1006. if (res->flags & IORESOURCE_PREFETCH)
  1007. p = string_nocheck(p, pend, " pref", str_spec);
  1008. if (res->flags & IORESOURCE_WINDOW)
  1009. p = string_nocheck(p, pend, " window", str_spec);
  1010. if (res->flags & IORESOURCE_DISABLED)
  1011. p = string_nocheck(p, pend, " disabled", str_spec);
  1012. } else {
  1013. p = string_nocheck(p, pend, " flags ", str_spec);
  1014. p = number(p, pend, res->flags, default_flag_spec);
  1015. }
  1016. *p++ = ']';
  1017. *p = '\0';
  1018. return string_nocheck(buf, end, sym, spec);
  1019. }
  1020. static noinline_for_stack
  1021. char *range_string(char *buf, char *end, const struct range *range,
  1022. struct printf_spec spec, const char *fmt)
  1023. {
  1024. char sym[sizeof("[range 0x0123456789abcdef-0x0123456789abcdef]")];
  1025. char *p = sym, *pend = sym + sizeof(sym);
  1026. if (check_pointer(&buf, end, range, spec))
  1027. return buf;
  1028. p = string_nocheck(p, pend, "[range ", default_str_spec);
  1029. p = hex_range(p, pend, range->start, range->end, special_hex_spec(sizeof(range->start)));
  1030. *p++ = ']';
  1031. *p = '\0';
  1032. return string_nocheck(buf, end, sym, spec);
  1033. }
  1034. static noinline_for_stack
  1035. char *hex_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
  1036. const char *fmt)
  1037. {
  1038. int i, len = 1; /* if we pass '%ph[CDN]', field width remains
  1039. negative value, fallback to the default */
  1040. char separator;
  1041. if (spec.field_width == 0)
  1042. /* nothing to print */
  1043. return buf;
  1044. if (check_pointer(&buf, end, addr, spec))
  1045. return buf;
  1046. switch (fmt[1]) {
  1047. case 'C':
  1048. separator = ':';
  1049. break;
  1050. case 'D':
  1051. separator = '-';
  1052. break;
  1053. case 'N':
  1054. separator = 0;
  1055. break;
  1056. default:
  1057. separator = ' ';
  1058. break;
  1059. }
  1060. if (spec.field_width > 0)
  1061. len = min_t(int, spec.field_width, 64);
  1062. for (i = 0; i < len; ++i) {
  1063. if (buf < end)
  1064. *buf = hex_asc_hi(addr[i]);
  1065. ++buf;
  1066. if (buf < end)
  1067. *buf = hex_asc_lo(addr[i]);
  1068. ++buf;
  1069. if (separator && i != len - 1) {
  1070. if (buf < end)
  1071. *buf = separator;
  1072. ++buf;
  1073. }
  1074. }
  1075. return buf;
  1076. }
  1077. static noinline_for_stack
  1078. char *bitmap_string(char *buf, char *end, const unsigned long *bitmap,
  1079. struct printf_spec spec, const char *fmt)
  1080. {
  1081. const int CHUNKSZ = 32;
  1082. int nr_bits = max_t(int, spec.field_width, 0);
  1083. int i, chunksz;
  1084. bool first = true;
  1085. if (check_pointer(&buf, end, bitmap, spec))
  1086. return buf;
  1087. /* reused to print numbers */
  1088. spec = (struct printf_spec){ .flags = SMALL | ZEROPAD, .base = 16 };
  1089. chunksz = nr_bits & (CHUNKSZ - 1);
  1090. if (chunksz == 0)
  1091. chunksz = CHUNKSZ;
  1092. i = ALIGN(nr_bits, CHUNKSZ) - CHUNKSZ;
  1093. for (; i >= 0; i -= CHUNKSZ) {
  1094. u32 chunkmask, val;
  1095. int word, bit;
  1096. chunkmask = ((1ULL << chunksz) - 1);
  1097. word = i / BITS_PER_LONG;
  1098. bit = i % BITS_PER_LONG;
  1099. val = (bitmap[word] >> bit) & chunkmask;
  1100. if (!first) {
  1101. if (buf < end)
  1102. *buf = ',';
  1103. buf++;
  1104. }
  1105. first = false;
  1106. spec.field_width = DIV_ROUND_UP(chunksz, 4);
  1107. buf = number(buf, end, val, spec);
  1108. chunksz = CHUNKSZ;
  1109. }
  1110. return buf;
  1111. }
  1112. static noinline_for_stack
  1113. char *bitmap_list_string(char *buf, char *end, const unsigned long *bitmap,
  1114. struct printf_spec spec, const char *fmt)
  1115. {
  1116. int nr_bits = max_t(int, spec.field_width, 0);
  1117. bool first = true;
  1118. int rbot, rtop;
  1119. if (check_pointer(&buf, end, bitmap, spec))
  1120. return buf;
  1121. for_each_set_bitrange(rbot, rtop, bitmap, nr_bits) {
  1122. if (!first) {
  1123. if (buf < end)
  1124. *buf = ',';
  1125. buf++;
  1126. }
  1127. first = false;
  1128. buf = number(buf, end, rbot, default_dec_spec);
  1129. if (rtop == rbot + 1)
  1130. continue;
  1131. if (buf < end)
  1132. *buf = '-';
  1133. buf = number(++buf, end, rtop - 1, default_dec_spec);
  1134. }
  1135. return buf;
  1136. }
  1137. static noinline_for_stack
  1138. char *mac_address_string(char *buf, char *end, u8 *addr,
  1139. struct printf_spec spec, const char *fmt)
  1140. {
  1141. char mac_addr[sizeof("xx:xx:xx:xx:xx:xx")];
  1142. char *p = mac_addr;
  1143. int i;
  1144. char separator;
  1145. bool reversed = false;
  1146. if (check_pointer(&buf, end, addr, spec))
  1147. return buf;
  1148. switch (fmt[1]) {
  1149. case 'F':
  1150. separator = '-';
  1151. break;
  1152. case 'R':
  1153. reversed = true;
  1154. fallthrough;
  1155. default:
  1156. separator = ':';
  1157. break;
  1158. }
  1159. for (i = 0; i < 6; i++) {
  1160. if (reversed)
  1161. p = hex_byte_pack(p, addr[5 - i]);
  1162. else
  1163. p = hex_byte_pack(p, addr[i]);
  1164. if (fmt[0] == 'M' && i != 5)
  1165. *p++ = separator;
  1166. }
  1167. *p = '\0';
  1168. return string_nocheck(buf, end, mac_addr, spec);
  1169. }
  1170. static noinline_for_stack
  1171. char *ip4_string(char *p, const u8 *addr, const char *fmt)
  1172. {
  1173. int i;
  1174. bool leading_zeros = (fmt[0] == 'i');
  1175. int index;
  1176. int step;
  1177. switch (fmt[2]) {
  1178. case 'h':
  1179. #ifdef __BIG_ENDIAN
  1180. index = 0;
  1181. step = 1;
  1182. #else
  1183. index = 3;
  1184. step = -1;
  1185. #endif
  1186. break;
  1187. case 'l':
  1188. index = 3;
  1189. step = -1;
  1190. break;
  1191. case 'n':
  1192. case 'b':
  1193. default:
  1194. index = 0;
  1195. step = 1;
  1196. break;
  1197. }
  1198. for (i = 0; i < 4; i++) {
  1199. char temp[4] __aligned(2); /* hold each IP quad in reverse order */
  1200. int digits = put_dec_trunc8(temp, addr[index]) - temp;
  1201. if (leading_zeros) {
  1202. if (digits < 3)
  1203. *p++ = '0';
  1204. if (digits < 2)
  1205. *p++ = '0';
  1206. }
  1207. /* reverse the digits in the quad */
  1208. while (digits--)
  1209. *p++ = temp[digits];
  1210. if (i < 3)
  1211. *p++ = '.';
  1212. index += step;
  1213. }
  1214. *p = '\0';
  1215. return p;
  1216. }
  1217. static noinline_for_stack
  1218. char *ip6_compressed_string(char *p, const char *addr)
  1219. {
  1220. int i, j, range;
  1221. unsigned char zerolength[8];
  1222. int longest = 1;
  1223. int colonpos = -1;
  1224. u16 word;
  1225. u8 hi, lo;
  1226. bool needcolon = false;
  1227. bool useIPv4;
  1228. struct in6_addr in6;
  1229. memcpy(&in6, addr, sizeof(struct in6_addr));
  1230. useIPv4 = ipv6_addr_v4mapped(&in6) || ipv6_addr_is_isatap(&in6);
  1231. memset(zerolength, 0, sizeof(zerolength));
  1232. if (useIPv4)
  1233. range = 6;
  1234. else
  1235. range = 8;
  1236. /* find position of longest 0 run */
  1237. for (i = 0; i < range; i++) {
  1238. for (j = i; j < range; j++) {
  1239. if (in6.s6_addr16[j] != 0)
  1240. break;
  1241. zerolength[i]++;
  1242. }
  1243. }
  1244. for (i = 0; i < range; i++) {
  1245. if (zerolength[i] > longest) {
  1246. longest = zerolength[i];
  1247. colonpos = i;
  1248. }
  1249. }
  1250. if (longest == 1) /* don't compress a single 0 */
  1251. colonpos = -1;
  1252. /* emit address */
  1253. for (i = 0; i < range; i++) {
  1254. if (i == colonpos) {
  1255. if (needcolon || i == 0)
  1256. *p++ = ':';
  1257. *p++ = ':';
  1258. needcolon = false;
  1259. i += longest - 1;
  1260. continue;
  1261. }
  1262. if (needcolon) {
  1263. *p++ = ':';
  1264. needcolon = false;
  1265. }
  1266. /* hex u16 without leading 0s */
  1267. word = ntohs(in6.s6_addr16[i]);
  1268. hi = word >> 8;
  1269. lo = word & 0xff;
  1270. if (hi) {
  1271. if (hi > 0x0f)
  1272. p = hex_byte_pack(p, hi);
  1273. else
  1274. *p++ = hex_asc_lo(hi);
  1275. p = hex_byte_pack(p, lo);
  1276. }
  1277. else if (lo > 0x0f)
  1278. p = hex_byte_pack(p, lo);
  1279. else
  1280. *p++ = hex_asc_lo(lo);
  1281. needcolon = true;
  1282. }
  1283. if (useIPv4) {
  1284. if (needcolon)
  1285. *p++ = ':';
  1286. p = ip4_string(p, &in6.s6_addr[12], "I4");
  1287. }
  1288. *p = '\0';
  1289. return p;
  1290. }
  1291. static noinline_for_stack
  1292. char *ip6_string(char *p, const char *addr, const char *fmt)
  1293. {
  1294. int i;
  1295. for (i = 0; i < 8; i++) {
  1296. p = hex_byte_pack(p, *addr++);
  1297. p = hex_byte_pack(p, *addr++);
  1298. if (fmt[0] == 'I' && i != 7)
  1299. *p++ = ':';
  1300. }
  1301. *p = '\0';
  1302. return p;
  1303. }
  1304. static noinline_for_stack
  1305. char *ip6_addr_string(char *buf, char *end, const u8 *addr,
  1306. struct printf_spec spec, const char *fmt)
  1307. {
  1308. char ip6_addr[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255")];
  1309. if (fmt[0] == 'I' && fmt[2] == 'c')
  1310. ip6_compressed_string(ip6_addr, addr);
  1311. else
  1312. ip6_string(ip6_addr, addr, fmt);
  1313. return string_nocheck(buf, end, ip6_addr, spec);
  1314. }
  1315. static noinline_for_stack
  1316. char *ip4_addr_string(char *buf, char *end, const u8 *addr,
  1317. struct printf_spec spec, const char *fmt)
  1318. {
  1319. char ip4_addr[sizeof("255.255.255.255")];
  1320. ip4_string(ip4_addr, addr, fmt);
  1321. return string_nocheck(buf, end, ip4_addr, spec);
  1322. }
  1323. static noinline_for_stack
  1324. char *ip6_addr_string_sa(char *buf, char *end, const struct sockaddr_in6 *sa,
  1325. struct printf_spec spec, const char *fmt)
  1326. {
  1327. bool have_p = false, have_s = false, have_f = false, have_c = false;
  1328. char ip6_addr[sizeof("[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255]") +
  1329. sizeof(":12345") + sizeof("/123456789") +
  1330. sizeof("%1234567890")];
  1331. char *p = ip6_addr, *pend = ip6_addr + sizeof(ip6_addr);
  1332. const u8 *addr = (const u8 *) &sa->sin6_addr;
  1333. char fmt6[2] = { fmt[0], '6' };
  1334. u8 off = 0;
  1335. fmt++;
  1336. while (isalpha(*++fmt)) {
  1337. switch (*fmt) {
  1338. case 'p':
  1339. have_p = true;
  1340. break;
  1341. case 'f':
  1342. have_f = true;
  1343. break;
  1344. case 's':
  1345. have_s = true;
  1346. break;
  1347. case 'c':
  1348. have_c = true;
  1349. break;
  1350. }
  1351. }
  1352. if (have_p || have_s || have_f) {
  1353. *p = '[';
  1354. off = 1;
  1355. }
  1356. if (fmt6[0] == 'I' && have_c)
  1357. p = ip6_compressed_string(ip6_addr + off, addr);
  1358. else
  1359. p = ip6_string(ip6_addr + off, addr, fmt6);
  1360. if (have_p || have_s || have_f)
  1361. *p++ = ']';
  1362. if (have_p) {
  1363. *p++ = ':';
  1364. p = number(p, pend, ntohs(sa->sin6_port), spec);
  1365. }
  1366. if (have_f) {
  1367. *p++ = '/';
  1368. p = number(p, pend, ntohl(sa->sin6_flowinfo &
  1369. IPV6_FLOWINFO_MASK), spec);
  1370. }
  1371. if (have_s) {
  1372. *p++ = '%';
  1373. p = number(p, pend, sa->sin6_scope_id, spec);
  1374. }
  1375. *p = '\0';
  1376. return string_nocheck(buf, end, ip6_addr, spec);
  1377. }
  1378. static noinline_for_stack
  1379. char *ip4_addr_string_sa(char *buf, char *end, const struct sockaddr_in *sa,
  1380. struct printf_spec spec, const char *fmt)
  1381. {
  1382. bool have_p = false;
  1383. char *p, ip4_addr[sizeof("255.255.255.255") + sizeof(":12345")];
  1384. char *pend = ip4_addr + sizeof(ip4_addr);
  1385. const u8 *addr = (const u8 *) &sa->sin_addr.s_addr;
  1386. char fmt4[3] = { fmt[0], '4', 0 };
  1387. fmt++;
  1388. while (isalpha(*++fmt)) {
  1389. switch (*fmt) {
  1390. case 'p':
  1391. have_p = true;
  1392. break;
  1393. case 'h':
  1394. case 'l':
  1395. case 'n':
  1396. case 'b':
  1397. fmt4[2] = *fmt;
  1398. break;
  1399. }
  1400. }
  1401. p = ip4_string(ip4_addr, addr, fmt4);
  1402. if (have_p) {
  1403. *p++ = ':';
  1404. p = number(p, pend, ntohs(sa->sin_port), spec);
  1405. }
  1406. *p = '\0';
  1407. return string_nocheck(buf, end, ip4_addr, spec);
  1408. }
  1409. static noinline_for_stack
  1410. char *ip_addr_string(char *buf, char *end, const void *ptr,
  1411. struct printf_spec spec, const char *fmt)
  1412. {
  1413. char *err_fmt_msg;
  1414. if (check_pointer(&buf, end, ptr, spec))
  1415. return buf;
  1416. switch (fmt[1]) {
  1417. case '6':
  1418. return ip6_addr_string(buf, end, ptr, spec, fmt);
  1419. case '4':
  1420. return ip4_addr_string(buf, end, ptr, spec, fmt);
  1421. case 'S': {
  1422. const union {
  1423. struct sockaddr raw;
  1424. struct sockaddr_in v4;
  1425. struct sockaddr_in6 v6;
  1426. } *sa = ptr;
  1427. switch (sa->raw.sa_family) {
  1428. case AF_INET:
  1429. return ip4_addr_string_sa(buf, end, &sa->v4, spec, fmt);
  1430. case AF_INET6:
  1431. return ip6_addr_string_sa(buf, end, &sa->v6, spec, fmt);
  1432. default:
  1433. return error_string(buf, end, "(einval)", spec);
  1434. }}
  1435. }
  1436. err_fmt_msg = fmt[0] == 'i' ? "(%pi?)" : "(%pI?)";
  1437. return error_string(buf, end, err_fmt_msg, spec);
  1438. }
  1439. static noinline_for_stack
  1440. char *escaped_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
  1441. const char *fmt)
  1442. {
  1443. bool found = true;
  1444. int count = 1;
  1445. unsigned int flags = 0;
  1446. int len;
  1447. if (spec.field_width == 0)
  1448. return buf; /* nothing to print */
  1449. if (check_pointer(&buf, end, addr, spec))
  1450. return buf;
  1451. do {
  1452. switch (fmt[count++]) {
  1453. case 'a':
  1454. flags |= ESCAPE_ANY;
  1455. break;
  1456. case 'c':
  1457. flags |= ESCAPE_SPECIAL;
  1458. break;
  1459. case 'h':
  1460. flags |= ESCAPE_HEX;
  1461. break;
  1462. case 'n':
  1463. flags |= ESCAPE_NULL;
  1464. break;
  1465. case 'o':
  1466. flags |= ESCAPE_OCTAL;
  1467. break;
  1468. case 'p':
  1469. flags |= ESCAPE_NP;
  1470. break;
  1471. case 's':
  1472. flags |= ESCAPE_SPACE;
  1473. break;
  1474. default:
  1475. found = false;
  1476. break;
  1477. }
  1478. } while (found);
  1479. if (!flags)
  1480. flags = ESCAPE_ANY_NP;
  1481. len = spec.field_width < 0 ? 1 : spec.field_width;
  1482. /*
  1483. * string_escape_mem() writes as many characters as it can to
  1484. * the given buffer, and returns the total size of the output
  1485. * had the buffer been big enough.
  1486. */
  1487. buf += string_escape_mem(addr, len, buf, buf < end ? end - buf : 0, flags, NULL);
  1488. return buf;
  1489. }
  1490. __diag_push();
  1491. __diag_ignore(GCC, all, "-Wsuggest-attribute=format",
  1492. "Not a valid __printf() conversion candidate.");
  1493. static char *va_format(char *buf, char *end, struct va_format *va_fmt,
  1494. struct printf_spec spec)
  1495. {
  1496. va_list va;
  1497. if (check_pointer(&buf, end, va_fmt, spec))
  1498. return buf;
  1499. va_copy(va, *va_fmt->va);
  1500. buf += vsnprintf(buf, end > buf ? end - buf : 0, va_fmt->fmt, va);
  1501. va_end(va);
  1502. return buf;
  1503. }
  1504. __diag_pop();
  1505. static noinline_for_stack
  1506. char *uuid_string(char *buf, char *end, const u8 *addr,
  1507. struct printf_spec spec, const char *fmt)
  1508. {
  1509. char uuid[UUID_STRING_LEN + 1];
  1510. char *p = uuid;
  1511. int i;
  1512. const u8 *index = uuid_index;
  1513. bool uc = false;
  1514. if (check_pointer(&buf, end, addr, spec))
  1515. return buf;
  1516. switch (*(++fmt)) {
  1517. case 'L':
  1518. uc = true;
  1519. fallthrough;
  1520. case 'l':
  1521. index = guid_index;
  1522. break;
  1523. case 'B':
  1524. uc = true;
  1525. break;
  1526. }
  1527. for (i = 0; i < 16; i++) {
  1528. if (uc)
  1529. p = hex_byte_pack_upper(p, addr[index[i]]);
  1530. else
  1531. p = hex_byte_pack(p, addr[index[i]]);
  1532. switch (i) {
  1533. case 3:
  1534. case 5:
  1535. case 7:
  1536. case 9:
  1537. *p++ = '-';
  1538. break;
  1539. }
  1540. }
  1541. *p = 0;
  1542. return string_nocheck(buf, end, uuid, spec);
  1543. }
  1544. static noinline_for_stack
  1545. char *netdev_bits(char *buf, char *end, const void *addr,
  1546. struct printf_spec spec, const char *fmt)
  1547. {
  1548. unsigned long long num;
  1549. int size;
  1550. if (check_pointer(&buf, end, addr, spec))
  1551. return buf;
  1552. switch (fmt[1]) {
  1553. case 'F':
  1554. num = *(const netdev_features_t *)addr;
  1555. size = sizeof(netdev_features_t);
  1556. break;
  1557. default:
  1558. return error_string(buf, end, "(%pN?)", spec);
  1559. }
  1560. return special_hex_number(buf, end, num, size);
  1561. }
  1562. static noinline_for_stack
  1563. char *fourcc_string(char *buf, char *end, const u32 *fourcc,
  1564. struct printf_spec spec, const char *fmt)
  1565. {
  1566. char output[sizeof("0123 little-endian (0x01234567)")];
  1567. char *p = output;
  1568. unsigned int i;
  1569. bool pixel_fmt = false;
  1570. u32 orig, val;
  1571. if (fmt[1] != 'c')
  1572. return error_string(buf, end, "(%p4?)", spec);
  1573. if (check_pointer(&buf, end, fourcc, spec))
  1574. return buf;
  1575. orig = get_unaligned(fourcc);
  1576. switch (fmt[2]) {
  1577. case 'h':
  1578. if (fmt[3] == 'R')
  1579. orig = swab32(orig);
  1580. break;
  1581. case 'l':
  1582. orig = (__force u32)cpu_to_le32(orig);
  1583. break;
  1584. case 'b':
  1585. orig = (__force u32)cpu_to_be32(orig);
  1586. break;
  1587. case 'c':
  1588. /* Pixel formats are printed LSB-first */
  1589. pixel_fmt = true;
  1590. break;
  1591. default:
  1592. return error_string(buf, end, "(%p4?)", spec);
  1593. }
  1594. val = pixel_fmt ? swab32(orig & ~BIT(31)) : orig;
  1595. for (i = 0; i < sizeof(u32); i++) {
  1596. unsigned char c = val >> ((3 - i) * 8);
  1597. /* Print non-control ASCII characters as-is, dot otherwise */
  1598. *p++ = isascii(c) && isprint(c) ? c : '.';
  1599. }
  1600. if (pixel_fmt) {
  1601. *p++ = ' ';
  1602. strcpy(p, orig & BIT(31) ? "big-endian" : "little-endian");
  1603. p += strlen(p);
  1604. }
  1605. *p++ = ' ';
  1606. *p++ = '(';
  1607. p = special_hex_number(p, output + sizeof(output) - 2, orig, sizeof(u32));
  1608. *p++ = ')';
  1609. *p = '\0';
  1610. return string(buf, end, output, spec);
  1611. }
  1612. static noinline_for_stack
  1613. char *address_val(char *buf, char *end, const void *addr,
  1614. struct printf_spec spec, const char *fmt)
  1615. {
  1616. unsigned long long num;
  1617. int size;
  1618. if (check_pointer(&buf, end, addr, spec))
  1619. return buf;
  1620. switch (fmt[1]) {
  1621. case 'd':
  1622. num = *(const dma_addr_t *)addr;
  1623. size = sizeof(dma_addr_t);
  1624. break;
  1625. case 'p':
  1626. default:
  1627. num = *(const phys_addr_t *)addr;
  1628. size = sizeof(phys_addr_t);
  1629. break;
  1630. }
  1631. return special_hex_number(buf, end, num, size);
  1632. }
  1633. static noinline_for_stack
  1634. char *date_str(char *buf, char *end, const struct rtc_time *tm, bool r)
  1635. {
  1636. int year = tm->tm_year + (r ? 0 : 1900);
  1637. int mon = tm->tm_mon + (r ? 0 : 1);
  1638. buf = number(buf, end, year, default_dec04_spec);
  1639. if (buf < end)
  1640. *buf = '-';
  1641. buf++;
  1642. buf = number(buf, end, mon, default_dec02_spec);
  1643. if (buf < end)
  1644. *buf = '-';
  1645. buf++;
  1646. return number(buf, end, tm->tm_mday, default_dec02_spec);
  1647. }
  1648. static noinline_for_stack
  1649. char *time_str(char *buf, char *end, const struct rtc_time *tm, bool r)
  1650. {
  1651. buf = number(buf, end, tm->tm_hour, default_dec02_spec);
  1652. if (buf < end)
  1653. *buf = ':';
  1654. buf++;
  1655. buf = number(buf, end, tm->tm_min, default_dec02_spec);
  1656. if (buf < end)
  1657. *buf = ':';
  1658. buf++;
  1659. return number(buf, end, tm->tm_sec, default_dec02_spec);
  1660. }
  1661. static noinline_for_stack
  1662. char *rtc_str(char *buf, char *end, const struct rtc_time *tm,
  1663. struct printf_spec spec, const char *fmt)
  1664. {
  1665. bool have_t = true, have_d = true;
  1666. bool raw = false, iso8601_separator = true;
  1667. bool found = true;
  1668. int count = 2;
  1669. switch (fmt[count]) {
  1670. case 'd':
  1671. have_t = false;
  1672. count++;
  1673. break;
  1674. case 't':
  1675. have_d = false;
  1676. count++;
  1677. break;
  1678. }
  1679. do {
  1680. switch (fmt[count++]) {
  1681. case 'r':
  1682. raw = true;
  1683. break;
  1684. case 's':
  1685. iso8601_separator = false;
  1686. break;
  1687. default:
  1688. found = false;
  1689. break;
  1690. }
  1691. } while (found);
  1692. if (have_d)
  1693. buf = date_str(buf, end, tm, raw);
  1694. if (have_d && have_t) {
  1695. if (buf < end)
  1696. *buf = iso8601_separator ? 'T' : ' ';
  1697. buf++;
  1698. }
  1699. if (have_t)
  1700. buf = time_str(buf, end, tm, raw);
  1701. return buf;
  1702. }
  1703. static noinline_for_stack
  1704. char *time64_str(char *buf, char *end, const time64_t time,
  1705. struct printf_spec spec, const char *fmt)
  1706. {
  1707. struct rtc_time rtc_time;
  1708. struct tm tm;
  1709. time64_to_tm(time, 0, &tm);
  1710. rtc_time.tm_sec = tm.tm_sec;
  1711. rtc_time.tm_min = tm.tm_min;
  1712. rtc_time.tm_hour = tm.tm_hour;
  1713. rtc_time.tm_mday = tm.tm_mday;
  1714. rtc_time.tm_mon = tm.tm_mon;
  1715. rtc_time.tm_year = tm.tm_year;
  1716. rtc_time.tm_wday = tm.tm_wday;
  1717. rtc_time.tm_yday = tm.tm_yday;
  1718. rtc_time.tm_isdst = 0;
  1719. return rtc_str(buf, end, &rtc_time, spec, fmt);
  1720. }
  1721. static noinline_for_stack
  1722. char *timespec64_str(char *buf, char *end, const struct timespec64 *ts,
  1723. struct printf_spec spec, const char *fmt)
  1724. {
  1725. static const struct printf_spec default_dec09_spec = {
  1726. .base = 10,
  1727. .field_width = 9,
  1728. .precision = -1,
  1729. .flags = ZEROPAD,
  1730. };
  1731. if (fmt[2] == 'p')
  1732. buf = number(buf, end, ts->tv_sec, default_dec_spec);
  1733. else
  1734. buf = time64_str(buf, end, ts->tv_sec, spec, fmt);
  1735. if (buf < end)
  1736. *buf = '.';
  1737. buf++;
  1738. return number(buf, end, ts->tv_nsec, default_dec09_spec);
  1739. }
  1740. static noinline_for_stack
  1741. char *time_and_date(char *buf, char *end, void *ptr, struct printf_spec spec,
  1742. const char *fmt)
  1743. {
  1744. if (check_pointer(&buf, end, ptr, spec))
  1745. return buf;
  1746. switch (fmt[1]) {
  1747. case 'R':
  1748. return rtc_str(buf, end, (const struct rtc_time *)ptr, spec, fmt);
  1749. case 'S':
  1750. return timespec64_str(buf, end, (const struct timespec64 *)ptr, spec, fmt);
  1751. case 'T':
  1752. return time64_str(buf, end, *(const time64_t *)ptr, spec, fmt);
  1753. default:
  1754. return error_string(buf, end, "(%pt?)", spec);
  1755. }
  1756. }
  1757. static noinline_for_stack
  1758. char *clock(char *buf, char *end, struct clk *clk, struct printf_spec spec,
  1759. const char *fmt)
  1760. {
  1761. if (!IS_ENABLED(CONFIG_HAVE_CLK))
  1762. return error_string(buf, end, "(%pC?)", spec);
  1763. if (check_pointer(&buf, end, clk, spec))
  1764. return buf;
  1765. #ifdef CONFIG_COMMON_CLK
  1766. return string(buf, end, __clk_get_name(clk), spec);
  1767. #else
  1768. return ptr_to_id(buf, end, clk, spec);
  1769. #endif
  1770. }
  1771. static
  1772. char *format_flags(char *buf, char *end, unsigned long flags,
  1773. const struct trace_print_flags *names)
  1774. {
  1775. unsigned long mask;
  1776. for ( ; flags && names->name; names++) {
  1777. mask = names->mask;
  1778. if ((flags & mask) != mask)
  1779. continue;
  1780. buf = string(buf, end, names->name, default_str_spec);
  1781. flags &= ~mask;
  1782. if (flags) {
  1783. if (buf < end)
  1784. *buf = '|';
  1785. buf++;
  1786. }
  1787. }
  1788. if (flags)
  1789. buf = number(buf, end, flags, default_flag_spec);
  1790. return buf;
  1791. }
  1792. struct page_flags_fields {
  1793. int width;
  1794. int shift;
  1795. int mask;
  1796. const struct printf_spec *spec;
  1797. const char *name;
  1798. };
  1799. static const struct page_flags_fields pff[] = {
  1800. {SECTIONS_WIDTH, SECTIONS_PGSHIFT, SECTIONS_MASK,
  1801. &default_dec_spec, "section"},
  1802. {NODES_WIDTH, NODES_PGSHIFT, NODES_MASK,
  1803. &default_dec_spec, "node"},
  1804. {ZONES_WIDTH, ZONES_PGSHIFT, ZONES_MASK,
  1805. &default_dec_spec, "zone"},
  1806. {LAST_CPUPID_WIDTH, LAST_CPUPID_PGSHIFT, LAST_CPUPID_MASK,
  1807. &default_flag_spec, "lastcpupid"},
  1808. {KASAN_TAG_WIDTH, KASAN_TAG_PGSHIFT, KASAN_TAG_MASK,
  1809. &default_flag_spec, "kasantag"},
  1810. };
  1811. static
  1812. char *format_page_flags(char *buf, char *end, unsigned long flags)
  1813. {
  1814. unsigned long main_flags = flags & PAGEFLAGS_MASK;
  1815. bool append = false;
  1816. int i;
  1817. buf = number(buf, end, flags, default_flag_spec);
  1818. if (buf < end)
  1819. *buf = '(';
  1820. buf++;
  1821. /* Page flags from the main area. */
  1822. if (main_flags) {
  1823. buf = format_flags(buf, end, main_flags, pageflag_names);
  1824. append = true;
  1825. }
  1826. /* Page flags from the fields area */
  1827. for (i = 0; i < ARRAY_SIZE(pff); i++) {
  1828. /* Skip undefined fields. */
  1829. if (!pff[i].width)
  1830. continue;
  1831. /* Format: Flag Name + '=' (equals sign) + Number + '|' (separator) */
  1832. if (append) {
  1833. if (buf < end)
  1834. *buf = '|';
  1835. buf++;
  1836. }
  1837. buf = string(buf, end, pff[i].name, default_str_spec);
  1838. if (buf < end)
  1839. *buf = '=';
  1840. buf++;
  1841. buf = number(buf, end, (flags >> pff[i].shift) & pff[i].mask,
  1842. *pff[i].spec);
  1843. append = true;
  1844. }
  1845. if (buf < end)
  1846. *buf = ')';
  1847. buf++;
  1848. return buf;
  1849. }
  1850. static noinline_for_stack
  1851. char *flags_string(char *buf, char *end, void *flags_ptr,
  1852. struct printf_spec spec, const char *fmt)
  1853. {
  1854. unsigned long flags;
  1855. const struct trace_print_flags *names;
  1856. if (check_pointer(&buf, end, flags_ptr, spec))
  1857. return buf;
  1858. switch (fmt[1]) {
  1859. case 'p':
  1860. return format_page_flags(buf, end, *(unsigned long *)flags_ptr);
  1861. case 'v':
  1862. flags = *(unsigned long *)flags_ptr;
  1863. names = vmaflag_names;
  1864. break;
  1865. case 'g':
  1866. flags = (__force unsigned long)(*(gfp_t *)flags_ptr);
  1867. names = gfpflag_names;
  1868. break;
  1869. default:
  1870. return error_string(buf, end, "(%pG?)", spec);
  1871. }
  1872. return format_flags(buf, end, flags, names);
  1873. }
  1874. static noinline_for_stack
  1875. char *fwnode_full_name_string(struct fwnode_handle *fwnode, char *buf,
  1876. char *end)
  1877. {
  1878. int depth;
  1879. /* Loop starting from the root node to the current node. */
  1880. for (depth = fwnode_count_parents(fwnode); depth >= 0; depth--) {
  1881. /*
  1882. * Only get a reference for other nodes (i.e. parent nodes).
  1883. * fwnode refcount may be 0 here.
  1884. */
  1885. struct fwnode_handle *__fwnode = depth ?
  1886. fwnode_get_nth_parent(fwnode, depth) : fwnode;
  1887. buf = string(buf, end, fwnode_get_name_prefix(__fwnode),
  1888. default_str_spec);
  1889. buf = string(buf, end, fwnode_get_name(__fwnode),
  1890. default_str_spec);
  1891. if (depth)
  1892. fwnode_handle_put(__fwnode);
  1893. }
  1894. return buf;
  1895. }
  1896. static noinline_for_stack
  1897. char *device_node_string(char *buf, char *end, struct device_node *dn,
  1898. struct printf_spec spec, const char *fmt)
  1899. {
  1900. char tbuf[sizeof("xxxx") + 1];
  1901. const char *p;
  1902. int ret;
  1903. char *buf_start = buf;
  1904. struct property *prop;
  1905. bool has_mult, pass;
  1906. struct printf_spec str_spec = spec;
  1907. str_spec.field_width = -1;
  1908. if (fmt[0] != 'F')
  1909. return error_string(buf, end, "(%pO?)", spec);
  1910. if (!IS_ENABLED(CONFIG_OF))
  1911. return error_string(buf, end, "(%pOF?)", spec);
  1912. if (check_pointer(&buf, end, dn, spec))
  1913. return buf;
  1914. /* simple case without anything any more format specifiers */
  1915. fmt++;
  1916. if (fmt[0] == '\0' || strcspn(fmt,"fnpPFcC") > 0)
  1917. fmt = "f";
  1918. for (pass = false; strspn(fmt,"fnpPFcC"); fmt++, pass = true) {
  1919. int precision;
  1920. if (pass) {
  1921. if (buf < end)
  1922. *buf = ':';
  1923. buf++;
  1924. }
  1925. switch (*fmt) {
  1926. case 'f': /* full_name */
  1927. buf = fwnode_full_name_string(of_fwnode_handle(dn), buf,
  1928. end);
  1929. break;
  1930. case 'n': /* name */
  1931. p = fwnode_get_name(of_fwnode_handle(dn));
  1932. precision = str_spec.precision;
  1933. str_spec.precision = strchrnul(p, '@') - p;
  1934. buf = string(buf, end, p, str_spec);
  1935. str_spec.precision = precision;
  1936. break;
  1937. case 'p': /* phandle */
  1938. buf = number(buf, end, (unsigned int)dn->phandle, default_dec_spec);
  1939. break;
  1940. case 'P': /* path-spec */
  1941. p = fwnode_get_name(of_fwnode_handle(dn));
  1942. if (!p[1])
  1943. p = "/";
  1944. buf = string(buf, end, p, str_spec);
  1945. break;
  1946. case 'F': /* flags */
  1947. tbuf[0] = of_node_check_flag(dn, OF_DYNAMIC) ? 'D' : '-';
  1948. tbuf[1] = of_node_check_flag(dn, OF_DETACHED) ? 'd' : '-';
  1949. tbuf[2] = of_node_check_flag(dn, OF_POPULATED) ? 'P' : '-';
  1950. tbuf[3] = of_node_check_flag(dn, OF_POPULATED_BUS) ? 'B' : '-';
  1951. tbuf[4] = 0;
  1952. buf = string_nocheck(buf, end, tbuf, str_spec);
  1953. break;
  1954. case 'c': /* major compatible string */
  1955. ret = of_property_read_string(dn, "compatible", &p);
  1956. if (!ret)
  1957. buf = string(buf, end, p, str_spec);
  1958. break;
  1959. case 'C': /* full compatible string */
  1960. has_mult = false;
  1961. of_property_for_each_string(dn, "compatible", prop, p) {
  1962. if (has_mult)
  1963. buf = string_nocheck(buf, end, ",", str_spec);
  1964. buf = string_nocheck(buf, end, "\"", str_spec);
  1965. buf = string(buf, end, p, str_spec);
  1966. buf = string_nocheck(buf, end, "\"", str_spec);
  1967. has_mult = true;
  1968. }
  1969. break;
  1970. default:
  1971. break;
  1972. }
  1973. }
  1974. return widen_string(buf, buf - buf_start, end, spec);
  1975. }
  1976. static noinline_for_stack
  1977. char *fwnode_string(char *buf, char *end, struct fwnode_handle *fwnode,
  1978. struct printf_spec spec, const char *fmt)
  1979. {
  1980. struct printf_spec str_spec = spec;
  1981. char *buf_start = buf;
  1982. str_spec.field_width = -1;
  1983. if (*fmt != 'w')
  1984. return error_string(buf, end, "(%pf?)", spec);
  1985. if (check_pointer(&buf, end, fwnode, spec))
  1986. return buf;
  1987. fmt++;
  1988. switch (*fmt) {
  1989. case 'P': /* name */
  1990. buf = string(buf, end, fwnode_get_name(fwnode), str_spec);
  1991. break;
  1992. case 'f': /* full_name */
  1993. default:
  1994. buf = fwnode_full_name_string(fwnode, buf, end);
  1995. break;
  1996. }
  1997. return widen_string(buf, buf - buf_start, end, spec);
  1998. }
  1999. static noinline_for_stack
  2000. char *resource_or_range(const char *fmt, char *buf, char *end, void *ptr,
  2001. struct printf_spec spec)
  2002. {
  2003. if (*fmt == 'r' && fmt[1] == 'a')
  2004. return range_string(buf, end, ptr, spec, fmt);
  2005. return resource_string(buf, end, ptr, spec, fmt);
  2006. }
  2007. void __init hash_pointers_finalize(bool slub_debug)
  2008. {
  2009. switch (hash_pointers_mode) {
  2010. case HASH_PTR_ALWAYS:
  2011. no_hash_pointers = false;
  2012. break;
  2013. case HASH_PTR_NEVER:
  2014. no_hash_pointers = true;
  2015. break;
  2016. case HASH_PTR_AUTO:
  2017. default:
  2018. no_hash_pointers = slub_debug;
  2019. break;
  2020. }
  2021. if (!no_hash_pointers)
  2022. return;
  2023. pr_warn("**********************************************************\n");
  2024. pr_warn("** NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE **\n");
  2025. pr_warn("** **\n");
  2026. pr_warn("** This system shows unhashed kernel memory addresses **\n");
  2027. pr_warn("** via the console, logs, and other interfaces. This **\n");
  2028. pr_warn("** might reduce the security of your system. **\n");
  2029. pr_warn("** **\n");
  2030. pr_warn("** If you see this message and you are not debugging **\n");
  2031. pr_warn("** the kernel, report this immediately to your system **\n");
  2032. pr_warn("** administrator! **\n");
  2033. pr_warn("** **\n");
  2034. pr_warn("** Use hash_pointers=always to force this mode off **\n");
  2035. pr_warn("** **\n");
  2036. pr_warn("** NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE **\n");
  2037. pr_warn("**********************************************************\n");
  2038. }
  2039. static int __init hash_pointers_mode_parse(char *str)
  2040. {
  2041. if (!str) {
  2042. pr_warn("Hash pointers mode empty; falling back to auto.\n");
  2043. hash_pointers_mode = HASH_PTR_AUTO;
  2044. } else if (strncmp(str, "auto", 4) == 0) {
  2045. pr_info("Hash pointers mode set to auto.\n");
  2046. hash_pointers_mode = HASH_PTR_AUTO;
  2047. } else if (strncmp(str, "never", 5) == 0) {
  2048. pr_info("Hash pointers mode set to never.\n");
  2049. hash_pointers_mode = HASH_PTR_NEVER;
  2050. } else if (strncmp(str, "always", 6) == 0) {
  2051. pr_info("Hash pointers mode set to always.\n");
  2052. hash_pointers_mode = HASH_PTR_ALWAYS;
  2053. } else {
  2054. pr_warn("Unknown hash_pointers mode '%s' specified; assuming auto.\n", str);
  2055. hash_pointers_mode = HASH_PTR_AUTO;
  2056. }
  2057. return 0;
  2058. }
  2059. early_param("hash_pointers", hash_pointers_mode_parse);
  2060. static int __init no_hash_pointers_enable(char *str)
  2061. {
  2062. return hash_pointers_mode_parse("never");
  2063. }
  2064. early_param("no_hash_pointers", no_hash_pointers_enable);
  2065. /*
  2066. * Show a '%p' thing. A kernel extension is that the '%p' is followed
  2067. * by an extra set of alphanumeric characters that are extended format
  2068. * specifiers.
  2069. *
  2070. * Please update scripts/checkpatch.pl when adding/removing conversion
  2071. * characters. (Search for "check for vsprintf extension").
  2072. *
  2073. * Right now we handle:
  2074. *
  2075. * - 'S' For symbolic direct pointers (or function descriptors) with offset
  2076. * - 's' For symbolic direct pointers (or function descriptors) without offset
  2077. * - '[Ss]R' as above with __builtin_extract_return_addr() translation
  2078. * - 'S[R]b' as above with module build ID (for use in backtraces)
  2079. * - '[Ff]' %pf and %pF were obsoleted and later removed in favor of
  2080. * %ps and %pS. Be careful when re-using these specifiers.
  2081. * - 'B' For backtraced symbolic direct pointers with offset
  2082. * - 'Bb' as above with module build ID (for use in backtraces)
  2083. * - 'R' For decoded struct resource, e.g., [mem 0x0-0x1f 64bit pref]
  2084. * - 'r' For raw struct resource, e.g., [mem 0x0-0x1f flags 0x201]
  2085. * - 'ra' For struct ranges, e.g., [range 0x0000000000000000 - 0x00000000000000ff]
  2086. * - 'b[l]' For a bitmap, the number of bits is determined by the field
  2087. * width which must be explicitly specified either as part of the
  2088. * format string '%32b[l]' or through '%*b[l]', [l] selects
  2089. * range-list format instead of hex format
  2090. * - 'M' For a 6-byte MAC address, it prints the address in the
  2091. * usual colon-separated hex notation
  2092. * - 'm' For a 6-byte MAC address, it prints the hex address without colons
  2093. * - 'MF' For a 6-byte MAC FDDI address, it prints the address
  2094. * with a dash-separated hex notation
  2095. * - '[mM]R' For a 6-byte MAC address, Reverse order (Bluetooth)
  2096. * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way
  2097. * IPv4 uses dot-separated decimal without leading 0's (1.2.3.4)
  2098. * IPv6 uses colon separated network-order 16 bit hex with leading 0's
  2099. * [S][pfs]
  2100. * Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
  2101. * [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
  2102. * - 'i' [46] for 'raw' IPv4/IPv6 addresses
  2103. * IPv6 omits the colons (01020304...0f)
  2104. * IPv4 uses dot-separated decimal with leading 0's (010.123.045.006)
  2105. * [S][pfs]
  2106. * Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
  2107. * [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
  2108. * - '[Ii][4S][hnbl]' IPv4 addresses in host, network, big or little endian order
  2109. * - 'I[6S]c' for IPv6 addresses printed as specified by
  2110. * https://tools.ietf.org/html/rfc5952
  2111. * - 'E[achnops]' For an escaped buffer, where rules are defined by combination
  2112. * of the following flags (see string_escape_mem() for the
  2113. * details):
  2114. * a - ESCAPE_ANY
  2115. * c - ESCAPE_SPECIAL
  2116. * h - ESCAPE_HEX
  2117. * n - ESCAPE_NULL
  2118. * o - ESCAPE_OCTAL
  2119. * p - ESCAPE_NP
  2120. * s - ESCAPE_SPACE
  2121. * By default ESCAPE_ANY_NP is used.
  2122. * - 'U' For a 16 byte UUID/GUID, it prints the UUID/GUID in the form
  2123. * "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
  2124. * Options for %pU are:
  2125. * b big endian lower case hex (default)
  2126. * B big endian UPPER case hex
  2127. * l little endian lower case hex
  2128. * L little endian UPPER case hex
  2129. * big endian output byte order is:
  2130. * [0][1][2][3]-[4][5]-[6][7]-[8][9]-[10][11][12][13][14][15]
  2131. * little endian output byte order is:
  2132. * [3][2][1][0]-[5][4]-[7][6]-[8][9]-[10][11][12][13][14][15]
  2133. * - 'V' For a struct va_format which contains a format string * and va_list *,
  2134. * call vsnprintf(->format, *->va_list).
  2135. * Implements a "recursive vsnprintf".
  2136. * Do not use this feature without some mechanism to verify the
  2137. * correctness of the format string and va_list arguments.
  2138. * - 'K' For a kernel pointer that should be hidden from unprivileged users.
  2139. * Use only for procfs, sysfs and similar files, not printk(); please
  2140. * read the documentation (path below) first.
  2141. * - 'NF' For a netdev_features_t
  2142. * - '4cc' V4L2 or DRM FourCC code, with endianness and raw numerical value.
  2143. * - '4c[h[R]lb]' For generic FourCC code with raw numerical value. Both are
  2144. * displayed in the big-endian format. This is the opposite of V4L2 or
  2145. * DRM FourCCs.
  2146. * The additional specifiers define what endianness is used to load
  2147. * the stored bytes. The data might be interpreted using the host,
  2148. * reversed host byte order, little-endian, or big-endian.
  2149. * - 'h[CDN]' For a variable-length buffer, it prints it as a hex string with
  2150. * a certain separator (' ' by default):
  2151. * C colon
  2152. * D dash
  2153. * N no separator
  2154. * The maximum supported length is 64 bytes of the input. Consider
  2155. * to use print_hex_dump() for the larger input.
  2156. * - 'a[pd]' For address types [p] phys_addr_t, [d] dma_addr_t and derivatives
  2157. * (default assumed to be phys_addr_t, passed by reference)
  2158. * - 'd[234]' For a dentry name (optionally 2-4 last components)
  2159. * - 'D[234]' Same as 'd' but for a struct file
  2160. * - 'g' For block_device name (gendisk + partition number)
  2161. * - 't[RST][dt][r][s]' For time and date as represented by:
  2162. * R struct rtc_time
  2163. * S struct timespec64
  2164. * T time64_t
  2165. * - 'tSp' For time represented by struct timespec64 printed as <seconds>.<nanoseconds>
  2166. * - 'C' For a clock, it prints the name (Common Clock Framework) or address
  2167. * (legacy clock framework) of the clock
  2168. * - 'G' For flags to be printed as a collection of symbolic strings that would
  2169. * construct the specific value. Supported flags given by option:
  2170. * p page flags (see struct page) given as pointer to unsigned long
  2171. * g gfp flags (GFP_* and __GFP_*) given as pointer to gfp_t
  2172. * v vma flags (VM_*) given as pointer to unsigned long
  2173. * - 'OF[fnpPcCF]' For a device tree object
  2174. * Without any optional arguments prints the full_name
  2175. * f device node full_name
  2176. * n device node name
  2177. * p device node phandle
  2178. * P device node path spec (name + @unit)
  2179. * F device node flags
  2180. * c major compatible string
  2181. * C full compatible string
  2182. * - 'fw[fP]' For a firmware node (struct fwnode_handle) pointer
  2183. * Without an option prints the full name of the node
  2184. * f full name
  2185. * P node name, including a possible unit address
  2186. * - 'x' For printing the address unmodified. Equivalent to "%lx".
  2187. * Please read the documentation (path below) before using!
  2188. * - '[ku]s' For a BPF/tracing related format specifier, e.g. used out of
  2189. * bpf_trace_printk() where [ku] prefix specifies either kernel (k)
  2190. * or user (u) memory to probe, and:
  2191. * s a string, equivalent to "%s" on direct vsnprintf() use
  2192. *
  2193. * ** When making changes please also update:
  2194. * Documentation/core-api/printk-formats.rst
  2195. *
  2196. * Note: The default behaviour (unadorned %p) is to hash the address,
  2197. * rendering it useful as a unique identifier.
  2198. *
  2199. * There is also a '%pA' format specifier, but it is only intended to be used
  2200. * from Rust code to format core::fmt::Arguments. Do *not* use it from C.
  2201. * See rust/kernel/print.rs for details.
  2202. */
  2203. static noinline_for_stack
  2204. char *pointer(const char *fmt, char *buf, char *end, void *ptr,
  2205. struct printf_spec spec)
  2206. {
  2207. switch (*fmt) {
  2208. case 'S':
  2209. case 's':
  2210. ptr = dereference_symbol_descriptor(ptr);
  2211. fallthrough;
  2212. case 'B':
  2213. return symbol_string(buf, end, ptr, spec, fmt);
  2214. case 'R':
  2215. case 'r':
  2216. return resource_or_range(fmt, buf, end, ptr, spec);
  2217. case 'h':
  2218. return hex_string(buf, end, ptr, spec, fmt);
  2219. case 'b':
  2220. switch (fmt[1]) {
  2221. case 'l':
  2222. return bitmap_list_string(buf, end, ptr, spec, fmt);
  2223. default:
  2224. return bitmap_string(buf, end, ptr, spec, fmt);
  2225. }
  2226. case 'M': /* Colon separated: 00:01:02:03:04:05 */
  2227. case 'm': /* Contiguous: 000102030405 */
  2228. /* [mM]F (FDDI) */
  2229. /* [mM]R (Reverse order; Bluetooth) */
  2230. return mac_address_string(buf, end, ptr, spec, fmt);
  2231. case 'I': /* Formatted IP supported
  2232. * 4: 1.2.3.4
  2233. * 6: 0001:0203:...:0708
  2234. * 6c: 1::708 or 1::1.2.3.4
  2235. */
  2236. case 'i': /* Contiguous:
  2237. * 4: 001.002.003.004
  2238. * 6: 000102...0f
  2239. */
  2240. return ip_addr_string(buf, end, ptr, spec, fmt);
  2241. case 'E':
  2242. return escaped_string(buf, end, ptr, spec, fmt);
  2243. case 'U':
  2244. return uuid_string(buf, end, ptr, spec, fmt);
  2245. case 'V':
  2246. return va_format(buf, end, ptr, spec);
  2247. case 'K':
  2248. return restricted_pointer(buf, end, ptr, spec);
  2249. case 'N':
  2250. return netdev_bits(buf, end, ptr, spec, fmt);
  2251. case '4':
  2252. return fourcc_string(buf, end, ptr, spec, fmt);
  2253. case 'a':
  2254. return address_val(buf, end, ptr, spec, fmt);
  2255. case 'd':
  2256. return dentry_name(buf, end, ptr, spec, fmt);
  2257. case 't':
  2258. return time_and_date(buf, end, ptr, spec, fmt);
  2259. case 'C':
  2260. return clock(buf, end, ptr, spec, fmt);
  2261. case 'D':
  2262. return file_dentry_name(buf, end, ptr, spec, fmt);
  2263. #ifdef CONFIG_BLOCK
  2264. case 'g':
  2265. return bdev_name(buf, end, ptr, spec, fmt);
  2266. #endif
  2267. case 'G':
  2268. return flags_string(buf, end, ptr, spec, fmt);
  2269. case 'O':
  2270. return device_node_string(buf, end, ptr, spec, fmt + 1);
  2271. case 'f':
  2272. return fwnode_string(buf, end, ptr, spec, fmt + 1);
  2273. case 'A':
  2274. if (!IS_ENABLED(CONFIG_RUST)) {
  2275. WARN_ONCE(1, "Please remove %%pA from non-Rust code\n");
  2276. return error_string(buf, end, "(%pA?)", spec);
  2277. }
  2278. return rust_fmt_argument(buf, end, ptr);
  2279. case 'x':
  2280. return pointer_string(buf, end, ptr, spec);
  2281. case 'e':
  2282. /* %pe with a non-ERR_PTR gets treated as plain %p */
  2283. if (!IS_ERR(ptr))
  2284. return default_pointer(buf, end, ptr, spec);
  2285. return err_ptr(buf, end, ptr, spec);
  2286. case 'u':
  2287. case 'k':
  2288. switch (fmt[1]) {
  2289. case 's':
  2290. return string(buf, end, ptr, spec);
  2291. default:
  2292. return error_string(buf, end, "(einval)", spec);
  2293. }
  2294. default:
  2295. return default_pointer(buf, end, ptr, spec);
  2296. }
  2297. }
  2298. struct fmt {
  2299. const char *str;
  2300. unsigned char state; // enum format_state
  2301. unsigned char size; // size of numbers
  2302. };
  2303. #define SPEC_CHAR(x, flag) [(x)-32] = flag
  2304. static unsigned char spec_flag(unsigned char c)
  2305. {
  2306. static const unsigned char spec_flag_array[] = {
  2307. SPEC_CHAR(' ', SPACE),
  2308. SPEC_CHAR('#', SPECIAL),
  2309. SPEC_CHAR('+', PLUS),
  2310. SPEC_CHAR('-', LEFT),
  2311. SPEC_CHAR('0', ZEROPAD),
  2312. };
  2313. c -= 32;
  2314. return (c < sizeof(spec_flag_array)) ? spec_flag_array[c] : 0;
  2315. }
  2316. /*
  2317. * Helper function to decode printf style format.
  2318. * Each call decode a token from the format and return the
  2319. * number of characters read (or likely the delta where it wants
  2320. * to go on the next call).
  2321. * The decoded token is returned through the parameters
  2322. *
  2323. * 'h', 'l', or 'L' for integer fields
  2324. * 'z' support added 23/7/1999 S.H.
  2325. * 'z' changed to 'Z' --davidm 1/25/99
  2326. * 'Z' changed to 'z' --adobriyan 2017-01-25
  2327. * 't' added for ptrdiff_t
  2328. *
  2329. * @fmt: the format string
  2330. * @type of the token returned
  2331. * @flags: various flags such as +, -, # tokens..
  2332. * @field_width: overwritten width
  2333. * @base: base of the number (octal, hex, ...)
  2334. * @precision: precision of a number
  2335. * @qualifier: qualifier of a number (long, size_t, ...)
  2336. */
  2337. static noinline_for_stack
  2338. struct fmt format_decode(struct fmt fmt, struct printf_spec *spec)
  2339. {
  2340. const char *start = fmt.str;
  2341. char flag;
  2342. /* we finished early by reading the field width */
  2343. if (unlikely(fmt.state == FORMAT_STATE_WIDTH)) {
  2344. if (spec->field_width < 0) {
  2345. spec->field_width = -spec->field_width;
  2346. spec->flags |= LEFT;
  2347. }
  2348. fmt.state = FORMAT_STATE_NONE;
  2349. goto precision;
  2350. }
  2351. /* we finished early by reading the precision */
  2352. if (unlikely(fmt.state == FORMAT_STATE_PRECISION)) {
  2353. if (spec->precision < 0)
  2354. spec->precision = 0;
  2355. fmt.state = FORMAT_STATE_NONE;
  2356. goto qualifier;
  2357. }
  2358. /* By default */
  2359. fmt.state = FORMAT_STATE_NONE;
  2360. for (; *fmt.str ; fmt.str++) {
  2361. if (*fmt.str == '%')
  2362. break;
  2363. }
  2364. /* Return the current non-format string */
  2365. if (fmt.str != start || !*fmt.str)
  2366. return fmt;
  2367. /* Process flags. This also skips the first '%' */
  2368. spec->flags = 0;
  2369. do {
  2370. /* this also skips first '%' */
  2371. flag = spec_flag(*++fmt.str);
  2372. spec->flags |= flag;
  2373. } while (flag);
  2374. /* get field width */
  2375. spec->field_width = -1;
  2376. if (isdigit(*fmt.str))
  2377. spec->field_width = skip_atoi(&fmt.str);
  2378. else if (unlikely(*fmt.str == '*')) {
  2379. /* it's the next argument */
  2380. fmt.state = FORMAT_STATE_WIDTH;
  2381. fmt.str++;
  2382. return fmt;
  2383. }
  2384. precision:
  2385. /* get the precision */
  2386. spec->precision = -1;
  2387. if (unlikely(*fmt.str == '.')) {
  2388. fmt.str++;
  2389. if (isdigit(*fmt.str)) {
  2390. spec->precision = skip_atoi(&fmt.str);
  2391. if (spec->precision < 0)
  2392. spec->precision = 0;
  2393. } else if (*fmt.str == '*') {
  2394. /* it's the next argument */
  2395. fmt.state = FORMAT_STATE_PRECISION;
  2396. fmt.str++;
  2397. return fmt;
  2398. }
  2399. }
  2400. qualifier:
  2401. /* Set up default numeric format */
  2402. spec->base = 10;
  2403. fmt.state = FORMAT_STATE_NUM;
  2404. fmt.size = sizeof(int);
  2405. static const struct format_state {
  2406. unsigned char state;
  2407. unsigned char size;
  2408. unsigned char flags_or_double_size;
  2409. unsigned char base;
  2410. } lookup_state[256] = {
  2411. // Length
  2412. ['l'] = { 0, sizeof(long), sizeof(long long) },
  2413. ['L'] = { 0, sizeof(long long) },
  2414. ['h'] = { 0, sizeof(short), sizeof(char) },
  2415. ['H'] = { 0, sizeof(char) }, // Questionable historical
  2416. ['z'] = { 0, sizeof(size_t) },
  2417. ['t'] = { 0, sizeof(ptrdiff_t) },
  2418. // Non-numeric formats
  2419. ['c'] = { FORMAT_STATE_CHAR },
  2420. ['s'] = { FORMAT_STATE_STR },
  2421. ['p'] = { FORMAT_STATE_PTR },
  2422. ['%'] = { FORMAT_STATE_PERCENT_CHAR },
  2423. // Numerics
  2424. ['o'] = { FORMAT_STATE_NUM, 0, 0, 8 },
  2425. ['x'] = { FORMAT_STATE_NUM, 0, SMALL, 16 },
  2426. ['X'] = { FORMAT_STATE_NUM, 0, 0, 16 },
  2427. ['d'] = { FORMAT_STATE_NUM, 0, SIGN, 10 },
  2428. ['i'] = { FORMAT_STATE_NUM, 0, SIGN, 10 },
  2429. ['u'] = { FORMAT_STATE_NUM, 0, 0, 10, },
  2430. /*
  2431. * Since %n poses a greater security risk than
  2432. * utility, treat it as any other invalid or
  2433. * unsupported format specifier.
  2434. */
  2435. };
  2436. const struct format_state *p = lookup_state + (u8)*fmt.str;
  2437. if (p->size) {
  2438. fmt.size = p->size;
  2439. if (p->flags_or_double_size && fmt.str[0] == fmt.str[1]) {
  2440. fmt.size = p->flags_or_double_size;
  2441. fmt.str++;
  2442. }
  2443. fmt.str++;
  2444. p = lookup_state + *fmt.str;
  2445. }
  2446. if (p->state) {
  2447. if (p->base)
  2448. spec->base = p->base;
  2449. spec->flags |= p->flags_or_double_size;
  2450. fmt.state = p->state;
  2451. fmt.str++;
  2452. return fmt;
  2453. }
  2454. WARN_ONCE(1, "Please remove unsupported %%%c in format string\n", *fmt.str);
  2455. fmt.state = FORMAT_STATE_INVALID;
  2456. return fmt;
  2457. }
  2458. static void
  2459. set_field_width(struct printf_spec *spec, int width)
  2460. {
  2461. spec->field_width = width;
  2462. if (WARN_ONCE(spec->field_width != width, "field width %d too large", width)) {
  2463. spec->field_width = clamp(width, -FIELD_WIDTH_MAX, FIELD_WIDTH_MAX);
  2464. }
  2465. }
  2466. static void
  2467. set_precision(struct printf_spec *spec, int prec)
  2468. {
  2469. spec->precision = prec;
  2470. if (WARN_ONCE(spec->precision != prec, "precision %d too large", prec)) {
  2471. spec->precision = clamp(prec, 0, PRECISION_MAX);
  2472. }
  2473. }
  2474. /*
  2475. * Turn a 1/2/4-byte value into a 64-bit one for printing: truncate
  2476. * as necessary and deal with signedness.
  2477. *
  2478. * 'size' is the size of the value in bytes.
  2479. */
  2480. static unsigned long long convert_num_spec(unsigned int val, int size, struct printf_spec spec)
  2481. {
  2482. unsigned int shift = 32 - size*8;
  2483. val <<= shift;
  2484. if (!(spec.flags & SIGN))
  2485. return val >> shift;
  2486. return (int)val >> shift;
  2487. }
  2488. /**
  2489. * vsnprintf - Format a string and place it in a buffer
  2490. * @buf: The buffer to place the result into
  2491. * @size: The size of the buffer, including the trailing null space
  2492. * @fmt_str: The format string to use
  2493. * @args: Arguments for the format string
  2494. *
  2495. * This function generally follows C99 vsnprintf, but has some
  2496. * extensions and a few limitations:
  2497. *
  2498. * - ``%n`` is unsupported
  2499. * - ``%p*`` is handled by pointer()
  2500. *
  2501. * See pointer() or Documentation/core-api/printk-formats.rst for more
  2502. * extensive description.
  2503. *
  2504. * **Please update the documentation in both places when making changes**
  2505. *
  2506. * The return value is the number of characters which would
  2507. * be generated for the given input, excluding the trailing
  2508. * '\0', as per ISO C99. If you want to have the exact
  2509. * number of characters written into @buf as return value
  2510. * (not including the trailing '\0'), use vscnprintf(). If the
  2511. * return is greater than or equal to @size, the resulting
  2512. * string is truncated.
  2513. *
  2514. * If you're not already dealing with a va_list consider using snprintf().
  2515. */
  2516. int vsnprintf(char *buf, size_t size, const char *fmt_str, va_list args)
  2517. {
  2518. char *str, *end;
  2519. struct printf_spec spec = {0};
  2520. struct fmt fmt = {
  2521. .str = fmt_str,
  2522. .state = FORMAT_STATE_NONE,
  2523. };
  2524. /* Reject out-of-range values early. Large positive sizes are
  2525. used for unknown buffer sizes. */
  2526. if (WARN_ON_ONCE(size > INT_MAX))
  2527. return 0;
  2528. str = buf;
  2529. end = buf + size;
  2530. /* Make sure end is always >= buf */
  2531. if (end < buf) {
  2532. end = ((void *)-1);
  2533. size = end - buf;
  2534. }
  2535. while (*fmt.str) {
  2536. const char *old_fmt = fmt.str;
  2537. fmt = format_decode(fmt, &spec);
  2538. switch (fmt.state) {
  2539. case FORMAT_STATE_NONE: {
  2540. int read = fmt.str - old_fmt;
  2541. if (str < end) {
  2542. int copy = read;
  2543. if (copy > end - str)
  2544. copy = end - str;
  2545. memcpy(str, old_fmt, copy);
  2546. }
  2547. str += read;
  2548. continue;
  2549. }
  2550. case FORMAT_STATE_NUM: {
  2551. unsigned long long num;
  2552. if (fmt.size > sizeof(int))
  2553. num = va_arg(args, long long);
  2554. else
  2555. num = convert_num_spec(va_arg(args, int), fmt.size, spec);
  2556. str = number(str, end, num, spec);
  2557. continue;
  2558. }
  2559. case FORMAT_STATE_WIDTH:
  2560. set_field_width(&spec, va_arg(args, int));
  2561. continue;
  2562. case FORMAT_STATE_PRECISION:
  2563. set_precision(&spec, va_arg(args, int));
  2564. continue;
  2565. case FORMAT_STATE_CHAR: {
  2566. char c;
  2567. if (!(spec.flags & LEFT)) {
  2568. while (--spec.field_width > 0) {
  2569. if (str < end)
  2570. *str = ' ';
  2571. ++str;
  2572. }
  2573. }
  2574. c = (unsigned char) va_arg(args, int);
  2575. if (str < end)
  2576. *str = c;
  2577. ++str;
  2578. while (--spec.field_width > 0) {
  2579. if (str < end)
  2580. *str = ' ';
  2581. ++str;
  2582. }
  2583. continue;
  2584. }
  2585. case FORMAT_STATE_STR:
  2586. str = string(str, end, va_arg(args, char *), spec);
  2587. continue;
  2588. case FORMAT_STATE_PTR:
  2589. str = pointer(fmt.str, str, end, va_arg(args, void *),
  2590. spec);
  2591. while (isalnum(*fmt.str))
  2592. fmt.str++;
  2593. continue;
  2594. case FORMAT_STATE_PERCENT_CHAR:
  2595. if (str < end)
  2596. *str = '%';
  2597. ++str;
  2598. continue;
  2599. default:
  2600. /*
  2601. * Presumably the arguments passed gcc's type
  2602. * checking, but there is no safe or sane way
  2603. * for us to continue parsing the format and
  2604. * fetching from the va_list; the remaining
  2605. * specifiers and arguments would be out of
  2606. * sync.
  2607. */
  2608. goto out;
  2609. }
  2610. }
  2611. out:
  2612. if (size > 0) {
  2613. if (str < end)
  2614. *str = '\0';
  2615. else
  2616. end[-1] = '\0';
  2617. }
  2618. /* the trailing null byte doesn't count towards the total */
  2619. return str-buf;
  2620. }
  2621. EXPORT_SYMBOL(vsnprintf);
  2622. /**
  2623. * vscnprintf - Format a string and place it in a buffer
  2624. * @buf: The buffer to place the result into
  2625. * @size: The size of the buffer, including the trailing null space
  2626. * @fmt: The format string to use
  2627. * @args: Arguments for the format string
  2628. *
  2629. * The return value is the number of characters which have been written into
  2630. * the @buf not including the trailing '\0'. If @size is == 0 the function
  2631. * returns 0.
  2632. *
  2633. * If you're not already dealing with a va_list consider using scnprintf().
  2634. *
  2635. * See the vsnprintf() documentation for format string extensions over C99.
  2636. */
  2637. int vscnprintf(char *buf, size_t size, const char *fmt, va_list args)
  2638. {
  2639. int i;
  2640. if (unlikely(!size))
  2641. return 0;
  2642. i = vsnprintf(buf, size, fmt, args);
  2643. if (likely(i < size))
  2644. return i;
  2645. return size - 1;
  2646. }
  2647. EXPORT_SYMBOL(vscnprintf);
  2648. /**
  2649. * snprintf - Format a string and place it in a buffer
  2650. * @buf: The buffer to place the result into
  2651. * @size: The size of the buffer, including the trailing null space
  2652. * @fmt: The format string to use
  2653. * @...: Arguments for the format string
  2654. *
  2655. * The return value is the number of characters which would be
  2656. * generated for the given input, excluding the trailing null,
  2657. * as per ISO C99. If the return is greater than or equal to
  2658. * @size, the resulting string is truncated.
  2659. *
  2660. * See the vsnprintf() documentation for format string extensions over C99.
  2661. */
  2662. int snprintf(char *buf, size_t size, const char *fmt, ...)
  2663. {
  2664. va_list args;
  2665. int i;
  2666. va_start(args, fmt);
  2667. i = vsnprintf(buf, size, fmt, args);
  2668. va_end(args);
  2669. return i;
  2670. }
  2671. EXPORT_SYMBOL(snprintf);
  2672. /**
  2673. * scnprintf - Format a string and place it in a buffer
  2674. * @buf: The buffer to place the result into
  2675. * @size: The size of the buffer, including the trailing null space
  2676. * @fmt: The format string to use
  2677. * @...: Arguments for the format string
  2678. *
  2679. * The return value is the number of characters written into @buf not including
  2680. * the trailing '\0'. If @size is == 0 the function returns 0.
  2681. */
  2682. int scnprintf(char *buf, size_t size, const char *fmt, ...)
  2683. {
  2684. va_list args;
  2685. int i;
  2686. va_start(args, fmt);
  2687. i = vscnprintf(buf, size, fmt, args);
  2688. va_end(args);
  2689. return i;
  2690. }
  2691. EXPORT_SYMBOL(scnprintf);
  2692. /**
  2693. * vsprintf - Format a string and place it in a buffer
  2694. * @buf: The buffer to place the result into
  2695. * @fmt: The format string to use
  2696. * @args: Arguments for the format string
  2697. *
  2698. * The return value is the number of characters written into @buf not including
  2699. * the trailing '\0'. Use vsnprintf() or vscnprintf() in order to avoid
  2700. * buffer overflows.
  2701. *
  2702. * If you're not already dealing with a va_list consider using sprintf().
  2703. *
  2704. * See the vsnprintf() documentation for format string extensions over C99.
  2705. */
  2706. int vsprintf(char *buf, const char *fmt, va_list args)
  2707. {
  2708. return vsnprintf(buf, INT_MAX, fmt, args);
  2709. }
  2710. EXPORT_SYMBOL(vsprintf);
  2711. /**
  2712. * sprintf - Format a string and place it in a buffer
  2713. * @buf: The buffer to place the result into
  2714. * @fmt: The format string to use
  2715. * @...: Arguments for the format string
  2716. *
  2717. * The return value is the number of characters written into @buf not including
  2718. * the trailing '\0'. Use snprintf() or scnprintf() in order to avoid
  2719. * buffer overflows.
  2720. *
  2721. * See the vsnprintf() documentation for format string extensions over C99.
  2722. */
  2723. int sprintf(char *buf, const char *fmt, ...)
  2724. {
  2725. va_list args;
  2726. int i;
  2727. va_start(args, fmt);
  2728. i = vsnprintf(buf, INT_MAX, fmt, args);
  2729. va_end(args);
  2730. return i;
  2731. }
  2732. EXPORT_SYMBOL(sprintf);
  2733. #ifdef CONFIG_BINARY_PRINTF
  2734. /*
  2735. * bprintf service:
  2736. * vbin_printf() - VA arguments to binary data
  2737. * bstr_printf() - Binary data to text string
  2738. */
  2739. /**
  2740. * vbin_printf - Parse a format string and place args' binary value in a buffer
  2741. * @bin_buf: The buffer to place args' binary value
  2742. * @size: The size of the buffer(by words(32bits), not characters)
  2743. * @fmt_str: The format string to use
  2744. * @args: Arguments for the format string
  2745. *
  2746. * The format follows C99 vsnprintf, except %n is ignored, and its argument
  2747. * is skipped.
  2748. *
  2749. * The return value is the number of words(32bits) which would be generated for
  2750. * the given input.
  2751. *
  2752. * NOTE:
  2753. * If the return value is greater than @size, the resulting bin_buf is NOT
  2754. * valid for bstr_printf().
  2755. */
  2756. int vbin_printf(u32 *bin_buf, size_t size, const char *fmt_str, va_list args)
  2757. {
  2758. struct fmt fmt = {
  2759. .str = fmt_str,
  2760. .state = FORMAT_STATE_NONE,
  2761. };
  2762. struct printf_spec spec = {0};
  2763. char *str, *end;
  2764. int width;
  2765. str = (char *)bin_buf;
  2766. end = (char *)(bin_buf + size);
  2767. #define save_arg(type) \
  2768. ({ \
  2769. unsigned long long value; \
  2770. if (sizeof(type) == 8) { \
  2771. unsigned long long val8; \
  2772. str = PTR_ALIGN(str, sizeof(u32)); \
  2773. val8 = va_arg(args, unsigned long long); \
  2774. if (str + sizeof(type) <= end) { \
  2775. *(u32 *)str = *(u32 *)&val8; \
  2776. *(u32 *)(str + 4) = *((u32 *)&val8 + 1); \
  2777. } \
  2778. value = val8; \
  2779. } else { \
  2780. unsigned int val4; \
  2781. str = PTR_ALIGN(str, sizeof(type)); \
  2782. val4 = va_arg(args, int); \
  2783. if (str + sizeof(type) <= end) \
  2784. *(typeof(type) *)str = (type)(long)val4; \
  2785. value = (unsigned long long)val4; \
  2786. } \
  2787. str += sizeof(type); \
  2788. value; \
  2789. })
  2790. while (*fmt.str) {
  2791. fmt = format_decode(fmt, &spec);
  2792. switch (fmt.state) {
  2793. case FORMAT_STATE_NONE:
  2794. case FORMAT_STATE_PERCENT_CHAR:
  2795. break;
  2796. case FORMAT_STATE_INVALID:
  2797. goto out;
  2798. case FORMAT_STATE_WIDTH:
  2799. case FORMAT_STATE_PRECISION:
  2800. width = (int)save_arg(int);
  2801. /* Pointers may require the width */
  2802. if (*fmt.str == 'p')
  2803. set_field_width(&spec, width);
  2804. break;
  2805. case FORMAT_STATE_CHAR:
  2806. save_arg(char);
  2807. break;
  2808. case FORMAT_STATE_STR: {
  2809. const char *save_str = va_arg(args, char *);
  2810. const char *err_msg;
  2811. size_t len;
  2812. err_msg = check_pointer_msg(save_str);
  2813. if (err_msg)
  2814. save_str = err_msg;
  2815. len = strlen(save_str) + 1;
  2816. if (str + len < end)
  2817. memcpy(str, save_str, len);
  2818. str += len;
  2819. break;
  2820. }
  2821. case FORMAT_STATE_PTR:
  2822. /* Dereferenced pointers must be done now */
  2823. switch (*fmt.str) {
  2824. /* Dereference of functions is still OK */
  2825. case 'S':
  2826. case 's':
  2827. case 'x':
  2828. case 'K':
  2829. case 'e':
  2830. save_arg(void *);
  2831. break;
  2832. default:
  2833. if (!isalnum(*fmt.str)) {
  2834. save_arg(void *);
  2835. break;
  2836. }
  2837. str = pointer(fmt.str, str, end, va_arg(args, void *),
  2838. spec);
  2839. if (str + 1 < end)
  2840. *str++ = '\0';
  2841. else
  2842. end[-1] = '\0'; /* Must be nul terminated */
  2843. }
  2844. /* skip all alphanumeric pointer suffixes */
  2845. while (isalnum(*fmt.str))
  2846. fmt.str++;
  2847. break;
  2848. case FORMAT_STATE_NUM:
  2849. if (fmt.size > sizeof(int)) {
  2850. save_arg(long long);
  2851. } else {
  2852. save_arg(int);
  2853. }
  2854. }
  2855. }
  2856. out:
  2857. return (u32 *)(PTR_ALIGN(str, sizeof(u32))) - bin_buf;
  2858. #undef save_arg
  2859. }
  2860. EXPORT_SYMBOL_GPL(vbin_printf);
  2861. /**
  2862. * bstr_printf - Format a string from binary arguments and place it in a buffer
  2863. * @buf: The buffer to place the result into
  2864. * @size: The size of the buffer, including the trailing null space
  2865. * @fmt_str: The format string to use
  2866. * @bin_buf: Binary arguments for the format string
  2867. *
  2868. * This function like C99 vsnprintf, but the difference is that vsnprintf gets
  2869. * arguments from stack, and bstr_printf gets arguments from @bin_buf which is
  2870. * a binary buffer that generated by vbin_printf.
  2871. *
  2872. * The format follows C99 vsnprintf, but has some extensions:
  2873. * see vsnprintf comment for details.
  2874. *
  2875. * The return value is the number of characters which would
  2876. * be generated for the given input, excluding the trailing
  2877. * '\0', as per ISO C99. If you want to have the exact
  2878. * number of characters written into @buf as return value
  2879. * (not including the trailing '\0'), use vscnprintf(). If the
  2880. * return is greater than or equal to @size, the resulting
  2881. * string is truncated.
  2882. */
  2883. int bstr_printf(char *buf, size_t size, const char *fmt_str, const u32 *bin_buf)
  2884. {
  2885. struct fmt fmt = {
  2886. .str = fmt_str,
  2887. .state = FORMAT_STATE_NONE,
  2888. };
  2889. struct printf_spec spec = {0};
  2890. char *str, *end;
  2891. const char *args = (const char *)bin_buf;
  2892. if (WARN_ON_ONCE(size > INT_MAX))
  2893. return 0;
  2894. str = buf;
  2895. end = buf + size;
  2896. #define get_arg(type) \
  2897. ({ \
  2898. typeof(type) value; \
  2899. if (sizeof(type) == 8) { \
  2900. args = PTR_ALIGN(args, sizeof(u32)); \
  2901. *(u32 *)&value = *(u32 *)args; \
  2902. *((u32 *)&value + 1) = *(u32 *)(args + 4); \
  2903. } else { \
  2904. args = PTR_ALIGN(args, sizeof(type)); \
  2905. value = *(typeof(type) *)args; \
  2906. } \
  2907. args += sizeof(type); \
  2908. value; \
  2909. })
  2910. /* Make sure end is always >= buf */
  2911. if (end < buf) {
  2912. end = ((void *)-1);
  2913. size = end - buf;
  2914. }
  2915. while (*fmt.str) {
  2916. const char *old_fmt = fmt.str;
  2917. unsigned long long num;
  2918. fmt = format_decode(fmt, &spec);
  2919. switch (fmt.state) {
  2920. case FORMAT_STATE_NONE: {
  2921. int read = fmt.str - old_fmt;
  2922. if (str < end) {
  2923. int copy = read;
  2924. if (copy > end - str)
  2925. copy = end - str;
  2926. memcpy(str, old_fmt, copy);
  2927. }
  2928. str += read;
  2929. continue;
  2930. }
  2931. case FORMAT_STATE_WIDTH:
  2932. set_field_width(&spec, get_arg(int));
  2933. continue;
  2934. case FORMAT_STATE_PRECISION:
  2935. set_precision(&spec, get_arg(int));
  2936. continue;
  2937. case FORMAT_STATE_CHAR: {
  2938. char c;
  2939. if (!(spec.flags & LEFT)) {
  2940. while (--spec.field_width > 0) {
  2941. if (str < end)
  2942. *str = ' ';
  2943. ++str;
  2944. }
  2945. }
  2946. c = (unsigned char) get_arg(char);
  2947. if (str < end)
  2948. *str = c;
  2949. ++str;
  2950. while (--spec.field_width > 0) {
  2951. if (str < end)
  2952. *str = ' ';
  2953. ++str;
  2954. }
  2955. continue;
  2956. }
  2957. case FORMAT_STATE_STR: {
  2958. const char *str_arg = args;
  2959. args += strlen(str_arg) + 1;
  2960. str = string(str, end, (char *)str_arg, spec);
  2961. continue;
  2962. }
  2963. case FORMAT_STATE_PTR: {
  2964. bool process = false;
  2965. int copy, len;
  2966. /* Non function dereferences were already done */
  2967. switch (*fmt.str) {
  2968. case 'S':
  2969. case 's':
  2970. case 'x':
  2971. case 'K':
  2972. case 'e':
  2973. process = true;
  2974. break;
  2975. default:
  2976. if (!isalnum(*fmt.str)) {
  2977. process = true;
  2978. break;
  2979. }
  2980. /* Pointer dereference was already processed */
  2981. if (str < end) {
  2982. len = copy = strlen(args);
  2983. if (copy > end - str)
  2984. copy = end - str;
  2985. memcpy(str, args, copy);
  2986. str += len;
  2987. args += len + 1;
  2988. }
  2989. }
  2990. if (process)
  2991. str = pointer(fmt.str, str, end, get_arg(void *), spec);
  2992. while (isalnum(*fmt.str))
  2993. fmt.str++;
  2994. continue;
  2995. }
  2996. case FORMAT_STATE_PERCENT_CHAR:
  2997. if (str < end)
  2998. *str = '%';
  2999. ++str;
  3000. continue;
  3001. case FORMAT_STATE_INVALID:
  3002. goto out;
  3003. case FORMAT_STATE_NUM:
  3004. if (fmt.size > sizeof(int))
  3005. num = get_arg(long long);
  3006. else
  3007. num = convert_num_spec(get_arg(int), fmt.size, spec);
  3008. str = number(str, end, num, spec);
  3009. continue;
  3010. }
  3011. } /* while(*fmt.str) */
  3012. out:
  3013. if (size > 0) {
  3014. if (str < end)
  3015. *str = '\0';
  3016. else
  3017. end[-1] = '\0';
  3018. }
  3019. #undef get_arg
  3020. /* the trailing null byte doesn't count towards the total */
  3021. return str - buf;
  3022. }
  3023. EXPORT_SYMBOL_GPL(bstr_printf);
  3024. #endif /* CONFIG_BINARY_PRINTF */
  3025. /**
  3026. * vsscanf - Unformat a buffer into a list of arguments
  3027. * @buf: input buffer
  3028. * @fmt: format of buffer
  3029. * @args: arguments
  3030. */
  3031. int vsscanf(const char *buf, const char *fmt, va_list args)
  3032. {
  3033. const char *str = buf;
  3034. char *next;
  3035. char digit;
  3036. int num = 0;
  3037. u8 qualifier;
  3038. unsigned int base;
  3039. union {
  3040. long long s;
  3041. unsigned long long u;
  3042. } val;
  3043. s16 field_width;
  3044. bool is_sign;
  3045. while (*fmt) {
  3046. /* skip any white space in format */
  3047. /* white space in format matches any amount of
  3048. * white space, including none, in the input.
  3049. */
  3050. if (isspace(*fmt)) {
  3051. fmt = skip_spaces(++fmt);
  3052. str = skip_spaces(str);
  3053. }
  3054. /* anything that is not a conversion must match exactly */
  3055. if (*fmt != '%' && *fmt) {
  3056. if (*fmt++ != *str++)
  3057. break;
  3058. continue;
  3059. }
  3060. if (!*fmt)
  3061. break;
  3062. ++fmt;
  3063. /* skip this conversion.
  3064. * advance both strings to next white space
  3065. */
  3066. if (*fmt == '*') {
  3067. if (!*str)
  3068. break;
  3069. while (!isspace(*fmt) && *fmt != '%' && *fmt) {
  3070. /* '%*[' not yet supported, invalid format */
  3071. if (*fmt == '[')
  3072. return num;
  3073. fmt++;
  3074. }
  3075. while (!isspace(*str) && *str)
  3076. str++;
  3077. continue;
  3078. }
  3079. /* get field width */
  3080. field_width = -1;
  3081. if (isdigit(*fmt)) {
  3082. field_width = skip_atoi(&fmt);
  3083. if (field_width <= 0)
  3084. break;
  3085. }
  3086. /* get conversion qualifier */
  3087. qualifier = -1;
  3088. if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
  3089. *fmt == 'z') {
  3090. qualifier = *fmt++;
  3091. if (unlikely(qualifier == *fmt)) {
  3092. if (qualifier == 'h') {
  3093. qualifier = 'H';
  3094. fmt++;
  3095. } else if (qualifier == 'l') {
  3096. qualifier = 'L';
  3097. fmt++;
  3098. }
  3099. }
  3100. }
  3101. if (!*fmt)
  3102. break;
  3103. if (*fmt == 'n') {
  3104. /* return number of characters read so far */
  3105. *va_arg(args, int *) = str - buf;
  3106. ++fmt;
  3107. continue;
  3108. }
  3109. if (!*str)
  3110. break;
  3111. base = 10;
  3112. is_sign = false;
  3113. switch (*fmt++) {
  3114. case 'c':
  3115. {
  3116. char *s = (char *)va_arg(args, char*);
  3117. if (field_width == -1)
  3118. field_width = 1;
  3119. do {
  3120. *s++ = *str++;
  3121. } while (--field_width > 0 && *str);
  3122. num++;
  3123. }
  3124. continue;
  3125. case 's':
  3126. {
  3127. char *s = (char *)va_arg(args, char *);
  3128. if (field_width == -1)
  3129. field_width = SHRT_MAX;
  3130. /* first, skip leading white space in buffer */
  3131. str = skip_spaces(str);
  3132. /* now copy until next white space */
  3133. while (*str && !isspace(*str) && field_width--)
  3134. *s++ = *str++;
  3135. *s = '\0';
  3136. num++;
  3137. }
  3138. continue;
  3139. /*
  3140. * Warning: This implementation of the '[' conversion specifier
  3141. * deviates from its glibc counterpart in the following ways:
  3142. * (1) It does NOT support ranges i.e. '-' is NOT a special
  3143. * character
  3144. * (2) It cannot match the closing bracket ']' itself
  3145. * (3) A field width is required
  3146. * (4) '%*[' (discard matching input) is currently not supported
  3147. *
  3148. * Example usage:
  3149. * ret = sscanf("00:0a:95","%2[^:]:%2[^:]:%2[^:]",
  3150. * buf1, buf2, buf3);
  3151. * if (ret < 3)
  3152. * // etc..
  3153. */
  3154. case '[':
  3155. {
  3156. char *s = (char *)va_arg(args, char *);
  3157. DECLARE_BITMAP(set, 256) = {0};
  3158. unsigned int len = 0;
  3159. bool negate = (*fmt == '^');
  3160. /* field width is required */
  3161. if (field_width == -1)
  3162. return num;
  3163. if (negate)
  3164. ++fmt;
  3165. for ( ; *fmt && *fmt != ']'; ++fmt, ++len)
  3166. __set_bit((u8)*fmt, set);
  3167. /* no ']' or no character set found */
  3168. if (!*fmt || !len)
  3169. return num;
  3170. ++fmt;
  3171. if (negate) {
  3172. bitmap_complement(set, set, 256);
  3173. /* exclude null '\0' byte */
  3174. __clear_bit(0, set);
  3175. }
  3176. /* match must be non-empty */
  3177. if (!test_bit((u8)*str, set))
  3178. return num;
  3179. while (test_bit((u8)*str, set) && field_width--)
  3180. *s++ = *str++;
  3181. *s = '\0';
  3182. ++num;
  3183. }
  3184. continue;
  3185. case 'o':
  3186. base = 8;
  3187. break;
  3188. case 'x':
  3189. case 'X':
  3190. base = 16;
  3191. break;
  3192. case 'i':
  3193. base = 0;
  3194. fallthrough;
  3195. case 'd':
  3196. is_sign = true;
  3197. fallthrough;
  3198. case 'u':
  3199. break;
  3200. case '%':
  3201. /* looking for '%' in str */
  3202. if (*str++ != '%')
  3203. return num;
  3204. continue;
  3205. default:
  3206. /* invalid format; stop here */
  3207. return num;
  3208. }
  3209. /* have some sort of integer conversion.
  3210. * first, skip white space in buffer.
  3211. */
  3212. str = skip_spaces(str);
  3213. digit = *str;
  3214. if (is_sign && digit == '-') {
  3215. if (field_width == 1)
  3216. break;
  3217. digit = *(str + 1);
  3218. }
  3219. if (!digit
  3220. || (base == 16 && !isxdigit(digit))
  3221. || (base == 10 && !isdigit(digit))
  3222. || (base == 8 && !isodigit(digit))
  3223. || (base == 0 && !isdigit(digit)))
  3224. break;
  3225. if (is_sign)
  3226. val.s = simple_strntoll(str, &next, base,
  3227. field_width >= 0 ? field_width : INT_MAX);
  3228. else
  3229. val.u = simple_strntoull(str, &next, base,
  3230. field_width >= 0 ? field_width : INT_MAX);
  3231. switch (qualifier) {
  3232. case 'H': /* that's 'hh' in format */
  3233. if (is_sign)
  3234. *va_arg(args, signed char *) = val.s;
  3235. else
  3236. *va_arg(args, unsigned char *) = val.u;
  3237. break;
  3238. case 'h':
  3239. if (is_sign)
  3240. *va_arg(args, short *) = val.s;
  3241. else
  3242. *va_arg(args, unsigned short *) = val.u;
  3243. break;
  3244. case 'l':
  3245. if (is_sign)
  3246. *va_arg(args, long *) = val.s;
  3247. else
  3248. *va_arg(args, unsigned long *) = val.u;
  3249. break;
  3250. case 'L':
  3251. if (is_sign)
  3252. *va_arg(args, long long *) = val.s;
  3253. else
  3254. *va_arg(args, unsigned long long *) = val.u;
  3255. break;
  3256. case 'z':
  3257. *va_arg(args, size_t *) = val.u;
  3258. break;
  3259. default:
  3260. if (is_sign)
  3261. *va_arg(args, int *) = val.s;
  3262. else
  3263. *va_arg(args, unsigned int *) = val.u;
  3264. break;
  3265. }
  3266. num++;
  3267. if (!next)
  3268. break;
  3269. str = next;
  3270. }
  3271. return num;
  3272. }
  3273. EXPORT_SYMBOL(vsscanf);
  3274. /**
  3275. * sscanf - Unformat a buffer into a list of arguments
  3276. * @buf: input buffer
  3277. * @fmt: formatting of buffer
  3278. * @...: resulting arguments
  3279. */
  3280. int sscanf(const char *buf, const char *fmt, ...)
  3281. {
  3282. va_list args;
  3283. int i;
  3284. va_start(args, fmt);
  3285. i = vsscanf(buf, fmt, args);
  3286. va_end(args);
  3287. return i;
  3288. }
  3289. EXPORT_SYMBOL(sscanf);