2 /* Jim - A small embeddable Tcl interpreter
4 * Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
5 * Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
6 * Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
7 * Copyright 2008 oharboe - Øyvind Harboe - oyvind.harboe@zylin.com
8 * Copyright 2008 Andrew Lunn <andrew@lunn.ch>
9 * Copyright 2008 Duane Ellis <openocd@duaneellis.com>
10 * Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above
19 * copyright notice, this list of conditions and the following
20 * disclaimer in the documentation and/or other materials
21 * provided with the distribution.
23 * THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
24 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
25 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
26 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 * JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
28 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
32 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
34 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 * The views and conclusions contained in the software and documentation
37 * are those of the authors and should not be interpreted as representing
38 * official policies, either expressed or implied, of the Jim Tcl Project.
42 #include "jimautoconf.h"
43 #include "jim-eventloop.h"
47 #include <sys/types.h>
52 #if defined(__MINGW32__)
57 #include <sys/select.h>
60 /* XXX: Implement this in terms of select() or nanosleep() */
63 #define msleep(MS) sleep((MS) / 1000); usleep(((MS) % 1000) * 1000);
68 /* File event structure */
69 typedef struct Jim_FileEvent
72 int mask
; /* one of JIM_EVENT_(READABLE|WRITABLE|EXCEPTION) */
73 Jim_FileProc
*fileProc
;
74 Jim_EventFinalizerProc
*finalizerProc
;
76 struct Jim_FileEvent
*next
;
79 /* Time event structure */
80 typedef struct Jim_TimeEvent
82 jim_wide id
; /* time event identifier. */
83 int mode
; /* restart, repetitive .. UK */
84 long initialms
; /* initial relativ timer value UK */
85 long when_sec
; /* seconds */
86 long when_ms
; /* milliseconds */
87 Jim_TimeProc
*timeProc
;
88 Jim_EventFinalizerProc
*finalizerProc
;
90 struct Jim_TimeEvent
*next
;
93 /* Per-interp stucture containing the state of the event loop */
94 typedef struct Jim_EventLoop
96 jim_wide timeEventNextId
;
97 Jim_FileEvent
*fileEventHead
;
98 Jim_TimeEvent
*timeEventHead
;
99 int suppress_bgerror
; /* bgerror returned break, so don't call it again */
102 static void JimAfterTimeHandler(Jim_Interp
*interp
, void *clientData
);
103 static void JimAfterTimeEventFinalizer(Jim_Interp
*interp
, void *clientData
);
105 int Jim_EvalObjBackground(Jim_Interp
*interp
, Jim_Obj
*scriptObjPtr
)
107 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
108 Jim_CallFrame
*savedFramePtr
;
111 savedFramePtr
= interp
->framePtr
;
112 interp
->framePtr
= interp
->topFramePtr
;
113 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
114 interp
->framePtr
= savedFramePtr
;
115 /* Try to report the error (if any) via the bgerror proc */
116 if (retval
!= JIM_OK
&& !eventLoop
->suppress_bgerror
) {
120 objv
[0] = Jim_NewStringObj(interp
, "bgerror", -1);
121 objv
[1] = Jim_GetResult(interp
);
122 Jim_IncrRefCount(objv
[0]);
123 Jim_IncrRefCount(objv
[1]);
124 if (Jim_GetCommand(interp
, objv
[0], JIM_NONE
) == NULL
|| (rc
= Jim_EvalObjVector(interp
, 2, objv
)) != JIM_OK
) {
125 if (rc
== JIM_BREAK
) {
126 /* No more bgerror calls */
127 eventLoop
->suppress_bgerror
++;
130 /* Report the error to stderr. */
131 Jim_MakeErrorMessage(interp
);
132 fprintf(stderr
, "%s\n", Jim_String(Jim_GetResult(interp
)));
133 /* And reset the result */
134 Jim_SetResultString(interp
, "", -1);
137 Jim_DecrRefCount(interp
, objv
[0]);
138 Jim_DecrRefCount(interp
, objv
[1]);
144 void Jim_CreateFileHandler(Jim_Interp
*interp
, FILE * handle
, int mask
,
145 Jim_FileProc
* proc
, void *clientData
, Jim_EventFinalizerProc
* finalizerProc
)
148 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
150 fe
= Jim_Alloc(sizeof(*fe
));
154 fe
->finalizerProc
= finalizerProc
;
155 fe
->clientData
= clientData
;
156 fe
->next
= eventLoop
->fileEventHead
;
157 eventLoop
->fileEventHead
= fe
;
160 void Jim_DeleteFileHandler(Jim_Interp
*interp
, FILE * handle
)
162 Jim_FileEvent
*fe
, *prev
= NULL
;
163 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
165 fe
= eventLoop
->fileEventHead
;
167 if (fe
->handle
== handle
) {
169 eventLoop
->fileEventHead
= fe
->next
;
171 prev
->next
= fe
->next
;
172 if (fe
->finalizerProc
)
173 fe
->finalizerProc(interp
, fe
->clientData
);
182 static void JimGetTime(long *seconds
, long *milliseconds
)
186 gettimeofday(&tv
, NULL
);
187 *seconds
= tv
.tv_sec
;
188 *milliseconds
= tv
.tv_usec
/ 1000;
191 jim_wide
Jim_CreateTimeHandler(Jim_Interp
*interp
, jim_wide milliseconds
,
192 Jim_TimeProc
* proc
, void *clientData
, Jim_EventFinalizerProc
* finalizerProc
)
194 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
195 jim_wide id
= eventLoop
->timeEventNextId
++;
196 Jim_TimeEvent
*te
, *e
, *prev
;
197 long cur_sec
, cur_ms
;
199 JimGetTime(&cur_sec
, &cur_ms
);
201 te
= Jim_Alloc(sizeof(*te
));
204 te
->initialms
= milliseconds
;
205 te
->when_sec
= cur_sec
+ milliseconds
/ 1000;
206 te
->when_ms
= cur_ms
+ milliseconds
% 1000;
207 if (te
->when_ms
>= 1000) {
212 te
->finalizerProc
= finalizerProc
;
213 te
->clientData
= clientData
;
215 /* Add to the appropriate place in the list */
216 if (eventLoop
->timeEventHead
) {
218 for (e
= eventLoop
->timeEventHead
; e
; e
= e
->next
) {
219 if (te
->when_sec
< e
->when_sec
|| (te
->when_sec
== e
->when_sec
&& te
->when_ms
< e
->when_ms
)) {
225 te
->next
= prev
->next
;
231 te
->next
= eventLoop
->timeEventHead
;
232 eventLoop
->timeEventHead
= te
;
237 static jim_wide
JimParseAfterId(Jim_Obj
*idObj
)
240 const char *tok
= Jim_GetString(idObj
, &len
);
243 if (strncmp(tok
, "after#", 6) == 0 && Jim_StringToWide(tok
+ 6, &id
, 10) == JIM_OK
) {
244 /* Got an event by id */
250 static jim_wide
JimFindAfterByScript(Jim_EventLoop
*eventLoop
, Jim_Obj
*scriptObj
)
254 for (te
= eventLoop
->timeEventHead
; te
; te
= te
->next
) {
255 /* Is this an 'after' event? */
256 if (te
->timeProc
== JimAfterTimeHandler
) {
257 if (Jim_StringEqObj(scriptObj
, te
->clientData
)) {
262 return -1; /* NO event with the specified ID found */
265 static Jim_TimeEvent
*JimFindTimeHandlerById(Jim_EventLoop
*eventLoop
, jim_wide id
)
269 for (te
= eventLoop
->timeEventHead
; te
; te
= te
->next
) {
277 static Jim_TimeEvent
*Jim_RemoveTimeHandler(Jim_EventLoop
*eventLoop
, jim_wide id
)
279 Jim_TimeEvent
*te
, *prev
= NULL
;
281 for (te
= eventLoop
->timeEventHead
; te
; te
= te
->next
) {
284 eventLoop
->timeEventHead
= te
->next
;
286 prev
->next
= te
->next
;
294 static void Jim_FreeTimeHandler(Jim_Interp
*interp
, Jim_TimeEvent
*te
)
296 if (te
->finalizerProc
)
297 te
->finalizerProc(interp
, te
->clientData
);
301 jim_wide
Jim_DeleteTimeHandler(Jim_Interp
*interp
, jim_wide id
)
304 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
306 if (id
>= eventLoop
->timeEventNextId
) {
307 return -2; /* wrong event ID */
310 te
= Jim_RemoveTimeHandler(eventLoop
, id
);
313 long cur_sec
, cur_ms
;
315 JimGetTime(&cur_sec
, &cur_ms
);
317 remain
= (te
->when_sec
- cur_sec
) * 1000;
318 remain
+= (te
->when_ms
- cur_ms
);
319 remain
= (remain
< 0) ? 0 : remain
;
321 Jim_FreeTimeHandler(interp
, te
);
324 return -1; /* NO event with the specified ID found */
327 /* --- POSIX version of Jim_ProcessEvents, for now the only available --- */
329 /* Process every pending time event, then every pending file event
330 * (that may be registered by time event callbacks just processed).
331 * Without special flags the function sleeps until some file event
332 * fires, or when the next time event occurrs (if any).
334 * If flags is 0, the function does nothing and returns.
335 * if flags has JIM_ALL_EVENTS set, all the kind of events are processed.
336 * if flags has JIM_FILE_EVENTS set, file events are processed.
337 * if flags has JIM_TIME_EVENTS set, time events are processed.
338 * if flags has JIM_DONT_WAIT set the function returns ASAP until all
339 * the events that's possible to process without to wait are processed.
341 * The function returns the number of events processed or -1 if
342 * there are no matching handlers, or -2 on error.
344 int Jim_ProcessEvents(Jim_Interp
*interp
, int flags
)
346 jim_wide sleep_ms
= -1;
347 int maxfd
= -1, numfd
= 0, processed
= 0;
348 fd_set rfds
, wfds
, efds
;
349 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
350 Jim_FileEvent
*fe
= eventLoop
->fileEventHead
;
354 if ((flags
& JIM_FILE_EVENTS
) == 0 || fe
== NULL
) {
356 if ((flags
& JIM_TIME_EVENTS
) == 0 || eventLoop
->timeEventHead
== NULL
) {
362 if (flags
& JIM_FILE_EVENTS
) {
367 /* Check file events */
369 int fd
= fileno(fe
->handle
);
371 if (fe
->mask
& JIM_EVENT_READABLE
)
373 if (fe
->mask
& JIM_EVENT_WRITABLE
)
375 if (fe
->mask
& JIM_EVENT_EXCEPTION
)
384 /* Note that we want call select() even if there are no
385 * file events to process as long as we want to process time
386 * events, in order to sleep until the next time event is ready
389 if (flags
& JIM_DONT_WAIT
) {
393 else if (flags
& JIM_TIME_EVENTS
) {
394 /* The nearest timer is always at the head of the list */
395 if (eventLoop
->timeEventHead
) {
396 Jim_TimeEvent
*shortest
= eventLoop
->timeEventHead
;
397 long now_sec
, now_ms
;
399 /* Calculate the time missing for the nearest
401 JimGetTime(&now_sec
, &now_ms
);
402 sleep_ms
= 1000 * (shortest
->when_sec
- now_sec
) + (shortest
->when_ms
- now_ms
);
414 /* Some systems (mingw) can't select() in this case, so convert to a simple sleep */
421 struct timeval tv
, *tvp
= NULL
;
424 tvp
->tv_sec
= sleep_ms
/ 1000;
425 tvp
->tv_usec
= 1000 * (sleep_ms
% 1000);
428 retval
= select(maxfd
+ 1, &rfds
, &wfds
, &efds
, tvp
);
431 if (errno
== EINVAL
) {
432 /* This can happen on mingw32 if a non-socket filehandle is passed */
433 Jim_SetResultString(interp
, "non-waitable filehandle", -1);
436 /* XXX: What about EINTR? */
438 else if (retval
> 0) {
439 fe
= eventLoop
->fileEventHead
;
441 int fd
= fileno(fe
->handle
);
443 if ((fe
->mask
& JIM_EVENT_READABLE
&& FD_ISSET(fd
, &rfds
)) ||
444 (fe
->mask
& JIM_EVENT_WRITABLE
&& FD_ISSET(fd
, &wfds
)) ||
445 (fe
->mask
& JIM_EVENT_EXCEPTION
&& FD_ISSET(fd
, &efds
))) {
448 if ((fe
->mask
& JIM_EVENT_READABLE
) && FD_ISSET(fd
, &rfds
)) {
449 mask
|= JIM_EVENT_READABLE
;
450 if ((fe
->mask
& JIM_EVENT_FEOF
) && feof(fe
->handle
))
451 mask
|= JIM_EVENT_FEOF
;
453 if (fe
->mask
& JIM_EVENT_WRITABLE
&& FD_ISSET(fd
, &wfds
))
454 mask
|= JIM_EVENT_WRITABLE
;
455 if (fe
->mask
& JIM_EVENT_EXCEPTION
&& FD_ISSET(fd
, &efds
))
456 mask
|= JIM_EVENT_EXCEPTION
;
457 if (fe
->fileProc(interp
, fe
->clientData
, mask
) != JIM_OK
) {
458 /* Remove the element on handler error */
459 Jim_DeleteFileHandler(interp
, fe
->handle
);
462 /* After an event is processed our file event list
463 * may no longer be the same, so what we do
464 * is to clear the bit for this file descriptor and
465 * restart again from the head. */
466 fe
= eventLoop
->fileEventHead
;
478 /* Check time events */
479 te
= eventLoop
->timeEventHead
;
480 maxId
= eventLoop
->timeEventNextId
- 1;
482 long now_sec
, now_ms
;
485 if (te
->id
> maxId
) {
489 JimGetTime(&now_sec
, &now_ms
);
490 if (now_sec
> te
->when_sec
|| (now_sec
== te
->when_sec
&& now_ms
>= te
->when_ms
)) {
492 /* Remove from the list before executing */
493 Jim_RemoveTimeHandler(eventLoop
, id
);
494 te
->timeProc(interp
, te
->clientData
);
495 /* After an event is processed our time event list may
496 * no longer be the same, so we restart from head.
497 * Still we make sure to don't process events registered
498 * by event handlers itself in order to don't loop forever
499 * even in case an [after 0] that continuously register
500 * itself. To do so we saved the max ID we want to handle. */
501 Jim_FreeTimeHandler(interp
, te
);
503 te
= eventLoop
->timeEventHead
;
514 /* ---------------------------------------------------------------------- */
516 static void JimELAssocDataDeleProc(Jim_Interp
*interp
, void *data
)
521 Jim_EventLoop
*eventLoop
= data
;
523 fe
= eventLoop
->fileEventHead
;
526 if (fe
->finalizerProc
)
527 fe
->finalizerProc(interp
, fe
->clientData
);
532 te
= eventLoop
->timeEventHead
;
535 if (te
->finalizerProc
)
536 te
->finalizerProc(interp
, te
->clientData
);
543 static int JimELVwaitCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
545 Jim_EventLoop
*eventLoop
= Jim_CmdPrivData(interp
);
550 Jim_WrongNumArgs(interp
, 1, argv
, "name");
554 oldValue
= Jim_GetGlobalVariable(interp
, argv
[1], JIM_NONE
);
556 Jim_IncrRefCount(oldValue
);
559 /* If a result was left, it is an error */
561 Jim_GetString(interp
->result
, &len
);
567 eventLoop
->suppress_bgerror
= 0;
569 while ((rc
= Jim_ProcessEvents(interp
, JIM_ALL_EVENTS
)) >= 0) {
571 currValue
= Jim_GetGlobalVariable(interp
, argv
[1], JIM_NONE
);
572 /* Stop the loop if the vwait-ed variable changed value,
573 * or if was unset and now is set (or the contrary). */
574 if ((oldValue
&& !currValue
) ||
575 (!oldValue
&& currValue
) ||
576 (oldValue
&& currValue
&& !Jim_StringEqObj(oldValue
, currValue
)))
580 Jim_DecrRefCount(interp
, oldValue
);
587 Jim_SetEmptyResult(interp
);
591 static int JimELUpdateCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
593 Jim_EventLoop
*eventLoop
= Jim_CmdPrivData(interp
);
594 static const char * const options
[] = {
597 enum { UPDATE_IDLE
, UPDATE_NONE
};
598 int option
= UPDATE_NONE
;
599 int flags
= JIM_TIME_EVENTS
;
602 flags
= JIM_ALL_EVENTS
;
604 else if (argc
> 2 || Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
, JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
605 Jim_WrongNumArgs(interp
, 1, argv
, "?idletasks?");
609 eventLoop
->suppress_bgerror
= 0;
611 while (Jim_ProcessEvents(interp
, flags
| JIM_DONT_WAIT
) > 0) {
617 static void JimAfterTimeHandler(Jim_Interp
*interp
, void *clientData
)
619 Jim_Obj
*objPtr
= clientData
;
621 Jim_EvalObjBackground(interp
, objPtr
);
624 static void JimAfterTimeEventFinalizer(Jim_Interp
*interp
, void *clientData
)
626 Jim_Obj
*objPtr
= clientData
;
628 Jim_DecrRefCount(interp
, objPtr
);
631 static int JimELAfterCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
633 Jim_EventLoop
*eventLoop
= Jim_CmdPrivData(interp
);
635 Jim_Obj
*objPtr
, *idObjPtr
;
636 static const char * const options
[] = {
637 "cancel", "info", "idle", NULL
640 { AFTER_CANCEL
, AFTER_INFO
, AFTER_IDLE
, AFTER_RESTART
, AFTER_EXPIRE
, AFTER_CREATE
};
641 int option
= AFTER_CREATE
;
644 Jim_WrongNumArgs(interp
, 1, argv
, "option ?arg ...?");
647 if (Jim_GetWide(interp
, argv
[1], &ms
) != JIM_OK
) {
648 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "argument", JIM_ERRMSG
) != JIM_OK
) {
651 Jim_SetEmptyResult(interp
);
653 else if (argc
== 2) {
662 Jim_WrongNumArgs(interp
, 2, argv
, "script ?script ...?");
667 Jim_Obj
*scriptObj
= Jim_ConcatObj(interp
, argc
- 2, argv
+ 2);
668 Jim_IncrRefCount(scriptObj
);
669 id
= Jim_CreateTimeHandler(interp
, ms
, JimAfterTimeHandler
, scriptObj
,
670 JimAfterTimeEventFinalizer
);
671 objPtr
= Jim_NewStringObj(interp
, NULL
, 0);
672 Jim_AppendString(interp
, objPtr
, "after#", -1);
673 idObjPtr
= Jim_NewIntObj(interp
, id
);
674 Jim_IncrRefCount(idObjPtr
);
675 Jim_AppendObj(interp
, objPtr
, idObjPtr
);
676 Jim_DecrRefCount(interp
, idObjPtr
);
677 Jim_SetResult(interp
, objPtr
);
682 Jim_WrongNumArgs(interp
, 2, argv
, "id|command");
688 id
= JimParseAfterId(argv
[2]);
690 /* Not an event id, so search by script */
691 Jim_Obj
*scriptObj
= Jim_ConcatObj(interp
, argc
- 2, argv
+ 2);
692 id
= JimFindAfterByScript(eventLoop
, scriptObj
);
693 Jim_FreeNewObj(interp
, scriptObj
);
699 remain
= Jim_DeleteTimeHandler(interp
, id
);
701 Jim_SetResultInt(interp
, remain
);
708 Jim_TimeEvent
*te
= eventLoop
->timeEventHead
;
709 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
711 const char *fmt
= "after#%" JIM_WIDE_MODIFIER
;
714 snprintf(buf
, sizeof(buf
), fmt
, te
->id
);
715 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
, buf
, -1));
718 Jim_SetResult(interp
, listObj
);
720 else if (argc
== 3) {
721 id
= JimParseAfterId(argv
[2]);
723 Jim_TimeEvent
*e
= JimFindTimeHandlerById(eventLoop
, id
);
724 if (e
&& e
->timeProc
== JimAfterTimeHandler
) {
725 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
726 Jim_ListAppendElement(interp
, listObj
, e
->clientData
);
727 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
, e
->initialms
? "timer" : "idle", -1));
728 Jim_SetResult(interp
, listObj
);
732 Jim_SetResultFormatted(interp
, "event \"%#s\" doesn't exist", argv
[2]);
736 Jim_WrongNumArgs(interp
, 2, argv
, "?id?");
744 int Jim_eventloopInit(Jim_Interp
*interp
)
746 Jim_EventLoop
*eventLoop
;
748 if (Jim_PackageProvide(interp
, "eventloop", "1.0", JIM_ERRMSG
))
751 eventLoop
= Jim_Alloc(sizeof(*eventLoop
));
752 eventLoop
->fileEventHead
= NULL
;
753 eventLoop
->timeEventHead
= NULL
;
754 eventLoop
->timeEventNextId
= 1;
755 eventLoop
->suppress_bgerror
= 0;
756 Jim_SetAssocData(interp
, "eventloop", JimELAssocDataDeleProc
, eventLoop
);
758 Jim_CreateCommand(interp
, "vwait", JimELVwaitCommand
, eventLoop
, NULL
);
759 Jim_CreateCommand(interp
, "update", JimELUpdateCommand
, eventLoop
, NULL
);
760 Jim_CreateCommand(interp
, "after", JimELAfterCommand
, eventLoop
, NULL
);