File Coverage

blib/lib/Scope/Cleanup.pm
Criterion Covered Total %
statement 14 14 100.0
branch n/a
condition n/a
subroutine 5 5 100.0
pod n/a
total 19 19 100.0


line stmt bran cond sub pod time code
1             =head1 NAME
2              
3             Scope::Cleanup - reliably run code upon exit of dynamic scope
4              
5             =head1 SYNOPSIS
6              
7             use Scope::Cleanup qw(establish_cleanup);
8              
9             establish_cleanup sub { ... };
10             establish_cleanup \&do_cleanup;
11             establish_cleanup $cleanup_code_ref;
12              
13             =head1 DESCRIPTION
14              
15             This module provides a facility for automatically running cleanup code
16             when exiting a dynamic scope. The cleanup code is attached to the stack
17             frame directly, rather than being attached to an object that must then
18             be managed separately. The cleanup code reliably runs when the stack
19             frame unwinds, regardless of the reason for unwinding: it may be a normal
20             return, exception throwing, program exit, or any kind of non-local return.
21              
22             Cleanup code established through this module has direct access to Perl's
23             dynamic state. It can do things such as C to change the course of
24             execution outside the cleanup.
25              
26             =head1 STACK UNWINDING
27              
28             While returning (locally or non-locally) to an outer stack frame,
29             things must be done automatically at each stage, depending on the
30             circumstances in which the stack frames were created. Variables that
31             were given dynamically-local values (with C) are restored to
32             their previous values. Objects used by the stack frames, that are
33             not referenced elsewhere, are destroyed. These things happen in the
34             reverse of the order in which their stack frames were established.
35             This is referred to as "unwinding the stack".
36              
37             It is sometimes desired to establish some code that will be automatically
38             executed during unwinding, for example to release resources that are not
39             reified as objects. A common way of doing this in Perl, implemented
40             in the L module, is to create a blessed object whose C
41             method will perform the desired action, and hold a reference to it in
42             a lexical variable. If the object is not otherwise touched, then upon
43             unwinding its destructor will fire. This isn't really a clean approach
44             for arbitrary cleanup code, which is more concerned with its specific
45             stack frame than with a specific object. This module provides a better
46             way to run arbitrary cleanup code, registering code directly to run
47             during unwinding, without any intermediation.
48              
49             An object destructor is run inside an implicit C block. This
50             prevents it from making any non-local control transfer outside the
51             confines of the destructor. This is an appropriate limitation to put
52             on object destructors, but is not so appropriate for code associated
53             with a specific stack frame. Code run directly is not so wrapped, and
54             is free to make non-local control transfers. However, when the stack
55             unwinding is due to one of Perl's native mechanisms, critical parts of
56             the stack can be seen in an inconsistent state, which interferes with some
57             non-local transfers that ought to be valid. This is because Perl doesn't
58             expect arbitrary code to run without an C block during unwinding.
59             The unwinding performed by L's non-local control transfers
60             is better behaved.
61              
62             =head1 VULNERABLE STATE VARIABLES
63              
64             Cleanup code must be especially careful about certain global state
65             variables. The five variables C<$.>, C<$@>, C<$!>, C<$^E>, and C<$?>
66             are all set as a side effect by relevant operations, indicating part of
67             the result of that operation. They are expected to be examined by code
68             run subsequently, before the next operation relevant to the variable
69             overwrites it. (For C<$.> the value itself does not behave like this,
70             because that is actually part of an I/O handle's persistent state.
71             However, the choice of which I/O handle the variable looks at is such
72             temporary status.)
73              
74             If some code that incidentally overwrites one of the status variables
75             is somehow executed between a relevant operation and the code that
76             expected to read the variable, then the wrong value will be read.
77             The most serious type of problem occurs with C setting C<$@>,
78             where reading the correct value from C<$@> is almost always critical to
79             the next bit of program logic. Also, prior to Perl 5.13.1, C is
80             much more vulnerable to having the variable clobbered than are operations
81             involving the other variables. When Cing on an older Perl, C<$@>
82             gets set first, then the stack unwinds to the eval frame, and only
83             then does C complete. So there is a large window of opportunity
84             during unwinding for C<$@> to lose the exception that is being thrown.
85             From Perl 5.13.1 onwards that particular vulnerability has been fixed,
86             but C<$@> can still potentially be clobbered after C completes.
87              
88             There are three main ways that lexically remote code could get run
89             unexpectedly: signal handlers, object destructors, and scope cleanup code.
90             Signal handlers can be run at essentially any time. Not knowing what
91             code they might be interrupting, it is vital that they avoid changing
92             any of the status variables. It must also be careful not to C
93             or otherwise exit non-locally. (Though it can validly use exceptions
94             internally.) Object destructors are a bit more predictable, and in fact
95             predictable destruction time is often used as a hack to achieve a scope
96             cleanup effect, but basically destructors can run at nearly any time.
97             Destructors should also, therefore, always avoid changing any of the
98             status variables.
99              
100             Scope cleanup code is in a different position. Because it is guaranteed
101             to run when a particular scope exits, the code around that scope may be
102             expecting the effects of the cleanup code. That might include performing
103             operations that set status variables, for code running just outside the
104             scope to read. It is permitted to do this sort of thing, but liable to
105             be confusing, so it is recommended that you not pass information out of
106             cleanup code in this way. (You should read the status variable inside the
107             cleanup code, and put the result in an ordinary well-behaved variable.)
108             Cleanup code might also intentionally C or perform another kind of
109             non-local control transfer.
110              
111             Where automatically-run code does not intend to set the global status
112             variables for other code to read, it should consistently localise them,
113             with "C". This should be done as early as
114             possible in the signal handler, destructor, or cleanup function.
115              
116             If a scope cleanup function intends to exit by C, there is a
117             complication. Prior to Perl 5.13.1, localising C<$@> prevents the C
118             from working normally: the restoration of the previous value will itself
119             clobber C<$@> for the purposes of that C. (This is due to C<$@>
120             being set early in the C, as described above.) In this case, the
121             cleanup function must not localise C<$@>, and must make other arrangements
122             to avoid clobbering C<$@> in the event that it does not exit by C.
123              
124             There is ongoing discussion about changing some of the Perl core's
125             semantics, to make the above more tractable. The changes to C<$@>
126             behaviour in Perl 5.13.1 were a result of these concerns, and further
127             change is likely.
128              
129             =cut
130              
131             package Scope::Cleanup;
132              
133 14     14   1013945 { use 5.008001; }
  14         65  
134 14     14   95 use warnings;
  14         34  
  14         489  
135 14     14   89 use strict;
  14         39  
  14         544  
136              
137 14     14   8875 use Devel::CallChecker 0.003 ();
  14         24209  
  14         651  
138              
139             our $VERSION = "0.003";
140              
141 14     14   115 use parent "Exporter";
  14         37  
  14         64  
142             our @EXPORT_OK = qw(establish_cleanup);
143              
144             require XSLoader;
145             XSLoader::load(__PACKAGE__, $VERSION);
146              
147             =head1 OPERATORS
148              
149             These operators should be used through bareword function call syntax,
150             as if they were functions. However, they cannot otherwise be called as
151             functions in the normal manner. Attempting to take a reference to them
152             will result in a code reference that does not have any of the behaviour
153             described.
154              
155             =over
156              
157             =item establish_cleanup(CLEANUP_CODE)
158              
159             I must be a reference to a subroutine. A cleanup handler
160             is established, such that the referenced subroutine will be called during
161             unwinding of the current stack frame.
162              
163             =back
164              
165             =head1 SEE ALSO
166              
167             L,
168             L
169              
170             =head1 AUTHOR
171              
172             Andrew Main (Zefram)
173              
174             =head1 COPYRIGHT
175              
176             Copyright (C) 2010, 2012, 2017 Andrew Main (Zefram)
177              
178             =head1 LICENSE
179              
180             This module is free software; you can redistribute it and/or modify it
181             under the same terms as Perl itself.
182              
183             =cut
184              
185             1;