1perlfilter(3)         User Contributed Perl Documentation        perlfilter(3)
2
3
4

NAME

6       perlfilter - Source Filters
7

DESCRIPTION

9       This article is about a little-known feature of Perl called source
10       filters. Source filters alter the program text of a module before Perl
11       sees it, much as a C preprocessor alters the source text of a C program
12       before the compiler sees it. This article tells you more about what
13       source filters are, how they work, and how to write your own.
14
15       The original purpose of source filters was to let you encrypt your
16       program source to prevent casual piracy. This isn't all they can do, as
17       you'll soon learn. But first, the basics.
18

CONCEPTS

20       Before the Perl interpreter can execute a Perl script, it must first
21       read it from a file into memory for parsing and compilation. If that
22       script itself includes other scripts with a "use" or "require"
23       statement, then each of those scripts will have to be read from their
24       respective files as well.
25
26       Now think of each logical connection between the Perl parser and an
27       individual file as a source stream. A source stream is created when the
28       Perl parser opens a file, it continues to exist as the source code is
29       read into memory, and it is destroyed when Perl is finished parsing the
30       file. If the parser encounters a "require" or "use" statement in a
31       source stream, a new and distinct stream is created just for that file.
32
33       The diagram below represents a single source stream, with the flow of
34       source from a Perl script file on the left into the Perl parser on the
35       right. This is how Perl normally operates.
36
37           file -------> parser
38
39       There are two important points to remember:
40
41       1.   Although there can be any number of source streams in existence at
42            any given time, only one will be active.
43
44       2.   Every source stream is associated with only one file.
45
46       A source filter is a special kind of Perl module that intercepts and
47       modifies a source stream before it reaches the parser. A source filter
48       changes our diagram like this:
49
50           file ----> filter ----> parser
51
52       If that doesn't make much sense, consider the analogy of a command
53       pipeline. Say you have a shell script stored in the compressed file
54       trial.gz. The simple pipeline command below runs the script without
55       needing to create a temporary file to hold the uncompressed file.
56
57           gunzip -c trial.gz | sh
58
59       In this case, the data flow from the pipeline can be represented as
60       follows:
61
62           trial.gz ----> gunzip ----> sh
63
64       With source filters, you can store the text of your script compressed
65       and use a source filter to uncompress it for Perl's parser:
66
67            compressed           gunzip
68           Perl program ---> source filter ---> parser
69

USING FILTERS

71       So how do you use a source filter in a Perl script? Above, I said that
72       a source filter is just a special kind of module. Like all Perl
73       modules, a source filter is invoked with a use statement.
74
75       Say you want to pass your Perl source through the C preprocessor before
76       execution. As it happens, the source filters distribution comes with a
77       C preprocessor filter module called Filter::cpp.
78
79       Below is an example program, "cpp_test", which makes use of this
80       filter.  Line numbers have been added to allow specific lines to be
81       referenced easily.
82
83           1: use Filter::cpp;
84           2: #define TRUE 1
85           3: $a = TRUE;
86           4: print "a = $a\n";
87
88       When you execute this script, Perl creates a source stream for the
89       file. Before the parser processes any of the lines from the file, the
90       source stream looks like this:
91
92           cpp_test ---------> parser
93
94       Line 1, "use Filter::cpp", includes and installs the "cpp" filter
95       module. All source filters work this way. The use statement is compiled
96       and executed at compile time, before any more of the file is read, and
97       it attaches the cpp filter to the source stream behind the scenes. Now
98       the data flow looks like this:
99
100           cpp_test ----> cpp filter ----> parser
101
102       As the parser reads the second and subsequent lines from the source
103       stream, it feeds those lines through the "cpp" source filter before
104       processing them. The "cpp" filter simply passes each line through the
105       real C preprocessor. The output from the C preprocessor is then
106       inserted back into the source stream by the filter.
107
108                         .-> cpp --.
109                         |         |
110                         |         |
111                         |       <-'
112          cpp_test ----> cpp filter ----> parser
113
114       The parser then sees the following code:
115
116           use Filter::cpp;
117           $a = 1;
118           print "a = $a\n";
119
120       Let's consider what happens when the filtered code includes another
121       module with use:
122
123           1: use Filter::cpp;
124           2: #define TRUE 1
125           3: use Fred;
126           4: $a = TRUE;
127           5: print "a = $a\n";
128
129       The "cpp" filter does not apply to the text of the Fred module, only to
130       the text of the file that used it ("cpp_test"). Although the use
131       statement on line 3 will pass through the cpp filter, the module that
132       gets included ("Fred") will not. The source streams look like this
133       after line 3 has been parsed and before line 4 is parsed:
134
135           cpp_test ---> cpp filter ---> parser (INACTIVE)
136
137           Fred.pm ----> parser
138
139       As you can see, a new stream has been created for reading the source
140       from "Fred.pm". This stream will remain active until all of "Fred.pm"
141       has been parsed. The source stream for "cpp_test" will still exist, but
142       is inactive. Once the parser has finished reading Fred.pm, the source
143       stream associated with it will be destroyed. The source stream for
144       "cpp_test" then becomes active again and the parser reads line 4 and
145       subsequent lines from "cpp_test".
146
147       You can use more than one source filter on a single file. Similarly,
148       you can reuse the same filter in as many files as you like.
149
150       For example, if you have a uuencoded and compressed source file, it is
151       possible to stack a uudecode filter and an uncompression filter like
152       this:
153
154           use Filter::uudecode; use Filter::uncompress;
155           M'XL(".H<US4''V9I;F%L')Q;>7/;1I;_>_I3=&E=%:F*I"T?22Q/
156           M6]9*<IQCO*XFT"0[PL%%'Y+IG?WN^ZYN-$'J.[.JE$,20/?K=_[>
157           ...
158
159       Once the first line has been processed, the flow will look like this:
160
161           file ---> uudecode ---> uncompress ---> parser
162                      filter         filter
163
164       Data flows through filters in the same order they appear in the source
165       file. The uudecode filter appeared before the uncompress filter, so the
166       source file will be uudecoded before it's uncompressed.
167

WRITING A SOURCE FILTER

169       There are three ways to write your own source filter. You can write it
170       in C, use an external program as a filter, or write the filter in Perl.
171       I won't cover the first two in any great detail, so I'll get them out
172       of the way first. Writing the filter in Perl is most convenient, so
173       I'll devote the most space to it.
174

WRITING A SOURCE FILTER IN C

176       The first of the three available techniques is to write the filter
177       completely in C. The external module you create interfaces directly
178       with the source filter hooks provided by Perl.
179
180       The advantage of this technique is that you have complete control over
181       the implementation of your filter. The big disadvantage is the
182       increased complexity required to write the filter - not only do you
183       need to understand the source filter hooks, but you also need a
184       reasonable knowledge of Perl guts. One of the few times it is worth
185       going to this trouble is when writing a source scrambler. The "decrypt"
186       filter (which unscrambles the source before Perl parses it) included
187       with the source filter distribution is an example of a C source filter
188       (see Decryption Filters, below).
189
190       Decryption Filters
191            All decryption filters work on the principle of "security through
192            obscurity." Regardless of how well you write a decryption filter
193            and how strong your encryption algorithm is, anyone determined
194            enough can retrieve the original source code. The reason is quite
195            simple - once the decryption filter has decrypted the source back
196            to its original form, fragments of it will be stored in the
197            computer's memory as Perl parses it. The source might only be in
198            memory for a short period of time, but anyone possessing a
199            debugger, skill, and lots of patience can eventually reconstruct
200            your program.
201
202            That said, there are a number of steps that can be taken to make
203            life difficult for the potential cracker. The most important:
204            Write your decryption filter in C and statically link the
205            decryption module into the Perl binary. For further tips to make
206            life difficult for the potential cracker, see the file decrypt.pm
207            in the source filters distribution.
208

CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE

210       An alternative to writing the filter in C is to create a separate
211       executable in the language of your choice. The separate executable
212       reads from standard input, does whatever processing is necessary, and
213       writes the filtered data to standard output. "Filter::cpp" is an
214       example of a source filter implemented as a separate executable - the
215       executable is the C preprocessor bundled with your C compiler.
216
217       The source filter distribution includes two modules that simplify this
218       task: "Filter::exec" and "Filter::sh". Both allow you to run any
219       external executable. Both use a coprocess to control the flow of data
220       into and out of the external executable. (For details on coprocesses,
221       see Stephens, W.R., "Advanced Programming in the UNIX Environment."
222       Addison-Wesley, ISBN 0-210-56317-7, pages 441-445.) The difference
223       between them is that "Filter::exec" spawns the external command
224       directly, while "Filter::sh" spawns a shell to execute the external
225       command. (Unix uses the Bourne shell; NT uses the cmd shell.) Spawning
226       a shell allows you to make use of the shell metacharacters and
227       redirection facilities.
228
229       Here is an example script that uses "Filter::sh":
230
231           use Filter::sh 'tr XYZ PQR';
232           $a = 1;
233           print "XYZ a = $a\n";
234
235       The output you'll get when the script is executed:
236
237           PQR a = 1
238
239       Writing a source filter as a separate executable works fine, but a
240       small performance penalty is incurred. For example, if you execute the
241       small example above, a separate subprocess will be created to run the
242       Unix "tr" command. Each use of the filter requires its own subprocess.
243       If creating subprocesses is expensive on your system, you might want to
244       consider one of the other options for creating source filters.
245

WRITING A SOURCE FILTER IN PERL

247       The easiest and most portable option available for creating your own
248       source filter is to write it completely in Perl. To distinguish this
249       from the previous two techniques, I'll call it a Perl source filter.
250
251       To help understand how to write a Perl source filter we need an example
252       to study. Here is a complete source filter that performs rot13
253       decoding. (Rot13 is a very simple encryption scheme used in Usenet
254       postings to hide the contents of offensive posts. It moves every letter
255       forward thirteen places, so that A becomes N, B becomes O, and Z
256       becomes M.)
257
258          package Rot13;
259
260          use Filter::Util::Call;
261
262          sub import {
263             my ($type) = @_;
264             my ($ref) = [];
265             filter_add(bless $ref);
266          }
267
268          sub filter {
269             my ($self) = @_;
270             my ($status);
271
272             tr/n-za-mN-ZA-M/a-zA-Z/
273                if ($status = filter_read()) > 0;
274             $status;
275          }
276
277          1;
278
279       All Perl source filters are implemented as Perl classes and have the
280       same basic structure as the example above.
281
282       First, we include the "Filter::Util::Call" module, which exports a
283       number of functions into your filter's namespace. The filter shown
284       above uses two of these functions, "filter_add()" and "filter_read()".
285
286       Next, we create the filter object and associate it with the source
287       stream by defining the "import" function. If you know Perl well enough,
288       you know that "import" is called automatically every time a module is
289       included with a use statement. This makes "import" the ideal place to
290       both create and install a filter object.
291
292       In the example filter, the object ($ref) is blessed just like any other
293       Perl object. Our example uses an anonymous array, but this isn't a
294       requirement. Because this example doesn't need to store any context
295       information, we could have used a scalar or hash reference just as
296       well. The next section demonstrates context data.
297
298       The association between the filter object and the source stream is made
299       with the "filter_add()" function. This takes a filter object as a
300       parameter ($ref in this case) and installs it in the source stream.
301
302       Finally, there is the code that actually does the filtering. For this
303       type of Perl source filter, all the filtering is done in a method
304       called "filter()". (It is also possible to write a Perl source filter
305       using a closure. See the "Filter::Util::Call" manual page for more
306       details.) It's called every time the Perl parser needs another line of
307       source to process. The "filter()" method, in turn, reads lines from the
308       source stream using the "filter_read()" function.
309
310       If a line was available from the source stream, "filter_read()" returns
311       a status value greater than zero and appends the line to $_.  A status
312       value of zero indicates end-of-file, less than zero means an error. The
313       filter function itself is expected to return its status in the same
314       way, and put the filtered line it wants written to the source stream in
315       $_. The use of $_ accounts for the brevity of most Perl source filters.
316
317       In order to make use of the rot13 filter we need some way of encoding
318       the source file in rot13 format. The script below, "mkrot13", does just
319       that.
320
321           die "usage mkrot13 filename\n" unless @ARGV;
322           my $in = $ARGV[0];
323           my $out = "$in.tmp";
324           open(IN, "<$in") or die "Cannot open file $in: $!\n";
325           open(OUT, ">$out") or die "Cannot open file $out: $!\n";
326
327           print OUT "use Rot13;\n";
328           while (<IN>) {
329              tr/a-zA-Z/n-za-mN-ZA-M/;
330              print OUT;
331           }
332
333           close IN;
334           close OUT;
335           unlink $in;
336           rename $out, $in;
337
338       If we encrypt this with "mkrot13":
339
340           print " hello fred \n";
341
342       the result will be this:
343
344           use Rot13;
345           cevag "uryyb serq\a";
346
347       Running it produces this output:
348
349           hello fred
350

USING CONTEXT: THE DEBUG FILTER

352       The rot13 example was a trivial example. Here's another demonstration
353       that shows off a few more features.
354
355       Say you wanted to include a lot of debugging code in your Perl script
356       during development, but you didn't want it available in the released
357       product. Source filters offer a solution. In order to keep the example
358       simple, let's say you wanted the debugging output to be controlled by
359       an environment variable, "DEBUG". Debugging code is enabled if the
360       variable exists, otherwise it is disabled.
361
362       Two special marker lines will bracket debugging code, like this:
363
364           ## DEBUG_BEGIN
365           if ($year > 1999) {
366              warn "Debug: millennium bug in year $year\n";
367           }
368           ## DEBUG_END
369
370       The filter ensures that Perl parses the code between the <DEBUG_BEGIN>
371       and "DEBUG_END" markers only when the "DEBUG" environment variable
372       exists. That means that when "DEBUG" does exist, the code above should
373       be passed through the filter unchanged. The marker lines can also be
374       passed through as-is, because the Perl parser will see them as comment
375       lines. When "DEBUG" isn't set, we need a way to disable the debug code.
376       A simple way to achieve that is to convert the lines between the two
377       markers into comments:
378
379           ## DEBUG_BEGIN
380           #if ($year > 1999) {
381           #     warn "Debug: millennium bug in year $year\n";
382           #}
383           ## DEBUG_END
384
385       Here is the complete Debug filter:
386
387           package Debug;
388
389           use strict;
390           use warnings;
391           use Filter::Util::Call;
392
393           use constant TRUE => 1;
394           use constant FALSE => 0;
395
396           sub import {
397              my ($type) = @_;
398              my (%context) = (
399                Enabled => defined $ENV{DEBUG},
400                InTraceBlock => FALSE,
401                Filename => (caller)[1],
402                LineNo => 0,
403                LastBegin => 0,
404              );
405              filter_add(bless \%context);
406           }
407
408           sub Die {
409              my ($self) = shift;
410              my ($message) = shift;
411              my ($line_no) = shift || $self->{LastBegin};
412              die "$message at $self->{Filename} line $line_no.\n"
413           }
414
415           sub filter {
416              my ($self) = @_;
417              my ($status);
418              $status = filter_read();
419              ++ $self->{LineNo};
420
421              # deal with EOF/error first
422              if ($status <= 0) {
423                  $self->Die("DEBUG_BEGIN has no DEBUG_END")
424                      if $self->{InTraceBlock};
425                  return $status;
426              }
427
428              if ($self->{InTraceBlock}) {
429                 if (/^\s*##\s*DEBUG_BEGIN/ ) {
430                     $self->Die("Nested DEBUG_BEGIN", $self->{LineNo})
431                 } elsif (/^\s*##\s*DEBUG_END/) {
432                     $self->{InTraceBlock} = FALSE;
433                 }
434
435                 # comment out the debug lines when the filter is disabled
436                 s/^/#/ if ! $self->{Enabled};
437              } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
438                 $self->{InTraceBlock} = TRUE;
439                 $self->{LastBegin} = $self->{LineNo};
440              } elsif ( /^\s*##\s*DEBUG_END/ ) {
441                 $self->Die("DEBUG_END has no DEBUG_BEGIN", $self->{LineNo});
442              }
443              return $status;
444           }
445
446           1;
447
448       The big difference between this filter and the previous example is the
449       use of context data in the filter object. The filter object is based on
450       a hash reference, and is used to keep various pieces of context
451       information between calls to the filter function. All but two of the
452       hash fields are used for error reporting. The first of those two,
453       Enabled, is used by the filter to determine whether the debugging code
454       should be given to the Perl parser. The second, InTraceBlock, is true
455       when the filter has encountered a "DEBUG_BEGIN" line, but has not yet
456       encountered the following "DEBUG_END" line.
457
458       If you ignore all the error checking that most of the code does, the
459       essence of the filter is as follows:
460
461           sub filter {
462              my ($self) = @_;
463              my ($status);
464              $status = filter_read();
465
466              # deal with EOF/error first
467              return $status if $status <= 0;
468              if ($self->{InTraceBlock}) {
469                 if (/^\s*##\s*DEBUG_END/) {
470                    $self->{InTraceBlock} = FALSE
471                 }
472
473                 # comment out debug lines when the filter is disabled
474                 s/^/#/ if ! $self->{Enabled};
475              } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
476                 $self->{InTraceBlock} = TRUE;
477              }
478              return $status;
479           }
480
481       Be warned: just as the C-preprocessor doesn't know C, the Debug filter
482       doesn't know Perl. It can be fooled quite easily:
483
484           print <<EOM;
485           ##DEBUG_BEGIN
486           EOM
487
488       Such things aside, you can see that a lot can be achieved with a modest
489       amount of code.
490

CONCLUSION

492       You now have better understanding of what a source filter is, and you
493       might even have a possible use for them. If you feel like playing with
494       source filters but need a bit of inspiration, here are some extra
495       features you could add to the Debug filter.
496
497       First, an easy one. Rather than having debugging code that is all-or-
498       nothing, it would be much more useful to be able to control which
499       specific blocks of debugging code get included. Try extending the
500       syntax for debug blocks to allow each to be identified. The contents of
501       the "DEBUG" environment variable can then be used to control which
502       blocks get included.
503
504       Once you can identify individual blocks, try allowing them to be
505       nested. That isn't difficult either.
506
507       Here is an interesting idea that doesn't involve the Debug filter.
508       Currently Perl subroutines have fairly limited support for formal
509       parameter lists. You can specify the number of parameters and their
510       type, but you still have to manually take them out of the @_ array
511       yourself. Write a source filter that allows you to have a named
512       parameter list. Such a filter would turn this:
513
514           sub MySub ($first, $second, @rest) { ... }
515
516       into this:
517
518           sub MySub($$@) {
519              my ($first) = shift;
520              my ($second) = shift;
521              my (@rest) = @_;
522              ...
523           }
524
525       Finally, if you feel like a real challenge, have a go at writing a
526       full-blown Perl macro preprocessor as a source filter. Borrow the
527       useful features from the C preprocessor and any other macro processors
528       you know. The tricky bit will be choosing how much knowledge of Perl's
529       syntax you want your filter to have.
530

LIMITATIONS

532       Source filters only work on the string level, thus are highly limited
533       in its ability to change source code on the fly. It cannot detect
534       comments, quoted strings, heredocs, it is no replacement for a real
535       parser.  The only stable usage for source filters are encryption,
536       compression, or the byteloader, to translate binary code back to source
537       code.
538
539       See for example the limitations in Switch, which uses source filters,
540       and thus is does not work inside a string eval, the presence of regexes
541       with embedded newlines that are specified with raw "/.../" delimiters
542       and don't have a modifier "//x" are indistinguishable from code chunks
543       beginning with the division operator "/". As a workaround you must use
544       "m/.../" or "m?...?" for such patterns. Also, the presence of regexes
545       specified with raw "?...?" delimiters may cause mysterious errors. The
546       workaround is to use "m?...?" instead.  See
547       <http://search.cpan.org/perldoc?Switch#LIMITATIONS>
548
549       Currently the content of the "__DATA__" block is not filtered.
550
551       Currently internal buffer lengths are limited to 32-bit only.
552

THINGS TO LOOK OUT FOR

554       Some Filters Clobber the "DATA" Handle
555            Some source filters use the "DATA" handle to read the calling
556            program.  When using these source filters you cannot rely on this
557            handle, nor expect any particular kind of behavior when operating
558            on it.  Filters based on Filter::Util::Call (and therefore
559            Filter::Simple) do not alter the "DATA" filehandle, but on the
560            other hand totally ignore the text after "__DATA__".
561

REQUIREMENTS

563       The Source Filters distribution is available on CPAN, in
564
565           CPAN/modules/by-module/Filter
566
567       Starting from Perl 5.8 Filter::Util::Call (the core part of the Source
568       Filters distribution) is part of the standard Perl distribution.  Also
569       included is a friendlier interface called Filter::Simple, by Damian
570       Conway.
571

AUTHOR

573       Paul Marquess <Paul.Marquess@btinternet.com>
574
575       Reini Urban <rurban@cpan.org>
576

Copyrights

578       The first version of this article originally appeared in The Perl
579       Journal #11, and is copyright 1998 The Perl Journal. It appears
580       courtesy of Jon Orwant and The Perl Journal.  This document may be
581       distributed under the same terms as Perl itself.
582
583
584
585perl v5.30.0                      2019-07-26                     perlfilter(3)
Impressum