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

552 lines
18 KiB

  1. /* Jim - A small embeddable Tcl interpreter
  2. *
  3. * Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
  4. * Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
  5. * Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
  6. * Copyright 2008 oharboe - √ėyvind Harboe - oyvind.harboe@zylin.com
  7. * Copyright 2008 Andrew Lunn <andrew@lunn.ch>
  8. * Copyright 2008 Duane Ellis <openocd@duaneellis.com>
  9. * Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
  10. *
  11. * The FreeBSD license
  12. *
  13. * Redistribution and use in source and binary forms, with or without
  14. * modification, are permitted provided that the following conditions
  15. * are met:
  16. *
  17. * 1. Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. * 2. Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials
  22. * provided with the distribution.
  23. *
  24. * THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
  25. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  26. * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  27. * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  28. * JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  29. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  30. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  31. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  32. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  33. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  34. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  35. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  36. *
  37. * The views and conclusions contained in the software and documentation
  38. * are those of the authors and should not be interpreted as representing
  39. * official policies, either expressed or implied, of the Jim Tcl Project.
  40. **/
  41. /* TODO:
  42. *
  43. * - to really use flags in Jim_ProcessEvents()
  44. * - more complete [after] command with [after info] and other subcommands.
  45. * - Win32 port
  46. */
  47. #define JIM_EXTENSION
  48. #define __JIM_EVENTLOOP_CORE__
  49. #ifdef __ECOS
  50. #include <pkgconf/jimtcl.h>
  51. #endif
  52. #ifdef __ECOS
  53. #include <cyg/jimtcl/jim.h>
  54. #include <cyg/jimtcl/jim-eventloop.h>
  55. #else
  56. #include "jim.h"
  57. #include "jim-eventloop.h"
  58. #endif
  59. /* POSIX includes */
  60. #include <sys/time.h>
  61. #include <sys/types.h>
  62. #include <unistd.h>
  63. #include <errno.h>
  64. #include "replacements.h"
  65. /* --- */
  66. /* File event structure */
  67. typedef struct Jim_FileEvent {
  68. void *handle;
  69. int mask; /* one of JIM_EVENT_(READABLE|WRITABLE|EXCEPTION) */
  70. Jim_FileProc *fileProc;
  71. Jim_EventFinalizerProc *finalizerProc;
  72. void *clientData;
  73. struct Jim_FileEvent *next;
  74. } Jim_FileEvent;
  75. /* Time event structure */
  76. typedef struct Jim_TimeEvent {
  77. jim_wide id; /* time event identifier. */
  78. int mode; /* restart, repetitive .. UK */
  79. long initialms; /* initial relativ timer value UK */
  80. long when_sec; /* seconds */
  81. long when_ms; /* milliseconds */
  82. Jim_TimeProc *timeProc;
  83. Jim_EventFinalizerProc *finalizerProc;
  84. void *clientData;
  85. struct Jim_TimeEvent *next;
  86. } Jim_TimeEvent;
  87. /* Per-interp stucture containing the state of the event loop */
  88. typedef struct Jim_EventLoop {
  89. jim_wide timeEventNextId;
  90. Jim_FileEvent *fileEventHead;
  91. Jim_TimeEvent *timeEventHead;
  92. } Jim_EventLoop;
  93. void Jim_CreateFileHandler(Jim_Interp *interp, void *handle, int mask,
  94. Jim_FileProc *proc, void *clientData,
  95. Jim_EventFinalizerProc *finalizerProc)
  96. {
  97. Jim_FileEvent *fe;
  98. Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
  99. // fprintf(stderr,"rein\n");
  100. fe = Jim_Alloc(sizeof(*fe));
  101. fe->handle = handle;
  102. fe->mask = mask;
  103. fe->fileProc = proc;
  104. fe->finalizerProc = finalizerProc;
  105. fe->clientData = clientData;
  106. fe->next = eventLoop->fileEventHead;
  107. eventLoop->fileEventHead = fe;
  108. // fprintf(stderr,"raus\n");
  109. }
  110. void Jim_DeleteFileHandler(Jim_Interp *interp, void *handle)
  111. {
  112. Jim_FileEvent *fe, *prev = NULL;
  113. Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
  114. fe = eventLoop->fileEventHead;
  115. while(fe) {
  116. if (fe->handle == handle) {
  117. if (prev == NULL)
  118. eventLoop->fileEventHead = fe->next;
  119. else
  120. prev->next = fe->next;
  121. if (fe->finalizerProc)
  122. fe->finalizerProc(interp, fe->clientData);
  123. Jim_Free(fe);
  124. return;
  125. }
  126. prev = fe;
  127. fe = fe->next;
  128. }
  129. }
  130. // The same for signals.
  131. void Jim_CreateSignalHandler(Jim_Interp *interp, int signum,
  132. Jim_FileProc *proc, void *clientData,
  133. Jim_EventFinalizerProc *finalizerProc)
  134. {
  135. }
  136. void Jim_DeleteSignalHandler(Jim_Interp *interp, int signum)
  137. {
  138. }
  139. /* That's another part of this extension that needs to be ported
  140. * to WIN32. */
  141. static void JimGetTime(long *seconds, long *milliseconds)
  142. {
  143. struct timeval tv;
  144. gettimeofday(&tv, NULL);
  145. *seconds = tv.tv_sec;
  146. *milliseconds = tv.tv_usec/1000;
  147. }
  148. jim_wide Jim_CreateTimeHandler(Jim_Interp *interp, jim_wide milliseconds,
  149. Jim_TimeProc *proc, void *clientData,
  150. Jim_EventFinalizerProc *finalizerProc)
  151. {
  152. Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
  153. jim_wide id = eventLoop->timeEventNextId++;
  154. Jim_TimeEvent *te;
  155. long cur_sec, cur_ms;
  156. JimGetTime(&cur_sec, &cur_ms);
  157. te = Jim_Alloc(sizeof(*te));
  158. te->id = id;
  159. te->mode = 0;
  160. te->initialms = milliseconds;
  161. te->when_sec = cur_sec + milliseconds/1000;
  162. te->when_ms = cur_ms + milliseconds%1000;
  163. if (te->when_ms >= 1000) {
  164. te->when_sec ++;
  165. te->when_ms -= 1000;
  166. }
  167. te->timeProc = proc;
  168. te->finalizerProc = finalizerProc;
  169. te->clientData = clientData;
  170. te->next = eventLoop->timeEventHead;
  171. eventLoop->timeEventHead = te;
  172. return id;
  173. }
  174. jim_wide Jim_DeleteTimeHandler(Jim_Interp *interp, jim_wide id)
  175. {
  176. Jim_TimeEvent *te, *prev = NULL;
  177. Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
  178. long cur_sec, cur_ms;
  179. jim_wide remain ;
  180. JimGetTime(&cur_sec, &cur_ms);
  181. te = eventLoop->timeEventHead;
  182. if (id >= eventLoop->timeEventNextId)
  183. return -2; /* wrong event ID */
  184. while(te) {
  185. if (te->id == id) {
  186. remain = (te->when_sec - cur_sec) * 1000;
  187. remain += (te->when_ms - cur_ms) ;
  188. remain = (remain < 0) ? 0 : remain ;
  189. if (prev == NULL)
  190. eventLoop->timeEventHead = te->next;
  191. else
  192. prev->next = te->next;
  193. if (te->finalizerProc)
  194. te->finalizerProc(interp, te->clientData);
  195. Jim_Free(te);
  196. return remain;
  197. }
  198. prev = te;
  199. te = te->next;
  200. }
  201. return -1; /* NO event with the specified ID found */
  202. }
  203. /* Search the first timer to fire.
  204. * This operation is useful to know how many time the select can be
  205. * put in sleep without to delay any event.
  206. * If there are no timers NULL is returned. */
  207. static Jim_TimeEvent *JimSearchNearestTimer(Jim_EventLoop *eventLoop)
  208. {
  209. Jim_TimeEvent *te = eventLoop->timeEventHead;
  210. Jim_TimeEvent *nearest = NULL;
  211. while(te) {
  212. if (!nearest || te->when_sec < nearest->when_sec ||
  213. (te->when_sec == nearest->when_sec &&
  214. te->when_ms < nearest->when_ms))
  215. nearest = te;
  216. te = te->next;
  217. }
  218. return nearest;
  219. }
  220. /* --- POSIX version of Jim_ProcessEvents, for now the only available --- */
  221. #define JIM_FILE_EVENTS 1
  222. #define JIM_TIME_EVENTS 2
  223. #define JIM_ALL_EVENTS (JIM_FILE_EVENTS|JIM_TIME_EVENTS)
  224. #define JIM_DONT_WAIT 4
  225. /* Process every pending time event, then every pending file event
  226. * (that may be registered by time event callbacks just processed).
  227. * Without special flags the function sleeps until some file event
  228. * fires, or when the next time event occurrs (if any).
  229. *
  230. * If flags is 0, the function does nothing and returns.
  231. * if flags has JIM_ALL_EVENTS set, all the kind of events are processed.
  232. * if flags has JIM_FILE_EVENTS set, file events are processed.
  233. * if flags has JIM_TIME_EVENTS set, time events are processed.
  234. * if flags has JIM_DONT_WAIT set the function returns ASAP until all
  235. * the events that's possible to process without to wait are processed.
  236. *
  237. * The function returns the number of events processed. */
  238. int Jim_ProcessEvents(Jim_Interp *interp, int flags)
  239. {
  240. int maxfd = 0, numfd = 0, processed = 0;
  241. fd_set rfds, wfds, efds;
  242. Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
  243. Jim_FileEvent *fe = eventLoop->fileEventHead;
  244. Jim_TimeEvent *te;
  245. jim_wide maxId;
  246. JIM_NOTUSED(flags);
  247. FD_ZERO(&rfds);
  248. FD_ZERO(&wfds);
  249. FD_ZERO(&efds);
  250. /* Check file events */
  251. while (fe != NULL) {
  252. int fd = fileno((FILE*)fe->handle);
  253. if (fe->mask & JIM_EVENT_READABLE)
  254. FD_SET(fd, &rfds);
  255. if (fe->mask & JIM_EVENT_WRITABLE) FD_SET(fd, &wfds);
  256. if (fe->mask & JIM_EVENT_EXCEPTION) FD_SET(fd, &efds);
  257. if (maxfd < fd) maxfd = fd;
  258. numfd++;
  259. fe = fe->next;
  260. }
  261. /* Note that we want call select() even if there are no
  262. * file events to process as long as we want to process time
  263. * events, in order to sleep until the next time event is ready
  264. * to fire. */
  265. if (numfd || ((flags & JIM_TIME_EVENTS) && !(flags & JIM_DONT_WAIT))) {
  266. int retval;
  267. Jim_TimeEvent *shortest;
  268. struct timeval tv, *tvp;
  269. jim_wide dt;
  270. shortest = JimSearchNearestTimer(eventLoop);
  271. if (shortest) {
  272. long now_sec, now_ms;
  273. /* Calculate the time missing for the nearest
  274. * timer to fire. */
  275. JimGetTime(&now_sec, &now_ms);
  276. tvp = &tv;
  277. dt = 1000 * (shortest->when_sec - now_sec);
  278. dt += ( shortest->when_ms - now_ms);
  279. if (dt < 0) {
  280. dt = 1;
  281. }
  282. tvp->tv_sec = dt / 1000;
  283. tvp->tv_usec = dt % 1000;
  284. // fprintf(stderr,"Next %d.% 8d\n",(int)tvp->tv_sec,(int)tvp->tv_usec);
  285. } else {
  286. tvp = NULL; /* wait forever */
  287. // fprintf(stderr,"No Event\n");
  288. }
  289. retval = select(maxfd+1, &rfds, &wfds, &efds, tvp);
  290. if (retval < 0) {
  291. switch (errno) {
  292. case EINTR: fprintf(stderr,"select EINTR\n"); break;
  293. case EINVAL: fprintf(stderr,"select EINVAL\n"); break;
  294. case ENOMEM: fprintf(stderr,"select ENOMEM\n"); break;
  295. }
  296. } else if (retval > 0) {
  297. fe = eventLoop->fileEventHead;
  298. while(fe != NULL) {
  299. int fd = fileno((FILE*)fe->handle);
  300. // fprintf(stderr,"fd: %d mask: %02x \n",fd,fe->mask);
  301. if ((fe->mask & JIM_EVENT_READABLE && FD_ISSET(fd, &rfds)) ||
  302. (fe->mask & JIM_EVENT_WRITABLE && FD_ISSET(fd, &wfds)) ||
  303. (fe->mask & JIM_EVENT_EXCEPTION && FD_ISSET(fd, &efds)))
  304. {
  305. int mask = 0;
  306. if (fe->mask & JIM_EVENT_READABLE && FD_ISSET(fd, &rfds)) {
  307. mask |= JIM_EVENT_READABLE;
  308. if ((fe->mask & JIM_EVENT_FEOF) && feof((FILE *)fe->handle))
  309. mask |= JIM_EVENT_FEOF;
  310. }
  311. if (fe->mask & JIM_EVENT_WRITABLE && FD_ISSET(fd, &wfds))
  312. mask |= JIM_EVENT_WRITABLE;
  313. if (fe->mask & JIM_EVENT_EXCEPTION && FD_ISSET(fd, &efds))
  314. mask |= JIM_EVENT_EXCEPTION;
  315. if (fe->fileProc(interp, fe->clientData, mask) == JIM_ERR) {
  316. /* Remove the element on handler error */
  317. Jim_DeleteFileHandler(interp, fe->handle);
  318. }
  319. processed++;
  320. /* After an event is processed our file event list
  321. * may no longer be the same, so what we do
  322. * is to clear the bit for this file descriptor and
  323. * restart again from the head. */
  324. fe = eventLoop->fileEventHead;
  325. FD_CLR(fd, &rfds);
  326. FD_CLR(fd, &wfds);
  327. FD_CLR(fd, &efds);
  328. } else {
  329. fe = fe->next;
  330. }
  331. }
  332. }
  333. }
  334. /* Check time events */
  335. te = eventLoop->timeEventHead;
  336. maxId = eventLoop->timeEventNextId-1;
  337. while(te) {
  338. long now_sec, now_ms;
  339. jim_wide id;
  340. if (te->id > maxId) {
  341. te = te->next;
  342. continue;
  343. }
  344. JimGetTime(&now_sec, &now_ms);
  345. if (now_sec > te->when_sec ||
  346. (now_sec == te->when_sec && now_ms >= te->when_ms))
  347. {
  348. id = te->id;
  349. te->timeProc(interp, te->clientData);
  350. /* After an event is processed our time event list may
  351. * no longer be the same, so we restart from head.
  352. * Still we make sure to don't process events registered
  353. * by event handlers itself in order to don't loop forever
  354. * even in case an [after 0] that continuously register
  355. * itself. To do so we saved the max ID we want to handle. */
  356. Jim_DeleteTimeHandler(interp, id);
  357. te = eventLoop->timeEventHead;
  358. } else {
  359. te = te->next;
  360. }
  361. }
  362. return processed;
  363. }
  364. /* ---------------------------------------------------------------------- */
  365. void JimELAssocDataDeleProc(Jim_Interp *interp, void *data)
  366. {
  367. void *next;
  368. Jim_FileEvent *fe;
  369. Jim_TimeEvent *te;
  370. Jim_EventLoop *eventLoop = data;
  371. fe = eventLoop->fileEventHead;
  372. while(fe) {
  373. next = fe->next;
  374. if (fe->finalizerProc)
  375. fe->finalizerProc(interp, fe->clientData);
  376. Jim_Free(fe);
  377. fe = next;
  378. }
  379. te = eventLoop->timeEventHead;
  380. while(te) {
  381. next = te->next;
  382. if (te->finalizerProc)
  383. te->finalizerProc(interp, te->clientData);
  384. Jim_Free(te);
  385. te = next;
  386. }
  387. Jim_Free(data);
  388. }
  389. static int JimELVwaitCommand(Jim_Interp *interp, int argc,
  390. Jim_Obj *const *argv)
  391. {
  392. Jim_Obj *oldValue;
  393. if (argc != 2) {
  394. Jim_WrongNumArgs(interp, 1, argv, "name");
  395. return JIM_ERR;
  396. }
  397. oldValue = Jim_GetGlobalVariable(interp, argv[1], JIM_NONE);
  398. if (oldValue) Jim_IncrRefCount(oldValue);
  399. while (1) {
  400. Jim_Obj *currValue;
  401. Jim_ProcessEvents(interp, JIM_ALL_EVENTS);
  402. currValue = Jim_GetGlobalVariable(interp, argv[1], JIM_NONE);
  403. /* Stop the loop if the vwait-ed variable changed value,
  404. * or if was unset and now is set (or the contrary). */
  405. if ((oldValue && !currValue) ||
  406. (!oldValue && currValue) ||
  407. (oldValue && currValue &&
  408. !Jim_StringEqObj(oldValue, currValue, JIM_CASESENS)))
  409. break;
  410. }
  411. if (oldValue) Jim_DecrRefCount(interp, oldValue);
  412. return JIM_OK;
  413. }
  414. void JimAfterTimeHandler(Jim_Interp *interp, void *clientData)
  415. {
  416. Jim_Obj *objPtr = clientData;
  417. Jim_EvalObjBackground(interp, objPtr);
  418. }
  419. void JimAfterTimeEventFinalizer(Jim_Interp *interp, void *clientData)
  420. {
  421. Jim_Obj *objPtr = clientData;
  422. Jim_DecrRefCount(interp, objPtr);
  423. }
  424. static int JimELAfterCommand(Jim_Interp *interp, int argc,
  425. Jim_Obj *const *argv)
  426. {
  427. jim_wide ms, id;
  428. Jim_Obj *objPtr, *idObjPtr;
  429. const char *options[] = {
  430. "info", "cancel", "restart", "expire", NULL
  431. };
  432. enum {INFO, CANCEL, RESTART, EXPIRE, CREATE };
  433. int option = CREATE ;
  434. if (argc < 3) {
  435. Jim_WrongNumArgs(interp, 1, argv, "<after milliseconds> script");
  436. return JIM_ERR;
  437. }
  438. if (Jim_GetWide(interp, argv[1], &ms) != JIM_OK)
  439. if (Jim_GetEnum(interp, argv[1], options, &option, "after options",
  440. JIM_ERRMSG) != JIM_OK)
  441. return JIM_ERR;
  442. switch (option) {
  443. case CREATE:
  444. Jim_IncrRefCount(argv[2]);
  445. id = Jim_CreateTimeHandler(interp, ms, JimAfterTimeHandler, argv[2],
  446. JimAfterTimeEventFinalizer);
  447. objPtr = Jim_NewStringObj(interp, NULL, 0);
  448. Jim_AppendString(interp, objPtr, "after#", -1);
  449. idObjPtr = Jim_NewIntObj(interp, id);
  450. Jim_IncrRefCount(idObjPtr);
  451. Jim_AppendObj(interp, objPtr, idObjPtr);
  452. Jim_DecrRefCount(interp, idObjPtr);
  453. Jim_SetResult(interp, objPtr);
  454. return JIM_OK;
  455. case CANCEL:
  456. {
  457. int tlen ;
  458. jim_wide remain = 0;
  459. const char *tok = Jim_GetString(argv[2], &tlen);
  460. if ( sscanf(tok,"after#%lld",&id) == 1) {
  461. remain = Jim_DeleteTimeHandler(interp, id);
  462. if (remain > -2) {
  463. Jim_SetResult(interp, Jim_NewIntObj(interp, remain));
  464. return JIM_OK;
  465. }
  466. }
  467. Jim_SetResultString(interp, "invalid event" , -1);
  468. return JIM_ERR;
  469. }
  470. default:
  471. fprintf(stderr,"unserviced option to after %d\n",option);
  472. }
  473. return JIM_OK;
  474. }
  475. /* This extension is not dynamically loaded, instead it's linked statically,
  476. which is why we shouldn't use the unspecific 'Jim_OnLoad' name */
  477. int Jim_EventLoopOnLoad(Jim_Interp *interp)
  478. {
  479. Jim_EventLoop *eventLoop;
  480. Jim_InitExtension(interp);
  481. if (Jim_PackageProvide(interp, "eventloop", "1.0", JIM_ERRMSG) != JIM_OK)
  482. return JIM_ERR;
  483. eventLoop = Jim_Alloc(sizeof(*eventLoop));
  484. eventLoop->fileEventHead = NULL;
  485. eventLoop->timeEventHead = NULL;
  486. eventLoop->timeEventNextId = 1;
  487. Jim_SetAssocData(interp, "eventloop", JimELAssocDataDeleProc, eventLoop);
  488. Jim_CreateCommand(interp, "vwait", JimELVwaitCommand, NULL, NULL);
  489. Jim_CreateCommand(interp, "after", JimELAfterCommand, NULL, NULL);
  490. /* Export events API */
  491. Jim_RegisterApi(interp, "Jim_CreateFileHandler", Jim_CreateFileHandler);
  492. Jim_RegisterApi(interp, "Jim_DeleteFileHandler", Jim_DeleteFileHandler);
  493. Jim_RegisterApi(interp, "Jim_CreateTimeHandler", Jim_CreateTimeHandler);
  494. Jim_RegisterApi(interp, "Jim_DeleteTimeHandler", Jim_DeleteTimeHandler);
  495. Jim_RegisterApi(interp, "Jim_ProcessEvents", Jim_ProcessEvents);
  496. return JIM_OK;
  497. }