You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

monitor.c 127KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729
  1. /*
  2. * QEMU monitor
  3. *
  4. * Copyright (c) 2003-2004 Fabrice Bellard
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. #include "qemu/osdep.h"
  25. #include "qemu/units.h"
  26. #include <dirent.h>
  27. #include "cpu.h"
  28. #include "hw/hw.h"
  29. #include "monitor/qdev.h"
  30. #include "hw/usb.h"
  31. #include "hw/pci/pci.h"
  32. #include "sysemu/watchdog.h"
  33. #include "hw/loader.h"
  34. #include "exec/gdbstub.h"
  35. #include "net/net.h"
  36. #include "net/slirp.h"
  37. #include "chardev/char-fe.h"
  38. #include "chardev/char-io.h"
  39. #include "chardev/char-mux.h"
  40. #include "ui/qemu-spice.h"
  41. #include "sysemu/numa.h"
  42. #include "monitor/monitor.h"
  43. #include "qemu/config-file.h"
  44. #include "qemu/ctype.h"
  45. #include "qemu/readline.h"
  46. #include "ui/console.h"
  47. #include "ui/input.h"
  48. #include "sysemu/block-backend.h"
  49. #include "audio/audio.h"
  50. #include "disas/disas.h"
  51. #include "sysemu/balloon.h"
  52. #include "qemu/timer.h"
  53. #include "sysemu/hw_accel.h"
  54. #include "authz/list.h"
  55. #include "qapi/util.h"
  56. #include "sysemu/tcg.h"
  57. #include "sysemu/tpm.h"
  58. #include "qapi/qmp/qdict.h"
  59. #include "qapi/qmp/qerror.h"
  60. #include "qapi/qmp/qnum.h"
  61. #include "qapi/qmp/qstring.h"
  62. #include "qapi/qmp/qjson.h"
  63. #include "qapi/qmp/json-parser.h"
  64. #include "qapi/qmp/qlist.h"
  65. #include "qom/object_interfaces.h"
  66. #include "trace-root.h"
  67. #include "trace/control.h"
  68. #include "monitor/hmp-target.h"
  69. #ifdef CONFIG_TRACE_SIMPLE
  70. #include "trace/simple.h"
  71. #endif
  72. #include "exec/memory.h"
  73. #include "exec/exec-all.h"
  74. #include "qemu/log.h"
  75. #include "qemu/option.h"
  76. #include "hmp.h"
  77. #include "qemu/thread.h"
  78. #include "block/qapi.h"
  79. #include "qapi/qapi-commands.h"
  80. #include "qapi/qapi-emit-events.h"
  81. #include "qapi/error.h"
  82. #include "qapi/qmp-event.h"
  83. #include "qapi/qapi-introspect.h"
  84. #include "sysemu/qtest.h"
  85. #include "sysemu/cpus.h"
  86. #include "sysemu/iothread.h"
  87. #include "qemu/cutils.h"
  88. #include "tcg/tcg.h"
  89. #if defined(TARGET_S390X)
  90. #include "hw/s390x/storage-keys.h"
  91. #include "hw/s390x/storage-attributes.h"
  92. #endif
  93. /*
  94. * Supported types:
  95. *
  96. * 'F' filename
  97. * 'B' block device name
  98. * 's' string (accept optional quote)
  99. * 'S' it just appends the rest of the string (accept optional quote)
  100. * 'O' option string of the form NAME=VALUE,...
  101. * parsed according to QemuOptsList given by its name
  102. * Example: 'device:O' uses qemu_device_opts.
  103. * Restriction: only lists with empty desc are supported
  104. * TODO lift the restriction
  105. * 'i' 32 bit integer
  106. * 'l' target long (32 or 64 bit)
  107. * 'M' Non-negative target long (32 or 64 bit), in user mode the
  108. * value is multiplied by 2^20 (think Mebibyte)
  109. * 'o' octets (aka bytes)
  110. * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
  111. * K, k suffix, which multiplies the value by 2^60 for suffixes E
  112. * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
  113. * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
  114. * 'T' double
  115. * user mode accepts an optional ms, us, ns suffix,
  116. * which divides the value by 1e3, 1e6, 1e9, respectively
  117. * '/' optional gdb-like print format (like "/10x")
  118. *
  119. * '?' optional type (for all types, except '/')
  120. * '.' other form of optional type (for 'i' and 'l')
  121. * 'b' boolean
  122. * user mode accepts "on" or "off"
  123. * '-' optional parameter (eg. '-f')
  124. *
  125. */
  126. typedef struct mon_cmd_t {
  127. const char *name;
  128. const char *args_type;
  129. const char *params;
  130. const char *help;
  131. const char *flags; /* p=preconfig */
  132. void (*cmd)(Monitor *mon, const QDict *qdict);
  133. /* @sub_table is a list of 2nd level of commands. If it does not exist,
  134. * cmd should be used. If it exists, sub_table[?].cmd should be
  135. * used, and cmd of 1st level plays the role of help function.
  136. */
  137. struct mon_cmd_t *sub_table;
  138. void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
  139. } mon_cmd_t;
  140. /* file descriptors passed via SCM_RIGHTS */
  141. typedef struct mon_fd_t mon_fd_t;
  142. struct mon_fd_t {
  143. char *name;
  144. int fd;
  145. QLIST_ENTRY(mon_fd_t) next;
  146. };
  147. /* file descriptor associated with a file descriptor set */
  148. typedef struct MonFdsetFd MonFdsetFd;
  149. struct MonFdsetFd {
  150. int fd;
  151. bool removed;
  152. char *opaque;
  153. QLIST_ENTRY(MonFdsetFd) next;
  154. };
  155. /* file descriptor set containing fds passed via SCM_RIGHTS */
  156. typedef struct MonFdset MonFdset;
  157. struct MonFdset {
  158. int64_t id;
  159. QLIST_HEAD(, MonFdsetFd) fds;
  160. QLIST_HEAD(, MonFdsetFd) dup_fds;
  161. QLIST_ENTRY(MonFdset) next;
  162. };
  163. typedef struct {
  164. JSONMessageParser parser;
  165. /*
  166. * When a client connects, we're in capabilities negotiation mode.
  167. * @commands is &qmp_cap_negotiation_commands then. When command
  168. * qmp_capabilities succeeds, we go into command mode, and
  169. * @command becomes &qmp_commands.
  170. */
  171. QmpCommandList *commands;
  172. bool capab_offered[QMP_CAPABILITY__MAX]; /* capabilities offered */
  173. bool capab[QMP_CAPABILITY__MAX]; /* offered and accepted */
  174. /*
  175. * Protects qmp request/response queue.
  176. * Take monitor_lock first when you need both.
  177. */
  178. QemuMutex qmp_queue_lock;
  179. /* Input queue that holds all the parsed QMP requests */
  180. GQueue *qmp_requests;
  181. } MonitorQMP;
  182. /*
  183. * To prevent flooding clients, events can be throttled. The
  184. * throttling is calculated globally, rather than per-Monitor
  185. * instance.
  186. */
  187. typedef struct MonitorQAPIEventState {
  188. QAPIEvent event; /* Throttling state for this event type and... */
  189. QDict *data; /* ... data, see qapi_event_throttle_equal() */
  190. QEMUTimer *timer; /* Timer for handling delayed events */
  191. QDict *qdict; /* Delayed event (if any) */
  192. } MonitorQAPIEventState;
  193. typedef struct {
  194. int64_t rate; /* Minimum time (in ns) between two events */
  195. } MonitorQAPIEventConf;
  196. struct Monitor {
  197. CharBackend chr;
  198. int reset_seen;
  199. int flags;
  200. int suspend_cnt; /* Needs to be accessed atomically */
  201. bool skip_flush;
  202. bool use_io_thread;
  203. /*
  204. * State used only in the thread "owning" the monitor.
  205. * If @use_io_thread, this is @mon_iothread.
  206. * Else, it's the main thread.
  207. * These members can be safely accessed without locks.
  208. */
  209. ReadLineState *rs;
  210. MonitorQMP qmp;
  211. gchar *mon_cpu_path;
  212. BlockCompletionFunc *password_completion_cb;
  213. void *password_opaque;
  214. mon_cmd_t *cmd_table;
  215. QTAILQ_ENTRY(Monitor) entry;
  216. /*
  217. * The per-monitor lock. We can't access guest memory when holding
  218. * the lock.
  219. */
  220. QemuMutex mon_lock;
  221. /*
  222. * Members that are protected by the per-monitor lock
  223. */
  224. QLIST_HEAD(, mon_fd_t) fds;
  225. QString *outbuf;
  226. guint out_watch;
  227. /* Read under either BQL or mon_lock, written with BQL+mon_lock. */
  228. int mux_out;
  229. };
  230. /* Shared monitor I/O thread */
  231. IOThread *mon_iothread;
  232. /* Bottom half to dispatch the requests received from I/O thread */
  233. QEMUBH *qmp_dispatcher_bh;
  234. struct QMPRequest {
  235. /* Owner of the request */
  236. Monitor *mon;
  237. /*
  238. * Request object to be handled or Error to be reported
  239. * (exactly one of them is non-null)
  240. */
  241. QObject *req;
  242. Error *err;
  243. };
  244. typedef struct QMPRequest QMPRequest;
  245. /* QMP checker flags */
  246. #define QMP_ACCEPT_UNKNOWNS 1
  247. /* Protects mon_list, monitor_qapi_event_state, monitor_destroyed. */
  248. static QemuMutex monitor_lock;
  249. static GHashTable *monitor_qapi_event_state;
  250. static QTAILQ_HEAD(, Monitor) mon_list;
  251. static bool monitor_destroyed;
  252. /* Protects mon_fdsets */
  253. static QemuMutex mon_fdsets_lock;
  254. static QLIST_HEAD(, MonFdset) mon_fdsets;
  255. static int mon_refcount;
  256. static mon_cmd_t mon_cmds[];
  257. static mon_cmd_t info_cmds[];
  258. QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
  259. __thread Monitor *cur_mon;
  260. static void monitor_command_cb(void *opaque, const char *cmdline,
  261. void *readline_opaque);
  262. /**
  263. * Is @mon a QMP monitor?
  264. */
  265. static inline bool monitor_is_qmp(const Monitor *mon)
  266. {
  267. return (mon->flags & MONITOR_USE_CONTROL);
  268. }
  269. /**
  270. * Is @mon is using readline?
  271. * Note: not all HMP monitors use readline, e.g., gdbserver has a
  272. * non-interactive HMP monitor, so readline is not used there.
  273. */
  274. static inline bool monitor_uses_readline(const Monitor *mon)
  275. {
  276. return mon->flags & MONITOR_USE_READLINE;
  277. }
  278. static inline bool monitor_is_hmp_non_interactive(const Monitor *mon)
  279. {
  280. return !monitor_is_qmp(mon) && !monitor_uses_readline(mon);
  281. }
  282. /*
  283. * Return the clock to use for recording an event's time.
  284. * It's QEMU_CLOCK_REALTIME, except for qtests it's
  285. * QEMU_CLOCK_VIRTUAL, to support testing rate limits.
  286. * Beware: result is invalid before configure_accelerator().
  287. */
  288. static inline QEMUClockType monitor_get_event_clock(void)
  289. {
  290. return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME;
  291. }
  292. /**
  293. * Is the current monitor, if any, a QMP monitor?
  294. */
  295. bool monitor_cur_is_qmp(void)
  296. {
  297. return cur_mon && monitor_is_qmp(cur_mon);
  298. }
  299. void monitor_read_command(Monitor *mon, int show_prompt)
  300. {
  301. if (!mon->rs)
  302. return;
  303. readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
  304. if (show_prompt)
  305. readline_show_prompt(mon->rs);
  306. }
  307. int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
  308. void *opaque)
  309. {
  310. if (mon->rs) {
  311. readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
  312. /* prompt is printed on return from the command handler */
  313. return 0;
  314. } else {
  315. monitor_printf(mon, "terminal does not support password prompting\n");
  316. return -ENOTTY;
  317. }
  318. }
  319. static void qmp_request_free(QMPRequest *req)
  320. {
  321. qobject_unref(req->req);
  322. error_free(req->err);
  323. g_free(req);
  324. }
  325. /* Caller must hold mon->qmp.qmp_queue_lock */
  326. static void monitor_qmp_cleanup_req_queue_locked(Monitor *mon)
  327. {
  328. while (!g_queue_is_empty(mon->qmp.qmp_requests)) {
  329. qmp_request_free(g_queue_pop_head(mon->qmp.qmp_requests));
  330. }
  331. }
  332. static void monitor_qmp_cleanup_queues(Monitor *mon)
  333. {
  334. qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
  335. monitor_qmp_cleanup_req_queue_locked(mon);
  336. qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
  337. }
  338. static void monitor_flush_locked(Monitor *mon);
  339. static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
  340. void *opaque)
  341. {
  342. Monitor *mon = opaque;
  343. qemu_mutex_lock(&mon->mon_lock);
  344. mon->out_watch = 0;
  345. monitor_flush_locked(mon);
  346. qemu_mutex_unlock(&mon->mon_lock);
  347. return FALSE;
  348. }
  349. /* Caller must hold mon->mon_lock */
  350. static void monitor_flush_locked(Monitor *mon)
  351. {
  352. int rc;
  353. size_t len;
  354. const char *buf;
  355. if (mon->skip_flush) {
  356. return;
  357. }
  358. buf = qstring_get_str(mon->outbuf);
  359. len = qstring_get_length(mon->outbuf);
  360. if (len && !mon->mux_out) {
  361. rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
  362. if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
  363. /* all flushed or error */
  364. qobject_unref(mon->outbuf);
  365. mon->outbuf = qstring_new();
  366. return;
  367. }
  368. if (rc > 0) {
  369. /* partial write */
  370. QString *tmp = qstring_from_str(buf + rc);
  371. qobject_unref(mon->outbuf);
  372. mon->outbuf = tmp;
  373. }
  374. if (mon->out_watch == 0) {
  375. mon->out_watch =
  376. qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
  377. monitor_unblocked, mon);
  378. }
  379. }
  380. }
  381. void monitor_flush(Monitor *mon)
  382. {
  383. qemu_mutex_lock(&mon->mon_lock);
  384. monitor_flush_locked(mon);
  385. qemu_mutex_unlock(&mon->mon_lock);
  386. }
  387. /* flush at every end of line */
  388. static int monitor_puts(Monitor *mon, const char *str)
  389. {
  390. int i;
  391. char c;
  392. qemu_mutex_lock(&mon->mon_lock);
  393. for (i = 0; str[i]; i++) {
  394. c = str[i];
  395. if (c == '\n') {
  396. qstring_append_chr(mon->outbuf, '\r');
  397. }
  398. qstring_append_chr(mon->outbuf, c);
  399. if (c == '\n') {
  400. monitor_flush_locked(mon);
  401. }
  402. }
  403. qemu_mutex_unlock(&mon->mon_lock);
  404. return i;
  405. }
  406. int monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
  407. {
  408. char *buf;
  409. int n;
  410. if (!mon)
  411. return -1;
  412. if (monitor_is_qmp(mon)) {
  413. return -1;
  414. }
  415. buf = g_strdup_vprintf(fmt, ap);
  416. n = monitor_puts(mon, buf);
  417. g_free(buf);
  418. return n;
  419. }
  420. int monitor_printf(Monitor *mon, const char *fmt, ...)
  421. {
  422. int ret;
  423. va_list ap;
  424. va_start(ap, fmt);
  425. ret = monitor_vprintf(mon, fmt, ap);
  426. va_end(ap);
  427. return ret;
  428. }
  429. static void qmp_send_response(Monitor *mon, const QDict *rsp)
  430. {
  431. const QObject *data = QOBJECT(rsp);
  432. QString *json;
  433. json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
  434. qobject_to_json(data);
  435. assert(json != NULL);
  436. qstring_append_chr(json, '\n');
  437. monitor_puts(mon, qstring_get_str(json));
  438. qobject_unref(json);
  439. }
  440. static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
  441. /* Limit guest-triggerable events to 1 per second */
  442. [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
  443. [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
  444. [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
  445. [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
  446. [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
  447. [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
  448. };
  449. /*
  450. * Broadcast an event to all monitors.
  451. * @qdict is the event object. Its member "event" must match @event.
  452. * Caller must hold monitor_lock.
  453. */
  454. static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
  455. {
  456. Monitor *mon;
  457. trace_monitor_protocol_event_emit(event, qdict);
  458. QTAILQ_FOREACH(mon, &mon_list, entry) {
  459. if (monitor_is_qmp(mon)
  460. && mon->qmp.commands != &qmp_cap_negotiation_commands) {
  461. qmp_send_response(mon, qdict);
  462. }
  463. }
  464. }
  465. static void monitor_qapi_event_handler(void *opaque);
  466. /*
  467. * Queue a new event for emission to Monitor instances,
  468. * applying any rate limiting if required.
  469. */
  470. static void
  471. monitor_qapi_event_queue_no_reenter(QAPIEvent event, QDict *qdict)
  472. {
  473. MonitorQAPIEventConf *evconf;
  474. MonitorQAPIEventState *evstate;
  475. assert(event < QAPI_EVENT__MAX);
  476. evconf = &monitor_qapi_event_conf[event];
  477. trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
  478. qemu_mutex_lock(&monitor_lock);
  479. if (!evconf->rate) {
  480. /* Unthrottled event */
  481. monitor_qapi_event_emit(event, qdict);
  482. } else {
  483. QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
  484. MonitorQAPIEventState key = { .event = event, .data = data };
  485. evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
  486. assert(!evstate || timer_pending(evstate->timer));
  487. if (evstate) {
  488. /*
  489. * Timer is pending for (at least) evconf->rate ns after
  490. * last send. Store event for sending when timer fires,
  491. * replacing a prior stored event if any.
  492. */
  493. qobject_unref(evstate->qdict);
  494. evstate->qdict = qobject_ref(qdict);
  495. } else {
  496. /*
  497. * Last send was (at least) evconf->rate ns ago.
  498. * Send immediately, and arm the timer to call
  499. * monitor_qapi_event_handler() in evconf->rate ns. Any
  500. * events arriving before then will be delayed until then.
  501. */
  502. int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
  503. monitor_qapi_event_emit(event, qdict);
  504. evstate = g_new(MonitorQAPIEventState, 1);
  505. evstate->event = event;
  506. evstate->data = qobject_ref(data);
  507. evstate->qdict = NULL;
  508. evstate->timer = timer_new_ns(monitor_get_event_clock(),
  509. monitor_qapi_event_handler,
  510. evstate);
  511. g_hash_table_add(monitor_qapi_event_state, evstate);
  512. timer_mod_ns(evstate->timer, now + evconf->rate);
  513. }
  514. }
  515. qemu_mutex_unlock(&monitor_lock);
  516. }
  517. void qapi_event_emit(QAPIEvent event, QDict *qdict)
  518. {
  519. /*
  520. * monitor_qapi_event_queue_no_reenter() is not reentrant: it
  521. * would deadlock on monitor_lock. Work around by queueing
  522. * events in thread-local storage.
  523. * TODO: remove this, make it re-enter safe.
  524. */
  525. typedef struct MonitorQapiEvent {
  526. QAPIEvent event;
  527. QDict *qdict;
  528. QSIMPLEQ_ENTRY(MonitorQapiEvent) entry;
  529. } MonitorQapiEvent;
  530. static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue;
  531. static __thread bool reentered;
  532. MonitorQapiEvent *ev;
  533. if (!reentered) {
  534. QSIMPLEQ_INIT(&event_queue);
  535. }
  536. ev = g_new(MonitorQapiEvent, 1);
  537. ev->qdict = qobject_ref(qdict);
  538. ev->event = event;
  539. QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry);
  540. if (reentered) {
  541. return;
  542. }
  543. reentered = true;
  544. while ((ev = QSIMPLEQ_FIRST(&event_queue)) != NULL) {
  545. QSIMPLEQ_REMOVE_HEAD(&event_queue, entry);
  546. monitor_qapi_event_queue_no_reenter(ev->event, ev->qdict);
  547. qobject_unref(ev->qdict);
  548. g_free(ev);
  549. }
  550. reentered = false;
  551. }
  552. /*
  553. * This function runs evconf->rate ns after sending a throttled
  554. * event.
  555. * If another event has since been stored, send it.
  556. */
  557. static void monitor_qapi_event_handler(void *opaque)
  558. {
  559. MonitorQAPIEventState *evstate = opaque;
  560. MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
  561. trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
  562. qemu_mutex_lock(&monitor_lock);
  563. if (evstate->qdict) {
  564. int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
  565. monitor_qapi_event_emit(evstate->event, evstate->qdict);
  566. qobject_unref(evstate->qdict);
  567. evstate->qdict = NULL;
  568. timer_mod_ns(evstate->timer, now + evconf->rate);
  569. } else {
  570. g_hash_table_remove(monitor_qapi_event_state, evstate);
  571. qobject_unref(evstate->data);
  572. timer_free(evstate->timer);
  573. g_free(evstate);
  574. }
  575. qemu_mutex_unlock(&monitor_lock);
  576. }
  577. static unsigned int qapi_event_throttle_hash(const void *key)
  578. {
  579. const MonitorQAPIEventState *evstate = key;
  580. unsigned int hash = evstate->event * 255;
  581. if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
  582. hash += g_str_hash(qdict_get_str(evstate->data, "id"));
  583. }
  584. if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
  585. hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
  586. }
  587. return hash;
  588. }
  589. static gboolean qapi_event_throttle_equal(const void *a, const void *b)
  590. {
  591. const MonitorQAPIEventState *eva = a;
  592. const MonitorQAPIEventState *evb = b;
  593. if (eva->event != evb->event) {
  594. return FALSE;
  595. }
  596. if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
  597. return !strcmp(qdict_get_str(eva->data, "id"),
  598. qdict_get_str(evb->data, "id"));
  599. }
  600. if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
  601. return !strcmp(qdict_get_str(eva->data, "node-name"),
  602. qdict_get_str(evb->data, "node-name"));
  603. }
  604. return TRUE;
  605. }
  606. static void monitor_qapi_event_init(void)
  607. {
  608. monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
  609. qapi_event_throttle_equal);
  610. }
  611. static void handle_hmp_command(Monitor *mon, const char *cmdline);
  612. static void monitor_iothread_init(void);
  613. static void monitor_data_init(Monitor *mon, bool skip_flush,
  614. bool use_io_thread)
  615. {
  616. if (use_io_thread && !mon_iothread) {
  617. monitor_iothread_init();
  618. }
  619. memset(mon, 0, sizeof(Monitor));
  620. qemu_mutex_init(&mon->mon_lock);
  621. qemu_mutex_init(&mon->qmp.qmp_queue_lock);
  622. mon->outbuf = qstring_new();
  623. /* Use *mon_cmds by default. */
  624. mon->cmd_table = mon_cmds;
  625. mon->skip_flush = skip_flush;
  626. mon->use_io_thread = use_io_thread;
  627. mon->qmp.qmp_requests = g_queue_new();
  628. }
  629. static void monitor_data_destroy(Monitor *mon)
  630. {
  631. g_free(mon->mon_cpu_path);
  632. qemu_chr_fe_deinit(&mon->chr, false);
  633. if (monitor_is_qmp(mon)) {
  634. json_message_parser_destroy(&mon->qmp.parser);
  635. }
  636. readline_free(mon->rs);
  637. qobject_unref(mon->outbuf);
  638. qemu_mutex_destroy(&mon->mon_lock);
  639. qemu_mutex_destroy(&mon->qmp.qmp_queue_lock);
  640. monitor_qmp_cleanup_req_queue_locked(mon);
  641. g_queue_free(mon->qmp.qmp_requests);
  642. }
  643. char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
  644. int64_t cpu_index, Error **errp)
  645. {
  646. char *output = NULL;
  647. Monitor *old_mon, hmp;
  648. monitor_data_init(&hmp, true, false);
  649. old_mon = cur_mon;
  650. cur_mon = &hmp;
  651. if (has_cpu_index) {
  652. int ret = monitor_set_cpu(cpu_index);
  653. if (ret < 0) {
  654. cur_mon = old_mon;
  655. error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
  656. "a CPU number");
  657. goto out;
  658. }
  659. }
  660. handle_hmp_command(&hmp, command_line);
  661. cur_mon = old_mon;
  662. qemu_mutex_lock(&hmp.mon_lock);
  663. if (qstring_get_length(hmp.outbuf) > 0) {
  664. output = g_strdup(qstring_get_str(hmp.outbuf));
  665. } else {
  666. output = g_strdup("");
  667. }
  668. qemu_mutex_unlock(&hmp.mon_lock);
  669. out:
  670. monitor_data_destroy(&hmp);
  671. return output;
  672. }
  673. static int compare_cmd(const char *name, const char *list)
  674. {
  675. const char *p, *pstart;
  676. int len;
  677. len = strlen(name);
  678. p = list;
  679. for(;;) {
  680. pstart = p;
  681. p = qemu_strchrnul(p, '|');
  682. if ((p - pstart) == len && !memcmp(pstart, name, len))
  683. return 1;
  684. if (*p == '\0')
  685. break;
  686. p++;
  687. }
  688. return 0;
  689. }
  690. static int get_str(char *buf, int buf_size, const char **pp)
  691. {
  692. const char *p;
  693. char *q;
  694. int c;
  695. q = buf;
  696. p = *pp;
  697. while (qemu_isspace(*p)) {
  698. p++;
  699. }
  700. if (*p == '\0') {
  701. fail:
  702. *q = '\0';
  703. *pp = p;
  704. return -1;
  705. }
  706. if (*p == '\"') {
  707. p++;
  708. while (*p != '\0' && *p != '\"') {
  709. if (*p == '\\') {
  710. p++;
  711. c = *p++;
  712. switch (c) {
  713. case 'n':
  714. c = '\n';
  715. break;
  716. case 'r':
  717. c = '\r';
  718. break;
  719. case '\\':
  720. case '\'':
  721. case '\"':
  722. break;
  723. default:
  724. printf("unsupported escape code: '\\%c'\n", c);
  725. goto fail;
  726. }
  727. if ((q - buf) < buf_size - 1) {
  728. *q++ = c;
  729. }
  730. } else {
  731. if ((q - buf) < buf_size - 1) {
  732. *q++ = *p;
  733. }
  734. p++;
  735. }
  736. }
  737. if (*p != '\"') {
  738. printf("unterminated string\n");
  739. goto fail;
  740. }
  741. p++;
  742. } else {
  743. while (*p != '\0' && !qemu_isspace(*p)) {
  744. if ((q - buf) < buf_size - 1) {
  745. *q++ = *p;
  746. }
  747. p++;
  748. }
  749. }
  750. *q = '\0';
  751. *pp = p;
  752. return 0;
  753. }
  754. #define MAX_ARGS 16
  755. static void free_cmdline_args(char **args, int nb_args)
  756. {
  757. int i;
  758. assert(nb_args <= MAX_ARGS);
  759. for (i = 0; i < nb_args; i++) {
  760. g_free(args[i]);
  761. }
  762. }
  763. /*
  764. * Parse the command line to get valid args.
  765. * @cmdline: command line to be parsed.
  766. * @pnb_args: location to store the number of args, must NOT be NULL.
  767. * @args: location to store the args, which should be freed by caller, must
  768. * NOT be NULL.
  769. *
  770. * Returns 0 on success, negative on failure.
  771. *
  772. * NOTE: this parser is an approximate form of the real command parser. Number
  773. * of args have a limit of MAX_ARGS. If cmdline contains more, it will
  774. * return with failure.
  775. */
  776. static int parse_cmdline(const char *cmdline,
  777. int *pnb_args, char **args)
  778. {
  779. const char *p;
  780. int nb_args, ret;
  781. char buf[1024];
  782. p = cmdline;
  783. nb_args = 0;
  784. for (;;) {
  785. while (qemu_isspace(*p)) {
  786. p++;
  787. }
  788. if (*p == '\0') {
  789. break;
  790. }
  791. if (nb_args >= MAX_ARGS) {
  792. goto fail;
  793. }
  794. ret = get_str(buf, sizeof(buf), &p);
  795. if (ret < 0) {
  796. goto fail;
  797. }
  798. args[nb_args] = g_strdup(buf);
  799. nb_args++;
  800. }
  801. *pnb_args = nb_args;
  802. return 0;
  803. fail:
  804. free_cmdline_args(args, nb_args);
  805. return -1;
  806. }
  807. /*
  808. * Can command @cmd be executed in preconfig state?
  809. */
  810. static bool cmd_can_preconfig(const mon_cmd_t *cmd)
  811. {
  812. if (!cmd->flags) {
  813. return false;
  814. }
  815. return strchr(cmd->flags, 'p');
  816. }
  817. static void help_cmd_dump_one(Monitor *mon,
  818. const mon_cmd_t *cmd,
  819. char **prefix_args,
  820. int prefix_args_nb)
  821. {
  822. int i;
  823. if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
  824. return;
  825. }
  826. for (i = 0; i < prefix_args_nb; i++) {
  827. monitor_printf(mon, "%s ", prefix_args[i]);
  828. }
  829. monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
  830. }
  831. /* @args[@arg_index] is the valid command need to find in @cmds */
  832. static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
  833. char **args, int nb_args, int arg_index)
  834. {
  835. const mon_cmd_t *cmd;
  836. size_t i;
  837. /* No valid arg need to compare with, dump all in *cmds */
  838. if (arg_index >= nb_args) {
  839. for (cmd = cmds; cmd->name != NULL; cmd++) {
  840. help_cmd_dump_one(mon, cmd, args, arg_index);
  841. }
  842. return;
  843. }
  844. /* Find one entry to dump */
  845. for (cmd = cmds; cmd->name != NULL; cmd++) {
  846. if (compare_cmd(args[arg_index], cmd->name) &&
  847. ((!runstate_check(RUN_STATE_PRECONFIG) ||
  848. cmd_can_preconfig(cmd)))) {
  849. if (cmd->sub_table) {
  850. /* continue with next arg */
  851. help_cmd_dump(mon, cmd->sub_table,
  852. args, nb_args, arg_index + 1);
  853. } else {
  854. help_cmd_dump_one(mon, cmd, args, arg_index);
  855. }
  856. return;
  857. }
  858. }
  859. /* Command not found */
  860. monitor_printf(mon, "unknown command: '");
  861. for (i = 0; i <= arg_index; i++) {
  862. monitor_printf(mon, "%s%s", args[i], i == arg_index ? "'\n" : " ");
  863. }
  864. }
  865. static void help_cmd(Monitor *mon, const char *name)
  866. {
  867. char *args[MAX_ARGS];
  868. int nb_args = 0;
  869. /* 1. parse user input */
  870. if (name) {
  871. /* special case for log, directly dump and return */
  872. if (!strcmp(name, "log")) {
  873. const QEMULogItem *item;
  874. monitor_printf(mon, "Log items (comma separated):\n");
  875. monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
  876. for (item = qemu_log_items; item->mask != 0; item++) {
  877. monitor_printf(mon, "%-10s %s\n", item->name, item->help);
  878. }
  879. return;
  880. }
  881. if (parse_cmdline(name, &nb_args, args) < 0) {
  882. return;
  883. }
  884. }
  885. /* 2. dump the contents according to parsed args */
  886. help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
  887. free_cmdline_args(args, nb_args);
  888. }
  889. static void do_help_cmd(Monitor *mon, const QDict *qdict)
  890. {
  891. help_cmd(mon, qdict_get_try_str(qdict, "name"));
  892. }
  893. static void hmp_trace_event(Monitor *mon, const QDict *qdict)
  894. {
  895. const char *tp_name = qdict_get_str(qdict, "name");
  896. bool new_state = qdict_get_bool(qdict, "option");
  897. bool has_vcpu = qdict_haskey(qdict, "vcpu");
  898. int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
  899. Error *local_err = NULL;
  900. if (vcpu < 0) {
  901. monitor_printf(mon, "argument vcpu must be positive");
  902. return;
  903. }
  904. qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
  905. if (local_err) {
  906. error_report_err(local_err);
  907. }
  908. }
  909. #ifdef CONFIG_TRACE_SIMPLE
  910. static void hmp_trace_file(Monitor *mon, const QDict *qdict)
  911. {
  912. const char *op = qdict_get_try_str(qdict, "op");
  913. const char *arg = qdict_get_try_str(qdict, "arg");
  914. if (!op) {
  915. st_print_trace_file_status();
  916. } else if (!strcmp(op, "on")) {
  917. st_set_trace_file_enabled(true);
  918. } else if (!strcmp(op, "off")) {
  919. st_set_trace_file_enabled(false);
  920. } else if (!strcmp(op, "flush")) {
  921. st_flush_trace_buffer();
  922. } else if (!strcmp(op, "set")) {
  923. if (arg) {
  924. st_set_trace_file(arg);
  925. }
  926. } else {
  927. monitor_printf(mon, "unexpected argument \"%s\"\n", op);
  928. help_cmd(mon, "trace-file");
  929. }
  930. }
  931. #endif
  932. static void hmp_info_help(Monitor *mon, const QDict *qdict)
  933. {
  934. help_cmd(mon, "info");
  935. }
  936. static void query_commands_cb(QmpCommand *cmd, void *opaque)
  937. {
  938. CommandInfoList *info, **list = opaque;
  939. if (!cmd->enabled) {
  940. return;
  941. }
  942. info = g_malloc0(sizeof(*info));
  943. info->value = g_malloc0(sizeof(*info->value));
  944. info->value->name = g_strdup(cmd->name);
  945. info->next = *list;
  946. *list = info;
  947. }
  948. CommandInfoList *qmp_query_commands(Error **errp)
  949. {
  950. CommandInfoList *list = NULL;
  951. qmp_for_each_command(cur_mon->qmp.commands, query_commands_cb, &list);
  952. return list;
  953. }
  954. EventInfoList *qmp_query_events(Error **errp)
  955. {
  956. /*
  957. * TODO This deprecated command is the only user of
  958. * QAPIEvent_str() and QAPIEvent_lookup[]. When the command goes,
  959. * they should go, too.
  960. */
  961. EventInfoList *info, *ev_list = NULL;
  962. QAPIEvent e;
  963. for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
  964. const char *event_name = QAPIEvent_str(e);
  965. assert(event_name != NULL);
  966. info = g_malloc0(sizeof(*info));
  967. info->value = g_malloc0(sizeof(*info->value));
  968. info->value->name = g_strdup(event_name);
  969. info->next = ev_list;
  970. ev_list = info;
  971. }
  972. return ev_list;
  973. }
  974. /*
  975. * Minor hack: generated marshalling suppressed for this command
  976. * ('gen': false in the schema) so we can parse the JSON string
  977. * directly into QObject instead of first parsing it with
  978. * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
  979. * to QObject with generated output marshallers, every time. Instead,
  980. * we do it in test-qobject-input-visitor.c, just to make sure
  981. * qapi-gen.py's output actually conforms to the schema.
  982. */
  983. static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
  984. Error **errp)
  985. {
  986. *ret_data = qobject_from_qlit(&qmp_schema_qlit);
  987. }
  988. static void monitor_init_qmp_commands(void)
  989. {
  990. /*
  991. * Two command lists:
  992. * - qmp_commands contains all QMP commands
  993. * - qmp_cap_negotiation_commands contains just
  994. * "qmp_capabilities", to enforce capability negotiation
  995. */
  996. qmp_init_marshal(&qmp_commands);
  997. qmp_register_command(&qmp_commands, "query-qmp-schema",
  998. qmp_query_qmp_schema, QCO_ALLOW_PRECONFIG);
  999. qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
  1000. QCO_NO_OPTIONS);
  1001. qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
  1002. QCO_NO_OPTIONS);
  1003. QTAILQ_INIT(&qmp_cap_negotiation_commands);
  1004. qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
  1005. qmp_marshal_qmp_capabilities, QCO_ALLOW_PRECONFIG);
  1006. }
  1007. static bool qmp_oob_enabled(Monitor *mon)
  1008. {
  1009. return mon->qmp.capab[QMP_CAPABILITY_OOB];
  1010. }
  1011. static void monitor_qmp_caps_reset(Monitor *mon)
  1012. {
  1013. memset(mon->qmp.capab_offered, 0, sizeof(mon->qmp.capab_offered));
  1014. memset(mon->qmp.capab, 0, sizeof(mon->qmp.capab));
  1015. mon->qmp.capab_offered[QMP_CAPABILITY_OOB] = mon->use_io_thread;
  1016. }
  1017. /*
  1018. * Accept QMP capabilities in @list for @mon.
  1019. * On success, set mon->qmp.capab[], and return true.
  1020. * On error, set @errp, and return false.
  1021. */
  1022. static bool qmp_caps_accept(Monitor *mon, QMPCapabilityList *list,
  1023. Error **errp)
  1024. {
  1025. GString *unavailable = NULL;
  1026. bool capab[QMP_CAPABILITY__MAX];
  1027. memset(capab, 0, sizeof(capab));
  1028. for (; list; list = list->next) {
  1029. if (!mon->qmp.capab_offered[list->value]) {
  1030. if (!unavailable) {
  1031. unavailable = g_string_new(QMPCapability_str(list->value));
  1032. } else {
  1033. g_string_append_printf(unavailable, ", %s",
  1034. QMPCapability_str(list->value));
  1035. }
  1036. }
  1037. capab[list->value] = true;
  1038. }
  1039. if (unavailable) {
  1040. error_setg(errp, "Capability %s not available", unavailable->str);
  1041. g_string_free(unavailable, true);
  1042. return false;
  1043. }
  1044. memcpy(mon->qmp.capab, capab, sizeof(capab));
  1045. return true;
  1046. }
  1047. void qmp_qmp_capabilities(bool has_enable, QMPCapabilityList *enable,
  1048. Error **errp)
  1049. {
  1050. if (cur_mon->qmp.commands == &qmp_commands) {
  1051. error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
  1052. "Capabilities negotiation is already complete, command "
  1053. "ignored");
  1054. return;
  1055. }
  1056. if (!qmp_caps_accept(cur_mon, enable, errp)) {
  1057. return;
  1058. }
  1059. cur_mon->qmp.commands = &qmp_commands;
  1060. }
  1061. /* Set the current CPU defined by the user. Callers must hold BQL. */
  1062. int monitor_set_cpu(int cpu_index)
  1063. {
  1064. CPUState *cpu;
  1065. cpu = qemu_get_cpu(cpu_index);
  1066. if (cpu == NULL) {
  1067. return -1;
  1068. }
  1069. g_free(cur_mon->mon_cpu_path);
  1070. cur_mon->mon_cpu_path = object_get_canonical_path(OBJECT(cpu));
  1071. return 0;
  1072. }
  1073. /* Callers must hold BQL. */
  1074. static CPUState *mon_get_cpu_sync(bool synchronize)
  1075. {
  1076. CPUState *cpu;
  1077. if (cur_mon->mon_cpu_path) {
  1078. cpu = (CPUState *) object_resolve_path_type(cur_mon->mon_cpu_path,
  1079. TYPE_CPU, NULL);
  1080. if (!cpu) {
  1081. g_free(cur_mon->mon_cpu_path);
  1082. cur_mon->mon_cpu_path = NULL;
  1083. }
  1084. }
  1085. if (!cur_mon->mon_cpu_path) {
  1086. if (!first_cpu) {
  1087. return NULL;
  1088. }
  1089. monitor_set_cpu(first_cpu->cpu_index);
  1090. cpu = first_cpu;
  1091. }
  1092. if (synchronize) {
  1093. cpu_synchronize_state(cpu);
  1094. }
  1095. return cpu;
  1096. }
  1097. CPUState *mon_get_cpu(void)
  1098. {
  1099. return mon_get_cpu_sync(true);
  1100. }
  1101. CPUArchState *mon_get_cpu_env(void)
  1102. {
  1103. CPUState *cs = mon_get_cpu();
  1104. return cs ? cs->env_ptr : NULL;
  1105. }
  1106. int monitor_get_cpu_index(void)
  1107. {
  1108. CPUState *cs = mon_get_cpu_sync(false);
  1109. return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
  1110. }
  1111. static void hmp_info_registers(Monitor *mon, const QDict *qdict)
  1112. {
  1113. bool all_cpus = qdict_get_try_bool(qdict, "cpustate_all", false);
  1114. CPUState *cs;
  1115. if (all_cpus) {
  1116. CPU_FOREACH(cs) {
  1117. monitor_printf(mon, "\nCPU#%d\n", cs->cpu_index);
  1118. cpu_dump_state(cs, NULL, CPU_DUMP_FPU);
  1119. }
  1120. } else {
  1121. cs = mon_get_cpu();
  1122. if (!cs) {
  1123. monitor_printf(mon, "No CPU available\n");
  1124. return;
  1125. }
  1126. cpu_dump_state(cs, NULL, CPU_DUMP_FPU);
  1127. }
  1128. }
  1129. #ifdef CONFIG_TCG
  1130. static void hmp_info_jit(Monitor *mon, const QDict *qdict)
  1131. {
  1132. if (!tcg_enabled()) {
  1133. error_report("JIT information is only available with accel=tcg");
  1134. return;
  1135. }
  1136. dump_exec_info();
  1137. dump_drift_info();
  1138. }
  1139. static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
  1140. {
  1141. dump_opcount_info();
  1142. }
  1143. #endif
  1144. static void hmp_info_sync_profile(Monitor *mon, const QDict *qdict)
  1145. {
  1146. int64_t max = qdict_get_try_int(qdict, "max", 10);
  1147. bool mean = qdict_get_try_bool(qdict, "mean", false);
  1148. bool coalesce = !qdict_get_try_bool(qdict, "no_coalesce", false);
  1149. enum QSPSortBy sort_by;
  1150. sort_by = mean ? QSP_SORT_BY_AVG_WAIT_TIME : QSP_SORT_BY_TOTAL_WAIT_TIME;
  1151. qsp_report(max, sort_by, coalesce);
  1152. }
  1153. static void hmp_info_history(Monitor *mon, const QDict *qdict)
  1154. {
  1155. int i;
  1156. const char *str;
  1157. if (!mon->rs)
  1158. return;
  1159. i = 0;
  1160. for(;;) {
  1161. str = readline_get_history(mon->rs, i);
  1162. if (!str)
  1163. break;
  1164. monitor_printf(mon, "%d: '%s'\n", i, str);
  1165. i++;
  1166. }
  1167. }
  1168. static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
  1169. {
  1170. CPUState *cs = mon_get_cpu();
  1171. if (!cs) {
  1172. monitor_printf(mon, "No CPU available\n");
  1173. return;
  1174. }
  1175. cpu_dump_statistics(cs, 0);
  1176. }
  1177. static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
  1178. {
  1179. const char *name = qdict_get_try_str(qdict, "name");
  1180. bool has_vcpu = qdict_haskey(qdict, "vcpu");
  1181. int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
  1182. TraceEventInfoList *events;
  1183. TraceEventInfoList *elem;
  1184. Error *local_err = NULL;
  1185. if (name == NULL) {
  1186. name = "*";
  1187. }
  1188. if (vcpu < 0) {
  1189. monitor_printf(mon, "argument vcpu must be positive");
  1190. return;
  1191. }
  1192. events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
  1193. if (local_err) {
  1194. error_report_err(local_err);
  1195. return;
  1196. }
  1197. for (elem = events; elem != NULL; elem = elem->next) {
  1198. monitor_printf(mon, "%s : state %u\n",
  1199. elem->value->name,
  1200. elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
  1201. }
  1202. qapi_free_TraceEventInfoList(events);
  1203. }
  1204. void qmp_client_migrate_info(const char *protocol, const char *hostname,
  1205. bool has_port, int64_t port,
  1206. bool has_tls_port, int64_t tls_port,
  1207. bool has_cert_subject, const char *cert_subject,
  1208. Error **errp)
  1209. {
  1210. if (strcmp(protocol, "spice") == 0) {
  1211. if (!qemu_using_spice(errp)) {
  1212. return;
  1213. }
  1214. if (!has_port && !has_tls_port) {
  1215. error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
  1216. return;
  1217. }
  1218. if (qemu_spice_migrate_info(hostname,
  1219. has_port ? port : -1,
  1220. has_tls_port ? tls_port : -1,
  1221. cert_subject)) {
  1222. error_setg(errp, QERR_UNDEFINED_ERROR);
  1223. return;
  1224. }
  1225. return;
  1226. }
  1227. error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
  1228. }
  1229. static void hmp_logfile(Monitor *mon, const QDict *qdict)
  1230. {
  1231. Error *err = NULL;
  1232. qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
  1233. if (err) {
  1234. error_report_err(err);
  1235. }
  1236. }
  1237. static void hmp_log(Monitor *mon, const QDict *qdict)
  1238. {
  1239. int mask;
  1240. const char *items = qdict_get_str(qdict, "items");
  1241. if (!strcmp(items, "none")) {
  1242. mask = 0;
  1243. } else {
  1244. mask = qemu_str_to_log_mask(items);
  1245. if (!mask) {
  1246. help_cmd(mon, "log");
  1247. return;
  1248. }
  1249. }
  1250. qemu_set_log(mask);
  1251. }
  1252. static void hmp_singlestep(Monitor *mon, const QDict *qdict)
  1253. {
  1254. const char *option = qdict_get_try_str(qdict, "option");
  1255. if (!option || !strcmp(option, "on")) {
  1256. singlestep = 1;
  1257. } else if (!strcmp(option, "off")) {
  1258. singlestep = 0;
  1259. } else {
  1260. monitor_printf(mon, "unexpected option %s\n", option);
  1261. }
  1262. }
  1263. static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
  1264. {
  1265. const char *device = qdict_get_try_str(qdict, "device");
  1266. if (!device)
  1267. device = "tcp::" DEFAULT_GDBSTUB_PORT;
  1268. if (gdbserver_start(device) < 0) {
  1269. monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
  1270. device);
  1271. } else if (strcmp(device, "none") == 0) {
  1272. monitor_printf(mon, "Disabled gdbserver\n");
  1273. } else {
  1274. monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
  1275. device);
  1276. }
  1277. }
  1278. static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
  1279. {
  1280. const char *action = qdict_get_str(qdict, "action");
  1281. if (select_watchdog_action(action) == -1) {
  1282. monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
  1283. }
  1284. }
  1285. static void monitor_printc(Monitor *mon, int c)
  1286. {
  1287. monitor_printf(mon, "'");
  1288. switch(c) {
  1289. case '\'':
  1290. monitor_printf(mon, "\\'");
  1291. break;
  1292. case '\\':
  1293. monitor_printf(mon, "\\\\");
  1294. break;
  1295. case '\n':
  1296. monitor_printf(mon, "\\n");
  1297. break;
  1298. case '\r':
  1299. monitor_printf(mon, "\\r");
  1300. break;
  1301. default:
  1302. if (c >= 32 && c <= 126) {
  1303. monitor_printf(mon, "%c", c);
  1304. } else {
  1305. monitor_printf(mon, "\\x%02x", c);
  1306. }
  1307. break;
  1308. }
  1309. monitor_printf(mon, "'");
  1310. }
  1311. static void memory_dump(Monitor *mon, int count, int format, int wsize,
  1312. hwaddr addr, int is_physical)
  1313. {
  1314. int l, line_size, i, max_digits, len;
  1315. uint8_t buf[16];
  1316. uint64_t v;
  1317. CPUState *cs = mon_get_cpu();
  1318. if (!cs && (format == 'i' || !is_physical)) {
  1319. monitor_printf(mon, "Can not dump without CPU\n");
  1320. return;
  1321. }
  1322. if (format == 'i') {
  1323. monitor_disas(mon, cs, addr, count, is_physical);
  1324. return;
  1325. }
  1326. len = wsize * count;
  1327. if (wsize == 1)
  1328. line_size = 8;
  1329. else
  1330. line_size = 16;
  1331. max_digits = 0;
  1332. switch(format) {
  1333. case 'o':
  1334. max_digits = DIV_ROUND_UP(wsize * 8, 3);
  1335. break;
  1336. default:
  1337. case 'x':
  1338. max_digits = (wsize * 8) / 4;
  1339. break;
  1340. case 'u':
  1341. case 'd':
  1342. max_digits = DIV_ROUND_UP(wsize * 8 * 10, 33);
  1343. break;
  1344. case 'c':
  1345. wsize = 1;
  1346. break;
  1347. }
  1348. while (len > 0) {
  1349. if (is_physical)
  1350. monitor_printf(mon, TARGET_FMT_plx ":", addr);
  1351. else
  1352. monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
  1353. l = len;
  1354. if (l > line_size)
  1355. l = line_size;
  1356. if (is_physical) {
  1357. AddressSpace *as = cs ? cs->as : &address_space_memory;
  1358. MemTxResult r = address_space_read(as, addr,
  1359. MEMTXATTRS_UNSPECIFIED, buf, l);
  1360. if (r != MEMTX_OK) {
  1361. monitor_printf(mon, " Cannot access memory\n");
  1362. break;
  1363. }
  1364. } else {
  1365. if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
  1366. monitor_printf(mon, " Cannot access memory\n");
  1367. break;
  1368. }
  1369. }
  1370. i = 0;
  1371. while (i < l) {
  1372. switch(wsize) {
  1373. default:
  1374. case 1:
  1375. v = ldub_p(buf + i);
  1376. break;
  1377. case 2:
  1378. v = lduw_p(buf + i);
  1379. break;
  1380. case 4:
  1381. v = (uint32_t)ldl_p(buf + i);
  1382. break;
  1383. case 8:
  1384. v = ldq_p(buf + i);
  1385. break;
  1386. }
  1387. monitor_printf(mon, " ");
  1388. switch(format) {
  1389. case 'o':
  1390. monitor_printf(mon, "%#*" PRIo64, max_digits, v);
  1391. break;
  1392. case 'x':
  1393. monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
  1394. break;
  1395. case 'u':
  1396. monitor_printf(mon, "%*" PRIu64, max_digits, v);
  1397. break;
  1398. case 'd':
  1399. monitor_printf(mon, "%*" PRId64, max_digits, v);
  1400. break;
  1401. case 'c':
  1402. monitor_printc(mon, v);
  1403. break;
  1404. }
  1405. i += wsize;
  1406. }
  1407. monitor_printf(mon, "\n");
  1408. addr += l;
  1409. len -= l;
  1410. }
  1411. }
  1412. static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
  1413. {
  1414. int count = qdict_get_int(qdict, "count");
  1415. int format = qdict_get_int(qdict, "format");
  1416. int size = qdict_get_int(qdict, "size");
  1417. target_long addr = qdict_get_int(qdict, "addr");
  1418. memory_dump(mon, count, format, size, addr, 0);
  1419. }
  1420. static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
  1421. {
  1422. int count = qdict_get_int(qdict, "count");
  1423. int format = qdict_get_int(qdict, "format");
  1424. int size = qdict_get_int(qdict, "size");
  1425. hwaddr addr = qdict_get_int(qdict, "addr");
  1426. memory_dump(mon, count, format, size, addr, 1);
  1427. }
  1428. static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
  1429. {
  1430. MemoryRegionSection mrs = memory_region_find(get_system_memory(),
  1431. addr, 1);
  1432. if (!mrs.mr) {
  1433. error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
  1434. return NULL;
  1435. }
  1436. if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
  1437. error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
  1438. memory_region_unref(mrs.mr);
  1439. return NULL;
  1440. }
  1441. *p_mr = mrs.mr;
  1442. return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
  1443. }
  1444. static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
  1445. {
  1446. hwaddr addr = qdict_get_int(qdict, "addr");
  1447. Error *local_err = NULL;
  1448. MemoryRegion *mr = NULL;
  1449. void *ptr;
  1450. ptr = gpa2hva(&mr, addr, &local_err);
  1451. if (local_err) {
  1452. error_report_err(local_err);
  1453. return;
  1454. }
  1455. monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
  1456. " (%s) is %p\n",
  1457. addr, mr->name, ptr);
  1458. memory_region_unref(mr);
  1459. }
  1460. static void hmp_gva2gpa(Monitor *mon, const QDict *qdict)
  1461. {
  1462. target_ulong addr = qdict_get_int(qdict, "addr");
  1463. MemTxAttrs attrs;
  1464. CPUState *cs = mon_get_cpu();
  1465. hwaddr gpa;
  1466. if (!cs) {
  1467. monitor_printf(mon, "No cpu\n");
  1468. return;
  1469. }
  1470. gpa = cpu_get_phys_page_attrs_debug(cs, addr & TARGET_PAGE_MASK, &attrs);
  1471. if (gpa == -1) {
  1472. monitor_printf(mon, "Unmapped\n");
  1473. } else {
  1474. monitor_printf(mon, "gpa: %#" HWADDR_PRIx "\n",
  1475. gpa + (addr & ~TARGET_PAGE_MASK));
  1476. }
  1477. }
  1478. #ifdef CONFIG_LINUX
  1479. static uint64_t vtop(void *ptr, Error **errp)
  1480. {
  1481. uint64_t pinfo;
  1482. uint64_t ret = -1;
  1483. uintptr_t addr = (uintptr_t) ptr;
  1484. uintptr_t pagesize = getpagesize();
  1485. off_t offset = addr / pagesize * sizeof(pinfo);
  1486. int fd;
  1487. fd = open("/proc/self/pagemap", O_RDONLY);
  1488. if (fd == -1) {
  1489. error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
  1490. return -1;
  1491. }
  1492. /* Force copy-on-write if necessary. */
  1493. atomic_add((uint8_t *)ptr, 0);
  1494. if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
  1495. error_setg_errno(errp, errno, "Cannot read pagemap");
  1496. goto out;
  1497. }
  1498. if ((pinfo & (1ull << 63)) == 0) {
  1499. error_setg(errp, "Page not present");
  1500. goto out;
  1501. }
  1502. ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
  1503. out:
  1504. close(fd);
  1505. return ret;
  1506. }
  1507. static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
  1508. {
  1509. hwaddr addr = qdict_get_int(qdict, "addr");
  1510. Error *local_err = NULL;
  1511. MemoryRegion *mr = NULL;
  1512. void *ptr;
  1513. uint64_t physaddr;
  1514. ptr = gpa2hva(&mr, addr, &local_err);
  1515. if (local_err) {
  1516. error_report_err(local_err);
  1517. return;
  1518. }
  1519. physaddr = vtop(ptr, &local_err);
  1520. if (local_err) {
  1521. error_report_err(local_err);
  1522. } else {
  1523. monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
  1524. " (%s) is 0x%" PRIx64 "\n",
  1525. addr, mr->name, (uint64_t) physaddr);
  1526. }
  1527. memory_region_unref(mr);
  1528. }
  1529. #endif
  1530. static void do_print(Monitor *mon, const QDict *qdict)
  1531. {
  1532. int format = qdict_get_int(qdict, "format");
  1533. hwaddr val = qdict_get_int(qdict, "val");
  1534. switch(format) {
  1535. case 'o':
  1536. monitor_printf(mon, "%#" HWADDR_PRIo, val);
  1537. break;
  1538. case 'x':
  1539. monitor_printf(mon, "%#" HWADDR_PRIx, val);
  1540. break;
  1541. case 'u':
  1542. monitor_printf(mon, "%" HWADDR_PRIu, val);
  1543. break;
  1544. default:
  1545. case 'd':
  1546. monitor_printf(mon, "%" HWADDR_PRId, val);
  1547. break;
  1548. case 'c':
  1549. monitor_printc(mon, val);
  1550. break;
  1551. }
  1552. monitor_printf(mon, "\n");
  1553. }
  1554. static void hmp_sum(Monitor *mon, const QDict *qdict)
  1555. {
  1556. uint32_t addr;
  1557. uint16_t sum;
  1558. uint32_t start = qdict_get_int(qdict, "start");
  1559. uint32_t size = qdict_get_int(qdict, "size");
  1560. sum = 0;
  1561. for(addr = start; addr < (start + size); addr++) {
  1562. uint8_t val = address_space_ldub(&address_space_memory, addr,
  1563. MEMTXATTRS_UNSPECIFIED, NULL);
  1564. /* BSD sum algorithm ('sum' Unix command) */
  1565. sum = (sum >> 1) | (sum << 15);
  1566. sum += val;
  1567. }
  1568. monitor_printf(mon, "%05d\n", sum);
  1569. }
  1570. static int mouse_button_state;
  1571. static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
  1572. {
  1573. int dx, dy, dz, button;
  1574. const char *dx_str = qdict_get_str(qdict, "dx_str");
  1575. const char *dy_str = qdict_get_str(qdict, "dy_str");
  1576. const char *dz_str = qdict_get_try_str(qdict, "dz_str");
  1577. dx = strtol(dx_str, NULL, 0);
  1578. dy = strtol(dy_str, NULL, 0);
  1579. qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
  1580. qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
  1581. if (dz_str) {
  1582. dz = strtol(dz_str, NULL, 0);
  1583. if (dz != 0) {
  1584. button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
  1585. qemu_input_queue_btn(NULL, button, true);
  1586. qemu_input_event_sync();
  1587. qemu_input_queue_btn(NULL, button, false);
  1588. }
  1589. }
  1590. qemu_input_event_sync();
  1591. }
  1592. static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
  1593. {
  1594. static uint32_t bmap[INPUT_BUTTON__MAX] = {
  1595. [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
  1596. [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
  1597. [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
  1598. };
  1599. int button_state = qdict_get_int(qdict, "button_state");
  1600. if (mouse_button_state == button_state) {
  1601. return;
  1602. }
  1603. qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
  1604. qemu_input_event_sync();
  1605. mouse_button_state = button_state;
  1606. }
  1607. static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
  1608. {
  1609. int size = qdict_get_int(qdict, "size");
  1610. int addr = qdict_get_int(qdict, "addr");
  1611. int has_index = qdict_haskey(qdict, "index");
  1612. uint32_t val;
  1613. int suffix;
  1614. if (has_index) {
  1615. int index = qdict_get_int(qdict, "index");
  1616. cpu_outb(addr & IOPORTS_MASK, index & 0xff);
  1617. addr++;
  1618. }
  1619. addr &= 0xffff;
  1620. switch(size) {
  1621. default:
  1622. case 1:
  1623. val = cpu_inb(addr);
  1624. suffix = 'b';
  1625. break;
  1626. case 2:
  1627. val = cpu_inw(addr);
  1628. suffix = 'w';
  1629. break;
  1630. case 4:
  1631. val = cpu_inl(addr);
  1632. suffix = 'l';
  1633. break;
  1634. }
  1635. monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
  1636. suffix, addr, size * 2, val);
  1637. }
  1638. static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
  1639. {
  1640. int size = qdict_get_int(qdict, "size");
  1641. int addr = qdict_get_int(qdict, "addr");
  1642. int val = qdict_get_int(qdict, "val");
  1643. addr &= IOPORTS_MASK;
  1644. switch (size) {
  1645. default:
  1646. case 1:
  1647. cpu_outb(addr, val);
  1648. break;
  1649. case 2:
  1650. cpu_outw(addr, val);
  1651. break;
  1652. case 4:
  1653. cpu_outl(addr, val);
  1654. break;
  1655. }
  1656. }
  1657. static void hmp_boot_set(Monitor *mon, const QDict *qdict)
  1658. {
  1659. Error *local_err = NULL;
  1660. const char *bootdevice = qdict_get_str(qdict, "bootdevice");
  1661. qemu_boot_set(bootdevice, &local_err);
  1662. if (local_err) {
  1663. error_report_err(local_err);
  1664. } else {
  1665. monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
  1666. }
  1667. }
  1668. static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
  1669. {
  1670. bool flatview = qdict_get_try_bool(qdict, "flatview", false);
  1671. bool dispatch_tree = qdict_get_try_bool(qdict, "dispatch_tree", false);
  1672. bool owner = qdict_get_try_bool(qdict, "owner", false);
  1673. mtree_info(flatview, dispatch_tree, owner);
  1674. }
  1675. static void hmp_info_numa(Monitor *mon, const QDict *qdict)
  1676. {
  1677. int i;
  1678. NumaNodeMem *node_mem;
  1679. CpuInfoList *cpu_list, *cpu;
  1680. cpu_list = qmp_query_cpus(&error_abort);
  1681. node_mem = g_new0(NumaNodeMem, nb_numa_nodes);
  1682. query_numa_node_mem(node_mem);
  1683. monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
  1684. for (i = 0; i < nb_numa_nodes; i++) {
  1685. monitor_printf(mon, "node %d cpus:", i);
  1686. for (cpu = cpu_list; cpu; cpu = cpu->next) {
  1687. if (cpu->value->has_props && cpu->value->props->has_node_id &&
  1688. cpu->value->props->node_id == i) {
  1689. monitor_printf(mon, " %" PRIi64, cpu->value->CPU);
  1690. }
  1691. }
  1692. monitor_printf(mon, "\n");
  1693. monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
  1694. node_mem[i].node_mem >> 20);
  1695. monitor_printf(mon, "node %d plugged: %" PRId64 " MB\n", i,
  1696. node_mem[i].node_plugged_mem >> 20);
  1697. }
  1698. qapi_free_CpuInfoList(cpu_list);
  1699. g_free(node_mem);
  1700. }
  1701. #ifdef CONFIG_PROFILER
  1702. int64_t dev_time;
  1703. static void hmp_info_profile(Monitor *mon, const QDict *qdict)
  1704. {
  1705. static int64_t last_cpu_exec_time;
  1706. int64_t cpu_exec_time;
  1707. int64_t delta;
  1708. cpu_exec_time = tcg_cpu_exec_time();
  1709. delta = cpu_exec_time - last_cpu_exec_time;
  1710. monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
  1711. dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
  1712. monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
  1713. delta, delta / (double)NANOSECONDS_PER_SECOND);
  1714. last_cpu_exec_time = cpu_exec_time;
  1715. dev_time = 0;
  1716. }
  1717. #else
  1718. static void hmp_info_profile(Monitor *mon, const QDict *qdict)
  1719. {
  1720. monitor_printf(mon, "Internal profiler not compiled\n");
  1721. }
  1722. #endif
  1723. /* Capture support */
  1724. static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
  1725. static void hmp_info_capture(Monitor *mon, const QDict *qdict)
  1726. {
  1727. int i;
  1728. CaptureState *s;
  1729. for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
  1730. monitor_printf(mon, "[%d]: ", i);
  1731. s->ops.info (s->opaque);
  1732. }
  1733. }
  1734. static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
  1735. {
  1736. int i;
  1737. int n = qdict_get_int(qdict, "n");
  1738. CaptureState *s;
  1739. for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
  1740. if (i == n) {
  1741. s->ops.destroy (s->opaque);
  1742. QLIST_REMOVE (s, entries);
  1743. g_free (s);
  1744. return;
  1745. }
  1746. }
  1747. }
  1748. static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
  1749. {
  1750. const char *path = qdict_get_str(qdict, "path");
  1751. int has_freq = qdict_haskey(qdict, "freq");
  1752. int freq = qdict_get_try_int(qdict, "freq", -1);
  1753. int has_bits = qdict_haskey(qdict, "bits");
  1754. int bits = qdict_get_try_int(qdict, "bits", -1);
  1755. int has_channels = qdict_haskey(qdict, "nchannels");
  1756. int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
  1757. CaptureState *s;
  1758. s = g_malloc0 (sizeof (*s));
  1759. freq = has_freq ? freq : 44100;
  1760. bits = has_bits ? bits : 16;
  1761. nchannels = has_channels ? nchannels : 2;
  1762. if (wav_start_capture (s, path, freq, bits, nchannels)) {
  1763. monitor_printf(mon, "Failed to add wave capture\n");
  1764. g_free (s);
  1765. return;
  1766. }
  1767. QLIST_INSERT_HEAD (&capture_head, s, entries);
  1768. }
  1769. static QAuthZList *find_auth(Monitor *mon, const char *name)
  1770. {
  1771. Object *obj;
  1772. Object *container;
  1773. container = object_get_objects_root();
  1774. obj = object_resolve_path_component(container, name);
  1775. if (!obj) {
  1776. monitor_printf(mon, "acl: unknown list '%s'\n", name);
  1777. return NULL;
  1778. }
  1779. return QAUTHZ_LIST(obj);
  1780. }
  1781. static bool warn_acl;
  1782. static void hmp_warn_acl(void)
  1783. {
  1784. if (warn_acl) {
  1785. return;
  1786. }
  1787. error_report("The acl_show, acl_reset, acl_policy, acl_add, acl_remove "
  1788. "commands are deprecated with no replacement. Authorization "
  1789. "for VNC should be performed using the pluggable QAuthZ "
  1790. "objects");
  1791. warn_acl = true;
  1792. }
  1793. static void hmp_acl_show(Monitor *mon, const QDict *qdict)
  1794. {
  1795. const char *aclname = qdict_get_str(qdict, "aclname");
  1796. QAuthZList *auth = find_auth(mon, aclname);
  1797. QAuthZListRuleList *rules;
  1798. size_t i = 0;
  1799. hmp_warn_acl();
  1800. if (!auth) {
  1801. return;
  1802. }
  1803. monitor_printf(mon, "policy: %s\n",
  1804. QAuthZListPolicy_str(auth->policy));
  1805. rules = auth->rules;
  1806. while (rules) {
  1807. QAuthZListRule *rule = rules->value;
  1808. i++;
  1809. monitor_printf(mon, "%zu: %s %s\n", i,
  1810. QAuthZListPolicy_str(rule->policy),
  1811. rule->match);
  1812. rules = rules->next;
  1813. }
  1814. }
  1815. static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
  1816. {
  1817. const char *aclname = qdict_get_str(qdict, "aclname");
  1818. QAuthZList *auth = find_auth(mon, aclname);
  1819. hmp_warn_acl();
  1820. if (!auth) {
  1821. return;
  1822. }
  1823. auth->policy = QAUTHZ_LIST_POLICY_DENY;
  1824. qapi_free_QAuthZListRuleList(auth->rules);
  1825. auth->rules = NULL;
  1826. monitor_printf(mon, "acl: removed all rules\n");
  1827. }
  1828. static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
  1829. {
  1830. const char *aclname = qdict_get_str(qdict, "aclname");
  1831. const char *policy = qdict_get_str(qdict, "policy");
  1832. QAuthZList *auth = find_auth(mon, aclname);
  1833. int val;
  1834. Error *err = NULL;
  1835. hmp_warn_acl();
  1836. if (!auth) {
  1837. return;
  1838. }
  1839. val = qapi_enum_parse(&QAuthZListPolicy_lookup,
  1840. policy,
  1841. QAUTHZ_LIST_POLICY_DENY,
  1842. &err);
  1843. if (err) {
  1844. error_free(err);
  1845. monitor_printf(mon, "acl: unknown policy '%s', "
  1846. "expected 'deny' or 'allow'\n", policy);
  1847. } else {
  1848. auth->policy = val;
  1849. if (auth->policy == QAUTHZ_LIST_POLICY_ALLOW) {
  1850. monitor_printf(mon, "acl: policy set to 'allow'\n");
  1851. } else {
  1852. monitor_printf(mon, "acl: policy set to 'deny'\n");
  1853. }
  1854. }
  1855. }
  1856. static QAuthZListFormat hmp_acl_get_format(const char *match)
  1857. {
  1858. if (strchr(match, '*')) {
  1859. return QAUTHZ_LIST_FORMAT_GLOB;
  1860. } else {
  1861. return QAUTHZ_LIST_FORMAT_EXACT;
  1862. }
  1863. }
  1864. static void hmp_acl_add(Monitor *mon, const QDict *qdict)
  1865. {
  1866. const char *aclname = qdict_get_str(qdict, "aclname");
  1867. const char *match = qdict_get_str(qdict, "match");
  1868. const char *policystr = qdict_get_str(qdict, "policy");
  1869. int has_index = qdict_haskey(qdict, "index");
  1870. int index = qdict_get_try_int(qdict, "index", -1);
  1871. QAuthZList *auth = find_auth(mon, aclname);
  1872. Error *err = NULL;
  1873. QAuthZListPolicy policy;
  1874. QAuthZListFormat format;
  1875. size_t i = 0;
  1876. hmp_warn_acl();
  1877. if (!auth) {
  1878. return;
  1879. }
  1880. policy = qapi_enum_parse(&QAuthZListPolicy_lookup,
  1881. policystr,
  1882. QAUTHZ_LIST_POLICY_DENY,
  1883. &err);
  1884. if (err) {
  1885. error_free(err);
  1886. monitor_printf(mon, "acl: unknown policy '%s', "
  1887. "expected 'deny' or 'allow'\n", policystr);
  1888. return;
  1889. }
  1890. format = hmp_acl_get_format(match);
  1891. if (has_index && index == 0) {
  1892. monitor_printf(mon, "acl: unable to add acl entry\n");
  1893. return;
  1894. }
  1895. if (has_index) {
  1896. i = qauthz_list_insert_rule(auth, match, policy,
  1897. format, index - 1, &err);
  1898. } else {
  1899. i = qauthz_list_append_rule(auth, match, policy,
  1900. format, &err);
  1901. }
  1902. if (err) {
  1903. monitor_printf(mon, "acl: unable to add rule: %s",
  1904. error_get_pretty(err));
  1905. error_free(err);
  1906. } else {
  1907. monitor_printf(mon, "acl: added rule at position %zu\n", i + 1);
  1908. }
  1909. }
  1910. static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
  1911. {
  1912. const char *aclname = qdict_get_str(qdict, "aclname");
  1913. const char *match = qdict_get_str(qdict, "match");
  1914. QAuthZList *auth = find_auth(mon, aclname);
  1915. ssize_t i = 0;
  1916. hmp_warn_acl();
  1917. if (!auth) {
  1918. return;
  1919. }
  1920. i = qauthz_list_delete_rule(auth, match);
  1921. if (i >= 0) {
  1922. monitor_printf(mon, "acl: removed rule at position %zu\n", i + 1);
  1923. } else {
  1924. monitor_printf(mon, "acl: no matching acl entry\n");
  1925. }
  1926. }
  1927. void qmp_getfd(const char *fdname, Error **errp)
  1928. {
  1929. mon_fd_t *monfd;
  1930. int fd, tmp_fd;
  1931. fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
  1932. if (fd == -1) {
  1933. error_setg(errp, QERR_FD_NOT_SUPPLIED);
  1934. return;
  1935. }
  1936. if (qemu_isdigit(fdname[0])) {
  1937. close(fd);
  1938. error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
  1939. "a name not starting with a digit");
  1940. return;
  1941. }
  1942. qemu_mutex_lock(&cur_mon->mon_lock);
  1943. QLIST_FOREACH(monfd, &cur_mon->fds, next) {
  1944. if (strcmp(monfd->name, fdname) != 0) {
  1945. continue;
  1946. }
  1947. tmp_fd = monfd->fd;
  1948. monfd->fd = fd;
  1949. qemu_mutex_unlock(&cur_mon->mon_lock);
  1950. /* Make sure close() is outside critical section */
  1951. close(tmp_fd);
  1952. return;
  1953. }
  1954. monfd = g_malloc0(sizeof(mon_fd_t));
  1955. monfd->name = g_strdup(fdname);
  1956. monfd->fd = fd;
  1957. QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
  1958. qemu_mutex_unlock(&cur_mon->mon_lock);
  1959. }
  1960. void qmp_closefd(const char *fdname, Error **errp)
  1961. {
  1962. mon_fd_t *monfd;
  1963. int tmp_fd;
  1964. qemu_mutex_lock(&cur_mon->mon_lock);
  1965. QLIST_FOREACH(monfd, &cur_mon->fds, next) {
  1966. if (strcmp(monfd->name, fdname) != 0) {
  1967. continue;
  1968. }
  1969. QLIST_REMOVE(monfd, next);
  1970. tmp_fd = monfd->fd;
  1971. g_free(monfd->name);
  1972. g_free(monfd);
  1973. qemu_mutex_unlock(&cur_mon->mon_lock);
  1974. /* Make sure close() is outside critical section */
  1975. close(tmp_fd);
  1976. return;
  1977. }
  1978. qemu_mutex_unlock(&cur_mon->mon_lock);
  1979. error_setg(errp, QERR_FD_NOT_FOUND, fdname);
  1980. }
  1981. int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
  1982. {
  1983. mon_fd_t *monfd;
  1984. qemu_mutex_lock(&mon->mon_lock);
  1985. QLIST_FOREACH(monfd, &mon->fds, next) {
  1986. int fd;
  1987. if (strcmp(monfd->name, fdname) != 0) {
  1988. continue;
  1989. }
  1990. fd = monfd->fd;
  1991. /* caller takes ownership of fd */
  1992. QLIST_REMOVE(monfd, next);
  1993. g_free(monfd->name);
  1994. g_free(monfd);
  1995. qemu_mutex_unlock(&mon->mon_lock);
  1996. return fd;
  1997. }
  1998. qemu_mutex_unlock(&mon->mon_lock);
  1999. error_setg(errp, "File descriptor named '%s' has not been found", fdname);
  2000. return -1;
  2001. }
  2002. static void monitor_fdset_cleanup(MonFdset *mon_fdset)
  2003. {
  2004. MonFdsetFd *mon_fdset_fd;
  2005. MonFdsetFd *mon_fdset_fd_next;
  2006. QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
  2007. if ((mon_fdset_fd->removed ||
  2008. (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
  2009. runstate_is_running()) {
  2010. close(mon_fdset_fd->fd);
  2011. g_free(mon_fdset_fd->opaque);
  2012. QLIST_REMOVE(mon_fdset_fd, next);
  2013. g_free(mon_fdset_fd);
  2014. }
  2015. }
  2016. if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
  2017. QLIST_REMOVE(mon_fdset, next);
  2018. g_free(mon_fdset);
  2019. }
  2020. }
  2021. static void monitor_fdsets_cleanup(void)
  2022. {
  2023. MonFdset *mon_fdset;
  2024. MonFdset *mon_fdset_next;
  2025. qemu_mutex_lock(&mon_fdsets_lock);
  2026. QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
  2027. monitor_fdset_cleanup(mon_fdset);
  2028. }
  2029. qemu_mutex_unlock(&mon_fdsets_lock);
  2030. }
  2031. AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
  2032. const char *opaque, Error **errp)
  2033. {
  2034. int fd;
  2035. Monitor *mon = cur_mon;
  2036. AddfdInfo *fdinfo;
  2037. fd = qemu_chr_fe_get_msgfd(&mon->chr);
  2038. if (fd == -1) {
  2039. error_setg(errp, QERR_FD_NOT_SUPPLIED);
  2040. goto error;
  2041. }
  2042. fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
  2043. has_opaque, opaque, errp);
  2044. if (fdinfo) {
  2045. return fdinfo;
  2046. }
  2047. error:
  2048. if (fd != -1) {
  2049. close(fd);
  2050. }
  2051. return NULL;
  2052. }
  2053. void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
  2054. {
  2055. MonFdset *mon_fdset;
  2056. MonFdsetFd *mon_fdset_fd;
  2057. char fd_str[60];
  2058. qemu_mutex_lock(&mon_fdsets_lock);
  2059. QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
  2060. if (mon_fdset->id != fdset_id) {
  2061. continue;
  2062. }
  2063. QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
  2064. if (has_fd) {
  2065. if (mon_fdset_fd->fd != fd) {
  2066. continue;
  2067. }
  2068. mon_fdset_fd->removed = true;
  2069. break;
  2070. } else {
  2071. mon_fdset_fd->removed = true;
  2072. }
  2073. }
  2074. if (has_fd && !mon_fdset_fd) {
  2075. goto error;
  2076. }
  2077. monitor_fdset_cleanup(mon_fdset);
  2078. qemu_mutex_unlock(&mon_fdsets_lock);
  2079. return;
  2080. }
  2081. error:
  2082. qemu_mutex_unlock(&mon_fdsets_lock);
  2083. if (has_fd) {
  2084. snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
  2085. fdset_id, fd);
  2086. } else {
  2087. snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
  2088. }
  2089. error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
  2090. }
  2091. FdsetInfoList *qmp_query_fdsets(Error **errp)
  2092. {
  2093. MonFdset *mon_fdset;
  2094. MonFdsetFd *mon_fdset_fd;
  2095. FdsetInfoList *fdset_list = NULL;
  2096. qemu_mutex_lock(&mon_fdsets_lock);
  2097. QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
  2098. FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
  2099. FdsetFdInfoList *fdsetfd_list = NULL;
  2100. fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
  2101. fdset_info->value->fdset_id = mon_fdset->id;
  2102. QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
  2103. FdsetFdInfoList *fdsetfd_info;
  2104. fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
  2105. fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
  2106. fdsetfd_info->value->fd = mon_fdset_fd->fd;
  2107. if (mon_fdset_fd->opaque) {
  2108. fdsetfd_info->value->has_opaque = true;
  2109. fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
  2110. } else {
  2111. fdsetfd_info->value->has_opaque = false;
  2112. }
  2113. fdsetfd_info->next = fdsetfd_list;
  2114. fdsetfd_list = fdsetfd_info;
  2115. }
  2116. fdset_info->value->fds = fdsetfd_list;
  2117. fdset_info->next = fdset_list;
  2118. fdset_list = fdset_info;
  2119. }
  2120. qemu_mutex_unlock(&mon_fdsets_lock);
  2121. return fdset_list;
  2122. }
  2123. AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
  2124. bool has_opaque, const char *opaque,
  2125. Error **errp)
  2126. {
  2127. MonFdset *mon_fdset = NULL;
  2128. MonFdsetFd *mon_fdset_fd;
  2129. AddfdInfo *fdinfo;
  2130. qemu_mutex_lock(&mon_fdsets_lock);
  2131. if (has_fdset_id) {
  2132. QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
  2133. /* Break if match found or match impossible due to ordering by ID */
  2134. if (fdset_id <= mon_fdset->id) {
  2135. if (fdset_id < mon_fdset->id) {
  2136. mon_fdset = NULL;
  2137. }
  2138. break;
  2139. }
  2140. }
  2141. }
  2142. if (mon_fdset == NULL) {
  2143. int64_t fdset_id_prev = -1;
  2144. MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
  2145. if (has_fdset_id) {
  2146. if (fdset_id < 0) {
  2147. error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
  2148. "a non-negative value");
  2149. qemu_mutex_unlock(&mon_fdsets_lock);
  2150. return NULL;
  2151. }
  2152. /* Use specified fdset ID */
  2153. QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
  2154. mon_fdset_cur = mon_fdset;
  2155. if (fdset_id < mon_fdset_cur->id) {
  2156. break;
  2157. }
  2158. }
  2159. } else {
  2160. /* Use first available fdset ID */
  2161. QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
  2162. mon_fdset_cur = mon_fdset;
  2163. if (fdset_id_prev == mon_fdset_cur->id - 1) {
  2164. fdset_id_prev = mon_fdset_cur->id;
  2165. continue;
  2166. }
  2167. break;
  2168. }
  2169. }
  2170. mon_fdset = g_malloc0(sizeof(*mon_fdset));
  2171. if (has_fdset_id) {
  2172. mon_fdset->id = fdset_id;
  2173. } else {
  2174. mon_fdset->id = fdset_id_prev + 1;
  2175. }
  2176. /* The fdset list is ordered by fdset ID */
  2177. if (!mon_fdset_cur) {
  2178. QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
  2179. } else if (mon_fdset->id < mon_fdset_cur->id) {
  2180. QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
  2181. } else {
  2182. QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
  2183. }
  2184. }
  2185. mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
  2186. mon_fdset_fd->fd = fd;
  2187. mon_fdset_fd->removed = false;
  2188. if (has_opaque) {
  2189. mon_fdset_fd->opaque = g_strdup(opaque);
  2190. }
  2191. QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
  2192. fdinfo = g_malloc0(sizeof(*fdinfo));
  2193. fdinfo->fdset_id = mon_fdset->id;
  2194. fdinfo->fd = mon_fdset_fd->fd;
  2195. qemu_mutex_unlock(&mon_fdsets_lock);
  2196. return fdinfo;
  2197. }
  2198. int monitor_fdset_get_fd(int64_t fdset_id, int flags)
  2199. {
  2200. #ifdef _WIN32
  2201. return -ENOENT;
  2202. #else
  2203. MonFdset *mon_fdset;
  2204. MonFdsetFd *mon_fdset_fd;
  2205. int mon_fd_flags;
  2206. int ret;
  2207. qemu_mutex_lock(&mon_fdsets_lock);
  2208. QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
  2209. if (mon_fdset->id != fdset_id) {
  2210. continue;
  2211. }
  2212. QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
  2213. mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
  2214. if (mon_fd_flags == -1) {
  2215. ret = -errno;
  2216. goto out;
  2217. }
  2218. if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
  2219. ret = mon_fdset_fd->fd;
  2220. goto out;
  2221. }
  2222. }
  2223. ret = -EACCES;
  2224. goto out;
  2225. }
  2226. ret = -ENOENT;
  2227. out:
  2228. qemu_mutex_unlock(&mon_fdsets_lock);
  2229. return ret;
  2230. #endif
  2231. }
  2232. int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
  2233. {
  2234. MonFdset *mon_fdset;
  2235. MonFdsetFd *mon_fdset_fd_dup;
  2236. qemu_mutex_lock(&mon_fdsets_lock);
  2237. QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
  2238. if (mon_fdset->id != fdset_id) {
  2239. continue;
  2240. }
  2241. QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
  2242. if (mon_fdset_fd_dup->fd == dup_fd) {
  2243. goto err;
  2244. }
  2245. }
  2246. mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
  2247. mon_fdset_fd_dup->fd = dup_fd;
  2248. QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
  2249. qemu_mutex_unlock(&mon_fdsets_lock);
  2250. return 0;
  2251. }
  2252. err:
  2253. qemu_mutex_unlock(&mon_fdsets_lock);
  2254. return -1;
  2255. }
  2256. static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
  2257. {
  2258. MonFdset *mon_fdset;
  2259. MonFdsetFd *mon_fdset_fd_dup;
  2260. qemu_mutex_lock(&mon_fdsets_lock);
  2261. QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
  2262. QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
  2263. if (mon_fdset_fd_dup->fd == dup_fd) {
  2264. if (remove) {
  2265. QLIST_REMOVE(mon_fdset_fd_dup, next);
  2266. if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
  2267. monitor_fdset_cleanup(mon_fdset);
  2268. }
  2269. goto err;
  2270. } else {
  2271. qemu_mutex_unlock(&mon_fdsets_lock);
  2272. return mon_fdset->id;
  2273. }
  2274. }
  2275. }
  2276. }
  2277. err:
  2278. qemu_mutex_unlock(&mon_fdsets_lock);
  2279. return -1;
  2280. }
  2281. int monitor_fdset_dup_fd_find(int dup_fd)
  2282. {
  2283. return monitor_fdset_dup_fd_find_remove(dup_fd, false);
  2284. }
  2285. void monitor_fdset_dup_fd_remove(int dup_fd)
  2286. {
  2287. monitor_fdset_dup_fd_find_remove(dup_fd, true);
  2288. }
  2289. int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
  2290. {
  2291. int fd;
  2292. Error *local_err = NULL;
  2293. if (!qemu_isdigit(fdname[0]) && mon) {
  2294. fd = monitor_get_fd(mon, fdname, &local_err);
  2295. } else {
  2296. fd = qemu_parse_fd(fdname);
  2297. if (fd == -1) {
  2298. error_setg(&local_err, "Invalid file descriptor number '%s'",
  2299. fdname);
  2300. }
  2301. }
  2302. if (local_err) {
  2303. error_propagate(errp, local_err);
  2304. assert(fd == -1);
  2305. } else {
  2306. assert(fd != -1);
  2307. }
  2308. return fd;
  2309. }
  2310. /* Please update hmp-commands.hx when adding or changing commands */
  2311. static mon_cmd_t info_cmds[] = {
  2312. #include "hmp-commands-info.h"
  2313. { NULL, NULL, },
  2314. };
  2315. /* mon_cmds and info_cmds would be sorted at runtime */
  2316. static mon_cmd_t mon_cmds[] = {
  2317. #include "hmp-commands.h"
  2318. { NULL, NULL, },
  2319. };
  2320. /*******************************************************************/
  2321. static const char *pch;
  2322. static sigjmp_buf expr_env;
  2323. static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
  2324. expr_error(Monitor *mon, const char *fmt, ...)
  2325. {
  2326. va_list ap;
  2327. va_start(ap, fmt);
  2328. monitor_vprintf(mon, fmt, ap);
  2329. monitor_printf(mon, "\n");
  2330. va_end(ap);
  2331. siglongjmp(expr_env, 1);
  2332. }
  2333. /* return 0 if OK, -1 if not found */
  2334. static int get_monitor_def(target_long *pval, const char *name)
  2335. {
  2336. const MonitorDef *md = target_monitor_defs();
  2337. CPUState *cs = mon_get_cpu();
  2338. void *ptr;
  2339. uint64_t tmp = 0;
  2340. int ret;
  2341. if (cs == NULL || md == NULL) {
  2342. return -1;
  2343. }
  2344. for(; md->name != NULL; md++) {
  2345. if (compare_cmd(name, md->name)) {
  2346. if (md->get_value) {
  2347. *pval = md->get_value(md, md->offset);
  2348. } else {
  2349. CPUArchState *env = mon_get_cpu_env();
  2350. ptr = (uint8_t *)env + md->offset;
  2351. switch(md->type) {
  2352. case MD_I32:
  2353. *pval = *(int32_t *)ptr;
  2354. break;
  2355. case MD_TLONG:
  2356. *pval = *(target_long *)ptr;
  2357. break;
  2358. default:
  2359. *pval = 0;
  2360. break;
  2361. }
  2362. }
  2363. return 0;
  2364. }
  2365. }
  2366. ret = target_get_monitor_def(cs, name, &tmp);
  2367. if (!ret) {
  2368. *pval = (target_long) tmp;
  2369. }
  2370. return ret;
  2371. }
  2372. static void next(void)
  2373. {
  2374. if (*pch != '\0') {
  2375. pch++;
  2376. while (qemu_isspace(*pch))
  2377. pch++;
  2378. }
  2379. }
  2380. static int64_t expr_sum(Monitor *mon);
  2381. static int64_t expr_unary(Monitor *mon)
  2382. {
  2383. int64_t n;
  2384. char *p;
  2385. int ret;
  2386. switch(*pch) {
  2387. case '+':
  2388. next();
  2389. n = expr_unary(mon);
  2390. break;
  2391. case '-':
  2392. next();
  2393. n = -expr_unary(mon);
  2394. break;
  2395. case '~':
  2396. next();
  2397. n = ~expr_unary(mon);
  2398. break;
  2399. case '(':
  2400. next();
  2401. n = expr_sum(mon);
  2402. if (*pch != ')') {
  2403. expr_error(mon, "')' expected");
  2404. }
  2405. next();
  2406. break;
  2407. case '\'':
  2408. pch++;
  2409. if (*pch == '\0')
  2410. expr_error(mon, "character constant expected");
  2411. n = *pch;
  2412. pch++;
  2413. if (*pch != '\'')
  2414. expr_error(mon, "missing terminating \' character");
  2415. next();
  2416. break;
  2417. case '$':
  2418. {
  2419. char buf[128], *q;
  2420. target_long reg=0;
  2421. pch++;
  2422. q = buf;
  2423. while ((*pch >= 'a' && *pch <= 'z') ||
  2424. (*pch >= 'A' && *pch <= 'Z') ||
  2425. (*pch >= '0' && *pch <= '9') ||
  2426. *pch == '_' || *pch == '.') {
  2427. if ((q - buf) < sizeof(buf) - 1)
  2428. *q++ = *pch;
  2429. pch++;
  2430. }
  2431. while (qemu_isspace(*pch))
  2432. pch++;
  2433. *q = 0;
  2434. ret = get_monitor_def(&reg, buf);
  2435. if (ret < 0)
  2436. expr_error(mon, "unknown register");
  2437. n = reg;
  2438. }
  2439. break;
  2440. case '\0':
  2441. expr_error(mon, "unexpected end of expression");
  2442. n = 0;
  2443. break;
  2444. default:
  2445. errno = 0;
  2446. n = strtoull(pch, &p, 0);
  2447. if (errno == ERANGE) {
  2448. expr_error(mon, "number too large");
  2449. }
  2450. if (pch == p) {
  2451. expr_error(mon, "invalid char '%c' in expression", *p);
  2452. }
  2453. pch = p;
  2454. while (qemu_isspace(*pch))
  2455. pch++;
  2456. break;
  2457. }
  2458. return n;
  2459. }
  2460. static int64_t expr_prod(Monitor *mon)
  2461. {
  2462. int64_t val, val2;
  2463. int op;
  2464. val = expr_unary(mon);
  2465. for(;;) {
  2466. op = *pch;
  2467. if (op != '*' && op != '/' && op != '%')
  2468. break;
  2469. next();
  2470. val2 = expr_unary(mon);
  2471. switch(op) {
  2472. default:
  2473. case '*':
  2474. val *= val2;
  2475. break;
  2476. case '/':
  2477. case '%':
  2478. if (val2 == 0)
  2479. expr_error(mon, "division by zero");
  2480. if (op == '/')
  2481. val /= val2;
  2482. else
  2483. val %= val2;
  2484. break;
  2485. }
  2486. }
  2487. return val;
  2488. }
  2489. static int64_t expr_logic(Monitor *mon)
  2490. {
  2491. int64_t val, val2;
  2492. int op;
  2493. val = expr_prod(mon);
  2494. for(;;) {
  2495. op = *pch;
  2496. if (op != '&' && op != '|' && op != '^')
  2497. break;
  2498. next();
  2499. val2 = expr_prod(mon);
  2500. switch(op) {
  2501. default:
  2502. case '&':
  2503. val &= val2;
  2504. break;
  2505. case '|':
  2506. val |= val2;
  2507. break;
  2508. case '^':
  2509. val ^= val2;
  2510. break;
  2511. }
  2512. }
  2513. return val;
  2514. }
  2515. static int64_t expr_sum(Monitor *mon)
  2516. {
  2517. int64_t val, val2;
  2518. int op;
  2519. val = expr_logic(mon);
  2520. for(;;) {
  2521. op = *pch;
  2522. if (op != '+' && op != '-')
  2523. break;
  2524. next();
  2525. val2 = expr_logic(mon);
  2526. if (op == '+')
  2527. val += val2;
  2528. else
  2529. val -= val2;
  2530. }
  2531. return val;
  2532. }
  2533. static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
  2534. {
  2535. pch = *pp;
  2536. if (sigsetjmp(expr_env, 0)) {
  2537. *pp = pch;
  2538. return -1;
  2539. }
  2540. while (qemu_isspace(*pch))
  2541. pch++;
  2542. *pval = expr_sum(mon);
  2543. *pp = pch;
  2544. return 0;
  2545. }
  2546. static int get_double(Monitor *mon, double *pval, const char **pp)
  2547. {
  2548. const char *p = *pp;
  2549. char *tailp;
  2550. double d;
  2551. d = strtod(p, &tailp);
  2552. if (tailp == p) {
  2553. monitor_printf(mon, "Number expected\n");
  2554. return -1;
  2555. }
  2556. if (d != d || d - d != 0) {
  2557. /* NaN or infinity */
  2558. monitor_printf(mon, "Bad number\n");
  2559. return -1;
  2560. }
  2561. *pval = d;
  2562. *pp = tailp;
  2563. return 0;
  2564. }
  2565. /*
  2566. * Store the command-name in cmdname, and return a pointer to
  2567. * the remaining of the command string.
  2568. */
  2569. static const char *get_command_name(const char *cmdline,
  2570. char *cmdname, size_t nlen)
  2571. {
  2572. size_t len;
  2573. const char *p, *pstart;
  2574. p = cmdline;
  2575. while (qemu_isspace(*p))
  2576. p++;
  2577. if (*p == '\0')
  2578. return NULL;
  2579. pstart = p;
  2580. while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
  2581. p++;
  2582. len = p - pstart;
  2583. if (len > nlen - 1)
  2584. len = nlen - 1;
  2585. memcpy(cmdname, pstart, len);
  2586. cmdname[len] = '\0';
  2587. return p;
  2588. }
  2589. /**
  2590. * Read key of 'type' into 'key' and return the current
  2591. * 'type' pointer.
  2592. */
  2593. static char *key_get_info(const char *type, char **key)
  2594. {
  2595. size_t len;
  2596. char *p, *str;
  2597. if (*type == ',')
  2598. type++;
  2599. p = strchr(type, ':');
  2600. if (!p) {
  2601. *key = NULL;
  2602. return NULL;
  2603. }
  2604. len = p - type;
  2605. str = g_malloc(len + 1);
  2606. memcpy(str, type, len);
  2607. str[len] = '\0';
  2608. *key = str;
  2609. return ++p;
  2610. }
  2611. static int default_fmt_format = 'x';
  2612. static int default_fmt_size = 4;
  2613. static int is_valid_option(const char *c, const char *typestr)
  2614. {
  2615. char option[3];
  2616. option[0] = '-';
  2617. option[1] = *c;
  2618. option[2] = '\0';
  2619. typestr = strstr(typestr, option);
  2620. return (typestr != NULL);
  2621. }
  2622. static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
  2623. const char *cmdname)
  2624. {
  2625. const mon_cmd_t *cmd;
  2626. for (cmd = disp_table; cmd->name != NULL; cmd++) {
  2627. if (compare_cmd(cmdname, cmd->name)) {
  2628. return cmd;
  2629. }
  2630. }
  2631. return NULL;
  2632. }
  2633. /*
  2634. * Parse command name from @cmdp according to command table @table.
  2635. * If blank, return NULL.
  2636. * Else, if no valid command can be found, report to @mon, and return
  2637. * NULL.
  2638. * Else, change @cmdp to point right behind the name, and return its
  2639. * command table entry.
  2640. * Do not assume the return value points into @table! It doesn't when
  2641. * the command is found in a sub-command table.
  2642. */
  2643. static const mon_cmd_t *monitor_parse_command(Monitor *mon,
  2644. const char *cmdp_start,
  2645. const char **cmdp,
  2646. mon_cmd_t *table)
  2647. {
  2648. const char *p;
  2649. const mon_cmd_t *cmd;
  2650. char cmdname[256];
  2651. /* extract the command name */
  2652. p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
  2653. if (!p)
  2654. return NULL;
  2655. cmd = search_dispatch_table(table, cmdname);
  2656. if (!cmd) {
  2657. monitor_printf(mon, "unknown command: '%.*s'\n",
  2658. (int)(p - cmdp_start), cmdp_start);
  2659. return NULL;
  2660. }
  2661. if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
  2662. monitor_printf(mon, "Command '%.*s' not available with -preconfig "
  2663. "until after exit_preconfig.\n",
  2664. (int)(p - cmdp_start), cmdp_start);
  2665. return NULL;
  2666. }
  2667. /* filter out following useless space */
  2668. while (qemu_isspace(*p)) {
  2669. p++;
  2670. }
  2671. *cmdp = p;
  2672. /* search sub command */
  2673. if (cmd->sub_table != NULL && *p != '\0') {
  2674. return monitor_parse_command(mon, cmdp_start, cmdp, cmd->sub_table);
  2675. }
  2676. return cmd;
  2677. }
  2678. /*
  2679. * Parse arguments for @cmd.
  2680. * If it can't be parsed, report to @mon, and return NULL.
  2681. * Else, insert command arguments into a QDict, and return it.
  2682. * Note: On success, caller has to free the QDict structure.
  2683. */
  2684. static QDict *monitor_parse_arguments(Monitor *mon,
  2685. const char **endp,
  2686. const mon_cmd_t *cmd)
  2687. {
  2688. const char *typestr;
  2689. char *key;
  2690. int c;
  2691. const char *p = *endp;
  2692. char buf[1024];
  2693. QDict *qdict = qdict_new();
  2694. /* parse the parameters */
  2695. typestr = cmd->args_type;
  2696. for(;;) {
  2697. typestr = key_get_info(typestr, &key);
  2698. if (!typestr)
  2699. break;
  2700. c = *typestr;
  2701. typestr++;
  2702. switch(c) {
  2703. case 'F':
  2704. case 'B':
  2705. case 's':
  2706. {
  2707. int ret;
  2708. while (qemu_isspace(*p))
  2709. p++;
  2710. if (*typestr == '?') {
  2711. typestr++;
  2712. if (*p == '\0') {
  2713. /* no optional string: NULL argument */
  2714. break;
  2715. }
  2716. }
  2717. ret = get_str(buf, sizeof(buf), &p);
  2718. if (ret < 0) {
  2719. switch(c) {
  2720. case 'F':
  2721. monitor_printf(mon, "%s: filename expected\n",
  2722. cmd->name);
  2723. break;
  2724. case 'B':
  2725. monitor_printf(mon, "%s: block device name expected\n",
  2726. cmd->name);
  2727. break;
  2728. default:
  2729. monitor_printf(mon, "%s: string expected\n", cmd->name);
  2730. break;
  2731. }
  2732. goto fail;
  2733. }
  2734. qdict_put_str(qdict, key, buf);
  2735. }
  2736. break;
  2737. case 'O':
  2738. {
  2739. QemuOptsList *opts_list;
  2740. QemuOpts *opts;
  2741. opts_list = qemu_find_opts(key);
  2742. if (!opts_list || opts_list->desc->name) {
  2743. goto bad_type;
  2744. }
  2745. while (qemu_isspace(*p)) {
  2746. p++;
  2747. }
  2748. if (!*p)
  2749. break;
  2750. if (get_str(buf, sizeof(buf), &p) < 0) {
  2751. goto fail;
  2752. }
  2753. opts = qemu_opts_parse_noisily(opts_list, buf, true);
  2754. if (!opts) {
  2755. goto fail;
  2756. }
  2757. qemu_opts_to_qdict(opts, qdict);
  2758. qemu_opts_del(opts);
  2759. }
  2760. break;
  2761. case '/':
  2762. {
  2763. int count, format, size;
  2764. while (qemu_isspace(*p))
  2765. p++;
  2766. if (*p == '/') {
  2767. /* format found */
  2768. p++;
  2769. count = 1;
  2770. if (qemu_isdigit(*p)) {
  2771. count = 0;
  2772. while (qemu_isdigit(*p)) {
  2773. count = count * 10 + (*p - '0');
  2774. p++;
  2775. }
  2776. }
  2777. size = -1;
  2778. format = -1;
  2779. for(;;) {
  2780. switch(*p) {
  2781. case 'o':
  2782. case 'd':
  2783. case 'u':
  2784. case 'x':
  2785. case 'i':
  2786. case 'c':
  2787. format = *p++;
  2788. break;
  2789. case 'b':
  2790. size = 1;
  2791. p++;
  2792. break;
  2793. case 'h':
  2794. size = 2;
  2795. p++;
  2796. break;
  2797. case 'w':
  2798. size = 4;
  2799. p++;
  2800. break;
  2801. case 'g':
  2802. case 'L':
  2803. size = 8;
  2804. p++;
  2805. break;
  2806. default:
  2807. goto next;
  2808. }
  2809. }
  2810. next:
  2811. if (*p != '\0' && !qemu_isspace(*p)) {
  2812. monitor_printf(mon, "invalid char in format: '%c'\n",
  2813. *p);
  2814. goto fail;
  2815. }
  2816. if (format < 0)
  2817. format = default_fmt_format;
  2818. if (format != 'i') {
  2819. /* for 'i', not specifying a size gives -1 as size */
  2820. if (size < 0)
  2821. size = default_fmt_size;
  2822. default_fmt_size = size;
  2823. }
  2824. default_fmt_format = format;
  2825. } else {
  2826. count = 1;
  2827. format = default_fmt_format;
  2828. if (format != 'i') {
  2829. size = default_fmt_size;
  2830. } else {
  2831. size = -1;
  2832. }
  2833. }
  2834. qdict_put_int(qdict, "count", count);
  2835. qdict_put_int(qdict, "format", format);
  2836. qdict_put_int(qdict, "size", size);
  2837. }
  2838. break;
  2839. case 'i':
  2840. case 'l':
  2841. case 'M':
  2842. {
  2843. int64_t val;
  2844. while (qemu_isspace(*p))
  2845. p++;
  2846. if (*typestr == '?' || *typestr == '.') {
  2847. if (*typestr == '?') {
  2848. if (*p == '\0') {
  2849. typestr++;
  2850. break;
  2851. }
  2852. } else {
  2853. if (*p == '.') {
  2854. p++;
  2855. while (qemu_isspace(*p))
  2856. p++;
  2857. } else {
  2858. typestr++;
  2859. break;
  2860. }
  2861. }
  2862. typestr++;
  2863. }
  2864. if (get_expr(mon, &val, &p))
  2865. goto fail;
  2866. /* Check if 'i' is greater than 32-bit */
  2867. if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
  2868. monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
  2869. monitor_printf(mon, "integer is for 32-bit values\n");
  2870. goto fail;
  2871. } else if (c == 'M') {
  2872. if (val < 0) {
  2873. monitor_printf(mon, "enter a positive value\n");
  2874. goto fail;
  2875. }
  2876. val *= MiB;
  2877. }
  2878. qdict_put_int(qdict, key, val);
  2879. }
  2880. break;
  2881. case 'o':
  2882. {
  2883. int ret;
  2884. uint64_t val;
  2885. const char *end;
  2886. while (qemu_isspace(*p)) {
  2887. p++;
  2888. }
  2889. if (*typestr == '?') {
  2890. typestr++;
  2891. if (*p == '\0') {
  2892. break;
  2893. }
  2894. }
  2895. ret = qemu_strtosz_MiB(p, &end, &val);
  2896. if (ret < 0 || val > INT64_MAX) {
  2897. monitor_printf(mon, "invalid size\n");
  2898. goto fail;
  2899. }
  2900. qdict_put_int(qdict, key, val);
  2901. p = end;
  2902. }
  2903. break;
  2904. case 'T':
  2905. {
  2906. double val;
  2907. while (qemu_isspace(*p))
  2908. p++;
  2909. if (*typestr == '?') {
  2910. typestr++;
  2911. if (*p == '\0') {
  2912. break;
  2913. }
  2914. }
  2915. if (get_double(mon, &val, &p) < 0) {
  2916. goto fail;
  2917. }
  2918. if (p[0] && p[1] == 's') {
  2919. switch (*p) {
  2920. case 'm':
  2921. val /= 1e3; p += 2; break;
  2922. case 'u':
  2923. val /= 1e6; p += 2; break;
  2924. case 'n':
  2925. val /= 1e9; p += 2; break;
  2926. }
  2927. }
  2928. if (*p && !qemu_isspace(*p)) {
  2929. monitor_printf(mon, "Unknown unit suffix\n");
  2930. goto fail;
  2931. }
  2932. qdict_put(qdict, key, qnum_from_double(val));
  2933. }
  2934. break;
  2935. case 'b':
  2936. {
  2937. const char *beg;
  2938. bool val;
  2939. while (qemu_isspace(*p)) {
  2940. p++;
  2941. }
  2942. beg = p;
  2943. while (qemu_isgraph(*p)) {
  2944. p++;
  2945. }
  2946. if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
  2947. val = true;
  2948. } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
  2949. val = false;
  2950. } else {
  2951. monitor_printf(mon, "Expected 'on' or 'off'\n");
  2952. goto fail;
  2953. }
  2954. qdict_put_bool(qdict, key, val);
  2955. }
  2956. break;
  2957. case '-':
  2958. {
  2959. const char *tmp = p;
  2960. int skip_key = 0;
  2961. /* option */
  2962. c = *typestr++;
  2963. if (c == '\0')
  2964. goto bad_type;
  2965. while (qemu_isspace(*p))
  2966. p++;
  2967. if (*p == '-') {
  2968. p++;
  2969. if(c != *p) {
  2970. if(!is_valid_option(p, typestr)) {
  2971. monitor_printf(mon, "%s: unsupported option -%c\n",
  2972. cmd->name, *p);
  2973. goto fail;
  2974. } else {
  2975. skip_key = 1;
  2976. }
  2977. }
  2978. if(skip_key) {
  2979. p = tmp;
  2980. } else {
  2981. /* has option */
  2982. p++;
  2983. qdict_put_bool(qdict, key, true);
  2984. }
  2985. }
  2986. }
  2987. break;
  2988. case 'S':
  2989. {
  2990. /* package all remaining string */
  2991. int len;
  2992. while (qemu_isspace(*p)) {
  2993. p++;
  2994. }
  2995. if (*typestr == '?') {
  2996. typestr++;
  2997. if (*p == '\0') {
  2998. /* no remaining string: NULL argument */
  2999. break;
  3000. }
  3001. }
  3002. len = strlen(p);
  3003. if (len <= 0) {
  3004. monitor_printf(mon, "%s: string expected\n",
  3005. cmd->name);
  3006. goto fail;
  3007. }
  3008. qdict_put_str(qdict, key, p);
  3009. p += len;
  3010. }
  3011. break;
  3012. default:
  3013. bad_type:
  3014. monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
  3015. goto fail;
  3016. }
  3017. g_free(key);
  3018. key = NULL;
  3019. }
  3020. /* check that all arguments were parsed */
  3021. while (qemu_isspace(*p))
  3022. p++;
  3023. if (*p != '\0') {
  3024. monitor_printf(mon, "%s: extraneous characters at the end of line\n",
  3025. cmd->name);
  3026. goto fail;
  3027. }
  3028. return qdict;
  3029. fail:
  3030. qobject_unref(qdict);
  3031. g_free(key);
  3032. return NULL;
  3033. }
  3034. static void handle_hmp_command(Monitor *mon, const char *cmdline)
  3035. {
  3036. QDict *qdict;
  3037. const mon_cmd_t *cmd;
  3038. const char *cmd_start = cmdline;
  3039. trace_handle_hmp_command(mon, cmdline);
  3040. cmd = monitor_parse_command(mon, cmdline, &cmdline, mon->cmd_table);
  3041. if (!cmd) {
  3042. return;
  3043. }
  3044. qdict = monitor_parse_arguments(mon, &cmdline, cmd);
  3045. if (!qdict) {
  3046. while (cmdline > cmd_start && qemu_isspace(cmdline[-1])) {
  3047. cmdline--;
  3048. }
  3049. monitor_printf(mon, "Try \"help %.*s\" for more information\n",
  3050. (int)(cmdline - cmd_start), cmd_start);
  3051. return;
  3052. }
  3053. cmd->cmd(mon, qdict);
  3054. qobject_unref(qdict);
  3055. }
  3056. static void cmd_completion(Monitor *mon, const char *name, const char *list)
  3057. {
  3058. const char *p, *pstart;
  3059. char cmd[128];
  3060. int len;
  3061. p = list;
  3062. for(;;) {
  3063. pstart = p;
  3064. p = qemu_strchrnul(p, '|');
  3065. len = p - pstart;
  3066. if (len > sizeof(cmd) - 2)
  3067. len = sizeof(cmd) - 2;
  3068. memcpy(cmd, pstart, len);
  3069. cmd[len] = '\0';
  3070. if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
  3071. readline_add_completion(mon->rs, cmd);
  3072. }
  3073. if (*p == '\0')
  3074. break;
  3075. p++;
  3076. }
  3077. }
  3078. static void file_completion(Monitor *mon, const char *input)
  3079. {
  3080. DIR *ffs;
  3081. struct dirent *d;
  3082. char path[1024];
  3083. char file[1024], file_prefix[1024];
  3084. int input_path_len;
  3085. const char *p;
  3086. p = strrchr(input, '/');
  3087. if (!p) {
  3088. input_path_len = 0;
  3089. pstrcpy(file_prefix, sizeof(file_prefix), input);
  3090. pstrcpy(path, sizeof(path), ".");
  3091. } else {
  3092. input_path_len = p - input + 1;
  3093. memcpy(path, input, input_path_len);
  3094. if (input_path_len > sizeof(path) - 1)
  3095. input_path_len = sizeof(path) - 1;
  3096. path[input_path_len] = '\0';
  3097. pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
  3098. }
  3099. ffs = opendir(path);
  3100. if (!ffs)
  3101. return;
  3102. for(;;) {
  3103. struct stat sb;
  3104. d = readdir(ffs);
  3105. if (!d)
  3106. break;
  3107. if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
  3108. continue;
  3109. }
  3110. if (strstart(d->d_name, file_prefix, NULL)) {
  3111. memcpy(file, input, input_path_len);
  3112. if (input_path_len < sizeof(file))
  3113. pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
  3114. d->d_name);
  3115. /* stat the file to find out if it's a directory.
  3116. * In that case add a slash to speed up typing long paths
  3117. */
  3118. if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
  3119. pstrcat(file, sizeof(file), "/");
  3120. }
  3121. readline_add_completion(mon->rs, file);
  3122. }
  3123. }
  3124. closedir(ffs);
  3125. }
  3126. static const char *next_arg_type(const char *typestr)
  3127. {
  3128. const char *p = strchr(typestr, ':');
  3129. return (p != NULL ? ++p : typestr);
  3130. }
  3131. static void add_completion_option(ReadLineState *rs, const char *str,
  3132. const char *option)
  3133. {
  3134. if (!str || !option) {
  3135. return;
  3136. }
  3137. if (!strncmp(option, str, strlen(str))) {
  3138. readline_add_completion(rs, option);
  3139. }
  3140. }
  3141. void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
  3142. {
  3143. size_t len;
  3144. ChardevBackendInfoList *list, *start;
  3145. if (nb_args != 2) {
  3146. return;
  3147. }
  3148. len = strlen(str);
  3149. readline_set_completion_index(rs, len);
  3150. start = list = qmp_query_chardev_backends(NULL);
  3151. while (list) {
  3152. const char *chr_name = list->value->name;
  3153. if (!strncmp(chr_name, str, len)) {
  3154. readline_add_completion(rs, chr_name);
  3155. }
  3156. list = list->next;
  3157. }
  3158. qapi_free_ChardevBackendInfoList(start);
  3159. }
  3160. void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
  3161. {
  3162. size_t len;
  3163. int i;
  3164. if (nb_args != 2) {
  3165. return;
  3166. }
  3167. len = strlen(str);
  3168. readline_set_completion_index(rs, len);
  3169. for (i = 0; i < NET_CLIENT_DRIVER__MAX; i++) {
  3170. add_completion_option(rs, str, NetClientDriver_str(i));
  3171. }
  3172. }
  3173. void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
  3174. {
  3175. GSList *list, *elt;
  3176. size_t len;
  3177. if (nb_args != 2) {
  3178. return;
  3179. }
  3180. len = strlen(str);
  3181. readline_set_completion_index(rs, len);
  3182. list = elt = object_class_get_list(TYPE_DEVICE, false);
  3183. while (elt) {
  3184. const char *name;
  3185. DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
  3186. TYPE_DEVICE);
  3187. name = object_class_get_name(OBJECT_CLASS(dc));
  3188. if (dc->user_creatable
  3189. && !strncmp(name, str, len)) {
  3190. readline_add_completion(rs, name);
  3191. }
  3192. elt = elt->next;
  3193. }
  3194. g_slist_free(list);
  3195. }
  3196. void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
  3197. {
  3198. GSList *list, *elt;
  3199. size_t len;
  3200. if (nb_args != 2) {
  3201. return;
  3202. }
  3203. len = strlen(str);
  3204. readline_set_completion_index(rs, len);
  3205. list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
  3206. while (elt) {
  3207. const char *name;
  3208. name = object_class_get_name(OBJECT_CLASS(elt->data));
  3209. if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
  3210. readline_add_completion(rs, name);
  3211. }
  3212. elt = elt->next;
  3213. }
  3214. g_slist_free(list);
  3215. }
  3216. static void peripheral_device_del_completion(ReadLineState *rs,
  3217. const char *str, size_t len)
  3218. {
  3219. Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
  3220. GSList *list, *item;
  3221. list = qdev_build_hotpluggable_device_list(peripheral);
  3222. if (!list) {
  3223. return;
  3224. }
  3225. for (item = list; item; item = g_slist_next(item)) {
  3226. DeviceState *dev = item->data;
  3227. if (dev->id && !strncmp(str, dev->id, len)) {
  3228. readline_add_completion(rs, dev->id);
  3229. }
  3230. }
  3231. g_slist_free(list);
  3232. }
  3233. void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
  3234. {
  3235. size_t len;
  3236. ChardevInfoList *list, *start;
  3237. if (nb_args != 2) {
  3238. return;
  3239. }
  3240. len = strlen(str);
  3241. readline_set_completion_index(rs, len);
  3242. start = list = qmp_query_chardev(NULL);
  3243. while (list) {
  3244. ChardevInfo *chr = list->value;
  3245. if (!strncmp(chr->label, str, len)) {
  3246. readline_add_completion(rs, chr->label);
  3247. }
  3248. list = list->next;
  3249. }
  3250. qapi_free_ChardevInfoList(start);
  3251. }
  3252. static void ringbuf_completion(ReadLineState *rs, const char *str)
  3253. {
  3254. size_t len;
  3255. ChardevInfoList *list, *start;
  3256. len = strlen(str);
  3257. readline_set_completion_index(rs, len);
  3258. start = list = qmp_query_chardev(NULL);
  3259. while (list) {
  3260. ChardevInfo *chr_info = list->value;
  3261. if (!strncmp(chr_info->label, str, len)) {
  3262. Chardev *chr = qemu_chr_find(chr_info->label);
  3263. if (chr && CHARDEV_IS_RINGBUF(chr)) {
  3264. readline_add_completion(rs, chr_info->label);
  3265. }
  3266. }
  3267. list = list->next;
  3268. }
  3269. qapi_free_ChardevInfoList(start);
  3270. }
  3271. void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
  3272. {
  3273. if (nb_args != 2) {
  3274. return;
  3275. }
  3276. ringbuf_completion(rs, str);
  3277. }
  3278. void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
  3279. {
  3280. size_t len;
  3281. if (nb_args != 2) {
  3282. return;
  3283. }
  3284. len = strlen(str);
  3285. readline_set_completion_index(rs, len);
  3286. peripheral_device_del_completion(rs, str, len);
  3287. }
  3288. void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
  3289. {
  3290. ObjectPropertyInfoList *list, *start;
  3291. size_t len;
  3292. if (nb_args != 2) {
  3293. return;
  3294. }
  3295. len = strlen(str);
  3296. readline_set_completion_index(rs, len);
  3297. start = list = qmp_qom_list("/objects", NULL);
  3298. while (list) {
  3299. ObjectPropertyInfo *info = list->value;
  3300. if (!strncmp(info->type, "child<", 5)
  3301. && !strncmp(info->name, str, len)) {
  3302. readline_add_completion(rs, info->name);
  3303. }
  3304. list = list->next;
  3305. }
  3306. qapi_free_ObjectPropertyInfoList(start);
  3307. }
  3308. void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
  3309. {
  3310. int i;
  3311. char *sep;
  3312. size_t len;
  3313. if (nb_args != 2) {
  3314. return;
  3315. }
  3316. sep = strrchr(str, '-');
  3317. if (sep) {
  3318. str = sep + 1;
  3319. }
  3320. len = strlen(str);
  3321. readline_set_completion_index(rs, len);
  3322. for (i = 0; i < Q_KEY_CODE__MAX; i++) {
  3323. if (!strncmp(str, QKeyCode_str(i), len)) {
  3324. readline_add_completion(rs, QKeyCode_str(i));
  3325. }
  3326. }
  3327. }
  3328. void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
  3329. {
  3330. size_t len;
  3331. len = strlen(str);
  3332. readline_set_completion_index(rs, len);
  3333. if (nb_args == 2) {
  3334. NetClientState *ncs[MAX_QUEUE_NUM];
  3335. int count, i;
  3336. count = qemu_find_net_clients_except(NULL, ncs,
  3337. NET_CLIENT_DRIVER_NONE,
  3338. MAX_QUEUE_NUM);
  3339. for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
  3340. const char *name = ncs[i]->name;
  3341. if (!strncmp(str, name, len)) {
  3342. readline_add_completion(rs, name);
  3343. }
  3344. }
  3345. } else if (nb_args == 3) {
  3346. add_completion_option(rs, str, "on");
  3347. add_completion_option(rs, str, "off");
  3348. }
  3349. }
  3350. void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
  3351. {
  3352. int len, count, i;
  3353. NetClientState *ncs[MAX_QUEUE_NUM];
  3354. if (nb_args != 2) {
  3355. return;
  3356. }
  3357. len = strlen(str);
  3358. readline_set_completion_index(rs, len);
  3359. count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
  3360. MAX_QUEUE_NUM);
  3361. for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
  3362. QemuOpts *opts;
  3363. const char *name = ncs[i]->name;
  3364. if (strncmp(str, name, len)) {
  3365. continue;
  3366. }
  3367. opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
  3368. if (opts) {
  3369. readline_add_completion(rs, name);
  3370. }
  3371. }
  3372. }
  3373. void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
  3374. {
  3375. size_t len;
  3376. len = strlen(str);
  3377. readline_set_completion_index(rs, len);
  3378. if (nb_args == 2) {
  3379. TraceEventIter iter;
  3380. TraceEvent *ev;
  3381. char *pattern = g_strdup_printf("%s*", str);
  3382. trace_event_iter_init(&iter, pattern);
  3383. while ((ev = trace_event_iter_next(&iter)) != NULL) {
  3384. readline_add_completion(rs, trace_event_get_name(ev));
  3385. }
  3386. g_free(pattern);
  3387. }
  3388. }
  3389. void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
  3390. {
  3391. size_t len;
  3392. len = strlen(str);
  3393. readline_set_completion_index(rs, len);
  3394. if (nb_args == 2) {
  3395. TraceEventIter iter;
  3396. TraceEvent *ev;
  3397. char *pattern = g_strdup_printf("%s*", str);
  3398. trace_event_iter_init(&iter, pattern);
  3399. while ((ev = trace_event_iter_next(&iter)) != NULL) {
  3400. readline_add_completion(rs, trace_event_get_name(ev));
  3401. }
  3402. g_free(pattern);
  3403. } else if (nb_args == 3) {
  3404. add_completion_option(rs, str, "on");
  3405. add_completion_option(rs, str, "off");
  3406. }
  3407. }
  3408. void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
  3409. {
  3410. int i;
  3411. if (nb_args != 2) {
  3412. return;
  3413. }
  3414. readline_set_completion_index(rs, strlen(str));
  3415. for (i = 0; i < WATCHDOG_ACTION__MAX; i++) {
  3416. add_completion_option(rs, str, WatchdogAction_str(i));
  3417. }
  3418. }
  3419. void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
  3420. const char *str)
  3421. {
  3422. size_t len;
  3423. len = strlen(str);
  3424. readline_set_completion_index(rs, len);
  3425. if (nb_args == 2) {
  3426. int i;
  3427. for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
  3428. const char *name = MigrationCapability_str(i);
  3429. if (!strncmp(str, name, len)) {
  3430. readline_add_completion(rs, name);
  3431. }
  3432. }
  3433. } else if (nb_args == 3) {
  3434. add_completion_option(rs, str, "on");
  3435. add_completion_option(rs, str, "off");
  3436. }
  3437. }
  3438. void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
  3439. const char *str)
  3440. {
  3441. size_t len;
  3442. len = strlen(str);
  3443. readline_set_completion_index(rs, len);
  3444. if (nb_args == 2) {
  3445. int i;
  3446. for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
  3447. const char *name = MigrationParameter_str(i);
  3448. if (!strncmp(str, name, len)) {
  3449. readline_add_completion(rs, name);
  3450. }
  3451. }
  3452. }
  3453. }
  3454. static void vm_completion(ReadLineState *rs, const char *str)
  3455. {
  3456. size_t len;
  3457. BlockDriverState *bs;
  3458. BdrvNextIterator it;
  3459. len = strlen(str);
  3460. readline_set_completion_index(rs, len);
  3461. for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
  3462. SnapshotInfoList *snapshots, *snapshot;
  3463. AioContext *ctx = bdrv_get_aio_context(bs);
  3464. bool ok = false;
  3465. aio_context_acquire(ctx);
  3466. if (bdrv_can_snapshot(bs)) {
  3467. ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
  3468. }
  3469. aio_context_release(ctx);
  3470. if (!ok) {
  3471. continue;
  3472. }
  3473. snapshot = snapshots;
  3474. while (snapshot) {
  3475. char *completion = snapshot->value->name;
  3476. if (!strncmp(str, completion, len)) {
  3477. readline_add_completion(rs, completion);
  3478. }
  3479. completion = snapshot->value->id;
  3480. if (!strncmp(str, completion, len)) {
  3481. readline_add_completion(rs, completion);
  3482. }
  3483. snapshot = snapshot->next;
  3484. }
  3485. qapi_free_SnapshotInfoList(snapshots);
  3486. }
  3487. }
  3488. void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
  3489. {
  3490. if (nb_args == 2) {
  3491. vm_completion(rs, str);
  3492. }
  3493. }
  3494. void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
  3495. {
  3496. if (nb_args == 2) {
  3497. vm_completion(rs, str);
  3498. }
  3499. }
  3500. static void monitor_find_completion_by_table(Monitor *mon,
  3501. const mon_cmd_t *cmd_table,
  3502. char **args,
  3503. int nb_args)
  3504. {
  3505. const char *cmdname;
  3506. int i;
  3507. const char *ptype, *old_ptype, *str, *name;
  3508. const mon_cmd_t *cmd;
  3509. BlockBackend *blk = NULL;
  3510. if (nb_args <= 1) {
  3511. /* command completion */
  3512. if (nb_args == 0)
  3513. cmdname = "";
  3514. else
  3515. cmdname = args[0];
  3516. readline_set_completion_index(mon->rs, strlen(cmdname));
  3517. for (cmd = cmd_table; cmd->name != NULL; cmd++) {
  3518. if (!runstate_check(RUN_STATE_PRECONFIG) ||
  3519. cmd_can_preconfig(cmd)) {
  3520. cmd_completion(mon, cmdname, cmd->name);
  3521. }
  3522. }
  3523. } else {
  3524. /* find the command */
  3525. for (cmd = cmd_table; cmd->name != NULL; cmd++) {
  3526. if (compare_cmd(args[0], cmd->name) &&
  3527. (!runstate_check(RUN_STATE_PRECONFIG) ||
  3528. cmd_can_preconfig(cmd))) {
  3529. break;
  3530. }
  3531. }
  3532. if (!cmd->name) {
  3533. return;
  3534. }
  3535. if (cmd->sub_table) {
  3536. /* do the job again */
  3537. monitor_find_completion_by_table(mon, cmd->sub_table,
  3538. &args[1], nb_args - 1);
  3539. return;
  3540. }
  3541. if (cmd->command_completion) {
  3542. cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
  3543. return;
  3544. }
  3545. ptype = next_arg_type(cmd->args_type);
  3546. for(i = 0; i < nb_args - 2; i++) {
  3547. if (*ptype != '\0') {
  3548. ptype = next_arg_type(ptype);
  3549. while (*ptype == '?')
  3550. ptype = next_arg_type(ptype);
  3551. }
  3552. }
  3553. str = args[nb_args - 1];
  3554. old_ptype = NULL;
  3555. while (*ptype == '-' && old_ptype != ptype) {
  3556. old_ptype = ptype;
  3557. ptype = next_arg_type(ptype);
  3558. }
  3559. switch(*ptype) {
  3560. case 'F':
  3561. /* file completion */
  3562. readline_set_completion_index(mon->rs, strlen(str));
  3563. file_completion(mon, str);
  3564. break;
  3565. case 'B':
  3566. /* block device name completion */
  3567. readline_set_completion_index(mon->rs, strlen(str));
  3568. while ((blk = blk_next(blk)) != NULL) {
  3569. name = blk_name(blk);
  3570. if (str[0] == '\0' ||
  3571. !strncmp(name, str, strlen(str))) {
  3572. readline_add_completion(mon->rs, name);
  3573. }
  3574. }
  3575. break;
  3576. case 's':
  3577. case 'S':
  3578. if (!strcmp(cmd->name, "help|?")) {
  3579. monitor_find_completion_by_table(mon, cmd_table,
  3580. &args[1], nb_args - 1);
  3581. }
  3582. break;
  3583. default:
  3584. break;
  3585. }
  3586. }
  3587. }
  3588. static void monitor_find_completion(void *opaque,
  3589. const char *cmdline)
  3590. {
  3591. Monitor *mon = opaque;
  3592. char *args[MAX_ARGS];
  3593. int nb_args, len;
  3594. /* 1. parse the cmdline */
  3595. if (parse_cmdline(cmdline, &nb_args, args) < 0) {
  3596. return;
  3597. }
  3598. /* if the line ends with a space, it means we want to complete the
  3599. next arg */
  3600. len = strlen(cmdline);
  3601. if (len > 0 && qemu_isspace(cmdline[len - 1])) {
  3602. if (nb_args >= MAX_ARGS) {
  3603. goto cleanup;
  3604. }
  3605. args[nb_args++] = g_strdup("");
  3606. }
  3607. /* 2. auto complete according to args */
  3608. monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
  3609. cleanup:
  3610. free_cmdline_args(args, nb_args);
  3611. }
  3612. static int monitor_can_read(void *opaque)
  3613. {
  3614. Monitor *mon = opaque;
  3615. return !atomic_mb_read(&mon->suspend_cnt);
  3616. }
  3617. /*
  3618. * Emit QMP response @rsp with ID @id to @mon.
  3619. * Null @rsp can only happen for commands with QCO_NO_SUCCESS_RESP.
  3620. * Nothing is emitted then.
  3621. */
  3622. static void monitor_qmp_respond(Monitor *mon, QDict *rsp)
  3623. {
  3624. if (rsp) {
  3625. qmp_send_response(mon, rsp);
  3626. }
  3627. }
  3628. static void monitor_qmp_dispatch(Monitor *mon, QObject *req)
  3629. {
  3630. Monitor *old_mon;
  3631. QDict *rsp;
  3632. QDict *error;
  3633. old_mon = cur_mon;
  3634. cur_mon = mon;
  3635. rsp = qmp_dispatch(mon->qmp.commands, req, qmp_oob_enabled(mon));
  3636. cur_mon = old_mon;
  3637. if (mon->qmp.commands == &qmp_cap_negotiation_commands) {
  3638. error = qdict_get_qdict(rsp, "error");
  3639. if (error
  3640. && !g_strcmp0(qdict_get_try_str(error, "class"),
  3641. QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
  3642. /* Provide a more useful error message */
  3643. qdict_del(error, "desc");
  3644. qdict_put_str(error, "desc", "Expecting capabilities negotiation"
  3645. " with 'qmp_capabilities'");
  3646. }
  3647. }
  3648. monitor_qmp_respond(mon, rsp);
  3649. qobject_unref(rsp);
  3650. }
  3651. /*
  3652. * Pop a QMP request from a monitor request queue.
  3653. * Return the request, or NULL all request queues are empty.
  3654. * We are using round-robin fashion to pop the request, to avoid
  3655. * processing commands only on a very busy monitor. To achieve that,
  3656. * when we process one request on a specific monitor, we put that
  3657. * monitor to the end of mon_list queue.
  3658. *
  3659. * Note: if the function returned with non-NULL, then the caller will
  3660. * be with mon->qmp.qmp_queue_lock held, and the caller is responsible
  3661. * to release it.
  3662. */
  3663. static QMPRequest *monitor_qmp_requests_pop_any_with_lock(void)
  3664. {
  3665. QMPRequest *req_obj = NULL;
  3666. Monitor *mon;
  3667. qemu_mutex_lock(&monitor_lock);
  3668. QTAILQ_FOREACH(mon, &mon_list, entry) {
  3669. qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
  3670. req_obj = g_queue_pop_head(mon->qmp.qmp_requests);
  3671. if (req_obj) {
  3672. /* With the lock of corresponding queue held */
  3673. break;
  3674. }
  3675. qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
  3676. }
  3677. if (req_obj) {
  3678. /*
  3679. * We found one request on the monitor. Degrade this monitor's
  3680. * priority to lowest by re-inserting it to end of queue.
  3681. */
  3682. QTAILQ_REMOVE(&mon_list, mon, entry);
  3683. QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
  3684. }
  3685. qemu_mutex_unlock(&monitor_lock);
  3686. return req_obj;
  3687. }
  3688. static void monitor_qmp_bh_dispatcher(void *data)
  3689. {
  3690. QMPRequest *req_obj = monitor_qmp_requests_pop_any_with_lock();
  3691. QDict *rsp;
  3692. bool need_resume;
  3693. Monitor *mon;
  3694. if (!req_obj) {
  3695. return;
  3696. }
  3697. mon = req_obj->mon;
  3698. /* qmp_oob_enabled() might change after "qmp_capabilities" */
  3699. need_resume = !qmp_oob_enabled(mon) ||
  3700. mon->qmp.qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1;
  3701. qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
  3702. if (req_obj->req) {
  3703. QDict *qdict = qobject_to(QDict, req_obj->req);
  3704. QObject *id = qdict ? qdict_get(qdict, "id") : NULL;
  3705. trace_monitor_qmp_cmd_in_band(qobject_get_try_str(id) ?: "");
  3706. monitor_qmp_dispatch(mon, req_obj->req);
  3707. } else {
  3708. assert(req_obj->err);
  3709. rsp = qmp_error_response(req_obj->err);
  3710. req_obj->err = NULL;
  3711. monitor_qmp_respond(mon, rsp);
  3712. qobject_unref(rsp);
  3713. }
  3714. if (need_resume) {
  3715. /* Pairs with the monitor_suspend() in handle_qmp_command() */
  3716. monitor_resume(mon);
  3717. }
  3718. qmp_request_free(req_obj);
  3719. /* Reschedule instead of looping so the main loop stays responsive */
  3720. qemu_bh_schedule(qmp_dispatcher_bh);
  3721. }
  3722. static void handle_qmp_command(void *opaque, QObject *req, Error *err)
  3723. {
  3724. Monitor *mon = opaque;
  3725. QObject *id = NULL;
  3726. QDict *qdict;
  3727. QMPRequest *req_obj;
  3728. assert(!req != !err);
  3729. qdict = qobject_to(QDict, req);
  3730. if (qdict) {
  3731. id = qdict_get(qdict, "id");
  3732. } /* else will fail qmp_dispatch() */
  3733. if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
  3734. QString *req_json = qobject_to_json(req);
  3735. trace_handle_qmp_command(mon, qstring_get_str(req_json));
  3736. qobject_unref(req_json);
  3737. }
  3738. if (qdict && qmp_is_oob(qdict)) {
  3739. /* OOB commands are executed immediately */
  3740. trace_monitor_qmp_cmd_out_of_band(qobject_get_try_str(id) ?: "");
  3741. monitor_qmp_dispatch(mon, req);
  3742. qobject_unref(req);
  3743. return;
  3744. }
  3745. req_obj = g_new0(QMPRequest, 1);
  3746. req_obj->mon = mon;
  3747. req_obj->req = req;
  3748. req_obj->err = err;
  3749. /* Protect qmp_requests and fetching its length. */
  3750. qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
  3751. /*
  3752. * Suspend the monitor when we can't queue more requests after
  3753. * this one. Dequeuing in monitor_qmp_bh_dispatcher() will resume
  3754. * it. Note that when OOB is disabled, we queue at most one
  3755. * command, for backward compatibility.
  3756. */
  3757. if (!qmp_oob_enabled(mon) ||
  3758. mon->qmp.qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
  3759. monitor_suspend(mon);
  3760. }
  3761. /*
  3762. * Put the request to the end of queue so that requests will be
  3763. * handled in time order. Ownership for req_obj, req,
  3764. * etc. will be delivered to the handler side.
  3765. */
  3766. assert(mon->qmp.qmp_requests->length < QMP_REQ_QUEUE_LEN_MAX);
  3767. g_queue_push_tail(mon->qmp.qmp_requests, req_obj);
  3768. qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
  3769. /* Kick the dispatcher routine */
  3770. qemu_bh_schedule(qmp_dispatcher_bh);
  3771. }
  3772. static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
  3773. {
  3774. Monitor *mon = opaque;
  3775. json_message_parser_feed(&mon->qmp.parser, (const char *) buf, size);
  3776. }
  3777. static void monitor_read(void *opaque, const uint8_t *buf, int size)
  3778. {
  3779. Monitor *old_mon = cur_mon;
  3780. int i;
  3781. cur_mon = opaque;
  3782. if (cur_mon->rs) {
  3783. for (i = 0; i < size; i++)
  3784. readline_handle_byte(cur_mon->rs, buf[i]);
  3785. } else {
  3786. if (size == 0 || buf[size - 1] != 0)
  3787. monitor_printf(cur_mon, "corrupted command\n");
  3788. else
  3789. handle_hmp_command(cur_mon, (char *)buf);
  3790. }
  3791. cur_mon = old_mon;
  3792. }
  3793. static void monitor_command_cb(void *opaque, const char *cmdline,
  3794. void *readline_opaque)
  3795. {
  3796. Monitor *mon = opaque;
  3797. monitor_suspend(mon);
  3798. handle_hmp_command(mon, cmdline);
  3799. monitor_resume(mon);
  3800. }
  3801. int monitor_suspend(Monitor *mon)
  3802. {
  3803. if (monitor_is_hmp_non_interactive(mon)) {
  3804. return -ENOTTY;
  3805. }
  3806. atomic_inc(&mon->suspend_cnt);
  3807. if (mon->use_io_thread) {
  3808. /*
  3809. * Kick I/O thread to make sure this takes effect. It'll be
  3810. * evaluated again in prepare() of the watch object.
  3811. */
  3812. aio_notify(iothread_get_aio_context(mon_iothread));
  3813. }
  3814. trace_monitor_suspend(mon, 1);
  3815. return 0;
  3816. }
  3817. static void monitor_accept_input(void *opaque)
  3818. {
  3819. Monitor *mon = opaque;
  3820. qemu_chr_fe_accept_input(&mon->chr);
  3821. }
  3822. void monitor_resume(Monitor *mon)
  3823. {
  3824. if (monitor_is_hmp_non_interactive(mon)) {
  3825. return;
  3826. }
  3827. if (atomic_dec_fetch(&mon->suspend_cnt) == 0) {
  3828. AioContext *ctx;
  3829. if (mon->use_io_thread) {
  3830. ctx = iothread_get_aio_context(mon_iothread);
  3831. } else {
  3832. ctx = qemu_get_aio_context();
  3833. }
  3834. if (!monitor_is_qmp(mon)) {
  3835. assert(mon->rs);
  3836. readline_show_prompt(mon->rs);
  3837. }
  3838. aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon);
  3839. }
  3840. trace_monitor_suspend(mon, -1);
  3841. }
  3842. static QDict *qmp_greeting(Monitor *mon)
  3843. {
  3844. QList *cap_list = qlist_new();
  3845. QObject *ver = NULL;
  3846. QMPCapability cap;
  3847. qmp_marshal_query_version(NULL, &ver, NULL);
  3848. for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
  3849. if (mon->qmp.capab_offered[cap]) {
  3850. qlist_append_str(cap_list, QMPCapability_str(cap));
  3851. }
  3852. }
  3853. return qdict_from_jsonf_nofail(
  3854. "{'QMP': {'version': %p, 'capabilities': %p}}",
  3855. ver, cap_list);
  3856. }
  3857. static void monitor_qmp_event(void *opaque, int event)
  3858. {
  3859. QDict *data;
  3860. Monitor *mon = opaque;
  3861. switch (event) {
  3862. case CHR_EVENT_OPENED:
  3863. mon->qmp.commands = &qmp_cap_negotiation_commands;
  3864. monitor_qmp_caps_reset(mon);
  3865. data = qmp_greeting(mon);
  3866. qmp_send_response(mon, data);
  3867. qobject_unref(data);
  3868. mon_refcount++;
  3869. break;
  3870. case CHR_EVENT_CLOSED:
  3871. /*
  3872. * Note: this is only useful when the output of the chardev
  3873. * backend is still open. For example, when the backend is
  3874. * stdio, it's possible that stdout is still open when stdin
  3875. * is closed.
  3876. */
  3877. monitor_qmp_cleanup_queues(mon);
  3878. json_message_parser_destroy(&mon->qmp.parser);
  3879. json_message_parser_init(&mon->qmp.parser, handle_qmp_command,
  3880. mon, NULL);
  3881. mon_refcount--;
  3882. monitor_fdsets_cleanup();
  3883. break;
  3884. }
  3885. }
  3886. static void monitor_event(void *opaque, int event)
  3887. {
  3888. Monitor *mon = opaque;
  3889. switch (event) {
  3890. case CHR_EVENT_MUX_IN:
  3891. qemu_mutex_lock(&mon->mon_lock);
  3892. mon->mux_out = 0;
  3893. qemu_mutex_unlock(&mon->mon_lock);
  3894. if (mon->reset_seen) {
  3895. readline_restart(mon->rs);
  3896. monitor_resume(mon);
  3897. monitor_flush(mon);
  3898. } else {
  3899. atomic_mb_set(&mon->suspend_cnt, 0);
  3900. }
  3901. break;
  3902. case CHR_EVENT_MUX_OUT:
  3903. if (mon->reset_seen) {
  3904. if (atomic_mb_read(&mon->suspend_cnt) == 0) {
  3905. monitor_printf(mon, "\n");
  3906. }
  3907. monitor_flush(mon);
  3908. monitor_suspend(mon);
  3909. } else {
  3910. atomic_inc(&mon->suspend_cnt);
  3911. }
  3912. qemu_mutex_lock(&mon->mon_lock);
  3913. mon->mux_out = 1;
  3914. qemu_mutex_unlock(&mon->mon_lock);
  3915. break;
  3916. case CHR_EVENT_OPENED:
  3917. monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
  3918. "information\n", QEMU_VERSION);
  3919. if (!mon->mux_out) {
  3920. readline_restart(mon->rs);
  3921. readline_show_prompt(mon->rs);
  3922. }
  3923. mon->reset_seen = 1;
  3924. mon_refcount++;
  3925. break;
  3926. case CHR_EVENT_CLOSED:
  3927. mon_refcount--;
  3928. monitor_fdsets_cleanup();
  3929. break;
  3930. }
  3931. }
  3932. static int
  3933. compare_mon_cmd(const void *a, const void *b)
  3934. {
  3935. return strcmp(((const mon_cmd_t *)a)->name,
  3936. ((const mon_cmd_t *)b)->name);
  3937. }
  3938. static void sortcmdlist(void)
  3939. {
  3940. int array_num;
  3941. int elem_size = sizeof(mon_cmd_t);
  3942. array_num = sizeof(mon_cmds)/elem_size-1;
  3943. qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
  3944. array_num = sizeof(info_cmds)/elem_size-1;
  3945. qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
  3946. }
  3947. static void monitor_iothread_init(void)
  3948. {
  3949. mon_iothread = iothread_create("mon_iothread", &error_abort);
  3950. }
  3951. void monitor_init_globals(void)
  3952. {
  3953. monitor_init_qmp_commands();
  3954. monitor_qapi_event_init();
  3955. sortcmdlist();
  3956. qemu_mutex_init(&monitor_lock);
  3957. qemu_mutex_init(&mon_fdsets_lock);
  3958. /*
  3959. * The dispatcher BH must run in the main loop thread, since we
  3960. * have commands assuming that context. It would be nice to get
  3961. * rid of those assumptions.
  3962. */
  3963. qmp_dispatcher_bh = aio_bh_new(iohandler_get_aio_context(),
  3964. monitor_qmp_bh_dispatcher,
  3965. NULL);
  3966. }
  3967. /* These functions just adapt the readline interface in a typesafe way. We
  3968. * could cast function pointers but that discards compiler checks.
  3969. */
  3970. static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
  3971. const char *fmt, ...)
  3972. {
  3973. va_list ap;
  3974. va_start(ap, fmt);
  3975. monitor_vprintf(opaque, fmt, ap);
  3976. va_end(ap);
  3977. }
  3978. static void monitor_readline_flush(void *opaque)
  3979. {
  3980. monitor_flush(opaque);
  3981. }
  3982. /*
  3983. * Print to current monitor if we have one, else to stderr.
  3984. */
  3985. int error_vprintf(const char *fmt, va_list ap)
  3986. {
  3987. if (cur_mon && !monitor_cur_is_qmp()) {
  3988. return monitor_vprintf(cur_mon, fmt, ap);
  3989. }
  3990. return vfprintf(stderr, fmt, ap);
  3991. }
  3992. int error_vprintf_unless_qmp(const char *fmt, va_list ap)
  3993. {
  3994. if (!cur_mon) {
  3995. return vfprintf(stderr, fmt, ap);
  3996. }
  3997. if (!monitor_cur_is_qmp()) {
  3998. return monitor_vprintf(cur_mon, fmt, ap);
  3999. }
  4000. return -1;
  4001. }
  4002. static void monitor_list_append(Monitor *mon)
  4003. {
  4004. qemu_mutex_lock(&monitor_lock);
  4005. /*
  4006. * This prevents inserting new monitors during monitor_cleanup().
  4007. * A cleaner solution would involve the main thread telling other
  4008. * threads to terminate, waiting for their termination.
  4009. */
  4010. if (!monitor_destroyed) {
  4011. QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
  4012. mon = NULL;
  4013. }
  4014. qemu_mutex_unlock(&monitor_lock);
  4015. if (mon) {
  4016. monitor_data_destroy(mon);
  4017. g_free(mon);
  4018. }
  4019. }
  4020. static void monitor_qmp_setup_handlers_bh(void *opaque)
  4021. {
  4022. Monitor *mon = opaque;
  4023. GMainContext *context;
  4024. assert(mon->use_io_thread);
  4025. context = iothread_get_g_main_context(mon_iothread);
  4026. assert(context);
  4027. qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
  4028. monitor_qmp_event, NULL, mon, context, true);
  4029. monitor_list_append(mon);
  4030. }
  4031. void monitor_init(Chardev *chr, int flags)
  4032. {
  4033. Monitor *mon = g_malloc(sizeof(*mon));
  4034. bool use_readline = flags & MONITOR_USE_READLINE;
  4035. /* Note: we run QMP monitor in I/O thread when @chr supports that */
  4036. monitor_data_init(mon, false,
  4037. (flags & MONITOR_USE_CONTROL)
  4038. && qemu_chr_has_feature(chr,
  4039. QEMU_CHAR_FEATURE_GCONTEXT));
  4040. qemu_chr_fe_init(&mon->chr, chr, &error_abort);
  4041. mon->flags = flags;
  4042. if (use_readline) {
  4043. mon->rs = readline_init(monitor_readline_printf,
  4044. monitor_readline_flush,
  4045. mon,
  4046. monitor_find_completion);
  4047. monitor_read_command(mon, 0);
  4048. }
  4049. if (monitor_is_qmp(mon)) {
  4050. qemu_chr_fe_set_echo(&mon->chr, true);
  4051. json_message_parser_init(&mon->qmp.parser, handle_qmp_command,
  4052. mon, NULL);
  4053. if (mon->use_io_thread) {
  4054. /*
  4055. * Make sure the old iowatch is gone. It's possible when
  4056. * e.g. the chardev is in client mode, with wait=on.
  4057. */
  4058. remove_fd_in_watch(chr);
  4059. /*
  4060. * We can't call qemu_chr_fe_set_handlers() directly here
  4061. * since chardev might be running in the monitor I/O
  4062. * thread. Schedule a bottom half.
  4063. */
  4064. aio_bh_schedule_oneshot(iothread_get_aio_context(mon_iothread),
  4065. monitor_qmp_setup_handlers_bh, mon);
  4066. /* The bottom half will add @mon to @mon_list */
  4067. return;
  4068. } else {
  4069. qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read,
  4070. monitor_qmp_read, monitor_qmp_event,
  4071. NULL, mon, NULL, true);
  4072. }
  4073. } else {
  4074. qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
  4075. monitor_event, NULL, mon, NULL, true);
  4076. }
  4077. monitor_list_append(mon);
  4078. }
  4079. void monitor_cleanup(void)
  4080. {
  4081. /*
  4082. * We need to explicitly stop the I/O thread (but not destroy it),
  4083. * clean up the monitor resources, then destroy the I/O thread since
  4084. * we need to unregister from chardev below in
  4085. * monitor_data_destroy(), and chardev is not thread-safe yet
  4086. */
  4087. if (mon_iothread) {
  4088. iothread_stop(mon_iothread);
  4089. }
  4090. /* Flush output buffers and destroy monitors */
  4091. qemu_mutex_lock(&monitor_lock);
  4092. monitor_destroyed = true;
  4093. while (!QTAILQ_EMPTY(&mon_list)) {
  4094. Monitor *mon = QTAILQ_FIRST(&mon_list);
  4095. QTAILQ_REMOVE(&mon_list, mon, entry);
  4096. /* Permit QAPI event emission from character frontend release */
  4097. qemu_mutex_unlock(&monitor_lock);
  4098. monitor_flush(mon);
  4099. monitor_data_destroy(mon);
  4100. qemu_mutex_lock(&monitor_lock);
  4101. g_free(mon);
  4102. }
  4103. qemu_mutex_unlock(&monitor_lock);
  4104. /* QEMUBHs needs to be deleted before destroying the I/O thread */
  4105. qemu_bh_delete(qmp_dispatcher_bh);
  4106. qmp_dispatcher_bh = NULL;
  4107. if (mon_iothread) {
  4108. iothread_destroy(mon_iothread);
  4109. mon_iothread = NULL;
  4110. }
  4111. }
  4112. QemuOptsList qemu_mon_opts = {
  4113. .name = "mon",
  4114. .implied_opt_name = "chardev",
  4115. .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
  4116. .desc = {
  4117. {
  4118. .name = "mode",
  4119. .type = QEMU_OPT_STRING,
  4120. },{
  4121. .name = "chardev",
  4122. .type = QEMU_OPT_STRING,
  4123. },{
  4124. .name = "pretty",
  4125. .type = QEMU_OPT_BOOL,
  4126. },
  4127. { /* end of list */ }
  4128. },
  4129. };
  4130. HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
  4131. {
  4132. MachineState *ms = MACHINE(qdev_get_machine());
  4133. MachineClass *mc = MACHINE_GET_CLASS(ms);
  4134. if (!mc->has_hotpluggable_cpus) {
  4135. error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
  4136. return NULL;
  4137. }
  4138. return machine_query_hotpluggable_cpus(ms);
  4139. }