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.
41 * - to really use flags in Jim_ProcessEvents()
42 * - more complete [after] command with [after info] and other subcommands.
50 #define __JIM_EVENTLOOP_CORE__
52 #include <pkgconf/jimtcl.h>
54 #include <cyg/jimtcl/jim.h>
55 #include <cyg/jimtcl/jim-eventloop.h>
58 #include "jim-eventloop.h"
61 /* File event structure */
62 typedef struct Jim_FileEvent
{
64 int mask
; /* one of JIM_EVENT_(READABLE | WRITABLE | EXCEPTION) */
65 Jim_FileProc
*fileProc
;
66 Jim_EventFinalizerProc
*finalizerProc
;
68 struct Jim_FileEvent
*next
;
71 /* Time event structure */
72 typedef struct Jim_TimeEvent
{
73 jim_wide id
; /* time event identifier. */
74 int mode
; /* restart, repetitive .. UK */
75 long initialms
; /* initial relativ timer value UK */
76 long when_sec
; /* seconds */
77 long when_ms
; /* milliseconds */
78 Jim_TimeProc
*timeProc
;
79 Jim_EventFinalizerProc
*finalizerProc
;
81 struct Jim_TimeEvent
*next
;
84 /* Per-interp stucture containing the state of the event loop */
85 typedef struct Jim_EventLoop
{
86 jim_wide timeEventNextId
;
87 Jim_FileEvent
*fileEventHead
;
88 Jim_TimeEvent
*timeEventHead
;
91 void Jim_CreateFileHandler(Jim_Interp
*interp
, void *handle
, int mask
,
92 Jim_FileProc
*proc
, void *clientData
,
93 Jim_EventFinalizerProc
*finalizerProc
)
96 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
98 // fprintf(stderr,"rein\n");
99 fe
= Jim_Alloc(sizeof(*fe
));
103 fe
->finalizerProc
= finalizerProc
;
104 fe
->clientData
= clientData
;
105 fe
->next
= eventLoop
->fileEventHead
;
106 eventLoop
->fileEventHead
= fe
;
107 // fprintf(stderr,"raus\n");
110 void Jim_DeleteFileHandler(Jim_Interp
*interp
, void *handle
)
112 Jim_FileEvent
*fe
, *prev
= NULL
;
113 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
115 fe
= eventLoop
->fileEventHead
;
117 if (fe
->handle
== handle
) {
119 eventLoop
->fileEventHead
= fe
->next
;
121 prev
->next
= fe
->next
;
122 if (fe
->finalizerProc
)
123 fe
->finalizerProc(interp
, fe
->clientData
);
132 // The same for signals.
133 void Jim_CreateSignalHandler(Jim_Interp
*interp
, int signum
,
134 Jim_FileProc
*proc
, void *clientData
,
135 Jim_EventFinalizerProc
*finalizerProc
)
138 void Jim_DeleteSignalHandler(Jim_Interp
*interp
, int signum
)
142 /* That's another part of this extension that needs to be ported
144 static void JimGetTime(long *seconds
, long *milliseconds
)
148 gettimeofday(&tv
, NULL
);
149 *seconds
= tv
.tv_sec
;
150 *milliseconds
= tv
.tv_usec
/1000;
153 jim_wide
Jim_CreateTimeHandler(Jim_Interp
*interp
, jim_wide milliseconds
,
154 Jim_TimeProc
*proc
, void *clientData
,
155 Jim_EventFinalizerProc
*finalizerProc
)
157 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
158 jim_wide id
= eventLoop
->timeEventNextId
++;
160 long cur_sec
, cur_ms
;
162 JimGetTime(&cur_sec
, &cur_ms
);
164 te
= Jim_Alloc(sizeof(*te
));
167 te
->initialms
= milliseconds
;
168 te
->when_sec
= cur_sec
+ milliseconds
/1000;
169 te
->when_ms
= cur_ms
+ milliseconds
%1000;
170 if (te
->when_ms
>= 1000) {
175 te
->finalizerProc
= finalizerProc
;
176 te
->clientData
= clientData
;
177 te
->next
= eventLoop
->timeEventHead
;
178 eventLoop
->timeEventHead
= te
;
182 jim_wide
Jim_DeleteTimeHandler(Jim_Interp
*interp
, jim_wide id
)
184 Jim_TimeEvent
*te
, *prev
= NULL
;
185 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
186 long cur_sec
, cur_ms
;
189 JimGetTime(&cur_sec
, &cur_ms
);
191 te
= eventLoop
->timeEventHead
;
192 if (id
>= eventLoop
->timeEventNextId
)
193 return -2; /* wrong event ID */
196 remain
= (te
->when_sec
- cur_sec
) * 1000;
197 remain
+= (te
->when_ms
- cur_ms
) ;
198 remain
= (remain
< 0) ? 0 : remain
;
201 eventLoop
->timeEventHead
= te
->next
;
203 prev
->next
= te
->next
;
204 if (te
->finalizerProc
)
205 te
->finalizerProc(interp
, te
->clientData
);
212 return -1; /* NO event with the specified ID found */
215 /* Search the first timer to fire.
216 * This operation is useful to know how many time the select can be
217 * put in sleep without to delay any event.
218 * If there are no timers NULL is returned. */
219 static Jim_TimeEvent
*JimSearchNearestTimer(Jim_EventLoop
*eventLoop
)
221 Jim_TimeEvent
*te
= eventLoop
->timeEventHead
;
222 Jim_TimeEvent
*nearest
= NULL
;
225 if (!nearest
|| te
->when_sec
< nearest
->when_sec
||
226 (te
->when_sec
== nearest
->when_sec
&&
227 te
->when_ms
< nearest
->when_ms
))
234 /* --- POSIX version of Jim_ProcessEvents, for now the only available --- */
235 #define JIM_FILE_EVENTS 1
236 #define JIM_TIME_EVENTS 2
237 #define JIM_ALL_EVENTS (JIM_FILE_EVENTS | JIM_TIME_EVENTS)
238 #define JIM_DONT_WAIT 4
240 /* Process every pending time event, then every pending file event
241 * (that may be registered by time event callbacks just processed).
242 * Without special flags the function sleeps until some file event
243 * fires, or when the next time event occurrs (if any).
245 * If flags is 0, the function does nothing and returns.
246 * if flags has JIM_ALL_EVENTS set, all the kind of events are processed.
247 * if flags has JIM_FILE_EVENTS set, file events are processed.
248 * if flags has JIM_TIME_EVENTS set, time events are processed.
249 * if flags has JIM_DONT_WAIT set the function returns ASAP until all
250 * the events that's possible to process without to wait are processed.
252 * The function returns the number of events processed. */
253 int Jim_ProcessEvents(Jim_Interp
*interp
, int flags
)
255 int maxfd
= 0, numfd
= 0, processed
= 0;
256 fd_set rfds
, wfds
, efds
;
257 Jim_EventLoop
*eventLoop
= Jim_GetAssocData(interp
, "eventloop");
258 Jim_FileEvent
*fe
= eventLoop
->fileEventHead
;
267 /* Check file events */
269 int fd
= fileno((FILE*)fe
->handle
);
271 if (fe
->mask
& JIM_EVENT_READABLE
)
273 if (fe
->mask
& JIM_EVENT_WRITABLE
) FD_SET(fd
, &wfds
);
274 if (fe
->mask
& JIM_EVENT_EXCEPTION
) FD_SET(fd
, &efds
);
275 if (maxfd
< fd
) maxfd
= fd
;
279 /* Note that we want call select() even if there are no
280 * file events to process as long as we want to process time
281 * events, in order to sleep until the next time event is ready
283 if (numfd
|| ((flags
& JIM_TIME_EVENTS
) && !(flags
& JIM_DONT_WAIT
))) {
285 Jim_TimeEvent
*shortest
;
286 struct timeval tv
, *tvp
;
289 shortest
= JimSearchNearestTimer(eventLoop
);
291 long now_sec
, now_ms
;
293 /* Calculate the time missing for the nearest
295 JimGetTime(&now_sec
, &now_ms
);
297 dt
= 1000 * (shortest
->when_sec
- now_sec
);
298 dt
+= (shortest
->when_ms
- now_ms
);
302 tvp
->tv_sec
= dt
/ 1000;
303 tvp
->tv_usec
= dt
% 1000;
304 // fprintf(stderr,"Next %d.% 8d\n",(int)tvp->tv_sec,(int)tvp->tv_usec);
306 tvp
= NULL
; /* wait forever */
307 // fprintf(stderr,"No Event\n");
310 retval
= select(maxfd
+ 1, &rfds
, &wfds
, &efds
, tvp
);
313 case EINTR
: fprintf(stderr
,"select EINTR\n"); break;
314 case EINVAL
: fprintf(stderr
,"select EINVAL\n"); break;
315 case ENOMEM
: fprintf(stderr
,"select ENOMEM\n"); break;
317 } else if (retval
> 0) {
318 fe
= eventLoop
->fileEventHead
;
320 int fd
= fileno((FILE*)fe
->handle
);
322 // fprintf(stderr,"fd: %d mask: %02x \n",fd,fe->mask);
324 if ((fe
->mask
& JIM_EVENT_READABLE
&& FD_ISSET(fd
, &rfds
)) ||
325 (fe
->mask
& JIM_EVENT_WRITABLE
&& FD_ISSET(fd
, &wfds
)) ||
326 (fe
->mask
& JIM_EVENT_EXCEPTION
&& FD_ISSET(fd
, &efds
)))
330 if (fe
->mask
& JIM_EVENT_READABLE
&& FD_ISSET(fd
, &rfds
)) {
331 mask
|= JIM_EVENT_READABLE
;
332 if ((fe
->mask
& JIM_EVENT_FEOF
) && feof((FILE *)fe
->handle
))
333 mask
|= JIM_EVENT_FEOF
;
335 if (fe
->mask
& JIM_EVENT_WRITABLE
&& FD_ISSET(fd
, &wfds
))
336 mask
|= JIM_EVENT_WRITABLE
;
337 if (fe
->mask
& JIM_EVENT_EXCEPTION
&& FD_ISSET(fd
, &efds
))
338 mask
|= JIM_EVENT_EXCEPTION
;
339 if (fe
->fileProc(interp
, fe
->clientData
, mask
) == JIM_ERR
) {
340 /* Remove the element on handler error */
341 Jim_DeleteFileHandler(interp
, fe
->handle
);
344 /* After an event is processed our file event list
345 * may no longer be the same, so what we do
346 * is to clear the bit for this file descriptor and
347 * restart again from the head. */
348 fe
= eventLoop
->fileEventHead
;
358 /* Check time events */
359 te
= eventLoop
->timeEventHead
;
360 maxId
= eventLoop
->timeEventNextId
-1;
362 long now_sec
, now_ms
;
365 if (te
->id
> maxId
) {
369 JimGetTime(&now_sec
, &now_ms
);
370 if (now_sec
> te
->when_sec
||
371 (now_sec
== te
->when_sec
&& now_ms
>= te
->when_ms
))
374 te
->timeProc(interp
, te
->clientData
);
375 /* After an event is processed our time event list may
376 * no longer be the same, so we restart from head.
377 * Still we make sure to don't process events registered
378 * by event handlers itself in order to don't loop forever
379 * even in case an [after 0] that continuously register
380 * itself. To do so we saved the max ID we want to handle. */
381 Jim_DeleteTimeHandler(interp
, id
);
382 te
= eventLoop
->timeEventHead
;
390 /* ---------------------------------------------------------------------- */
392 void JimELAssocDataDeleProc(Jim_Interp
*interp
, void *data
)
397 Jim_EventLoop
*eventLoop
= data
;
399 fe
= eventLoop
->fileEventHead
;
402 if (fe
->finalizerProc
)
403 fe
->finalizerProc(interp
, fe
->clientData
);
408 te
= eventLoop
->timeEventHead
;
411 if (te
->finalizerProc
)
412 te
->finalizerProc(interp
, te
->clientData
);
419 static int JimELVwaitCommand(Jim_Interp
*interp
, int argc
,
420 Jim_Obj
*const *argv
)
425 Jim_WrongNumArgs(interp
, 1, argv
, "name");
428 oldValue
= Jim_GetGlobalVariable(interp
, argv
[1], JIM_NONE
);
429 if (oldValue
) Jim_IncrRefCount(oldValue
);
433 Jim_ProcessEvents(interp
, JIM_ALL_EVENTS
);
434 currValue
= Jim_GetGlobalVariable(interp
, argv
[1], JIM_NONE
);
435 /* Stop the loop if the vwait-ed variable changed value,
436 * or if was unset and now is set (or the contrary). */
437 if ((oldValue
&& !currValue
) ||
438 (!oldValue
&& currValue
) ||
439 (oldValue
&& currValue
&&
440 !Jim_StringEqObj(oldValue
, currValue
, JIM_CASESENS
)))
443 if (oldValue
) Jim_DecrRefCount(interp
, oldValue
);
447 void JimAfterTimeHandler(Jim_Interp
*interp
, void *clientData
)
449 Jim_Obj
*objPtr
= clientData
;
451 Jim_EvalObjBackground(interp
, objPtr
);
454 void JimAfterTimeEventFinalizer(Jim_Interp
*interp
, void *clientData
)
456 Jim_Obj
*objPtr
= clientData
;
458 Jim_DecrRefCount(interp
, objPtr
);
461 static int JimELAfterCommand(Jim_Interp
*interp
, int argc
,
462 Jim_Obj
*const *argv
)
465 Jim_Obj
*objPtr
, *idObjPtr
;
466 const char *options
[] = {
467 "info", "cancel", "restart", "expire", NULL
469 enum {INFO
, CANCEL
, RESTART
, EXPIRE
, CREATE
};
470 int option
= CREATE
;
473 Jim_WrongNumArgs(interp
, 1, argv
, "<after milliseconds> script");
476 if (Jim_GetWide(interp
, argv
[1], &ms
) != JIM_OK
)
477 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "after options",
478 JIM_ERRMSG
) != JIM_OK
)
482 Jim_IncrRefCount(argv
[2]);
483 id
= Jim_CreateTimeHandler(interp
, ms
, JimAfterTimeHandler
, argv
[2],
484 JimAfterTimeEventFinalizer
);
485 objPtr
= Jim_NewStringObj(interp
, NULL
, 0);
486 Jim_AppendString(interp
, objPtr
, "after#", -1);
487 idObjPtr
= Jim_NewIntObj(interp
, id
);
488 Jim_IncrRefCount(idObjPtr
);
489 Jim_AppendObj(interp
, objPtr
, idObjPtr
);
490 Jim_DecrRefCount(interp
, idObjPtr
);
491 Jim_SetResult(interp
, objPtr
);
497 const char *tok
= Jim_GetString(argv
[2], &tlen
);
498 if (sscanf(tok
,"after#%" JIM_WIDE_MODIFIER
, &id
) == 1) {
499 remain
= Jim_DeleteTimeHandler(interp
, id
);
501 Jim_SetResult(interp
, Jim_NewIntObj(interp
, remain
));
505 Jim_SetResultString(interp
, "invalid event" , -1);
509 fprintf(stderr
,"unserviced option to after %d\n",option
);
514 /* This extension is not dynamically loaded, instead it's linked statically,
515 which is why we shouldn't use the unspecific 'Jim_OnLoad' name */
516 int Jim_EventLoopOnLoad(Jim_Interp
*interp
)
518 Jim_EventLoop
*eventLoop
;
520 Jim_InitExtension(interp
);
521 if (Jim_PackageProvide(interp
, "eventloop", "1.0", JIM_ERRMSG
) != JIM_OK
)
524 eventLoop
= Jim_Alloc(sizeof(*eventLoop
));
525 eventLoop
->fileEventHead
= NULL
;
526 eventLoop
->timeEventHead
= NULL
;
527 eventLoop
->timeEventNextId
= 1;
528 Jim_SetAssocData(interp
, "eventloop", JimELAssocDataDeleProc
, eventLoop
);
530 Jim_CreateCommand(interp
, "vwait", JimELVwaitCommand
, NULL
, NULL
);
531 Jim_CreateCommand(interp
, "after", JimELAfterCommand
, NULL
, NULL
);
533 /* Export events API */
534 Jim_RegisterApi(interp
, "Jim_CreateFileHandler", Jim_CreateFileHandler
);
535 Jim_RegisterApi(interp
, "Jim_DeleteFileHandler", Jim_DeleteFileHandler
);
536 Jim_RegisterApi(interp
, "Jim_CreateTimeHandler", Jim_CreateTimeHandler
);
537 Jim_RegisterApi(interp
, "Jim_DeleteTimeHandler", Jim_DeleteTimeHandler
);
538 Jim_RegisterApi(interp
, "Jim_ProcessEvents", Jim_ProcessEvents
);