1 /* Jim - A small embeddable Tcl interpreter
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>
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above
18 * copyright notice, this list of conditions and the following
19 * disclaimer in the documentation and/or other materials
20 * provided with the distribution.
22 * THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
23 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
24 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
25 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
27 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
33 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 * The views and conclusions contained in the software and documentation
36 * are those of the authors and should not be interpreted as representing
37 * official policies, either expressed or implied, of the Jim Tcl Project.
40 #include "jimautoconf.h"
42 #include <jim-eventloop.h>
50 #ifdef HAVE_SYS_TIME_H
54 #if defined(__MINGW32__)
58 #define usleep(US) Sleep((US) / 1000)
62 #include <sys/types.h>
63 #ifdef HAVE_SYS_SELECT_H
64 #include <sys/select.h>
69 /* XXX: Implement this in terms of select() or nanosleep() */
70 #define usleep(US) sleep((US) / 1000000)
71 #warning "sub-second sleep not supported"
76 /* File event structure */
77 typedef struct Jim_FileEvent
80 int mask
; /* one of JIM_EVENT_(READABLE|WRITABLE|EXCEPTION) */
81 Jim_FileProc
*fileProc
;
82 Jim_EventFinalizerProc
*finalizerProc
;
84 struct Jim_FileEvent
*next
;
87 /* Time event structure */
88 typedef struct Jim_TimeEvent
90 jim_wide id
; /* time event identifier. */
91 jim_wide initialus
; /* initial relative timer value in microseconds */
92 jim_wide when
; /* microseconds */
93 Jim_TimeProc
*timeProc
;
94 Jim_EventFinalizerProc
*finalizerProc
;
96 struct Jim_TimeEvent
*next
;
99 /* Per-interp stucture containing the state of the event loop */
100 typedef struct Jim_EventLoop
102 Jim_FileEvent
*fileEventHead
;
103 Jim_TimeEvent
*timeEventHead
;
104 jim_wide timeEventNextId
; /* highest event id created, starting at 1 */
106 int suppress_bgerror
; /* bgerror returned break, so don't call it again */
109 static void JimAfterTimeHandler(Jim_Interp
*interp
, void *clientData
);
110 static void JimAfterTimeEventFinalizer(Jim_Interp
*interp
, void *clientData
);
112 int Jim_EvalObjBackground(Jim_Interp
*interp
, Jim_Obj
*scriptObjPtr
)
114 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
115 Jim_CallFrame
*savedFramePtr
;
118 savedFramePtr
= interp
->framePtr
;
119 interp
->framePtr
= interp
->topFramePtr
;
120 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
121 interp
->framePtr
= savedFramePtr
;
122 /* Try to report the error (if any) via the bgerror proc */
123 if (retval
!= JIM_OK
&& retval
!= JIM_RETURN
&& !eventLoop
->suppress_bgerror
) {
127 objv
[0] = Jim_NewStringObj(interp
, "bgerror", -1);
128 objv
[1] = Jim_GetResult(interp
);
129 Jim_IncrRefCount(objv
[0]);
130 Jim_IncrRefCount(objv
[1]);
131 if (Jim_GetCommand(interp
, objv
[0], JIM_NONE
) == NULL
|| (rc
= Jim_EvalObjVector(interp
, 2, objv
)) != JIM_OK
) {
132 if (rc
== JIM_BREAK
) {
133 /* No more bgerror calls */
134 eventLoop
->suppress_bgerror
++;
137 /* Report the error to stderr. */
138 Jim_MakeErrorMessage(interp
);
139 fprintf(stderr
, "%s\n", Jim_String(Jim_GetResult(interp
)));
140 /* And reset the result */
141 Jim_SetResultString(interp
, "", -1);
144 Jim_DecrRefCount(interp
, objv
[0]);
145 Jim_DecrRefCount(interp
, objv
[1]);
151 void Jim_CreateFileHandler(Jim_Interp
*interp
, int fd
, int mask
,
152 Jim_FileProc
* proc
, void *clientData
, Jim_EventFinalizerProc
* finalizerProc
)
155 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
157 fe
= Jim_Alloc(sizeof(*fe
));
161 fe
->finalizerProc
= finalizerProc
;
162 fe
->clientData
= clientData
;
163 fe
->next
= eventLoop
->fileEventHead
;
164 eventLoop
->fileEventHead
= fe
;
168 * Removes all event handlers for 'handle' that match 'mask'.
170 void Jim_DeleteFileHandler(Jim_Interp
*interp
, int fd
, int mask
)
172 Jim_FileEvent
*fe
, *next
, *prev
= NULL
;
173 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
175 for (fe
= eventLoop
->fileEventHead
; fe
; fe
= next
) {
177 if (fe
->fd
== fd
&& (fe
->mask
& mask
)) {
178 /* Remove this entry from the list */
180 eventLoop
->fileEventHead
= next
;
183 if (fe
->finalizerProc
)
184 fe
->finalizerProc(interp
, fe
->clientData
);
193 * Returns the time since interp creation in microseconds.
195 static jim_wide
JimGetTimeUsec(Jim_EventLoop
*eventLoop
)
200 #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC_RAW)
203 if (clock_gettime(CLOCK_MONOTONIC_RAW
, &ts
) == 0) {
204 now
= ts
.tv_sec
* 1000000LL + ts
.tv_nsec
/ 1000;
209 gettimeofday(&tv
, NULL
);
211 now
= tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
214 return now
- eventLoop
->timeBase
;
217 jim_wide
Jim_CreateTimeHandler(Jim_Interp
*interp
, jim_wide us
,
218 Jim_TimeProc
* proc
, void *clientData
, Jim_EventFinalizerProc
* finalizerProc
)
220 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
221 jim_wide id
= ++eventLoop
->timeEventNextId
;
222 Jim_TimeEvent
*te
, *e
, *prev
;
224 te
= Jim_Alloc(sizeof(*te
));
227 te
->when
= JimGetTimeUsec(eventLoop
) + us
;
229 te
->finalizerProc
= finalizerProc
;
230 te
->clientData
= clientData
;
232 /* Add to the appropriate place in the list */
234 for (e
= eventLoop
->timeEventHead
; e
; e
= e
->next
) {
235 if (te
->when
< e
->when
) {
241 te
->next
= prev
->next
;
245 te
->next
= eventLoop
->timeEventHead
;
246 eventLoop
->timeEventHead
= te
;
252 static jim_wide
JimParseAfterId(Jim_Obj
*idObj
)
254 const char *tok
= Jim_String(idObj
);
257 if (strncmp(tok
, "after#", 6) == 0 && Jim_StringToWide(tok
+ 6, &id
, 10) == JIM_OK
) {
258 /* Got an event by id */
264 static jim_wide
JimFindAfterByScript(Jim_EventLoop
*eventLoop
, Jim_Obj
*scriptObj
)
268 for (te
= eventLoop
->timeEventHead
; te
; te
= te
->next
) {
269 /* Is this an 'after' event? */
270 if (te
->timeProc
== JimAfterTimeHandler
) {
271 if (Jim_StringEqObj(scriptObj
, te
->clientData
)) {
276 return -1; /* NO event with the specified ID found */
279 static Jim_TimeEvent
*JimFindTimeHandlerById(Jim_EventLoop
*eventLoop
, jim_wide id
)
283 for (te
= eventLoop
->timeEventHead
; te
; te
= te
->next
) {
291 static Jim_TimeEvent
*Jim_RemoveTimeHandler(Jim_EventLoop
*eventLoop
, jim_wide id
)
293 Jim_TimeEvent
*te
, *prev
= NULL
;
295 for (te
= eventLoop
->timeEventHead
; te
; te
= te
->next
) {
298 eventLoop
->timeEventHead
= te
->next
;
300 prev
->next
= te
->next
;
308 static void Jim_FreeTimeHandler(Jim_Interp
*interp
, Jim_TimeEvent
*te
)
310 if (te
->finalizerProc
)
311 te
->finalizerProc(interp
, te
->clientData
);
315 jim_wide
Jim_DeleteTimeHandler(Jim_Interp
*interp
, jim_wide id
)
318 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
320 if (id
> eventLoop
->timeEventNextId
) {
321 return -2; /* wrong event ID */
324 te
= Jim_RemoveTimeHandler(eventLoop
, id
);
328 remain
= te
->when
- JimGetTimeUsec(eventLoop
);
329 remain
= (remain
< 0) ? 0 : remain
;
331 Jim_FreeTimeHandler(interp
, te
);
334 return -1; /* NO event with the specified ID found */
337 /* --- POSIX version of Jim_ProcessEvents, for now the only available --- */
339 /* Process every pending time event, then every pending file event
340 * (that may be registered by time event callbacks just processed).
341 * The behaviour depends upon the setting of flags:
343 * If flags is 0, the function does nothing and returns.
344 * if flags has JIM_ALL_EVENTS set, all event types are processed.
345 * if flags has JIM_FILE_EVENTS set, file events are processed.
346 * if flags has JIM_TIME_EVENTS set, time events are processed.
347 * if flags has JIM_DONT_WAIT set, the function returns as soon as all
348 * the events that are possible to process without waiting are processed.
350 * Returns the number of events processed or -1 if
351 * there are no matching handlers, or -2 on error.
353 int Jim_ProcessEvents(Jim_Interp
*interp
, int flags
)
355 jim_wide sleep_us
= -1;
357 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
358 Jim_FileEvent
*fe
= eventLoop
->fileEventHead
;
362 if ((flags
& JIM_FILE_EVENTS
) == 0 || fe
== NULL
) {
364 if ((flags
& JIM_TIME_EVENTS
) == 0 || eventLoop
->timeEventHead
== NULL
) {
370 /* Note that we want call select() even if there are no
371 * file events to process as long as we want to process time
372 * events, in order to sleep until the next time event is ready
375 if (flags
& JIM_DONT_WAIT
) {
379 else if (flags
& JIM_TIME_EVENTS
) {
380 /* The nearest timer is always at the head of the list */
381 if (eventLoop
->timeEventHead
) {
382 Jim_TimeEvent
*shortest
= eventLoop
->timeEventHead
;
384 /* Calculate the time missing for the nearest
386 sleep_us
= shortest
->when
- JimGetTimeUsec(eventLoop
);
398 if (flags
& JIM_FILE_EVENTS
) {
400 struct timeval tv
, *tvp
= NULL
;
401 fd_set rfds
, wfds
, efds
;
408 /* Check file events */
410 if (fe
->mask
& JIM_EVENT_READABLE
)
411 FD_SET(fe
->fd
, &rfds
);
412 if (fe
->mask
& JIM_EVENT_WRITABLE
)
413 FD_SET(fe
->fd
, &wfds
);
414 if (fe
->mask
& JIM_EVENT_EXCEPTION
)
415 FD_SET(fe
->fd
, &efds
);
423 tvp
->tv_sec
= sleep_us
/ 1000000;
424 tvp
->tv_usec
= sleep_us
% 1000000;
427 retval
= select(maxfd
+ 1, &rfds
, &wfds
, &efds
, tvp
);
430 if (errno
== EINVAL
) {
431 /* This can happen on mingw32 if a non-socket filehandle is passed */
432 Jim_SetResultString(interp
, "non-waitable filehandle", -1);
436 else if (retval
> 0) {
437 fe
= eventLoop
->fileEventHead
;
442 if ((fe
->mask
& JIM_EVENT_READABLE
) && FD_ISSET(fd
, &rfds
))
443 mask
|= JIM_EVENT_READABLE
;
444 if (fe
->mask
& JIM_EVENT_WRITABLE
&& FD_ISSET(fd
, &wfds
))
445 mask
|= JIM_EVENT_WRITABLE
;
446 if (fe
->mask
& JIM_EVENT_EXCEPTION
&& FD_ISSET(fd
, &efds
))
447 mask
|= JIM_EVENT_EXCEPTION
;
450 int ret
= fe
->fileProc(interp
, fe
->clientData
, mask
);
451 if (ret
!= JIM_OK
&& ret
!= JIM_RETURN
) {
452 /* Remove the element on handler error */
453 Jim_DeleteFileHandler(interp
, fd
, mask
);
454 /* At this point fe is no longer valid - it will be assigned below */
457 /* After an event is processed our file event list
458 * may no longer be the same, so what we do
459 * is to clear the bit for this file descriptor and
460 * restart again from the head. */
464 fe
= eventLoop
->fileEventHead
;
478 /* Check time events */
479 te
= eventLoop
->timeEventHead
;
480 maxId
= eventLoop
->timeEventNextId
;
484 if (te
->id
> maxId
) {
488 if (JimGetTimeUsec(eventLoop
) >= te
->when
) {
490 /* Remove from the list before executing */
491 Jim_RemoveTimeHandler(eventLoop
, id
);
492 te
->timeProc(interp
, te
->clientData
);
493 /* After an event is processed our time event list may
494 * no longer be the same, so we restart from head.
495 * Still we make sure to don't process events registered
496 * by event handlers itself in order to don't loop forever
497 * even in case an [after 0] that continuously register
498 * itself. To do so we saved the max ID we want to handle. */
499 Jim_FreeTimeHandler(interp
, te
);
501 te
= eventLoop
->timeEventHead
;
512 /* ---------------------------------------------------------------------- */
514 static void JimELAssocDataDeleProc(Jim_Interp
*interp
, void *data
)
519 Jim_EventLoop
*eventLoop
= data
;
521 fe
= eventLoop
->fileEventHead
;
524 if (fe
->finalizerProc
)
525 fe
->finalizerProc(interp
, fe
->clientData
);
530 te
= eventLoop
->timeEventHead
;
533 if (te
->finalizerProc
)
534 te
->finalizerProc(interp
, te
->clientData
);
541 static int JimELVwaitCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
543 Jim_EventLoop
*eventLoop
= Jim_CmdPrivData(interp
);
548 Jim_WrongNumArgs(interp
, 1, argv
, "name");
552 oldValue
= Jim_GetGlobalVariable(interp
, argv
[1], JIM_NONE
);
554 Jim_IncrRefCount(oldValue
);
557 /* If a result was left, it is an error */
558 if (Jim_Length(Jim_GetResult(interp
))) {
563 eventLoop
->suppress_bgerror
= 0;
565 while ((rc
= Jim_ProcessEvents(interp
, JIM_ALL_EVENTS
)) >= 0) {
567 currValue
= Jim_GetGlobalVariable(interp
, argv
[1], JIM_NONE
);
568 /* Stop the loop if the vwait-ed variable changed value,
569 * or if was unset and now is set (or the contrary)
570 * or if a signal was caught
572 if ((oldValue
&& !currValue
) ||
573 (!oldValue
&& currValue
) ||
574 (oldValue
&& currValue
&& !Jim_StringEqObj(oldValue
, currValue
)) ||
575 Jim_CheckSignal(interp
)) {
580 Jim_DecrRefCount(interp
, oldValue
);
586 Jim_SetEmptyResult(interp
);
590 static int JimELUpdateCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
592 Jim_EventLoop
*eventLoop
= Jim_CmdPrivData(interp
);
593 static const char * const options
[] = {
596 enum { UPDATE_IDLE
, UPDATE_NONE
};
597 int option
= UPDATE_NONE
;
598 int flags
= JIM_TIME_EVENTS
;
601 flags
= JIM_ALL_EVENTS
;
603 else if (argc
> 2 || Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
, JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
604 Jim_WrongNumArgs(interp
, 1, argv
, "?idletasks?");
608 eventLoop
->suppress_bgerror
= 0;
610 while (Jim_ProcessEvents(interp
, flags
| JIM_DONT_WAIT
) > 0) {
616 static void JimAfterTimeHandler(Jim_Interp
*interp
, void *clientData
)
618 Jim_Obj
*objPtr
= clientData
;
620 Jim_EvalObjBackground(interp
, objPtr
);
623 static void JimAfterTimeEventFinalizer(Jim_Interp
*interp
, void *clientData
)
625 Jim_Obj
*objPtr
= clientData
;
627 Jim_DecrRefCount(interp
, objPtr
);
630 static int JimELAfterCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
632 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_GetDouble(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
, (jim_wide
)(ms
* 1000), 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
->initialus
? "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 memset(eventLoop
, 0, sizeof(*eventLoop
));
754 Jim_SetAssocData(interp
, "eventloop", JimELAssocDataDeleProc
, eventLoop
);
756 Jim_CreateCommand(interp
, "vwait", JimELVwaitCommand
, eventLoop
, NULL
);
757 Jim_CreateCommand(interp
, "update", JimELUpdateCommand
, eventLoop
, NULL
);
758 Jim_CreateCommand(interp
, "after", JimELAfterCommand
, eventLoop
, NULL
);