Skip to content

Commit 484a086

Browse files
authored
updates from flat allocation (#402)
* disabling the pager in my pretty printing run script * change the elaboration of `new` and non-local Invocations to match the flat yul object style (#367) * making a change to double check work flow * adding a stub for computing the size of a contract; that'll be its own PR entirely one day fairly soon, but for now, we assume that we just need 32 bytes * using hex values for some boilerplate so that it matches the docs * reworking constructors to just allocate memory * adding some helper functions in util. one is a renaming for transactions from child contracts; the other is basically a type-checked comment pointing out uses of some pretty substantian technical debt * temporarily removing the code to translate child contracts. rewriting the translation of Invocations to remap everything to local invocations instead, into the names that will be created in the flat yul object * removing an assertion and adding translation of string literals * whitespace, scala style * utility function for undoing the transaction renaming * generate flat yul object from child contracts (#369) * rename, add boolean for main-ness in translate decl * changing signature of translateDeclaration to remove a return that doesn't do anything * whitespace, scala style * comments * scraps; adding an assert * changing how child contracts are processed * rewrite of translateTransaction * chainging signature of translateStatement * more threading through inMain * whitespace, scala style * adding some docs * removing the nicer output for typed names in favor of a bland one, per solc's current limitations. adding a comment about why. * adding a temporary fix to the top of the dispatch table pending talking with MC" * removing a stale comment * comments * adding missing declarations to invocations * cleaning up comments and some messy logic around temporary variables * removing comment * more hacks for specific tests in advance of type info * changing hardcoded value in the mustache file for this to be the current contract address * adding a couple of args to get this to typecheck * use type annotations in Yul codegen (#377) * removing a util function to rename functions in the dispatch table; that no longer makes sense with the solution for flattening that we've settled on for now * adding comments; expanding getcontractname * ripping out some code, adding comments * adding a comment that may help to locate a bug later * moving comment closer to the source and updating it * comments * scraps; this change seemed likely but breaks a bunch of tests * quick function to traverse over an expression and check a given predicate on all the annotations * fixing some import dependencies * traversal of a program rather than just an expression; i sure hope i don't have to come back and make this the fully polymorphic map reduce but i bet i will * adding updates to the expression returned in the checker from just the ReferenceIdentifier cases, after some debugging with @mcoblenz * adding additional ParserUtil.updateExprType uses as seems right. bunch of tests fail, some of which i expected some i didn't, and i don't know how to fix a lot of them * updating width calculation to actually inspect the type, now that we know it * removing an assert that caused a bunch of false negatives. * small changes per PR comments * copying a slightly cut down version of linked lists, but this needs to be edited down even more to be the right goal for a demo. * compute the sizes of contracts for allocation (#378) * copying a slightly cut down version of linked lists, but this needs to be edited down even more to be the right goal for a demo. * computing sizes of types recursively * adding some simple hard coded unit tests * copying over a helper from type checker tests to test on actual contracts in files * adding more general tests; it doesn't work but i think i know why * scraps and printlines from trying to debug sizes * changing the type of the size computation function so it has enough information, per MC. reworking tests * renaming size function; fixing the main test * adding some comments and a variable for pointer sizes * formatting, reworking base test * removing the two simpler unit tests. it is hard and somewhat pointless to be the parser and create a contract table by hand, the existing test is informative enough * fixing type checker errors (#380) * debugging scraps * copying a slightly cut down version of linked lists, but this needs to be edited down even more to be the right goal for a demo. * commenting out spammy prints * patch from MC * updating override syntax to not introduce a new field * updating expr type update to set the location and use the one field rather than build new ones * removing printlines * updating logged errors in a few places; this fixes some but not all of #379 * error in resourcesTest was in the test itself; it was incorrectly looking for m to be at int * formatting, whitespace * fixed permission passing test; also errors in the definition of the test, not the checker * fixing all permowned error * scala style, whitespace * scraps * adding a comment, removing a comment, removing an assert * compute offsets, store fields in memory (#384) * fixing a bug in computing sizes by translating from set to list; adding an assert; whitespace and style * adding helper to compute offsets * typoe and adding a test to demonstrate that the bug computing sizes is gone * adding a sandbox test case file * adding a traversal of the declarations sequence in the contract rather than relying on the toList of an unordered collection; using that helper function both in computing sizes and offsets * refactoring tests for util functions to reuse the code to produce a symbol table; adding tests for computing offests * style, whitespace * a couple more tests for offsets * a couple more tests for offsets * updating tests, adding comments for myself * helper to wrap call to field offsets, changing sload and sstore to m* * updating test to show that fields get overwritten; adding json so it gets run because it passes * messing with test files * changing the ganache test script to use the test skipping checking script that i think works across platforms, per #361 * adding sort, per #631 * scala style, fussy fixes to doc strings etc * scala style, fussy fixes to doc strings etc * scala style, fussy fixes to doc strings etc * scala style, fussy fixes to doc strings etc * some house keeping to clean up a util function, removing a source of bugs related to computing sizes * refactoring to change the definition of typed name to have an actual type in it, not just its string representation * adding clause to type name helper for contracts * whitespace in obsidian files * housekeeping, adding docs and removing stale todos * Adding another passing test * updating travis test script to work with solc 0.8.10 * iterating on travis script * allocate fields with pointers, rewrite yulobject and mustache interaction to reflect current object layout (#388) * adding test case for nonprimitive fields in the main contract * adding an ownership to the test field to make it valid obsidian * removing some dead code * removing unused childContracts argument from YulObject * scraps * new test * fixing local util script for new version of solc, adding a little code for #389 but not a complete idea yet * scraps * rewriting yulobject to take an optional int to indicate the size of the main contract and if the contract being elaborated is the main one (if it has as size). this is temporary and not going to last * removing what i am nearly positive is dead code * first half of a big rewrite of the YulObject class * back half of the refactor to update code generation * adding some todos and notes * scraps, scala style and whitespace * scraps * updating the implementation of switch toString to not print out invalid switches with no branches. this fixes the emptycontract dispatch table. * scraps * add the this argument uniformly in codegen not printing, and only remove it for the hashed dispatch table entries * pulling the body of local invocation out into a helper so that it can get called in both places with different arguments * documentation, cleaning up todos * scraps * adding a little more documentation * functions with arguments (#394) * adding test case for nonprimitive fields in the main contract * adding an ownership to the test field to make it valid obsidian * removing some dead code * removing unused childContracts argument from YulObject * scraps * new test * fixing local util script for new version of solc, adding a little code for #389 but not a complete idea yet * scraps * rewriting yulobject to take an optional int to indicate the size of the main contract and if the contract being elaborated is the main one (if it has as size). this is temporary and not going to last * removing what i am nearly positive is dead code * first half of a big rewrite of the YulObject class * back half of the refactor to update code generation * adding some todos and notes * scraps, scala style and whitespace * scraps * updating the implementation of switch toString to not print out invalid switches with no branches. this fixes the emptycontract dispatch table. * scraps * add the this argument uniformly in codegen not printing, and only remove it for the hashed dispatch table entries * pulling the body of local invocation out into a helper so that it can get called in both places with different arguments * documentation, cleaning up todos * scraps * renaming some files * removing half baked linked list test * typo * adding json so this test gets run in Travis * translate constrctors to transactions on the flattened object (#396) * updating test case so that it compiled and hits missing code * Adding new test cases * adding code so that constructors get emitted, named with a hash of their arguments so that objecst with multiple consturctors can call whichever one * fixed constructors with arguments * updating ganache test suite with a few constructor examples * adding code to constructor elaboration to not generate a call to a constructor that doesn't exist * monkeying around with the install script * monkeying around with the install script * monkeying around with the install script * monkeying around with the install script * monkeying with travis more * adding version info to output * Adding debugging output * debugging output * monkeying with the host name * test script * trying running ganache on localhost directly * following some shellcheck fixes * moving npm commands around * checking for ganache in the processes * unhiding ganache output * downgrading node to LTS version 16 * moving some install commands around, trying to get a lower version of node * adding possible node work around * env vars * undoing env vars, since the 16 now got picked up * removing debug messages * removing the ganache install script since that's in travis.yml now * scraps * support integer arguments to the main function (#400) * adding a test case to show that an old bug got fixed. closes #334 * adding a new test case to show that arguments are not currently passed to main * adding a different presentation of the tests info while i'm thinking of it * fixing a bad change to IDE settings * adding a yul statement for comments * adding helpers to compute abi decoder functions and insert them into the dispatch table and emit them in the body of the object * updating test cases * removing old test * removing old test * code to decode individual ints, using that to decode tuples, emitting it in the output file * i forget to change the name of the contract every single time i copy a test * traveseing the params not the returns * renaming, scraps * fixing an error in the ABI names we map to * removing a todo " * scraps, scala style * adding parameters to the json for the two tests that use them; the technical debt here is quickly becoming too much but i want to make sure this works before doing a pass at rewriting the test harness * removing duplicate decoders from output, only assigning params to locals if there are more than 0 of them. this should make the old tests pass again * using distinct instead of hard to read translations to and from set * Adding some documentation and removing some todos * fixing json for mainargs1, updating test script to read json for the two new tests in a slightly hacky and specific way * increasing the padding size on arguments * test.json is kind of part of a rewrite of the test infrastructure and not really part of this PR. so it doesn't belong in this branch anyway AND is breaking the tests * removing some dead boilerplate * updating the padding to the right length in the test script; removing a dead call to decode * scala style and whitespace * scraps, comments
1 parent 50ada69 commit 484a086

File tree

12 files changed

+275
-49
lines changed

12 files changed

+275
-49
lines changed

.idea/misc.xml

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Obsidian_Runtime/src/main/yul_templates/object.mustache

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -34,16 +34,11 @@ object "{{contractName}}" {
3434
{{! these functions for memory management are produced by the solc IR backend for
3535
Solidity programs analagous to our test Obsidian programs.
3636
}}
37-
function abi_decode_tuple(headStart, dataEnd) {
38-
if slt(sub(dataEnd, headStart), 0) { revert(0, 0) }
39-
}
40-
41-
function abi_decode_t_uint256_fromMemory(offset, end) -> value {
42-
value := mload(offset)
43-
}
4437
4538
{{abiEncodeTupleFuncs}}
4639
40+
{{abiDecodeFuncs}}
41+
4742
function allocate_memory(size) -> memPtr {
4843
memPtr := allocate_unbounded()
4944
finalize_allocation(memPtr, size)
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"gas" : 30000000,
3+
"gasprice" : "0x9184e72a000",
4+
"startingeth" : 5000000,
5+
"numaccts" : 1,
6+
"testexp" : "f()",
7+
"expected" : "8"
8+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
main contract Return2 {
2+
transaction f() returns int{
3+
return (4+4);
4+
}
5+
transaction g(){
6+
f();
7+
return;
8+
}
9+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"gas" : 30000000,
3+
"gasprice" : "0x9184e72a000",
4+
"startingeth" : 5000000,
5+
"numaccts" : 1,
6+
"testexp" : null,
7+
"expected" : "5",
8+
"method_name" : "main",
9+
"method_signature" : "int256",
10+
"method_params" : [3]
11+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
contract IntContainer{
2+
int x;
3+
4+
IntContainer@Owned(int init) {
5+
x = init;
6+
}
7+
8+
transaction set(int value) {
9+
x = value;
10+
}
11+
transaction get() returns int{
12+
return x;
13+
}
14+
}
15+
16+
main contract SetGetMainArgs1{
17+
transaction main(int fromclient) returns int{
18+
IntContainer ic = new IntContainer(fromclient);
19+
return (ic.get() + 2);
20+
}
21+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"gas" : 30000000,
3+
"gasprice" : "0x9184e72a000",
4+
"startingeth" : 5000000,
5+
"numaccts" : 1,
6+
"testexp" : null,
7+
"expected" : "8",
8+
"method_name" : "main",
9+
"method_signature" : "int256,int256,int256",
10+
"method_params" : [3, 2, 1]
11+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
contract IntContainer{
2+
int x;
3+
4+
IntContainer@Owned(int init) {
5+
x = init;
6+
}
7+
8+
transaction set(int value) {
9+
x = value;
10+
}
11+
transaction get() returns int{
12+
return x;
13+
}
14+
}
15+
16+
main contract SetGetMainArgs3{
17+
transaction main(int fc1, int fc2, int fc3) returns int{
18+
IntContainer ic = new IntContainer(fc1 + fc2 + fc3);
19+
return (ic.get() + 2);
20+
}
21+
}

src/main/scala/edu/cmu/cs/obsidian/codegen/CodeGenYul.scala

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -393,9 +393,6 @@ object CodeGenYul extends CodeGenerator {
393393

394394
// the result is the recursive translation and the expression either using the temp
395395
// here or not.
396-
397-
// todo: this does not work with non-void functions that are called without binding
398-
// their results, ie "f()" if f returns an int
399396
ids.map(id => decl_0exp(id)) ++
400397
seqs.flatten ++ (width match {
401398
case 0 => Seq(ExpressionStatement(FunctionCall(Identifier(name), thisID +: ids)))
@@ -513,17 +510,17 @@ object CodeGenYul extends CodeGenerator {
513510
// arguments and invoke the constructor as normal transaction with the hash appended
514511
// to the name to call the right one
515512
val conCall =
516-
if (checkedTable.contract(contractType.contractName).get.contract.declarations.exists(d => isMatchingConstructor(d))) {
517-
translateInvocation(name = transactionNameMapping(contractType.contractName, contractType.contractName) + hashOfFunctionName(contractType.contractName, typeNames),
518-
args = args,
519-
obstype = Some(UnitType()),
520-
thisID = id_memaddr,
521-
retvar = retvar, contractName = contractName, checkedTable = checkedTable, inMain = inMain)
522-
} else {
523-
Seq()
524-
}
513+
if (checkedTable.contract(contractType.contractName).get.contract.declarations.exists(d => isMatchingConstructor(d))) {
514+
translateInvocation(name = transactionNameMapping(contractType.contractName, contractType.contractName) + hashOfFunctionName(contractType.contractName, typeNames),
515+
args = args,
516+
obstype = Some(UnitType()),
517+
thisID = id_memaddr,
518+
retvar = retvar, contractName = contractName, checkedTable = checkedTable, inMain = inMain)
519+
} else {
520+
Seq()
521+
}
525522

526-
Seq(// grab the appropriate amount of space of memory sequentially, off the free memory pointer
523+
Seq( // grab the appropriate amount of space of memory sequentially, off the free memory pointer
527524
decl_1exp(id_memaddr, apply("allocate_memory", intlit(sizeOfContractST(contractType.contractName, checkedTable)))),
528525

529526
// return the address that the space starts at

src/main/scala/edu/cmu/cs/obsidian/codegen/Util.scala

Lines changed: 96 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ object Util {
182182
def baseTypeToYulName(typ: ObsidianType): String = {
183183
typ match {
184184
case primitiveType: PrimitiveType => primitiveType match {
185-
case IntType() => "u256"
185+
case IntType() => "int256"
186186
case BoolType() => "bool"
187187
case StringType() => "string"
188188
case Int256Type() => "int256"
@@ -242,7 +242,6 @@ object Util {
242242
* no spaces are used"
243243
*/
244244
def hashOfFunctionName(name: String, types: Seq[String]): String = {
245-
// todo: the keccak256 implementation seems to agree with solc, but it's never been run on functions with arguments.
246245
keccak256(name + paren(types.mkString(",")))
247246
}
248247

@@ -422,12 +421,23 @@ object Util {
422421
*/
423422
def dropThisArgument(f: FunctionDefinition): FunctionDefinition = {
424423
f.parameters match {
424+
// todo: string type is a temporary hack here
425425
case TypedName("this", StringType()) :: tl => FunctionDefinition(f.name, tl, f.returnVariables, f.body)
426426
case _ :: _ => throw new RuntimeException("dropping `this` argument from a sequence of args that doesn't start with `this`")
427427
case _ => throw new RuntimeException("dropping argument from empty list")
428428
}
429429
}
430430

431+
432+
/** given an integer, return the name of the abi tuple encoder for that integer
433+
*
434+
* @param n the size of the tuples encoded
435+
* @return the name of the function used in the output
436+
*/
437+
def abi_encode_name(n: Int): String = {
438+
s"abi_encode_tuple_to_fromStack${n.toString}"
439+
}
440+
431441
/**
432442
* compute the abi tuple encode function for a given number of returns. for example, for 0,
433443
* 1, and 2 returns:
@@ -456,16 +466,98 @@ object Util {
456466
* @param n the number of returns
457467
* @return the function definition for output
458468
*/
459-
def write_abi_encode(n: Int): FunctionDefinition = {
469+
def write_abi_encode_tuple_from_stack(n: Int): FunctionDefinition = {
460470
val var_indices: Seq[Int] = Seq.tabulate(n)(i => i)
461471
val encode_lines: Seq[YulStatement] = var_indices.map(i =>
462472
ExpressionStatement(apply("abi_encode_t_uint256_to_t_uint256_fromStack",
463473
Identifier("value" + i.toString),
464474
apply("add", Identifier("headStart"), intlit((n - 1) * 32)))))
465475

466476
val bod: Seq[YulStatement] = assign1(Identifier("tail"), apply("add", Identifier("headStart"), intlit(32 * n))) +: encode_lines
467-
FunctionDefinition("abi_encode_tuple_to_fromStack" + n.toString,
477+
FunctionDefinition(abi_encode_name(n),
468478
TypedName("headStart", IntType()) +: var_indices.map(i => TypedName("value" + i.toString, IntType())),
469479
Seq(TypedName("tail", IntType())), Block(bod))
470480
}
481+
482+
/** given an function definition, return the name of the abi tuple decode for that functions
483+
* arugments
484+
*
485+
* @param f the function whose arguments are to be decoded
486+
* @return the name of the function that will be emitted to decode the arguments
487+
*/
488+
def abi_decode_tuple_name(f: FunctionDefinition): String = {
489+
s"abi_decode_tuple_${f.parameters.map(tn => tn.typ.toString).mkString}"
490+
}
491+
492+
/** Given an obsidian type, produce the name of the function that will be emitted to decode
493+
* values of the corresponding yul type as parameters
494+
*
495+
* @param t the obsidian type to decode
496+
* @return the name of the function that does the decoding
497+
*/
498+
def abi_decode_name(t: ObsidianType): String = {
499+
s"abi_decode_${t.baseTypeName}"
500+
}
501+
502+
/** Given an obsidian type, produce the function to emit to decode
503+
* values of the corresponding yul type as parameters
504+
*
505+
* @param t the obsidian type to decode
506+
* @return the yul function that does the decoding
507+
*/
508+
def write_abi_decode(t: ObsidianType): FunctionDefinition = {
509+
val offset = TypedName("offset", IntType())
510+
val end = TypedName("end", IntType())
511+
val ret = TypedName("ret", t)
512+
513+
val bod = t match {
514+
case primitiveType: PrimitiveType => primitiveType match {
515+
case IntType() =>
516+
Seq(
517+
//value := calldataload(offset)
518+
assign1(Identifier(ret.name), apply("calldataload", Identifier(offset.name)))
519+
)
520+
case BoolType() => throw new RuntimeException(s"abi decoding not implemented for ${t.toString}")
521+
case StringType() => throw new RuntimeException(s"abi decoding not implemented for ${t.toString}")
522+
case Int256Type() => throw new RuntimeException(s"abi decoding not implemented for ${t.toString}")
523+
case UnitType() => throw new RuntimeException(s"abi decoding not implemented for ${t.toString}")
524+
}
525+
case _: NonPrimitiveType => throw new RuntimeException(s"abi decoding not implemented for ${t.toString}")
526+
case BottomType() => throw new RuntimeException(s"abi decoding not implemented for ${t.toString}")
527+
}
528+
529+
FunctionDefinition(name = abi_decode_name(t),
530+
parameters = Seq(offset, end),
531+
returnVariables = Seq(ret),
532+
body = Block(bod))
533+
}
534+
535+
/** Given a function definition, provide a function that decodes parameters of the argument type
536+
* from the ABI.
537+
*
538+
* @param f the function to produce a parameter decoder for
539+
* @return the decoder for the parameters of the argument function
540+
*/
541+
def write_abi_decode_tuple(f: FunctionDefinition): FunctionDefinition = {
542+
val retVars: Seq[TypedName] = f.parameters.zipWithIndex.map { case (tn, i) => TypedName(s"ret${i.toString}", tn.typ) }
543+
544+
val start = TypedName("start", IntType())
545+
val end = TypedName("end", IntType())
546+
547+
val offsets: Seq[Int] = f.parameters.scanLeft(0)({ (acc, tn) => acc + sizeOfObsType(tn.typ) })
548+
549+
val bod: Seq[YulStatement] =
550+
// if slt(sub(end, start), SUM_OF_SIZES) { revert(0,0) }
551+
revertIf(apply("slt", apply("sub", Identifier(end.name), Identifier(start.name)), intlit(offsets.last))) +:
552+
// for each argument, `value0 := abi_decode_TYPE(add(headStart, offset), dataEnd)`
553+
f.parameters.zipWithIndex.zip(offsets).map {
554+
case ((tn, i), off) =>
555+
assign1(Identifier(s"ret${i.toString}"), apply(abi_decode_name(tn.typ), apply("add", Identifier(start.name), intlit(off)), Identifier(end.name)))
556+
}
557+
558+
FunctionDefinition(name = abi_decode_tuple_name(f),
559+
parameters = Seq(start, end),
560+
returnVariables = retVars,
561+
body = Block(bod))
562+
}
471563
}

0 commit comments

Comments
 (0)