/
Kernel.pm
3919 lines (2955 loc) · 119 KB
/
Kernel.pm
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
# $Id$
package POE::Kernel;
use strict;
use POSIX qw(errno_h fcntl_h sys_wait_h uname signal_h);
use Carp;
use vars qw( $poe_kernel $poe_tk_main_window );
use Exporter;
@POE::Kernel::ISA = qw(Exporter);
@POE::Kernel::EXPORT = qw( $poe_kernel $poe_tk_main_window );
#------------------------------------------------------------------------------
# Macro definitions.
use POE::Preprocessor;
macro sig_remove (<session>,<signal>) {
delete $self->[KR_SESSIONS]->{<session>}->[SS_SIGNALS]->{<signal>};
delete $self->[KR_SIGNALS]->{<signal>}->{<session>};
}
macro sid (<session>) {
"session " . <session>->ID
}
macro ssid {
"session " . $session->ID
}
macro ses_leak_hash (<field>) {
if (my $leaked = keys(%{$sessions->{$session}->[<field>]})) {
warn {% ssid %}, " leaked $leaked <field>\a\n";
$errors++;
}
}
macro kernel_leak_hash (<field>) {
if (my $leaked = keys %{$self->[<field>]}) {
warn "*** KERNEL LEAK: <field> = $leaked\a\n";
}
}
macro kernel_leak_vec (<field>) {
{ my $bits = unpack('b*', $self->[KR_VECTORS]->[<field>]);
if (index($bits, '1') >= 0) {
warn "*** KERNEL LEAK: KR_VECTORS/<field> = $bits\a\n";
}
}
}
macro kernel_leak_array (<field>) {
if (my $leaked = @{$self->[<field>]}) {
warn "*** KERNEL LEAK: <field> = $leaked\a\n";
}
}
macro assert_session_refcount (<session>,<count>) {
ASSERT_REFCOUNT and do {
die {% sid <session> %}, " reference count <count> went below zero\n"
if $self->[KR_SESSIONS]->{<session>}->[<count>] < 0;
};
}
macro ses_refcount_dec (<session>) {
$self->[KR_SESSIONS]->{<session>}->[SS_REFCOUNT]--;
{% assert_session_refcount <session>, SS_REFCOUNT %}
}
macro ses_refcount_dec2 (<session>,<count>) {
$self->[KR_SESSIONS]->{<session>}->[<count>]--;
{% assert_session_refcount <session>, <count> %}
{% ses_refcount_dec <session> %}
}
macro ses_refcount_inc (<session>) {
$self->[KR_SESSIONS]->{<session>}->[SS_REFCOUNT]++;
}
macro ses_refcount_inc2 (<session>,<count>) {
$self->[KR_SESSIONS]->{<session>}->[<count>]++;
{% ses_refcount_inc <session> %}
}
macro remove_extra_reference (<session>,<tag>) {
delete $self->[KR_SESSIONS]->{<session>}->[SS_EXTRA_REFS]->{<tag>};
{% ses_refcount_dec <session> %}
}
# There is an string equality test in alias_resolve that should not be
# made into a numeric equality test. <name> is often a string.
macro alias_resolve (<name>) {
# Resolve against sessions.
( (exists $self->[KR_SESSIONS]->{<name>})
? $self->[KR_SESSIONS]->{<name>}->[SS_SESSION]
# Resolve against IDs.
: ( (exists $self->[KR_SESSION_IDS]->{<name>})
? $self->[KR_SESSION_IDS]->{<name>}
# Resolve against aliases.
: ( (exists $self->[KR_ALIASES]->{<name>})
? $self->[KR_ALIASES]->{<name>}
# Resolve against self.
: ( (<name> eq $self)
? $self
# Game over!
: undef
)
)
)
)
}
macro collect_garbage (<session>) {
if ( (<session> != $self)
and (exists $self->[KR_SESSIONS]->{<session>})
and (!$self->[KR_SESSIONS]->{<session>}->[SS_REFCOUNT])
) {
TRACE_GARBAGE and $self->trace_gc_refcount(<session>);
ASSERT_GARBAGE and $self->assert_gc_refcount(<session>);
$self->session_free(<session>);
}
}
macro validate_handle (<handle>,<vector>) {
# Don't bother if the kernel isn't tracking the handle.
return 0 unless exists $self->[KR_HANDLES]->{<handle>};
# Don't bother if the kernel isn't tracking the handle's write status.
return 0 unless $self->[KR_HANDLES]->{<handle>}->[HND_VECCOUNT]->[<vector>];
}
macro remove_alias (<session>,<alias>) {
delete $self->[KR_ALIASES]->{<alias>};
delete $self->[KR_SESSIONS]->{<session>}->[SS_ALIASES]->{<alias>};
{% ses_refcount_dec <session> %}
}
macro state_to_enqueue {
[ @_[1..8], ++$queue_seqnum ]
}
macro define_trace (<const>) {
defined &TRACE_<const> or eval 'sub TRACE_<const> () { TRACE_DEFAULT }';
}
macro define_assert (<const>) {
defined &ASSERT_<const> or eval 'sub ASSERT_<const> () { ASSERT_DEFAULT }';
}
macro test_resolve (<name>,<resolved>) {
unless (defined <resolved>) {
ASSERT_SESSIONS and do {
confess "Cannot resolve <name> into a session reference\n";
};
$! = ESRCH;
return undef;
}
}
macro test_for_idle_poe_kernel {
unless ( @{$self->[KR_STATES]} or
@{$self->[KR_ALARMS]} or
%{$self->[KR_HANDLES]}
) {
$self->_enqueue_state( $self, $self,
EN_SIGNAL, ET_SIGNAL,
[ 'IDLE' ],
time(), __FILE__, __LINE__
)
if keys %{$self->[KR_SESSIONS]};
}
}
macro post_plain_signal (<destination>,<signal_name>) {
$poe_kernel->_enqueue_state( <destination>, $poe_kernel,
EN_SIGNAL, ET_SIGNAL,
[ <signal_name> ],
time(), __FILE__, __LINE__
);
}
macro post_child_signal(<destination>,<pid>,<exit_status>) {
# Determine if the child process is really exiting and not just
# stopping for some other reason. This is per Perl Cookbook recipe
# 16.19.
if (WIFEXITED(<exit_status>)) {
$poe_kernel->_enqueue_state( <destination>, $poe_kernel,
EN_SIGNAL, ET_SIGNAL,
[ 'CHLD', <pid>, <exit_status> ],
time(), __FILE__, __LINE__
);
}
}
macro dispatch_one_from_fifo {
if ( @{ $self->[KR_STATES] } ) {
# Pull an event off the queue.
my $event = shift @{ $self->[KR_STATES] };
{% ses_refcount_dec2 $event->[ST_SESSION], SS_EVCOUNT %}
# Dispatch it, and see if that was the last thing the session
# needed to do.
$self->_dispatch_state(@$event);
{% collect_garbage $event->[ST_SESSION] %}
}
}
macro dispatch_due_alarms {
my $now = time();
while ( @{ $self->[KR_ALARMS] } and
($self->[KR_ALARMS]->[0]->[ST_TIME] <= $now)
) {
# Pull an alarm off the queue.
my $event = shift @{ $self->[KR_ALARMS] };
{% ses_refcount_dec2 $event->[ST_SESSION], SS_ALCOUNT %}
# Dispatch it, and see if that was the last thing the session
# needed to do.
$self->_dispatch_state(@$event);
{% collect_garbage $event->[ST_SESSION] %}
}
}
macro dispatch_ready_selects {
my @selects =
values %{ $self->[KR_HANDLES]->{$handle}->[HND_SESSIONS]->[$vector] };
foreach my $select (@selects) {
$self->_dispatch_state
( $select->[HSS_SESSION], $select->[HSS_SESSION],
$select->[HSS_STATE], ET_SELECT,
[ $select->[HSS_HANDLE] ],
time(), __FILE__, __LINE__, undef
);
{% collect_garbage $select->[HSS_SESSION] %}
}
}
# MACROS END <-- search tag for editing
#------------------------------------------------------------------------------
# Perform some optional setup.
BEGIN {
local $SIG{'__DIE__'} = 'DEFAULT';
# Include Time::HiRes, which is pretty darned cool, if it's
# available. Life goes on without it.
eval {
require Time::HiRes;
import Time::HiRes qw(time);
};
# Set a constant to indicate the presence of Time::HiRes. This
# enables some runtime optimization.
if ($@) {
eval 'sub POE_HAS_TIME_HIRES () { 0 }';
}
else {
eval 'sub POE_HAS_TIME_HIRES () { 1 }';
}
# http://support.microsoft.com/support/kb/articles/Q150/5/37.asp
# defines EINPROGRESS as 10035. We provide it here because some
# Win32 users report POSIX::EINPROGRESS is not vendor-supported.
if ($^O eq 'MSWin32') {
eval '*EINPROGRESS = sub { 10035 };'
}
}
#------------------------------------------------------------------------------
# globals
$poe_kernel = undef; # only one active kernel; sorry
#------------------------------------------------------------------------------
# Debugging flags for subsystems. They're done as double evals here
# so that someone may define them before using POE, and the
# pre-defined value will take precedence over the defaults here.
BEGIN {
# TRACE_DEFAULT changes the default value for other TRACE_*
# constants. Since the define_trace macro uses TRACE_DEFAULT
# internally, it can't be used to define TRACE_DEFAULT itself.
defined &TRACE_DEFAULT or eval 'sub TRACE_DEFAULT () { 0 }';
{% define_trace EVENTS %}
{% define_trace GARBAGE %}
{% define_trace PROFILE %}
{% define_trace QUEUE %}
{% define_trace REFCOUNT %}
{% define_trace SELECT %}
# See the notes for TRACE_DEFAULT, except read ASSERT and assert
# where you see TRACE and trace.
defined &ASSERT_DEFAULT or eval 'sub ASSERT_DEFAULT () { 0 }';
{% define_assert GARBAGE %}
{% define_assert REFCOUNT %}
{% define_assert RELATIONS %}
{% define_assert SELECT %}
{% define_assert SESSIONS %}
}
# Determine whether Tk or Event is loaded. If either is, set a
# constant that enables its specific behaviors throughout POE::Kernel.
# Replace the unused ones' methods with dummies; these won't ever be
# called, but they need to be present so that POE::Kernel compiles.
BEGIN {
# Can't use Tk and Event at the same time.
if (exists $INC{'Tk.pm'} and exists $INC{'Event.pm'}) {
croak "POE: Tk and Event have incompatible event loops. Can't use both";
}
# Check for Tk.
if (exists $INC{'Tk.pm'}) {
eval <<' EOE';
sub POE_HAS_TK () { 1 }
EOE
}
else {
eval <<' EOE';
sub POE_HAS_TK () { 0 }
sub Tk::MainLoop () { 0 }
sub Tk::MainWindow::new () { undef }
EOE
}
# Check for Event.
if (exists $INC{'Event.pm'}) {
eval <<' EOE';
sub POE_HAS_EVENT () { 1 }
EOE
}
else {
eval <<' EOE';
sub POE_HAS_EVENT () { 0 }
sub Event::loop () { 0 }
sub Event::unloop_all ($) { 0 }
sub Event::idle () { 0 }
sub Event::timer () { 0 }
EOE
}
}
#------------------------------------------------------------------------------
# Handles and vectors sub-fields.
enum VEC_RD VEC_WR VEC_EX
# Session structure
enum SS_SESSION SS_REFCOUNT SS_EVCOUNT SS_PARENT SS_CHILDREN SS_HANDLES
enum + SS_SIGNALS SS_ALIASES SS_PROCESSES SS_ID SS_EXTRA_REFS SS_ALCOUNT
# session handle structure
enum SH_HANDLE SH_REFCOUNT SH_VECCOUNT
# The Kernel object. KR_SIZE goes last (it's the index count).
enum KR_SESSIONS KR_VECTORS KR_HANDLES KR_STATES KR_SIGNALS KR_ALIASES
enum + KR_ACTIVE_SESSION KR_PROCESSES KR_ALARMS KR_ID KR_SESSION_IDS
enum + KR_ID_INDEX KR_WATCHER_TIMER KR_WATCHER_IDLE KR_SIZE
# Handle structure.
enum HND_HANDLE HND_REFCOUNT HND_VECCOUNT HND_SESSIONS HND_FILENO HND_WATCHERS
# Handle session structure.
enum HSS_HANDLE HSS_SESSION HSS_STATE
# State transition events.
enum ST_SESSION ST_SOURCE ST_NAME ST_TYPE ST_ARGS
# These go towards the end, in this order, because they're optional
# parameters in some cases.
enum + ST_TIME ST_OWNER_FILE ST_OWNER_LINE ST_SEQ
# These are names of internal events.
const EN_START '_start'
const EN_STOP '_stop'
const EN_SIGNAL '_signal'
const EN_GC '_garbage_collect'
const EN_PARENT '_parent'
const EN_CHILD '_child'
const EN_SCPOLL '_sigchld_poll'
# These are event classes (types). They often shadow actual event
# names, but they can encompass a large group of events. For example,
# ET_ALARM describes anything posted by an alarm call. Types are
# preferred over names because bitmask tests tend to be faster than
# string equality checks.
const ET_USER 0x0000
const ET_START 0x0001
const ET_STOP 0x0002
const ET_SIGNAL 0x0004
const ET_GC 0x0008
const ET_PARENT 0x0010
const ET_CHILD 0x0020
const ET_SCPOLL 0x0040
const ET_ALARM 0x0080
const ET_SELECT 0x0100
# The amount of time to spend dispatching FIFO events. Increasing
# this value will improve POE's FIFO dispatch performance by
# increasing the time between select and alarm checks.
const FIFO_DISPATCH_TIME 0.01
#------------------------------------------------------------------------------
# Here is a roadmap of POE's internal data structures. It's complex
# enough that even the author needs a scorecard.
#------------------------------------------------------------------------------
#
# states:
# [ [ $session, $source_session, $state, $type, \@etc, $time,
# $poster_file, $poster_line, $debug_sequence
# ],
# ...
# ]
#
# alarms:
# [ [ $session, $source_session, $state, $type, \@etc, $time,
# $poster_file, $poster_line, $debug_sequence
# ],
# ...
# ]
#
# processes: { $pid => $parent_session, ... }
#
# kernel ID: { $kernel_id }
#
# session IDs: { $id => $session, ... }
#
# handles:
# { $handle =>
# [ $handle,
# $refcount,
# [ $ref_r, $ref_w, $ref_x ],
# [ { $session => [ $handle, $session, $state ], .. },
# { $session => [ $handle, $session, $state ], .. },
# { $session => [ $handle, $session, $state ], .. }
# ],
# fileno(),
# [ $watcher_r, $watcher_w, $watcher_x ],
# ]
# };
#
# vectors: [ $read_vector, $write_vector, $expedite_vector ];
#
# signals: { $signal => { $session => $state, ... } };
#
# sessions:
# { $session =>
# [ $session, # blessed version of the key
# $refcount, # number of things keeping this alive
# $evcnt, # event count
# $parent, # parent session
# { $child => $child, ... },
# { $handle =>
# [ $hdl,
# $rcnt,
# [ $r,$w,$e ]
# ],
# ...
# },
# { $signal => $state, ... },
# { $name => 1, ... },
# { $pid => 1, ... }, # child processes
# $session_id, # session ID
# { $tag => $count, ... }, # extra reference counts
# $alarm_count, # alarm count
# ]
# };
#
# names: { $name => $session };
#
#------------------------------------------------------------------------------
#==============================================================================
# SIGNALS
#==============================================================================
# This is a list of signals that will terminate sessions that don't
# handle them.
my %_terminal_signals =
( QUIT => 1, INT => 1, KILL => 1, TERM => 1, HUP => 1, IDLE => 1 );
### POE's signal handlers. These are just plain old Perl.
sub _poe_signal_handler_generic {
if (defined $_[0]) {
{% post_plain_signal $poe_kernel, $_[0] %}
$SIG{$_[0]} = \&_poe_signal_handler_generic;
}
else {
warn "POE::Kernel::_signal_handler_generic detected an undefined signal";
}
}
# SIGPIPE is handled a little differently. It tends to be
# synchronous, so it's posted at the current active session. We can
# do this better by generating a pseudo SIGPIPE whenever a driver
# returns EPIPE, but that requires people to use Wheel::ReadWrite on
# similar dilligence.
sub _poe_signal_handler_pipe {
if (defined $_[0]) {
{% post_plain_signal $poe_kernel->[KR_ACTIVE_SESSION], $_[0] %}
$SIG{$_[0]} = \&_poe_signal_handler_pipe;
}
else {
warn "POE::Kernel::_signal_handler_pipe detected an undefined signal";
}
}
# SIGCH?LD are normalized to SIGCHLD and include the child process'
# PID and return code. Philip Gwyn rewrote most of the SIGCH?LD code
# for version 0.1006; it got rewritten again while the patches were
# manually applied. I expect it to be rewritten a few more times to
# fix Philip's code back the way it ought to be.
sub _poe_signal_handler_child {
if (defined $_[0]) {
# The default SIGCH?LD action is "discard". We set it here to
# prevent Perl from catching more SIGCHLD signals while the Kernel
# polls for child processes.
$SIG{$_[0]} = 'DEFAULT';
$poe_kernel->_enqueue_state( $poe_kernel, $poe_kernel,
EN_SCPOLL, ET_SCPOLL,
[ ],
time(), __FILE__, __LINE__
);
}
else {
warn "POE::Kernel::_signal_handler_child detected an undefined signal";
}
}
### Event's signal handlers.
sub _event_signal_handler_generic {
{% post_plain_signal $poe_kernel, $_[0]->w->signal %}
}
sub _event_signal_handler_pipe {
{% post_plain_signal $poe_kernel->[KR_ACTIVE_SESSION], $_[0]->w->signal %}
}
sub _event_signal_handler_child {
# Reap until there are no more children. This uses one of Event's
# own scripts for an example. I only mention it because I'm scared
# of wait(2).
$poe_kernel->_enqueue_state( $poe_kernel, $poe_kernel,
EN_SCPOLL, ET_SCPOLL,
[ ],
time(), __FILE__, __LINE__
);
}
#------------------------------------------------------------------------------
# Register or remove signals.
# Public interface for adding or removing signal handlers.
sub sig {
my ($self, $signal, $state) = @_;
if (defined $state) {
my $session = $self->[KR_ACTIVE_SESSION];
$self->[KR_SESSIONS]->{$session}->[SS_SIGNALS]->{$signal} = $state;
$self->[KR_SIGNALS]->{$signal}->{$session} = $state;
}
else {
{% sig_remove $self->[KR_ACTIVE_SESSION], $signal %}
}
}
# Public interface for posting signal events. 5.6.0 places a signal
# symbol in our table; the BEGIN block deletes it to prevent
# "Subroutine signal redefined" warnings.
BEGIN { delete $POE::Kernel::{signal}; }
sub POE::Kernel::signal {
my ($self, $destination, $signal) = @_;
my $session = {% alias_resolve $destination %};
{% test_resolve $destination, $session %}
$self->_enqueue_state( $session, $self->[KR_ACTIVE_SESSION],
EN_SIGNAL, ET_SIGNAL,
[ $signal ],
time(), (caller)[1,2]
);
}
#==============================================================================
# KERNEL
#==============================================================================
sub new {
my $type = shift;
# Prevent multiple instances, no matter how many times it's called.
# This is a backward-compatibility enhancement for programs that
# have used versions prior to 0.06.
unless (defined $poe_kernel) {
$poe_tk_main_window = Tk::MainWindow->new();
# If we have a Tk main window, then register an onDestroy handler
# for it. This handler broadcasts a terminal TKDESTROY signal to
# every session.
if (defined $poe_tk_main_window) {
$poe_tk_main_window->OnDestroy
( sub {
$poe_kernel->_dispatch_state
( $poe_kernel, $poe_kernel,
EN_SIGNAL, ET_SIGNAL, [ 'TKDESTROY' ],
time(), __FILE__, __LINE__, undef
);
}
);
}
my $self = $poe_kernel = bless
[ { }, # KR_SESSIONS
[ '', '', '' ], # KR_VECTORS
{ }, # KR_HANDLES
[ ], # KR_STATES
{ }, # KR_SIGNALS
{ }, # KR_ALIASES
undef, # KR_ACTIVE_SESSION
{ }, # KR_PROCESSES
[ ], # KR_ALARMS
undef, # KR_ID
{ }, # KR_SESSION_IDS
1, # KR_ID_INDEX
undef, # KR_WATCHER_TIMER
undef, # KR_WATCHER_IDLE
], $type;
# If POE uses Event to drive its queues, then one-time initialize
# watchers for idle and timed events.
if ( POE_HAS_EVENT ) {
$self->[KR_WATCHER_TIMER] = Event->timer
( cb => \&_event_alarm_callback,
after => 0,
parked => 1,
);
$self->[KR_WATCHER_IDLE ] = Event->idle
( cb => \&_event_fifo_callback,
repeat => 1,
min => 0,
max => 0,
parked => 1,
);
}
# Kernel ID, based on Philip Gwyn's code. I hope he still can
# recognize it. KR_SESSION_IDS is a hash because it will almost
# always be sparse.
$self->[KR_ID] = ( (uname)[1] . '-' .
unpack 'H*', pack 'N*', time, $$
);
$self->[KR_SESSION_IDS]->{$self->[KR_ID]} = $self;
# Initialize the vectors as vectors.
vec($self->[KR_VECTORS]->[VEC_RD], 0, 1) = 0;
vec($self->[KR_VECTORS]->[VEC_WR], 0, 1) = 0;
vec($self->[KR_VECTORS]->[VEC_EX], 0, 1) = 0;
# Register all known signal handlers, except the troublesome ones.
foreach my $signal (keys(%SIG)) {
# Some signals aren't real, and the act of setting handlers for
# them can have strange, even fatal side effects. Recognize and
# ignore them.
next if ($signal =~ /^( NUM\d+
|__[A-Z0-9]+__
|ALL|CATCHALL|DEFER|HOLD|IGNORE|MAX|PAUSE
|RTMIN|RTMAX|SETS
|SEGV
|
)$/x
);
# Artur has been experiencing problems where POE programs crash
# after resizing xterm windows. It was discovered that the
# xterm resizing was sending several WINCH signals, which
# eventually causes Perl to become unstable. Ignoring SIGWINCH
# seems to prevent the problem, but it's only a temporary
# solution. At some point, POE will include a set of Curses
# widgets, and SIGWINCH will be needed...
if ($signal eq 'WINCH') {
# Event polls signals in some XS, which means they ought not
# kill Perl. Use an Event->signal watcher if Event is
# available.
if (POE_HAS_EVENT) {
Event->signal( signal => $signal,
cb => \&_event_signal_handler_generic
);
}
# Otherwise ignore WINCH.
else {
$SIG{$signal} = 'IGNORE';
next;
}
}
# Windows doesn't have a SIGBUS, but the debugger causes SIGBUS
# to be entered into %SIG. Registering a handler for it becomes
# a fatal error. Don't do that!
if ($signal eq 'BUS' and $^O eq 'MSWin32') {
next;
}
# Register signal handlers by type.
if ($signal =~ /^CH?LD$/) {
# Leave SIGCHLD alone if running under apache.
unless (exists $INC{'Apache.pm'}) {
# Register an Event signal watcher on it. Rename the signal
# 'CHLD' regardless whether it's CHLD or CLD.
if (POE_HAS_EVENT) {
Event->signal( signal => $signal,
cb => \&_event_signal_handler_child
);
}
# Otherwise register a regular Perl signal handler.
else {
$SIG{$signal} = \&_poe_signal_handler_child;
}
}
}
elsif ($signal eq 'PIPE') {
# Register an Event signal watcher.
if (POE_HAS_EVENT) {
Event->signal( signal => $signal,
cb => \&_event_signal_handler_pipe
);
}
# Otherwise register a plain Perl signal handler.
else {
$SIG{$signal} = \&_poe_signal_handler_pipe;
}
}
else {
# If Event is available, register a signal watcher with it.
# Don't register a SIGKILL handler, though, because Event
# doesn't like that.
if (POE_HAS_EVENT and $signal ne 'KILL' and $signal ne 'STOP') {
Event->signal( signal => $signal,
cb => \&_event_signal_handler_generic
);
}
# Otherwise register a plain signal handler.
else {
$SIG{$signal} = \&_poe_signal_handler_generic;
}
}
$self->[KR_SIGNALS]->{$signal} = { };
}
# The kernel is a session, sort of.
$self->[KR_ACTIVE_SESSION] = $self;
$self->[KR_SESSIONS]->{$self} =
[ $self, # SS_SESSION
0, # SS_REFCOUNT
0, # SS_EVCOUNT
undef, # SS_PARENT
{ }, # SS_CHILDREN
{ }, # SS_HANDLES
{ }, # SS_SIGNALS
{ }, # SS_ALIASES
{ }, # SS_PROCESSES
$self->[KR_ID], # SS_ID
{ }, # SS_EXTRA_REFS
0, # SS_ALCOUNT
];
}
# Return the global instance.
$poe_kernel;
}
#------------------------------------------------------------------------------
# Send a state to a session right now. Used by _disp_select to
# expedite select() states, and used by run() to deliver posted states
# from the queue.
# This is for collecting state frequencies if TRACE_PROFILE is enabled.
my %profile;
# Dispatch a stat transition event to its session. A lot of work goes
# on here.
sub _dispatch_state {
my ( $self, $session, $source_session, $state, $type, $etc, $time,
$file, $line, $seq
) = @_;
# A copy of the state name, in case we have to change it.
my $local_state = $state;
# We do a lot with the sessions structure. Cache it in a lexical to
# save on dereferences.
my $sessions = $self->[KR_SESSIONS];
TRACE_PROFILE and $profile{$state}++;
# Pre-dispatch processing.
if ($type) {
# The _start state is dispatched immediately as part of allocating
# a session. Set up the kernel's tables for this session.
if ($type & ET_START) {
my $new_session = $sessions->{$session} =
[ $session, # SS_SESSION
0, # SS_REFCOUNT
0, # SS_EVCOUNT
$source_session, # SS_PARENT
{ }, # SS_CHILDREN
{ }, # SS_HANDLES
{ }, # SS_SIGNALS
{ }, # SS_ALIASES
{ }, # SS_PROCESSES
$self->[KR_ID_INDEX]++, # SS_ID
{ }, # SS_EXTRA_REFS
0, # SS_ALCOUNT
];
# For the ID to session reference lookup.
$self->[KR_SESSION_IDS]->{$new_session->[SS_ID]} = $session;
# Ensure sanity.
ASSERT_RELATIONS and do {
die {% ssid %}, " is its own parent\a"
if ($session == $source_session);
die( {% ssid %},
" already is a child of ", {% sid $source_session %}, "\a"
)
if (exists $sessions->{$source_session}->[SS_CHILDREN]->{$session});
};
# Add the new session to its parent's children.
$sessions->{$source_session}->[SS_CHILDREN]->{$session} = $session;
{% ses_refcount_inc $source_session %}
}
# Some sessions don't do anything in _start and expect their
# creators to provide a start-up event. This means we can't
# &_collect_garbage at _start time. Instead, we post a
# garbage-collect event at start time, and &_collect_garbage at
# delivery time. This gives the session's creator time to do
# things with it before we reap it.
elsif ($type & ET_GC) {
{% collect_garbage $session %}
return 0;
}
# A session's about to stop. Notify its parents and children of
# the impending change in their relationships. Incidental _stop
# events are handled before the dispatch.
elsif ($type & ET_STOP) {
# Tell child sessions that they have a new parent (the departing
# session's parent). Tell the departing session's parent that
# it has new child sessions.
my $parent = $sessions->{$session}->[SS_PARENT];
my @children = values %{$sessions->{$session}->[SS_CHILDREN]};
foreach my $child (@children) {
$self->_dispatch_state( $parent, $self,
EN_CHILD, ET_CHILD,
[ 'gain', $child ],
time(), $file, $line, undef
);
$self->_dispatch_state( $child, $self,
EN_PARENT, ET_PARENT,
[ $sessions->{$child}->[SS_PARENT], $parent, ],
time(), $file, $line, undef
);
}
# Tell the departing session's parent that the departing session
# is departing.
if (defined $parent) {
$self->_dispatch_state( $parent, $self,
EN_CHILD, ET_CHILD,
[ 'lose', $session ],
time(), $file, $line, undef
);
}
}
# Preprocess signals. This is where _signal is translated into
# its registered handler's state name, if there is one.
elsif ($type & ET_SIGNAL) {
my $signal = $etc->[0];
# Propagate the signal to this session's children. This happens
# first, making the signal's traversal through the parent/child
# tree depth first. It ensures that signals posted to the
# Kernel are delivered to the Kernel last.
my @children = values %{$sessions->{$session}->[SS_CHILDREN]};
foreach (@children) {
$self->_dispatch_state( $_, $self,
$state, ET_SIGNAL,
$etc,
time(), $file, $line, undef
);
}
# Translate the '_signal' state to its handler's name.
if (exists $self->[KR_SIGNALS]->{$signal}->{$session}) {
$local_state = $self->[KR_SIGNALS]->{$signal}->{$session};
}
}
}
# The destination session doesn't exist. This is an indication of
# sloppy programming, either on POE's author's part or its user's
# part.
unless (exists $self->[KR_SESSIONS]->{$session}) {
TRACE_EVENTS and do {
warn ">>> discarding $state to nonexistent ", {% ssid %}, "\n";
};
return;
}
TRACE_EVENTS and do {
warn ">>> dispatching $state to ", {% ssid %}, "\n";
};
# Prepare to call the appropriate state. Push the current active
# session on Perl's call stack.
my $hold_active_session = $self->[KR_ACTIVE_SESSION];
$self->[KR_ACTIVE_SESSION] = $session;
# Dispatch the event, at long last.
my $return =
$session->_invoke_state($source_session, $local_state, $etc, $file, $line);
# Stringify the state's return value if it belongs in the POE
# namespace. $return's scope exists beyond the post-dispatch
# processing, which includes POE's garbage collection. The scope
# bleed was known to break determinism in surprising ways.
if (defined $return) {
if (substr(ref($return), 0, 5) eq 'POE::') {
$return = "$return";
}
}
else {
$return = '';
}
# Pop the active session, now that it's not active anymore.
$self->[KR_ACTIVE_SESSION] = $hold_active_session;
TRACE_EVENTS and do {
warn "<<< ", {% ssid %}, " -> $state returns ($return)\n";