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;
348 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
349 Jim_FileEvent
*fe
= eventLoop
->fileEventHead
;
353 if ((flags
& JIM_FILE_EVENTS
) == 0 || fe
== NULL
) {
355 if ((flags
& JIM_TIME_EVENTS
) == 0 || eventLoop
->timeEventHead
== NULL
) {
361 /* Note that we want call select() even if there are no
362 * file events to process as long as we want to process time
363 * events, in order to sleep until the next time event is ready
366 if (flags
& JIM_DONT_WAIT
) {
370 else if (flags
& JIM_TIME_EVENTS
) {
371 /* The nearest timer is always at the head of the list */
372 if (eventLoop
->timeEventHead
) {
373 Jim_TimeEvent
*shortest
= eventLoop
->timeEventHead
;
374 long now_sec
, now_ms
;
376 /* Calculate the time missing for the nearest
378 JimGetTime(&now_sec
, &now_ms
);
379 sleep_ms
= 1000 * (shortest
->when_sec
- now_sec
) + (shortest
->when_ms
- now_ms
);
391 if (flags
& JIM_FILE_EVENTS
) {
393 struct timeval tv
, *tvp
= NULL
;
394 fd_set rfds
, wfds
, efds
;
401 /* Check file events */
403 int fd
= fileno(fe
->handle
);
405 if (fe
->mask
& JIM_EVENT_READABLE
)
407 if (fe
->mask
& JIM_EVENT_WRITABLE
)
409 if (fe
->mask
& JIM_EVENT_EXCEPTION
)
418 tvp
->tv_sec
= sleep_ms
/ 1000;
419 tvp
->tv_usec
= 1000 * (sleep_ms
% 1000);
422 retval
= select(maxfd
+ 1, &rfds
, &wfds
, &efds
, tvp
);
425 if (errno
== EINVAL
) {
426 /* This can happen on mingw32 if a non-socket filehandle is passed */
427 Jim_SetResultString(interp
, "non-waitable filehandle", -1);
430 /* XXX: What about EINTR? */
432 else if (retval
> 0) {
433 fe
= eventLoop
->fileEventHead
;
435 int fd
= fileno(fe
->handle
);
437 if ((fe
->mask
& JIM_EVENT_READABLE
&& FD_ISSET(fd
, &rfds
)) ||
438 (fe
->mask
& JIM_EVENT_WRITABLE
&& FD_ISSET(fd
, &wfds
)) ||
439 (fe
->mask
& JIM_EVENT_EXCEPTION
&& FD_ISSET(fd
, &efds
))) {
442 if ((fe
->mask
& JIM_EVENT_READABLE
) && FD_ISSET(fd
, &rfds
)) {
443 mask
|= JIM_EVENT_READABLE
;
444 if ((fe
->mask
& JIM_EVENT_FEOF
) && feof(fe
->handle
))
445 mask
|= JIM_EVENT_FEOF
;
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
;
451 if (fe
->fileProc(interp
, fe
->clientData
, mask
) != JIM_OK
) {
452 /* Remove the element on handler error */
453 Jim_DeleteFileHandler(interp
, fe
->handle
);
456 /* After an event is processed our file event list
457 * may no longer be the same, so what we do
458 * is to clear the bit for this file descriptor and
459 * restart again from the head. */
460 fe
= eventLoop
->fileEventHead
;
477 /* Check time events */
478 te
= eventLoop
->timeEventHead
;
479 maxId
= eventLoop
->timeEventNextId
- 1;
481 long now_sec
, now_ms
;
484 if (te
->id
> maxId
) {
488 JimGetTime(&now_sec
, &now_ms
);
489 if (now_sec
> te
->when_sec
|| (now_sec
== te
->when_sec
&& now_ms
>= te
->when_ms
)) {
491 /* Remove from the list before executing */
492 Jim_RemoveTimeHandler(eventLoop
, id
);
493 te
->timeProc(interp
, te
->clientData
);
494 /* After an event is processed our time event list may
495 * no longer be the same, so we restart from head.
496 * Still we make sure to don't process events registered
497 * by event handlers itself in order to don't loop forever
498 * even in case an [after 0] that continuously register
499 * itself. To do so we saved the max ID we want to handle. */
500 Jim_FreeTimeHandler(interp
, te
);
502 te
= eventLoop
->timeEventHead
;
513 /* ---------------------------------------------------------------------- */
515 static void JimELAssocDataDeleProc(Jim_Interp
*interp
, void *data
)
520 Jim_EventLoop
*eventLoop
= data
;
522 fe
= eventLoop
->fileEventHead
;
525 if (fe
->finalizerProc
)
526 fe
->finalizerProc(interp
, fe
->clientData
);
531 te
= eventLoop
->timeEventHead
;
534 if (te
->finalizerProc
)
535 te
->finalizerProc(interp
, te
->clientData
);
542 static int JimELVwaitCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
544 Jim_EventLoop
*eventLoop
= Jim_CmdPrivData(interp
);
549 Jim_WrongNumArgs(interp
, 1, argv
, "name");
553 oldValue
= Jim_GetGlobalVariable(interp
, argv
[1], JIM_NONE
);
555 Jim_IncrRefCount(oldValue
);
558 /* If a result was left, it is an error */
560 Jim_GetString(interp
->result
, &len
);
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 if ((oldValue
&& !currValue
) ||
574 (!oldValue
&& currValue
) ||
575 (oldValue
&& currValue
&& !Jim_StringEqObj(oldValue
, currValue
)))
579 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
);
634 Jim_Obj
*objPtr
, *idObjPtr
;
635 static const char * const options
[] = {
636 "cancel", "info", "idle", NULL
639 { AFTER_CANCEL
, AFTER_INFO
, AFTER_IDLE
, AFTER_RESTART
, AFTER_EXPIRE
, AFTER_CREATE
};
640 int option
= AFTER_CREATE
;
643 Jim_WrongNumArgs(interp
, 1, argv
, "option ?arg ...?");
646 if (Jim_GetWide(interp
, argv
[1], &ms
) != JIM_OK
) {
647 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "argument", JIM_ERRMSG
) != JIM_OK
) {
650 Jim_SetEmptyResult(interp
);
652 else if (argc
== 2) {
661 Jim_WrongNumArgs(interp
, 2, argv
, "script ?script ...?");
666 Jim_Obj
*scriptObj
= Jim_ConcatObj(interp
, argc
- 2, argv
+ 2);
667 Jim_IncrRefCount(scriptObj
);
668 id
= Jim_CreateTimeHandler(interp
, ms
, JimAfterTimeHandler
, scriptObj
,
669 JimAfterTimeEventFinalizer
);
670 objPtr
= Jim_NewStringObj(interp
, NULL
, 0);
671 Jim_AppendString(interp
, objPtr
, "after#", -1);
672 idObjPtr
= Jim_NewIntObj(interp
, id
);
673 Jim_IncrRefCount(idObjPtr
);
674 Jim_AppendObj(interp
, objPtr
, idObjPtr
);
675 Jim_DecrRefCount(interp
, idObjPtr
);
676 Jim_SetResult(interp
, objPtr
);
681 Jim_WrongNumArgs(interp
, 2, argv
, "id|command");
687 id
= JimParseAfterId(argv
[2]);
689 /* Not an event id, so search by script */
690 Jim_Obj
*scriptObj
= Jim_ConcatObj(interp
, argc
- 2, argv
+ 2);
691 id
= JimFindAfterByScript(eventLoop
, scriptObj
);
692 Jim_FreeNewObj(interp
, scriptObj
);
698 remain
= Jim_DeleteTimeHandler(interp
, id
);
700 Jim_SetResultInt(interp
, remain
);
707 Jim_TimeEvent
*te
= eventLoop
->timeEventHead
;
708 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
710 const char *fmt
= "after#%" JIM_WIDE_MODIFIER
;
713 snprintf(buf
, sizeof(buf
), fmt
, te
->id
);
714 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
, buf
, -1));
717 Jim_SetResult(interp
, listObj
);
719 else if (argc
== 3) {
720 id
= JimParseAfterId(argv
[2]);
722 Jim_TimeEvent
*e
= JimFindTimeHandlerById(eventLoop
, id
);
723 if (e
&& e
->timeProc
== JimAfterTimeHandler
) {
724 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
725 Jim_ListAppendElement(interp
, listObj
, e
->clientData
);
726 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
, e
->initialms
? "timer" : "idle", -1));
727 Jim_SetResult(interp
, listObj
);
731 Jim_SetResultFormatted(interp
, "event \"%#s\" doesn't exist", argv
[2]);
735 Jim_WrongNumArgs(interp
, 2, argv
, "?id?");
743 int Jim_eventloopInit(Jim_Interp
*interp
)
745 Jim_EventLoop
*eventLoop
;
747 if (Jim_PackageProvide(interp
, "eventloop", "1.0", JIM_ERRMSG
))
750 eventLoop
= Jim_Alloc(sizeof(*eventLoop
));
751 eventLoop
->fileEventHead
= NULL
;
752 eventLoop
->timeEventHead
= NULL
;
753 eventLoop
->timeEventNextId
= 1;
754 eventLoop
->suppress_bgerror
= 0;
755 Jim_SetAssocData(interp
, "eventloop", JimELAssocDataDeleProc
, eventLoop
);
757 Jim_CreateCommand(interp
, "vwait", JimELVwaitCommand
, eventLoop
, NULL
);
758 Jim_CreateCommand(interp
, "update", JimELUpdateCommand
, eventLoop
, NULL
);
759 Jim_CreateCommand(interp
, "after", JimELAfterCommand
, eventLoop
, NULL
);