NAMEperlfilter - Source Filters
DESCRIPTIONThis article is about a little-known feature of Perl called source filters. Source filters alter the program text of a module before Perl sees it, much as a C preprocessor alters the source text of a C program before the compiler sees it. This article tells you more about what source filters are, how they work, and how to write your own. The original purpose of source filters was to let you encrypt your program source to prevent casual piracy. This isn't all they can do, as you'll soon learn. But first, the basics.
CONCEPTSBefore the Perl interpreter can execute a Perl script, it must first
read it from a file into memory for parsing and compilation. If that
script itself includes other scripts with a Now think of each logical connection between the Perl parser and an
individual file as a source stream. A source stream is created when
the Perl parser opens a file, it continues to exist as the source code
is read into memory, and it is destroyed when Perl is finished parsing
the file. If the parser encounters a The diagram below represents a single source stream, with the flow of source from a Perl script file on the left into the Perl parser on the right. This is how Perl normally operates. file -------> parser There are two important points to remember:
A source filter is a special kind of Perl module that intercepts and modifies a source stream before it reaches the parser. A source filter changes our diagram like this: file ----> filter ----> parser If that doesn't make much sense, consider the analogy of a command pipeline. Say you have a shell script stored in the compressed file trial.gz. The simple pipeline command below runs the script without needing to create a temporary file to hold the uncompressed file. gunzip -c trial.gz | sh In this case, the data flow from the pipeline can be represented as follows: trial.gz ----> gunzip ----> sh With source filters, you can store the text of your script compressed and use a source filter to uncompress it for Perl's parser: compressed gunzip Perl program ---> source filter ---> parser
USING FILTERSSo how do you use a source filter in a Perl script? Above, I said that a source filter is just a special kind of module. Like all Perl modules, a source filter is invoked with a use statement. Say you want to pass your Perl source through the C preprocessor before
execution. You could use the existing Below is an example program, 1: use Filter::cpp ; 2: #define TRUE 1 3: $a = TRUE ; 4: print "a = $a\n" ; When you execute this script, Perl creates a source stream for the file. Before the parser processes any of the lines from the file, the source stream looks like this: cpp_test ---------> parser Line 1, cpp_test ----> cpp filter ----> parser As the parser reads the second and subsequent lines from the source
stream, it feeds those lines through the .-> cpp --. | | | | | <-' cpp_test ----> cpp filter ----> parser The parser then sees the following code: use Filter::cpp ; $a = 1 ; print "a = $a\n" ; Let's consider what happens when the filtered code includes another module with use: 1: use Filter::cpp ; 2: #define TRUE 1 3: use Fred ; 4: $a = TRUE ; 5: print "a = $a\n" ; The cpp_test ---> cpp filter ---> parser (INACTIVE) Fred.pm ----> parser As you can see, a new stream has been created for reading the source
from You can use more than one source filter on a single file. Similarly, you can reuse the same filter in as many files as you like. For example, if you have a uuencoded and compressed source file, it is possible to stack a uudecode filter and an uncompression filter like this: use Filter::uudecode ; use Filter::uncompress ; M'XL(".H<US4''V9I;F%L')Q;>7/;1I;_>_I3=&E=%:F*I"T?22Q/ M6]9*<IQCO*XFT"0[PL%%'Y+IG?WN^ZYN-$'J.[.JE$,20/?K=_[> ... Once the first line has been processed, the flow will look like this: file ---> uudecode ---> uncompress ---> parser filter filter Data flows through filters in the same order they appear in the source file. The uudecode filter appeared before the uncompress filter, so the source file will be uudecoded before it's uncompressed.
WRITING A SOURCE FILTERThere are three ways to write your own source filter. You can write it in C, use an external program as a filter, or write the filter in Perl. I won't cover the first two in any great detail, so I'll get them out of the way first. Writing the filter in Perl is most convenient, so I'll devote the most space to it.
WRITING A SOURCE FILTER IN CThe first of the three available techniques is to write the filter completely in C. The external module you create interfaces directly with the source filter hooks provided by Perl. The advantage of this technique is that you have complete control over
the implementation of your filter. The big disadvantage is the
increased complexity required to write the filter - not only do you
need to understand the source filter hooks, but you also need a
reasonable knowledge of Perl guts. One of the few times it is worth
going to this trouble is when writing a source scrambler. The
CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLEAn alternative to writing the filter in C is to create a separate
executable in the language of your choice. The separate executable
reads from standard input, does whatever processing is necessary, and
writes the filtered data to standard output. The source filter distribution includes two modules that simplify this
task: Here is an example script that uses use Filter::sh 'tr XYZ PQR' ; $a = 1 ; print "XYZ a = $a\n" ; The output you'll get when the script is executed: PQR a = 1 Writing a source filter as a separate executable works fine, but a
small performance penalty is incurred. For example, if you execute the
small example above, a separate subprocess will be created to run the
Unix
WRITING A SOURCE FILTER IN PERLThe easiest and most portable option available for creating your own source filter is to write it completely in Perl. To distinguish this from the previous two techniques, I'll call it a Perl source filter. To help understand how to write a Perl source filter we need an example to study. Here is a complete source filter that performs rot13 decoding. (Rot13 is a very simple encryption scheme used in Usenet postings to hide the contents of offensive posts. It moves every letter forward thirteen places, so that A becomes N, B becomes O, and Z becomes M.) package Rot13 ; use Filter::Util::Call ; sub import { my ($type) = @_ ; my ($ref) = [] ; filter_add(bless $ref) ; } sub filter { my ($self) = @_ ; my ($status) ; tr/n-za-mN-ZA-M/a-zA-Z/ if ($status = filter_read()) > 0 ; $status ; } 1; All Perl source filters are implemented as Perl classes and have the same basic structure as the example above. First, we include the Next, we create the filter object and associate it with the source
stream by defining the In the example filter, the object ( The association between the filter object and the source stream is made
with the Finally, there is the code that actually does the filtering. For this
type of Perl source filter, all the filtering is done in a method
called If a line was available from the source stream, In order to make use of the rot13 filter we need some way of encoding
the source file in rot13 format. The script below, die "usage mkrot13 filename\n" unless @ARGV ; my $in = $ARGV[0] ; my $out = "$in.tmp" ; open(IN, "<$in") or die "Cannot open file $in: $!\n"; open(OUT, ">$out") or die "Cannot open file $out: $!\n"; print OUT "use Rot13;\n" ; while (<IN>) { tr/a-zA-Z/n-za-mN-ZA-M/ ; print OUT ; } close IN; close OUT; unlink $in; rename $out, $in; If we encrypt this with print " hello fred \n" ; the result will be this: use Rot13; cevag "uryyb serq\a" ; Running it produces this output: hello fred
USING CONTEXT: THE DEBUG FILTERThe rot13 example was a trivial example. Here's another demonstration that shows off a few more features. Say you wanted to include a lot of debugging code in your Perl script
during development, but you didn't want it available in the released
product. Source filters offer a solution. In order to keep the example
simple, let's say you wanted the debugging output to be controlled by
an environment variable, Two special marker lines will bracket debugging code, like this: ## DEBUG_BEGIN if ($year > 1999) { warn "Debug: millennium bug in year $year\n" ; } ## DEBUG_END When the ## DEBUG_BEGIN #if ($year > 1999) { # warn "Debug: millennium bug in year $year\n" ; #} ## DEBUG_END Here is the complete Debug filter: package Debug; use strict; use warnings; use Filter::Util::Call ; use constant TRUE => 1 ; use constant FALSE => 0 ; sub import { my ($type) = @_ ; my (%context) = ( Enabled => defined $ENV{DEBUG}, InTraceBlock => FALSE, Filename => (caller)[1], LineNo => 0, LastBegin => 0, ) ; filter_add(bless \%context) ; } sub Die { my ($self) = shift ; my ($message) = shift ; my ($line_no) = shift || $self->{LastBegin} ; die "$message at $self->{Filename} line $line_no.\n" } sub filter { my ($self) = @_ ; my ($status) ; $status = filter_read() ; ++ $self->{LineNo} ; # deal with EOF/error first if ($status <= 0) { $self->Die("DEBUG_BEGIN has no DEBUG_END") if $self->{InTraceBlock} ; return $status ; } if ($self->{InTraceBlock}) { if (/^\s*##\s*DEBUG_BEGIN/ ) { $self->Die("Nested DEBUG_BEGIN", $self->{LineNo}) } elsif (/^\s*##\s*DEBUG_END/) { $self->{InTraceBlock} = FALSE ; } # comment out the debug lines when the filter is disabled s/^/#/ if ! $self->{Enabled} ; } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) { $self->{InTraceBlock} = TRUE ; $self->{LastBegin} = $self->{LineNo} ; } elsif ( /^\s*##\s*DEBUG_END/ ) { $self->Die("DEBUG_END has no DEBUG_BEGIN", $self->{LineNo}); } return $status ; } 1 ; The big difference between this filter and the previous example is the
use of context data in the filter object. The filter object is based on
a hash reference, and is used to keep various pieces of context
information between calls to the filter function. All but two of the
hash fields are used for error reporting. The first of those two,
Enabled, is used by the filter to determine whether the debugging code
should be given to the Perl parser. The second, InTraceBlock, is true
when the filter has encountered a If you ignore all the error checking that most of the code does, the essence of the filter is as follows: sub filter { my ($self) = @_ ; my ($status) ; $status = filter_read() ; # deal with EOF/error first return $status if $status <= 0 ; if ($self->{InTraceBlock}) { if (/^\s*##\s*DEBUG_END/) { $self->{InTraceBlock} = FALSE } # comment out debug lines when the filter is disabled s/^/#/ if ! $self->{Enabled} ; } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) { $self->{InTraceBlock} = TRUE ; } return $status ; } Be warned: just as the C-preprocessor doesn't know C, the Debug filter doesn't know Perl. It can be fooled quite easily: print <<EOM; ##DEBUG_BEGIN EOM Such things aside, you can see that a lot can be achieved with a modest amount of code.
CONCLUSIONYou now have better understanding of what a source filter is, and you might even have a possible use for them. If you feel like playing with source filters but need a bit of inspiration, here are some extra features you could add to the Debug filter. First, an easy one. Rather than having debugging code that is
all-or-nothing, it would be much more useful to be able to control
which specific blocks of debugging code get included. Try extending the
syntax for debug blocks to allow each to be identified. The contents of
the Once you can identify individual blocks, try allowing them to be nested. That isn't difficult either. Here is a interesting idea that doesn't involve the Debug filter.
Currently Perl subroutines have fairly limited support for formal
parameter lists. You can specify the number of parameters and their
type, but you still have to manually take them out of the sub MySub ($first, $second, @rest) { ... } into this: sub MySub($$@) { my ($first) = shift ; my ($second) = shift ; my (@rest) = @_ ; ... } Finally, if you feel like a real challenge, have a go at writing a full-blown Perl macro preprocessor as a source filter. Borrow the useful features from the C preprocessor and any other macro processors you know. The tricky bit will be choosing how much knowledge of Perl's syntax you want your filter to have.
REQUIREMENTSThe Source Filters distribution is available on CPAN, in CPAN/modules/by-module/Filter
AUTHORPaul Marquess <Paul.Marquess@btinternet.com>
CopyrightsThis article originally appeared in The Perl Journal #11, and is copyright 1998 The Perl Journal. It appears courtesy of Jon Orwant and The Perl Journal. This document may be distributed under the same terms as Perl itself.
|