EXC_BAD_ACCESS on iOS 8.1 with Dictionary - dictionary

I have an object accessible via a static var in a struct (workaround for the lack of class variable support in swift right now), structured like this:
struct Constants{
static var myObj = MyObject()
}
MyObject has a dictionary in it like so:
class MyObject{
private var params = Dictionary<String,AnyObject>()
func addParam(key:String, value:AnyObject){
params[key] = value
}
}
Now on the first call to this object for Contants.myObj.addParam("param", value:123) all is well and params has contents ["param":123]. On the second call for Contants.myObj.addParam("param", value:456), I get a EXC_BAD_ACCESS.
Here's the kicker though, this only occurs in iOS 8.1. Also, if I add the line let stupidHack = self.params as the first line of my addParam method, it works fine. My assumption is that it deals with mutability of dictionaries. The let may somehow trigger the dictionary to be mutable again after initialization.
Has anyone else run into this issue before? Any idea on how to fix it?
Thanks!

Looks like a compiler bug.
Have you tried switching between Release and Debug then rebuilding? If debug works but not release it can be an indication of a compiler/optimizer bug.
Does it happen in the simulator also?
Your code works for me on iOS 8.1 with XCode 6.1.

By chance, do you have an iPhone 6 with 64Gb ?
I have one and I had the same issue using Dictionaries twice.
In the news (well the tech news ...), I read that the defective memory modules delivered by Toshiba for precisely this iPhone model could cause incorrect allocations in memory.

Try adjusting the Swift compiler optimization level to "None" (Build Settings).
I had a similar issue with a class being deallocated for no apparent reason, it is mostly a compiler bug like Lee said.

Faced similar kind of issues with swift code and fixed such issues by disabling swift compiler optimisation in the build settings of the application target.

Related

setting CilBody.KeepOldMaxStack or MetadataOptions.Flags

While decompiling .net assembly using de4dot I am getting following message in console:
Error calculating max stack value. If the method's obfuscated, set CilBody.KeepOldMaxStack or MetadataOptions.Flags (KeepOldMaxStack, global option) to ignore this error
How do I set CilBody.KeepOldMaxStack or MetadataOptions.Flags?
Maybe a bit late, but I ran into the same problem today, finding your open question while looking for a solution, and this is how I solved it - I hope it works for you, too:
// Working with an assembly definition
var ass = AssemblyDef.Load("filename.dll");
// Do whatever you want to do with dnLib here
// Create global module writer options
var options = new ModuleWriterOptions(ass.Modules[0]);
options.MetadataOptions.Flags |= MetadataFlags.KeepOldMaxStack;
// Write the new assembly using the global writer options
ass.Write("newfilename.dll", options);
If you want to set the flag only for a selection of methods that produce the problem before writing, just for example:
// Find the type in the first module, then find the method to set the flag for
ass.Modules[0]
.Types.First((type) => type.Name == nameof(TypeToFind))
.FindMethod(nameof(MethodToFind))
.KeepOldMaxStack = true;
CilBody is maybe a bit confusing, if you're not too deep into the internal .NET assembly structures: It simply means the body object of the method that produces the problem, when writing the modified assembly. Obfuscators often try to confuse disassemblers by producing invalid structures, what may cause a problem when calculating the maxstack value before writing the assembly with dnLib. By keeping the original maxstack value, you can step over those invalid method structures.
In the context of de4dot it seems to be a bug, or the application is simply not designed to solve invalid method structures of obfuscated assemblies - in this case there's no solution for you, if the de4net developer won't fix/implement it, and you don't want to write a patch using the source code from GitHub.

"Cannot access a property or method of a null object reference." without any meaningfull stack trace

Regularly during my application run, I get
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at mx.managers::SystemManager/stageEventHandler()[C:\autobuild\3.4.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:5649]
This is the full stack trace. Obviously, I guess there is something wrong, but I can't understand what.
Is there any way for me to find the origin of that bad behaviour ?
EDIT
Having added my SDK sources to my debugger, I can now say precisely which line it is :
private function stageEventHandler(event:Event):void
{
if (event.target is Stage)
mouseCatcher.dispatchEvent(event); // This is line 5649
}
mouseCatcher is indeed null. The current event target is indeed a Stage object, and event type contains the "deactivate" String. As event occurs at application startup (before I try to do any kind of user interaction), I guess it's a kind of initialization bug, but where ? and why ?
Look at the source code, this is always your best option. The 3.4 SDK is open source (datavisualization and the flash player itself aside) and you probably already have the source for it in your FlashBuilder/FlexBuilder install/sdks folder. Use grep or windows grep to find the file in question (or find, whatever floats your boat). Open the SystemManager file and check what's happening at that line, check for calls to the method (if it's public use grep again, if it's private you just need to look within the SystemManager). Try to understand why it gets to this point, as pointed out by some others it's likely a timing related issue where you're trying to access something before it has been assigned, in this case the SystemManager, you probably need to defer whatever action you're taking that is causing the error to a later part of the life-cycle (if you're using initialize event or pre-initialize try on creationComplete instead since that will be dispatched after the createChildren method is called).
Note: Mine is located here
C:\CleanFS\SDKs\flex\3.4.0.9271\frameworks\projects\framework\src\mx\managers
In my copy of SystemManager with the version of the SDK I have that line number doesn't make any sense since it's a block closure not an executable line so you'll have to look at your specific version.
It looks like you are using the Flex 3.4 SDK. Are you listening for the ADDED_TO_STAGE event when the application loads? Or doing anything with the Stage object on load? If so, you might be hitting a bug specific to the 3.4 SDK:
http://bugs.adobe.com/jira/browse/SDK-23332
The most obvious solution is to swap out the 3.4 SDK for a later version (3.4A, 3.5 or 3.6). You can do that here: http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+3
All of your code should be backwards compatable with the newer Flex 3 SDKs.

QVariantMap crash in destructor

I am building a JSON-object with Qt and convert it to a QString using QJson. This (normally) works fine and it does in this case but in the destructor of my Qt data structure, it crashes with an Access Violation. The Object is built fine, it is sent over my network connection and after the function ends, my application crashes.
My code looks like this:
void bar()
{
QVariantMap data;
data.insert("Id", 1);
QList<QVariant> list; //QVariantList
for (QMap<...>:ConstIterator ... ) //Loop through a Map
{
QMap<QString, QVariant> singleEntry; //QVariantMap
singleEntry.insert("LocalId", it.value());
QList<QVariant> entryList; //QVariantList
for (...) //Loop through another structure
{
entryList.append("foo");
}
singleEntry.insert("List", entryList);
list.append(singleEntry);
}
data.insert("Entries", list);
QJson::Serializer.serialize(data); // Works fine
} // Crash here
If I remove the inner loop, which builds up entryList, everything works fine. It seems that the destructor of data cannot delete the contents but I have no idea, why. The whole data structure seems to be fine while serializing it (and I hope that QJson does not change anything in the given data) but it cannot be cleaned up..
Best Regards,
Tobias
As Raiv said this can happen when mixing debug and release dlls, but in my oppinion this can also happen if the application and the Qt DLL's use different CRT libraries. Some people say that when they recompiled Qt on their machines the problem dissapears and I think this is because the CRT dlls after Qt rebuild are the same as the app's. Try to set the Runtime Library option in C/C++ Code Generation is set to Multi-threaded Debug DLL (/MDd) or Multi-threaded DLL (/MD) respectively for Debug and Release. Some Qt types as QVariantMap, QVariantList, QModelIndexList are probably allocated with /MD (in Qt's dll) and when they are deallocated with /MT (in the app) I think this causes the crash. This can also fix the crash on QString::toStdWString(). In order for this to link maybe the Ignore All Default Libraries should be set to No and Ignore Specific Library should not mention crt dlls used by Qt.
I got a little workaround, which fits my needs. I have still no idea, why this crash happens, but I know, which should be the problem.
I tried to build up a static structure like this:
QVariantMap
QVariantList
QVariantMap
QVariantList
and it crashes. If I remove the QVariantList at the bottom and add QVariantMap or anything else instead, it is working fine. I think this is a problem with the nesting level in this case.
I have now just joined my list as a comma-seperated QString and then it works fine.
If anyone of you has an idea, why the crash in destructing such a nested struct (another information: doesnt matter if a allocate the QVariants in heap and delete them myself or stack) and how to fix it, please let me know.

Flex Compile Time Constants - Timestamp

I'm trying to use Flex Compile Time Constants to include the date and time the SWF was built (source control revision/timestamp such as SVN:Keywords is not sufficient for our needs, we need to know the actual build time, not the commit time).
I've tried using actionscript (like the documentation suggests you should be able to):
-define+=COMPILE::Timestamp,"new Date()"
But this gives "The initializer for a configuration value must be a compile time constant"
I've tried getting it to drop to shell and use the date command (using various single and double quote configurations), for example:
-define+=COMPILE::Timestamp,`date +%Y%m%d%H%M%S`
I can only get it to work with simple strings and simple constant expressions (eg, I can do 4-2 and it'll be 2 at runtime. But I can't get it to do anything whose value wouldn't be explicitly known at the time I declare the define.
Has anyone had any luck with something like this?
I had the same problem and ended up using this blog post as a starting point. Worked really well for me. Just had to update a few bits of the class to flex 4. Pulled the date right out of the complied swf.
The key to your problem is most likely in the following statement by Adobe referring to Compile Time Constants:
The constant can be a Boolean, String, or Number, or an expression that can be evaluated in ActionScript at compile time.
I would assume that the Timestamp is not available at compile time.
However, you may try using a string instead (something like this)
public function GetUnixTime():String{
var myDate:Date = new Date();
var unixTime:Number = Math.round(myDate.getTime()/1000);
return unixTime.toString();
}
Another thought is that you could get the information from the compiled file.
Hope this helps.
After extensive research, I've concluded that this simply isn't doable.
If you don't use FlexBuilder to do your builds you can do it quite easily.
I do something like this with FlexMojos in Maven.
In the relevant config section:
<definesDeclaration>
<property><name>BUILD::buildVersion</name><value>"${project.version}"</value></property>
<property><name>BUILD::buildRevision</name><value>"${buildNumber}"</value></property>
<property><name>BUILD::buildTimestamp</name><value>"${timestamp}"</value></property>
</definesDeclaration>
FlexBuilder pretty much sucks as a build environment for reasons like the one you mention

Compact Framework - Get Storage Card Serial Number

Morning all,
How would I go about getting the serial number of the storage/sd card on my mobile device? I am using C#.Net 2.0 on the Compact Framework V2.0.
Thanks.
The Smart Device Framework provides a mechanism to get SD Card serial numbers and manufacturer IDs.
I'm not on a machine that I can get the syntax for you but I believe you can use the System.IO namespace to get IO based attributes.
First get a DirectoryInfo to the storage card. (I'm not 100% on the code here, you may need to test, I'll update it if I can get to my machine)
public DirectoryInfo GetStorageCard() {
DirectoryInfo deviceRoot = new DirectoryInfo("/");
foreach (DirectoryInfo dir in deviceRoot.GetDirectories())
if (dir.Attributes == FileAttributes.Directory & dir.Attributes = FileAttributes.Temporary)
return dir;
}
Then check all the properties on the DirectoryInfo that code returns. Thanks to the joys of debugging you should be able to see if the serial number is one of the available properties.
If not, you may need to look to something a bit more unmanaged.
Hope this helps.
You need to use some unmanaged APIs. Specifically, DeviceIoControl using a 'control code' of IOCT_DISK_GET_STORAGEID. This will, in turn, return a STORAGE_IDENTIFICATION structure.
Here's where it gets a bit tricky, as STORAGE_IDENTIFICATION uses a property (dwSerialNumOffset) to specify the (memory) offset from the beginning of the structure, which would be difficult to translate into interop calls.
Edit: Found a VB.NET implementation on the MSDN forums

Resources