xref: /openbsd/gnu/usr.bin/perl/pod/perlfilter.pod (revision e0680481)
1=head1 NAME
2
3perlfilter - Source Filters
4
5=head1 DESCRIPTION
6
7This article is about a little-known feature of Perl called
8I<source filters>. Source filters alter the program text of a module
9before Perl sees it, much as a C preprocessor alters the source text of
10a C program before the compiler sees it. This article tells you more
11about what source filters are, how they work, and how to write your
12own.
13
14The original purpose of source filters was to let you encrypt your
15program source to prevent casual reading. This isn't all they can do, as
16you'll soon learn. But first, the basics.
17
18=head1 CONCEPTS
19
20Before the Perl interpreter can execute a Perl script, it must first
21read it from a file into memory for parsing and compilation. If that
22script itself includes other scripts with a C<use> or C<require>
23statement, then each of those scripts will have to be read from their
24respective files as well.
25
26Now think of each logical connection between the Perl parser and an
27individual file as a I<source stream>. A source stream is created when
28the Perl parser opens a file, it continues to exist as the source code
29is read into memory, and it is destroyed when Perl is finished parsing
30the file. If the parser encounters a C<require> or C<use> statement in
31a source stream, a new and distinct stream is created just for that
32file.
33
34The diagram below represents a single source stream, with the flow of
35source from a Perl script file on the left into the Perl parser on the
36right. This is how Perl normally operates.
37
38    file -------> parser
39
40There are two important points to remember:
41
42=over 5
43
44=item 1.
45
46Although there can be any number of source streams in existence at any
47given time, only one will be active.
48
49=item 2.
50
51Every source stream is associated with only one file.
52
53=back
54
55A source filter is a special kind of Perl module that intercepts and
56modifies a source stream before it reaches the parser. A source filter
57changes our diagram like this:
58
59    file ----> filter ----> parser
60
61If that doesn't make much sense, consider the analogy of a command
62pipeline. Say you have a shell script stored in the compressed file
63I<trial.gz>. The simple pipeline command below runs the script without
64needing to create a temporary file to hold the uncompressed file.
65
66    gunzip -c trial.gz | sh
67
68In this case, the data flow from the pipeline can be represented as follows:
69
70    trial.gz ----> gunzip ----> sh
71
72With source filters, you can store the text of your script compressed and use a source filter to uncompress it for Perl's parser:
73
74     compressed           gunzip
75    Perl program ---> source filter ---> parser
76
77=head1 USING FILTERS
78
79So how do you use a source filter in a Perl script? Above, I said that
80a source filter is just a special kind of module. Like all Perl
81modules, a source filter is invoked with a use statement.
82
83Say you want to pass your Perl source through the C preprocessor before
84execution. As it happens, the source filters distribution comes with a C
85preprocessor filter module called Filter::cpp.
86
87Below is an example program, C<cpp_test>, which makes use of this filter.
88Line numbers have been added to allow specific lines to be referenced
89easily.
90
91    1: use Filter::cpp;
92    2: #define TRUE 1
93    3: $a = TRUE;
94    4: print "a = $a\n";
95
96When you execute this script, Perl creates a source stream for the
97file. Before the parser processes any of the lines from the file, the
98source stream looks like this:
99
100    cpp_test ---------> parser
101
102Line 1, C<use Filter::cpp>, includes and installs the C<cpp> filter
103module. All source filters work this way. The use statement is compiled
104and executed at compile time, before any more of the file is read, and
105it attaches the cpp filter to the source stream behind the scenes. Now
106the data flow looks like this:
107
108    cpp_test ----> cpp filter ----> parser
109
110As the parser reads the second and subsequent lines from the source
111stream, it feeds those lines through the C<cpp> source filter before
112processing them. The C<cpp> filter simply passes each line through the
113real C preprocessor. The output from the C preprocessor is then
114inserted back into the source stream by the filter.
115
116                  .-> cpp --.
117                  |         |
118                  |         |
119                  |       <-'
120   cpp_test ----> cpp filter ----> parser
121
122The parser then sees the following code:
123
124    use Filter::cpp;
125    $a = 1;
126    print "a = $a\n";
127
128Let's consider what happens when the filtered code includes another
129module with use:
130
131    1: use Filter::cpp;
132    2: #define TRUE 1
133    3: use Fred;
134    4: $a = TRUE;
135    5: print "a = $a\n";
136
137The C<cpp> filter does not apply to the text of the Fred module, only
138to the text of the file that used it (C<cpp_test>). Although the use
139statement on line 3 will pass through the cpp filter, the module that
140gets included (C<Fred>) will not. The source streams look like this
141after line 3 has been parsed and before line 4 is parsed:
142
143    cpp_test ---> cpp filter ---> parser (INACTIVE)
144
145    Fred.pm ----> parser
146
147As you can see, a new stream has been created for reading the source
148from C<Fred.pm>. This stream will remain active until all of C<Fred.pm>
149has been parsed. The source stream for C<cpp_test> will still exist,
150but is inactive. Once the parser has finished reading Fred.pm, the
151source stream associated with it will be destroyed. The source stream
152for C<cpp_test> then becomes active again and the parser reads line 4
153and subsequent lines from C<cpp_test>.
154
155You can use more than one source filter on a single file. Similarly,
156you can reuse the same filter in as many files as you like.
157
158For example, if you have a uuencoded and compressed source file, it is
159possible to stack a uudecode filter and an uncompression filter like
160this:
161
162    use Filter::uudecode; use Filter::uncompress;
163    M'XL(".H<US4''V9I;F%L')Q;>7/;1I;_>_I3=&E=%:F*I"T?22Q/
164    M6]9*<IQCO*XFT"0[PL%%'Y+IG?WN^ZYN-$'J.[.JE$,20/?K=_[>
165    ...
166
167Once the first line has been processed, the flow will look like this:
168
169    file ---> uudecode ---> uncompress ---> parser
170               filter         filter
171
172Data flows through filters in the same order they appear in the source
173file. The uudecode filter appeared before the uncompress filter, so the
174source file will be uudecoded before it's uncompressed.
175
176=head1 WRITING A SOURCE FILTER
177
178There are three ways to write your own source filter. You can write it
179in C, use an external program as a filter, or write the filter in Perl.
180I won't cover the first two in any great detail, so I'll get them out
181of the way first. Writing the filter in Perl is most convenient, so
182I'll devote the most space to it.
183
184=head1 WRITING A SOURCE FILTER IN C
185
186The first of the three available techniques is to write the filter
187completely in C. The external module you create interfaces directly
188with the source filter hooks provided by Perl.
189
190The advantage of this technique is that you have complete control over
191the implementation of your filter. The big disadvantage is the
192increased complexity required to write the filter - not only do you
193need to understand the source filter hooks, but you also need a
194reasonable knowledge of Perl guts. One of the few times it is worth
195going to this trouble is when writing a source scrambler. The
196C<decrypt> filter (which unscrambles the source before Perl parses it)
197included with the source filter distribution is an example of a C
198source filter (see Decryption Filters, below).
199
200
201=over 5
202
203=item B<Decryption Filters>
204
205All decryption filters work on the principle of "security through
206obscurity." Regardless of how well you write a decryption filter and
207how strong your encryption algorithm is, anyone determined enough can
208retrieve the original source code. The reason is quite simple:
209in order to execute your program Perl must parse its source code.
210This means that Perl must have all the information needed to decrypt
211your program, and that means that that information is also available to
212anyone able to run the program.
213
214That said, there are a number of steps that can be taken to make life
215difficult for the potential reader. The most important: Write your
216decryption filter in C and statically link the decryption module into
217the Perl binary. For further tips to make life difficult for the
218potential reader, see the file I<decrypt.pm> in the source filters
219distribution.
220
221=back
222
223=head1 CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE
224
225An alternative to writing the filter in C is to create a separate
226executable in the language of your choice. The separate executable
227reads from standard input, does whatever processing is necessary, and
228writes the filtered data to standard output. C<Filter::cpp> is an
229example of a source filter implemented as a separate executable - the
230executable is the C preprocessor bundled with your C compiler.
231
232The source filter distribution includes two modules that simplify this
233task: C<Filter::exec> and C<Filter::sh>. Both allow you to run any
234external executable. Both use a coprocess to control the flow of data
235into and out of the external executable. (For details on coprocesses,
236see Stephens, W.R., "Advanced Programming in the UNIX Environment."
237Addison-Wesley, ISBN 0-210-56317-7, pages 441-445.) The difference
238between them is that C<Filter::exec> spawns the external command
239directly, while C<Filter::sh> spawns a shell to execute the external
240command. (Unix uses the Bourne shell; NT uses the cmd shell.) Spawning
241a shell allows you to make use of the shell metacharacters and
242redirection facilities.
243
244Here is an example script that uses C<Filter::sh>:
245
246    use Filter::sh 'tr XYZ PQR';
247    $a = 1;
248    print "XYZ a = $a\n";
249
250The output you'll get when the script is executed:
251
252    PQR a = 1
253
254Writing a source filter as a separate executable works fine, but a
255small performance penalty is incurred. For example, if you execute the
256small example above, a separate subprocess will be created to run the
257Unix C<tr> command. Each use of the filter requires its own subprocess.
258If creating subprocesses is expensive on your system, you might want to
259consider one of the other options for creating source filters.
260
261=head1 WRITING A SOURCE FILTER IN PERL
262
263The easiest and most portable option available for creating your own
264source filter is to write it completely in Perl. To distinguish this
265from the previous two techniques, I'll call it a Perl source filter.
266
267To help understand how to write a Perl source filter we need an example
268to study. Here is a complete source filter that performs rot13
269decoding. (Rot13 is a very simple encryption scheme used in Usenet
270postings to hide the contents of offensive posts. It moves every letter
271forward thirteen places, so that A becomes N, B becomes O, and Z
272becomes M.)
273
274
275   package Rot13;
276
277   use Filter::Util::Call;
278
279   sub import {
280      my ($type) = @_;
281      my ($ref) = [];
282      filter_add(bless $ref);
283   }
284
285   sub filter {
286      my ($self) = @_;
287      my ($status);
288
289      tr/n-za-mN-ZA-M/a-zA-Z/
290         if ($status = filter_read()) > 0;
291      $status;
292   }
293
294   1;
295
296=for apidoc filter_add
297=for apidoc filter_read
298
299All Perl source filters are implemented as Perl classes and have the
300same basic structure as the example above.
301
302First, we include the C<Filter::Util::Call> module, which exports a
303number of functions into your filter's namespace. The filter shown
304above uses two of these functions, C<filter_add()> and
305C<filter_read()>.
306
307Next, we create the filter object and associate it with the source
308stream by defining the C<import> function. If you know Perl well
309enough, you know that C<import> is called automatically every time a
310module is included with a use statement. This makes C<import> the ideal
311place to both create and install a filter object.
312
313In the example filter, the object (C<$ref>) is blessed just like any
314other Perl object. Our example uses an anonymous array, but this isn't
315a requirement. Because this example doesn't need to store any context
316information, we could have used a scalar or hash reference just as
317well. The next section demonstrates context data.
318
319The association between the filter object and the source stream is made
320with the C<filter_add()> function. This takes a filter object as a
321parameter (C<$ref> in this case) and installs it in the source stream.
322
323Finally, there is the code that actually does the filtering. For this
324type of Perl source filter, all the filtering is done in a method
325called C<filter()>. (It is also possible to write a Perl source filter
326using a closure. See the C<Filter::Util::Call> manual page for more
327details.) It's called every time the Perl parser needs another line of
328source to process. The C<filter()> method, in turn, reads lines from
329the source stream using the C<filter_read()> function.
330
331If a line was available from the source stream, C<filter_read()>
332returns a status value greater than zero and appends the line to C<$_>.
333A status value of zero indicates end-of-file, less than zero means an
334error. The filter function itself is expected to return its status in
335the same way, and put the filtered line it wants written to the source
336stream in C<$_>. The use of C<$_> accounts for the brevity of most Perl
337source filters.
338
339In order to make use of the rot13 filter we need some way of encoding
340the source file in rot13 format. The script below, C<mkrot13>, does
341just that.
342
343    die "usage mkrot13 filename\n" unless @ARGV;
344    my $in = $ARGV[0];
345    my $out = "$in.tmp";
346    open(IN, "<$in") or die "Cannot open file $in: $!\n";
347    open(OUT, ">$out") or die "Cannot open file $out: $!\n";
348
349    print OUT "use Rot13;\n";
350    while (<IN>) {
351       tr/a-zA-Z/n-za-mN-ZA-M/;
352       print OUT;
353    }
354
355    close IN;
356    close OUT;
357    unlink $in;
358    rename $out, $in;
359
360If we encrypt this with C<mkrot13>:
361
362    print " hello fred \n";
363
364the result will be this:
365
366    use Rot13;
367    cevag "uryyb serq\a";
368
369Running it produces this output:
370
371    hello fred
372
373=head1 USING CONTEXT: THE DEBUG FILTER
374
375The rot13 example was a trivial example. Here's another demonstration
376that shows off a few more features.
377
378Say you wanted to include a lot of debugging code in your Perl script
379during development, but you didn't want it available in the released
380product. Source filters offer a solution. In order to keep the example
381simple, let's say you wanted the debugging output to be controlled by
382an environment variable, C<DEBUG>. Debugging code is enabled if the
383variable exists, otherwise it is disabled.
384
385Two special marker lines will bracket debugging code, like this:
386
387    ## DEBUG_BEGIN
388    if ($year > 1999) {
389       warn "Debug: millennium bug in year $year\n";
390    }
391    ## DEBUG_END
392
393The filter ensures that Perl parses the code between the <DEBUG_BEGIN>
394and C<DEBUG_END> markers only when the C<DEBUG> environment variable
395exists. That means that when C<DEBUG> does exist, the code above
396should be passed through the filter unchanged. The marker lines can
397also be passed through as-is, because the Perl parser will see them as
398comment lines. When C<DEBUG> isn't set, we need a way to disable the
399debug code. A simple way to achieve that is to convert the lines
400between the two markers into comments:
401
402    ## DEBUG_BEGIN
403    #if ($year > 1999) {
404    #     warn "Debug: millennium bug in year $year\n";
405    #}
406    ## DEBUG_END
407
408Here is the complete Debug filter:
409
410    package Debug;
411
412    use v5.36;
413    use Filter::Util::Call;
414
415    use constant TRUE => 1;
416    use constant FALSE => 0;
417
418    sub import {
419       my ($type) = @_;
420       my (%context) = (
421         Enabled => defined $ENV{DEBUG},
422         InTraceBlock => FALSE,
423         Filename => (caller)[1],
424         LineNo => 0,
425         LastBegin => 0,
426       );
427       filter_add(bless \%context);
428    }
429
430    sub Die {
431       my ($self) = shift;
432       my ($message) = shift;
433       my ($line_no) = shift || $self->{LastBegin};
434       die "$message at $self->{Filename} line $line_no.\n"
435    }
436
437    sub filter {
438       my ($self) = @_;
439       my ($status);
440       $status = filter_read();
441       ++ $self->{LineNo};
442
443       # deal with EOF/error first
444       if ($status <= 0) {
445           $self->Die("DEBUG_BEGIN has no DEBUG_END")
446               if $self->{InTraceBlock};
447           return $status;
448       }
449
450       if ($self->{InTraceBlock}) {
451          if (/^\s*##\s*DEBUG_BEGIN/ ) {
452              $self->Die("Nested DEBUG_BEGIN", $self->{LineNo})
453          } elsif (/^\s*##\s*DEBUG_END/) {
454              $self->{InTraceBlock} = FALSE;
455          }
456
457          # comment out the debug lines when the filter is disabled
458          s/^/#/ if ! $self->{Enabled};
459       } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
460          $self->{InTraceBlock} = TRUE;
461          $self->{LastBegin} = $self->{LineNo};
462       } elsif ( /^\s*##\s*DEBUG_END/ ) {
463          $self->Die("DEBUG_END has no DEBUG_BEGIN", $self->{LineNo});
464       }
465       return $status;
466    }
467
468    1;
469
470The big difference between this filter and the previous example is the
471use of context data in the filter object. The filter object is based on
472a hash reference, and is used to keep various pieces of context
473information between calls to the filter function. All but two of the
474hash fields are used for error reporting. The first of those two,
475Enabled, is used by the filter to determine whether the debugging code
476should be given to the Perl parser. The second, InTraceBlock, is true
477when the filter has encountered a C<DEBUG_BEGIN> line, but has not yet
478encountered the following C<DEBUG_END> line.
479
480If you ignore all the error checking that most of the code does, the
481essence of the filter is as follows:
482
483    sub filter {
484       my ($self) = @_;
485       my ($status);
486       $status = filter_read();
487
488       # deal with EOF/error first
489       return $status if $status <= 0;
490       if ($self->{InTraceBlock}) {
491          if (/^\s*##\s*DEBUG_END/) {
492             $self->{InTraceBlock} = FALSE
493          }
494
495          # comment out debug lines when the filter is disabled
496          s/^/#/ if ! $self->{Enabled};
497       } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
498          $self->{InTraceBlock} = TRUE;
499       }
500       return $status;
501    }
502
503Be warned: just as the C-preprocessor doesn't know C, the Debug filter
504doesn't know Perl. It can be fooled quite easily:
505
506    print <<EOM;
507    ##DEBUG_BEGIN
508    EOM
509
510Such things aside, you can see that a lot can be achieved with a modest
511amount of code.
512
513=head1 CONCLUSION
514
515You now have better understanding of what a source filter is, and you
516might even have a possible use for them. If you feel like playing with
517source filters but need a bit of inspiration, here are some extra
518features you could add to the Debug filter.
519
520First, an easy one. Rather than having debugging code that is
521all-or-nothing, it would be much more useful to be able to control
522which specific blocks of debugging code get included. Try extending the
523syntax for debug blocks to allow each to be identified. The contents of
524the C<DEBUG> environment variable can then be used to control which
525blocks get included.
526
527Once you can identify individual blocks, try allowing them to be
528nested. That isn't difficult either.
529
530Here is an interesting idea that doesn't involve the Debug filter.
531Currently Perl subroutines have fairly limited support for formal
532parameter lists. You can specify the number of parameters and their
533type, but you still have to manually take them out of the C<@_> array
534yourself. Write a source filter that allows you to have a named
535parameter list. Such a filter would turn this:
536
537    sub MySub ($first, $second, @rest) { ... }
538
539into this:
540
541    sub MySub($$@) {
542       my ($first) = shift;
543       my ($second) = shift;
544       my (@rest) = @_;
545       ...
546    }
547
548Finally, if you feel like a real challenge, have a go at writing a
549full-blown Perl macro preprocessor as a source filter. Borrow the
550useful features from the C preprocessor and any other macro processors
551you know. The tricky bit will be choosing how much knowledge of Perl's
552syntax you want your filter to have.
553
554=head1 LIMITATIONS
555
556Source filters only work on the string level, thus are highly limited
557in its ability to change source code on the fly. It cannot detect
558comments, quoted strings, heredocs, it is no replacement for a real
559parser.
560The only stable usage for source filters are encryption, compression,
561or the byteloader, to translate binary code back to source code.
562
563See for example the limitations in L<Switch>, which uses source filters,
564and thus is does not work inside a string eval, the presence of
565regexes with embedded newlines that are specified with raw C</.../>
566delimiters and don't have a modifier C<//x> are indistinguishable from
567code chunks beginning with the division operator C</>. As a workaround
568you must use C<m/.../> or C<m?...?> for such patterns. Also, the presence of
569regexes specified with raw C<?...?> delimiters may cause mysterious
570errors. The workaround is to use C<m?...?> instead.  See
571L<https://metacpan.org/pod/Switch#LIMITATIONS>.
572
573Currently the content of the C<__DATA__> block is not filtered.
574
575Currently internal buffer lengths are limited to 32-bit only.
576
577
578=head1 THINGS TO LOOK OUT FOR
579
580=over 5
581
582=item Some Filters Clobber the C<DATA> Handle
583
584Some source filters use the C<DATA> handle to read the calling program.
585When using these source filters you cannot rely on this handle, nor expect
586any particular kind of behavior when operating on it.  Filters based on
587Filter::Util::Call (and therefore Filter::Simple) do not alter the C<DATA>
588filehandle, but on the other hand totally ignore the text after C<__DATA__>.
589
590=back
591
592=head1 REQUIREMENTS
593
594The Source Filters distribution is available on CPAN, in
595
596    CPAN/modules/by-module/Filter
597
598Starting from Perl 5.8 Filter::Util::Call (the core part of the
599Source Filters distribution) is part of the standard Perl distribution.
600Also included is a friendlier interface called Filter::Simple, by
601Damian Conway.
602
603=head1 AUTHOR
604
605Paul Marquess E<lt>Paul.Marquess@btinternet.comE<gt>
606
607Reini Urban E<lt>rurban@cpan.orgE<gt>
608
609=head1 Copyrights
610
611The first version of this article originally appeared in The Perl
612Journal #11, and is copyright 1998 The Perl Journal. It appears
613courtesy of Jon Orwant and The Perl Journal.  This document may be
614distributed under the same terms as Perl itself.
615