lib/Language/Zcode/Runtime/State.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« lib/Language/Zcode/Parser.pm ↑ Summary lib/Language/Zcode/Util.pm »
1 package Language::Zcode::Runtime::State;
2
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 our @ISA = qw(Exporter);
6 our @EXPORT = qw(z_call save_state restore_state);
7
8 0 ▶use Language::Zcode::Runtime::Quetzal;
Subroutine BEGIN: called CC=1 SCAR=2.6
9
10 =head1 NAME
11
12 Language::Zcode::Runtime::State - Handle saving, restoring, etc. the game state
13
14 =cut
15
16
17 # @Call_Stack is a Z-machine (Quetzal) call stack we read from a save file.
18 # To restore a saved state, we climb it and restore each frame.
19 # Call stack originally has a dummy frame in it
20 # (I'm creating that by doing a z_call(first sub) tho.
21 # TODO v6 there's no dummy frame.
22 my @Call_Stack;
23 my $Restore_PC;
24
25 =head2 restoring
26
27 Getter/setter: currently in the process of restoring or not?
28
29 =cut
30
31 my $Restoring = 0;
32 sub restoring() {
33 $Restoring = $_[0] if defined $_[0];
34 return $Restoring;
35 }
36
37 =head2 start_machine
38
39 Start executing the Z-machine.
40
41 In the normal case (starting a new game, or restarting), this is as simple
42 as calling the Z-machine subroutine whose address is stored in the header.
43
44 If we're restoring from a save file, it's more complicated.
45 See L</"resume_execution">.
46
47 =back
48
49 =cut
50
51 sub start_machine {
52 if (restoring()) { # resume Z-machine execution right where we left off
53 &resume_execution();
54
55 } else { # regular old (re)start
56
57 }
58
59 }
60
61 =head2 z_call
62
63 Wrapper around Z-code subroutine calls. The main reason we need it is
64 for save/restore.
65
66 In the normal case, z_call just calls the Z-code subroutine at address arg0
67 with the given args (arg5-argn), if any. Args 1-4 aren't used by z_call, but
68 (hack alert!) they go into the Perl call stack, which is needed for
69 saving Z-machine state.
70
71 Input: subroutine address to call, local variables & eval stack (arrayrefs),
72 next PC, store variable, args to the Z-sub.
73
74 See L</"The call stack"> for far more detail on this sub and save/restore.
75
76 =cut
77
78 # TODO put 'A' variables into a [], maybe after @args because they're not
79 # used by the sub. Just pop them off.
80 sub z_call {
81 # 'A' vars are just passed in so they'll be in the Perl call stack;
82 # they're not actually used in this sub!
83 # $Astore is undef for call_?n
84 my ($sub_address, $Aloc, $Astack, $Anext, $Astore, @args) = @_;
85
86 # Spec 6.4.3, 15 'call': "When the address 0 is called as a routine, nothing
87 # happens and the return value is false".
88 return 0 if $sub_address == 0;
89
90 printf "Sub $sub_address (%x) called with params (@args)\n", $sub_address
91 if $main::DEBUG;
92
93 # Special info for recreating the call stack during restore,
94 # when the called sub has to start in the middle,
95 my $frame_info = [];
96
97 if (restoring()) {
98 # Recursively call z_call to climb the stack (which as a side effect
99 # rebuilds the Perl call stack), store the return value,
100 # then call the Z-code sub with new args so it starts in the middle
101 # and has the correct @locv/@stack
102 my %frame = %{shift @Call_Stack};
103 my ($locref, $stackref) = @frame{qw(locals eval_stack)};
104 my @locv = @$locref;
105 my @stack = @$stackref;
106
107 # address to resume at (jump to) in the to-be-called sub.
108 my $next_PC;
109 if (@Call_Stack) {
110 # Climb one frame on the stack and call z_call recursively
111 %frame = %{$Call_Stack[0]}; # don't shift; need it next time
112 $next_PC = $frame{next_PC};
113
114 my $next_next = @Call_Stack > 1 ?
115 $Call_Stack[1]->{next_PC} : $Restore_PC;
116 my $sub_to_call = &_find_sub_start($next_next);
117 # All we need is correct *number* of args, so call stack looks right
118 my @dummy_args = (-1) x ($frame{args} =~ tr/1//);
119 my $store_var = $frame{discard_result} ? undef : $frame{store_var};
120 my $result = z_call($sub_to_call, $locref, $stackref, $next_PC,
121 $store_var, @dummy_args);
122
123 # Store the result in variables from the calling sub (or globals)
124 if (defined $store_var) { # otherwise, discard result
125 die ("Invalid store_var $store_var in restored state")
126 if $store_var =~ /\D/ || $store_var > 255;
127 if ($store_var == 0) {
128 push @stack, $result;
129 } elsif ($store_var < 16) {
130 $locv[$store_var - 1] = $result;
131 } else {
132 Language::Zcode::Runtime::Opcodes::global_var($store_var - 16, $result);
133 }
134 }
135
136 } else {
137 # we're about to jump into the top stack frame, and we'll start
138 # it at the address where it calls save
139 # - Don't store result in a store_var. &save_state will return
140 # a value to @save.
141 # - next_PC will be restore_PC instead of a frame's next_PC
142 # - stop recursion
143 $next_PC = $Restore_PC;
144 }
145
146 # Call the sub with extra info so that it starts execution in the middle
147 $frame_info = [$next_PC, \@locv, \@stack];
148 } # end if (restoring())
149
150
151 # Actually call the subroutine, possibly telling it to start executing
152 # somewhere in the middle with restored values
153 my $result = do {
154 no strict 'refs'; &{"main::rtn$sub_address"}($frame_info, @args)
155 };
156
157 return $result; # may be undef
158 }
159
160 # Given an address, find the subroutine that that address falls in.
161 # HACK: Find all subroutine start addresses by peeking at the symbol table.
162 sub _find_sub_start {
163 my $addr = shift;
164 my @rtns = sort grep { /^rtn(\d+)/ and $_ = $1 } keys %::;
165 # print "Match $addr. Routines are @rtns\n";
166 # Binary search (except we won't find an exact match - but that's OK
167 # because first byte in a sub CAN'T be an opcode address.)
168 # Perl golf'ed down to one line, tho I didn't take out the whitspace :)
169 my ($lo, $hi, $i) = (0, $#rtns+1); # +1 so $lo can get up to $#rtns
170 ($addr >= $rtns[$i = int(($lo + $hi)/2)] ? $lo : $hi) = $i
171 while $hi - $lo > 1;
172 return $rtns[$lo];
173 }
174
175 =head2 save_state
176
177 Implement the @save opcode, saving the current Z-machine state (as opposed to
178 writing a table to a file, the other use of the @save opcode)
179
180 Note that this sub also gets called at the very end of the restoring process.
181
182 Returns 0 for failed save, 1 for successful save, 2 for "just finished
183 restoring".
184
185 =cut
186
187 sub save_state {
188 my ($PC, $locref, $stackref) = @_;
189 my $save_result = 0;
190
191 if (&restoring()) { # Just finished a restore
192 &restoring(0); # We're done restoring
193 $save_result = 2;
194
195 } else { # really save
196
197 my $save_name = Language::Zcode::Runtime::IO::filename_prompt("-ext"=>"sav",-check=>1)
198 or return 0;
199
200 my $header = {
201 release => $main::Constants{release_number},
202 serial => $main::Constants{serial_code},
203 checksum => $main::Constants{file_checksum},
204 restore_PC => $PC,
205 };
206
207 # Munge the Perl call stack to create a Z-machine call stack
208 # that will get saved.
209 my @Z_Stack = build_save_stack($locref, $stackref);
210
211 my ($str) = Language::Zcode::Runtime::Quetzal::build_quetzal(
212 $header, \@Z_Stack, &PlotzMemory::get_dynamic_memory);
213 if ($str) {
214 write_file($save_name, $str);
215 $save_result = 1;
216 }
217 }
218
219 return $save_result;
220 }
221
222 =head2 build_save_stack
223
224 Create a Z-machine call stack by peeking at the Perl call stack.
225
226 When calling Z_machine subroutines, we call z_call with all the information
227 contained in a Z stack frame. We retrieve that information from the Perl
228 call stack and build a Z-machine call stack with it.
229
230 =cut
231
232 sub build_save_stack {
233 my ($locref, $stackref) = @_;
234 my @save = ();
235 {
236 package DB; # make caller() set @DB::args
237 my $i = 0;
238 my ($lref, $sref) = ($locref, $stackref);
239 while (my ($p,$f,$l,$s) = caller(++$i)) {
240 if ($s =~ /z_call/) {
241 #z_call(ROUTINE, \@locv, \@stack, NEXT_PC, STORE_VAR, ARG_LIST)
242 my @a = @DB::args;
243 my $discard = defined $a[4] ? 0 : 1;
244 my $store_var = $discard ? 0 : $a[4];
245 #my $args = substr('0'x8 . '1'x($#a - 4), -8, 8);
246 my $args = sprintf('%08s', '1' x ($#a - 4));
247 unshift @save, {
248 discard_bit => $discard, store_var => $store_var,
249 args => $args, next_PC => $a[3],
250 locals => $lref, eval_stack => $sref,
251 };
252 ($lref, $sref) = @a[1, 2]; # for next frame
253 }
254 }
255 }
256 # Quetzal 4.11.1: Dummy frame at bottom of stack has discard=0, too
257 $save[0]{discard_bit} = 0;
258 return @save;
259 }
260
261 =head2 restore_state
262
263 Implement the @restore opcode, restoring the current Z-machine state (as
264 opposed to reading a table from a file, the other use of the @restore opcode)
265
266 =cut
267
268 sub restore_state {
269 # TODO static variable in this package stores name of the last
270 # restore file, and offers to reuse. in case user e.g., keeps dying
271 my $restore_name = Language::Zcode::Runtime::IO::filename_prompt(
272 "-ext" => "sav") or return 0;
273 warn "Can't find file '$restore_name'\n", return 0
274 unless -e $restore_name;
275
276 my $restore_result = 0;
277 my $save_string = read_file($restore_name) or return 0;
278 my ($memory_ref, $stack_ref, $header_ref) =
279 Language::Zcode::Runtime::Quetzal::parse_quetzal($save_string);
280 # Store new memory to be restored after we "die"
281 PlotzMemory::store_dynamic_memory($memory_ref);
282 my %header = %$header_ref;
283 my ($release, $serial, $checksum, $PC) =
284 @header{qw(release serial checksum restore_PC)};
285
286 # verify this is a valid restore for this game
287 my $error = "";
288 if ($release ne $main::Constants{release_number}) {
289 $error = "Save file is for game release $release, " .
290 "not $main::Constants{release_number}";
291 } elsif ($checksum ne $main::Constants{file_checksum}) {
292 $error = "Checksum in save file is different than game checksum";
293 } elsif ($serial ne $main::Constants{serial_code}) {
294 $error = "Save file is for game serial # $serial, " .
295 "not $main::Constanst{serial_code}";
296 }
297 if ($error) {
298 Language::Zcode::Runtime::IO::write_text($error);
299 Language::Zcode::Runtime::IO::newline();
300 } else {
301 $Restore_PC = $PC;
302 @Call_Stack = @$stack_ref;
303 &restoring(1); # turn on global restoring flag
304
305 # Now throw an exception that'll reboot the Z-machine
306 die "Restore\n";
307 }
308 return $restore_result; # 0. Otherwise, we've restored and are elsewhere
309 }
310
311 # read save file
312 sub read_file {
313 my $save_file = shift;
314 open F, $save_file or
315 warn "Opening $save_file for read: $!\n" and return 0;
316 binmode F;
317 my $st;
318 { local $/; undef $/; $st = <F>; }
319 close F;
320 return $st;
321 }
322
323 # write save file
324 sub write_file {
325 my ($save_file, $str) = @_;
326 open F, ">$save_file" or die "Opening $save_file for write: $!\n";binmode F;
327 print F $str;
328 close F;
329 }
330
331 =head1 NOTES
332
333 =head2 The call stack
334
335 The Z-code call stack is much different than the Perl call stack, so it
336 takes a bit of work to convert one to the other. Almost all of the work
337 is done by the z_call routine which is a wrapper around Z-code subs.
338
339 B<Building the call stack>
340
341 z_call is called with extra args (arg1-arg4), that are not technically used
342 by z_call or the subs it calls. However, the Perl call stack stores
343 these args, and we can later build a Z-machine (Quetzal) call stack
344 using @DB::args (see L<perlfunc/"caller">). Sneaky!
345
346 B<Restoring>
347
348 How do we restore from a save file? We need to start execution with the
349 Z-machine in the same state it was in when we did the @save. So we need to
350 restore local variables and the eval stack. We also need to restore the call
351 stack, so that when we finish a sub, we jump back into the middle of the sub
352 that called that sub (at the address right after the call).
353
354 restore_state is quite simple: it just sets the restoring flag and then die()s
355 (i.e., reboots the Z-machine). Most of the work is done by &z_call, when it
356 sees the restoring flag.
357
358 When we're restoring, z_call is more complicated. We need to start executing
359 subroutines in the middle (i.e., wherever the program counter was when @save
360 was called), with the correct local variable and eval stack values.
361
362 z_call does this by reading data from the call stack and calling the Z-code
363 subs with special args that tell them to start executing at a given address.
364
365 Where the usual calling tree looks like this:
366 The main Perl program calls z_code(A)
367 z_call calls Z-code sub A ('main' sub)
368 Z-code sub A calls z_call(B)
369 z_call calls B
370 Z-code sub B calls z_call(C), etc.
371
372 We instead do this:
373 The main Perl program calls z_code(A)
374 z_call sees that A will call B, so it calls z_call(B)
375 z_call(B) sees that B will call C, so it calls z_call(C)
376 ...
377 z_call(E) calls z_call(F), exhausting the restored call stack
378 z_call(F) stops recursing and calls Z-code sub F with special
379 args saying to start executing at the @save command
380 F says "stop restoring", and returns
381 z_call(E) calls E, saying to start executing after the call to F
382 ...
383 z_call(B) calls B, saying to start executing after the call to C
384
385 This is complicated, but has several benefits:
386
387 =over 4
388
389 =item *
390
391 We rebuild the Perl call stack so that if we call @save again from, say, a
392 later point in E, we'll save the stack correctly.
393
394 =item *
395
396 By climbing up the stack, we can properly store C's return value in a variable
397 in B, etc.
398
399 =item *
400
401 The complexity is (mostly) kept in z_call, not all over the translated
402 Z-code.
403
404 =item *
405
406 Each Z-code sub ends up executing in the middle of the sub, right where it was
407 - and in the same state as it was - when the @save happened.
408
409 =back
410
411 The very first opcode we execute when z_call gets to the top of the stack is
412 guaranteed to be @save. This turns the restoring flag off. By the time we
413 return from the called Z-code sub back to z_call, even though we're within
414 several levels of recursion, we're in normal program flow.
415
416 (Note that z_call and the Z-code subs were calling each other recursively
417 anyway. We just change the order around when restoring, so z_call calls itself
418 and then calls the Z-code sub.)
419
420 B<Frame mismatch>
421
422 Another piece of complexity is a mismatch between Quetzal and Perl.
423
424 Assume sub B calls sub C, with a call like
425 $result = z_call(C, Blocals, Bstack, Bnext_PC, Bstore_var, args);
426
427 (where Blocals means the local variables in subroutine B).
428
429 Quetzal frames actually mix values from different (Perl) subroutines, so
430 we have frames like (Clocals, Cstack, Bnext_PC, Bstore_var).
431
432 In addition, the only way we can figure out C while restoring is to
433 get Cnext_PC (which will be in the frame with Dlocals et al.!) and
434 to find the sub that contains the Cnext_PC address. So we actually
435 need to look at three different frames in order to recreate the
436 z_call that happened in the saved program.
437
438 B<Starting subs in the middle>
439
440 z_call is called with @args, the list of arguments to be passed to the Z-code
441 sub. Usually, we just pass the @args to the subroutine we call. However, when
442 we're restoring, we replace @args with the values that should be in @locv for
443 the called sub (which we got from the frame). We ignore @args in that case.
444 Since Z-code subs automatically set @locv to be equal to the input args,
445 this sets @locv to have the same value as it had when machine state
446 was saved.
447
448 Also note that Quetzal saves only the number of args in a subroutine call, not
449 their values. So when we're restoring and recursively calling z_call as we
450 climb the stack, we don't know which @args to pass to those z_call calls. So we
451 just pass in dummy values. (We need to get the right number of args so that the
452 call stack is built correctly.)
453
454 =cut
455
456 1;
« lib/Language/Zcode/Parser.pm ↑ Summary lib/Language/Zcode/Util.pm »