As we've seen, we make serializers, unserializers, and other transformers like expression simplifiers by composing a recognizer with a builder. The interface between the two is the DEBuilder API, explained in Appendix A: The Data-E Manual. Since most of the API is a straightforward reflection of the Data-E grammar productions, if you wish, you may safely skip these details and proceed here by example. Evaluating Data-EThe semantics of Data-E are defined by the semantics of its evaluation as an E program. We could unserialize using the full E evaluator. However, this is inefficient both as an implementation and as an explanation. Instead, here is the Data-E evaluator as a builder, implementing exactly this subset of E's semantics. def deSubgraphKit { to makeBuilder(scope) :near { # The index of the next temp variable var nextTemp := 0 # The frame of temp variables def temps := [].diverge() # The type returned by "internal" productions and passed as arguments to represent # built subtrees. def Node := any # The type returned by the builder as a whole. def Root := any # DEBuilderOf is a parameterized type constructor. def deSubgraphBuilder implements DEBuilderOf(Node, Root) { to getNodeType() :near { Node } to getRootType() :near { Root } /** Called at the end with the reconstructed root to obtain the value to return. */ to buildRoot(root :Node) :Root { root } /** A literal evaluates to its value. */ to buildLiteral(value) :Node { value } /** A free variable's name is looked up in the scope. */ to buildImport(varName :String) :Node { scope[varName] } /** A temporary variable's index is looked up in the temps frame. */ to buildIbid(tempIndex :int) :Node { temps[tempIndex] } /** Perform the described call. */ to buildCall(rec :Node, verb :String, args :Node[]) :Node { # E.call(..) is E's reflective invocation construct. For example, E.call(2, "add", [3]) # performs the same call as 2.add(3). E.call(rec, verb, args) } /** * Called prior to building the right-hand side of a defexpr, to allocate and bind the * next two temp variables to a promise and its resolver. * * @return the index of the temp holding the promise. The temp holding the * resolver is understood to be this plus one. */ to buildPromise() :int { def promIndex := nextTemp nextTemp += 2 def [prom,res] := Ref.promise() temps[promIndex] := prom temps[promIndex+1] := res promIndex } /** * Called once the right-hand side of a defexpr is built, use the resolver to resolve * the value of the promise. * * @return the value of the right-hand side. */ to buildDefrec(resIndex :int, rValue :Node) :Node { temps[resIndex].resolve(rValue) rValue } # ... buildDefine is an optimization of buildDefrec for known non-cyclic cases. } } # ... other useful tools } As we see, the E.call(..) underlined above is where all the object construction is done. All the rest is plumbing to hook the up the references among these objects. The only extra parameter to the above code, in addition to those specified by the DEBuilder API, is the scope parameter to makeBuilder(..). Typically, we will express unserialization-time policy choices using only this hook. With a bit of pre-planning at serialization time, this can be a surprisingly powerful hook, and will often prove adequate. Unevaluating to Data-E
We are now ready for the heart of serialization -- the Data-E subgraph recognizer. It has two parameters for expressing policy -- the uncallerList and the unscopeMap. Since we are evaling "in reverse", we need the inverse of a scope, which we call an unscope. An unscope maps from arbitrary values to a description of the "variable name" presumed to hold that reference. In the unscope table passed in as unscopeMap, each description is a normal variable name string, as would be used to look the value up in a scope. On each recognize(..), the ".diverge()" makes a private copy of the unscopeMap we put in the variable unscope, which we use from there. This private unscope table gets additional mappings from values to integers representing temporary variable indices. The uncallerList is used to obtain a portrayal of each object, as we explain below. def makeUnevaler(uncallerList, unscopeMap) :near { def unevaler { to recognize(root, builder) :(def Root := builder.getRootType()) { def Node := builder.getNodeType() def uncallers := uncallerList.snapshot() def unscope := unscopeMap.diverge() # forward declaration def generate /** traverse an uncall portrayal */ def genCall(rec, verb :String, args :any[]) :Node { def recExpr := generate(rec) var argExprs := [] for arg in args { argExprs := argExprs.with(generate(arg)) } builder.buildCall(recExpr, verb, argExprs) } /** When we're past all the variable manipulation. */ def genObject(obj) :Node {
if (obj =~ i :int) { return builder.buildLiteral(i) } if (obj =~ f :float64) { return builder.buildLiteral(f) } if (obj =~ c :char) { return builder.buildLiteral(c) } if (obj =~ twine :Twine && twine.isBare()) { return builder.buildLiteral(twine) }
for uncaller in uncallers { if (uncaller.optUncall(obj) =~ [rec, verb, args]) { return genCall(rec, verb, args) } } throw(`Can't uneval ${E.toQuote(obj)}`) } /** Build a use-occurrence of a variable. */ def genVarUse(varID :(String | int)) :Node { if (varID =~ varName :String) { builder.buildImport(varName) } else { builder.buildIbid(varID) } } /** * The internal recursive routine that will traverse the * subgraph and build a Data-E Node while manipulating the * above state. */ # "bind" resolves a forward declaration bind generate(obj) :Node {
if (unscope.fetch(obj, thunk{}) =~ varID :notNull) { return genVarUse(varID) } def promIndex := builder.buildPromise() unscope[obj] := promIndex def rValue := genObject(obj) builder.buildDefrec(promIndex+1, rValue) } builder.buildRoot(generate(root)) } } } During traversal, for every reference a subgraph recognizer already associates with a variable, whether from the original unscopeMap argument or because it has already been traversed, it builds a reference to that variable. Otherwise, it first builds a new pair of temporary variables for a promise and its resolver, and associates the promise variable as naming the new reference. In that context, it then builds code to generate a reconstruction of that reference. Finally, using defrec it builds code to resolve the previously generated promise to the reconstructed value. Traversal as Uncalling
Once again, most of the code above is plumbing, to hook references up correctly. The actual traversal step where objects are "taken apart" -- the inverse of the builder's E.call(..) step -- is the underlined call to each uncaller. Each uncaller returns either null, indicating a failure to portray the object, or a triple corresponding to the three arguments to E.call(..) -- a receiver, a verb (message name), and a list of arguments. Such a triple portrays the object for purpose of reconstruction. It says that a reconstruction of the object would be an E.call(..) performed in the reconstructing context using (a reconstruction of) the receiver, the verb, and (reconstructions of) the arguments. The uncallerList functions as a search path -- each uncaller is tried until one succeeds or the list is exhausted. If none succeed, then the recognition as a whole is terminated with a thrown exception. The default uncallerList consists of the minimalUncaller shown below and the import__uriGetter: [minimalUncaller, <import>] The minimalUncaller simply asks an object to provide its own portrayal. Our earlier generationCounter is an example of an object that overrides __optUncall() to provide its own self portrait. We say that such an object is transparent -- it provides this portrayal to any of its clients. The minimalUncaller can only portray transparent objects. def minimalUncaller implements Uncaller { to optUncall(obj) :nullOk[__Portrayal] { if (Ref.isNear(obj)) { obj.__optUncall() } else # ... we can ignore the non-Near cases for now } } Other uncallers are for portraying non-transparent objects. Some, such as the import__uriGetter, are a special category of uncaller called a Loader. These also have a .get(String) method that acts as the inverse of their .optUncall(..) method. For example, since StringBuffer is a safe class, it can be imported using the import__uriGetter: ? pragma.syntax("0.8") ? def makeStringBuffer := <import:java.lang.makeStringBuffer> # value: <makeStringBuffer> As explained earlier, the above code uses the URI-expression. It is just syntactic shorthand for: ? def makeStringBuffer := import__uriGetter.get("java.lang.makeStringBuffer") # value: <makeStringBuffer> The resulting object is a maker -- its protocol consists of (the enabled subset of) the public constructors and static methods of the class StringBuffer. That's why we name it makeStringBuffer -- it acts mostly as a function for making StringBuffers. Going the other way ? <import>.optUncall(makeStringBuffer) # value: [<import>, "get", ["java.lang.makeStringBuffer"]] So we see that the import__uriGetter is in effect saying
Loaders will normally follow this pattern, varying only the contents of the string argument. Putting all this together, and remembering that deSrcKit will depict using the URI-expression shorthand when it can, we have ? def makeSurgeon := <elib:serial.makeSurgeon> ? def surgeon := makeSurgeon.withSrcKit("de: ") ? surgeon.serialize(makeStringBuffer) # value: "de: <import:java.lang.makeStringBuffer>" Note that the makeStringBuffer reconstructed by these means isn't necessarily equivalent to the original. Rather, import__uriGetter embodies the policy choice that the reconstruction should be whatever object is importable by the same name in the reconstruction context. If this context represents a different version of the system, in which the object imported by this name acts differently, this policy choice would have us live with the consequences, including the possible failure to reconstruct. This is often the right engineering decision, and corresponds closely to the decisions built into other serialization systems, such as JOSS's handling of classes [ref Shapiro]. We now have all the basic ingredients needed to explain and address the security issues raised by serialization. Corresponding Concepts in Conventional SerializationIn our terminology, like Data-E, JOSS also solicits from each object not its depiction, but its portrayal in terms of other objects. Mallet can only claim to have a reference to Alice by producing a reference to Alice, which he can only do if he actually has such a reference. If an object simply implements Serializable and does nothing else, then its internal implementation doubles as its self-portrait. However, an object can offer a nominated replacement -- another object to be serialized in its stead, whose portrayal thereby serves as the original object's self-portrait. The serializer may use the nominated replacement. Or it may appoint its own replacement, by overriding the replaceObject(..) method of ObjectOutputStream, just as our serializer can appoint its own portrayal by adding an uncaller to the uncaller list. The resulting depiction is a literal picture only of the graph of appointed replacements. JOSS provides similar flexibility during unserialization, with objects offering a nominated resolution to take their place in the unserialized graph, with the unserializer potentially substituting an appointed resolution. Given cyclic graphs and the non-redirectability of Java references, this cannot be implemented correctly in Java. Using promises, we can easily implement the equivalent correctly in E for Data-E (and likewise in any other object-capability language with delayed references), but we haven't yet needed this flexibility during unserialization. |
|||||||||||||||
Unless stated otherwise, all text on this page which is either unattributed or by Mark S. Miller is hereby placed in the public domain.
|