1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
|
/* Part of SWI-Prolog
Author: Jan Wielemaker
E-mail: J.Wielemaker@vu.nl
WWW: http://www.swi-prolog.org
Copyright (c) 2002-2022, University of Amsterdam
VU University Amsterdam
SWI-Prolog Solutions b.v.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#define O_DEBUG 1 /* provides time:time_debug(+Level) */
//#define O_SAFE 1 /* extra safety checks */
#include <config.h>
#include <SWI-Stream.h>
#include <SWI-Prolog.h>
#include "error.h"
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <math.h>
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif
#include <string.h>
#include <errno.h>
#include <assert.h>
#ifdef O_SAFE
#define __USE_GNU
#endif
#ifdef __WINDOWS__
#undef ETIMEDOUT
#endif
#include <pthread.h>
typedef enum
{ TIME_ABS,
TIME_REL
} time_abs_rel;
#ifdef __WINDOWS__
#ifndef SIGALRM
#define SIGALRM 14
#endif
#endif
#ifdef _MSC_VER
#include <sys/timeb.h>
#include <malloc.h>
#ifndef WIN_PTHREADS
struct timeval
{ long tv_sec;
long tv_usec;
};
#endif
struct timezone
{ int zone;
};
static int
gettimeofday(struct timeval *tv, struct timezone *tz)
{ struct timeb tb;
ftime(&tb);
tv->tv_sec = (long)tb.time;
tv->tv_usec = tb.millitm * 1000;
return 0;
}
#else /*_MSC_VER*/
#include <time.h>
#include <sys/time.h>
#endif /*_MSC_VER*/
#ifdef O_DEBUG
static int debuglevel = 0;
#define DEBUG(n, g) if ( debuglevel >= n ) g
static foreign_t
pl_time_debug(term_t n)
{ return PL_get_integer(n, &debuglevel);
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
glibc defines backtrace() and friends to print the calling context. For
debugging this is just great, as the problem generally appear after
generating an exception.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#ifdef HAVE_EXECINFO_H
#define BACKTRACE 1
#if BACKTRACE
#include <execinfo.h>
#include <string.h>
static void
print_trace (void)
{ void *array[100];
size_t size;
char **strings;
size_t i;
size = backtrace(array, sizeof(array)/sizeof(void *));
strings = backtrace_symbols(array, size);
#ifdef _REENTRANT
Sdprintf("on_alarm() Prolog-context [thread %d]:\n", PL_thread_self());
#else
Sdprintf("on_alarm() Prolog-context:\n");
#endif
PL_action(PL_ACTION_BACKTRACE, 3);
Sdprintf("on_alarm() C-context:\n");
for(i = 0; i < size; i++)
{ if ( !strstr(strings[i], "checkData") )
Sdprintf("\t[%d] %s\n", i, strings[i]);
}
free(strings);
}
#endif /*BACKTRACE*/
#endif /*HAVE_EXECINFO_H*/
#else /*O_DEBUG*/
#define DEBUG(n, g) ((void)0)
#endif /*O_DEBUG*/
static void on_alarm(int sig);
static module_t MODULE_user;
static atom_t ATOM_remove;
static atom_t ATOM_install;
static atom_t ATOM_done;
static atom_t ATOM_next;
static atom_t ATOM_scheduled;
static functor_t FUNCTOR_module2;
static functor_t FUNCTOR_alarm1;
static functor_t FUNCTOR_alarm4;
static predicate_t PREDICATE_call1;
#define EV_MAGIC 1920299187 /* Random magic number */
#define EV_DONE 0x0001 /* Handled this one */
#define EV_REMOVE 0x0002 /* Automatically remove */
#define EV_FIRED 0x0004 /* Windows: got this one */
#define EV_NOINSTALL 0x0008 /* Only allocate; do not install */
typedef struct event
{ record_t goal; /* Thing to call */
module_t module; /* Module to call in */
struct event *next; /* linked list for current */
struct event *previous; /* idem */
unsigned long flags; /* misc flags */
long magic; /* validate magic */
struct timeval at; /* Time to deliver */
pthread_t thread_id; /* Thread to call in */
int pl_thread_id; /* Prolog thread ID */
} event, *Event;
typedef void (*handler_t)(int);
typedef struct
{ Event first; /* first in list */
Event scheduled; /* The one we scheduled for */
int stop; /* stop alarm-loop */
} schedule;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static int scheduler_running = FALSE; /* is scheduler running? */
static pthread_t scheduler; /* thread id of scheduler */
#define LOCK() pthread_mutex_lock(&mutex)
#define UNLOCK() pthread_mutex_unlock(&mutex)
static schedule the_schedule = {0}; /* the schedule */
#define TheSchedule() (&the_schedule) /* current schedule */
static int signal_function_set = FALSE; /* signal function is set */
static int sig_time = 0;
static pl_sigaction_t saved_sigaction; /* Old signal action */
static int removeEvent(Event ev);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Allocate the event, maintaining a time-sorted list of scheduled events.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static Event
allocEvent()
{ Event ev = malloc(sizeof(*ev));
if ( !ev )
{ pl_error(NULL, 0, NULL, ERR_ERRNO, errno, "allocate", "memory", 0);
return NULL;
}
memset(ev, 0, sizeof(*ev));
ev->magic = EV_MAGIC;
return ev;
}
static void
setTimeEventAbs(Event ev, double t)
{ struct timeval tv;
gettimeofday(&tv, NULL);
tv.tv_usec = (long)((t-floor(t))*1000000);
tv.tv_sec = (long)t;
ev->at = tv;
}
static void
setTimeEvent(Event ev, double t)
{ struct timeval tv;
gettimeofday(&tv, NULL);
tv.tv_usec += (long)((t-floor(t))*1000000);
tv.tv_sec += (long)t;
if ( tv.tv_usec >= 1000000 )
{ tv.tv_usec -= 1000000;
tv.tv_sec++;
}
ev->at = tv;
}
static int
insertEvent(Event ev)
{ schedule *sched = TheSchedule();
Event e;
DEBUG(1, Sdprintf("insertEvent(%d.%06d)\n", ev->at.tv_sec, ev->at.tv_usec));
for(e = sched->first; e; e = e->next)
{ struct timeval d;
if ( e == ev )
return ERR_PERMISSION; /* already scheduled */
d.tv_sec = ev->at.tv_sec - e->at.tv_sec;
d.tv_usec = ev->at.tv_usec - e->at.tv_usec;
if ( d.tv_usec < 0 )
{ d.tv_sec--;
d.tv_usec += 1000000;
}
if ( d.tv_sec < 0 ) /* new must be before e */
{ ev->next = e;
ev->previous = e->previous;
if ( e->previous )
{ e->previous->next = ev;
} else
{ assert(sched->first == e);
sched->first = ev;
}
e->previous = ev;
return TRUE;
} else
{ if ( e->next )
continue;
ev->previous = e; /* end of the list */
e->next = ev;
return TRUE;
}
}
sched->first = ev; /* the very first one */
return TRUE;
}
static void
unlinkEvent(Event ev)
{ schedule *sched = TheSchedule();
if ( sched->scheduled == ev )
sched->scheduled = NULL;
if ( ev->previous )
ev->previous->next = ev->next;
else
sched->first = ev->next;
if ( ev->next )
ev->next->previous = ev->previous;
ev->next = ev->previous = NULL; /* in case it's reused */
}
static void
freeEvent(Event ev)
{ unlinkEvent(ev);
if ( ev->goal )
PL_erase(ev->goal);
ev->magic = 0;
free(ev);
}
static void
cleanupHandler(void)
{ if ( signal_function_set )
{ PL_sigaction(sig_time, &saved_sigaction, NULL);
signal_function_set = FALSE;
}
}
static int
installHandler(void)
{ if ( !signal_function_set )
{ pl_sigaction_t act = {0};
act.sa_cfunction = on_alarm;
act.sa_flags = PLSIG_SYNC;
if ( (sig_time = PL_sigaction(0, &act, &saved_sigaction)) > 0 )
signal_function_set = TRUE;
else
return PL_warning("Could not initialize alarm signal handler\n");
}
return TRUE;
}
static int
cleanup(int rc, void *arg)
{ Event ev;
schedule *sched = TheSchedule();
sched->stop = TRUE;
while( (ev=sched->first) )
removeEvent(ev);
cleanupHandler();
if ( scheduler_running )
{ LOCK();
pthread_cond_signal(&cond);
UNLOCK();
pthread_join(scheduler, NULL);
scheduler_running = FALSE;
}
return 0;
}
static void
cleanup_thread(void *data)
{ schedule *sched = TheSchedule();
(void)data;
if ( sched->first )
{ Event ev, next;
int self = PL_thread_self();
LOCK();
for( ev=sched->first; ev; ev=next )
{ next = ev->next;
if ( self == ev->pl_thread_id )
{ DEBUG(1, Sdprintf("[%d] removing alarm %ld at exit\n",
PL_thread_self(), (long)(intptr_t)ev));
if ( sched->scheduled == ev )
ev->flags |= EV_DONE;
freeEvent(ev);
}
}
pthread_cond_signal(&cond);
UNLOCK();
}
}
static Event
nextEvent(schedule *sched)
{ Event ev;
for(ev=sched->first; ev; ev = ev->next)
{ if ( ev->flags & (EV_DONE|EV_FIRED) )
continue;
return ev;
}
return NULL;
}
typedef struct
{ int *bits;
size_t size;
size_t high;
} bitvector;
#define BITSPERINT (8*sizeof(int))
static int
set_bit(bitvector *v, size_t bit)
{ size_t offset = bit/BITSPERINT;
int bi = bit%BITSPERINT;
while ( offset >= v->size )
{ size_t osize = v->size * sizeof(int);
int *newbits = realloc(v->bits, osize*2);
if ( !newbits )
return FALSE;
memset((char*)newbits+osize, 0, osize);
v->bits = newbits;
v->size *= 2;
}
while ( bit > v->high ) /* TBD: zero entire ints */
{ size_t ho = v->high/BITSPERINT;
int b = v->high%BITSPERINT;
v->bits[ho] &= ~(1<<(b-1));
v->high++;
}
v->bits[offset] |= 1<<(bi-1);
return TRUE;
}
static int
is_set(bitvector *v, size_t bit)
{ if ( bit <= v->high )
{ size_t offset = bit/BITSPERINT;
int bi = bit%BITSPERINT;
return (v->bits[offset] & (1<<(bi-1))) != 0;
}
return FALSE;
}
static void *
alarm_loop(void * closure)
{ schedule *sched = TheSchedule();
bitvector signalled;
signalled.size = 4;
signalled.bits = malloc(signalled.size*sizeof(int));
signalled.high = 0;
LOCK(); /* for condition variable */
DEBUG(1, Sdprintf("Iterating alarm_loop()\n"));
while( !sched->stop )
{ Event ev = nextEvent(sched);
struct timeval now;
signalled.high = 0;
gettimeofday(&now, NULL);
for(; ev; ev = ev->next)
{ struct timeval left;
left.tv_sec = ev->at.tv_sec - now.tv_sec;
left.tv_usec = ev->at.tv_usec - now.tv_usec;
if ( left.tv_usec < 0 )
{ left.tv_sec--;
left.tv_usec += 1000000;
}
if ( left.tv_sec < 0 ||
(left.tv_sec == 0 && left.tv_usec == 0) )
{ if ( !is_set(&signalled, ev->pl_thread_id) )
{ DEBUG(1, Sdprintf("Signalling (left = %ld) %d ...\n",
(long)left.tv_sec,
ev->pl_thread_id));
set_bit(&signalled, ev->pl_thread_id);
PL_thread_raise(ev->pl_thread_id, sig_time);
}
} else
break;
}
if ( ev )
{ int rc;
struct timespec timeout;
timeout.tv_sec = ev->at.tv_sec;
timeout.tv_nsec = ev->at.tv_usec*1000;
retry_timed_wait:
DEBUG(1, Sdprintf("Waiting ...\n"));
rc = pthread_cond_timedwait(&cond, &mutex, &timeout);
switch( rc )
{ case ETIMEDOUT:
case 0:
continue;
case EINTR:
goto retry_timed_wait;
default:
Sdprintf("alarm/4: pthread_cond_timedwait(): %d (%s)\n",
rc, strerror(rc));
assert(0);
}
} else
{ int rc;
retry_wait:
DEBUG(1, Sdprintf("No waiting events\n"));
rc = pthread_cond_wait(&cond, &mutex);
switch(rc)
{ case EINTR:
goto retry_wait;
case 0:
continue;
default:
Sdprintf("alarm/4: pthread_cond_timedwait(): %d (%s)\n",
rc, strerror(rc));
assert(0);
}
}
}
free(signalled.bits);
return NULL;
}
static void
on_alarm(int sig)
{ Event ev;
schedule *sched = TheSchedule();
pthread_t self = pthread_self();
DEBUG(1, Sdprintf("Signal received in %d\n",
PL_thread_self()));
#ifdef BACKTRACE
DEBUG(10, print_trace());
#endif
for(;;)
{ struct timeval now;
term_t goal = 0;
module_t module = NULL;
gettimeofday(&now, NULL);
LOCK();
for(ev = sched->first; ev; ev=ev->next)
{ struct timeval left;
assert(ev->magic == EV_MAGIC);
if ( (ev->flags & (EV_DONE|EV_FIRED)) ||
!pthread_equal(self, ev->thread_id) )
continue;
left.tv_sec = ev->at.tv_sec - now.tv_sec;
left.tv_usec = ev->at.tv_usec - now.tv_usec;
if ( left.tv_usec < 0 )
{ left.tv_sec--;
left.tv_usec += 1000000;
}
if ( left.tv_sec < 0 ||
(left.tv_sec == 0 && left.tv_usec == 0) )
{ DEBUG(1, Sdprintf("Calling event\n"));
ev->flags |= EV_DONE;
module = ev->module;
goal = PL_new_term_ref();
PL_recorded(ev->goal, goal);
if ( ev->flags & EV_REMOVE )
freeEvent(ev);
break;
}
}
UNLOCK();
if ( goal )
{ PL_call_predicate(module,
PL_Q_PASS_EXCEPTION,
PREDICATE_call1,
goal);
} else
break;
}
DEBUG(1, Sdprintf("Processed pending events; signalling scheduler\n"));
LOCK();
pthread_cond_signal(&cond);
UNLOCK();
}
static int
installEvent(Event ev)
{ int rc;
ev->thread_id = pthread_self();
ev->pl_thread_id = PL_thread_self();
LOCK();
if ( !scheduler_running )
{ pthread_attr_t attr;
TheSchedule()->stop = FALSE;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 8192);
rc = pthread_create(&scheduler, &attr, alarm_loop, NULL);
pthread_attr_destroy(&attr);
if ( rc != 0 )
{ UNLOCK();
return pl_error("alarm", 4, "Failed to start schedule thread",
ERR_ERRNO, rc);
}
DEBUG(1, Sdprintf("Started scheduler thread\n"));
scheduler_running = TRUE;
}
if ( (rc = insertEvent(ev)) )
pthread_cond_signal(&cond);
UNLOCK();
return rc;
}
static int
uninstallEvent(Event ev)
{ LOCK();
if ( TheSchedule()->scheduled == ev )
ev->flags |= EV_DONE;
unlinkEvent(ev);
ev->flags &= ~(EV_FIRED|EV_DONE);
pthread_cond_signal(&cond);
UNLOCK();
return TRUE;
}
static int
removeEvent(Event ev)
{ LOCK();
if ( TheSchedule()->scheduled == ev )
ev->flags |= EV_DONE;
freeEvent(ev);
pthread_cond_signal(&cond);
UNLOCK();
return TRUE;
}
/*******************************
* PROLOG CONNECTION *
*******************************/
int
alarm_error(term_t alarm, int err)
{ switch(err)
{ case ERR_RESOURCE:
return pl_error(NULL, 0, NULL, ERR_RESOURCE, "timers");
case ERR_PERMISSION:
return pl_error(NULL, 0, "already installed", ERR_PERMISSION,
alarm, "install", "alarm");
default:
assert(0);
return FALSE;
}
}
static int
unify_timer(term_t t, Event ev)
{ if ( !PL_is_variable(t) )
return pl_error(NULL, 0, NULL, ERR_ARGTYPE, 0, t, "unbound");
return PL_unify_term(t,
PL_FUNCTOR, FUNCTOR_alarm1,
PL_POINTER, ev);
}
static int
get_timer(term_t t, Event *ev)
{ if ( TheSchedule()->stop )
return FALSE;
if ( PL_is_functor(t, FUNCTOR_alarm1) )
{ term_t a = PL_new_term_ref();
void *p;
_PL_get_arg(1, t, a);
if ( PL_get_pointer(a, &p) )
{ Event e = p;
if ( e->magic == EV_MAGIC )
{ *ev = e;
return TRUE;
} else
{ return pl_error("get_timer", 1, NULL,
ERR_DOMAIN, t, "alarm");
}
}
}
return pl_error("get_timer", 1, NULL,
ERR_ARGTYPE, 1, t, "alarm");
}
static int
pl_get_bool_ex(term_t arg, int *val)
{ if ( PL_get_bool(arg, val) )
return TRUE;
return pl_error(NULL, 0, NULL, ERR_ARGTYPE, 0, arg, "bool");
}
static foreign_t
alarm4_gen(time_abs_rel abs_rel, term_t time, term_t callable,
term_t id, term_t options)
{ Event ev;
double t;
module_t m = NULL;
unsigned long flags = 0L;
if ( options )
{ term_t tail = PL_copy_term_ref(options);
term_t head = PL_new_term_ref();
while( PL_get_list(tail, head, tail) )
{ atom_t name;
size_t arity;
if ( PL_get_name_arity(head, &name, &arity) )
{ if ( arity == 1 )
{ term_t arg = PL_new_term_ref();
_PL_get_arg(1, head, arg);
if ( name == ATOM_remove )
{ int t = FALSE;
if ( !pl_get_bool_ex(arg, &t) )
return FALSE;
if ( t )
flags |= EV_REMOVE;
} else if ( name == ATOM_install )
{ int t = TRUE;
if ( !pl_get_bool_ex(arg, &t) )
return FALSE;
if ( !t )
flags |= EV_NOINSTALL;
}
}
}
}
if ( !PL_get_nil(tail) )
return pl_error(NULL, 0, NULL, ERR_ARGTYPE, 4, options, "list");
}
if ( !PL_get_float(time, &t) )
return pl_error(NULL, 0, NULL, ERR_ARGTYPE, 1,
time, "number");
if ( !PL_strip_module(callable, &m, callable) )
return FALSE;
if ( !(ev = allocEvent()) )
return FALSE;
if (abs_rel==TIME_REL)
setTimeEvent(ev, t);
else
setTimeEventAbs(ev,t);
if ( !unify_timer(id, ev) )
{ freeEvent(ev); /* not linked: no need to lock */
return FALSE;
}
ev->flags = flags;
ev->module = m;
ev->goal = PL_record(callable);
if ( !(ev->flags & EV_NOINSTALL) )
{ int rc;
if ( (rc=installEvent(ev)) != TRUE )
{ freeEvent(ev); /* not linked: no need to lock */
return alarm_error(id, rc);
}
}
return TRUE;
}
static foreign_t
alarm4_abs(term_t time, term_t callable, term_t id, term_t options)
{ return alarm4_gen(TIME_ABS,time,callable,id,options);
}
static foreign_t
alarm4_rel(term_t time, term_t callable, term_t id, term_t options)
{ return alarm4_gen(TIME_REL,time,callable,id,options);
}
static foreign_t
alarm3_abs(term_t time, term_t callable, term_t id)
{ return alarm4_gen(TIME_ABS,time, callable, id, 0);
}
static foreign_t
alarm3_rel(term_t time, term_t callable, term_t id)
{ return alarm4_gen(TIME_REL,time, callable, id, 0);
}
static foreign_t
install_alarm(term_t alarm)
{ Event ev = NULL;
int rc;
if ( !get_timer(alarm, &ev) )
return FALSE;
if ( (rc=installEvent(ev)) != TRUE )
return alarm_error(alarm, rc);
return TRUE;
}
static foreign_t
install_alarm2(term_t alarm, term_t time)
{ Event ev = NULL;
double t;
int rc;
if ( !get_timer(alarm, &ev) )
return FALSE;
if ( !PL_get_float(time, &t) )
return pl_error(NULL, 0, NULL, ERR_ARGTYPE, 1,
time, "number");
setTimeEvent(ev, t);
if ( (rc=installEvent(ev)) != TRUE )
return alarm_error(alarm, rc);
return TRUE;
}
static foreign_t
uninstall_alarm(term_t alarm)
{ Event ev = NULL;
if ( !get_timer(alarm, &ev) )
return FALSE;
return uninstallEvent(ev);
}
static foreign_t
remove_alarm(term_t alarm)
{ if ( !TheSchedule()->stop )
{ Event ev = NULL;
if ( !get_timer(alarm, &ev) )
return FALSE;
return removeEvent(ev);
}
return TRUE;
}
static int
unify_event_goal(term_t goal, Event ev)
{ term_t g = PL_new_term_ref();
return ( PL_recorded(ev->goal, g) &&
PL_unify_term(goal,
PL_FUNCTOR, FUNCTOR_module2,
PL_ATOM, PL_module_name(ev->module),
PL_TERM, g) );
}
static foreign_t
current_alarms(term_t time, term_t goal, term_t id, term_t status,
term_t matching)
{ Event ev;
term_t next = PL_new_term_ref();
term_t tail = PL_copy_term_ref(matching);
term_t head = PL_new_term_ref();
term_t av = PL_new_term_refs(4);
pthread_t self = pthread_self();
int iterate;
LOCK();
if ( !PL_is_variable(id) )
{ if ( !get_timer(id, &ev) )
{ UNLOCK();
return FALSE;
}
if ( !pthread_equal(self, ev->thread_id) )
ev = NULL;
iterate = FALSE;
} else
{ ev = TheSchedule()->first;
iterate = TRUE;
}
for(; ev; ev = ev->next)
{ atom_t s;
double at;
fid_t fid;
int ok;
if ( !pthread_equal(self, ev->thread_id) )
continue;
fid = PL_open_foreign_frame();
if ( ev->flags & EV_DONE )
s = ATOM_done;
else if ( ev == TheSchedule()->scheduled )
s = ATOM_next;
else
s = ATOM_scheduled;
ok = PL_unify_atom(status, s);
if ( ok )
ok = unify_event_goal(goal, ev);
if ( ok )
{ at = (double)ev->at.tv_sec + (double)ev->at.tv_usec / 1000000.0;
ok = PL_unify_float(time, at);
}
PL_discard_foreign_frame(fid);
if ( ok )
{ if ( !PL_put_float(av+0, at) || /* time */
!PL_put_variable(av+1) || /* goal */
!unify_event_goal(av+1, ev) ||
!PL_put_variable(av+2) || /* id */
!unify_timer(av+2, ev) ||
!PL_put_atom(av+3, s) || /* status */
/* Create term */
!PL_cons_functor_v(next, FUNCTOR_alarm4, av) ||
/* Add to list */
!PL_unify_list(tail, head, tail) ||
!PL_unify(head, next) )
{ UNLOCK();
return FALSE;
}
} else
{ if ( PL_exception(0) )
{ UNLOCK();
return FALSE;
}
}
if ( !iterate )
break;
}
UNLOCK();
return PL_unify_nil(tail);
}
install_t
install_time(void)
{ MODULE_user = PL_new_module(PL_new_atom("user"));
FUNCTOR_alarm1 = PL_new_functor(PL_new_atom("$alarm"), 1);
FUNCTOR_alarm4 = PL_new_functor(PL_new_atom("alarm"), 4);
FUNCTOR_module2 = PL_new_functor(PL_new_atom(":"), 2);
ATOM_remove = PL_new_atom("remove");
ATOM_install = PL_new_atom("install");
ATOM_done = PL_new_atom("done");
ATOM_next = PL_new_atom("next");
ATOM_scheduled = PL_new_atom("scheduled");
PREDICATE_call1 = PL_predicate("call", 1, "user");
PL_register_foreign("alarm_at", 4, alarm4_abs, PL_FA_TRANSPARENT);
PL_register_foreign("alarm", 4, alarm4_rel, PL_FA_TRANSPARENT);
PL_register_foreign("alarm_at", 3, alarm3_abs, PL_FA_TRANSPARENT);
PL_register_foreign("alarm", 3, alarm3_rel, PL_FA_TRANSPARENT);
PL_register_foreign("remove_alarm", 1, remove_alarm, 0);
PL_register_foreign("uninstall_alarm",1, uninstall_alarm,0);
PL_register_foreign("install_alarm", 1, install_alarm, 0);
PL_register_foreign("install_alarm", 2, install_alarm2, 0);
PL_register_foreign("remove_alarm_notrace",1, remove_alarm, PL_FA_NOTRACE);
PL_register_foreign("current_alarms", 5, current_alarms, 0);
#ifdef O_DEBUG
PL_register_foreign("time_debug", 1, pl_time_debug, 0);
#endif
if ( installHandler() )
PL_on_halt(cleanup, NULL);
PL_thread_at_exit(cleanup_thread, NULL, TRUE);
}
install_t
uninstall_time(void)
{ cleanup(0, NULL);
}
|