-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinary
More file actions
executable file
·1546 lines (1352 loc) · 63.9 KB
/
Copy pathbinary
File metadata and controls
executable file
·1546 lines (1352 loc) · 63.9 KB
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
#!/usr/bin/perl
# 99aeabc9ec7fe80b1b39f5e53dc7e49e <- self-modifying Perl magic
# state: 3adfc957094f35e4175a95ae9f70f55b
# istate: 606dfbfbb1378e9a1c99362e070d2e0d
# id: 93194ecf50e38f2adb6e273909e007b5
# This is a self-modifying Perl file. I'm sorry you're viewing the source (it's
# really gnarly). If you're curious what it's made of, I recommend reading
# https://github.com/spencertipping/writing-self-modifying-perl.
#
# If you got one of these from someone and don't know what to do with it, send
# it to spencer@spencertipping.com and I'll see if I can figure out what it
# does.
# For the benefit of HTML viewers (this is a hack):
# <div id='cover' style='position: absolute; left: 0; top: 0; width: 10000px; height: 10000px; background: white'></div>
$|++;
my %data;
my %transient;
my %externalized_functions;
my %datatypes;
my %locations; # Maps eval-numbers to attribute names
my $global_data = join '', <DATA>;
sub meta::define_form {
my ($namespace, $delegate) = @_;
$datatypes{$namespace} = $delegate;
*{"meta::${namespace}::implementation"} = $delegate;
*{"meta::$namespace"} = sub {
my ($name, $value, %options) = @_;
chomp $value;
$data{"${namespace}::$name"} = $value unless $options{no_binding};
&$delegate($name, $value) unless $options{no_delegate}}}
sub meta::eval_in {
my ($what, $where) = @_;
# Obtain next eval-number and alias it to the designated location
@locations{eval('__FILE__') =~ /\(eval (\d+)\)/} = ($where);
my $result = eval $what;
$@ =~ s/\(eval \d+\)/$where/ if $@;
warn $@ if $@;
$result}
meta::define_form 'meta', sub {
my ($name, $value) = @_;
meta::eval_in($value, "meta::$name")};
meta::meta('configure', <<'__');
# A function to configure transients. Transients can be used to store any number of
# different things, but one of the more common usages is type descriptors.
sub meta::configure {
my ($datatype, %options) = @_;
$transient{$_}{$datatype} = $options{$_} for keys %options;
}
__
meta::meta('externalize', <<'__');
# Function externalization. Data types should call this method when defining a function
# that has an external interface.
sub meta::externalize {
my ($name, $attribute, $implementation) = @_;
my $escaped = $name;
$escaped =~ s/[^A-Za-z0-9:]/_/go;
$externalized_functions{$name} = $externalized_functions{$escaped} = $attribute;
*{"::$name"} = *{"::$escaped"} = $implementation || $attribute;
}
__
meta::meta('functor::editable', <<'__');
# An editable type. This creates a type whose default action is to open an editor
# on whichever value is mentioned. This can be changed using different flags.
sub meta::functor::editable {
my ($typename, %options) = @_;
meta::configure $typename, %options;
meta::define_form $typename, sub {
my ($name, $value) = @_;
$options{on_bind} && &{$options{on_bind}}($name, $value);
meta::externalize $options{prefix} . $name, "${typename}::$name", sub {
my $attribute = "${typename}::$name";
my ($command, @new_value) = @_;
return &{$options{default}}(retrieve($attribute)) if ref $options{default} eq 'CODE' and not defined $command;
return edit($attribute) if $command eq 'edit' or $options{default} eq 'edit' and not defined $command;
return associate($attribute, @new_value ? join(' ', @new_value) : join('', <STDIN>)) if $command eq '=' or $command eq 'import' or $options{default} eq 'import' and not defined $command;
return retrieve($attribute)}}}
__
meta::meta('type::alias', <<'__');
meta::configure 'alias', inherit => 0, trim => 1;
meta::define_form 'alias', sub {
my ($name, $value) = @_;
meta::externalize $name, "alias::$name", sub {
# Can't pre-tokenize because shell::tokenize doesn't exist until the library::
# namespace has been evaluated (which will be after alias::).
shell::run(shell::tokenize($value), shell::tokenize(@_));
};
};
__
meta::meta('type::binary', 'meta::functor::editable \'binary\', extension => \'.binary\', default => \'edit\', inherit => 0;');
meta::meta('type::bootstrap', <<'__');
# Bootstrap attributes don't get executed. The reason for this is that because
# they are serialized directly into the header of the file (and later duplicated
# as regular data attributes), they will have already been executed when the
# file is loaded.
meta::configure 'bootstrap', extension => '.pl', inherit => 1, trim => 1;
meta::define_form 'bootstrap', sub {};
__
meta::meta('type::cache', <<'__');
meta::configure 'cache', inherit => 0, trim => 1;
meta::define_form 'cache', \&meta::bootstrap::implementation;
__
meta::meta('type::data', 'meta::functor::editable \'data\', extension => \'\', inherit => 0, default => \'cat\';');
meta::meta('type::function', <<'__');
meta::configure 'function', extension => '.pl', inherit => 1, trim => 1;
meta::define_form 'function', sub {
my ($name, $value) = @_;
meta::externalize $name, "function::$name", meta::eval_in("sub {\n$value\n}", "function::$name");
};
__
meta::meta('type::hook', <<'__');
meta::configure 'hook', extension => '.pl', inherit => 0, trim => 1;
meta::define_form 'hook', sub {
my ($name, $value) = @_;
*{"hook::$name"} = meta::eval_in("sub {\n$value\n}", "hook::$name");
};
__
meta::meta('type::inc', <<'__');
meta::configure 'inc', inherit => 1, extension => '.pl', trim => 1;
meta::define_form 'inc', sub {
use File::Path 'mkpath';
use File::Basename qw/basename dirname/;
my ($name, $value) = @_;
my $tmpdir = basename($0) . '-' . $$;
my $filename = "/tmp/$tmpdir/$name";
push @INC, "/tmp/$tmpdir" unless grep /^\/tmp\/$tmpdir$/, @INC;
mkpath(dirname($filename));
unless (-e $filename) {
open my $fh, '>', $filename;
print $fh $value;
close $fh;
}
};
__
meta::meta('type::indicator', <<'__');
# Shell indicator function. The output of each of these is automatically
# appended to the shell prompt.
meta::configure 'indicator', inherit => 1, extension => '.pl', trim => 1;
meta::define_form 'indicator', sub {
my ($name, $value) = @_;
*{"indicator::$name"} = meta::eval_in("sub {\n$value\n}", "indicator::$name");
};
__
meta::meta('type::internal_function', <<'__');
meta::configure 'internal_function', extension => '.pl', inherit => 1, trim => 1;
meta::define_form 'internal_function', sub {
my ($name, $value) = @_;
*{$name} = meta::eval_in("sub {\n$value\n}", "internal_function::$name");
};
__
meta::meta('type::library', <<'__');
meta::configure 'library', extension => '.pl', inherit => 1, trim => 1;
meta::define_form 'library', sub {
my ($name, $value) = @_;
meta::eval_in($value, "library::$name");
};
__
meta::meta('type::message_color', <<'__');
meta::configure 'message_color', extension => '', inherit => 1, trim => 1;
meta::define_form 'message_color', sub {
my ($name, $value) = @_;
terminal::color($name, $value);
};
__
meta::meta('type::meta', <<'__');
# This doesn't define a new type. It customizes the existing 'meta' type
# defined in bootstrap::initialization. Note that horrible things will
# happen if you redefine it using the editable functor.
meta::configure 'meta', extension => '.pl', inherit => 1, trim => 1;
__
meta::meta('type::parent', <<'__');
meta::define_form 'parent', \&meta::bootstrap::implementation;
meta::configure 'parent', extension => '', inherit => 1, trim => 1;
__
meta::meta('type::retriever', <<'__');
meta::configure 'retriever', extension => '.pl', inherit => 1, trim => 1;
meta::define_form 'retriever', sub {
my ($name, $value) = @_;
$transient{retrievers}{$name} = meta::eval_in("sub {\n$value\n}", "retriever::$name");
};
__
meta::meta('type::state', <<'__');
# Allows temporary or long-term storage of states. Nothing particularly insightful
# is done about compression, so storing alternative states will cause a large
# increase in size. Also, states don't contain other states -- otherwise the size
# increase would be exponential.
# States are created with the save-state function.
meta::configure 'state', inherit => 0, extension => '.pl', trim => 1;
meta::define_form 'state', \&meta::bootstrap::implementation;
__
meta::meta('type::vim_highlighter', <<'__');
# Vim highlighters don't need to be inherited. The reason is that they are most
# often configured from the parent object using the 'vim' function. They are
# rarely sent to anyone else and configured after the fact.
meta::configure 'vim_highlighter', extension => '.vim', inherit => 0;
meta::define_form 'vim_highlighter', \&meta::bootstrap::implementation;
__
meta::bootstrap('html', <<'__');
<html>
<head>
<meta http-equiv='content-type' content='text/html; charset=UTF-8' />
<link rel='stylesheet' href='http://spencertipping.com/perl-objects/web/style.css'/>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js'></script>
<script src='http://spencertipping.com/caterwaul/caterwaul.all.min.js'></script>
<script src='http://spencertipping.com/montenegro/montenegro.client.js'></script>
<script src='http://spencertipping.com/perl-objects/web/attribute-parser.js'></script>
<script src='http://spencertipping.com/perl-objects/web/interface.js'></script>
</head>
<body></body>
</html>
__
meta::bootstrap('initialization', <<'__');
#!/usr/bin/perl
# 99aeabc9ec7fe80b1b39f5e53dc7e49e <- self-modifying Perl magic
# state: __state
# istate: __istate
# id: __id
# This is a self-modifying Perl file. I'm sorry you're viewing the source (it's
# really gnarly). If you're curious what it's made of, I recommend reading
# https://github.com/spencertipping/writing-self-modifying-perl.
#
# If you got one of these from someone and don't know what to do with it, send
# it to spencer@spencertipping.com and I'll see if I can figure out what it
# does.
# For the benefit of HTML viewers (this is a hack):
# <div id='cover' style='position: absolute; left: 0; top: 0; width: 10000px; height: 10000px; background: white'></div>
$|++;
my %data;
my %transient;
my %externalized_functions;
my %datatypes;
my %locations; # Maps eval-numbers to attribute names
my $global_data = join '', <DATA>;
sub meta::define_form {
my ($namespace, $delegate) = @_;
$datatypes{$namespace} = $delegate;
*{"meta::${namespace}::implementation"} = $delegate;
*{"meta::$namespace"} = sub {
my ($name, $value, %options) = @_;
chomp $value;
$data{"${namespace}::$name"} = $value unless $options{no_binding};
&$delegate($name, $value) unless $options{no_delegate}}}
sub meta::eval_in {
my ($what, $where) = @_;
# Obtain next eval-number and alias it to the designated location
@locations{eval('__FILE__') =~ /\(eval (\d+)\)/} = ($where);
my $result = eval $what;
$@ =~ s/\(eval \d+\)/$where/ if $@;
warn $@ if $@;
$result}
meta::define_form 'meta', sub {
my ($name, $value) = @_;
meta::eval_in($value, "meta::$name")};
__
meta::bootstrap('perldoc', <<'__');
=head1 Self-modifying Perl script
=head2 Original implementation by Spencer Tipping L<http://spencertipping.com>
The prototype for this script is licensed under the terms of the MIT source code license.
However, this script in particular may be under different licensing terms. To find out how
this script is licensed, please contact whoever sent it to you. Alternatively, you may
run it with the 'license' argument if they have specified a license that way.
You should not edit this file directly. For information about how it was constructed, go
to L<http://spencertipping.com/writing-self-modifying-perl>. For quick usage guidelines,
run this script with the 'usage' argument.
=cut
__
meta::cache('parent-identification', <<'__');
object 99aeabc9ec7fe80b1b39f5e53dc7e49e
vim-highlighters 902333a0bd6ed90ff919fe8477cb4e69
__
meta::cache('parent-state', <<'__');
902333a0bd6ed90ff919fe8477cb4e69 8d4ebdc5d3e901edca2bec5d546d6f7f
99aeabc9ec7fe80b1b39f5e53dc7e49e 13d3013b77dc0268499bab45dad28870
__
meta::data('author', <<'__');
Spencer Tipping <spencer@spencertipping.com>
__
meta::data('default-action', 'shell');
meta::data('license', <<'__');
MIT License
Copyright (c) 2010 Spencer Tipping
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
__
meta::data('permanent-identity', '93194ecf50e38f2adb6e273909e007b5');
meta::function('ad', <<'__');
my ($options, @paths) = separate_options(@_);
@{$transient{path}} = () if $$options{-c};
return @{$transient{path}} = () unless @paths;
push @{$transient{path}}, @paths;
__
meta::function('alias', <<'__');
my ($name, @stuff) = @_;
@_ ? @stuff ? around_hook('alias', @_, sub {associate("alias::$name", join(' ', @stuff), execute => 1)})
: retrieve("alias::$name") // "Undefined alias $name"
: table_display([select_keys('--namespace' => 'alias')], [map retrieve($_), select_keys('--namespace' => 'alias')]);
__
meta::function('cat', 'join "\\n", retrieve(@_);');
meta::function('cc', <<'__');
# Stashes a quick one-line continuation. (Used to remind me what I was doing.)
@_ ? associate('data::current-continuation', hook('set-cc', join(' ', @_))) : retrieve('data::current-continuation');
__
meta::function('ccc', 'rm(\'data::current-continuation\');');
meta::function('child', <<'__');
around_hook('child', @_, sub {
my ($child_name) = @_;
clone($child_name);
enable();
qx($child_name update-from $0);
terminal::info("$child_name\'s identity is " . join '', qx($child_name identity));
disable()});
__
meta::function('clone', <<'__');
my ($options, @files) = separate_options(@_);
for my $file (@files) {
around_hook('clone', $file, sub {
hypothetically(sub {
# Assign a new object identity.
rm('data::permanent-identity');
identity();
file::write($file, serialize(), noclobber => 1);
chmod(0700, $file)})})}
__
meta::function('compile-binary', <<'__');
# Compiles binary-text to binary output. The binary-text is tokenized and then
# compiled, where each token is one of the following:
#
# Literal:
# /[0-9a-f]{2}/ <- single byte in hex
# /o[0-3][0-7]{2}/ <- single byte in octal
# /-[01]{8}/ <- single byte in binary
# /'\S+/ <- bytes in ASCII
#
# Placement (low-level):
# /@![0-9a-f]+/ <- place assertion (die unless next byte is at place)
# /@[0-9a-f]+/ <- place seek (emit null bytes until next byte is place)
# /@\?(\w\+)/ <- debugging: print $1 followed by its location
# /@:[0-9a-f]+/ <- alignment: emit \0 until next byte is multiple of n
#
# Repetition:
# /\/(\d+)\// <- repeat next byte $1 times
#
# Assembler:
# /::([^' ]\+)/ <- create label $1 pointing to next byte offset
# /:\d*\[([^\]]+)\]/ <- insert bytes resulting from expression evaluation
#
# The assembler gives you a language you can use to evaluate expressions. It's
# ultimately a preprocessor transform to Perl; that is, a few string
# substitutions are made and then Perl evaluates the result, dropping that into
# the generated image. The assembler dies unless the expression's byte size
# matches the number before the open bracket. Here are the preprocessor
# transformations:
#
# s/:</$o/g <- offset at beginning of expression
# s/:>/($o + $e{size})/g <- offset at end of expression
# s/::?([^' ]+)/$places{'$1'}/g <- label references
# s/L(\d)?(.*)/&$le($1, $2)/g <- little-endian integer encoding
# s/B(\d)?(.*)/&$be($1, $2)/g <- big-endian integer encoding
#
# Little-endian and big-endian encoders take a numeric argument indicating how
# many bytes should be encoded. This number is limited only by Perl's numerical
# precision, and by the fact that you have only one digit to specify it. Results
# are sign-extended to the requested byte width. An error occurs if the value
# produces a signed overflow given its width.
#
# You can use 0 width to evaluate an expression with no output; that is, some
# form of side-effect. In this case, the bracketed expression's value is ignored
# and no length check occurs. A shorthand for this case is :[...].
#
# Note that all expressions are evaluated after the basic image has been
# generated. This allows you to use forward references to labels.
my ($options, @stuff) = separate_options(@_);
my $text = join ' ', map split(/\s+/), split /(?:\s|^)#.*/m, cat(@stuff);
my $hex_letters = '0123456789abcdef';
my %places;
my %expressions;
my @output;
my $offset = 0;
my $next = 1;
my $repeat = sub {$next = $_[0]; ''}; # Repeaters have no output
my $repetition = sub {my $count = $next; $next = 1; $count};
my $ascii = sub {$_[0]};
my $binary = sub {my $total = 0; $total = ($total << 1) + substr($_[0], $_, 1) for 0 .. 7; chr($total) x &$repetition()};
my $octal = sub {my $total = 0; $total = ($total << 3) + index($hex_letters, substr($_[0], $_, 1)) for 0 .. 2; chr($total) x &$repetition()};
my $hex = sub {my $total = 0; $total = ($total << 4) + index($hex_letters, lc substr($_[0], $_, 1)) for 0 .. 1; chr($total) x &$repetition()};
my $until = sub {my $address = hex $_[0]; "\0" x ($address - $offset)};
my $align = sub {my $width = hex $_[0]; "\0" x (($width - $offset % $width) % $width)};
my $debug = sub {printf STDERR "%s: 0x%x\n", $_[0], $offset; ''};
my $place = sub {die sprintf "incorrect address at place %x (actual is %x)", hex $_[0], $offset unless $offset == hex $_[0]; ''};
my $label = sub {die sprintf "label %s is defined twice" if exists $places{$_[0]}; $places{$_[0]} = $offset; ''};
my $expression = sub {push @{$expressions{$offset} ||= []}, {size => $_[0], e => $_[1]}; 'E' x $_[0]};
my $emit = sub {my ($s) = @_; $offset += length $s; push @output, $s};
my @tokens = split m#('\S+ | -[01]{8} | o[0-3][0-7]{2} | [0-9a-f]{2} | \@\?\S+ |
/\d+/ | ::\S+ | :\d*\[[^\]]+\] | \@[!:]?[0-9a-f]+)#x, $text;
&$emit(/^'(\S+)/ ? &$ascii($1) : /^\@\?(\S+)/ ? &$debug($1) :
/^-([01]{8})/ ? &$binary($1) : /^o([0-3][0-7]{2})/ ? &$octal($1) :
/^@!([0-9a-f]+)/ ? &$place($1) : /^\@([0-9a-f]+)/ ? &$until($1) :
/^\@:([0-9a-f]+)/ ? &$align($1) :
/^\/(\d+)\// ? &$repeat($1) : /^[0-9a-f]{2}/ ? &$hex($_) :
/^::(\S+)/ ? &$label($1) :
/^:(\d*)\[([^\]]+)\]/ ? &$expression($1, $2) : '') for @tokens;
# Now go through and evaluate every expression. Right now the spaces for the
# results contain repetitions of the byte 'E'.
my $concatenated = join '', @output;
my $check_overflow = sub {
my ($upper, $lower) = ((1 << $_[0] * 8 - 1) - 1, -(1 << $_[0] * 8 - 1));
die "$_[1] signed-overflows $_[0] bytes ($lower, $upper)"
unless $_[1] <= $upper and $_[1] >= $lower;
@_};
my $le = sub {join '', map chr($_[1] >> $_ * 8 & 255), 0 .. $_[0] - 1};
my $be = sub {join '', map chr($_[1] >> $_ * 8 & 255), reverse 0 .. $_[0] - 1};
for my $o (sort {$a <=> $b} keys %expressions) {
for my $e (@{$expressions{$o}}) {
my $expression = $$e{e};
my $size = $$e{size};
$_ = $expression;
s/:</$o/g, s/:>/($o + $size)/g;
# :: is unchecked, : is checked
s/::([^' ]+)/\$places{'$1'}/g;
s-:([^' ]+)-(\$places{'$1'} // die '$1 is not a defined label')-g;
s/L([1-9])?(.+)/&\$le(&\$check_overflow(($1) || $size, $2))/g;
s/B([1-9])?(.+)/&\$be(&\$check_overflow(($1) || $size, $2))/g;
my $result = eval;
die "error evaluating $_ as $expression: $@" if $@;
if ($size) {
die "result of $_ as $expression is " . length($result) .
" bytes; expected $size"
if length($result) != $size;
substr($concatenated, $o, $size) = $result;
}
}
}
# Bwoop bwoop bwoop egregious hack alert
$transient{compile_binary_places} = \%places if $$options{'--save-places'};
$concatenated;
__
meta::function('cp', <<'__');
my $from = shift @_;
my $value = retrieve($from);
associate($_, $value) for @_;
__
meta::function('create', <<'__');
my ($name, $value) = @_;
around_hook('create', $name, $value, sub {
return edit($name) if exists $data{$name};
associate($name, defined $value ? $value : '');
edit($name) unless defined $value});
__
meta::function('current-state', 'serialize(\'-pS\');');
meta::function('cwd', <<'__');
use Cwd qw/getcwd/;
getcwd();
__
meta::function('disable', 'hook(\'disable\', chmod_self(sub {$_[0] & 0666}));');
meta::function('edit', <<'__');
my ($options, @names) = separate_options(@_);
@names = select_keys('--criteria' => "^$$options{'--prefix'}.*" . join('.*', @names), %$options) if $$options{'--prefix'};
my ($name, @others) = @names;
die "cannot edit multiple attributes simultaneously (others are @others)" if @others;
die "$name is virtual or does not exist" unless exists $data{$name};
die "$name is inherited; use 'edit $name -f' to edit anyway" unless is($name, '-u') || is($name, '-d') || exists $$options{'-f'};
my $extension = extension_for($name);
around_hook('edit', @_, sub {
associate($name, invoke_editor_on($data{$name} // '', %$options, attribute => $name, extension => $extension), execute => 1)});
save() unless $data{'data::edit::no-save'} or state() eq $transient{initial};
'';
__
meta::function('edit-self', <<'__');
$global_data = invoke_editor_on($global_data);
save();
__
meta::function('enable', 'hook(\'enable\', chmod_self(sub {$_[0] | $_[0] >> 2}));');
meta::function('expanded-bootstrap', <<'__');
# Write headers into the bootstrap section. There is some subtle stuff going on
# here with the istate header. The idea is to provide other objects a very quick
# way to see whether our state has changed, but we don't want false positives.
# We would get a false positive if, for instance, we included the contents of
# parent:: attributes in the istate hash. The reason is that the parent::
# attribute contains a hash of every attribute provided by that parent, so any
# change in the parent would impact the istate of the child.
#
# The best way to deal with this is to treat parent:: attributes as being
# opaque; we record their existence or nonexistence, but we don't record their
# contents. We also look only at inheritable and unique attributes and fail to
# consider global state.
my $bootstrap_text = retrieve('bootstrap::initialization');
my $state = state();
my $istate = state('-iGP');
my $object_id = identity();
$bootstrap_text =~ s/__state/$state/g;
$bootstrap_text =~ s/__istate/$istate/g;
$bootstrap_text =~ s/__id/$object_id/g;
$bootstrap_text;
__
meta::function('export', <<'__');
# Exports data into a text file.
# export attr1 attr2 attr3 ... file.txt
my $name = pop @_;
@_ or die 'Expected filename';
file::write($name, join "\n", retrieve(@_));
__
meta::function('extern', '&{$_[0]}(retrieve(@_[1 .. $#_]));');
meta::function('grep', <<'__');
# Looks through attributes for a pattern. Usage is grep pattern [options], where
# [options] is the format as provided to select_keys.
my ($pattern, @args) = @_;
my ($options, @criteria) = separate_options(@args);
my @attributes = select_keys(%$options, '--criteria' => join('|', @criteria));
$pattern = qr/$pattern/;
my @m_attributes;
my @m_line_numbers;
my @m_lines;
for my $k (@attributes) {
next unless length $k;
my @lines = split /\n/, retrieve($k);
for (0 .. $#lines) {
next unless $lines[$_] =~ $pattern;
push @m_attributes, $k;
push @m_line_numbers, $_ + 1;
push @m_lines, '' . ($lines[$_] // '')}}
unless ($$options{'-C'}) {
s/($pattern)/\033[1;31m\1\033[0;0m/g for @m_lines;
s/^/\033[1;34m/o for @m_attributes;
s/^/\033[1;32m/o && s/$/\033[0;0m/o for @m_line_numbers}
table_display([@m_attributes], [@m_line_numbers], [@m_lines]);
__
meta::function('hash', 'fast_hash(@_);');
meta::function('hook', <<'__');
my ($hook, @args) = @_;
$transient{active_hooks}{$hook} = 1;
dangerous('', sub {&$_(@args)}) for grep /^hook::${hook}::/, sort keys %data;
@args;
__
meta::function('hooks', 'join "\\n", sort keys %{$transient{active_hooks}};');
meta::function('identity', <<'__');
retrieve('data::permanent-identity') or
associate('data::permanent-identity', fast_hash(join '|', map rand(), 1 .. 32));
__
meta::function('import', <<'__');
my $name = pop @_;
associate($name, @_ ? join('', map(file::read($_), @_)) : join('', <STDIN>));
__
meta::function('initial-state', '$transient{initial};');
meta::function('is', <<'__');
my ($attribute, @criteria) = @_;
my ($options, @stuff) = separate_options(@criteria);
exists $data{$attribute} and attribute_is($attribute, %$options);
__
meta::function('load-state', <<'__');
around_hook('load-state', @_, sub {
my ($state_name) = @_;
my $state = retrieve("state::$state_name");
terminal::state('saving current state into _...');
save_state('_');
delete $data{$_} for grep ! /^state::/, keys %data;
%externalized_functions = ();
terminal::state("restoring state $state_name...");
meta::eval_in($state, "state::$state_name");
terminal::error(hook('load-state-failed', $@)) if $@;
reload();
verify()});
__
meta::function('lock', 'hook(\'lock\', chmod_self(sub {$_[0] & 0555}));');
meta::function('ls', <<'__');
my ($options, @criteria) = separate_options(@_);
my ($external, $shadows, $sizes, $flags, $long, $hashes, $parent_hashes) = @$options{qw(-e -s -z -f -l -h -p)};
$sizes = $flags = $hashes = $parent_hashes = 1 if $long;
return table_display([grep ! exists $data{$externalized_functions{$_}}, sort keys %externalized_functions]) if $shadows;
my $criteria = join('|', @criteria);
my @definitions = select_keys('--criteria' => $criteria, '--path' => $transient{path}, %$options);
my %inverses = map {$externalized_functions{$_} => $_} keys %externalized_functions;
my @externals = map $inverses{$_}, grep length, @definitions;
my @internals = grep length $inverses{$_}, @definitions;
my @sizes = map sprintf('%6d %6d', length(serialize_single($_)), length(retrieve($_))), @{$external ? \@internals : \@definitions} if $sizes;
my @flags = map {my $k = $_; join '', map(is($k, "-$_") ? $_ : '-', qw(d i m u))} @definitions if $flags;
my @hashes = map fast_hash(retrieve($_)), @definitions if $hashes;
my %inherited = parent_attributes(grep /^parent::/o, keys %data) if $parent_hashes;
my @parent_hashes = map $inherited{$_} || '-', @definitions if $parent_hashes;
join "\n", map strip($_), split /\n/, table_display($external ? [grep length, @externals] : [@definitions],
$sizes ? ([@sizes]) : (), $flags ? ([@flags]) : (), $hashes ? ([@hashes]) : (), $parent_hashes ? ([@parent_hashes]) : ());
__
meta::function('metadata-from', <<'__');
my ($filename) = @_;
my %metadata;
# Not using file::read because we only need the first few lines.
open my($fh), '<', $filename or return {};
while (<$fh>) {
/^#\s*(\w+):\s*(.*)$/ and $metadata{$1} = $2;
last unless /^#/;
}
close $fh;
\%metadata;
__
meta::function('mv', <<'__');
my ($from, $to) = @_;
die "'$from' does not exist" unless exists $data{$from};
associate($to, retrieve($from), execute => 1);
rm($from);
__
meta::function('name', <<'__');
my $name = $0;
$name =~ s/^.*\///;
$name;
__
meta::function('parents', 'join "\\n", grep s/^parent:://o, sort keys %data;');
meta::function('perl', <<'__');
my @result = eval(join ' ', @_);
$@ ? terminal::error($@) : wantarray ? @result : $result[0];
__
meta::function('rd', <<'__');
if (@_) {my $pattern = join '|', @_;
@{$transient{path}} = grep $_ !~ /^$pattern$/, @{$transient{path}}}
else {pop @{$transient{path}}}
__
meta::function('reload', 'around_hook(\'reload\', sub {execute($_) for grep ! /^bootstrap::/, keys %data});');
meta::function('rm', <<'__');
around_hook('rm', @_, sub {
exists $data{$_} or terminal::warning("$_ does not exist") for @_;
delete @data{@_}});
__
meta::function('rmparent', <<'__');
# Removes one or more parents.
my ($options, @parents) = separate_options(@_);
my $clobber_divergent = $$options{'-D'} || $$options{'--clobber-divergent'};
my %parents = map {$_ => 1} @parents;
my @other_parents = grep !$parents{$_}, grep s/^parent:://, select_keys('--namespace' => 'parent');
my %kept_by_another_parent;
$kept_by_another_parent{$_} = 1 for grep s/^(\S+)\s.*$/\1/, split /\n/o, cat(@other_parents);
for my $parent (@parents) {
my $keep_parent_around = 0;
for my $line (split /\n/, retrieve("parent::$parent")) {
my ($name, $hash) = split /\s+/, $line;
next unless exists $data{$name};
my $local_hash = fast_hash(retrieve($name));
if ($clobber_divergent or $hash eq $local_hash or ! defined $hash) {rm($name) unless $kept_by_another_parent{$name}}
else {terminal::info("local attribute $name exists and is divergent; use rmparent -D $parent to delete it");
$keep_parent_around = 1}}
$keep_parent_around ? terminal::info("not deleting parent::$parent so that you can run", "rmparent -D $parent if you want to nuke divergent attributes too")
: rm("parent::$parent")}
__
meta::function('save', 'around_hook(\'save\', sub {dangerous(\'\', sub {file::write($0, serialize(\'-V\')); $transient{initial} = state()}) if verify()});');
meta::function('save-state', <<'__');
# Creates a named copy of the current state and stores it.
my ($state_name) = @_;
around_hook('save-state', $state_name, sub {
associate("state::$state_name", current_state(), execute => 1)});
__
meta::function('serialize', <<'__');
my ($options, @criteria) = separate_options(@_);
delete $$options{'-P'};
my $partial = delete $$options{'-p'};
my $criteria = join '|', @criteria;
my @attributes = map serialize_single($_), select_keys(%$options, '-m' => 1, '--criteria' => $criteria), select_keys(%$options, '-M' => 1, '--criteria' => $criteria);
my @final_array = @{$partial ? \@attributes : [expanded_bootstrap(), @attributes, 'internal::main();', '', '__DATA__', $global_data]};
join "\n", @final_array;
__
meta::function('serialize-single', <<'__');
# Serializes a single attribute and optimizes for content.
my $name = $_[0] || $_;
my $contents = retrieve_trimmed($name);
my $meta_function = 'meta::' . namespace($name);
my $invocation = attribute($name);
if ($contents !~ /\v/) {
$contents =~ s/\\/\\\\/go;
$contents =~ s/'/\\'/go;
return "$meta_function('$invocation', '$contents');"}
my $delimiter = '__' . fast_hash($contents);
my $chars = 2;
++$chars until $chars >= length($delimiter) || index("\n$contents", "\n" . substr($delimiter, 0, $chars)) == -1;
$delimiter = substr($delimiter, 0, $chars);
"$meta_function('$invocation', <<'$delimiter');\n$contents\n$delimiter";
__
meta::function('sh', <<'__');
around_hook('sh', @_, sub {
system(@_)});
__
meta::function('shb', <<'__');
# Backgrounded shell.
with_fork(@_, \&::sh);
__
meta::function('shell', <<'__');
my ($options, @arguments) = separate_options(@_);
$transient{repl_prefix} = $$options{'--repl-prefix'};
terminal::cc(retrieve('data::current-continuation')) if length $data{'data::current-continuation'};
around_hook('shell', sub {shell::repl(%$options)});
__
meta::function('size', <<'__');
my $size = 0;
$size += length $data{$_} for keys %data;
sprintf " full logical unique self\n% 7d % 7d % 7d % 7d", length(serialize()), $size, length(serialize('-up')), length $global_data;
__
meta::function('snapshot', <<'__');
my ($name) = @_;
file::write(my $finalname = temporary_name($name), serialize(), noclobber => 1);
chmod 0700, $finalname;
hook('snapshot', $finalname);
__
meta::function('snapshot-if-necessary', 'snapshot() if state() ne $transient{initial};');
meta::function('state', <<'__');
my ($options, @attributes) = separate_options(@_);
@attributes = grep !is($_, '-v'), sort keys %data unless @attributes;
@attributes = grep is($_, '-iu'), @attributes if $$options{'-i'};
@attributes = grep is($_, '-P'), @attributes if $$options{'-P'};
my $hash = fast_hash(fast_hash(scalar @attributes) . join '|', @attributes);
$hash = fast_hash(retrieve_trimmed($_) . "|$hash") for @attributes;
$hash = fast_hash(join '|', $hash, grep s/^parent:://, sort keys %data)
if $$options{'-P'};
$$options{'-G'} ? $hash : fast_hash("$global_data|$hash");
__
meta::function('touch', 'associate($_, \'\') for @_;');
meta::function('unlock', 'hook(\'unlock\', chmod_self(sub {$_[0] | 0200}));');
meta::function('update', 'update_from(@_, grep s/^parent:://o, sort keys %data);');
meta::function('update-from', <<'__');
# Upgrade all attributes that aren't customized. Customization is defined when the data type is created,
# and we determine it here by checking for $transient{inherit}{$type}.
# Note that this assumes you trust the remote script. If you don't, then you shouldn't update from it.
around_hook('update-from-invocation', separate_options(@_), sub {
my ($options, @targets) = @_;
my %parent_id_cache = cache('parent-identification');
my %parent_state_cache = cache('parent-state');
my %already_seen;
@targets or return;
my @known_targets = grep s/^parent:://, parent_ordering(map "parent::$_", grep exists $data{"parent::$_"}, @targets);
my @unknown_targets = grep ! exists $data{"parent::$_"}, @targets;
@targets = (@known_targets, @unknown_targets);
my $save_state = $$options{'-s'} || $$options{'--save'};
my $no_state = $$options{'-S'} || $$options{'--no-state'};
my $no_verify = $$options{'-V'} || $$options{'--no-verify'};
my $no_parents = $$options{'-P'} || $$options{'--no-parent'} || $$options{'--no-parents'};
my $force = $$options{'-f'} || $$options{'--force'};
my $clobber_divergent = $$options{'-D'} || $$options{'--clobber-divergent'};
my $can_skip_already_seen = !($$options{'-K'} || $$options{'--no-skip'}) &&
!$force && !$clobber_divergent;
save_state('before-update') unless $no_state;
for my $target (@targets) {
dangerous("updating from $target", sub {
around_hook('update-from', $target, sub {
my $target_filename = strip(qx(which $target)) || $target;
my %parent_metadata = %{metadata_from($target_filename)};
terminal::warning("$target_filename has no externally visible metadata (makes updating slower)") unless $parent_metadata{id};
my $identity = $parent_id_cache{$target} ||= $parent_metadata{id} || join '', qx($target identity);
next if $can_skip_already_seen and
exists $data{"parent::$target"} and
$already_seen{$identity} || $parent_state_cache{$identity} eq $parent_metadata{istate};
my $attributes = join '', qx($target ls -ahiu);
my %divergent;
die "skipping unreachable $target" unless $attributes;
# These need to come after the reachability check so that we retry against
# other copies in case something fails.
++$already_seen{$identity};
$parent_state_cache{$identity} = $parent_metadata{istate} || join '', qx($target state -iPG);
for my $to_rm (split /\n/, retrieve("parent::$target")) {
my ($name, $hash) = split(/\s+/, $to_rm);
next unless exists $data{$name};
my $local_hash = fast_hash(retrieve($name));
if ($clobber_divergent or $hash eq $local_hash or ! defined $hash) {rm($name)}
else {terminal::info("preserving local version of divergent attribute $name (use update -D to clobber it)");
$divergent{$name} = retrieve($name)}}
associate("parent::$target", $attributes) unless $no_parents;
dangerous('', sub {eval qx($target serialize -ipmu)});
dangerous('', sub {eval qx($target serialize -ipMu)});
map associate($_, $divergent{$_}), keys %divergent unless $clobber_divergent;
reload()})})}
cache('parent-identification', %parent_id_cache);
cache('parent-state', %parent_state_cache);
if ($no_verify) {hook('update-from-presumably-succeeded', $options, @targets);
rm('state::before-update') unless $no_state || $save_state}
elsif (verify()) {hook('update-from-succeeded', $options, @targets);
terminal::info("Successfully updated. Run 'load-state before-update' to undo this change.") if $save_state;
rm('state::before-update') unless $no_state || $save_state}
elsif ($force || $no_state) {hook('update-from-failed', $options, @targets);
terminal::warning('Failed to verify: at this point your object will not save properly, though backup copies will be created.',
$no_state ? 'You should attempt to repair this object since no prior state was saved.'
: 'Run "load-state before-update" to undo the update and return to a working state.')}
else {hook('update-from-failed', $options, @targets);
terminal::error('Verification failed after the upgrade was complete.');
terminal::info("$0 has been reverted to its pre-upgrade state.", "If you want to upgrade and keep the failure state, then run 'update-from $target --force'.");
load_state('before-update');
rm('state::before-update')}});
__
meta::function('usage', '"Usage: $0 action [arguments]\\nUnique actions (run \'$0 ls\' to see all actions):" . ls(\'-u\');');
meta::function('verify', <<'__');
file::write(my $other = $transient{temporary_filename} = temporary_name(), my $serialized_data = serialize());
chomp(my $observed = join '', qx|perl '$other' state|);
unlink $other if my $result = $observed eq (my $state = state());
terminal::error("Verification failed; expected $state but got $observed from $other") unless $result;
hook('after-verify', $result, observed => $observed, expected => $state);
$result;
__
meta::function('vim', <<'__');
# Installs VIM highlighters.
file::write("$ENV{'HOME'}/.vim/syntax/$_.vim", retrieve("vim_highlighter::$_")) for grep s/^vim_highlighter:://o, keys %data;
__
meta::indicator('cc', 'length ::retrieve(\'data::current-continuation\') ? "\\033[1;36mcc\\033[0;0m" : \'\';');
meta::indicator('locked', 'is_locked() ? "\\033[1;31mlocked\\033[0;0m" : \'\';');
meta::indicator('path', <<'__');
my @highlighted = map join("\033[1;30m|\033[0;0m", split /\|/, $_), @{$transient{path}};
join "\033[1;30m/\033[0;0m", @highlighted;
__
meta::internal_function('around_hook', <<'__');
# around_hook('hookname', @args, sub {
# stuff;
# });
# Invokes 'before-hookname' on @args before the sub runs, invokes the
# sub on @args, then invokes 'after-hookname' on @args afterwards.
# The after-hook is not invoked if the sub calls 'die' or otherwise
# unwinds the stack.
my $hook = shift @_;
my $f = pop @_;
hook("before-$hook", @_);
my @result = &$f(@_);
hook("after-$hook", @_, @result);
wantarray ? @result : $result[0];
__
meta::internal_function('associate', <<'__');
my ($name, $value, %options) = @_;
die "Namespace does not exist" unless exists $datatypes{namespace($name)};
$data{$name} = $value;
execute($name) if $options{execute};
$value;
__
meta::internal_function('attribute', <<'__');
my ($name) = @_;
$name =~ s/^[^:]*:://;
$name;
__
meta::internal_function('attribute_is', <<'__');
my ($a, %options) = @_;
my %inherited = parent_attributes(grep /^parent::/o, sort keys %data) if grep exists $options{$_}, qw/-u -U -d -D/;
my $criteria = $options{'--criteria'} || $options{'--namespace'} && "^$options{'--namespace'}::" || '.';
my %tests = ('-u' => sub {! $inherited{$a}},
'-d' => sub {$inherited{$a} && fast_hash(retrieve($a)) ne $inherited{$a}},
'-i' => sub {$transient{inherit}{namespace($a)}},
'-v' => sub {$transient{virtual}{namespace($a)}},
'-p' => sub {$a =~ /^parent::/o},
'-s' => sub {$a =~ /^state::/o},
'-m' => sub {$a =~ /^meta::/o});
return 0 unless scalar keys %tests == scalar grep ! exists $options{$_} || &{$tests{$_}}(), keys %tests;
return 0 unless scalar keys %tests == scalar grep ! exists $options{uc $_} || ! &{$tests{$_}}(), keys %tests;
$a =~ /$_/ || return 0 for @{$options{'--path'}};
$a =~ /$criteria/;
__
meta::internal_function('cache', <<'__');
my ($name, %pairs) = @_;
if (%pairs) {associate("cache::$name", join "\n", map {$pairs{$_} =~ s/\n//g; "$_ $pairs{$_}"} sort keys %pairs)}
else {map split(/\s/, $_, 2), split /\n/, retrieve("cache::$name")}
__
meta::internal_function('chmod_self', <<'__');
my ($mode_function) = @_;
my (undef, undef, $mode) = stat $0;
chmod &$mode_function($mode), $0;
__
meta::internal_function('dangerous', <<'__');
# Wraps a computation that may produce an error.