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__)
59 #include <sys/types.h>
60 #ifdef HAVE_SYS_SELECT_H
61 #include <sys/select.h>
65 /* XXX: Implement this in terms of select() or nanosleep() */
66 #define msleep(MS) sleep((MS) / 1000)
67 #warning "sub-second sleep not supported"
69 #define msleep(MS) sleep((MS) / 1000); usleep(((MS) % 1000) * 1000);
75 /* File event structure */
76 typedef struct Jim_FileEvent
79 int mask
; /* one of JIM_EVENT_(READABLE|WRITABLE|EXCEPTION) */
80 Jim_FileProc
*fileProc
;
81 Jim_EventFinalizerProc
*finalizerProc
;
83 struct Jim_FileEvent
*next
;
86 /* Time event structure */
87 typedef struct Jim_TimeEvent
89 jim_wide id
; /* time event identifier. */
90 long initialms
; /* initial relative timer value */
91 jim_wide when
; /* 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_FileEvent
*fileEventHead
;
102 Jim_TimeEvent
*timeEventHead
;
103 jim_wide timeEventNextId
; /* highest event id created, starting at 1 */
105 int suppress_bgerror
; /* bgerror returned break, so don't call it again */
108 static void JimAfterTimeHandler(Jim_Interp
*interp
, void *clientData
);
109 static void JimAfterTimeEventFinalizer(Jim_Interp
*interp
, void *clientData
);
111 int Jim_EvalObjBackground(Jim_Interp
*interp
, Jim_Obj
*scriptObjPtr
)
113 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
114 Jim_CallFrame
*savedFramePtr
;
117 savedFramePtr
= interp
->framePtr
;
118 interp
->framePtr
= interp
->topFramePtr
;
119 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
120 interp
->framePtr
= savedFramePtr
;
121 /* Try to report the error (if any) via the bgerror proc */
122 if (retval
!= JIM_OK
&& !eventLoop
->suppress_bgerror
) {
126 objv
[0] = Jim_NewStringObj(interp
, "bgerror", -1);
127 objv
[1] = Jim_GetResult(interp
);
128 Jim_IncrRefCount(objv
[0]);
129 Jim_IncrRefCount(objv
[1]);
130 if (Jim_GetCommand(interp
, objv
[0], JIM_NONE
) == NULL
|| (rc
= Jim_EvalObjVector(interp
, 2, objv
)) != JIM_OK
) {
131 if (rc
== JIM_BREAK
) {
132 /* No more bgerror calls */
133 eventLoop
->suppress_bgerror
++;
136 /* Report the error to stderr. */
137 Jim_MakeErrorMessage(interp
);
138 fprintf(stderr
, "%s\n", Jim_String(Jim_GetResult(interp
)));
139 /* And reset the result */
140 Jim_SetResultString(interp
, "", -1);
143 Jim_DecrRefCount(interp
, objv
[0]);
144 Jim_DecrRefCount(interp
, objv
[1]);
150 void Jim_CreateFileHandler(Jim_Interp
*interp
, int fd
, int mask
,
151 Jim_FileProc
* proc
, void *clientData
, Jim_EventFinalizerProc
* finalizerProc
)
154 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
156 fe
= Jim_Alloc(sizeof(*fe
));
160 fe
->finalizerProc
= finalizerProc
;
161 fe
->clientData
= clientData
;
162 fe
->next
= eventLoop
->fileEventHead
;
163 eventLoop
->fileEventHead
= fe
;
167 * Removes all event handlers for 'handle' that match 'mask'.
169 void Jim_DeleteFileHandler(Jim_Interp
*interp
, int fd
, int mask
)
171 Jim_FileEvent
*fe
, *next
, *prev
= NULL
;
172 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
174 for (fe
= eventLoop
->fileEventHead
; fe
; fe
= next
) {
176 if (fe
->fd
== fd
&& (fe
->mask
& mask
)) {
177 /* Remove this entry from the list */
179 eventLoop
->fileEventHead
= next
;
182 if (fe
->finalizerProc
)
183 fe
->finalizerProc(interp
, fe
->clientData
);
192 * Returns the time since interp creation in milliseconds.
194 static jim_wide
JimGetTime(Jim_EventLoop
*eventLoop
)
198 gettimeofday(&tv
, NULL
);
200 return (jim_wide
)(tv
.tv_sec
- eventLoop
->timeBase
) * 1000 + tv
.tv_usec
/ 1000;
203 jim_wide
Jim_CreateTimeHandler(Jim_Interp
*interp
, jim_wide milliseconds
,
204 Jim_TimeProc
* proc
, void *clientData
, Jim_EventFinalizerProc
* finalizerProc
)
206 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
207 jim_wide id
= ++eventLoop
->timeEventNextId
;
208 Jim_TimeEvent
*te
, *e
, *prev
;
210 te
= Jim_Alloc(sizeof(*te
));
212 te
->initialms
= milliseconds
;
213 te
->when
= JimGetTime(eventLoop
) + milliseconds
;
215 te
->finalizerProc
= finalizerProc
;
216 te
->clientData
= clientData
;
218 /* Add to the appropriate place in the list */
220 for (e
= eventLoop
->timeEventHead
; e
; e
= e
->next
) {
221 if (te
->when
< e
->when
) {
227 te
->next
= prev
->next
;
231 te
->next
= eventLoop
->timeEventHead
;
232 eventLoop
->timeEventHead
= te
;
238 static jim_wide
JimParseAfterId(Jim_Obj
*idObj
)
240 const char *tok
= Jim_String(idObj
);
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
);
314 remain
= te
->when
- JimGetTime(eventLoop
);
315 remain
= (remain
< 0) ? 0 : remain
;
317 Jim_FreeTimeHandler(interp
, te
);
320 return -1; /* NO event with the specified ID found */
323 /* --- POSIX version of Jim_ProcessEvents, for now the only available --- */
325 /* Process every pending time event, then every pending file event
326 * (that may be registered by time event callbacks just processed).
327 * The behaviour depends upon the setting of flags:
329 * If flags is 0, the function does nothing and returns.
330 * if flags has JIM_ALL_EVENTS set, all event types are processed.
331 * if flags has JIM_FILE_EVENTS set, file events are processed.
332 * if flags has JIM_TIME_EVENTS set, time events are processed.
333 * if flags has JIM_DONT_WAIT set, the function returns as soon as all
334 * the events that are possible to process without waiting are processed.
336 * Returns the number of events processed or -1 if
337 * there are no matching handlers, or -2 on error.
339 int Jim_ProcessEvents(Jim_Interp
*interp
, int flags
)
341 jim_wide sleep_ms
= -1;
343 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
344 Jim_FileEvent
*fe
= eventLoop
->fileEventHead
;
348 if ((flags
& JIM_FILE_EVENTS
) == 0 || fe
== NULL
) {
350 if ((flags
& JIM_TIME_EVENTS
) == 0 || eventLoop
->timeEventHead
== NULL
) {
356 /* Note that we want call select() even if there are no
357 * file events to process as long as we want to process time
358 * events, in order to sleep until the next time event is ready
361 if (flags
& JIM_DONT_WAIT
) {
365 else if (flags
& JIM_TIME_EVENTS
) {
366 /* The nearest timer is always at the head of the list */
367 if (eventLoop
->timeEventHead
) {
368 Jim_TimeEvent
*shortest
= eventLoop
->timeEventHead
;
370 /* Calculate the time missing for the nearest
372 sleep_ms
= shortest
->when
- JimGetTime(eventLoop
);
384 if (flags
& JIM_FILE_EVENTS
) {
386 struct timeval tv
, *tvp
= NULL
;
387 fd_set rfds
, wfds
, efds
;
394 /* Check file events */
396 if (fe
->mask
& JIM_EVENT_READABLE
)
397 FD_SET(fe
->fd
, &rfds
);
398 if (fe
->mask
& JIM_EVENT_WRITABLE
)
399 FD_SET(fe
->fd
, &wfds
);
400 if (fe
->mask
& JIM_EVENT_EXCEPTION
)
401 FD_SET(fe
->fd
, &efds
);
409 tvp
->tv_sec
= sleep_ms
/ 1000;
410 tvp
->tv_usec
= 1000 * (sleep_ms
% 1000);
413 retval
= select(maxfd
+ 1, &rfds
, &wfds
, &efds
, tvp
);
416 if (errno
== EINVAL
) {
417 /* This can happen on mingw32 if a non-socket filehandle is passed */
418 Jim_SetResultString(interp
, "non-waitable filehandle", -1);
422 else if (retval
> 0) {
423 fe
= eventLoop
->fileEventHead
;
428 if ((fe
->mask
& JIM_EVENT_READABLE
) && FD_ISSET(fd
, &rfds
))
429 mask
|= JIM_EVENT_READABLE
;
430 if (fe
->mask
& JIM_EVENT_WRITABLE
&& FD_ISSET(fd
, &wfds
))
431 mask
|= JIM_EVENT_WRITABLE
;
432 if (fe
->mask
& JIM_EVENT_EXCEPTION
&& FD_ISSET(fd
, &efds
))
433 mask
|= JIM_EVENT_EXCEPTION
;
436 if (fe
->fileProc(interp
, fe
->clientData
, mask
) != JIM_OK
) {
437 /* Remove the element on handler error */
438 Jim_DeleteFileHandler(interp
, fd
, mask
);
439 /* At this point fe is no longer valid - it will be assigned below */
442 /* After an event is processed our file event list
443 * may no longer be the same, so what we do
444 * is to clear the bit for this file descriptor and
445 * restart again from the head. */
449 fe
= eventLoop
->fileEventHead
;
463 /* Check time events */
464 te
= eventLoop
->timeEventHead
;
465 maxId
= eventLoop
->timeEventNextId
;
469 if (te
->id
> maxId
) {
473 if (JimGetTime(eventLoop
) >= te
->when
) {
475 /* Remove from the list before executing */
476 Jim_RemoveTimeHandler(eventLoop
, id
);
477 te
->timeProc(interp
, te
->clientData
);
478 /* After an event is processed our time event list may
479 * no longer be the same, so we restart from head.
480 * Still we make sure to don't process events registered
481 * by event handlers itself in order to don't loop forever
482 * even in case an [after 0] that continuously register
483 * itself. To do so we saved the max ID we want to handle. */
484 Jim_FreeTimeHandler(interp
, te
);
486 te
= eventLoop
->timeEventHead
;
497 /* ---------------------------------------------------------------------- */
499 static void JimELAssocDataDeleProc(Jim_Interp
*interp
, void *data
)
504 Jim_EventLoop
*eventLoop
= data
;
506 fe
= eventLoop
->fileEventHead
;
509 if (fe
->finalizerProc
)
510 fe
->finalizerProc(interp
, fe
->clientData
);
515 te
= eventLoop
->timeEventHead
;
518 if (te
->finalizerProc
)
519 te
->finalizerProc(interp
, te
->clientData
);
526 static int JimELVwaitCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
528 Jim_EventLoop
*eventLoop
= Jim_CmdPrivData(interp
);
533 Jim_WrongNumArgs(interp
, 1, argv
, "name");
537 oldValue
= Jim_GetGlobalVariable(interp
, argv
[1], JIM_NONE
);
539 Jim_IncrRefCount(oldValue
);
542 /* If a result was left, it is an error */
543 if (Jim_Length(Jim_GetResult(interp
))) {
548 eventLoop
->suppress_bgerror
= 0;
550 while ((rc
= Jim_ProcessEvents(interp
, JIM_ALL_EVENTS
)) >= 0) {
552 currValue
= Jim_GetGlobalVariable(interp
, argv
[1], JIM_NONE
);
553 /* Stop the loop if the vwait-ed variable changed value,
554 * or if was unset and now is set (or the contrary)
555 * or if a signal was caught
557 if ((oldValue
&& !currValue
) ||
558 (!oldValue
&& currValue
) ||
559 (oldValue
&& currValue
&& !Jim_StringEqObj(oldValue
, currValue
)) ||
560 Jim_CheckSignal(interp
)) {
565 Jim_DecrRefCount(interp
, oldValue
);
571 Jim_SetEmptyResult(interp
);
575 static int JimELUpdateCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
577 Jim_EventLoop
*eventLoop
= Jim_CmdPrivData(interp
);
578 static const char * const options
[] = {
581 enum { UPDATE_IDLE
, UPDATE_NONE
};
582 int option
= UPDATE_NONE
;
583 int flags
= JIM_TIME_EVENTS
;
586 flags
= JIM_ALL_EVENTS
;
588 else if (argc
> 2 || Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
, JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
589 Jim_WrongNumArgs(interp
, 1, argv
, "?idletasks?");
593 eventLoop
->suppress_bgerror
= 0;
595 while (Jim_ProcessEvents(interp
, flags
| JIM_DONT_WAIT
) > 0) {
601 static void JimAfterTimeHandler(Jim_Interp
*interp
, void *clientData
)
603 Jim_Obj
*objPtr
= clientData
;
605 Jim_EvalObjBackground(interp
, objPtr
);
608 static void JimAfterTimeEventFinalizer(Jim_Interp
*interp
, void *clientData
)
610 Jim_Obj
*objPtr
= clientData
;
612 Jim_DecrRefCount(interp
, objPtr
);
615 static int JimELAfterCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
617 Jim_EventLoop
*eventLoop
= Jim_CmdPrivData(interp
);
619 Jim_Obj
*objPtr
, *idObjPtr
;
620 static const char * const options
[] = {
621 "cancel", "info", "idle", NULL
624 { AFTER_CANCEL
, AFTER_INFO
, AFTER_IDLE
, AFTER_RESTART
, AFTER_EXPIRE
, AFTER_CREATE
};
625 int option
= AFTER_CREATE
;
628 Jim_WrongNumArgs(interp
, 1, argv
, "option ?arg ...?");
631 if (Jim_GetWide(interp
, argv
[1], &ms
) != JIM_OK
) {
632 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "argument", JIM_ERRMSG
) != JIM_OK
) {
635 Jim_SetEmptyResult(interp
);
637 else if (argc
== 2) {
646 Jim_WrongNumArgs(interp
, 2, argv
, "script ?script ...?");
651 Jim_Obj
*scriptObj
= Jim_ConcatObj(interp
, argc
- 2, argv
+ 2);
652 Jim_IncrRefCount(scriptObj
);
653 id
= Jim_CreateTimeHandler(interp
, ms
, JimAfterTimeHandler
, scriptObj
,
654 JimAfterTimeEventFinalizer
);
655 objPtr
= Jim_NewStringObj(interp
, NULL
, 0);
656 Jim_AppendString(interp
, objPtr
, "after#", -1);
657 idObjPtr
= Jim_NewIntObj(interp
, id
);
658 Jim_IncrRefCount(idObjPtr
);
659 Jim_AppendObj(interp
, objPtr
, idObjPtr
);
660 Jim_DecrRefCount(interp
, idObjPtr
);
661 Jim_SetResult(interp
, objPtr
);
666 Jim_WrongNumArgs(interp
, 2, argv
, "id|command");
672 id
= JimParseAfterId(argv
[2]);
674 /* Not an event id, so search by script */
675 Jim_Obj
*scriptObj
= Jim_ConcatObj(interp
, argc
- 2, argv
+ 2);
676 id
= JimFindAfterByScript(eventLoop
, scriptObj
);
677 Jim_FreeNewObj(interp
, scriptObj
);
683 remain
= Jim_DeleteTimeHandler(interp
, id
);
685 Jim_SetResultInt(interp
, remain
);
692 Jim_TimeEvent
*te
= eventLoop
->timeEventHead
;
693 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
695 const char *fmt
= "after#%" JIM_WIDE_MODIFIER
;
698 snprintf(buf
, sizeof(buf
), fmt
, te
->id
);
699 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
, buf
, -1));
702 Jim_SetResult(interp
, listObj
);
704 else if (argc
== 3) {
705 id
= JimParseAfterId(argv
[2]);
707 Jim_TimeEvent
*e
= JimFindTimeHandlerById(eventLoop
, id
);
708 if (e
&& e
->timeProc
== JimAfterTimeHandler
) {
709 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
710 Jim_ListAppendElement(interp
, listObj
, e
->clientData
);
711 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
, e
->initialms
? "timer" : "idle", -1));
712 Jim_SetResult(interp
, listObj
);
716 Jim_SetResultFormatted(interp
, "event \"%#s\" doesn't exist", argv
[2]);
720 Jim_WrongNumArgs(interp
, 2, argv
, "?id?");
728 int Jim_eventloopInit(Jim_Interp
*interp
)
730 Jim_EventLoop
*eventLoop
;
732 if (Jim_PackageProvide(interp
, "eventloop", "1.0", JIM_ERRMSG
))
735 eventLoop
= Jim_Alloc(sizeof(*eventLoop
));
736 memset(eventLoop
, 0, sizeof(*eventLoop
));
738 Jim_SetAssocData(interp
, "eventloop", JimELAssocDataDeleProc
, eventLoop
);
740 Jim_CreateCommand(interp
, "vwait", JimELVwaitCommand
, eventLoop
, NULL
);
741 Jim_CreateCommand(interp
, "update", JimELUpdateCommand
, eventLoop
, NULL
);
742 Jim_CreateCommand(interp
, "after", JimELAfterCommand
, eventLoop
, NULL
);