I'm trying to use "FiniteDomainSort" in my context, but when i give it to the solver it throws some exceptions.
Remarks:
* I use MkNumeral as suggested here
* Tested with z3-4.3.0 x64 (win) and z3-4.3.2 x64 (ubuntu)
* Runs fine when I use IntSort in the same example
Example:
using System;
using System.Collections.Generic;
using Microsoft.Z3;
namespace NS { class CL { public static void Main() {
Context ctx = new Context (new Dictionary<string, string> () { { "MODEL", "true" } });
Sort BOOL = ctx.BoolSort;
Sort INT = ctx.IntSort;
FuncDecl f1 = ctx.MkFuncDecl("f1", new Sort[] {INT}, BOOL);
Expr c1 = ctx.MkNumeral ( 1, INT);
BoolExpr app1 = (BoolExpr) ctx.MkApp (f1,c1);
Solver solver1 = ctx.MkSolver();
solver1.Assert(app1);
Console.WriteLine ("[Solver 1]");
Console.WriteLine ("Check: " + solver1.Check ());
Console.WriteLine ("Model\n" + solver1.Model);
Sort TEST = ctx.MkFiniteDomainSort ("MySort", 2); // size "2" just for demonstration
FuncDecl f2 = ctx.MkFuncDecl("g", new Sort[] {TEST}, BOOL);
Expr c2 = ctx.MkNumeral ( 1, TEST);
BoolExpr app2 = (BoolExpr) ctx.MkApp (f2,c2);
Solver solver2 = ctx.MkSolver();
solver2.Assert(app2);
Console.WriteLine ("[Solver 2]");
Console.WriteLine ("Check: " + solver2.Check ());
Console.WriteLine ("Model\n" + solver2.Model);
} } }
Output:
./Problem.exe
[Solver 1]
Check: SATISFIABLE
Model
(define-fun f1 ((x!1 Int)) Bool
(ite (= x!1 1) true
true))
[Solver 2]
Stacktrace:
at <unknown> <0xffffffff>
at (wrapper managed-to-native) Microsoft.Z3.Native/LIB.Z3_solver_check (intptr,intptr) <0xffffffff>
at Microsoft.Z3.Native.Z3_solver_check (intptr,intptr) <0x00023>
at Microsoft.Z3.Solver.Check (Microsoft.Z3.Expr[]) <0x00093>
at NS.CL.Main () <0x0049b>
at (wrapper runtime-invoke) object.runtime_invoke_void (object,intptr,intptr,intptr) <0xffffffff>
Native stacktrace:
/usr/bin/cli() [0x4b8e48]
/usr/bin/cli() [0x51211b]
/usr/bin/cli() [0x424152]
/lib/x86_64-linux-gnu/libpthread.so.0(+0xfbb0) [0x7f5aee780bb0]
/some/path/libz3.so(_ZN3smt15model_generator16top_sort_sourcesERK10ptr_vectorINS_5enodeEERK7obj_mapIS2_PNS_16model_value_procEER7svectorINS_22model_value_dependencyEjE+0x3d2) [0x7f5aeac9ffc2]
/some/path/libz3.so(_ZN3smt15model_generator9mk_valuesEv+0x17c) [0x7f5aeaca10ac]
/some/path/libz3.so(_ZN3smt15model_generator8mk_modelEv+0x21) [0x7f5aeaca2161]
/some/path/libz3.so(_ZN3smt7context14mk_proto_modelE5lbool+0x43) [0x7f5aeace17d3]
/some/path/libz3.so(_ZN3smt7context6searchEv+0x21d) [0x7f5aeace854d]
/some/path/libz3.so(_ZN3smt7context15setup_and_checkEb+0x88) [0x7f5aeace8948]
/some/path/libz3.so(_ZN10smt_tacticclERK3refI4goalER11sref_bufferIS1_Lj16EERS0_I15model_converterERS0_I15proof_converterER7obj_refIN18dependency_managerIN11ast_manager22expr_dependency_configEE10dependencyESG_E+0x12ee) [0x7f5aeac395ce]
/some/path/libz3.so(_ZN17and_then_tacticalclERK3refI4goalER11sref_bufferIS1_Lj16EERS0_I15model_converterERS0_I15proof_converterER7obj_refIN18dependency_managerIN11ast_manager22expr_dependency_configEE10dependencyESG_E+0xf82) [0x7f5aeb0d1282]
/some/path/libz3.so(_Z4execR6tacticRK3refI4goalER11sref_bufferIS2_Lj16EERS1_I15model_converterERS1_I15proof_converterER7obj_refIN18dependency_managerIN11ast_manager22expr_dependency_configEE10dependencyESH_E+0x40) [0x7f5aeb0c8240]
/some/path/libz3.so(_Z9check_satR6tacticR3refI4goalERS1_I5modelER7obj_refI3app11ast_managerERS8_IN18dependency_managerINSA_22expr_dependency_configEE10dependencyESA_ERSs+0x121) [0x7f5aeb0c86a1]
/some/path/libz3.so(_ZN13tactic2solver14check_sat_coreEjPKP4expr+0x1c6) [0x7f5aeaf92476]
/some/path/libz3.so(_ZN12solver_na2as9check_satEjPKP4expr+0x115) [0x7f5aeaf94445]
/some/path/libz3.so(_ZN15combined_solver9check_satEjPKP4expr+0x16f) [0x7f5aeaf93a9f]
/some/path/libz3.so(Z3_solver_check+0xdb) [0x7f5aea95304b]
[0x40142191]
Debug info from gdb:
Could not attach to process. If your uid matches the uid of the target
process, check the setting of /proc/sys/kernel/yama/ptrace_scope, or try
again as the root user. For more details, see /etc/sysctl.d/10-ptrace.conf
ptrace: Operation not permitted.
No threads.
=================================================================
Got a SIGSEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
=================================================================
Aborted
Looks like it was a bug and will be fixed in unstable.
See http://z3.codeplex.com/workitem/115
Related
Below is my sample code. Everything working perfectly but if trying to add a new property in PageLoad or TestDetailResponseModel struct then the app is getting crash. There is no issue in API response and parsing. Getting parsed value in the print statement. According to the crash log, it's something related to memory but I am unable to figure it out. Below is my sample code. My API response is approx 40 KB. Please help me.
Note-
I am not mutating the response objects only consuming.
If change PageLoad from struct to class app is not crashing
import RxCocoa
import RxSwift
public struct TestDetailViewModel {
private func getTestDetailSuccessResponse() -> Driver<TestDetailResponseModel?> {
//Make API call asynchronously using RxSwift and storing result in testDetailResponseModel
let testDetailResponseModel: TestDetailResponseModel? = RXNetworkManager.execute(request: MyRequestModel) {
//Api Response
//Parse response. Parsing is proper. responseModel prints all the parsed properties with correct values of TestDetailResponseModel and PageLoad objects (detail, and pageNumber)
print(responseModel)
}
return Driver.just(testDetailResponseModel)
}
private func loadDetail() {
let isDetailExist = getTestDetailSuccessResponse().compactMap { response -> Bool? in
print(response) //No Crash
print(response?.pageLoad) //App crashed here if add pageNumber property in PageLoad object
return response?.pageLoad != nil
}
}
}
public struct TestDetailResponseModel: Decodable {
public let pageLoad: PageLoad?
//...
}
public struct PageLoad: Decodable {
public let detail: String?
//...
public let pageNumber: Double? //New property
}
=================Crash Report for same====================
Exception Type: EXC_BAD_ACCESS (SIGABRT)
Exception Subtype: KERN_INVALID_ADDRESS at 0x50a01fb550981f18 -> 0xffff9fb550981f18 (possible pointer authentication failure)
Exception Codes: 0x0000000000000001, 0x50a01fb550981f18
VM Region Info: 0xffff9fb550981f18 is not in any region. Bytes after previous region: 18446532646169747225
REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL
MALLOC_NANO (reserved) 600018000000-600020000000 [128.0M] rw-/rwx SM=NUL ...(unallocated)
--->
UNUSED SPACE AT END
Exception Note: EXC_CORPSE_NOTIFY
Triggered by Thread: 0
Application Specific Information:
=================================================================
==17015==ERROR: AddressSanitizer: SEGV on unknown address 0x50a01fb550981f18 (pc 0x00018f9e1d50 bp 0x00016bbf60c0 sp 0x00016bbf6080 T0)
==17015==The signal is caused by a UNKNOWN memory access.
#0 0x18f9e1d50 in swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1> >::incrementSlow(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int)+0x2c (libswiftCore.dylib:arm64+0x302d50)
#1 0x18f9b20bc in _swift_retain_+0x54 (libswiftCore.dylib:arm64+0x2d30bc)
#2 0x10d8d5edc (liboainject.dylib:arm64+0x5edc)
#3 0x18f9e7958 in swift_bridgeObjectRetain+0x30 (libswiftCore.dylib:arm64+0x308958)
#4 0x1191ab100 in outlined copy of PageLoad?+0x1dc (TestCore:arm64+0x10ff100)
#5 0x1196cf554 in outlined copy of TestDetailResponseModel?+0x6a4 (TestCore:arm64+0x1623554)
#6 0x11a1541bc in TestDetailViewModel.getTestDetailSuccessResponse(response:) TestDetailViewModel+APICalls.swift:69
#7 0x1195240b8 in closure #13 in TestDetailViewModel.transform(input:) TestDetailViewModel.swift:108
#8 0x10e59b30c in CompactMapSink.on(_:) CompactMap.swift:47
#9 0x10e59b550 in protocol witness for ObserverType.on(_:) in conformance CompactMapSink<A, B> <compiler-generated>
#10 0x10e5f91d0 in partial apply for implicit closure #2 in implicit closure #1 in ShareWhileConnectedConnection._synchronized_subscribe<A>(_:) <compiler-generated>
#11 0x10e58d8d8 in thunk for #escaping #callee_guaranteed (#in_guaranteed Event<A>) -> () <compiler-generated>
#12 0x10e5f804c in ShareReplay1WhileConnectedConnection.on(_:)+0x70 (RxSwift:arm64+0x8804c)
#13 0x10e5f7bf4 in protocol witness for ObserverType.on(_:) in conformance ShareReplay1WhileConnectedConnection<A> <compiler-generated>
#14 0x10e5b0514 in Sink.forwardOn(_:) Sink.swift:34
#15 0x10e582398 in SwitchSinkIter._synchronized_on(_:) Switch.swift:160
#16 0x10e5abb68 in SynchronizedOnType.synchronizedOn(_:) SynchronizedOnType.swift:16
#17 0x10e582488 in protocol witness for ObserverType.on(_:) in conformance SwitchSinkIter<A, B, C> <compiler-generated>
#18 0x10e5f91d0 in partial apply for implicit closure #2 in implicit closure #1 in ShareWhileConnectedConnection._synchronized_subscribe<A>(_:) <compiler-generated>
#19 0x10e58d8d8 in thunk for #escaping #callee_guaranteed (#in_guaranteed Event<A>) -> () <compiler-generated>
#20 0x10e5f804c in ShareReplay1WhileConnectedConnection.on(_:)+0x70 (RxSwift:arm64+0x8804c)
#21 0x10e5f7bf4 in protocol witness for ObserverType.on(_:) in conformance ShareReplay1WhileConnectedConnection<A> <compiler-generated>
#22 0x10e5b0514 in Sink.forwardOn(_:) Sink.swift:34
#23 0x10e59d0c8 in CatchSink.on(_:) Catch.swift:131
#24 0x10e59d31c in protocol witness for ObserverType.on(_:) in conformance CatchSink<A> <compiler-generated>
#25 0x10e605534 in closure #1 in ObserveOnSerialDispatchQueueSink.init(scheduler:observer:cancel:) ObserveOn.swift:184
#26 0x10e605d48 in partial apply for thunk for #escaping #callee_guaranteed (#guaranteed ObserveOnSerialDispatchQueueSink<A>, #in_guaranteed Event<A.ObserverType.Element>) -> (#out Disposable) <compiler-generated>
#27 0x10e5904e4 in partial apply for closure #1 in MainScheduler.scheduleInternal<A>(_:action:) <compiler-generated>
#28 0x10e585410 in thunk for #escaping #callee_guaranteed () -> () <compiler-generated>
#29 0x1139f950c in __wrap_dispatch_async_block_invoke+0xb8 (libclang_rt.asan_iossim_dynamic.dylib:arm64+0x3d50c)
#30 0x18010d240 in _dispatch_call_block_and_release+0x14 (libdispatch.dylib:arm64+0x2240)
#31 0x18010ea94 in _dispatch_client_callout+0xc (libdispatch.dylib:arm64+0x3a94)
#32 0x18011c418 in _dispatch_main_queue_drain+0x3cc (libdispatch.dylib:arm64+0x11418)
#33 0x18011c038 in _dispatch_main_queue_callback_4CF+0x24 (libdispatch.dylib:arm64+0x11038)
#34 0x180361c28 in __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__+0x8 (CoreFoundation:arm64+0x85c28)
#35 0x18035c0ac in __CFRunLoopRun+0x97c (CoreFoundation:arm64+0x800ac)
#36 0x18035b214 in CFRunLoopRunSpecific+0x238 (CoreFoundation:arm64+0x7f214)
#37 0x18c25f608 in GSEventRunModal+0x9c (GraphicsServices:arm64+0x3608)
#38 0x184d88a94 in -[UIApplication _run]+0x3dc (UIKitCore:arm64+0xc0da94)
#39 0x184d8d630 in UIApplicationMain+0x6c (UIKitCore:arm64+0xc12630)
#40 0x104dc5958 in main AppDelegate.swift:32
#41 0x10b66dcd4 in start_sim+0x10 (dyld_sim:arm64+0x1cd4)
#42 0x10b71d084 (<unknown module>)
#43 0xa777ffffffffffc (<unknown module>)
==17015==Register values:
x[0] = 0x000000018035ba08 x[1] = 0xaa1403f6aa1303e1 x[2] = 0x0000000000000001 x[3] = 0x0000000000000001
x[4] = 0x0000000000000000 x[5] = 0x0000000000000000 x[6] = 0x0000000000000000 x[7] = 0x0000000000000000
x[8] = 0x50a01fb550981f08 x[9] = 0x000000018035ba00 x[10] = 0xffffffffffffffff x[11] = 0xaa1403f8aa1303e1
x[12] = 0x0000000000000000 x[13] = 0x0000000000000000 x[14] = 0x0000000000000000 x[15] = 0x0000000000000000
x[16] = 0x00000001cc0ac98c x[17] = 0x0000000000000000 x[18] = 0x0000000000000000 x[19] = 0x000000016bbf6118
x[20] = 0x000000018035ba00 x[21] = 0x000000010d8dc000 x[22] = 0x000000016bbf60f8 x[23] = 0x000000010d8dc000
x[24] = 0x000000010d8dc000 x[25] = 0x0000000000000000 x[26] = 0x40c1d7097c1bda51 x[27] = 0x4000000153eb88d0
x[28] = 0xc000000000000030 fp = 0x000000016bbf60c0 lr = 0x000000018f9b20c0 sp = 0x000000016bbf6080
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV (libswiftCore.dylib:arm64+0x302d50) in swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1> >::incrementSlow(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int)+0x2c
==17015==ABORTING
dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode_13.4.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_INSERT_LIBRARIES=/Applications/Xcode_13.4.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/DVTInstrumentsFoundation.framework/liboainject.dylib
CoreSimulator 802.6.1 - Device: iPhone 13 Pro Max (********-****-****-****-************) - Runtime: iOS 15.5 (19F70) - DeviceType: iPhone 13 Pro Max
dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode_13.4.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_INSERT_LIBRARIES=/Applications/Xcode_13.4.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/DVTInstrumentsFoundation.framework/liboainject.dylib
abort() called
Kernel Triage:
VM - Compressor failed a blocking pager_get
VM - Compressor failed a blocking pager_get
VM - Compressor failed a blocking pager_get
VM - Compressor failed a blocking pager_get
There is not much information, but I can guess what the problem is
Any Api call asynchronous, and you need use #escaping completion for handle result of dataTask
private func getTestDetailSuccessResponse(completion: #escaping (TestDetailResponseModel>)->Void) {
var testDetailResponseModel: TestDetailResponseModel?
// Make api call
// return result of call into completion as "completion(result)"
}
Using:
private func loadDetail() {
getTestDetailSuccessResponse { result in
let detail = result?.pageLoad
}
}
I am running some code written in F# with mono and I have seen that after some time running (weeks), some process are in sleep mode. Using strace as strace -p <pid> I get
Process 38756 attached - interrupt to quit
futex(0x272ee9c, FUTEX_WAIT_PRIVATE, 1, NULL
Which as far as I understand it means that some part is awaiting for something (other threads).
So I continued searching the problem with gdb attach <pid> in which I can see that there are 4 threads as:
(gdb) info threads
4 Thread 0x7ff06a3ff700 (LWP 38760) 0x0000003b3c80b5bc in pthread_cond_wait##GLIBC_2.3.2 () from /lib64/libpthread.so.0
3 Thread 0x7ff06aa17700 (LWP 38769) 0x0000003b3c80d930 in sem_wait () from /lib64/libpthread.so.0
2 Thread 0x7ff0677ff700 (LWP 38789) 0x0000003b3c80b5bc in pthread_cond_wait##GLIBC_2.3.2 () from /lib64/libpthread.so.0
* 1 Thread 0x7ff070a07760 (LWP 38756) 0x0000003b3c80b5bc in pthread_cond_wait##GLIBC_2.3.2 () from /lib64/libpthread.so.0
On thread 1 using where I can see that the place where it is not working is a Parallel.For().
From my part, the code where the process goes to sleep is:
let sinMod t (difRay:Vector) (fA:(float*Vector*float)[]) =
let duepi = 2.*PI
Array.fold(fun acc x -> let freq, amplitude, phase = fA.[x]
acc+sin(duepi*freq*t+phase)*(amplitude*difRay)) 0. [|0..fA.Length-1|]
let NextFunc (var1:type1,var2:type2,var3:type3) =
// do some stuff
...
// some context
let time = snd var3
let inputArray = var.SomeArray // float[]
// the function that doesn't works
Parallel.For(0, (inputArray .Length), fun i -> (inputArray .[i] <- inputArray .[i]+(ww*SINMOD time.[i])) ) |> ignore
inputArray // return from NextFunc
I really don't have any idea where is the problem. Sometimes the process goes to sleep and others this is not happening. I don't know if this can have any relation, but the length of the parallel.for is 40960
Why is the program going to sleep?
Thank you
EDIT:
I haven't specified why I believe the problem is happening in a function like I said. Using gdb I obtain:
(gdb) where
#0 0x0000003b3c80b5bc in pthread_cond_wait##GLIBC_2.3.2 () from /lib64/libpthread.so.0
#1 0x000000000060cd0d in mono_os_cond_wait (cond=0x272ee98, mutex=0x272ee70, timeout_ms=4294967295) at ../../mono/utils/mono-os-mutex.h:105
#2 mono_os_cond_timedwait (cond=0x272ee98, mutex=0x272ee70, timeout_ms=4294967295) at ../../mono/utils/mono-os-mutex.h:120
#3 0x000000000060f0c8 in _wapi_handle_timedwait_signal_handle (handle=0x410, timeout=4294967295, alertable=1, poll=0, alerted=0x7fff27d2a6cc)
at handles.c:1554
#4 0x00000000006245ea in wapi_WaitForSingleObjectEx (handle=0x410, timeout=4294967295, alertable=1) at wait.c:173
#5 0x00000000005b01f2 in ves_icall_System_Threading_Monitor_Monitor_wait (obj=0x7fed09df4cc0, ms=4294967295) at monitor.c:1294
#6 0x00007ff06806385e in System.Threading.Monitor:Wait (obj=<type 'exceptions.ValueError'>
zero length field name in format
140656049605824, millisecondsTimeout=-1) at /root/mono-4.3.2/mcs/class/corlib/System.Threading/Monitor.cs:148
#7 0x00007ff067e69dc2 in System.Threading.ManualResetEventSlim:Wait (this=..., millisecondsTimeout=-1, cancellationToken=0)
at /root/mono-4.3.2/external/referencesource/mscorlib/system/threading/ManualResetEventSlim.cs:669
#8 0x00007ff067e8544e in System.Threading.Tasks.Task:SpinThenBlockingWait (this=..., millisecondsTimeout=-1, cancellationToken=0)
at /root/mono-4.3.2/external/referencesource/mscorlib/system/threading/Tasks/Task.cs:3326
#9 0x00007ff067e8255d in System.Threading.Tasks.Task:InternalRunSynchronously (this=..., scheduler=..., waitForCompletion=true)
at /root/mono-4.3.2/external/referencesource/mscorlib/system/threading/Tasks/Task.cs:1231
#10 0x00007ff067e823c8 in System.Threading.Tasks.Task:RunSynchronously (this=..., scheduler=...)
at /root/mono-4.3.2/external/referencesource/mscorlib/system/threading/Tasks/Task.cs:1169
#11 0x00007ff067e77c03 in System.Threading.Tasks.Parallel:ForWorker<TLocal_REF> (fromInclusive=0, toExclusive=40960, parallelOptions=..., body=...,
bodyWithState=..., bodyWithLocal=..., localInit=..., localFinally=...)
at /root/mono-4.3.2/external/referencesource/mscorlib/system/threading/Tasks/Parallel.cs:1273
#12 0x00007ff067e76b8a in System.Threading.Tasks.Parallel:For (fromInclusive=0, toExclusive=40960, body=...)
at /root/mono-4.3.2/external/referencesource/mscorlib/system/threading/Tasks/Parallel.cs:441
#13 0x00000000402c11ee in ?? ()
#14 0x00007fff27d2aec0 in ?? ()
#15 0x00007ff0167eab00 in ?? ()
#16 0x0000000000000016 in ?? ()
#17 0x00007fef394db070 in ?? ()
#18 0x0000000000000000 in ?? ()
(gdb) p mono_pmip(0x00000000402c11ee)
$1 =
0x29ae0f0 " ShadingNoise:PhaseModulation (Types.types/Ray,Types.types/Intersection,System.Tuple`2<System.Tuple`3<double, Types.Algebra/Vector, double>[], double[]>) + 0x27e (0x402c0f70 0x402c1238) [0x273b080 - m"...
(gdb)
Where to specify, ShadingNoise:PhaseModulation is the function that I have defined as NextFunc in a simplified way. just in case, the original function it's here
NSData is extended to determine the file type:
extension NSData {
var dataType: String? {
// Ensure data length is at least 1 byte
guard self.length > 0 else { return nil }
// Get first byte
var c = [UInt8](count: 1, repeatedValue: 0)
self.getBytes(&c, length: 1)
// Identify data type
switch (c[0]) {
case 0xFF:
return "jpg"
case 0x89:
return "png"
case 0x47:
return "gif"
case 0x49, 0x4D:
return "tiff"
default:
return nil //unknown
}
}
}
The method above is called on a NSData object from image data that is fetched from a server.
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) {
do {
// Fetch image synchronously from server
let query = PFQuery(className: <...>)
let result = try query.getFirstObject()
guard
let imageObject = result.objectForKey(<...>) as? PFFile,
let imageData = try? imageObject.getData(),
let image = imageData.dataType == "gif" ? UIImage.animatedImageWithAnimatedGIFData(imageData) : UIImage(data: imageData)
else {
return
}
<...>
} catch (let error as NSError) {
<...>
}
}
However the app very rarely crashes at line self.getBytes:
What is the reason for this?
The buffer of getBytes is &c, an UnsafeMutablePointer - do I have to take any special memory considerations because of that?
Update
The crashes still occur with the following variation of the code:
// Get first byte
var c: UInt8 = 0;
self.getBytes(&c, length: 1)
Update
The crashes still occur with the following variation of the code:
// Get first byte
var c = [UInt8](count: 1, repeatedValue: 0)
c.withUnsafeMutableBufferPointer {
buffer in
getBytes(buffer.baseAddress, length: 1)
}
guard c.indices.contains(0) else { return nil }
I got the following crash and included the whole thread, maybe someone can spot a hint:
Thread 18 Crashed:
0 libsystem_platform.dylib 0x21a8e198 _platform_memmove$VARIANT$CortexA9 + 92
1 Foundation 0x22512923 __34-[_NSDispatchData getBytes:range:]_block_invoke + 176
2 libdispatch.dylib 0x218d238d _dispatch_data_apply + 82
3 libdispatch.dylib 0x218d4a51 dispatch_data_apply + 26
4 Foundation 0x22512865 -[_NSDispatchData getBytes:range:] + 86
5 Foundation 0x2267730b -[_NSDispatchData getBytes:length:] + 24
6 MyAppName 0x00079ba0 partial apply forwarder for (extension in MyAppName):__ObjC.NSData.(dataType.getter : Swift.String?).(closure #1) (NSData+Extension.swift:54)
7 MyAppName 0x00079c14 partial apply forwarder for reabstraction thunk helper from #callee_owned (#inout Swift.UnsafeMutableBufferPointer<Swift.UInt8>) -> (#unowned (), #error #owned Swift.ErrorType) to #callee_owned (#inout Swift.UnsafeMutableBufferPointer<Swift.UInt8>) -> (#out (), #error #owned Swift.ErrorType) (NSData+Extension.swift:0)
8 MyAppName 0x00079cb8 generic specialization <Swift.UInt8, ()> of Swift.Array.withUnsafeMutableBufferPointer <A> ((inout Swift.UnsafeMutableBufferPointer<A>) throws -> A1) throws -> A1 (NSData+Extension.swift:0)
9 MyAppName 0x00079a70 (extension in MyAppName):__ObjC.NSData.dataType.getter : Swift.String? (NSData+Extension.swift:55)
10 MyAppName 0x00079948 #objc (extension in MyAppName):__ObjC.NSData.dataType.getter : Swift.String? (NSData+Extension.swift:0)
11 MyAppName 0x000d2264 MyAppName.DataManager.(fetchImagesFromServer (MyAppName.ImageSet) -> ()).(closure #1) (DataManager.swift:1214)
12 libdispatch.dylib 0x218cd823 _dispatch_call_block_and_release + 8
13 libdispatch.dylib 0x218dc5e9 _dispatch_root_queue_drain + 1558
14 libdispatch.dylib 0x218dbfcd _dispatch_worker_thread3 + 94
15 libsystem_pthread.dylib 0x21a91b29 _pthread_wqthread + 1022
16 libsystem_pthread.dylib 0x21a91718 start_wqthread + 6
Update
The crashes still occur with the following variation of the code:
// Get first byte
var c = UnsafeMutablePointer<UInt8>.alloc(1)
defer { c.dealloc(1) }
self.getBytes(c, length: 1)
switch (c[0]) { ...
With the help of an Apple engineer (via a TSI ticket) the issue was finally identified.
All code permutations above for reading the first byte are valid and working.
The issue was that the NSData object was created when a file was fetched from a server using the Parse iOS SDK which stores the data in a temporary file with file protection key NSFileProtectionCompleteUntilFirstUserAuthentication.
The file protection key allows reading data of the NSData object only after the user unlocks the device once after reboot. Although the data is not readable before unlocking, the NSData object can be created and even the NSData.length property is accessible. However, attempting to read the data would throw an exception.
I changed the code and added a check if the protected data is available before attempting to read it with UIApplication.sharedApplication().protectedDataAvailable.
You may wonder why a file was fetched by the app before the device was even unlocked. The app was started by a remote user notification. That explains why the crash happened so rarely.
Learned 2 things:
Always check your file protection key
Apple technical support gave a super in-depth explanation and is worth the money
A Swift array is more like a C++ std::vector than a C array: it has other contents besides the array elements. You can't get a pointer to the first element using &c. You need to ask the array for a pointer to its elements, like this:
var c = [UInt8](count: 1, repeatedValue: 0)
c.withUnsafeMutableBufferPointer { buffer in
getBytes(buffer.baseAddress, length: 1)
}
For your particular case, it seems overkill to use an array, though. Why not just do:
var c: UInt8 = 0;
self.getBytes(&c, length: 1)
In python, after import z3, I did x = Int('x'). This gave me the traceback
In [16]: x = Int('x')
---------------------------------------------------------------------------
ArgumentError Traceback (most recent call last)
<ipython-input-16-adbc8f7df7ed> in <module>()
----> 1 x = Int('x')
/home/elliot/.local/lib/python2.7/site-packages/z3.pyc in Int(name, ctx)
2754 """
2755 ctx = _get_ctx(ctx)
-> 2756 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
2757
2758 def Ints(names, ctx=None):
/home/elliot/.local/lib/python2.7/site-packages/z3.pyc in IntSort(ctx)
2655 """
2656 ctx = _get_ctx(ctx)
-> 2657 return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
2658
2659 def RealSort(ctx=None):
/home/elliot/.local/lib/python2.7/site-packages/z3.pyc in __init__(self, ast, ctx)
275 self.ast = ast
276 self.ctx = _get_ctx(ctx)
--> 277 Z3_inc_ref(self.ctx.ref(), self.as_ast())
278
279 def __del__(self):
/home/elliot/.local/lib/python2.7/site-packages/z3core.pyc in Z3_inc_ref(a0, a1)
1252
1253 def Z3_inc_ref(a0, a1):
-> 1254 lib().Z3_inc_ref(a0, a1)
1255 err = lib().Z3_get_error_code(a0)
1256 if err != Z3_OK:
ArgumentError: argument 2: <type 'exceptions.TypeError'>: unbound method from_param() must be called with Ast instance as first argument (got int instance instead)
I installed z3 with pip install angr-z3. What's wrong?
I'm developing a jailbroken app on iOS and getting errno 22 when calling
mprotect(p, 1024, PROT_READ | PROT_EXEC)
errno 22 means invalid arguments but I can't figure out whats wrong. I've aligned p to be a multiple of page size, and I've malloced the memory previously before calling mprotect.
Here's my code and sample output
#define PAGESIZE 4096
FILE * pFile;
pFile = fopen ("log.txt","w");
uint32_t code[] = {
0xe2800001, // add r0, r0, #1
0xe12fff1e, // bx lr
};
fprintf(pFile, "Before Execution\n");
p = (uint32_t *)malloc(1024+PAGESIZE-1);
if (!p) {
fprintf(pFile, "Couldn't malloc(1024)");
perror("Couldn't malloc(1024)");
exit(errno);
}
fprintf(pFile, "Malloced to %p\n", p);
p = (uint32_t *)(((uintptr_t)p + PAGESIZE-1) & ~(PAGESIZE-1));
fprintf(pFile, "Moved pointer to %p\n", p);
fprintf(pFile, "Before Compiling\n");
// copy instructions to function
p[0] = code[0];
p[1] = code[1];
fprintf(pFile, "After Compiling\n");
if (mprotect(p, 1024, PROT_READ | PROT_EXEC)) {
int err = errno;
fprintf(pFile, "Couldn't mprotect2: %i\n", errno);
perror("Couldn't mprotect");
exit(errno);
}
And output:
Before Execution
Malloced to 0x13611ec00
Moved pointer 0x13611f000
Before Compiling
After Compiling
Couldn't mprotect2: 22
Fixed this by using posix_memalign(). Turns out I wasn't aligning my pointer to the page size correctly