How to avoid call-stack attack in the case of absence of EIP-150? - solidity

While before EIP-150, could we avoid the call-stack attack by checking return value, of low-level functions .send(), .call(), .delegatecall() and .staticcall(), whether is false or not?
For example (msg.sender is a contract):
...
msg.sender.send(amount);
...
changing to:
...
if(!msg.sender.send(amount)) revert Error("Call failed!");
...
Whole contract in:
https://hackernoon.com/smart-contract-attacks-part-2-ponzi-games-gone-wrong-d5a8b1a98dd8

I found the answer: Nope. Because, in this attack, call-stack slots are filled before execution reaches return of calling contract.
A way of preventing could be calculating expected amount of required gas for called function; setting the gas amount of calling function with respect to this.

Related

How are "special" return values that signal a condition called?

Suppose I have a function which calculates a length and returns it as a positive integer, but could also return -1 for timeout, -2 for "cannot compute", and -3 for invalid arguments.
Notwithstanding any discussion on best practices, proper exceptions, and whatnot, this occurs regularly in legacy codebases. What is the name for this practice or for return values which are outside of the normal output value range, -1 being the most common?
Exceptions vs. status returns article refers to them as return status codes:
Broadly speaking, there are two ways to handle errors as they pass
from layer to layer in software: throwing exceptions and returning
status codes...
With status returns, a valuable channel of communication (the return
value of the function) has been taken over for error handling.
Personally I would also call them status codes, similarly to HTTP status codes (if we pretend HTTP response is like a function return).
As a side note, beside exceptions and return status codes, there also exists a monadic approach to error handling, which in some sense combines the former two approaches. For example, in Scala, Either monad may be used to specify a return value that can express both an error status code and a regular happy value without having to block out part of the domain for status codes:
def divide(a: Double, b: Double): Either[String, Double] =
if (b == 0.0) Left("Division by zero") else Right(a / b)
divide(4,0)
divide(4,2)
which outputs
res0: Either[String,Double] = Left(Division by zero)
res1: Either[String,Double] = Right(2.0)
That's an example of a "magic" value. I don't know of any more specific term for when this idea is applied to a function's return value.

If-else statements to cut down processing time

Suppose I have a number of possible inputs from the user of my program listed from most likely to least as input1, input2, input3,...,inputN. Would the following framework cut down on processing time by accessing the most probable If statement needed first and then ignoring the rest (rather than testing the validity of each If statement thereafter)? I assume the least probable inputN will be extra burdensome on the processor, but the limited likelihood of the user giving that input makes it worth it if this structure reduces processing time overall.
If (input1) then (output1)
Else
If (input2) then (output2)
Else
If (input3) then:(output3)
Else
If ...
... Else
OutputN
Thanks!
This is how if-else-if statements work.
if(booleanTest1)
{
//do a thing
}
else if(booleanTest2)
{
//do another thing
}
//...ad infinitum
else
{
//do default behavior
}
If booleanTest1 is true, we execute its code, and then skip past all the other tests.
If you're comparing one variable against many possible values, use a switch statement.
I do not know for sure, but I'd assume, that a switch-case wolud be more efficient during runtime, because of branch prediction. With If-elses you have many branches, that might go wrong, which is not good for the piped commands in the processor que.
If there are really a lot of possibilities.
I usually do ist with a map / dictionary of <Key, Method to call>. As long as they have the same signature, this might work. It may not be as fast as a switch-case, but it will grant you some flexilibity, when you need to react to new inputs.
example:
Dictionary myDic = new Dictionary();
myDic.Add(input1,() => What ever to do when input1 comes);
the call the looks like this:
myDicinput1;

Reliable clean-up in Mathematica

For better or worse, Mathematica provides a wealth of constructs that allow you to do non-local transfers of control, including Return, Catch/Throw, Abort and Goto. However, these kinds of non-local transfers of control often conflict with writing robust programs that need to ensure that clean-up code (like closing streams) gets run. Many languages provide ways of ensuring that clean-up code gets run in a wide variety of circumstances; Java has its finally blocks, C++ has destructors, Common Lisp has UNWIND-PROTECT, and so on.
In Mathematica, I don't know how to accomplish the same thing. I have a partial solution that looks like this:
Attributes[CleanUp] = {HoldAll};
CleanUp[body_, form_] :=
Module[{return, aborted = False},
Catch[
CheckAbort[
return = body,
aborted = True];
form;
If[aborted,
Abort[],
return],
_, (form; Throw[##]) &]];
This certainly isn't going to win any beauty contests, but it also only handles Abort and Throw. In particular, it fails in the presence of Return; I figure if you're using Goto to do this kind of non-local control in Mathematica you deserve what you get.
I don't see a good way around this. There's no CheckReturn for instance, and when you get right down to it, Return has pretty murky semantics. Is there a trick I'm missing?
EDIT: The problem with Return, and the vagueness in its definition, has to do with its interaction with conditionals (which somehow aren't "control structures" in Mathematica). An example, using my CleanUp form:
CleanUp[
If[2 == 2,
If[3 == 3,
Return["foo"]]];
Print["bar"],
Print["cleanup"]]
This will return "foo" without printing "cleanup". Likewise,
CleanUp[
baz /.
{bar :> Return["wongle"],
baz :> Return["bongle"]},
Print["cleanup"]]
will return "bongle" without printing cleanup. I don't see a way around this without tedious, error-prone and maybe impossible code-walking or somehow locally redefining Return using Block, which is heinously hacky and doesn't actually seem to work (though experimenting with it is a great way to totally wedge a kernel!)
Great question, but I don't agree that the semantics of Return are murky; They are documented in the link you provide. In short, Return exits the innermost construct (namely, a control structure or function definition) in which it is invoked.
The only case in which your CleanUp function above fails to cleanup from a Return is when you directly pass a single or CompoundExpression (e.g. (one;two;three) directly as input to it.
Return exits the function f:
In[28]:= f[] := Return["ret"]
In[29]:= CleanUp[f[], Print["cleaned"]]
During evaluation of In[29]:= cleaned
Out[29]= "ret"
Return exits x:
In[31]:= x = Return["foo"]
In[32]:= CleanUp[x, Print["cleaned"]]
During evaluation of In[32]:= cleaned
Out[32]= "foo"
Return exits the Do loop:
In[33]:= g[] := (x = 0; Do[x++; Return["blah"], {10}]; x)
In[34]:= CleanUp[g[], Print["cleaned"]]
During evaluation of In[34]:= cleaned
Out[34]= 1
Returns from the body of CleanUp at the point where body is evaluated (since CleanUp is HoldAll):
In[35]:= CleanUp[Return["ret"], Print["cleaned"]];
Out[35]= "ret"
In[36]:= CleanUp[(Print["before"]; Return["ret"]; Print["after"]),
Print["cleaned"]]
During evaluation of In[36]:= before
Out[36]= "ret"
As I noted above, the latter two examples are the only problematic cases I can contrive (although I could be wrong) but they can be handled by adding a definition to CleanUp:
In[44]:= CleanUp[CompoundExpression[before___, Return[ret_], ___], form_] :=
(before; form; ret)
In[45]:= CleanUp[Return["ret"], Print["cleaned"]]
During evaluation of In[46]:= cleaned
Out[45]= "ret"
In[46]:= CleanUp[(Print["before"]; Return["ret"]; Print["after"]),
Print["cleaned"]]
During evaluation of In[46]:= before
During evaluation of In[46]:= cleaned
Out[46]= "ret"
As you said, not going to win any beauty contests, but hopefully this helps solve your problem!
Response to your update
I would argue that using Return inside If is unnecessary, and even an abuse of Return, given that If already returns either the second or third argument based on the state of the condition in the first argument. While I realize your example is probably contrived, If[3==3, Return["Foo"]] is functionally identical to If[3==3, "foo"]
If you have a more complicated If statement, you're better off using Throw and Catch to break out of the evaluation and "return" something to the point you want it to be returned to.
That said, I realize you might not always have control over the code you have to clean up after, so you could always wrap the expression in CleanUp in a no-op control structure, such as:
ret1 = Do[ret2 = expr, {1}]
... by abusing Do to force a Return not contained within a control structure in expr to return out of the Do loop. The only tricky part (I think, not having tried this) is having to deal with two different return values above: ret1 will contain the value of an uncontained Return, but ret2 would have the value of any other evaluation of expr. There's probably a cleaner way to handle that, but I can't see it right now.
HTH!
Pillsy's later version of CleanUp is a good one. At the risk of being pedantic, I must point out a troublesome use case:
Catch[CleanUp[Throw[23], Print["cleanup"]]]
The problem is due to the fact that one cannot explicitly specify a tag pattern for Catch that will match an untagged Throw.
The following version of CleanUp addresses that problem:
SetAttributes[CleanUp, HoldAll]
CleanUp[expr_, cleanup_] :=
Module[{exprFn, result, abort = False, rethrow = True, seq},
exprFn[] := expr;
result = CheckAbort[
Catch[
Catch[result = exprFn[]; rethrow = False; result],
_,
seq[##]&
],
abort = True
];
cleanup;
If[abort, Abort[]];
If[rethrow, Throw[result /. seq -> Sequence]];
result
]
Alas, this code is even less likely to be competitive in a beauty contest. Furthermore, it wouldn't surprise me if someone jumped in with yet another non-local control flow that that this code will not handle. Even in the unlikely event that it handles all possible cases now, problematic cases could be introduced in Mathematica X (where X > 7.01).
I fear that there cannot be a definitive answer to this problem until Wolfram introduces a new control structure expressly for this purpose. UnwindProtect would be a fine name for such a facility.
Michael Pilat provided the key trick for "catching" returns, but I ended up using it in a slightly different way, using the fact that Return forces the return value of a named function as well as control structures like Do. I made the expression that is being cleaned up after into the down-value of a local symbol, like so:
Attributes[CleanUp] = {HoldAll};
CleanUp[expr_, form_] :=
Module[{body, value, aborted = False},
body[] := expr;
Catch[
CheckAbort[
value = body[],
aborted = True];
form;
If[aborted,
Abort[],
value],
_, (form; Throw[##]) &]];

Need help in understanding kcachedgrind output

I am using valgrind callgrind to profile a program on gtk. And then I use kcachedgrind to read the result. I have captured an update a screenshot of kcachedgrind here: http://i41.tinypic.com/168spk0.jpg. It said the function gtk_moz_embed_new() costed '15.61%'.
But I dont understand how is that possible. the function gtk_moz_embed_new() literally has 1 line: and it is just calling a g_object_new().
GtkWidget *
gtk_moz_embed_new(void)
{
return GTK_WIDGET(g_object_new(GTK_TYPE_MOZ_EMBED, NULL));
}
Can you please help understanding the result or how to use kcachedgrind.
Thank you.
If i remember correctly that should mean (more or less) that function gtk_moz_embed_new() was executing 15.61% of the time the the app was running.
You see, that function returns an inline call to other functions (or classes or whatever) that also take time to execute. When they are all done it's then that the function gtk_moz_embed_new() acutally returns a value. The very same reason it takes main() 99% of the time to execute, it finisesh execution after all included code in it is executed.
Note that self value for the gtk_moz_embed_new() is 0 which is "exclusive cost" meaning that function it self did not really took any time to execute (it's really only a return call)
But to be exact:
1.1 What is the difference between 'Incl.' and 'Self'?
These are cost attributes for
functions regarding some event type.
As functions can call each other, it
makes sense to distinguish the cost of
the function itself ('Self Cost') and
the cost including all called
functions ('Inclusive Cost'). 'Self'
is sometimes also referred to as
'Exclusive' costs.
So e.g. for main(), you will always
have a inclusive cost of almost 100%,
whereas the self cost is neglectable
when the real work is done in another
function.

Is it possible to compare two Objective-C blocks by content?

float pi = 3.14;
float (^piSquare)(void) = ^(void){ return pi * pi; };
float (^piSquare2)(void) = ^(void){ return pi * pi; };
[piSquare isEqualTo: piSquare2]; // -> want it to behave like -isEqualToString...
To expand on Laurent's answer.
A Block is a combination of implementation and data. For two blocks to be equal, they would need to have both the exact same implementation and have captured the exact same data. Comparison, thus, requires comparing both the implementation and the data.
One might think comparing the implementation would be easy. It actually isn't because of the way the compiler's optimizer works.
While comparing simple data is fairly straightforward, blocks can capture objects-- including C++ objects (which might actually work someday)-- and comparison may or may not need to take that into account. A naive implementation would simply do a byte level comparison of the captured contents. However, one might also desire to test equality of objects using the object level comparators.
Then there is the issue of __block variables. A block, itself, doesn't actually have any metadata related to __block captured variables as it doesn't need it to fulfill the requirements of said variables. Thus, comparison couldn't compare __block values without significantly changing compiler codegen.
All of this is to say that, no, it isn't currently possible to compare blocks and to outline some of the reasons why. If you feel that this would be useful, file a bug via http://bugreport.apple.com/ and provide a use case.
Putting aside issues of compiler implementation and language design, what you're asking for is provably undecidable (unless you only care about detecting 100% identical programs). Deciding if two programs compute the same function is equivalent to solving the halting problem. This is a classic consequence of Rice's Theorem: Any "interesting" property of Turing machines is undecidable, where "interesting" just means that it's true for some machines and false for others.
Just for fun, here's the proof. Assume we can create a function to decide if two blocks are equivalent, called EQ(b1, b2). Now we'll use that function to solve the halting problem. We create a new function HALT(M, I) that tells us if Turing machine M will halt on input I like so:
BOOL HALT(M,I) {
return EQ(
^(int) {return 0;},
^(int) {M(I); return 0;}
);
}
If M(I) halts then the blocks are equivalent, so HALT(M,I) returns YES. If M(I) doesn't halt then the blocks are not equivalent, so HALT(M,I) returns NO. Note that we don't have to execute the blocks -- our hypothetical EQ function can compute their equivalence just by looking at them.
We have now solved the halting problem, which we know is not possible. Therefore, EQ cannot exist.
I don't think this is possible. Blocks can be roughly seen as advanced functions (with access to global or local variables). The same way you cannot compare functions' content, you cannot compare blocks' content.
All you can do is to compare their low-level implementation, but I doubt that the compiler will guarantee that two blocks with the same content share their implementation.