forked from ldmud/ldmud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackend.c
1837 lines (1572 loc) · 58.8 KB
/
backend.c
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
/*---------------------------------------------------------------------------
* Gamedriver Backend.
*
*---------------------------------------------------------------------------
* This module holds the backend loop, which polls the connected sockets
* for new input, passes the text read to the command parser (and thus
* executes the commands), and keeps track of regular house-keeping chores
* like garbage collection, swapping, heart beats and the triggers of
* call outs and mapping compaction.
*
* Timing is implemented using a one-shot 2 second alarm(). When the
* alarm is triggered, the handler sets the variable comm_time_to_call_heart-
* _beat which is monitored by various functions.
*
* One backend cycle begins with starting the alarm(). Then the pending
* heartbeats are evaluated, but no longer until the time runs out. Any
* heartbeat remaining will be evaluated in the next cycle. After the
* heartbeat, the call_outs are evaluated. Callouts have no time limit,
* but are bound by the eval_cost limit. Next, the object list is scanned
* for objects in need of a reset, cleanup or swap. The driver will
* (due objects given) perform at least one of each operation, but only
* as many as it can before the time runs out. Last, player commands are
* retrieved with get_message(). The semantic is so that all players are
* considered once before get_message() checks for a timeout. If a timeout
* is detected, get_message() select()s, but returns immediately with the
* variable time_to_call_heart_beat set, else it selects() in one second
* intervals until either commands come in or the time runs out.
*---------------------------------------------------------------------------
*/
#include "driver.h"
#include "typedefs.h"
#include "my-alloca.h"
#include <stddef.h>
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/time.h>
#include <signal.h>
#include <sys/times.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <math.h>
#include "backend.h"
#include "actions.h"
#include "array.h"
#include "call_out.h"
#include "closure.h"
#include "comm.h"
#include "ed.h"
#include "exec.h"
#include "filestat.h"
#include "gcollect.h"
#include "heartbeat.h"
#include "interpret.h"
#include "lex.h"
#include "main.h"
#include "mapping.h"
#include "mregex.h"
#include "mstrings.h"
#include "object.h"
#include "otable.h"
#include "pkg-python.h"
#include "random.h"
#include "simulate.h"
#include "stdstrings.h"
#include "svalue.h"
#include "swap.h"
#include "wiz_list.h"
#include "xalloc.h"
#include "i-current_object.h"
#include "i-eval_cost.h"
#include "../mudlib/sys/configuration.h"
#include "../mudlib/sys/driver_hook.h"
#include "../mudlib/sys/debug_message.h"
#include "../mudlib/sys/signals.h"
/*-------------------------------------------------------------------------*/
mp_int current_time;
/* The current time, updated every heart beat.
* TODO: Should be time_t if it is given that time_t is always a skalar.
*/
mp_int time_of_last_hb = 0;
/* For synchronous heart beats: the time of the last beat.
*/
Bool time_to_call_heart_beat = MY_FALSE;
/* True: It's time to call the heart beat. Set by comm.c when it recognizes
* an alarm(). */
volatile mp_int alarm_called = MY_FALSE;
/* The alarm() handler sets this to TRUE whenever it is called,
* to allow check_alarm() to verify that the alarm is still alive.
*/
volatile Bool comm_time_to_call_heart_beat = MY_FALSE;
/* True: An heart beat alarm() happened. Set from the alarm handler, this
* causes comm.c to set time_to_call_heart_beat.
*/
volatile Bool comm_return_to_backend = MY_FALSE;
/* True: A signal to be handled by the backend has happened.
* This causes comm.c to return without handling any further messages.
*/
volatile mp_int total_alarms = 0;
/* The total number of alarm()s so far, incremented from the alarm handler.
*/
uint32 total_player_commands = 0;
/* Total number of player commands so far.
*/
uint num_listed_objs = 0;
/* Number of objects in the object list.
*/
uint num_last_processed = 0;
/* Number of object processed in last process_objects().
*/
uint num_last_data_cleaned = 0;
/* Number of object data-cleaned in last process_objects().
*/
statistic_t stat_last_processed = { 0, 0, 0.0 };
statistic_t stat_last_data_cleaned = { 0, 0, 0.0 };
statistic_t stat_in_list = { 0, 0, 0.0 };
/* Decaying average number of objects processed and objects in the list.
*/
Bool extra_jobs_to_do = MY_FALSE;
/* True: the backend has other things to do in this cycle than just
* parsing commands or calling the heart_beat.
*/
volatile bool interrupt_execution = false;
/* True: abort the current execution with an error.
*/
GC_Request gc_request = gcDont;
/* gcDont: No garbage collection is due.
* gcMalloc: The mallocator requested a gc (requires extra_jobs_to_do).
* gcEfun: GC requested by efun (requires extra_jobs_to_do).
*/
/* TODO: all the 'extra jobs to do' should be collected here, in a nice
* TODO:: struct.
*/
Bool mud_is_up = MY_FALSE;
/* True: the driver is finished with the initial processing
* and has entered the main loop. This flag is currently not
* used by the driver, but can be useful for printf()-style debugging.
*/
statistic_t stat_load = { 0, 0, 0.0 };
/* The load average (player commands/second), weighted over the
* last period of time.
*/
statistic_t stat_compile = { 0, 0, 0.0 };
/* The average of compiled lines/second, weighted over the last period
* of time.
*/
static time_t time_last_slow_shut = 0;
/* Time of the last call to slow_shut_down(), to avoid repeated
* calls while the previous ones are still working.
*/
static sigset_t pending_signals;
/* The pending signals which should be delivered to the mudlib master.
*/
char sigaction_sighup = DCS_DEFAULT,
sigaction_sigint = DCS_DEFAULT,
sigaction_sigusr1 = DCS_DEFAULT,
sigaction_sigusr2 = DCS_DEFAULT;
/* Configured reactions to signals, is one of DCS_* defines.
* They are evaluated immediately when the signal occurs.
*/
/*-------------------------------------------------------------------------*/
/* --- Forward declarations --- */
static void process_objects(void);
/*-------------------------------------------------------------------------*/
void
update_statistic (statistic_t * pStat, long number)
/* Add the <number> to the statistics in <pStat> and update the weighted
* average over the last period of time.
*/
{
mp_int n;
double c;
pStat->sum += number;
if (current_time == pStat->last_time)
return;
n = current_time - pStat->last_time;
if (n < (int) (sizeof avg_consts / sizeof avg_consts[0]) )
c = avg_consts[n];
else
c = exp(- n / 900.0);
pStat->weighted_avg = c * pStat->weighted_avg + pStat->sum * (1 - c) / n;
pStat->last_time = current_time;
pStat->sum = 0;
} /* update_statistic() */
/*-------------------------------------------------------------------------*/
void
update_statistic_avg (statistic_t * pStat, long number)
/* Add the <number> to the statistics in <pStat> and update the weighted
* average by degrading the previous value.
*/
{
double c;
pStat->sum += number;
c = avg_consts[2];
pStat->weighted_avg = (1 - c) * pStat->weighted_avg + number * c;
} /* update_statistic_avg() */
/*-------------------------------------------------------------------------*/
double
relate_statistics (statistic_t sStat, statistic_t sRef)
/* Express the <sStat>.weighted_avg as a multiple of <sRef>.weighted_avg
* and return the factor.
*/
{
if (sRef.weighted_avg == 0.0)
return 0.0;
return sStat.weighted_avg / sRef.weighted_avg;
} /* relate_statistics() */
/*-------------------------------------------------------------------------*/
void
update_compile_av (int lines)
/* Compute the average of compiled lines/second, weighted over the
* last period of time.
*
* The function is called after every compilation and basically sums up
* the number of compiled lines in one backend loop.
*/
{
update_statistic(&stat_compile, lines);
} /* update_compile_av() */
/*-------------------------------------------------------------------------*/
void
clear_state (void)
/* Clear the global variables of the virtual machine. This is necessary
* after errors, which return directly to the backend, thus skipping the
* clean-up code in the VM itself.
*
* This routine must only be called from top level, not from inside
* stack machine execution (as the stack will be cleared).
* TODO: This too belongs into interpret.c
*/
{
current_loc.file = NULL;
clear_current_object();
command_giver = NULL;
current_interactive = NULL;
previous_ob = const0;
current_prog = NULL;
reset_machine(MY_FALSE); /* Pop down the stack. */
num_warning = 0;
} /* clear_state() */
/*-------------------------------------------------------------------------*/
#ifdef DEBUG
static void
do_state_check (int minlvl, const char *where)
/* Perform the simplistic interpret::check_state() if the check_state_lvl
* is at least <minlvl>. If an inconsistency is detected, the message
* "<timestamp> Inconsistency <where>" and a trace of the last instructions
* is logged, then the state is cleared.
*
* Be careful that the call to check_state()/clear_state() is
* not too costly, as it is done in every loop.
*/
{
if (check_state_level >= minlvl && check_state() )
{
debug_message("%s Inconsistency %s\n", time_stamp(), where);
printf("%s Inconsistency %s\n", time_stamp(), where);
(void)dump_trace(MY_TRUE, NULL, NULL);
#ifdef TRACE_CODE
last_instructions(TOTAL_TRACE_LENGTH, 1, 0);
#endif
clear_state();
}
} /* do_state_check() */
#else
#define do_state_check(minlvl, where)
#endif
/*-------------------------------------------------------------------------*/
static bool install_sigint_handler();
static void
handle_sigchild (int sig)
/* Handler for SIGCHLD signal. We inform comm (for erq) and Python.
*/
{
#ifdef ERQ_DEMON
wait_erq_demon();
#endif
#ifdef USE_PYTHON
/* Notify the python package. */
python_handle_sigchld();
#endif
}
static void
handle_signal (int sig)
/* General signal handler:
* First we look at the configured actions: IGNORE, TERMINATE and
* THROW_EXCEPTION we handle immediately. For all other we store
* the signal in a flag to be handled in the backend loop.
*
* Note: If we receive the same signal again before it is processed, the second
* signal will be lost.
*/
{
char action = DCS_DEFAULT;
switch (sig)
{
case SIGHUP:
action = sigaction_sighup;
break;
case SIGINT:
action = sigaction_sigint;
break;
case SIGUSR1:
action = sigaction_sigusr1;
break;
case SIGUSR2:
action = sigaction_sigusr2;
break;
}
switch (action)
{
case DCS_IGNORE:
/* Do nothing. */
break;
case DCS_TERMINATE:
{
/* Call the default handler, for all four signals
* this is termination.
*/
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = SIG_DFL;
if (sigaction(sig, &sa, NULL) == 0)
raise(sig);
/* If we are still here, exit... */
exit(sig);
return;
}
case DCS_THROW_EXCEPTION:
/* Set a flag to be evaluated by the interpreter. */
interrupt_execution = true;
#ifdef USE_PYTHON
/* Notify the python package. */
python_interrupt();
#endif
break;
default:
/* Process it in the backend loop. */
sigaddset(&pending_signals, sig);
extra_jobs_to_do = MY_TRUE;
comm_return_to_backend = MY_TRUE;
return;
}
// Reached in case of DCS_IGNORE and DCS_THROW_EXCEPTION.
// In both cases the signal handler has to be re-installed here
// (because process_pending_signals() - which would do it normally -
// isn't going to be called in these cases).
if (sig == SIGINT)
install_sigint_handler();
} /* handle_signal() */
/*-------------------------------------------------------------------------*/
static bool
install_sigint_handler ()
/* Installs the SIGINT handler again.
* The handler is reset upon each signal, so we need to install it again.
* Returns true on success.
*/
{
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART|SA_RESETHAND;
sa.sa_handler = handle_signal;
return (sigaction(SIGINT, &sa, NULL) == 0);
}
/*-------------------------------------------------------------------------*/
static INLINE bool
execute_signal_action (int sig, char configured)
/* Executes the configured signal action, that were not already handled in the
* signal handler itself: DEFAULT, SHUTDOWN, INFORM_MASTER and RELOAD_MASTER.
*
* Returns true, if the action was executed.
* Returns false, if the default action (besides calling the master)
* shall be conducted.
*/
{
switch (configured)
{
case DCS_SHUTDOWN:
extra_jobs_to_do = MY_TRUE;
game_is_being_shut_down = MY_TRUE;
break;
case DCS_RELOAD_MASTER:
extra_jobs_to_do = MY_TRUE;
master_will_be_updated = MY_TRUE;
break;
case DCS_INFORM_MASTER:
default:
{
svalue_t *res;
push_number(inter_sp, sig);
res = callback_master(STR_HANDLE_EXTERNAL_SIGNAL, 1);
// If we just inform the master or the master returned something
// that is not a number or the number 0 we go to the default action.
if (configured == DCS_INFORM_MASTER ||
!res || res->type != T_NUMBER || res->u.number == 0)
return false;
break;
}
}
return true;
} /* execute_signal_action() */
/*-------------------------------------------------------------------------*/
static INLINE void
process_pending_signals (void)
/* processes the pending signals: SIGHUP, SIGUSR1, SIGUSR2, SIGINT
* informs the master by applying handle_external_signal() in it and
* handles the signal, if the master does not.
*/
{
if (sigismember(&pending_signals, SIGTERM))
{
// SIGTERM: shutdown gracefully, but inform the mudlib master first.
// The master can't veto the shutdown.
execute_signal_action(LPC_SIGTERM, DCS_DEFAULT);
game_is_being_shut_down = MY_TRUE;
// ignore the rest of the signals
sigemptyset(&pending_signals);
return;
}
if (sigismember(&pending_signals, SIGHUP))
{
// SIGHUP: request a game shutdown.
sigdelset(&pending_signals, SIGHUP);
if (!execute_signal_action(LPC_SIGHUP, sigaction_sighup))
{
// master did not handle it, shut down.
extra_jobs_to_do = MY_TRUE;
game_is_being_shut_down = MY_TRUE;
// ignore the rest of the signals
sigemptyset(&pending_signals);
return;
}
}
if (sigismember(&pending_signals, SIGUSR1))
{
// SIGUSR1: request a master update.
sigdelset(&pending_signals, SIGUSR1);
if (!execute_signal_action(LPC_SIGUSR1, sigaction_sigusr1))
{
// Master did not handle it, update the master
extra_jobs_to_do = MY_TRUE;
master_will_be_updated = MY_TRUE;
eval_cost += max_eval_cost >> 3;
}
}
if (sigismember(&pending_signals, SIGUSR2))
{
// SIGUSR2: reopen the debug.log file.
sigdelset(&pending_signals, SIGUSR2);
if (!execute_signal_action(LPC_SIGUSR2, sigaction_sigusr2))
{
// Master did not handle it, re-open the log
reopen_debug_log = MY_TRUE;
}
}
if (sigismember(&pending_signals, SIGINT))
{
// SIGINT: standard behaviour is process termination. If the mudlib
// does not handle the signal, we send us the signal again (which terminates
// us).
sigdelset(&pending_signals, SIGINT);
if (!execute_signal_action(LPC_SIGINT, sigaction_sigint))
{
// if anything goes wrong, we terminate ourself, because it is the
// standard behaviour in case of SIGINT.
if (kill(getpid(), SIGINT))
fatal("%s Could not send ourself the SIGINT signal: %s\n",
time_stamp(), strerror(errno));
return;
}
// Otherwise we install our own handler again (the signal handler for
// SIGINT is installed with the SA_RESETHAND flag and thus reset upon
// signal delivery)
else if (!install_sigint_handler())
{
debug_message("%s Unable to reinstall signal handler for SIGINT: %s",
time_stamp(), strerror(errno));
}
}
} // process_pending_signals
/*-------------------------------------------------------------------------*/
static INLINE void
cleanup_stuff (void)
/* Perform a number of clean up operations: replacing programs, freeing
* driver hooks, and handling newly destructed objects.
* They are collected in one function so that they can be easily called from
* various places (backend loop and the process_objects loops); especially
* since it is not advisable to remove destructed objects before replacing
* the programs.
*
* This function does not call remove_destructed_objects() as this
* call might become costly, and it is also sufficient to call it in the
* context of process_objects() every couple of seconds.
*/
{
int i;
/* Reset the VM to avoid dangling references to invalid objects */
clear_state();
/* Replace programs */
if (obj_list_replace)
{
replace_programs();
}
/* Rebind all bindable closures back to the master */
for (i = 0; i < NUM_DRIVER_HOOKS; i++)
{
if (driver_hook[i].type == T_CLOSURE
&& driver_hook[i].x.closure_type == CLOSURE_LAMBDA)
{
lambda_t *l;
l = driver_hook[i].u.lambda;
if (l->ob.type != T_OBJECT || l->ob.u.ob != master_ob)
{
free_svalue(&(l->ob));
put_ref_object(&(l->ob), master_ob, "backend");
}
}
}
/* Finish up all newly destructed objects.
*/
handle_newly_destructed_objects();
} /* cleanup_stuff() */
/*-------------------------------------------------------------------------*/
void install_signal_handlers()
/* Installs the signal handlers for those signals the driver responds to. */
{
struct sigaction sa; // for installing the signal handlers
// empty the pending signals
sigemptyset(&pending_signals);
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART; // restart syscalls after handling a signal
sa.sa_handler = catch_alarm;
if (sigaction(SIGALRM, &sa, NULL) == -1)
fatal("Could not install the alarm (SIGALRM) handler: %s\n",
strerror(errno));
// install the general signal handler for some signals
// TODO: should we abort the startup if we can't install a handler?
sa.sa_handler = handle_signal;
if (sigaction(SIGHUP, &sa, NULL) == -1)
perror("Unable to install signal handler for SIGHUP");
if (sigaction(SIGUSR1, &sa, NULL) == -1)
perror("Unable to install signal handler for SIGUSR1");
if (sigaction(SIGUSR2, &sa, NULL) == -1)
perror("Unable to install signal handler for SIGUSR2");
// Profiling signal handler for the detection of long executions.
sa.sa_handler = handle_profiling_signal;
if (sigaction(SIGPROF, &sa, NULL) == -1) {
profiling_timevalue.tv_sec = 0;
profiling_timevalue.tv_usec = 0;
debug_message("%s Unable to install signal handler for SIGPROF - profiling "
"not available\n", time_stamp());
}
// for SIGTERM and SIGINT the default handler should be restored upon signal
// delivery, so that a repeated signal is handled immediately with the
// default action and not only in the next backend cycle.
sa.sa_handler = handle_signal;
sa.sa_flags |= SA_RESETHAND;
if (sigaction(SIGINT, &sa, NULL) == -1)
perror("Unable to install signal handler for SIGINT");
if (sigaction(SIGTERM, &sa, NULL) == -1)
perror("Unable to install signal handler for SIGTERM");
sa.sa_handler = handle_sigchild;
sa.sa_flags = SA_NOCLDSTOP;
if (sigaction(SIGCHLD, &sa, NULL) == -1)
perror("Unable to install signal handler for SIGCHLD");
handle_sigchild(SIGCHLD); /* In case we already have some zombies. */
}
/*-------------------------------------------------------------------------*/
void
backend (void)
/* The backend loop, the backbone of the driver's operations.
* It only returns when the game has to be shut down.
*/
{
char buff[MAX_TEXT+4];
/* Note that the size of buff[] is determined by MAX_TEXT, which
* is the max size of the network receive buffer. IOW: no
* buffer overruns are possible.
*/
size_t bufflength;
/* The size of the command in buff.*/
Bool prevent_object_cleanup;
/* Implement a low/high water mark handling for the call to
* cleanup_all_objects(), as it turns out that a single
* cleanup doesn't always remove enough destructed objects.
*/
/*
* Set up.
*/
prepare_ipc();
if (!disable_timers_flag) {
/* Setup the alarm timer. We set it up in a way that it expires on
* full seconds to synchronize mud time to host time.
*/
struct itimerval timer_value;
struct timeval cur_time;
timer_value.it_interval.tv_usec = 0;
timer_value.it_value.tv_usec = 0;
if (gettimeofday(&cur_time, NULL))
{
// no sync with host time.
perror("Could not get current time with gettimeofday, host and mud time will be out of sync");
timer_value.it_interval.tv_sec = alarm_time;
timer_value.it_value.tv_sec = alarm_time;
}
else
{
// the first timer will be a little bit shorter (<=1s)
timer_value.it_interval.tv_sec = alarm_time;
timer_value.it_value.tv_sec = alarm_time - 1;
timer_value.it_value.tv_usec = 1000000 - cur_time.tv_usec;
}
if(setitimer( ITIMER_REAL, &timer_value, NULL ))
{
fatal("Could not initialize the alarm timer: %s\n",
strerror(errno));
}
current_time = get_current_time();
}
printf("%s LDMud ready for users.\n", time_stamp());
fflush(stdout);
debug_message("%s LDMud ready for users.\n", time_stamp());
toplevel_context.rt.type = ERROR_RECOVERY_BACKEND;
setjmp(toplevel_context.con.text);
/*
* We come here after errors, and have to clear some global variables.
*/
mark_end_evaluation();
clear_state();
flush_all_player_mess();
prevent_object_cleanup = MY_FALSE;
/*
* The Loop.
*/
while(1)
{
do_state_check(1, "in main loop");
check_alarm();
RESET_LIMITS;
CLEAR_EVAL_COST;
#ifdef C_ALLOCA
/* Execute pending deallocations */
alloca(0); /* free alloca'd values from deeper levels of nesting */
#endif
mud_is_up = MY_TRUE;
/* Replace programs, remove destructed objects, and similar stuff */
cleanup_stuff();
#ifdef DEBUG
if (check_a_lot_ref_counts_flag)
check_a_lot_ref_counts(NULL);
/* after removing destructed objects! */
#endif
/*
* Do the extra jobs, if any.
*/
check_for_out_connections();
check_for_soft_malloc_limit();
if (prevent_object_cleanup)
{
if (num_listed_objs >= num_destructed/2)
prevent_object_cleanup = MY_FALSE;
}
else
{
if (num_listed_objs <= num_destructed)
{
cleanup_all_objects();
prevent_object_cleanup = MY_TRUE;
}
}
if (extra_jobs_to_do) {
current_interactive = NULL;
// process the pending signals we received since last time. Do
// this first, because some flags may be set which cause some
// extra jobs to done.
process_pending_signals();
if (game_is_being_shut_down)
{
command_giver = NULL;
clear_current_object();
return;
}
if (master_will_be_updated) {
deep_destruct(master_ob);
master_will_be_updated = MY_FALSE;
command_giver = NULL;
set_current_object(&dummy_current_object_for_loads);
callback_master(STR_EXT_RELOAD, 0);
clear_current_object();
}
if (gc_request != gcDont) {
time_t time_now = time(NULL);
char buf[120];
if (gc_request == gcEfun
|| time_now - time_last_gc >= 60)
{
sprintf(buf, "%s Garbage collection req by %s "
"(slow_shut to do: %d, "
"time since last gc: %ld\n"
, time_stamp()
, gc_request == gcEfun ? "efun" : "allocator"
, slow_shut_down_to_do
, (long)(time_now - time_last_gc)
);
write(1, buf, strlen(buf));
command_giver = NULL;
clear_current_object();
/* if the GC was not requested by an efun call, low_memory()
* in the master is called to inform the game. */
notify_lowmemory_condition(gc_request == gcEfun ?
NO_MALLOC_LIMIT_EXCEEDED :
HARD_MALLOC_LIMIT_EXCEEDED);
garbage_collection();
}
else
{
sprintf(buf, "%s Garbage collection req by %s refused "
"(slow_shut to do: %d, "
"time since last gc: %ld)\n"
, time_stamp()
, gc_request == gcEfun ? "efun" : "allocator"
, slow_shut_down_to_do
, (long)(time_now - time_last_gc));
write(1, buf, strlen(buf));
reallocate_reserved_areas();
}
gc_request = gcDont;
if (slow_shut_down_to_do)
{
if (time_now - time_last_slow_shut
>= slow_shut_down_to_do * 60
)
{
int minutes = slow_shut_down_to_do;
char shut_msg[90];
slow_shut_down_to_do = 0;
time_last_slow_shut = time_now;
malloc_privilege = MALLOC_MASTER;
sprintf(shut_msg, "%s slow_shut_down(%d)\n", time_stamp(), minutes);
write(1, shut_msg, strlen(shut_msg));
previous_ob = const0;
command_giver = NULL;
current_interactive = NULL;
push_number(inter_sp, minutes);
callback_master(STR_SLOW_SHUT, 1);
}
else
{
sprintf(buf, "%s Last slow_shut_down() still pending.\n"
, time_stamp()
);
write(1, buf, strlen(buf));
}
}
malloc_privilege = MALLOC_USER;
}
extra_jobs_to_do = MY_FALSE;
} /* if (extra_jobs_to_do */
#ifdef USE_PYTHON
python_process_pending_jobs();
#endif /* USE_PYTHON */
do_state_check(2, "before get_message()");
/*
* Call comm.c and wait for player input, or until the next
* heart beat is due.
*/
if (get_message(buff, &bufflength))
{
interactive_t *ip;
/* Create the new time_stamp string in the function's local
* buffer.
*/
(void)time_stamp();
total_player_commands++;
update_statistic(&stat_load, 1);
#ifdef MALLOC_EXT_STATISTICS
mem_update_stats();
#endif /* MALLOC_EXT_STATISTICS */
/*
* Now we have a string from the player. This string can go to
* one of several places. If it is prepended with input escape
* char, then it is an escape from the 'ed' editor, so we send it
* as a command to the parser.
* If any object function is waiting for an input string, then
* send it there.
* Otherwise, send the string to the parser.
* The command_parser will find that current_object is 0, and
* then set current_object to point to the object that defines
* the command. This will enable such functions to be static.
*/
clear_current_object();
current_interactive = command_giver;
(void)O_SET_INTERACTIVE(ip, command_giver);
#ifdef DEBUG
if (!ip)
{
fatal("Non interactive player in main loop !\n");
/* NOTREACHED */
}
#endif
tracedepth = 0;
mark_start_evaluation();
if (bufflength > 1 && buff[0] == input_escape)
{
if(!call_function_interactive(ip, buff, bufflength))
{
/* We got a bang-input, but no input context wants
* to handle it - treat it as a normal command.
*/
if ((ip->noecho & NOECHO) && ip->command_printed <= ip->command_start)
{
/* !message while in NOECHO - simulate the
* echo by sending the (remaining) raw data we got.
*/
add_message("%.*s\n", ip->command_start - ip->command_printed, buff + bufflength + ip->command_printed - ip->command_start);
ip->command_printed = ip->command_start;
}
buff[bufflength] = 0;
execute_command(buff+1, command_giver);
}
}
else if (call_function_interactive(ip, buff, bufflength))
NOOP;
else
{
buff[bufflength] = 0;
execute_command(buff, command_giver);
}
mark_end_evaluation();
/* ip might be invalid again here */
/*
* Print a prompt if player is still here.
*/
if (command_giver)
{
if (O_SET_INTERACTIVE(ip, command_giver)
&& !ip->do_close)
{
print_prompt();
}
}
do_state_check(2, "after handling message");
}
else
{
/* No new message, just create the new time_stamp string in
* the function's local buffer.
*/
(void)time_stamp();