llleap.cpp 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440
  1. /**
  2. * @file llleap.h
  3. * @brief Class implementation for LLeap, and its ancillary classes (LLProcess,
  4. * LLProcessListener, LLLeapListener).
  5. *
  6. * $LicenseInfo:firstyear=2010&license=viewergpl$
  7. *
  8. * Copyright (c) 2010-2022, Linden Research, Inc.
  9. *
  10. * Second Life Viewer Source Code
  11. * The source code in this file ("Source Code") is provided by Linden Lab
  12. * to you under the terms of the GNU General Public License, version 2.0
  13. * ("GPL"), unless you have obtained a separate licensing agreement
  14. * ("Other License"), formally executed by you and Linden Lab. Terms of
  15. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  16. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  17. *
  18. * There are special exceptions to the terms and conditions of the GPL as
  19. * it is applied to this Source Code. View the full text of the exception
  20. * in the file doc/FLOSS-exception.txt in this software distribution, or
  21. * online at
  22. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  23. *
  24. * By copying, modifying or distributing this software, you acknowledge
  25. * that you have read and understood your obligations described above,
  26. * and agree to abide by those obligations.
  27. *
  28. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  29. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  30. * COMPLETENESS OR PERFORMANCE.
  31. * $/LicenseInfo$
  32. */
  33. #include "linden_common.h"
  34. #include <algorithm>
  35. #include <iostream>
  36. #include <limits>
  37. #include <memory>
  38. #include <sstream>
  39. #include <utility>
  40. #include "apr_thread_proc.h"
  41. #include "apr_signal.h"
  42. #include "boost/asio/streambuf.hpp"
  43. #include "boost/asio/buffers_iterator.hpp"
  44. #include "boost/ptr_container/ptr_vector.hpp"
  45. #include "llleap.h"
  46. #include "llapr.h"
  47. #include "lleventdispatcher.h"
  48. #include "llsd.h"
  49. #include "llsdutil.h"
  50. #include "llsdserialize.h"
  51. #include "llstring.h"
  52. #include "lltimer.h"
  53. // 'this' used in initializer list: yes, intentionally
  54. #if LL_MSVC
  55. # pragma warning (disable : 4355)
  56. #endif
  57. ///////////////////////////////////////////////////////////////////////////////
  58. // LLProcess class. It is implemented in its own llprocess.h and llprocess.cpp
  59. // files in LL's viewer, but it is only used by LLLeap (we use the simpler and
  60. // APR-free LLProcessLauncher everywhere else in the Cool VL Viewer), so there
  61. // is no point in adding more files to the sources. HB
  62. ///////////////////////////////////////////////////////////////////////////////
  63. // Utility functions.
  64. static std::string get_desc(const LLSD& params)
  65. {
  66. std::string desc;
  67. if (params.has("desc"))
  68. {
  69. desc = params["desc"].asString();
  70. }
  71. // Do not leave desc empty and use the filename (and maybe full path) for
  72. // the executable.
  73. if (desc.empty())
  74. {
  75. desc = params["executable"].asString();
  76. }
  77. return desc;
  78. }
  79. static std::string whichfile(S32 index)
  80. {
  81. static const std::string stream_names[] =
  82. {
  83. "stdin", "stdout", "stderr"
  84. };
  85. if (index < 3)
  86. {
  87. return stream_names[index];
  88. }
  89. return llformat("file slot %d", index);
  90. }
  91. static std::string get_line_from_stream(std::istream& in)
  92. {
  93. std::string line;
  94. std::getline(in, line);
  95. // Blur the distinction between "\r\n" and plain "\n". std::getline() will
  96. // have eaten the "\n", but we could still end up with a trailing "\r".
  97. std::string::size_type lastpos = line.find_last_not_of("\r");
  98. if (lastpos != std::string::npos)
  99. {
  100. // Found at least one character that's not a trailing '\r'. SKIP OVER
  101. // IT and erase the rest of the line.
  102. line.erase(lastpos + 1);
  103. }
  104. return line;
  105. }
  106. // LLProcess handles launching an external process with specified command line
  107. // arguments. It also keeps track of whether the process is still running, and
  108. // can kill it if required.
  109. //
  110. // In discussing LLProcess, we use the term "parent" to refer to this process
  111. // (the process invoking LLProcess), versus "child" to refer to the process
  112. // spawned by LLProcess.
  113. //
  114. // LLProcess relies on periodic post() calls on the "mainloop" LLEventPump: an
  115. // LLProcess object's Status would not update until the next "mainloop" tick.
  116. // The viewer's main loop already posts to an LLEventPump by that name once per
  117. // iteration.
  118. class LLProcess final
  119. {
  120. protected:
  121. LOG_CLASS(LLProcess);
  122. public:
  123. typedef std::shared_ptr<LLProcess> ptr_t;
  124. // Non-copyable
  125. LLProcess(const LLProcess&) noexcept = delete;
  126. LLProcess& operator=(const LLProcess&) noexcept = delete;
  127. ~LLProcess();
  128. static ptr_t create(const LLSD& params);
  129. // State of child process
  130. enum state
  131. {
  132. UNSTARTED, // Initial value, invisible to consumer
  133. RUNNING, // Child process launched
  134. EXITED, // Child process terminated voluntarily
  135. KILLED // Child process terminated involuntarily
  136. };
  137. // Status info
  138. class Status
  139. {
  140. public:
  141. LL_INLINE Status()
  142. : mState(UNSTARTED),
  143. mData(0)
  144. {
  145. }
  146. static Status interpretStatus(int status);
  147. public:
  148. state mState;
  149. // For mState == EXITED: mData is exit() code
  150. // For mState == KILLED: mData is signal number (POSIX)
  151. // Otherwise: mData is undefined
  152. int mData;
  153. };
  154. // Status query
  155. LL_INLINE Status getStatus() const { return mStatus; }
  156. LL_INLINE static Status getStatus(const ptr_t& p)
  157. {
  158. // Note: default-constructed Status has mState == UNSTARTED
  159. return p ? p->mStatus : Status();
  160. }
  161. // Is child process still running ?
  162. LL_INLINE bool isRunning() const
  163. {
  164. return mStatus.mState == RUNNING;
  165. }
  166. LL_INLINE static bool isRunning(const ptr_t& p)
  167. {
  168. return p && p->isRunning();
  169. }
  170. // Plain text status string query, for logging etc.
  171. LL_INLINE std::string getStatusString() const
  172. {
  173. return getStatusString(mStatus);
  174. }
  175. LL_INLINE static std::string getStatusString(const std::string& desc,
  176. const ptr_t& p)
  177. {
  178. if (!p)
  179. {
  180. // Default-constructed Status has mState == UNSTARTED
  181. return getStatusString(desc, Status());
  182. }
  183. return desc + " " + p->getStatusString();
  184. }
  185. // Plain text status string query for previously-captured Status
  186. LL_INLINE std::string getStatusString(const Status& status) const
  187. {
  188. return getStatusString(mDesc, status);
  189. }
  190. // Plain text static status string query
  191. static std::string getStatusString(const std::string& desc,
  192. const Status& status);
  193. // Attempts to kill the process. Returns true if the process is no longer
  194. // running when it returns./ Note that even if this returns false, the
  195. // process may exit some time after it is called.
  196. bool kill(const std::string& who = LLStringUtil::null);
  197. LL_INLINE static bool kill(const ptr_t& p,
  198. const std::string& who = LLStringUtil::null)
  199. {
  200. return p && p->kill(who);
  201. }
  202. #if LL_WINDOWS
  203. typedef int id; // As returned by getProcessID()
  204. typedef HANDLE handle; // As returned by getProcessHandle()
  205. #else
  206. typedef pid_t id;
  207. typedef pid_t handle;
  208. #endif
  209. // Gets an int-like id value. This is primarily intended for a human reader
  210. // to differentiate processes.
  211. LL_INLINE id getProcessID() const
  212. {
  213. return mProcess.pid;
  214. }
  215. // Gets a "handle" of a kind that you might pass to platform-specific API
  216. // functions to engage features not directly supported by LLProcess.
  217. LL_INLINE handle getProcessHandle() const
  218. {
  219. #if LL_WINDOWS
  220. return mProcess.hproc;
  221. #else
  222. return mProcess.pid;
  223. #endif
  224. }
  225. // Tests if a process (handle obtained from getProcessHandle()) is still
  226. // running. Returns same nonzero handle value if still running, else zero,
  227. // so you can test it like a bool. But if you want to update a stored
  228. // variable as a side effect, you can write code like this:
  229. // hchild = LLProcess::isRunning(hchild);
  230. //
  231. // Note: this method is intended as a unit-test hook, not as the first of
  232. // a whole set of operations supported on freestanding handle values. New
  233. // functionality should be added as non-static members operating on the
  234. // same data as getProcessHandle().
  235. //
  236. // In particular, if child termination is detected by this static
  237. // isRunning() rather than by nonstatic isRunning(), the LLProcess object
  238. // would not be aware of the child's changed status and may encounter OS
  239. // errors trying to obtain it. This static isRunning() is only intended for
  240. // after the launching LLProcess object has been destroyed.
  241. static handle isRunning(handle,
  242. const std::string& desc = LLStringUtil::null);
  243. // Provides symbolic access to child's file slots
  244. enum FILESLOT { STDIN = 0, STDOUT = 1, STDERR = 2, NSLOTS = 3 };
  245. // Base of ReadPipe, WritePipe
  246. class BasePipe
  247. {
  248. public:
  249. virtual ~BasePipe() = default;
  250. typedef size_t size_type;
  251. static const size_type npos;
  252. // Gets accumulated buffer length.
  253. //
  254. // For WritePipe, is there still pending data to send to child ?
  255. //
  256. // For ReadPipe, we often need to refrain from actually reading the
  257. // std::istream returned by get_istream() until we have accumulated
  258. // enough data to make it worthwhile. For instance, if we are expecting
  259. // a number from the child, but the child happens to flush "12" before
  260. // emitting "3\n", get_istream() >> myint could return 12 rather than
  261. // 123 !
  262. virtual size_type size() const = 0;
  263. };
  264. // As returned by getWritePipe() or getOptWritePipe()
  265. class WritePipe : public BasePipe
  266. {
  267. public:
  268. // Get ostream& on which to write to child's stdin. Usage:
  269. // p->getWritePipe().get_ostream() << "Hello, child !" << std::endl;
  270. virtual std::ostream& get_ostream() = 0;
  271. };
  272. // As returned by getReadPipe() or getOptReadPipe()
  273. class ReadPipe : public BasePipe
  274. {
  275. public:
  276. // Gets istream& on which to read from child's stdout or stderr. Usage:
  277. // std::string stuff;
  278. // p->getReadPipe().get_istream() >> stuff;
  279. //
  280. // You should be sure in advance that the ReadPipe in question can fill
  281. // the request. See getPump()
  282. virtual std::istream& get_istream() = 0;
  283. // Like std::getline(get_istream(), line), but trims off trailing '\r'
  284. // to make calling code less platform-sensitive.
  285. virtual std::string getline() = 0;
  286. // Like get_istream().read(buffer, n), but returns std::string rather
  287. // than requiring caller to construct a buffer, etc.
  288. virtual std::string read(size_type len) = 0;
  289. // Peeks at accumulated buffer data without consuming it. Optional
  290. // parameters give you substr() functionality.
  291. //
  292. // Note: you can discard buffer data using get_istream().ignore(n).
  293. virtual std::string peek(size_type offset = 0,
  294. size_type len = npos) const = 0;
  295. // Searches for a substring in accumulated buffer data without
  296. // retrieving it. Returns size_type position at which found, or npos
  297. // meaning not found. Optional offset allows you to search from
  298. // specified position.
  299. virtual size_type find(const std::string& seek,
  300. size_type offset = 0) const = 0;
  301. // Detects the presence of a substring (or char) in accumulated buffer
  302. // data without retrieving it. Optional offset allows you to search
  303. // from specified position.
  304. template <typename SEEK>
  305. LL_INLINE bool contains(SEEK seek, size_type offset = 0) const
  306. {
  307. return find(seek, offset) != npos;
  308. }
  309. // Searches for a char in accumulated buffer data without retrieving
  310. // it. Returns size_type position at which found, or npos meaning not
  311. // found. Optional offset allows you to search from specified
  312. // position.
  313. virtual size_type find(char seek, size_type offset = 0) const = 0;
  314. // Gets LLEventPump& on which to listen for incoming data. The posted
  315. // LLSD::Map event will contain:
  316. //
  317. // - "data" part of pending data; see setLimit()
  318. // - "len" entire length of pending data, regardless of setLimit()
  319. // - "slot" this ReadPipe's FILESLOT, e.g. LLProcess::STDOUT
  320. // - "name" e.g. "stdout"
  321. // - "desc" e.g. "SLPlugin (pid) stdout"
  322. // - "eof" true means there no more data will arrive on this pipe,
  323. // therefore no more events on this pump
  324. //
  325. // If the child sends "abc", and this ReadPipe posts "data"="abc", but
  326. // you do not consume it by reading the std::istream returned by
  327. // get_istream(), and the child next sends "def", ReadPipe will post
  328. // "data"="abcdef".
  329. virtual LLEventPump& getPump() = 0;
  330. // Sets maximum length of buffer data that will be posted in the LLSD
  331. // announcing arrival of new data from the child. If you call
  332. // setLimit(5), and the child sends "abcdef", the LLSD event will
  333. // contain "data"="abcde". However, you may still read the entire
  334. // "abcdef" from get_istream(): this limit affects only the size of
  335. // the data posted with the LLSD event. If you do not call this method,
  336. // no data will be posted: the default is 0 bytes.
  337. virtual void setLimit(size_type limit) = 0;
  338. // Query the current setLimit() limit.
  339. virtual size_type getLimit() const = 0;
  340. };
  341. // Exception thrown by getWritePipe(), getReadPipe() if you did not ask to
  342. // create a pipe at the corresponding FILESLOT.
  343. struct NoPipe : public std::runtime_error
  344. {
  345. LL_INLINE NoPipe(const std::string& what)
  346. : std::runtime_error(what)
  347. {
  348. }
  349. LL_INLINE NoPipe(const char* what)
  350. : std::runtime_error(what)
  351. {
  352. }
  353. };
  354. // Gets a reference to the (only) WritePipe for this LLProcess. 'slot', if
  355. // specified, must be STDIN. Throws NoPipe if you did not request a "pipe"
  356. // for child stdin.
  357. WritePipe& getWritePipe(FILESLOT slot = STDIN);
  358. // Gets a reference to one of the ReadPipes for this LLProcess. 'slot', if
  359. // specified, must be STDOUT or STDERR. Throws NoPipe if you did not
  360. // request a "pipe" for child stdout or stderr.
  361. ReadPipe& getReadPipe(FILESLOT slot);
  362. // Let's offer some introspection methods for LLLeap to retransmit to the
  363. // user code via its own methods. HB
  364. LL_INLINE const std::string& getDesc() const
  365. {
  366. return mDesc;
  367. }
  368. LL_INLINE const std::string& getExecutable() const
  369. {
  370. return mExecutable;
  371. }
  372. LL_INLINE const std::string& getInterpreter() const
  373. {
  374. return mInterpreter;
  375. }
  376. LL_INLINE const std::string& getCwd() const
  377. {
  378. return mCwd;
  379. }
  380. LL_INLINE const std::vector<std::string>& getArgs() const
  381. {
  382. return mAgs;
  383. }
  384. private:
  385. // Use create() instead
  386. LLProcess(const LLSD& params);
  387. // Classic-C-style APR callback
  388. static void statusCallback(int reason, void* data, int status);
  389. // Object-oriented callback
  390. void handleStatus(int reason, int status);
  391. // Implementation for get[Read|Write]Pipe()
  392. template <class PIPETYPE>
  393. PIPETYPE& getPipe(FILESLOT slot);
  394. template <class PIPETYPE>
  395. PIPETYPE* getPipePtr(std::string& error, FILESLOT slot);
  396. private:
  397. apr_pool_t* mPool;
  398. std::string mDesc;
  399. std::string mExecutable;
  400. #if !LL_WINDOWS
  401. std::string mShebang;
  402. #endif
  403. std::string mInterpreter;
  404. std::string mCwd;
  405. std::string mPostend;
  406. std::vector<std::string> mAgs;
  407. apr_proc_t mProcess;
  408. // Explicitly want this ptr_vector to be able to store NULLs
  409. typedef boost::ptr_vector< boost::nullable<BasePipe> > pipe_vec_t;
  410. pipe_vec_t mPipes;
  411. Status mStatus;
  412. bool mAttached;
  413. };
  414. // Support class internal to LLProcess: a ref-counted "mainloop" listener,
  415. // which, as long as there are still outstanding LLProcess objects, keeps
  416. // listening on "mainloop" so we can keep polling APR for process status.
  417. class LLProcessListener final
  418. {
  419. protected:
  420. LOG_CLASS(LLProcessListener);
  421. public:
  422. LL_INLINE LLProcessListener()
  423. : mCount(0)
  424. {
  425. }
  426. void addPoll(const LLProcess&)
  427. {
  428. // Unconditionally increment mCount. If it was zero before
  429. // incrementing, listen on "mainloop".
  430. if (mCount++ == 0)
  431. {
  432. LL_DEBUGS("LLProcess") << "Listening on \"mainloop\"" << LL_ENDL;
  433. LLEventPump& pump = gEventPumps.obtain("mainloop");
  434. mConnection = pump.listen("LLProcessListener",
  435. boost::bind(&LLProcessListener::tick,
  436. this, _1));
  437. }
  438. }
  439. void dropPoll(const LLProcess&)
  440. {
  441. // Unconditionally decrement mCount. If it is zero after decrementing,
  442. // stop listening on "mainloop".
  443. if (--mCount == 0)
  444. {
  445. LL_DEBUGS("LLProcess") << "Disconnecting from \"mainloop\""
  446. << LL_ENDL;
  447. mConnection.disconnect();
  448. }
  449. }
  450. private:
  451. // Called once per frame by the "mainloop" LLEventPump
  452. bool tick(const LLSD&)
  453. {
  454. // Tell APR to sense whether each registered LLProcess is still running
  455. // and call handleStatus() appropriately. We should be able to get the
  456. // same info from an apr_proc_wait(APR_NOWAIT) call; but at least in
  457. // APR 1.4.2, testing suggests that even with APR_NOWAIT,
  458. // apr_proc_wait() blocks the caller. We cannot have that in the
  459. // viewer. Hence the callback rigmarole (once we update APR, it is
  460. // probably worth testing again). Also, although there is an
  461. // apr_proc_other_child_refresh() call, i.e. get that information for
  462. // one specific child, it accepts an 'apr_other_child_rec_t*' that is
  463. // mentioned NOWHERE else in the documentation or header files ! I
  464. // would use the specific call in LLProcess::getStatus() if I knew
  465. // how. As it is, each call to apr_proc_other_child_refresh_all() will
  466. // call callbacks for ALL still-running child processes. This is why we
  467. // centralize such calls, using "mainloop" to ensure it happens once
  468. // per frame, and refcounting running LLProcess objects to remain
  469. // registered only while needed.
  470. LL_DEBUGS("LLProcess") << "Calling apr_proc_other_child_refresh_all()"
  471. << LL_ENDL;
  472. apr_proc_other_child_refresh_all(APR_OC_REASON_RUNNING);
  473. return false;
  474. }
  475. private:
  476. // If this object is destroyed before mCount goes to zero, stop listening
  477. // on "mainloop" anyway.
  478. LLTempBoundListener mConnection;
  479. S32 mCount;
  480. };
  481. static LLProcessListener sProcessListener;
  482. // Use funky syntax to call max() to avoid blighted max() macros
  483. const LLProcess::BasePipe::size_type LLProcess::BasePipe::npos =
  484. (std::numeric_limits<LLProcess::BasePipe::size_type>::max)();
  485. class WritePipeImpl final : public LLProcess::WritePipe
  486. {
  487. protected:
  488. LOG_CLASS(WritePipeImpl);
  489. public:
  490. WritePipeImpl(const std::string& desc, apr_file_t* pipe)
  491. : mDesc(desc),
  492. mPipe(pipe),
  493. // We must initialize our std::ostream with our special streambuf !
  494. mStream(&mStreambuf)
  495. {
  496. LLEventPump& pump = gEventPumps.obtain("mainloop");
  497. mConnection = pump.listen(LLEventPump::inventName("WritePipe"),
  498. boost::bind(&WritePipeImpl::tick, this, _1));
  499. #if !LL_WINDOWS
  500. // We cannot count on every child process reading everything we try to
  501. // write to it. And if the child terminates with WritePipe data still
  502. // pending, unless we explicitly suppress it, POSIX will hit us with
  503. // SIGPIPE. That would terminate the viewer, boom. "Ignoring" it means
  504. // APR gets the correct errno, passes it back to us, we log it, etc.
  505. signal(SIGPIPE, SIG_IGN);
  506. #endif
  507. }
  508. LL_INLINE std::ostream& get_ostream() override { return mStream; }
  509. LL_INLINE size_type size() const override { return mStreambuf.size(); }
  510. bool tick(const LLSD&)
  511. {
  512. typedef boost::asio::streambuf::const_buffers_type const_buff_seq_t;
  513. // If there is anything to send, try to send it.
  514. size_t total = mStreambuf.size();
  515. size_t consumed = 0;
  516. if (total)
  517. {
  518. const_buff_seq_t bufs = mStreambuf.data();
  519. // In general, our streambuf might contain a number of different
  520. // physical buffers; iterate over those.
  521. bool keepwriting = true;
  522. for (const_buff_seq_t::const_iterator it = bufs.begin(),
  523. end = bufs.end();
  524. it != end && keepwriting; ++it)
  525. {
  526. // Although apr_file_write() accepts const void*, we
  527. // manipulate const char* so we can increment the pointer.
  528. const char* remainptr =
  529. boost::asio::buffer_cast<const char*>(*it);
  530. size_t remainlen = boost::asio::buffer_size(*it);
  531. while (remainlen)
  532. {
  533. // Tackle the current buffer in discrete chunks. On
  534. // Windows, we have observed strange failures when trying
  535. // to write big lengths (~1 MB) in a single operation. Even
  536. // a 32K chunk seems too large. At some point along the way
  537. // apr_file_write() returns 11 (resource temporarily
  538. // unavailable, i.e. EAGAIN) and says it wrote 0 bytes,
  539. // even though it did write the chunk ! Our next write
  540. // attempt retries with the same chunk, resulting in the
  541. // chunk being duplicated at the child end. Using smaller
  542. // chunks is empirically more reliable.
  543. size_t towrite = llmin(remainlen, size_t(4096));
  544. apr_size_t written(towrite);
  545. apr_status_t err = apr_file_write(mPipe, remainptr,
  546. &written);
  547. // EAGAIN is exactly what we want from a nonblocking pipe.
  548. // Rather than waiting for data, it should return
  549. // immediately.
  550. if (err != APR_SUCCESS && !APR_STATUS_IS_EAGAIN(err))
  551. {
  552. llwarns << "apr_file_write(" << towrite << ") on "
  553. << mDesc << " got " << err << llendl;
  554. ll_apr_warn_status(err);
  555. }
  556. // 'written' is modified to reflect the number of bytes
  557. // actually written. Make sure we consume those later (do
  558. // not consume them now, that would invalidate the buffer
  559. // iterator sequence !).
  560. consumed += written;
  561. // Do not forget to advance to next chunk of current buffer
  562. remainptr += written;
  563. remainlen -= written;
  564. LL_DEBUGS("LLProcess") << "Wrote " << written << " of "
  565. << towrite << " bytes to " << mDesc
  566. << " (original " << total << "),"
  567. << " code " << err << ": ";
  568. char msgbuf[512];
  569. LL_CONT << apr_strerror(err, msgbuf, sizeof(msgbuf))
  570. << LL_ENDL;
  571. // The parent end of this pipe is nonblocking. If we were
  572. // not able to write everything we wanted, do not keep
  573. // banging on it; that would not change until the child
  574. // reads some. Wait for next tick().
  575. if (written < towrite)
  576. {
  577. // Break outer loop over buffers too
  578. keepwriting = false;
  579. break;
  580. }
  581. } // Next chunk of current buffer
  582. } // Next buffer
  583. // In all, we managed to write 'consumed' bytes. Remove them from
  584. // the streambuf so we do not keep trying to send them. This could
  585. // be anywhere from 0 up to mStreambuf.size(); anything we have not
  586. // yet sent, we will try again later.
  587. mStreambuf.consume(consumed);
  588. }
  589. return false;
  590. }
  591. private:
  592. std::string mDesc;
  593. apr_file_t* mPipe;
  594. LLTempBoundListener mConnection;
  595. boost::asio::streambuf mStreambuf;
  596. std::ostream mStream;
  597. };
  598. class ReadPipeImpl final : public LLProcess::ReadPipe
  599. {
  600. protected:
  601. LOG_CLASS(ReadPipeImpl);
  602. public:
  603. ReadPipeImpl(const std::string& desc, apr_file_t* pipe,
  604. LLProcess::FILESLOT index)
  605. : mDesc(desc),
  606. mPipe(pipe),
  607. mIndex(index),
  608. // We need to initialize our std::istream with our special streambuf !
  609. mStream(&mStreambuf),
  610. mPump("ReadPipe", true), // Tweak name as needed to avoid collisions
  611. mLimit(0),
  612. mEOF(false)
  613. {
  614. LLEventPump& pump = gEventPumps.obtain("mainloop");
  615. mConnection = pump.listen(LLEventPump::inventName("ReadPipe"),
  616. boost::bind(&ReadPipeImpl::tick, this, _1));
  617. }
  618. ~ReadPipeImpl() override
  619. {
  620. if (mConnection.connected())
  621. {
  622. mConnection.disconnect();
  623. }
  624. }
  625. // Much of the implementation is simply connecting the abstract virtual
  626. // methods with implementation data concealed from the base class.
  627. LL_INLINE std::istream& get_istream() override { return mStream; }
  628. LL_INLINE std::string getline() override
  629. {
  630. return get_line_from_stream(mStream);
  631. }
  632. LL_INLINE LLEventPump& getPump() override { return mPump; }
  633. LL_INLINE void setLimit(size_type l) override { mLimit = l; }
  634. LL_INLINE size_type getLimit() const override { return mLimit; }
  635. LL_INLINE size_type size() const override { return mStreambuf.size(); }
  636. std::string read(size_type len) override
  637. {
  638. // Read specified number of bytes into a buffer.
  639. size_type readlen = llmin(size(), len);
  640. // Formally, &buffer[0] is invalid for a vector of size() 0. Exit
  641. // early in that situation.
  642. if (!readlen)
  643. {
  644. return "";
  645. }
  646. // Make a buffer big enough.
  647. std::vector<char> buffer(readlen);
  648. mStream.read(&buffer[0], readlen);
  649. // Since we have already clamped 'readlen', we can think of no reason
  650. // why mStream.read() should read fewer than 'readlen' bytes.
  651. // Nonetheless, use the actual retrieved length.
  652. return std::string(&buffer[0], mStream.gcount());
  653. }
  654. std::string peek(size_type offset = 0, size_type len = npos) const override
  655. {
  656. // Constrain caller's offset and len to overlap actual buffer content.
  657. size_t real_offset = llmin(mStreambuf.size(), size_t(offset));
  658. size_type want_end = len == npos ? npos : real_offset + len;
  659. size_t real_end = llmin(mStreambuf.size(), size_t(want_end));
  660. boost::asio::streambuf::const_buffers_type cbufs = mStreambuf.data();
  661. return std::string(boost::asio::buffers_begin(cbufs) + real_offset,
  662. boost::asio::buffers_begin(cbufs) + real_end);
  663. }
  664. size_type find(const std::string& seek, size_type off = 0) const override
  665. {
  666. // If we are passing a string of length 1, use find(char), which can
  667. // use an O(n) std::find() rather than the O(n^2) std::search().
  668. if (seek.length() == 1)
  669. {
  670. return find(seek[0], off);
  671. }
  672. // If off is beyond the whole buffer, we cannot even construct a valid
  673. // iterator range; cannot possibly find the string we seek.
  674. if (off > mStreambuf.size())
  675. {
  676. return npos;
  677. }
  678. typedef boost::asio::streambuf::const_buffers_type const_buff_type_t;
  679. const_buff_type_t cbufs = mStreambuf.data();
  680. boost::asio::buffers_iterator<const_buff_type_t> begin =
  681. boost::asio::buffers_begin(cbufs);
  682. boost::asio::buffers_iterator<const_buff_type_t> end =
  683. boost::asio::buffers_end(cbufs);
  684. boost::asio::buffers_iterator<const_buff_type_t> it =
  685. std::search(begin + off, end, seek.begin(), seek.end());
  686. return it == end ? npos : it - begin;
  687. }
  688. size_type find(char seek, size_type offset = 0) const override
  689. {
  690. // If offset is beyond the whole buffer, cannot even construct a valid
  691. // iterator range; cannot possibly find the char we seek.
  692. if (offset > mStreambuf.size())
  693. {
  694. return npos;
  695. }
  696. typedef boost::asio::streambuf::const_buffers_type const_buff_type_t;
  697. const_buff_type_t cbufs = mStreambuf.data();
  698. boost::asio::buffers_iterator<const_buff_type_t> begin =
  699. boost::asio::buffers_begin(cbufs);
  700. boost::asio::buffers_iterator<const_buff_type_t> end =
  701. boost::asio::buffers_end(cbufs);
  702. boost::asio::buffers_iterator<const_buff_type_t> it =
  703. std::find(begin + offset, end, seek);
  704. return it == end ? npos : it - begin;
  705. }
  706. bool tick(const LLSD&)
  707. {
  708. // Once we have hit EOF, skip all the rest of this.
  709. if (mEOF)
  710. {
  711. return false;
  712. }
  713. typedef boost::asio::streambuf::mutable_buffers_type mut_buff_seq_t;
  714. // Try, every time, to read into our streambuf. In fact, we have no
  715. // idea how much data the child might be trying to send: keep trying
  716. // until we are convinced we have temporarily exhausted the pipe.
  717. enum PipeState { RETRY, EXHAUSTED, CLOSED };
  718. PipeState state = RETRY;
  719. size_t committed = 0;
  720. do
  721. {
  722. // Attempt to read an arbitrary size
  723. mut_buff_seq_t bufs = mStreambuf.prepare(4096);
  724. // In general, the mut_buff_seq_t returned by prepare() might
  725. // contain a number of different physical buffers; iterate over
  726. // those.
  727. size_t tocommit = 0;
  728. for (mut_buff_seq_t::const_iterator it = bufs.begin(),
  729. end = bufs.end();
  730. it != end; ++it)
  731. {
  732. size_t toread = boost::asio::buffer_size(*it);
  733. apr_size_t gotten = toread;
  734. apr_status_t err =
  735. apr_file_read(mPipe, boost::asio::buffer_cast<void*>(*it),
  736. &gotten);
  737. // EAGAIN is exactly what we want from a nonblocking pipe.
  738. // Rather than waiting for data, it should return immediately.
  739. if (err != APR_SUCCESS && !APR_STATUS_IS_EAGAIN(err))
  740. {
  741. // Handle EOF specially: it is part of normal-case
  742. // processing.
  743. if (err == APR_EOF)
  744. {
  745. LL_DEBUGS("LLProcess") << "EOF on " << mDesc
  746. << LL_ENDL;
  747. }
  748. else
  749. {
  750. llwarns << "apr_file_read(" << toread << ") on "
  751. << mDesc << " got " << err << llendl;
  752. ll_apr_warn_status(err);
  753. }
  754. // Either way, though, we would not need any more tick()
  755. // calls.
  756. mConnection.disconnect();
  757. // Ignore any subsequent calls we might get anyway.
  758. mEOF = true;
  759. state = CLOSED; // Also break outer retry loop
  760. break;
  761. }
  762. // 'gotten' was modified to reflect the number of bytes
  763. // actually received. Make sure we commit those later (do not
  764. // commit them now, that would invalidate the buffer iterator
  765. // sequence !).
  766. tocommit += gotten;
  767. LL_DEBUGS("LLProcess") << "Filled " << gotten << " of "
  768. << toread << " bytes from " << mDesc
  769. << LL_ENDL;
  770. // The parent end of this pipe is nonblocking. If we were not
  771. // even able to fill this buffer, do not loop to try to fill
  772. // the next; that would not change until the child writes more.
  773. // Wait for next tick().
  774. if (gotten < toread)
  775. {
  776. state = EXHAUSTED; // Break outer retry loop too
  777. break;
  778. }
  779. }
  780. // Do not forget to "commit" the data !
  781. mStreambuf.commit(tocommit);
  782. committed += tocommit;
  783. // 'state' is changed from RETRY when we cannot fill any one buffer
  784. // of the mut_buff_seq_t established by the current prepare() call,
  785. // whether due to error or not enough bytes.
  786. // That is, if state is still RETRY, we have filled every physical
  787. // buffer in the mut_buff_seq_t. In that case, for all we know, the
  788. // child might have still more data pending: go for it !
  789. }
  790. while (state == RETRY);
  791. // Once we recognize that the pipe is closed, make one more call to
  792. // listener. The listener might be waiting for a particular substring
  793. // to arrive, or a particular length of data or something. The event
  794. // with "eof" == true announces that nothing further will arrive, so
  795. // use it or lose it.
  796. if (committed || state == CLOSED)
  797. {
  798. // If we actually received new data, publish it on our LLEventPump
  799. // as advertised. Constrain it by mLimit. But show listener the
  800. // actual accumulated buffer size, regardless of mLimit.
  801. size_type datasize(llmin(mLimit, size_type(mStreambuf.size())));
  802. mPump.post(LLSDMap("data", peek(0, datasize))
  803. ("len", LLSD::Integer(mStreambuf.size()))
  804. ("slot", LLSD::Integer(mIndex))
  805. ("name", whichfile(mIndex))
  806. ("desc", mDesc)
  807. ("eof", state == CLOSED));
  808. }
  809. return false;
  810. }
  811. private:
  812. std::string mDesc;
  813. apr_file_t* mPipe;
  814. LLTempBoundListener mConnection;
  815. LLEventStream mPump;
  816. boost::asio::streambuf mStreambuf;
  817. std::istream mStream;
  818. LLProcess::FILESLOT mIndex;
  819. size_type mLimit;
  820. bool mEOF;
  821. };
  822. LLProcess::ptr_t LLProcess::create(const LLSD& params)
  823. {
  824. try
  825. {
  826. return ptr_t(new LLProcess(params));
  827. }
  828. catch (const LLLeap::Error& e)
  829. {
  830. llwarns << e.what() << llendl;
  831. // If caller is requesting an event on process termination, send one
  832. // indicating bad launch. This may prevent someone waiting forever for
  833. // a termination post that cannot arrive because the child never
  834. // started.
  835. if (params.has("postend"))
  836. {
  837. gEventPumps.obtain(params["postend"].asString())
  838. .post(LLSDMap("desc", get_desc(params)) // No "id"
  839. ("state", LLProcess::UNSTARTED)
  840. // No "data"
  841. ("string", e.what()));
  842. }
  843. return ptr_t();
  844. }
  845. }
  846. // Calls an APR function returning apr_status_t. On failure, logs a warning and
  847. // throws LLLeap::Error mentioning the function call that produced that result.
  848. #define chkapr(func) \
  849. if (ll_apr_warn_status(func)) { throw LLLeap::Error(#func " failed"); }
  850. LLProcess::LLProcess(const LLSD& params)
  851. : mPool(NULL),
  852. mPipes(NSLOTS)
  853. {
  854. if (!params.isMap() || !params.has("executable"))
  855. {
  856. throw LLLeap::Error("process not launched: failed parameter validation");
  857. }
  858. // Create an argv vector for the child process; APR wants a vector of
  859. // pointers to constant C strings (see the note below about it).
  860. std::vector<const char*> argv;
  861. // In preparation for calling apr_proc_create(), we collect a number of
  862. // const char* pointers obtained from std::string::c_str().
  863. // Note: we store the parameters in member variable strings so that we can
  864. // guarantee (as long as a C++11 compiler and standard library are used)
  865. // that c_str() returns a pointer that will stay valid and constant during
  866. // the whole LLProcess instance life. HB
  867. mExecutable = params["executable"].asString();
  868. #if LL_WINDOWS
  869. // Replace Windows path separators with UNIX ones that APR can understand.
  870. LLStringUtil::replaceChar(mExecutable, '\\', '/');
  871. std::string lcname = mExecutable;
  872. size_t len = lcname.size();
  873. LLStringUtil::toLower(lcname);
  874. if (lcname.rfind(".exe") != len - 4 && lcname.rfind(".com") != len - 4)
  875. {
  876. // If we are not passed an executable, and since Windows does not
  877. // honour shebang lines in scripts, try and find an adequate
  878. // interpreter for the script file.
  879. llinfos << "File " << mExecutable
  880. << " is apparently not a Windows executable..." << llendl;
  881. if (lcname.rfind(".py") == len - 3)
  882. {
  883. llinfos << "Python script assumed, based on extension: trying 'pythonw.exe' to interpret it."
  884. << llendl;
  885. mInterpreter = "pythonw.exe";
  886. argv.emplace_back(mInterpreter.c_str());
  887. }
  888. else if (lcname.rfind(".bat") == len - 4 ||
  889. lcname.rfind(".cmd") == len - 4)
  890. {
  891. llinfos << "Batch script assumed, based on extension: trying 'cmd.exe' to interpret it."
  892. << llendl;
  893. mInterpreter = "cmd.exe";
  894. }
  895. else if (lcname.rfind(".lua") == len - 4)
  896. {
  897. llinfos << "Lua script assumed, based on extension: trying 'lua.exe' to interpret it."
  898. << llendl;
  899. mInterpreter = "lua.exe";
  900. }
  901. else
  902. {
  903. llwarns << "Not a known/supported script type: expect a failure..."
  904. << llendl;
  905. }
  906. }
  907. #else // POSIX
  908. // If we do have a full path, but the file is not executable, it could
  909. // still be a valid script (but with the exec bit not set). Since APR would
  910. // refuse to launch a non-executable script, try and find by ourselves a
  911. // shebang line and use it to launch the proper executable for that
  912. // script... HB
  913. llstat st;
  914. if (LLFile::stat(mExecutable, &st) == 0 && !(st.st_mode & S_IEXEC))
  915. {
  916. llwarns << "File " << mExecutable << " is not executable." << llendl;
  917. llifstream script(mExecutable.c_str());
  918. std::getline(script, mShebang);
  919. if (mShebang.size() > 3 && mShebang.compare(0, 2, "#!") == 0)
  920. {
  921. llinfos << "Found a shebang; assumed to be a script." << llendl;
  922. mInterpreter = mShebang.substr(2); // Remove the leading "#!"
  923. LLStringUtil::trim(mInterpreter); // Trim spaces
  924. size_t i = mInterpreter.find(' '); // E.g.: /usr/bin/env python
  925. if (i != std::string::npos)
  926. {
  927. // This is the actual executable (e.g. /usr/bin/env), so
  928. // place it in first position in the list of arguments. See
  929. // above remark about c_str().
  930. mShebang = mInterpreter.substr(0, i);
  931. argv.emplace_back(mShebang.c_str());
  932. // Get the interpreter name...
  933. mInterpreter = mInterpreter.substr(i + 1);
  934. LLStringUtil::trimHead(mInterpreter); // Trim spaces
  935. }
  936. }
  937. }
  938. #endif
  939. // Add any interpreter into the arguments list in first (or second, for
  940. // scripts using a shebang line with /usr/bin/env or such) position. See
  941. // above remark about c_str().
  942. if (!mInterpreter.empty())
  943. {
  944. llinfos << "Attempting to use the following intrepreter program: "
  945. << mInterpreter << llendl;
  946. argv.emplace_back(mInterpreter.c_str());
  947. }
  948. // We may now add the "executable" (or script) path. See above remark
  949. // about c_str().
  950. argv.emplace_back(mExecutable.c_str());
  951. // Hmm, when you construct a ptr_vector with a size, it merely reserves
  952. // space, it does not actually make it that big. Explicitly make it bigger.
  953. // Because of ptr_vector's odd semantics, have to push_back(0) the right
  954. // number of times ! resize() wants to default-construct new BasePipe
  955. // instances, which fails because it's pure virtual. But because of the
  956. // constructor call, these push_back() calls should require no new
  957. // allocation.
  958. for (size_t i = 0, count = mPipes.capacity(); i < count; ++i)
  959. {
  960. mPipes.push_back(0);
  961. }
  962. mAttached = params.has("attached") && params["attached"].asBoolean();
  963. if (params.has("postend"))
  964. {
  965. mPostend = params["postend"].asString();
  966. }
  967. apr_pool_create(&mPool, gAPRPoolp);
  968. if (!mPool)
  969. {
  970. throw LLLeap::Error("APR pool creation failed");
  971. }
  972. apr_procattr_t* procattr = NULL;
  973. chkapr(apr_procattr_create(&procattr, mPool));
  974. // IQA-490, CHOP-900: on Windows, ask APR to jump through hoops to
  975. // constrain the set of handles passed to the child process. Before we
  976. // changed to APR, the Windows implementation of LLProcessLauncher called
  977. // CreateProcess(bInheritHandles=FALSE), meaning to pass NO open handles
  978. // to the child process. Now that we support pipes, though, we must allow
  979. // apr_proc_create() to pass bInheritHandles=TRUE. But without taking
  980. // special pains, that causes trouble in a number of ways, due to the fact
  981. // that the viewer is constantly opening and closing files: most of which
  982. // CreateProcess() passes to every child process!
  983. #if defined(APR_HAS_PROCATTR_CONSTRAIN_HANDLE_SET)
  984. chkapr(apr_procattr_constrain_handle_set(procattr, 1));
  985. #else
  986. // Our special preprocessor symbol is not even defined: wrong APR !
  987. llwarns << "This version of APR lacks Linden "
  988. << "apr_procattr_constrain_handle_set() extension" << llendl;
  989. #endif
  990. // For which of stdin, stdout, stderr should we create a pipe to the
  991. // child ? In the viewer, there are only a couple viable
  992. // apr_procattr_io_set() alternatives: inherit the viewer's own stdxxx
  993. // handle (APR_NO_PIPE, e.g. for stdout, stderr), or create a pipe that is
  994. // blocking on the child end but nonblocking at the viewer end
  995. // (APR_CHILD_BLOCK).
  996. // Other major options could include explicitly creating a single APR pipe
  997. // and passing it as both stdout and stderr (apr_procattr_child_out_set(),
  998. // apr_procattr_child_err_set()), or accepting a filename, opening it and
  999. // passing that apr_file_t (simple <, >, 2> redirect emulation).
  1000. std::vector<apr_int32_t> select;
  1001. if (params.has("files"))
  1002. {
  1003. const LLSD& files = params["files"];
  1004. if (files.isArray())
  1005. {
  1006. for (LLSD::array_const_iterator it = files.beginArray(),
  1007. end = files.endArray();
  1008. it != end; ++it)
  1009. {
  1010. if (it->asString() == "pipe")
  1011. {
  1012. select.emplace_back(APR_CHILD_BLOCK);
  1013. }
  1014. // Ignore all unsupported file types and consider no file
  1015. // redirection was asked for them. HB
  1016. else
  1017. {
  1018. select.emplace_back(APR_NO_PIPE);
  1019. }
  1020. }
  1021. }
  1022. }
  1023. // By default, pass APR_NO_PIPE for unspecified slots.
  1024. while (select.size() < NSLOTS)
  1025. {
  1026. select.push_back(APR_NO_PIPE);
  1027. }
  1028. chkapr(apr_procattr_io_set(procattr, select[STDIN], select[STDOUT],
  1029. select[STDERR]));
  1030. // Thumbs down on implicitly invoking the shell to invoke the child. From
  1031. // our point of view, the other major alternative to APR_PROGRAM_PATH would
  1032. // be APR_PROGRAM_ENV: still copy environment, but require full executable
  1033. // pathname. There is no real downside to searching the PATH, though: if
  1034. // our caller wants (e.g.) a specific Python interpreter, they can still
  1035. // pass the full pathname.
  1036. chkapr(apr_procattr_cmdtype_set(procattr, APR_PROGRAM_PATH));
  1037. // YES, do extra work if necessary to report child exec() failures back to
  1038. // parent process.
  1039. chkapr(apr_procattr_error_check_set(procattr, 1));
  1040. if (params.has("cwd"))
  1041. {
  1042. mCwd = params["cwd"].asString();
  1043. chkapr(apr_procattr_dir_set(procattr, mCwd.c_str()));
  1044. }
  1045. if (params.has("args"))
  1046. {
  1047. const LLSD& args = params["args"];
  1048. if (args.isArray())
  1049. {
  1050. for (LLSD::array_const_iterator it = args.beginArray(),
  1051. end = args.endArray();
  1052. it != end; ++it)
  1053. {
  1054. mAgs.emplace_back(it->asString());
  1055. // See above remark about c_str().
  1056. argv.emplace_back(mAgs.back().c_str());
  1057. }
  1058. }
  1059. }
  1060. // Terminate with a null pointer
  1061. argv.push_back(NULL);
  1062. // Launch ! The NULL would be the environment block, if we were passing
  1063. // one. Hand-expand chkapr() macro so we can fill in the actual command
  1064. // string instead of the variable names.
  1065. if (ll_apr_warn_status(apr_proc_create(&mProcess, argv[0], &argv[0], NULL,
  1066. procattr, mPool)))
  1067. {
  1068. throw LLLeap::Error(get_desc(params) + " failed");
  1069. }
  1070. // Arrange to call statusCallback()
  1071. apr_proc_other_child_register(&mProcess, &LLProcess::statusCallback, this,
  1072. mProcess.in, mPool);
  1073. // And make sure we poll it once per "mainloop" tick
  1074. sProcessListener.addPoll(*this);
  1075. mStatus.mState = RUNNING;
  1076. mDesc = llformat("%s (%d)", get_desc(params).c_str(), mProcess.pid);
  1077. llinfos << mDesc << ": launched " << params << llendl;
  1078. // Instantiate the proper pipe I/O machinery: we want to be able to point
  1079. // to apr_proc_t::in, out, err by index
  1080. typedef apr_file_t* apr_proc_t::*apr_proc_file_ptr;
  1081. static apr_proc_file_ptr members[] =
  1082. {
  1083. &apr_proc_t::in,
  1084. &apr_proc_t::out,
  1085. &apr_proc_t::err
  1086. };
  1087. for (size_t i = 0; i < NSLOTS; ++i)
  1088. {
  1089. if (select[i] != APR_CHILD_BLOCK)
  1090. {
  1091. continue;
  1092. }
  1093. std::string desc = mDesc + " " + whichfile(FILESLOT(i));
  1094. apr_file_t* pipe(mProcess.*(members[i]));
  1095. if (i == STDIN)
  1096. {
  1097. mPipes.replace(i, new WritePipeImpl(desc, pipe));
  1098. }
  1099. else
  1100. {
  1101. mPipes.replace(i, new ReadPipeImpl(desc, pipe, FILESLOT(i)));
  1102. }
  1103. }
  1104. }
  1105. LLProcess::~LLProcess()
  1106. {
  1107. // Unregistering is pointless (and fatal) when this is called after the
  1108. // global APR pool has been destroyed on viewer exit, and kill(), which
  1109. // also relies on APR, is impossible anyway.
  1110. if (!mPool)
  1111. {
  1112. return;
  1113. }
  1114. // Only in state RUNNING are we registered for callback. In UNSTARTED we
  1115. // have not yet registered. And since receiving the callback is the only
  1116. // way we detect child termination, we only change from state RUNNING at
  1117. // the same time we unregister.
  1118. if (mStatus.mState == RUNNING)
  1119. {
  1120. // We are still registered for a callback: unregister. Do it before
  1121. // we even issue the kill(): even if kill() somehow prompted an
  1122. // instantaneous callback (unlikely), this object is going away ! Any
  1123. // information updated in this object by such a callback is no longer
  1124. // available to any consumer anyway.
  1125. apr_proc_other_child_unregister(this);
  1126. // One less LLProcess to poll for
  1127. sProcessListener.dropPoll(*this);
  1128. }
  1129. if (mAttached)
  1130. {
  1131. kill("destructor");
  1132. }
  1133. apr_pool_destroy(mPool);
  1134. mPool = NULL;
  1135. }
  1136. bool LLProcess::kill(const std::string& who)
  1137. {
  1138. if (isRunning())
  1139. {
  1140. llinfos << who << " killing " << mDesc << llendl;
  1141. #if LL_WINDOWS
  1142. int sig = -1;
  1143. #else // POSIX
  1144. int sig = SIGTERM;
  1145. #endif
  1146. ll_apr_warn_status(apr_proc_kill(&mProcess, sig));
  1147. }
  1148. return !isRunning();
  1149. }
  1150. //static
  1151. std::string LLProcess::getStatusString(const std::string& desc,
  1152. const Status& status)
  1153. {
  1154. if (status.mState == UNSTARTED)
  1155. {
  1156. return desc + " was never launched";
  1157. }
  1158. if (status.mState == RUNNING)
  1159. {
  1160. return desc + " running";
  1161. }
  1162. if (status.mState == EXITED)
  1163. {
  1164. return llformat("%s exited with code %d", desc.c_str(), status.mData);
  1165. }
  1166. if (status.mState == KILLED)
  1167. {
  1168. #if LL_WINDOWS
  1169. return llformat("%s killed with exception %x", desc.c_str(),
  1170. status.mData);
  1171. #else
  1172. return llformat("%s killed by signal %d (%s)", desc.c_str(),
  1173. status.mData,
  1174. apr_signal_description_get(status.mData));
  1175. #endif
  1176. }
  1177. return llformat("%s in unknown state %d (%d)", desc.c_str(), status.mState,
  1178. status.mData);
  1179. }
  1180. // Classic-C-style APR callback
  1181. void LLProcess::statusCallback(int reason, void* data, int status)
  1182. {
  1183. // Our only role is to bounce this static method call back into object
  1184. // space.
  1185. ((LLProcess*)data)->handleStatus(reason, status);
  1186. }
  1187. #define tabent(symbol) { symbol, #symbol }
  1188. static struct ReasonCode
  1189. {
  1190. int code;
  1191. const char* name;
  1192. } reasons[] =
  1193. {
  1194. tabent(APR_OC_REASON_DEATH),
  1195. tabent(APR_OC_REASON_UNWRITABLE),
  1196. tabent(APR_OC_REASON_RESTART),
  1197. tabent(APR_OC_REASON_UNREGISTER),
  1198. tabent(APR_OC_REASON_LOST),
  1199. tabent(APR_OC_REASON_RUNNING)
  1200. };
  1201. #undef tabent
  1202. // Object-oriented callback
  1203. void LLProcess::handleStatus(int reason, int status)
  1204. {
  1205. LL_DEBUGS("LLProcess") << mDesc << ": handleStatus(";
  1206. std::string reason_str;
  1207. for (const ReasonCode& rcp : reasons)
  1208. {
  1209. if (reason == rcp.code)
  1210. {
  1211. reason_str = rcp.name;
  1212. break;
  1213. }
  1214. }
  1215. if (reason_str.empty())
  1216. {
  1217. reason_str = llformat("unknown reason %d", reason);
  1218. }
  1219. LL_CONT << reason_str << ", " << status << ")" << LL_ENDL;
  1220. if (reason != APR_OC_REASON_DEATH && reason != APR_OC_REASON_LOST)
  1221. {
  1222. // We are only interested in the call when the child terminates.
  1223. return;
  1224. }
  1225. // Somewhat oddly, APR requires that you explicitly unregister even when
  1226. // it already knows the child has terminated. We must pass the same 'data'
  1227. // pointer as for the register() call, which was our 'this'.
  1228. apr_proc_other_child_unregister(this);
  1229. // Do not keep polling for a terminated process
  1230. sProcessListener.dropPoll(*this);
  1231. // We overload mStatus.mState to indicate whether the child is registered
  1232. // for APR callback: only RUNNING means registered. Track that we have
  1233. // unregistered. We know the child has terminated; might be EXITED or
  1234. // KILLED; refine below.
  1235. mStatus.mState = EXITED;
  1236. // Make last-gasp calls for each of the ReadPipes we have on hand. Since
  1237. // they are listening on "mainloop", we can be sure they will eventually
  1238. // collect all pending data from the child. But we want to be able to
  1239. // guarantee to our consumer that by the time we post on the "postend"
  1240. // LLEventPump, our ReadPipes are already buffering all the data there
  1241. // will ever be from the child. That lets the "postend" listener decide
  1242. // what to do with that final data.
  1243. std::string error;
  1244. for (size_t i = 0; i < mPipes.size(); ++i)
  1245. {
  1246. ReadPipeImpl* ppipe = getPipePtr<ReadPipeImpl>(error, FILESLOT(i));
  1247. if (ppipe)
  1248. {
  1249. static LLSD trivial;
  1250. ppipe->tick(trivial);
  1251. }
  1252. }
  1253. // wi->rv = apr_proc_wait(wi->child, &wi->rc, &wi->why, APR_NOWAIT);
  1254. // It is just wrong to call apr_proc_wait() here. The only way APR knows to
  1255. // call us with APR_OC_REASON_DEATH is that it has already reaped this
  1256. // child process, so calling wait() will only produce "huh ?" from the OS.
  1257. // We must rely on the status param passed in, which unfortunately comes
  1258. // straight from the OS wait() call, which means we have to decode it by
  1259. // hand.
  1260. mStatus = Status::interpretStatus(status);
  1261. llinfos << getStatusString() << llendl;
  1262. if (mPostend.empty())
  1263. {
  1264. return; // We are done
  1265. }
  1266. // If the caller requested notification on child termination, send it.
  1267. gEventPumps.obtain(mPostend).post(LLSDMap("id", getProcessID())
  1268. ("desc", mDesc)
  1269. ("state", mStatus.mState)
  1270. ("data", mStatus.mData)
  1271. ("string", getStatusString()));
  1272. }
  1273. template<class PIPETYPE>
  1274. PIPETYPE* LLProcess::getPipePtr(std::string& error, FILESLOT slot)
  1275. {
  1276. if (slot >= NSLOTS)
  1277. {
  1278. error = llformat("%s has no slot %d", mDesc.c_str(), slot);
  1279. return NULL;
  1280. }
  1281. if (mPipes.is_null(slot))
  1282. {
  1283. error = mDesc + " " + whichfile(slot) + " is not a monitored pipe";
  1284. return NULL;
  1285. }
  1286. // Make sure we dynamic_cast in pointer domain so we can test, rather than
  1287. // accepting runtime's exception.
  1288. PIPETYPE* ppipe = dynamic_cast<PIPETYPE*>(&mPipes[slot]);
  1289. if (!ppipe)
  1290. {
  1291. error = mDesc + " " + whichfile(slot) + " is not a " +
  1292. typeid(PIPETYPE).name();
  1293. return NULL;
  1294. }
  1295. error.clear();
  1296. return ppipe;
  1297. }
  1298. template <class PIPETYPE>
  1299. PIPETYPE& LLProcess::getPipe(FILESLOT slot)
  1300. {
  1301. std::string error;
  1302. PIPETYPE* wp = getPipePtr<PIPETYPE>(error, slot);
  1303. if (!wp)
  1304. {
  1305. throw NoPipe(error);
  1306. }
  1307. return *wp;
  1308. }
  1309. LLProcess::WritePipe& LLProcess::getWritePipe(FILESLOT slot)
  1310. {
  1311. return getPipe<WritePipe>(slot);
  1312. }
  1313. LLProcess::ReadPipe& LLProcess::getReadPipe(FILESLOT slot)
  1314. {
  1315. return getPipe<ReadPipe>(slot);
  1316. }
  1317. #if LL_WINDOWS
  1318. LLProcess::handle LLProcess::isRunning(handle h, const std::string& desc)
  1319. {
  1320. // This direct Windows implementation is because we have no access to the
  1321. // apr_proc_t struct: we expect it has been destroyed.
  1322. if (!h)
  1323. {
  1324. return 0;
  1325. }
  1326. DWORD waitresult = WaitForSingleObject(h, 0);
  1327. if (waitresult == WAIT_OBJECT_0)
  1328. {
  1329. // The process has completed.
  1330. if (!desc.empty())
  1331. {
  1332. DWORD status = 0;
  1333. if (!GetExitCodeProcess(h, &status))
  1334. {
  1335. llwarns << desc
  1336. << " terminated, but GetExitCodeProcess() failed with error code: "
  1337. << GetLastError() << llendl;
  1338. }
  1339. else
  1340. {
  1341. llinfos << getStatusString(desc,
  1342. Status::interpretStatus(status))
  1343. << llendl;
  1344. }
  1345. }
  1346. CloseHandle(h);
  1347. return 0;
  1348. }
  1349. return h;
  1350. }
  1351. //static
  1352. LLProcess::Status LLProcess::Status::interpretStatus(int status)
  1353. {
  1354. LLProcess::Status result;
  1355. // This bit of code is cribbed from apr/threadproc/win32/proc.c, a function
  1356. // (unfortunately static) called why_from_exit_code(). See WinNT.h
  1357. // STATUS_ACCESS_VIOLATION and family for how this class of failures was
  1358. // determined
  1359. if ((status & 0xFFFF0000) == 0xC0000000)
  1360. {
  1361. result.mState = LLProcess::KILLED;
  1362. }
  1363. else
  1364. {
  1365. result.mState = LLProcess::EXITED;
  1366. }
  1367. result.mData = status;
  1368. return result;
  1369. }
  1370. #else // Mac and linux
  1371. #include <signal.h>
  1372. #include <fcntl.h>
  1373. #include <errno.h>
  1374. #include <sys/wait.h>
  1375. // Attempts to reap a process ID. Returns true if the process has exited and
  1376. // been reaped, false otherwise.
  1377. static bool reap_pid(pid_t pid, LLProcess::Status* pstatus = NULL)
  1378. {
  1379. LLProcess::Status dummy;
  1380. if (!pstatus)
  1381. {
  1382. // If caller does not want to see Status, give us a target anyway so we
  1383. // do not have to have a bunch of conditionals.
  1384. pstatus = &dummy;
  1385. }
  1386. int status = 0;
  1387. pid_t wait_result = ::waitpid(pid, &status, WNOHANG);
  1388. if (wait_result == pid)
  1389. {
  1390. *pstatus = LLProcess::Status::interpretStatus(status);
  1391. return true;
  1392. }
  1393. if (wait_result == 0)
  1394. {
  1395. pstatus->mState = LLProcess::RUNNING;
  1396. pstatus->mData = 0;
  1397. return false;
  1398. }
  1399. // Clear caller's Status block; caller must interpret UNSTARTED to mean
  1400. // "if this PID was ever valid, it no longer is."
  1401. *pstatus = LLProcess::Status();
  1402. // We have dealt with the success cases: we were able to reap the child
  1403. // (wait_result == pid) or it is still running (wait_result == 0). It may
  1404. // be that the child terminated but did not hang around long enough for us
  1405. // to reap. In that case we still have no Status to report, but we can at
  1406. // least state that it's not running.
  1407. if (wait_result == -1 && errno == ECHILD)
  1408. {
  1409. // No such process: this may mean we are ignoring SIGCHILD.
  1410. return true;
  1411. }
  1412. // Uh, should never happen ?!
  1413. llwarns << "waitpid(" << pid << ") returned " << wait_result
  1414. << "; not meaningful ?" << llendl;
  1415. // If caller is looping until this pid terminates, and if we cannot find
  1416. // out, better to break the loop than to claim it is still running.
  1417. return true;
  1418. }
  1419. LLProcess::id LLProcess::isRunning(id pid, const std::string& desc)
  1420. {
  1421. // This direct POSIX implementation is because we have no access to the
  1422. // apr_proc_t struct: we expect it has been destroyed.
  1423. if (!pid)
  1424. {
  1425. return 0;
  1426. }
  1427. // Check whether the process has exited, and reap it if it has.
  1428. Status status;
  1429. if (reap_pid(pid, &status))
  1430. {
  1431. // The process has exited.
  1432. if (!desc.empty())
  1433. {
  1434. std::string str;
  1435. // We do not just pass UNSTARTED to getStatusString() because, in
  1436. // the context of reap_pid(), that state has special meaning.
  1437. if (status.mState != UNSTARTED)
  1438. {
  1439. str = getStatusString(desc, status);
  1440. }
  1441. else
  1442. {
  1443. str = desc + " apparently terminated: no status available";
  1444. }
  1445. llinfos << str << llendl;
  1446. }
  1447. return 0;
  1448. }
  1449. return pid;
  1450. }
  1451. //static
  1452. LLProcess::Status LLProcess::Status::interpretStatus(int status)
  1453. {
  1454. LLProcess::Status result;
  1455. if (WIFEXITED(status))
  1456. {
  1457. result.mState = LLProcess::EXITED;
  1458. result.mData = WEXITSTATUS(status);
  1459. }
  1460. else if (WIFSIGNALED(status))
  1461. {
  1462. result.mState = LLProcess::KILLED;
  1463. result.mData = WTERMSIG(status);
  1464. }
  1465. else // Should not happen
  1466. {
  1467. result.mState = LLProcess::EXITED;
  1468. result.mData = status; // Someone else will have to decode
  1469. }
  1470. return result;
  1471. }
  1472. #endif // POSIX
  1473. ///////////////////////////////////////////////////////////////////////////////
  1474. // LLLeapListener class. It is implemented in its own llleaplistener.h and
  1475. // llleaplistener.cpp files in LL's viewer, but it is only used internally to
  1476. // LLLeap, so there is no point in adding more files to the sources. HB
  1477. ///////////////////////////////////////////////////////////////////////////////
  1478. class LLLeapListener final : public LLEventAPI
  1479. {
  1480. public:
  1481. // Decouple LLLeap by dependency injection. Certain LLLeapListener
  1482. // operations must be able to cause LLLeap to listen on a specified
  1483. // LLEventPump with the LLLeap listener that wraps incoming events in an
  1484. // outer (pump=, data=) map and forwards them to the plugin. Very well,
  1485. // define the signature for a function that will perform that, and make
  1486. // our constructor accept such a function.
  1487. typedef boost::function<LLBoundListener(LLEventPump&,
  1488. const std::string& listener)>
  1489. connect_func_t;
  1490. LLLeapListener(const connect_func_t& connect);
  1491. ~LLLeapListener() override;
  1492. // The LLSD map obtained via getFeatures() is intended to be machine-
  1493. // readable (read: easily-parsed, if parsing be necessary) and to highlight
  1494. // the differences between this version of the LEAP protocol and the base
  1495. //line version. A client may thus determine whether or not the running
  1496. // viewer supports some recent feature of interest.
  1497. //
  1498. // This method is defined at the top of this implementation file so it is
  1499. // easy to find, easy to spot, easy to update as we enhance the LEAP
  1500. // protocol.
  1501. static LLSD getFeatures()
  1502. {
  1503. static LLSD features;
  1504. if (features.isUndefined())
  1505. {
  1506. // This initial implementation IS the baseline LEAP protocol; thus
  1507. // the set of differences is empty; thus features is initially
  1508. // empty. Expand with: features["featurename"] = "value";
  1509. features = LLSD::emptyMap();
  1510. }
  1511. return features;
  1512. }
  1513. private:
  1514. void newPump(const LLSD&);
  1515. void listen(const LLSD&);
  1516. void stopListening(const LLSD&);
  1517. void ping(const LLSD&) const;
  1518. void getAPIs(const LLSD&) const;
  1519. void getAPI(const LLSD&) const;
  1520. void getFeatures(const LLSD&) const;
  1521. void getFeature(const LLSD&) const;
  1522. void saveListener(const std::string& pump_name,
  1523. const std::string& listener_name,
  1524. const LLBoundListener& listener);
  1525. private:
  1526. connect_func_t mConnect;
  1527. // In theory, listen() could simply call the relevant LLEventPump's
  1528. // listen() method, stopListening() likewise. Lifespan issues make us
  1529. // capture the LLBoundListener objects: when this object goes away, all
  1530. // those listeners should be disconnected. But what if the client listens,
  1531. // stops, listens again on the same LLEventPump with the same listener
  1532. // name ? Merely collecting LLBoundListeners would not adequately track
  1533. // that. So capture the latest LLBoundListener for this LLEventPump name
  1534. // and listener name.
  1535. typedef std::map<std::pair<std::string, std::string>,
  1536. LLBoundListener> listen_map_t;
  1537. listen_map_t mListeners;
  1538. };
  1539. LLLeapListener::LLLeapListener(const connect_func_t& connect)
  1540. // Each LEAP plugin has an instance of this listener. Make the command
  1541. // pump name difficult for other such plugins to guess.
  1542. : LLEventAPI(LLUUID::generateNewID().asString(),
  1543. "Operations relating to the LLSD Event API Plugin (LEAP) protocol"),
  1544. mConnect(connect)
  1545. {
  1546. LLSD need_name(LLSDMap("name", LLSD()));
  1547. add("newpump",
  1548. "Instantiate a new LLEventPump named like [\"name\"] and listen to it.\n"
  1549. "[\"type\"] == \"LLEventStream\", \"LLEventMailDrop\" et al.\n"
  1550. "Events sent through new LLEventPump will be decorated with [\"pump\"]=name.\n"
  1551. "Returns actual name in [\"name\"] (may be different if collision).",
  1552. &LLLeapListener::newPump, need_name);
  1553. LLSD need_source_listener(LLSDMap("source", LLSD())("listener", LLSD()));
  1554. add("listen",
  1555. "Listen to an existing LLEventPump named [\"source\"], with listener name\n"
  1556. "[\"listener\"].\n"
  1557. "By default, send events on [\"source\"] to the plugin, decorated\n"
  1558. "with [\"pump\"]=[\"source\"].\n"
  1559. "If [\"dest\"] specified, send undecorated events on [\"source\"] to the\n"
  1560. "LLEventPump named [\"dest\"].\n"
  1561. "Returns [\"status\"] boolean indicating whether the connection was made.",
  1562. &LLLeapListener::listen, need_source_listener);
  1563. add("stoplistening",
  1564. "Disconnect a connection previously established by \"listen\".\n"
  1565. "Pass same [\"source\"] and [\"listener\"] arguments.\n"
  1566. "Returns [\"status\"] boolean indicating whether such a listener existed.",
  1567. &LLLeapListener::stopListening,
  1568. need_source_listener);
  1569. add("ping",
  1570. "No arguments, just a round-trip sanity check.",
  1571. &LLLeapListener::ping);
  1572. add("getAPIs",
  1573. "Enumerate all LLEventAPI instances by name and description.",
  1574. &LLLeapListener::getAPIs);
  1575. add("getAPI",
  1576. "Get name, description, dispatch key and operations for LLEventAPI [\"api\"].",
  1577. &LLLeapListener::getAPI,
  1578. LLSD().with("api", LLSD()));
  1579. add("getFeatures",
  1580. "Return an LLSD map of feature strings (deltas from baseline LEAP protocol)",
  1581. static_cast<void (LLLeapListener::*)(const LLSD&) const>(&LLLeapListener::getFeatures));
  1582. add("getFeature",
  1583. "Return the feature value with key [\"feature\"]",
  1584. &LLLeapListener::getFeature, LLSD().with("feature", LLSD()));
  1585. }
  1586. LLLeapListener::~LLLeapListener()
  1587. {
  1588. // We wouldd have stored a map of LLTempBoundListener instances, save that
  1589. // the operation of inserting into a std::map necessarily copies the
  1590. // value_type, and Bad Things would happen if you copied a
  1591. // LLTempBoundListener (destruction of the original would disconnect the
  1592. // listener, invalidating every stored connection).
  1593. for (listen_map_t::value_type& pair : mListeners)
  1594. {
  1595. pair.second.disconnect();
  1596. }
  1597. }
  1598. void LLLeapListener::newPump(const LLSD& request)
  1599. {
  1600. Response reply(LLSD(), request);
  1601. std::string name = request["name"];
  1602. std::string type = request["type"];
  1603. try
  1604. {
  1605. // Tweak the name for uniqueness
  1606. LLEventPump& new_pump(gEventPumps.make(name, true, type));
  1607. name = new_pump.getName();
  1608. reply["name"] = name;
  1609. // Now listen on this new pump with our plugin listener
  1610. std::string myname = "llleap";
  1611. saveListener(name, myname, mConnect(new_pump, myname));
  1612. }
  1613. catch (const LLEventPumps::BadType& error)
  1614. {
  1615. reply.error(error.what());
  1616. }
  1617. }
  1618. void LLLeapListener::listen(const LLSD& request)
  1619. {
  1620. Response reply(LLSD(), request);
  1621. reply["status"] = false;
  1622. std::string source_name = request["source"];
  1623. LLEventPump& source = gEventPumps.obtain(source_name);
  1624. std::string listener_name = request["listener"];
  1625. if (mListeners.count(listen_map_t::key_type(source_name,
  1626. listener_name)))
  1627. {
  1628. // We are already listening at that source...
  1629. return;
  1630. }
  1631. std::string dest_name = request["dest"];
  1632. try
  1633. {
  1634. if (request["dest"].isDefined())
  1635. {
  1636. // If we are asked to connect the "source" pump to a specific
  1637. // "dest" pump, find dest pump and connect it.
  1638. LLEventPump& dest = gEventPumps.obtain(dest_name);
  1639. saveListener(source_name, listener_name,
  1640. source.listen(listener_name,
  1641. boost::bind(&LLEventPump::post, &dest,
  1642. _1)));
  1643. }
  1644. else
  1645. {
  1646. // "dest" unspecified means to direct events on "source" to our
  1647. // plugin listener.
  1648. saveListener(source_name, listener_name,
  1649. mConnect(source, listener_name));
  1650. }
  1651. reply["status"] = true;
  1652. }
  1653. catch (const LLEventPump::DupListenerName &)
  1654. {
  1655. // Pass: status already set to false.
  1656. }
  1657. }
  1658. void LLLeapListener::stopListening(const LLSD& request)
  1659. {
  1660. Response reply(LLSD(), request);
  1661. std::string source_name = request["source"];
  1662. std::string listener_name = request["listener"];
  1663. listen_map_t::iterator it =
  1664. mListeners.find(listen_map_t::key_type(source_name, listener_name));
  1665. reply["status"] = false;
  1666. if (it != mListeners.end())
  1667. {
  1668. reply["status"] = true;
  1669. it->second.disconnect();
  1670. mListeners.erase(it);
  1671. }
  1672. }
  1673. void LLLeapListener::ping(const LLSD& request) const
  1674. {
  1675. // Do nothing, default reply suffices
  1676. Response(LLSD(), request);
  1677. }
  1678. void LLLeapListener::getAPIs(const LLSD& request) const
  1679. {
  1680. Response reply(LLSD(), request);
  1681. for (auto& ea : LLEventAPI::instance_snapshot())
  1682. {
  1683. LLSD info;
  1684. info["desc"] = ea.getDesc();
  1685. reply[ea.getName()] = info;
  1686. }
  1687. }
  1688. void LLLeapListener::getAPI(const LLSD& request) const
  1689. {
  1690. Response reply(LLSD(), request);
  1691. auto found = LLEventAPI::getNamedInstance(request["api"]);
  1692. if (found)
  1693. {
  1694. reply["name"] = found->getName();
  1695. reply["desc"] = found->getDesc();
  1696. reply["key"] = found->getDispatchKey();
  1697. LLSD ops;
  1698. for (LLEventAPI::const_iterator it = found->begin(),
  1699. end = found->end();
  1700. it != end; ++it)
  1701. {
  1702. ops.append(found->getMetadata(it->first));
  1703. }
  1704. reply["ops"] = ops;
  1705. }
  1706. }
  1707. void LLLeapListener::getFeatures(const LLSD& request) const
  1708. {
  1709. // Merely constructing and destroying a Response object suffices here.
  1710. // Giving it a name would only produce fatal 'unreferenced variable'
  1711. // warnings.
  1712. Response(getFeatures(), request);
  1713. }
  1714. void LLLeapListener::getFeature(const LLSD& request) const
  1715. {
  1716. Response reply(LLSD(), request);
  1717. LLSD::String feature_name(request["feature"]);
  1718. LLSD features(getFeatures());
  1719. if (features[feature_name].isDefined())
  1720. {
  1721. reply["feature"] = features[feature_name];
  1722. }
  1723. }
  1724. void LLLeapListener::saveListener(const std::string& pump_name,
  1725. const std::string& listener_name,
  1726. const LLBoundListener& listener)
  1727. {
  1728. mListeners.insert(
  1729. listen_map_t::value_type(listen_map_t::key_type(pump_name,
  1730. listener_name),
  1731. listener));
  1732. }
  1733. ///////////////////////////////////////////////////////////////////////////////
  1734. // LLLeap class and its LLLeapImpl
  1735. ///////////////////////////////////////////////////////////////////////////////
  1736. static std::set<std::string> sKnownInterpreters =
  1737. {
  1738. #if LL_WINDOWS
  1739. "pythonw3.exe", "pythonw.exe", "pyw.exe", "python.exe", "lua.exe", "cmd.exe"
  1740. #else
  1741. "python3", "python", "python2", "lua"
  1742. #endif
  1743. };
  1744. class LLLeapImpl final : public LLLeap
  1745. {
  1746. LOG_CLASS(LLLeapImpl);
  1747. public:
  1748. // Called only by LLLeap::create()
  1749. LLLeapImpl(const LLSD& params)
  1750. : mDonePump("LLLeap", true),
  1751. mReplyPump(LLUUID::generateNewID().asString()),
  1752. mExpect(0),
  1753. mBinaryInput(false),
  1754. mBinaryOutput(false),
  1755. mListener(new LLLeapListener(boost::bind(&LLLeapImpl::connect, this,
  1756. _1, _2)))
  1757. {
  1758. // Rule out unpopulated params block
  1759. if (!params.isMap() || !params.has("executable"))
  1760. {
  1761. throw Error("no plugin command");
  1762. }
  1763. if (params.has("desc"))
  1764. {
  1765. mDesc = params["desc"].asString();
  1766. }
  1767. // Do not leave desc empty either, but in this case, if we were not
  1768. // given one, we will fake one.
  1769. if (mDesc.empty())
  1770. {
  1771. mDesc = params["executable"].asString();
  1772. // If we are running a script for a known interpreter, use the
  1773. // script name for the desc instead of just the interpreter
  1774. // executable name.
  1775. if (params.has("args") && params["args"].isArray())
  1776. {
  1777. std::string desclower(mDesc);
  1778. LLStringUtil::toLower(desclower);
  1779. if (sKnownInterpreters.count(desclower))
  1780. {
  1781. mDesc = params["args"][0].asString();
  1782. }
  1783. }
  1784. }
  1785. // Listen for child "termination" right away to catch launch errors.
  1786. mDonePump.listen("LLLeap", boost::bind(&LLLeapImpl::badLaunch, this,
  1787. _1));
  1788. // Get a modifiable copy of params block to set files and postend.
  1789. LLSD pparams(params);
  1790. // Copy our deduced mDesc back into the params block
  1791. pparams["desc"] = mDesc;
  1792. // Pipe stdin, stdout and stderr
  1793. pparams["files"] = llsd::array("pipe", "pipe", "pipe"),
  1794. pparams["postend"] = mDonePump.getName();
  1795. mChild = LLProcess::create(pparams);
  1796. // If that did not work, no point in keeping this LLLeap object.
  1797. if (!mChild)
  1798. {
  1799. throw Error("failed to run " + mDesc);
  1800. }
  1801. // Launch apparently worked. Change our mDonePump listener.
  1802. mDonePump.stopListening("LLLeap");
  1803. mDonePump.listen("LLLeap", boost::bind(&LLLeapImpl::done, this, _1));
  1804. // Child might pump large volumes of data through either stdout or
  1805. // stderr. Do not bother copying all that data into notification event.
  1806. LLProcess::ReadPipe& childout(mChild->getReadPipe(LLProcess::STDOUT));
  1807. childout.setLimit(20);
  1808. LLProcess::ReadPipe& childerr(mChild->getReadPipe(LLProcess::STDERR));
  1809. childerr.setLimit(20);
  1810. // Serialize any event received on mReplyPump to our child's stdin.
  1811. mStdinConnection = connect(mReplyPump, "LLLeap");
  1812. // Listening on stdout is stateful. In general, we are either waiting
  1813. // for the length prefix or waiting for the specified length of data.
  1814. // We address that with two different listener methods, one of which
  1815. // is blocked at any given time.
  1816. mStdoutConnection =
  1817. childout.getPump().listen("prefix",
  1818. boost::bind(&LLLeapImpl::rstdout, this,
  1819. _1));
  1820. mStdoutDataConnection =
  1821. childout.getPump().listen("data",
  1822. boost::bind(&LLLeapImpl::rstdoutData,
  1823. this));
  1824. mBlocker.reset(new LLEventPump::Blocker(mStdoutDataConnection));
  1825. // Log anything sent up through stderr. When a typical program
  1826. // encounters an error, it writes its error message to stderr and
  1827. // terminates with nonzero exit code. In particular, the Python
  1828. // interpreter behaves that way. More generally, though, a plugin
  1829. // author can log whatever s/he wants to the viewer log using stderr.
  1830. mStderrConnection =
  1831. childerr.getPump().listen("LLLeap",
  1832. boost::bind(&LLLeapImpl::rstderr, this,
  1833. _1));
  1834. // Note: at this point, LL's implementation creates an LLError recorder
  1835. // to divert llerrs and inform the child process through its stdin when
  1836. // they occur: this is of no use to us since we only employ LLLeap with
  1837. // external plugins (which cannot use LLError by themselves) and since
  1838. // llerrs in the viewer code itself cause a voluntary crash anyway. I
  1839. // suppose this was done by LL to cover unit tests code and plugins,
  1840. // but we do not use any of these in the Cool VL Viewer. HB
  1841. // Send child a preliminary event reporting our own reply-pump name,
  1842. // which would otherwise be pretty tricky to guess !
  1843. wstdin(mReplyPump.getName(),
  1844. LLSDMap("command", mListener->getName())
  1845. // Include LLLeap features: this may be important for child to
  1846. // construct (or recognize) current protocol.
  1847. ("features", LLLeapListener::getFeatures()));
  1848. }
  1849. // Normally we would expect to arrive here only via done()
  1850. ~LLLeapImpl() override
  1851. {
  1852. LL_DEBUGS("Leap") << "Destroying LLLeap(\"" << mDesc << "\")"
  1853. << LL_ENDL;
  1854. }
  1855. // Listener for failed launch attempt
  1856. bool badLaunch(const LLSD& data)
  1857. {
  1858. llwarns << data["string"].asString() << llendl;
  1859. return false;
  1860. }
  1861. // Listener for child-process termination
  1862. bool done(const LLSD& data)
  1863. {
  1864. // Log the termination
  1865. llinfos << data["string"].asString() << llendl;
  1866. // Any leftover data at this moment are because protocol was not
  1867. // satisfied. Possibly the child was interrupted in the middle of
  1868. // sending a message, possibly the child did not flush stdout before
  1869. // terminating, possibly it is just garbage. Log its existence but
  1870. // discard it.
  1871. LLProcess::ReadPipe& childout(mChild->getReadPipe(LLProcess::STDOUT));
  1872. if (childout.size())
  1873. {
  1874. LLProcess::ReadPipe::size_type peeklen =
  1875. llmin(LLProcess::ReadPipe::size_type(50), childout.size());
  1876. llwarns << "Discarding final " << childout.size() << " bytes: "
  1877. << childout.peek(0, peeklen) << "..." << llendl;
  1878. }
  1879. // Kill this instance. MUST BE LAST before return !
  1880. delete this;
  1881. return false;
  1882. }
  1883. // Listener for events on mReplyPump: send to child stdin
  1884. bool wstdin(const std::string& pump, const LLSD& data)
  1885. {
  1886. LLSD packet(LLSDMap("pump", pump)("data", data));
  1887. std::ostringstream buffer;
  1888. if (mBinaryOutput)
  1889. {
  1890. // SL-18330: for large data blocks, it is much faster to parse
  1891. // binary LLSD than notation LLSD. Use serialize(LLSD_BINARY)
  1892. // rather than directly calling LLSDBinaryFormatter because,
  1893. // unlike the latter, serialize() prepends the relevant header,
  1894. // needed by a general-purpose LLSD parser to distinguish binary
  1895. // from notation.
  1896. LLSDSerialize::serialize(packet, buffer,
  1897. LLSDSerialize::LLSD_BINARY,
  1898. LLSDFormatter::OPTIONS_NONE);
  1899. }
  1900. else
  1901. {
  1902. buffer << LLSDNotationStreamer(packet);
  1903. }
  1904. LL_DEBUGS("Leap") << "Sending: " << (U64)buffer.tellp() << ':';
  1905. const std::streampos truncate = 80;
  1906. if (buffer.tellp() <= truncate)
  1907. {
  1908. LL_CONT << buffer.str();
  1909. }
  1910. else
  1911. {
  1912. LL_CONT << buffer.str().substr(0, truncate) << "...";
  1913. }
  1914. LL_CONT << LL_ENDL;
  1915. LLProcess::WritePipe& childin(mChild->getWritePipe(LLProcess::STDIN));
  1916. childin.get_ostream() << (U64)buffer.tellp() << ':' << buffer.str()
  1917. << std::flush;
  1918. return false;
  1919. }
  1920. // Initial state of stateful listening on child stdout: wait for a length
  1921. // prefix, followed by ':'.
  1922. bool rstdout(const LLSD& data)
  1923. {
  1924. LLProcess::ReadPipe& childout(mChild->getReadPipe(LLProcess::STDOUT));
  1925. // It's possible we got notified of a couple digit characters without
  1926. // seeing the ':' -- unlikely, but still. Until we see ':', keep
  1927. // waiting.
  1928. if (childout.contains(':'))
  1929. {
  1930. std::istream& childstream(childout.get_istream());
  1931. // Saw ':', read length prefix and store in mExpect.
  1932. size_t expect;
  1933. childstream >> expect;
  1934. int colon = childstream.get();
  1935. if ((char)colon != ':')
  1936. {
  1937. // Protocol failure. Clear out the rest of the pending data in
  1938. // childout (well, up to a max length) to log what was wrong.
  1939. LLProcess::ReadPipe::size_type readlen =
  1940. llmin(childout.size(), LLProcess::ReadPipe::size_type(80));
  1941. badProtocol(llformat("%d%c%s", expect, colon,
  1942. childout.read(readlen).c_str()));
  1943. }
  1944. else
  1945. {
  1946. // Saw length prefix, saw colon, life is good. Now wait for
  1947. // that length of data to arrive.
  1948. mExpect = expect;
  1949. LL_DEBUGS("Leap") << "Got length, waiting for "
  1950. << mExpect << " bytes of data" << LL_ENDL;
  1951. // Block calls to this method; resetting mBlocker unblocks
  1952. // calls to the other method.
  1953. mBlocker.reset(new LLEventPump::Blocker(mStdoutConnection));
  1954. // Go check if we have already received all the advertised
  1955. // data.
  1956. if (childout.size())
  1957. {
  1958. rstdoutData();
  1959. }
  1960. }
  1961. }
  1962. else if (childout.contains('\n'))
  1963. {
  1964. // Since this is the initial listening state, this is where we
  1965. // would arrive if the child is not following protocol at all; say
  1966. // because the user specified 'ls' or some darn thing.
  1967. badProtocol(childout.getline());
  1968. }
  1969. return false;
  1970. }
  1971. // State in which we listen on stdout for the specified length of data to
  1972. // arrive.
  1973. bool rstdoutData()
  1974. {
  1975. LLProcess::ReadPipe& childout(mChild->getReadPipe(LLProcess::STDOUT));
  1976. // Until we have accumulated the promised length of data, keep waiting.
  1977. if (childout.size() >= mExpect)
  1978. {
  1979. // Ready to rock and roll.
  1980. LLSD data;
  1981. bool success;
  1982. #if LL_USE_NEW_DESERIALIZE
  1983. if (mBinaryInput)
  1984. {
  1985. // SL-18330: accept any valid LLSD serialization format from
  1986. // child. Unfortunately this runs into trouble we have not yet
  1987. // debugged.
  1988. success = LLSDSerialize::deserialize(data,
  1989. childout.get_istream(),
  1990. mExpect);
  1991. }
  1992. else
  1993. #endif
  1994. {
  1995. // Specifically require notation LLSD from child.
  1996. LLPointer<LLSDParser> parser(new LLSDNotationParser());
  1997. S32 count = parser->parse(childout.get_istream(), data,
  1998. mExpect);
  1999. success = count != LLSDParser::PARSE_FAILURE;
  2000. }
  2001. if (!success)
  2002. {
  2003. badProtocol("unparseable LLSD data");
  2004. }
  2005. else if (!(data.isMap() && data["pump"].isString() &&
  2006. data.has("data")))
  2007. {
  2008. // We got an LLSD object, but it lacks required keys
  2009. badProtocol("missing 'pump' or 'data'");
  2010. }
  2011. else
  2012. {
  2013. // The LLSD object we got from our stream contains the keys we
  2014. // need.
  2015. gEventPumps.obtain(data["pump"]).post(data["data"]);
  2016. // Block calls to this method; resetting mBlocker unblocks calls
  2017. // to the other method.
  2018. mBlocker.reset(new LLEventPump::Blocker(mStdoutDataConnection));
  2019. // Go check for any more pending events in the buffer.
  2020. if (childout.size())
  2021. {
  2022. LLSD updata(data);
  2023. data["len"] = LLSD::Integer(childout.size());
  2024. rstdout(updata);
  2025. }
  2026. }
  2027. }
  2028. return false;
  2029. }
  2030. void badProtocol(const std::string& data)
  2031. {
  2032. llwarns << mDesc << ": invalid protocol: " << data << llendl;
  2033. // No point in continuing to run this child.
  2034. mChild->kill();
  2035. }
  2036. // Listen on child stderr and log everything that arrives
  2037. bool rstderr(const LLSD& data)
  2038. {
  2039. LLProcess::ReadPipe& childerr(mChild->getReadPipe(LLProcess::STDERR));
  2040. // We might have gotten a notification involving only a partial line
  2041. // or multiple lines. Read all complete lines; stop when there is only
  2042. // a partial line left.
  2043. while (childerr.contains('\n'))
  2044. {
  2045. // DO NOT make calls with side effects in a logging statement ! If
  2046. // that log level is suppressed, your side effects WOULD NOT
  2047. // HAPPEN.
  2048. std::string line(childerr.getline());
  2049. // Log the received line. Prefix it with the desc so we know which
  2050. // plugin it is from. This method name rstderr() is intentionally
  2051. // chosen to further qualify the log output.
  2052. llinfos << mDesc << ": " << line << llendl;
  2053. }
  2054. // What if child writes a final partial line to stderr ?
  2055. if (data["eof"].asBoolean() && childerr.size())
  2056. {
  2057. std::string rest(childerr.read(childerr.size()));
  2058. // Read all remaining bytes and log.
  2059. llinfos << mDesc << ": " << rest << llendl;
  2060. }
  2061. return false;
  2062. }
  2063. // To toggle binary LLSD stream from the viewer to the LEAP plugin
  2064. LL_INLINE void enableBinaryOutput(bool enable) override
  2065. {
  2066. mBinaryOutput = enable;
  2067. }
  2068. // To toggle binary LLSD stream from the LEAP plugin to the viewer (broken)
  2069. LL_INLINE void enableBinaryInput(bool enable) override
  2070. {
  2071. mBinaryInput = enable;
  2072. }
  2073. // Introspection methods overrides. HB
  2074. LL_INLINE bool binaryOutputEnabled() const override
  2075. {
  2076. return mBinaryOutput;
  2077. }
  2078. LL_INLINE bool binaryInputEnabled() const override
  2079. {
  2080. return mBinaryInput;
  2081. }
  2082. LL_INLINE const std::string& getDesc() const override
  2083. {
  2084. return mDesc;
  2085. }
  2086. LL_INLINE const std::string& getProcDesc() const override
  2087. {
  2088. return mChild ? mChild->getDesc() : LLStringUtil::null;
  2089. }
  2090. LL_INLINE const std::string& getExecutable() const override
  2091. {
  2092. return mChild ? mChild->getExecutable() : LLStringUtil::null;
  2093. }
  2094. LL_INLINE const std::string& getInterpreter() const override
  2095. {
  2096. return mChild ? mChild->getInterpreter() : LLStringUtil::null;
  2097. }
  2098. LL_INLINE const std::string& getCwd() const override
  2099. {
  2100. return mChild ? mChild->getCwd() : LLStringUtil::null;
  2101. }
  2102. // Not inlined to avoid scattering empty_vec's everywhere in the code...
  2103. LL_NO_INLINE const std::vector<std::string>& getArgs() const override
  2104. {
  2105. static const std::vector<std::string> empty_vec;
  2106. return mChild ? mChild->getArgs() : empty_vec;
  2107. }
  2108. private:
  2109. // We always want to listen on mReplyPump with wstdin(); under some
  2110. // circumstances we will also echo other LLEventPumps to the plugin.
  2111. LLBoundListener connect(LLEventPump& pump, const std::string& listener)
  2112. {
  2113. // Serialize any event received on the specified LLEventPump to our
  2114. // child's stdin, suitably enriched with the pump name on which it was
  2115. // received.
  2116. return pump.listen(listener,
  2117. boost::bind(&LLLeapImpl::wstdin, this,
  2118. pump.getName(), _1));
  2119. }
  2120. private:
  2121. std::string mDesc;
  2122. LLProcess::ptr_t mChild;
  2123. LLEventStream mDonePump;
  2124. LLEventStream mReplyPump;
  2125. LLTempBoundListener mStdinConnection;
  2126. LLTempBoundListener mStdoutConnection;
  2127. LLTempBoundListener mStdoutDataConnection;
  2128. LLTempBoundListener mStderrConnection;
  2129. std::unique_ptr<LLEventPump::Blocker> mBlocker;
  2130. std::unique_ptr<LLLeapListener> mListener;
  2131. LLProcess::ReadPipe::size_type mExpect;
  2132. bool mBinaryInput;
  2133. bool mBinaryOutput;
  2134. };
  2135. // These must follow the declaration of LLLeapImpl, so they may as well be
  2136. // last.
  2137. LLLeap* LLLeap::create(const LLSD& params, bool exc)
  2138. {
  2139. // If caller is willing to permit exceptions, just instantiate.
  2140. if (exc)
  2141. {
  2142. return new LLLeapImpl(params);
  2143. }
  2144. // Caller insists on suppressing LLLeap::Error. Very well, catch it.
  2145. try
  2146. {
  2147. return new LLLeapImpl(params);
  2148. }
  2149. catch (const LLLeap::Error&)
  2150. {
  2151. return NULL;
  2152. }
  2153. }
  2154. LLLeap* LLLeap::create(const std::string& desc,
  2155. const std::vector<std::string>& plugin, bool exc)
  2156. {
  2157. LLSD params = LLSD::emptyMap();
  2158. params["desc"] = desc;
  2159. U32 count = plugin.size();
  2160. if (count)
  2161. {
  2162. params["executable"] = plugin[0];
  2163. if (count > 1)
  2164. {
  2165. LLSD args = LLSD::emptyArray();
  2166. for (U32 i = 1; i < count; ++i)
  2167. {
  2168. args.set(LLSD::Integer(i - 1), LLSD(plugin[i]));
  2169. }
  2170. params["args"] = args;
  2171. }
  2172. }
  2173. return create(params, exc);
  2174. }
  2175. LLLeap* LLLeap::create(const std::string& desc, const std::string& plugin,
  2176. bool exc)
  2177. {
  2178. // Use LLStringUtil::getTokens() to parse the command line
  2179. return create(desc,
  2180. LLStringUtil::getTokens(plugin,
  2181. " \t\r\n", // drop_delims
  2182. "", // No keep_delims
  2183. "\"'", // Valid quotes
  2184. "\\"), // Backslash escape
  2185. exc);
  2186. }