- fix build issues under win32 (mingw)
[fw/openocd] / src / helper / jim-eventloop.c
1 /* Jim - A small embeddable Tcl interpreter
2  *
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>
10  * 
11  * The FreeBSD license
12  * 
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above
20  *    copyright notice, this list of conditions and the following
21  *    disclaimer in the documentation and/or other materials
22  *    provided with the distribution.
23  * 
24  * THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
25  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
26  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
27  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28  * JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
29  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
30  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
33  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  * 
37  * The views and conclusions contained in the software and documentation
38  * are those of the authors and should not be interpreted as representing
39  * official policies, either expressed or implied, of the Jim Tcl Project.
40  **/
41 /* TODO:
42  *
43  *  - to really use flags in Jim_ProcessEvents()
44  *  - more complete [after] command with [after info] and other subcommands.
45  *  - Win32 port
46  */
47
48 #define JIM_EXTENSION
49 #define __JIM_EVENTLOOP_CORE__
50 #ifdef __ECOS
51 #include <pkgconf/jimtcl.h>
52 #endif
53 #ifdef __ECOS
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
60
61 /* POSIX includes */
62 #include <sys/time.h>
63 #include <sys/types.h>
64 #include <unistd.h>
65 #include <errno.h>
66
67 #include "replacements.h"
68
69 extern int errno;
70 /* --- */
71
72 /* File event structure */
73 typedef struct Jim_FileEvent {
74     void *handle;
75     int mask; /* one of JIM_EVENT_(READABLE|WRITABLE|EXCEPTION) */
76     Jim_FileProc *fileProc;
77     Jim_EventFinalizerProc *finalizerProc;
78     void *clientData;
79     struct Jim_FileEvent *next;
80 } Jim_FileEvent;
81
82 /* Time event structure */
83 typedef struct Jim_TimeEvent {
84     jim_wide id; /* time event identifier. */
85     int mode;   /* restart, repetitive .. UK */
86     long initialms; /* initial relativ timer value UK */
87     long when_sec; /* seconds */
88     long when_ms; /* milliseconds */
89     Jim_TimeProc *timeProc;
90     Jim_EventFinalizerProc *finalizerProc;
91     void *clientData;
92     struct Jim_TimeEvent *next;
93 } Jim_TimeEvent;
94
95 /* Per-interp stucture containing the state of the event loop */
96 typedef struct Jim_EventLoop {
97     jim_wide timeEventNextId;
98     Jim_FileEvent *fileEventHead;
99     Jim_TimeEvent *timeEventHead;
100 } Jim_EventLoop;
101
102 void Jim_CreateFileHandler(Jim_Interp *interp, void *handle, int mask,
103         Jim_FileProc *proc, void *clientData,
104         Jim_EventFinalizerProc *finalizerProc)
105 {
106     Jim_FileEvent *fe;
107     Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
108
109         // fprintf(stderr,"rein\n");
110     fe = Jim_Alloc(sizeof(*fe));
111     fe->handle = handle;
112     fe->mask = mask;
113     fe->fileProc = proc;
114     fe->finalizerProc = finalizerProc;
115     fe->clientData = clientData;
116     fe->next = eventLoop->fileEventHead;
117     eventLoop->fileEventHead = fe;
118         // fprintf(stderr,"raus\n");
119 }
120
121 void Jim_DeleteFileHandler(Jim_Interp *interp, void *handle)
122 {
123     Jim_FileEvent *fe, *prev = NULL;
124     Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
125
126     fe = eventLoop->fileEventHead;
127     while(fe) {
128         if (fe->handle == handle) {
129             if (prev == NULL)
130                 eventLoop->fileEventHead = fe->next;
131             else
132                 prev->next = fe->next;
133             if (fe->finalizerProc)
134                 fe->finalizerProc(interp, fe->clientData);
135             Jim_Free(fe);
136             return;
137         }
138         prev = fe;
139         fe = fe->next;
140     }
141 }
142
143 // The same for signals.
144 void Jim_CreateSignalHandler(Jim_Interp *interp, int signum, 
145         Jim_FileProc *proc, void *clientData,
146         Jim_EventFinalizerProc *finalizerProc)
147 {
148 }
149 void Jim_DeleteSignalHandler(Jim_Interp *interp, int signum) 
150 {
151 }
152
153 /* That's another part of this extension that needs to be ported
154  * to WIN32. */
155 static void JimGetTime(long *seconds, long *milliseconds)
156 {
157     struct timeval tv;
158
159     gettimeofday(&tv, NULL);
160     *seconds = tv.tv_sec;
161     *milliseconds = tv.tv_usec/1000;
162 }
163
164 jim_wide Jim_CreateTimeHandler(Jim_Interp *interp, jim_wide milliseconds,
165         Jim_TimeProc *proc, void *clientData,
166         Jim_EventFinalizerProc *finalizerProc)
167 {
168     Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
169     jim_wide id = eventLoop->timeEventNextId++;
170     Jim_TimeEvent *te;
171     long cur_sec, cur_ms;
172
173     JimGetTime(&cur_sec, &cur_ms);
174
175     te = Jim_Alloc(sizeof(*te));
176     te->id = id;
177     te->mode = 0;
178     te->initialms = milliseconds;
179     te->when_sec = cur_sec + milliseconds/1000;
180     te->when_ms = cur_ms + milliseconds%1000;
181     if (te->when_ms >= 1000) {
182         te->when_sec ++;
183         te->when_ms -= 1000;
184     }
185     te->timeProc = proc;
186     te->finalizerProc = finalizerProc;
187     te->clientData = clientData;
188     te->next = eventLoop->timeEventHead;
189     eventLoop->timeEventHead = te;
190     return id;
191 }
192
193 jim_wide Jim_DeleteTimeHandler(Jim_Interp *interp, jim_wide id)
194 {
195     Jim_TimeEvent *te, *prev = NULL;
196     Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
197     long cur_sec, cur_ms;
198     jim_wide remain ;
199
200     JimGetTime(&cur_sec, &cur_ms);
201
202     te = eventLoop->timeEventHead;
203     if (id >= eventLoop->timeEventNextId) 
204         return -2; /* wrong event ID */
205     while(te) {
206         if (te->id == id) {
207             remain  = (te->when_sec - cur_sec) * 1000;
208             remain += (te->when_ms  - cur_ms) ;
209             remain = (remain < 0) ? 0 : remain ;
210
211             if (prev == NULL)
212                 eventLoop->timeEventHead = te->next;
213             else
214                 prev->next = te->next;
215             if (te->finalizerProc)
216                 te->finalizerProc(interp, te->clientData);
217             Jim_Free(te);
218             return remain;
219         }
220         prev = te;
221         te = te->next;
222     }
223     return -1; /* NO event with the specified ID found */
224 }
225
226 /* Search the first timer to fire.
227  * This operation is useful to know how many time the select can be
228  * put in sleep without to delay any event.
229  * If there are no timers NULL is returned. */
230 static Jim_TimeEvent *JimSearchNearestTimer(Jim_EventLoop *eventLoop)
231 {
232     Jim_TimeEvent *te = eventLoop->timeEventHead;
233     Jim_TimeEvent *nearest = NULL;
234
235     while(te) {
236         if (!nearest || te->when_sec < nearest->when_sec ||
237                 (te->when_sec == nearest->when_sec &&
238                  te->when_ms < nearest->when_ms))
239             nearest = te;
240         te = te->next;
241     }
242     return nearest;
243 }
244
245 /* Process every pending time event, then every pending file event
246  * (that may be registered by time event callbacks just processed).
247  * Without special flags the function sleeps until some file event
248  * fires, or when the next time event occurrs (if any).
249  *
250  * If flags is 0, the function does nothing and returns.
251  * if flags has JIM_ALL_EVENTS set, all the kind of events are processed.
252  * if flags has JIM_FILE_EVENTS set, file events are processed.
253  * if flags has JIM_TIME_EVENTS set, time events are processed.
254  * if flags has JIM_DONT_WAIT set the function returns ASAP until all
255  * the events that's possible to process without to wait are processed.
256  *
257  * The function returns the number of events processed. */
258 int Jim_ProcessEvents(Jim_Interp *interp, int flags)
259 {
260     int maxfd = 0, numfd = 0, processed = 0;
261     fd_set rfds, wfds, efds;
262     Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
263     Jim_FileEvent *fe = eventLoop->fileEventHead;
264     Jim_TimeEvent *te;
265     jim_wide maxId;
266     JIM_NOTUSED(flags);
267
268     FD_ZERO(&rfds);
269     FD_ZERO(&wfds);
270     FD_ZERO(&efds);
271
272     /* Check file events */
273     while (fe != NULL) {
274         int fd = fileno((FILE*)fe->handle);
275
276         if (fe->mask & JIM_EVENT_READABLE) 
277                 FD_SET(fd, &rfds);
278         if (fe->mask & JIM_EVENT_WRITABLE) FD_SET(fd, &wfds);
279         if (fe->mask & JIM_EVENT_EXCEPTION) FD_SET(fd, &efds);
280         if (maxfd < fd) maxfd = fd;
281         numfd++;
282         fe = fe->next;
283     }
284     /* Note that we want call select() even if there are no
285      * file events to process as long as we want to process time
286      * events, in order to sleep until the next time event is ready
287      * to fire. */
288     if (numfd || ((flags & JIM_TIME_EVENTS) && !(flags & JIM_DONT_WAIT))) {
289         int retval;
290         Jim_TimeEvent *shortest;
291         struct timeval tv, *tvp;
292         jim_wide dt;
293
294         shortest = JimSearchNearestTimer(eventLoop);
295         if (shortest) {
296             long now_sec, now_ms;
297
298             /* Calculate the time missing for the nearest
299              * timer to fire. */
300             JimGetTime(&now_sec, &now_ms);
301             tvp = &tv;
302             dt   = 1000 * (shortest->when_sec - now_sec);
303             dt  += ( shortest->when_ms  - now_ms);
304             if (dt < 0) {
305                 dt = 1;
306             }
307             tvp->tv_sec  = dt / 1000;
308             tvp->tv_usec = dt % 1000;
309             // fprintf(stderr,"Next %d.% 8d\n",(int)tvp->tv_sec,(int)tvp->tv_usec);
310         } else {
311             tvp = NULL; /* wait forever */
312                 // fprintf(stderr,"No Event\n");
313         }
314
315         retval = select(maxfd+1, &rfds, &wfds, &efds, tvp);
316         if (retval < 0) {
317            switch (errno) {
318                case EINTR:   fprintf(stderr,"select EINTR\n"); break;
319                case EINVAL:  fprintf(stderr,"select EINVAL\n"); break;
320                case ENOMEM:  fprintf(stderr,"select ENOMEM\n"); break;
321            }
322         } else if (retval > 0) {
323             fe = eventLoop->fileEventHead;
324             while(fe != NULL) {
325                 int fd = fileno((FILE*)fe->handle);
326
327                 // fprintf(stderr,"fd: %d mask: %02x \n",fd,fe->mask);
328
329                 if ((fe->mask & JIM_EVENT_READABLE && FD_ISSET(fd, &rfds)) ||
330                     (fe->mask & JIM_EVENT_WRITABLE && FD_ISSET(fd, &wfds)) ||
331                     (fe->mask & JIM_EVENT_EXCEPTION && FD_ISSET(fd, &efds)))
332                 {
333                     int mask = 0;
334
335                     if (fe->mask & JIM_EVENT_READABLE && FD_ISSET(fd, &rfds)) {
336                         mask |= JIM_EVENT_READABLE;
337                         if ((fe->mask & JIM_EVENT_FEOF) && feof((FILE *)fe->handle))
338                                 mask |= JIM_EVENT_FEOF;
339                     }
340                     if (fe->mask & JIM_EVENT_WRITABLE && FD_ISSET(fd, &wfds))
341                         mask |= JIM_EVENT_WRITABLE;
342                     if (fe->mask & JIM_EVENT_EXCEPTION && FD_ISSET(fd, &efds))
343                         mask |= JIM_EVENT_EXCEPTION;
344                     if (fe->fileProc(interp, fe->clientData, mask) == JIM_ERR) {
345                         /* Remove the element on handler error */
346                         Jim_DeleteFileHandler(interp, fe->handle);
347                     }
348                     processed++;
349                     /* After an event is processed our file event list
350                      * may no longer be the same, so what we do
351                      * is to clear the bit for this file descriptor and
352                      * restart again from the head. */
353                     fe = eventLoop->fileEventHead;
354                     FD_CLR(fd, &rfds);
355                     FD_CLR(fd, &wfds);
356                     FD_CLR(fd, &efds);
357                 } else {
358                     fe = fe->next;
359                 }
360             }
361         }
362     }
363     /* Check time events */
364     te = eventLoop->timeEventHead;
365     maxId = eventLoop->timeEventNextId-1;
366     while(te) {
367         long now_sec, now_ms;
368         jim_wide id;
369
370         if (te->id > maxId) {
371             te = te->next;
372             continue;
373         }
374         JimGetTime(&now_sec, &now_ms);
375         if (now_sec > te->when_sec ||
376             (now_sec == te->when_sec && now_ms >= te->when_ms))
377         {
378             id = te->id;
379             te->timeProc(interp, te->clientData);
380             /* After an event is processed our time event list may
381              * no longer be the same, so we restart from head.
382              * Still we make sure to don't process events registered
383              * by event handlers itself in order to don't loop forever
384              * even in case an [after 0] that continuously register
385              * itself. To do so we saved the max ID we want to handle. */
386             Jim_DeleteTimeHandler(interp, id);
387             te = eventLoop->timeEventHead;
388         } else {
389             te = te->next;
390         }
391     }
392
393     return processed;
394 }
395 /* ---------------------------------------------------------------------- */
396
397 void JimELAssocDataDeleProc(Jim_Interp *interp, void *data)
398 {
399     void *next;
400     Jim_FileEvent *fe;
401     Jim_TimeEvent *te;
402     Jim_EventLoop *eventLoop = data;
403
404     fe = eventLoop->fileEventHead;
405     while(fe) {
406         next = fe->next;
407         if (fe->finalizerProc)
408             fe->finalizerProc(interp, fe->clientData);
409         Jim_Free(fe);
410         fe = next;
411     }
412
413     te = eventLoop->timeEventHead;
414     while(te) {
415         next = te->next;
416         if (te->finalizerProc)
417             te->finalizerProc(interp, te->clientData);
418         Jim_Free(te);
419         te = next;
420     }
421     Jim_Free(data);
422 }
423
424 static int JimELVwaitCommand(Jim_Interp *interp, int argc, 
425         Jim_Obj *const *argv)
426 {
427     Jim_Obj *oldValue;
428
429     if (argc != 2) {
430         Jim_WrongNumArgs(interp, 1, argv, "name");
431         return JIM_ERR;
432     }
433     oldValue = Jim_GetGlobalVariable(interp, argv[1], JIM_NONE);
434     if (oldValue) Jim_IncrRefCount(oldValue);
435     while (1) {
436         Jim_Obj *currValue;
437
438         Jim_ProcessEvents(interp, JIM_ALL_EVENTS);
439         currValue = Jim_GetGlobalVariable(interp, argv[1], JIM_NONE);
440         /* Stop the loop if the vwait-ed variable changed value,
441          * or if was unset and now is set (or the contrary). */
442         if ((oldValue && !currValue) ||
443             (!oldValue && currValue) ||
444             (oldValue && currValue &&
445              !Jim_StringEqObj(oldValue, currValue, JIM_CASESENS)))
446             break;
447     }
448     if (oldValue) Jim_DecrRefCount(interp, oldValue);
449     return JIM_OK;
450 }
451
452 void JimAfterTimeHandler(Jim_Interp *interp, void *clientData)
453 {
454     Jim_Obj *objPtr = clientData;
455
456     Jim_EvalObjBackground(interp, objPtr);
457 }
458
459 void JimAfterTimeEventFinalizer(Jim_Interp *interp, void *clientData)
460 {
461     Jim_Obj *objPtr = clientData;
462
463     Jim_DecrRefCount(interp, objPtr);
464 }
465
466 static int JimELAfterCommand(Jim_Interp *interp, int argc, 
467         Jim_Obj *const *argv)
468 {
469     jim_wide ms, id;
470     Jim_Obj *objPtr, *idObjPtr;
471     const char *options[] = {
472         "info", "cancel", "restart", "expire", NULL
473     };
474     enum {INFO, CANCEL, RESTART, EXPIRE, CREATE };
475     int option = CREATE ;
476
477     if (argc < 3) {
478         Jim_WrongNumArgs(interp, 1, argv, "<after milliseconds> script");
479         return JIM_ERR;
480     }
481     if (Jim_GetWide(interp, argv[1], &ms) != JIM_OK)
482         if (Jim_GetEnum(interp, argv[1], options, &option, "after options",
483                     JIM_ERRMSG) != JIM_OK)
484             return JIM_ERR;
485     switch (option) {
486     case CREATE:
487         Jim_IncrRefCount(argv[2]);
488         id = Jim_CreateTimeHandler(interp, ms, JimAfterTimeHandler, argv[2],
489                 JimAfterTimeEventFinalizer);
490         objPtr = Jim_NewStringObj(interp, NULL, 0);
491         Jim_AppendString(interp, objPtr, "after#", -1);
492         idObjPtr = Jim_NewIntObj(interp, id);
493         Jim_IncrRefCount(idObjPtr);
494         Jim_AppendObj(interp, objPtr, idObjPtr);
495         Jim_DecrRefCount(interp, idObjPtr);
496         Jim_SetResult(interp, objPtr);
497         return JIM_OK;
498     case CANCEL:
499         {
500         int tlen ;
501         jim_wide remain = 0;
502         const char *tok = Jim_GetString(argv[2], &tlen);
503         if ( sscanf(tok,"after#%lld",&id) == 1) {
504                 remain =  Jim_DeleteTimeHandler(interp, id);
505                 if (remain > -2)  {
506                         Jim_SetResult(interp, Jim_NewIntObj(interp, remain));
507                         return JIM_OK;
508                 }
509         }
510         Jim_SetResultString(interp, "invalid event" , -1);
511         return JIM_ERR;
512         }
513     default:
514         fprintf(stderr,"unserviced option to after %d\n",option);
515     } 
516     return JIM_OK;
517 }
518
519 /* This extension is not dynamically loaded, instead it's linked statically,
520    which is why we shouldn't use the unspecific 'Jim_OnLoad' name */
521 #define Jim_OnLoad Jim_EventLoopOnLoad
522
523 int Jim_OnLoad(Jim_Interp *interp)
524 {
525     Jim_EventLoop *eventLoop;
526
527     Jim_InitExtension(interp);
528     if (Jim_PackageProvide(interp, "eventloop", "1.0", JIM_ERRMSG) != JIM_OK)
529         return JIM_ERR;
530
531     eventLoop = Jim_Alloc(sizeof(*eventLoop));
532     eventLoop->fileEventHead = NULL;
533     eventLoop->timeEventHead = NULL;
534     eventLoop->timeEventNextId = 1;
535     Jim_SetAssocData(interp, "eventloop", JimELAssocDataDeleProc, eventLoop);
536
537     Jim_CreateCommand(interp, "vwait", JimELVwaitCommand, NULL, NULL);
538     Jim_CreateCommand(interp, "after", JimELAfterCommand, NULL, NULL);
539
540     /* Export events API */
541     Jim_RegisterApi(interp, "Jim_CreateFileHandler", Jim_CreateFileHandler);
542     Jim_RegisterApi(interp, "Jim_DeleteFileHandler", Jim_DeleteFileHandler);
543     Jim_RegisterApi(interp, "Jim_CreateTimeHandler", Jim_CreateTimeHandler);
544     Jim_RegisterApi(interp, "Jim_DeleteTimeHandler", Jim_DeleteTimeHandler);
545     Jim_RegisterApi(interp, "Jim_ProcessEvents", Jim_ProcessEvents);
546     return JIM_OK;
547 }