lists: fix crash in ListInsertElements
[jimtcl.git] / jim-eventloop.c
bloba321f9ea4418a8ec57e858d207b4bea512f437f2
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
13 * are met:
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.
38 **/
39 /* TODO:
41 * - to really use flags in Jim_ProcessEvents()
42 * - more complete [after] command with [after info] and other subcommands.
43 * - Win32 port
45 #ifdef HAVE_CONFIG_H
46 #include "config.h"
47 #endif
49 #define JIM_EXTENSION
50 #define __JIM_EVENTLOOP_CORE__
51 #ifdef __ECOS
52 #include <pkgconf/jimtcl.h>
53 #include <sys/time.h>
54 #include <cyg/jimtcl/jim.h>
55 #include <cyg/jimtcl/jim-eventloop.h>
56 #else
57 #include "jim.h"
58 #include "jim-eventloop.h"
59 #endif
61 /* File event structure */
62 typedef struct Jim_FileEvent {
63 void *handle;
64 int mask; /* one of JIM_EVENT_(READABLE | WRITABLE | EXCEPTION) */
65 Jim_FileProc *fileProc;
66 Jim_EventFinalizerProc *finalizerProc;
67 void *clientData;
68 struct Jim_FileEvent *next;
69 } Jim_FileEvent;
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;
80 void *clientData;
81 struct Jim_TimeEvent *next;
82 } Jim_TimeEvent;
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;
89 } Jim_EventLoop;
91 void Jim_CreateFileHandler(Jim_Interp *interp, void *handle, int mask,
92 Jim_FileProc *proc, void *clientData,
93 Jim_EventFinalizerProc *finalizerProc)
95 Jim_FileEvent *fe;
96 Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
98 // fprintf(stderr,"rein\n");
99 fe = Jim_Alloc(sizeof(*fe));
100 fe->handle = handle;
101 fe->mask = mask;
102 fe->fileProc = proc;
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;
116 while (fe) {
117 if (fe->handle == handle) {
118 if (prev == NULL)
119 eventLoop->fileEventHead = fe->next;
120 else
121 prev->next = fe->next;
122 if (fe->finalizerProc)
123 fe->finalizerProc(interp, fe->clientData);
124 Jim_Free(fe);
125 return;
127 prev = fe;
128 fe = fe->next;
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
143 * to WIN32. */
144 static void JimGetTime(long *seconds, long *milliseconds)
146 struct timeval tv;
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++;
159 Jim_TimeEvent *te;
160 long cur_sec, cur_ms;
162 JimGetTime(&cur_sec, &cur_ms);
164 te = Jim_Alloc(sizeof(*te));
165 te->id = id;
166 te->mode = 0;
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) {
171 te->when_sec ++;
172 te->when_ms -= 1000;
174 te->timeProc = proc;
175 te->finalizerProc = finalizerProc;
176 te->clientData = clientData;
177 te->next = eventLoop->timeEventHead;
178 eventLoop->timeEventHead = te;
179 return id;
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;
187 jim_wide remain ;
189 JimGetTime(&cur_sec, &cur_ms);
191 te = eventLoop->timeEventHead;
192 if (id >= eventLoop->timeEventNextId)
193 return -2; /* wrong event ID */
194 while (te) {
195 if (te->id == id) {
196 remain = (te->when_sec - cur_sec) * 1000;
197 remain += (te->when_ms - cur_ms) ;
198 remain = (remain < 0) ? 0 : remain ;
200 if (prev == NULL)
201 eventLoop->timeEventHead = te->next;
202 else
203 prev->next = te->next;
204 if (te->finalizerProc)
205 te->finalizerProc(interp, te->clientData);
206 Jim_Free(te);
207 return remain;
209 prev = te;
210 te = te->next;
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;
224 while (te) {
225 if (!nearest || te->when_sec < nearest->when_sec ||
226 (te->when_sec == nearest->when_sec &&
227 te->when_ms < nearest->when_ms))
228 nearest = te;
229 te = te->next;
231 return nearest;
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;
259 Jim_TimeEvent *te;
260 jim_wide maxId;
261 JIM_NOTUSED(flags);
263 FD_ZERO(&rfds);
264 FD_ZERO(&wfds);
265 FD_ZERO(&efds);
267 /* Check file events */
268 while (fe != NULL) {
269 int fd = fileno((FILE*)fe->handle);
271 if (fe->mask & JIM_EVENT_READABLE)
272 FD_SET(fd, &rfds);
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;
276 numfd++;
277 fe = fe->next;
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
282 * to fire. */
283 if (numfd || ((flags & JIM_TIME_EVENTS) && !(flags & JIM_DONT_WAIT))) {
284 int retval;
285 Jim_TimeEvent *shortest;
286 struct timeval tv, *tvp;
287 jim_wide dt;
289 shortest = JimSearchNearestTimer(eventLoop);
290 if (shortest) {
291 long now_sec, now_ms;
293 /* Calculate the time missing for the nearest
294 * timer to fire. */
295 JimGetTime(&now_sec, &now_ms);
296 tvp = &tv;
297 dt = 1000 * (shortest->when_sec - now_sec);
298 dt += (shortest->when_ms - now_ms);
299 if (dt < 0) {
300 dt = 1;
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);
305 } else {
306 tvp = NULL; /* wait forever */
307 // fprintf(stderr,"No Event\n");
310 retval = select(maxfd + 1, &rfds, &wfds, &efds, tvp);
311 if (retval < 0) {
312 switch (errno) {
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;
319 while (fe != NULL) {
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)))
328 int mask = 0;
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);
343 processed++;
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;
349 FD_CLR(fd, &rfds);
350 FD_CLR(fd, &wfds);
351 FD_CLR(fd, &efds);
352 } else {
353 fe = fe->next;
358 /* Check time events */
359 te = eventLoop->timeEventHead;
360 maxId = eventLoop->timeEventNextId-1;
361 while (te) {
362 long now_sec, now_ms;
363 jim_wide id;
365 if (te->id > maxId) {
366 te = te->next;
367 continue;
369 JimGetTime(&now_sec, &now_ms);
370 if (now_sec > te->when_sec ||
371 (now_sec == te->when_sec && now_ms >= te->when_ms))
373 id = te->id;
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;
383 } else {
384 te = te->next;
388 return processed;
390 /* ---------------------------------------------------------------------- */
392 void JimELAssocDataDeleProc(Jim_Interp *interp, void *data)
394 void *next;
395 Jim_FileEvent *fe;
396 Jim_TimeEvent *te;
397 Jim_EventLoop *eventLoop = data;
399 fe = eventLoop->fileEventHead;
400 while (fe) {
401 next = fe->next;
402 if (fe->finalizerProc)
403 fe->finalizerProc(interp, fe->clientData);
404 Jim_Free(fe);
405 fe = next;
408 te = eventLoop->timeEventHead;
409 while (te) {
410 next = te->next;
411 if (te->finalizerProc)
412 te->finalizerProc(interp, te->clientData);
413 Jim_Free(te);
414 te = next;
416 Jim_Free(data);
419 static int JimELVwaitCommand(Jim_Interp *interp, int argc,
420 Jim_Obj *const *argv)
422 Jim_Obj *oldValue;
424 if (argc != 2) {
425 Jim_WrongNumArgs(interp, 1, argv, "name");
426 return JIM_ERR;
428 oldValue = Jim_GetGlobalVariable(interp, argv[1], JIM_NONE);
429 if (oldValue) Jim_IncrRefCount(oldValue);
430 while (1) {
431 Jim_Obj *currValue;
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)))
441 break;
443 if (oldValue) Jim_DecrRefCount(interp, oldValue);
444 return JIM_OK;
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)
464 jim_wide ms, id;
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 ;
472 if (argc < 3) {
473 Jim_WrongNumArgs(interp, 1, argv, "<after milliseconds> script");
474 return JIM_ERR;
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)
479 return JIM_ERR;
480 switch (option) {
481 case CREATE:
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);
492 return JIM_OK;
493 case CANCEL:
495 int tlen ;
496 jim_wide remain = 0;
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);
500 if (remain > -2) {
501 Jim_SetResult(interp, Jim_NewIntObj(interp, remain));
502 return JIM_OK;
505 Jim_SetResultString(interp, "invalid event" , -1);
506 return JIM_ERR;
508 default:
509 fprintf(stderr,"unserviced option to after %d\n",option);
511 return JIM_OK;
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)
522 return JIM_ERR;
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);
539 return JIM_OK;