Understanding heisenbug example: "Debuggers cause additional source code to be executed stealthily" - terminology

I read wikipedia page about heisunbug, but don't understand this example. Can anyone explain it in detail?
Debuggers also commonly provide watches or other user interfaces that cause additional source code (such as property accessors) to be executed stealthily, which can, in turn, change the state of the program.

I think what it's getting at is that the debugger itself may call code (such as getters) to retrieve the value of a property you might have placed a watch on.
Consider the getter:
def getter fahrenheit:
return celsius * 9 / 5 + 32;
and what would happen if you put a watch on the fahrenheit property.
That code would normally only be called if your code itself tried to access the fahrenheit propery but, if a debugger is calling it to maintain the watch, it may be called outside of the control of your program.
A simple example, let's say the getter has a (pretty obvious) bug which means that it returns the wrong result the first time it's called:
class temperature:
variable state
def init:
state = 1
def getter fahrenheit:
if state == 1:
state = 0
return -42
return celsius * 9 / 5 + 32;
So running your code without a debugger exhibits a problem in that it will return a weird value the first time your code calls it.
But, if your debugger is actually calling the getter to extract a value that it's watching (and it's probably doing this after every single-step operation you perform), that means the getter will be well and truly returning the correct value by the time your code calls it for what it thinks is the first time.
Hence the problem will disappear when you try to look closer at it, and that's the very definition of a Heisenbug, despite the fact that Heisenberg's actual uncertainty principle has little to do with the observer effect.

Related

What is really happening when using variables?

I have a really basic question about something that I've never paid much attention to until now:
I noticed that when creating a function (in JS or Python) that uses a variable from the outer scope, the function is not defined using the value of the variable but rather the variable itself. So if I change the value of the variable the function will use the new value.
This is what I mean
let a = 10;
function printA(){
console.log(a);
}
printA(); // => 10
a = 20;
printA(); // => 20
a = 10
def printA():
print(a)
printA() # => 10
a = 20
printA() # => 20
I thought this was only going to work of objects because of the way you can modify an object inside a function but not primitive variables because there's no way to change their value without reasigning them. I guess this is a different story.
What I'm trying to understand is: when typing a variable name is typing its memory address what I'm really doing? Does this happen with all languages?
when I create a function like printA() that uses a variable that is not an argument, is the variable bound forever to the function by its address?
The variable a is "captured" by the function. The specifics of how that happens are usually implementation details and may result in the compiler/interpreter producing code that doesn't much resemble the original.
For instance, in C# (I know, not one of the languages you mentioned, but it's the one I'm most familiar with), the compiler will create a separate hidden class which actually contains fields for the variables that are captured by a lambda or nested function. It then accesses these fields rather than plain variables.
by its address
Variables don't typically have an address. For instance, every time you call a method, it will typically have an "activation record" of some kind created, that will typically contain its variables. But note that these records are not at some fixed location, which is how you can have parallel execution of methods, recursion, etc, without interference. (Some older BASICs did have fixed activation records, which is why they didn't allow for recursion). These activation records may typically be placed on some kind of stack.
But as I say, for captured variables, the compiler will typically need to do even more so that those variables aren't just stored in an activation record, and so that their lifetime is no longer tied to a single call.

When is passing a subprogram as a parameter necessary

I've been reading a Concepts of Programming Languages by Robert W. Sebesta and in chapter 9 there is a brief section on passing a SubProgram to a function as a parameter. The section on this is extremely brief, about 1.5 pages, and the only explanation to its application is:
When a subprogram must sample some mathematical function. Such as a Subprogram that does numerical integration by estimating the area under a graph of a function by sampling the function at a number of different points. Such a Subprogram should be usable everywhere.
This is completely off from anything I have ever learned. If I were to approach this problem in my own way I would create a function object and create a function that accomplishes the above and accepts function objects.
I have no clue why this is a design issue for languages because I have no idea where I would ever use this. A quick search hasn't made this any clearer for me.
Apparently you can accomplish this in C and C++ by utilizing pointers. Languages that allow nested Subprograms such as JavaScript allow you do do this in 3 separate ways:
function sub1() {
var x;
function sub2() {
alert( x ); //Creates a dialog box with the value of x
};
function sub3() {
var x;
x = 3;
sub4( sub2 ); //*shallow binding* the environment of the
//call statement that enacts the passed
//subprogram
};
function sub4( subx ) {
var x;
x = 4;
subx();
};
x=1;
sub3();
};
I'd appreciate any insight offered.
Being able to pass "methods" is very useful for a variety of reasons. Among them:
Code which is performing a complicated operation might wish to provide a means of either notifying a user of its progress or allowing the user to cancel it. Having the code for the complicated operation has to do those actions itself will both add complexity to it and also cause ugliness if it's invoked from code which uses a different style of progress bar or "Cancel" button. By contrast, having the caller supply an UpdateStatusAndCheckCancel() method means that the caller can supply a method which will update whatever style of progress bar and cancellation method the caller wants to use.
Being able to store methods within a table can greatly simplify code that needs to export objects to a file and later import them again. Rather than needing to have code say
if (ObjectType == "Square")
AddObject(new Square(ObjectParams));
else if (ObjectType == "Circle")
AddObject(new Circle(ObjectParams));`
etc. for every kind of object
code can say something like
if (ObjectCreators.TryGetValue(ObjectType, out factory))
AddObject(factory(ObjectParams));
to handle all kinds of object whose creation methods have been added to ObjectCreators.
Sometimes it's desirable to be able to handle events that may occur at some unknown time in the future; the author of code which knows when those events occur might have no clue about what things are supposed to happen then. Allowing the person who wants the action to happen to give a method to the code which will know when it happens allows for that code to perform the action at the right time without having to know what it should do.
The first situation represents a special case of callback where the function which is given the method is expected to only use it before it returns. The second situation is an example of what's sometimes referred to as a "factory pattern" or "dependency injection" [though those terms are useful in some broader contexts as well]. The third case is commonly handled using constructs which frameworks refer to as events, or else with an "observer" pattern [the observer asks the observable object to notify it when something happens].

Invalid method when method is valid

I have just started a new version of my Crysis Wars Server Side Modification called InfinityX. For better management, I have put the functions inside tables as it looks neater and I can group functions together (like Core.PlayerHandle:GetIp(player)), but I have ran into a problem.
The problem is that the specified method to get the players' name, player:GetName() is being seen as an invalid method, when the method actually is completely valid.
I would like to know if using the below structure is causing a problem and if so, how to fix it. This is the first time I've used this structure for functions, but it is already proving easier than the old method I was using.
The Code:
Event =
{
PlayerConnect = function(player)
Msg.All:CenteredConsole("$4Event$8 (Connect)$9: $3"..player:GetName().." on channel "..player.actor:GetChannel());
System.LogAlways(Default.Tag.."Incoming Connect on Channel "..player.actor:GetChannel());
Event:Log("Connect", player);
end;
};
The below code works when I bypass the function and put the code directly where it's needed:
Msg.All:CenteredConsole("$4Event$8 (Connect)$9: $3"..player:GetName().." on channel "..player.actor:GetChannel());
System.LogAlways(Default.Tag.."Incoming Connect on Channel "..player.actor:GetChannel());
The Error:
[Warning] [Lua Error] infinityx/main/core.events.lua:23: attempt to call method 'GetName' (a nil value)
PlayerConnect, (infinityx/main/core.events.lua: 23)
ConnectScript, (infinityx/main/core.main.lua: 52)
OnClientEnteredGame, (scripts/gamerules/instantaction.lua: 511)
(null) (scripts/gamerules/teaminstantaction.lua: 520)
Any clarification would be appreciated.
Thanks :)
Well, as PlayerConnect is inside the table Event, and you are calling with a ":", add self as first arg in the function, like:
PlayerConnect = function(self, player)
Clearly, player in the first block of code is not the same as player in the second block of code. The problem must be that the caller of Event.PlayerConnect is not passing the same value.
To test that your Event.PlayerConnect function works, try this in the same place as your second block of code:
Event.PlayerConnect(player)
That should work as you expect.
So, the problem comes down to how Event.PlayerConnect is called without the second block of code. I'm not familiar with that game engine so I don't know how it is done. Perhaps reviewing the documentation and/or debugging that area would help. If you print(player) or call the equivalent log function in both cases, you should see they are different. If you can't run in a debugger, you can still get a stack trace with print(debug.traceback("Accessing player, who's value is: "..player)). If there is indeed some kind of table-based player object in both cases, you can try comparing their fields to see how they are different. You might need to write a simple dumping function to help with that.

How would Object.defineProperty be in AS3?

I'm an architect from a strong JavaScript background, but I did some .NET and Java in the past.
However, I wanted to put a hand on ActionScript3, which I was promised that is very related to JavaScript.
As a startup project I took on myself to try port to ActionScript3 one of my favorite assertion utils - should.js - that makes your test codes really pleasant to read.
Updated: 2013-02-19
I saw I confuse with my abstract speaking, so I replaced some of the post with the concrete question in mind.
Here's the full picture:
Consider the following JavaScript code:
Object.defineProperty(Object.prototype, 'should'
, { set: function(){}
, get:
function(){
return new Assertion(Object(this).valueOf());
}
, configurable: true
, enumerable : false
}
);
That is part of the implementation of the JavaScript module Should. The other part is a definition of a the class Assertion, that is constructed with a value, and implements a wide and nice set of assertion methods, against that value. Methods like like
var o = Assertion(actualValue)
o.equals(expectedValue1)
o.moreThan(expectedValue2)
o.contains(expectedValue3)
and aliases to keep english grammer
var o = Assertion(actualValue)
o.equal(expectedValue1)
o.contain(expectedValue3)
and aliases for the lazy sharpshooters, like
o.eql(expectedValue)
o.gt(expectedValue) //greater then
o.gte(...) //greater then or equal
//and so on...
and some connectors that just return this, (which is the instance of Assertion constructed with the test value) like
o.be
o.and
What does it give you?
A test code that looks like this:
var person = getPerson();
Should.exist(person); //that's a static call, and that's easy
//but these are a member calls:
person.should.have("name","age","address","friends");
person.name.should.equal("John");
person.age
.should
.be.number()
.and.be.between(20,30);
person.address
.should
.be.string().and
.startWith("\d").and
.endWith(" st.")
//or even
.and.match(/^[0-9]{1,9}\s+[A-Z][a-z0-9 ]* st\.$/);
person.friends
.should
.be.array().and
.be.between(3,5).and
.containOnlyType(String);
Isn't that wonderful? it's plain English!
You could argue about aesthetics of indentation, where to put the and, and if they are at all necessary, but besides that - anybody can read or write it:
Once you took the 'should' attribute that exists on every object but does not spoil map iterations - you can go on chaining whatever you have to claim regarding the value you started from.
It could have more nifty iteration tools, reflection utilities, be augmented with test functions relevant for your object model, and so on and so forth, but lets just get over the first step :)
But for that, you need every object in the system to feature a non-enumerable smart property called should that in it's getter function returns an Assertion object constructed with the this as the tested value.
(you ain't seen nothing yet - wait to see the beautiful rejection messages it gives! Yummie!!
So yea - I would happily sacrifice the option to call an attribute "should"... and will happily give up intelisense as well - at least as long as it's plain English)
So, in comments, bfavaretto gave us the first step - we know how to prevent enumeration of an attribute - great & thanks!!
Now, can we make it a getter-attribute who's function can access the this?
When I'm done I'm going to put it in some public repo licensed under MIT, for all of us to have fun with :)
Help anybody?
You example is actually 90% correct - but define it like actionscript, not like javascript!
You can still define prototypes in AS3 and they will still work just like prototypes in AS2. The only difference in AS3 is the compiler. AVM2 for some reason does not cast prototypes to native classes (although I didn't test custom classes).
The Prototype Trick: Cast the class as an object.
Eg: if you create:
Array.prototype.random = function():void{}
Then create the object:
var myProtoArray:Array = new Array;
2 things will happen:
myProtoArray.random() //ERROR - this will fail, AVM2 did not map the prototype to Array
but
Object(myProtoArray).random() //WORKS
random() was cast to the Object class, then mapped to Array - I have no idea why!
Hope this helps, cheers.
I confess I'm not keenly familiar with how Javascript works, but if I'm understanding defineProperties purpose correctly, it is a runtime dictation of not just what a property should be, but also the associated namespace to which it belongs (or at least what AS3 considers a namespace).
Class properties are either predefined & only modifiable via custom get() set() functions, or dynamic. Once compiled, their namespace cannot be changed (to my knowledge), so any non-private property is implicitly enumerable, and modifiable whether or not you've written getter/setters (ie: foo.a = value). According to Adobe...
Properties that you create are enumerable, but built-in properties are
generally not enumerable.
That said, you can get a complete list of properties from a class by using describeType. Quite an exhaustive amount of info can be gleaned this way, and I suspect should suit your needs if you wanted to port Mozilla's recreated defineProperties example. Below is an example printing out only property values.
function showProps(obj:*):void {
var desc:XML= describeType(obj);
// public vars
for each (var n:XML in desc.variable){
trace(n.#name + ": " + obj[n.#name]);
}
// getters
for each (n in desc.accessor){
try {
trace(n.#name + ": " + obj[n.#name]);
} catch (error:Error) {
trace("Unable to read write-only property.");
}
}
}
I hope this helps, but I'm certain I don't fully understand what you're trying to accomplish. If you could elaborate, that'd be appreciated.
Ok, guys, thanks for all the help, 22+
I'll give a summary for the people that are interested in the original question, and after that - I'll show you the outcome of my efforts.
The challange was made of two parts:
1 - prevent the augmented (=added on runtime) property from being enumerated
To the first part - thanks to #bfavaretto, commented on the question level - Object.setPropertyIsEnumerable - did the trick great.
2 - make the augmented property operate a getter function with access to the this so it can use it on the constructor of the returned value.
About this second part - Basically - I could not find a way to augment (=add) a property getter to a prototype, and have it operate on instances that enjoy it's API through the inheritance tree.
Anyway, within these limits - here's the outcome:
https://github.com/osher/should.as
Not exact porting because of the platform differences,
and I still have some methods to catch up with the original should.js (like the HTTP testing methods)
but close enough.
The main difference is that instead
var o:Object =
{ name : "Radagast"
, color: "Brown"
}
o.should.have.properties("name","color")
.and.have.property("name","Radagast");
o.name.should.not.equal("Palandoo");
o.color.should.equal("Brown");
you have to go
o.should().have.properties("name","color")
and.have.property("name","Radagast");
o.name.should().not.equal("Palandoo");
o.color.should().equal("Brown");
(the brackets - no getter possible - so the should attribute is a method, and you have to invoke it yourself)
Now if you get stuck and need help from the intellisense, you have to do this:
var should:tdd.Should = o.color.should();
should. <ctrl+space>
which kind'a takes the sting out, but for a peek in the intelisense - it helps
Important
One more thing - you have to force the static constructor of Should as soon in execution as you can,
for example, I do it here:
[Suite]
[RunWith("org.flexunit.runners.Suite")]
public class my_awsome_test_suite
{
//forces the static constructor of tdd.Should
import tdd.Should;
private static var s:Should = new Should();
public var c1:testCase1;
public var c2:testCase2;
public var c3:testCase3;
public var c4:testCase4;
}
I'll probably add some propper README.md later, and more awsome member functions to tdd.Should
Have fun

Is there any advantage in specifying types of variables and return type of functions?

I always set the types of my variables and functions, a habit I brought from my Java learning, seems the right thing to do.
But I always see "weak typing" in other people's code, but I can't disagree with that as I don't know what are the real advantages of keep everything strong typed.
I think my question is clear, but I gonna give some examples:
var id = "Z226";
function changeId(newId){
id = newId;
return newId;
}
My code would be like this:
var id:String = "Z226";
function changeId(newId:String):String{
id = newId;
return newId;
}
Yes, the big advantanges are:
faster code execution, because the runtime know the type, it does not have to evaluate the call
better tool support: auto completion and code hints will work with typed arguments and return types
far better readability
You get performance benefits from strongly typing. See http://gskinner.com/talks/quick/#45
I also find strongly typed code to be much more readable, but I guess depending on the person they may not care.
As pointed out by florian, two advantages of strongly typing are that development tools can can use the information to provide better code-hinting and code-completion, and that type, as an explicit indicator of how the variable or method is intended to be used, can make the code much easier to understand.
The question of performance seems to be up for debate. However, this answer on stackoverflow suggests that typed is definitely faster than untyped in certain benchmark tests but, as the author states, not so much that you would notice it under normal conditions.
However, I would argue that the biggest advantage of strong typing is that you get a compiler error if you attempt to assign or return a value of the wrong type. This helps prevent the kind of pernicious bug which can only be tracked down by actually running the program.
Consider the following contrived example in which ActionScript automatically converts the result to a string before returning. Strongly typing the method's parameter and return will ensure that the program will not compile and a warning is issued. This could potentially save you hours of debugging.
function increment(value) {
return value + 1;
}
trace(increment("1"));
// 11
While the points in the other answers about code hinting and error checking are accurate, I want to address the claim about performance. It's really not all that true. In theory, strong type allows the compiler to generate code that's closer to native. With the current VM though, such optimization doesn't happen. Here and there the AS3 compiler will employ an integer instruction instead of a floating point one. Otherwise the type indicators don't have much effect at runtime.
For example, consider the following code:
function hello():String {
return "Hello";
}
var s:String = hello() + ' world';
trace(s);
Here're the AVM2 op codes resulting from it:
getlocal_0
pushscope
getlocal_0
getlocal_0
callproperty 4 0 ; call hello()
pushstring 12 ; push ' world' onto stack
add ; concatenate the two
initproperty 5 ; save it to var s
findpropstrict 7 ; look up trace
getlocal_0 ; push this onto stack
getproperty 5 ; look up var s
callpropvoid 7 1 ; call trace
returnvoid
Now, if I remove the type indicators, I get the following:
getlocal_0
pushscope
getlocal_0
getlocal_0
callproperty 3 0
pushstring 11
add
initproperty 4
findpropstrict 6
getlocal_0
getproperty 4
callpropvoid 6 1
returnvoid
It's exactly the same, except all the name indices are one less since 'String' no longer appears in the constant table.
I'm not trying to discourage people from employing strong typing. One just shouldn't expect miracle on the performance front.
EDIT: In case anyone is interested, I've put my AS3 bytecode disassembler online:
http://flaczki.net46.net/codedump/
I've improved it so that it now dereferences the operands.