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

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