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.
41 #include "jimautoconf.h"
43 #include <jim-eventloop.h>
47 #include <sys/types.h>
52 #if defined(__MINGW32__)
57 #define usleep(US) msleep((US) / 1000)
60 #ifdef HAVE_SYS_SELECT_H
61 #include <sys/select.h>
65 /* XXX: Implement this in terms of select() or nanosleep() */
68 #define msleep(MS) sleep((MS) / 1000); usleep(((MS) % 1000) * 1000);
73 /* File event structure */
74 typedef struct Jim_FileEvent
77 int mask
; /* one of JIM_EVENT_(READABLE|WRITABLE|EXCEPTION) */
78 Jim_FileProc
*fileProc
;
79 Jim_EventFinalizerProc
*finalizerProc
;
81 struct Jim_FileEvent
*next
;
84 /* Time event structure */
85 typedef struct Jim_TimeEvent
87 jim_wide id
; /* time event identifier. */
88 int mode
; /* restart, repetitive .. UK */
89 long initialms
; /* initial relativ timer value UK */
90 long when_sec
; /* seconds */
91 long when_ms
; /* milliseconds */
92 Jim_TimeProc
*timeProc
;
93 Jim_EventFinalizerProc
*finalizerProc
;
95 struct Jim_TimeEvent
*next
;
98 /* Per-interp stucture containing the state of the event loop */
99 typedef struct Jim_EventLoop
101 jim_wide timeEventNextId
;
102 Jim_FileEvent
*fileEventHead
;
103 Jim_TimeEvent
*timeEventHead
;
104 int suppress_bgerror
; /* bgerror returned break, so don't call it again */
107 static void JimAfterTimeHandler(Jim_Interp
*interp
, void *clientData
);
108 static void JimAfterTimeEventFinalizer(Jim_Interp
*interp
, void *clientData
);
110 int Jim_EvalObjBackground(Jim_Interp
*interp
, Jim_Obj
*scriptObjPtr
)
112 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
113 Jim_CallFrame
*savedFramePtr
;
116 savedFramePtr
= interp
->framePtr
;
117 interp
->framePtr
= interp
->topFramePtr
;
118 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
119 interp
->framePtr
= savedFramePtr
;
120 /* Try to report the error (if any) via the bgerror proc */
121 if (retval
!= JIM_OK
&& !eventLoop
->suppress_bgerror
) {
125 objv
[0] = Jim_NewStringObj(interp
, "bgerror", -1);
126 objv
[1] = Jim_GetResult(interp
);
127 Jim_IncrRefCount(objv
[0]);
128 Jim_IncrRefCount(objv
[1]);
129 if (Jim_GetCommand(interp
, objv
[0], JIM_NONE
) == NULL
|| (rc
= Jim_EvalObjVector(interp
, 2, objv
)) != JIM_OK
) {
130 if (rc
== JIM_BREAK
) {
131 /* No more bgerror calls */
132 eventLoop
->suppress_bgerror
++;
135 /* Report the error to stderr. */
136 Jim_MakeErrorMessage(interp
);
137 fprintf(stderr
, "%s\n", Jim_String(Jim_GetResult(interp
)));
138 /* And reset the result */
139 Jim_SetResultString(interp
, "", -1);
142 Jim_DecrRefCount(interp
, objv
[0]);
143 Jim_DecrRefCount(interp
, objv
[1]);
149 void Jim_CreateFileHandler(Jim_Interp
*interp
, FILE * handle
, int mask
,
150 Jim_FileProc
* proc
, void *clientData
, Jim_EventFinalizerProc
* finalizerProc
)
153 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
155 fe
= Jim_Alloc(sizeof(*fe
));
159 fe
->finalizerProc
= finalizerProc
;
160 fe
->clientData
= clientData
;
161 fe
->next
= eventLoop
->fileEventHead
;
162 eventLoop
->fileEventHead
= fe
;
166 * Removes all event handlers for 'handle' that match 'mask'.
168 void Jim_DeleteFileHandler(Jim_Interp
*interp
, FILE * handle
, int mask
)
170 Jim_FileEvent
*fe
, *next
, *prev
= NULL
;
171 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
173 for (fe
= eventLoop
->fileEventHead
; fe
; fe
= next
) {
174 if (fe
->handle
== handle
&& (fe
->mask
& mask
)) {
175 /* Remove this entry from the list */
177 next
= eventLoop
->fileEventHead
= fe
->next
;
179 next
= prev
->next
= fe
->next
;
180 if (fe
->finalizerProc
)
181 fe
->finalizerProc(interp
, fe
->clientData
);
190 static void JimGetTime(long *seconds
, long *milliseconds
)
194 gettimeofday(&tv
, NULL
);
195 *seconds
= tv
.tv_sec
;
196 *milliseconds
= tv
.tv_usec
/ 1000;
199 jim_wide
Jim_CreateTimeHandler(Jim_Interp
*interp
, jim_wide milliseconds
,
200 Jim_TimeProc
* proc
, void *clientData
, Jim_EventFinalizerProc
* finalizerProc
)
202 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
203 jim_wide id
= eventLoop
->timeEventNextId
++;
204 Jim_TimeEvent
*te
, *e
, *prev
;
205 long cur_sec
, cur_ms
;
207 JimGetTime(&cur_sec
, &cur_ms
);
209 te
= Jim_Alloc(sizeof(*te
));
212 te
->initialms
= milliseconds
;
213 te
->when_sec
= cur_sec
+ milliseconds
/ 1000;
214 te
->when_ms
= cur_ms
+ milliseconds
% 1000;
215 if (te
->when_ms
>= 1000) {
220 te
->finalizerProc
= finalizerProc
;
221 te
->clientData
= clientData
;
223 /* Add to the appropriate place in the list */
224 if (eventLoop
->timeEventHead
) {
226 for (e
= eventLoop
->timeEventHead
; e
; e
= e
->next
) {
227 if (te
->when_sec
< e
->when_sec
|| (te
->when_sec
== e
->when_sec
&& te
->when_ms
< e
->when_ms
)) {
233 te
->next
= prev
->next
;
239 te
->next
= eventLoop
->timeEventHead
;
240 eventLoop
->timeEventHead
= te
;
245 static jim_wide
JimParseAfterId(Jim_Obj
*idObj
)
247 const char *tok
= Jim_String(idObj
);
250 if (strncmp(tok
, "after#", 6) == 0 && Jim_StringToWide(tok
+ 6, &id
, 10) == JIM_OK
) {
251 /* Got an event by id */
257 static jim_wide
JimFindAfterByScript(Jim_EventLoop
*eventLoop
, Jim_Obj
*scriptObj
)
261 for (te
= eventLoop
->timeEventHead
; te
; te
= te
->next
) {
262 /* Is this an 'after' event? */
263 if (te
->timeProc
== JimAfterTimeHandler
) {
264 if (Jim_StringEqObj(scriptObj
, te
->clientData
)) {
269 return -1; /* NO event with the specified ID found */
272 static Jim_TimeEvent
*JimFindTimeHandlerById(Jim_EventLoop
*eventLoop
, jim_wide id
)
276 for (te
= eventLoop
->timeEventHead
; te
; te
= te
->next
) {
284 static Jim_TimeEvent
*Jim_RemoveTimeHandler(Jim_EventLoop
*eventLoop
, jim_wide id
)
286 Jim_TimeEvent
*te
, *prev
= NULL
;
288 for (te
= eventLoop
->timeEventHead
; te
; te
= te
->next
) {
291 eventLoop
->timeEventHead
= te
->next
;
293 prev
->next
= te
->next
;
301 static void Jim_FreeTimeHandler(Jim_Interp
*interp
, Jim_TimeEvent
*te
)
303 if (te
->finalizerProc
)
304 te
->finalizerProc(interp
, te
->clientData
);
308 jim_wide
Jim_DeleteTimeHandler(Jim_Interp
*interp
, jim_wide id
)
311 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
313 if (id
>= eventLoop
->timeEventNextId
) {
314 return -2; /* wrong event ID */
317 te
= Jim_RemoveTimeHandler(eventLoop
, id
);
320 long cur_sec
, cur_ms
;
322 JimGetTime(&cur_sec
, &cur_ms
);
324 remain
= (te
->when_sec
- cur_sec
) * 1000;
325 remain
+= (te
->when_ms
- cur_ms
);
326 remain
= (remain
< 0) ? 0 : remain
;
328 Jim_FreeTimeHandler(interp
, te
);
331 return -1; /* NO event with the specified ID found */
334 /* --- POSIX version of Jim_ProcessEvents, for now the only available --- */
336 /* Process every pending time event, then every pending file event
337 * (that may be registered by time event callbacks just processed).
338 * Without special flags the function sleeps until some file event
339 * fires, or when the next time event occurrs (if any).
341 * If flags is 0, the function does nothing and returns.
342 * if flags has JIM_ALL_EVENTS set, all the kind of events are processed.
343 * if flags has JIM_FILE_EVENTS set, file events are processed.
344 * if flags has JIM_TIME_EVENTS set, time events are processed.
345 * if flags has JIM_DONT_WAIT set the function returns ASAP until all
346 * the events that's possible to process without to wait are processed.
348 * The function returns the number of events processed or -1 if
349 * there are no matching handlers, or -2 on error.
351 int Jim_ProcessEvents(Jim_Interp
*interp
, int flags
)
353 jim_wide sleep_ms
= -1;
355 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
356 Jim_FileEvent
*fe
= eventLoop
->fileEventHead
;
360 if ((flags
& JIM_FILE_EVENTS
) == 0 || fe
== NULL
) {
362 if ((flags
& JIM_TIME_EVENTS
) == 0 || eventLoop
->timeEventHead
== NULL
) {
368 /* Note that we want call select() even if there are no
369 * file events to process as long as we want to process time
370 * events, in order to sleep until the next time event is ready
373 if (flags
& JIM_DONT_WAIT
) {
377 else if (flags
& JIM_TIME_EVENTS
) {
378 /* The nearest timer is always at the head of the list */
379 if (eventLoop
->timeEventHead
) {
380 Jim_TimeEvent
*shortest
= eventLoop
->timeEventHead
;
381 long now_sec
, now_ms
;
383 /* Calculate the time missing for the nearest
385 JimGetTime(&now_sec
, &now_ms
);
386 sleep_ms
= 1000 * (shortest
->when_sec
- now_sec
) + (shortest
->when_ms
- now_ms
);
398 if (flags
& JIM_FILE_EVENTS
) {
400 struct timeval tv
, *tvp
= NULL
;
401 fd_set rfds
, wfds
, efds
;
408 /* Check file events */
410 int fd
= fileno(fe
->handle
);
412 if (fe
->mask
& JIM_EVENT_READABLE
)
414 if (fe
->mask
& JIM_EVENT_WRITABLE
)
416 if (fe
->mask
& JIM_EVENT_EXCEPTION
)
425 tvp
->tv_sec
= sleep_ms
/ 1000;
426 tvp
->tv_usec
= 1000 * (sleep_ms
% 1000);
429 retval
= select(maxfd
+ 1, &rfds
, &wfds
, &efds
, tvp
);
432 if (errno
== EINVAL
) {
433 /* This can happen on mingw32 if a non-socket filehandle is passed */
434 Jim_SetResultString(interp
, "non-waitable filehandle", -1);
437 /* XXX: What about EINTR? */
439 else if (retval
> 0) {
440 fe
= eventLoop
->fileEventHead
;
442 int fd
= fileno(fe
->handle
);
445 if ((fe
->mask
& JIM_EVENT_READABLE
) && FD_ISSET(fd
, &rfds
))
446 mask
|= JIM_EVENT_READABLE
;
447 if (fe
->mask
& JIM_EVENT_WRITABLE
&& FD_ISSET(fd
, &wfds
))
448 mask
|= JIM_EVENT_WRITABLE
;
449 if (fe
->mask
& JIM_EVENT_EXCEPTION
&& FD_ISSET(fd
, &efds
))
450 mask
|= JIM_EVENT_EXCEPTION
;
453 if (fe
->fileProc(interp
, fe
->clientData
, mask
) != JIM_OK
) {
454 /* Remove the element on handler error */
455 Jim_DeleteFileHandler(interp
, fe
->handle
, mask
);
458 /* After an event is processed our file event list
459 * may no longer be the same, so what we do
460 * is to clear the bit for this file descriptor and
461 * restart again from the head. */
462 fe
= eventLoop
->fileEventHead
;
479 /* Check time events */
480 te
= eventLoop
->timeEventHead
;
481 maxId
= eventLoop
->timeEventNextId
- 1;
483 long now_sec
, now_ms
;
486 if (te
->id
> maxId
) {
490 JimGetTime(&now_sec
, &now_ms
);
491 if (now_sec
> te
->when_sec
|| (now_sec
== te
->when_sec
&& now_ms
>= te
->when_ms
)) {
493 /* Remove from the list before executing */
494 Jim_RemoveTimeHandler(eventLoop
, id
);
495 te
->timeProc(interp
, te
->clientData
);
496 /* After an event is processed our time event list may
497 * no longer be the same, so we restart from head.
498 * Still we make sure to don't process events registered
499 * by event handlers itself in order to don't loop forever
500 * even in case an [after 0] that continuously register
501 * itself. To do so we saved the max ID we want to handle. */
502 Jim_FreeTimeHandler(interp
, te
);
504 te
= eventLoop
->timeEventHead
;
515 /* ---------------------------------------------------------------------- */
517 static void JimELAssocDataDeleProc(Jim_Interp
*interp
, void *data
)
522 Jim_EventLoop
*eventLoop
= data
;
524 fe
= eventLoop
->fileEventHead
;
527 if (fe
->finalizerProc
)
528 fe
->finalizerProc(interp
, fe
->clientData
);
533 te
= eventLoop
->timeEventHead
;
536 if (te
->finalizerProc
)
537 te
->finalizerProc(interp
, te
->clientData
);
544 static int JimELVwaitCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
546 Jim_EventLoop
*eventLoop
= Jim_CmdPrivData(interp
);
551 Jim_WrongNumArgs(interp
, 1, argv
, "name");
555 oldValue
= Jim_GetGlobalVariable(interp
, argv
[1], JIM_NONE
);
557 Jim_IncrRefCount(oldValue
);
560 /* If a result was left, it is an error */
561 if (Jim_Length(Jim_GetResult(interp
))) {
566 eventLoop
->suppress_bgerror
= 0;
568 while ((rc
= Jim_ProcessEvents(interp
, JIM_ALL_EVENTS
)) >= 0) {
570 currValue
= Jim_GetGlobalVariable(interp
, argv
[1], JIM_NONE
);
571 /* Stop the loop if the vwait-ed variable changed value,
572 * or if was unset and now is set (or the contrary)
573 * or if a signal was caught
575 if ((oldValue
&& !currValue
) ||
576 (!oldValue
&& currValue
) ||
577 (oldValue
&& currValue
&& !Jim_StringEqObj(oldValue
, currValue
)) ||
578 Jim_CheckSignal(interp
)) {
583 Jim_DecrRefCount(interp
, oldValue
);
589 Jim_SetEmptyResult(interp
);
593 static int JimELUpdateCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
595 Jim_EventLoop
*eventLoop
= Jim_CmdPrivData(interp
);
596 static const char * const options
[] = {
599 enum { UPDATE_IDLE
, UPDATE_NONE
};
600 int option
= UPDATE_NONE
;
601 int flags
= JIM_TIME_EVENTS
;
604 flags
= JIM_ALL_EVENTS
;
606 else if (argc
> 2 || Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
, JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
607 Jim_WrongNumArgs(interp
, 1, argv
, "?idletasks?");
611 eventLoop
->suppress_bgerror
= 0;
613 while (Jim_ProcessEvents(interp
, flags
| JIM_DONT_WAIT
) > 0) {
619 static void JimAfterTimeHandler(Jim_Interp
*interp
, void *clientData
)
621 Jim_Obj
*objPtr
= clientData
;
623 Jim_EvalObjBackground(interp
, objPtr
);
626 static void JimAfterTimeEventFinalizer(Jim_Interp
*interp
, void *clientData
)
628 Jim_Obj
*objPtr
= clientData
;
630 Jim_DecrRefCount(interp
, objPtr
);
633 static int JimELAfterCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
635 Jim_EventLoop
*eventLoop
= Jim_CmdPrivData(interp
);
637 Jim_Obj
*objPtr
, *idObjPtr
;
638 static const char * const options
[] = {
639 "cancel", "info", "idle", NULL
642 { AFTER_CANCEL
, AFTER_INFO
, AFTER_IDLE
, AFTER_RESTART
, AFTER_EXPIRE
, AFTER_CREATE
};
643 int option
= AFTER_CREATE
;
646 Jim_WrongNumArgs(interp
, 1, argv
, "option ?arg ...?");
649 if (Jim_GetWide(interp
, argv
[1], &ms
) != JIM_OK
) {
650 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "argument", JIM_ERRMSG
) != JIM_OK
) {
653 Jim_SetEmptyResult(interp
);
655 else if (argc
== 2) {
664 Jim_WrongNumArgs(interp
, 2, argv
, "script ?script ...?");
669 Jim_Obj
*scriptObj
= Jim_ConcatObj(interp
, argc
- 2, argv
+ 2);
670 Jim_IncrRefCount(scriptObj
);
671 id
= Jim_CreateTimeHandler(interp
, ms
, JimAfterTimeHandler
, scriptObj
,
672 JimAfterTimeEventFinalizer
);
673 objPtr
= Jim_NewStringObj(interp
, NULL
, 0);
674 Jim_AppendString(interp
, objPtr
, "after#", -1);
675 idObjPtr
= Jim_NewIntObj(interp
, id
);
676 Jim_IncrRefCount(idObjPtr
);
677 Jim_AppendObj(interp
, objPtr
, idObjPtr
);
678 Jim_DecrRefCount(interp
, idObjPtr
);
679 Jim_SetResult(interp
, objPtr
);
684 Jim_WrongNumArgs(interp
, 2, argv
, "id|command");
690 id
= JimParseAfterId(argv
[2]);
692 /* Not an event id, so search by script */
693 Jim_Obj
*scriptObj
= Jim_ConcatObj(interp
, argc
- 2, argv
+ 2);
694 id
= JimFindAfterByScript(eventLoop
, scriptObj
);
695 Jim_FreeNewObj(interp
, scriptObj
);
701 remain
= Jim_DeleteTimeHandler(interp
, id
);
703 Jim_SetResultInt(interp
, remain
);
710 Jim_TimeEvent
*te
= eventLoop
->timeEventHead
;
711 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
713 const char *fmt
= "after#%" JIM_WIDE_MODIFIER
;
716 snprintf(buf
, sizeof(buf
), fmt
, te
->id
);
717 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
, buf
, -1));
720 Jim_SetResult(interp
, listObj
);
722 else if (argc
== 3) {
723 id
= JimParseAfterId(argv
[2]);
725 Jim_TimeEvent
*e
= JimFindTimeHandlerById(eventLoop
, id
);
726 if (e
&& e
->timeProc
== JimAfterTimeHandler
) {
727 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
728 Jim_ListAppendElement(interp
, listObj
, e
->clientData
);
729 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
, e
->initialms
? "timer" : "idle", -1));
730 Jim_SetResult(interp
, listObj
);
734 Jim_SetResultFormatted(interp
, "event \"%#s\" doesn't exist", argv
[2]);
738 Jim_WrongNumArgs(interp
, 2, argv
, "?id?");
746 int Jim_eventloopInit(Jim_Interp
*interp
)
748 Jim_EventLoop
*eventLoop
;
750 if (Jim_PackageProvide(interp
, "eventloop", "1.0", JIM_ERRMSG
))
753 eventLoop
= Jim_Alloc(sizeof(*eventLoop
));
754 eventLoop
->fileEventHead
= NULL
;
755 eventLoop
->timeEventHead
= NULL
;
756 eventLoop
->timeEventNextId
= 1;
757 eventLoop
->suppress_bgerror
= 0;
758 Jim_SetAssocData(interp
, "eventloop", JimELAssocDataDeleProc
, eventLoop
);
760 Jim_CreateCommand(interp
, "vwait", JimELVwaitCommand
, eventLoop
, NULL
);
761 Jim_CreateCommand(interp
, "update", JimELUpdateCommand
, eventLoop
, NULL
);
762 Jim_CreateCommand(interp
, "after", JimELAfterCommand
, eventLoop
, NULL
);