Monday, 16 April 2018

An Introduction to CQL

Recently I have been working on a CommonMark extension for PHP7. It is based on the reference implementation in C, linking to it rather than re-implementing the spec.

The reference implementation in C is extremely fast, and so the extension has a focus on performance, trying to create PHP objects only when necessary, among other (boring) optimisations.

In C the iterators provided by the reference implementation are extremely fast; It simply doesn't matter that you might have to accept every node in a document when you're working in C.  In a dynamic language like PHP it really does matter, even if the objects representing the nodes are short lived. Again when you access a parent or child node in C, you are just doing pointer arithmetic (hidden behind function calls), it's all simple stuff. When it comes to a dynamic language there is all kinds of baggage attached to the object (and even the read operation itself), additional allocations and other such instructions must be executed before the C pointer can be passed into user land.

While the iterators from the reference implementation are fast, they are not smart - they don't really need to be, as explained. When it comes to inspecting a document (before conversion for example, or for editing), the kind of code you need to write in any language consists of complicated nested loops and or recursive calls, it's long and complicated, and difficult to get right.

Introducing CQL

CQL - CommonMark Query Language is a feature that has been developed alongside the CommonMark PHP extension, which solves some of the problems of iterating through a tree structure in a dynamic language by allowing the user to express as a string how to travel through the document and which nodes to return.

CQL consists of a lexer and parser, a compiler for a small set of instructions, and a virtual machine for executing the instructions.


For the real geeks, they can just look at the context free grammar, for the rest of us, a query describes a path through a document:


The above query will return the children of the first child node of a tree.

firstChild, lastChild, parent, next, previous, and children are all accepted paths.

children can accept sub queries (but cannot have other paths following it, because think about it ...):
/firstChild/children[ /children ]
The above query will return the children of the children of the first child node of a tree.

children can also accept a constraint:


The above query will return the children of the first child node of a tree that are BlockQuote objects.

Constraints may be or'd together:


The above query will return the children of the first child node of a tree that are BlockQuote or Paragraph objects.

Subqueries with constraints can also have subqueries:

/firstChild/children(BlockQuote)[ /children(Paragraph) ]

The above query will return Paragraphs that are children of BlockQuotes that are children of the first child node of a tree.

Constraints and sub queries may be nested ad-absurdum to describe a path to take through the tree. The form of the queries I have used here is for readability only, whitespace is ignored, and content after # is ignored.


Having lexed and parsed your query into an abstract syntax tree, CQL compiles the AST into discrete instructions for travelling through the tree. We're going to skip over a description of that AST because it's throw away and boring. Let's have a quick look at the result of compiling the AST, the instructions:

Each instruction has an input value (IV), and an output value (RV) or JMP target (#T), in addition it has an extended value (int) for storing constraints, and probably other things in future.

We'll start simple, with /firstChild/lastChild, which compiles to:

For simplicity, you can consider the numbers in IV and RV columns variables, the first instruction FCN sets 1 to the first child node of 0, the second LCN sets 2 to the last child node of 1, and the third instruction ENT dispatches a call to the caller of the function with the address of the node at 2.

Remembering that these "variables" are just addresses, no zvals, no php vars, all very low level stuff.

It gets a little more complicated when it comes to children, /firstChild/children compiles to the following instructions:

The first instruction FCN sets 1 to the first child node of 0, the second instruction sets the first child node of 1 to 2, the third ENT dispatches the enter call. The next instruction NEN sets 3 to the node next to 2 in the tree, the next SET instruction sets 2 to 3, and the next JMP jumps to ENT if 3 is positive, creating a loop until all the children are consumed.

The textual description of a query like:
/children(List)[ /children(Item)[ /children(Paragraph) ] ]
would be extremely boring, but here's what that query looks like:
The only new instruction is CON, which will skip nodes that do not match the constraint given.

The virtual machine that executes the instructions looks like:

Making execution of the query extremely efficient, much more so than you would be able to write in PHP.


Proper documentation for the PHP API will become available in the manual soon, here's a quick description for those that want to get started:

The CommonMark extension declares \CommonMark\CQL:
class \CommonMark\CQL {
    public function __construct(string $query);
    public function __invoke(\CommonMark\Node $node, callable $enter);

The callable provided $enter should have the prototype:
function (\CommonMark\Node $root, \CommonMark\Node $node)
and will be invoked by CQL on ENT instructions.

Get Involved or Wait :)

I am not finished writing tests for CQL yet, so it currently lives in a feature branch. It will be included in the next release of the extension, probably in the next couple of weeks.

If you feel like being helpful, you could come and submit a PR for tests ...

Peace out phomies ...

Tuesday, 16 January 2018

Sensible Targets

Fig 1. Current release cycle graph
There has been a lot of talk recently about which versions of PHP you should support for your new projects or packages.

As a release manager for PHP, someone who watches the way releases evolve extremely closely, and has some sway over what gets fixed and what doesn't, and as someone who helped to draft the security classification document for PHP; I feel I have some useful things to say on this subject, so here goes ...

The Release Cycle

Every release of PHP goes through the following cycle:

Pre Release:
  • 3 Alpha, two weeks apart
  • 3 Beta, two weeks apart
  • 6 RC, two weeks apart
  • GA, roughly 6 months after the first alpha
Actively Supported:
  • For two years the PHP team make a patch release every month with bug and security fixes.
Security Only:
  • For the final year of the three year cycle, the PHP team will make a patch release when security fixes warrant a release.

What isn't a security issue ?

We have various definitions to classify the threat level posed by any security issue, but importantly for the community at large, we also have a definition of what is not a security issue:
  • requires invocation of specific code, which may be valid but is obviously malicious
  • requires invocation of functions with specific arguments, which may be valid but are obviously malicious
  • requires specific actions to be performed on the server, which are not commonly performed, or are not commonly permissible for the user (uid) executing PHP
  • requires privileges superior to that of the user (uid) executing PHP
  • requires the use of debugging facilities - ex. xdebug, var_dump
  • requires the use of settings not recommended for production - ex. error reporting to output
  • requires the use of non-standard environment variables - ex. USE_ZEND_ALLOC
  • requires the use of non-standard builds - ex. obscure embedded platform, not commonly used compiler
  • requires the use of code or settings known to be insecure
Any issue that falls under any of the above categories, even though it may have security implications for you personally, is not treated as a security issue. It may be fixed as a normal bug, but that fix will not be included in a security fix only release.

In addition, any security issue classified as having a low threat level will not necessarily be included in a security fix only release. The lowest level of threat is defined thus:
This issue allows theoretical compromise of security, but practical attack is usually impossible or extremely hard due to common practices or limitations that are virtually always present or imposed.
This also includes problems with configuration, documentation, and other non-code parts of the PHP project that may mislead users, or cause them to make their system, or their code less secure.
Issues that can trigger unauthorised actions that do not seem to be useful for any practical attack can also be categorised as low severity.
Security issues, that are present only in unstable branches, belong to this category, too. Any branch that has no stable release, is per se not intended for the production use.
Aside from those bugs which may or may not be a security issue, there is a variety of bugs that are definitely not a security issue, but may cause your project serious harm, or present serious problems for your package - No fix is forthcoming for these, the vast majority of bugs, while the release is in security fix only cycle.

What should I target ?

Targeting a security fix only release of PHP for new projects doesn't make any sense: When a release is in security fix only cycle you should be concentrating on getting old projects upgraded, and a year is plenty of time to do that. In the case of PHP 5.6, we extended the security cycle to two years. If you are reading this and thinking a year isn't long enough to do that, then there is something wrong with the way you deploy or support projects or packages: It has to be long enough, running a version of PHP without active support is dangerous for your business, reputation, and soul.

New projects or packages should obviously target an actively developed version of PHP. At the time of writing both 7.1 and 7.2 are being actively developed (there will always be two versions in active development). Whether you choose to use 7.1 or 7.2 depends on your project or package, perhaps you'd like to use some new features, and not have to worry about security cycle for nearly two years and so can reasonably target 7.2. Perhaps you have reasons to stick with 7.1, and are prepared to deal with security cycle before the year is out.

The bottom line is this: New projects or packages must target an actively developed, fully supported version of PHP.