Ignoring Registervalidatefunction() for Flag Pointer 0X10Ef76Ec0: No Flag Found at That Address in Xcode

Black Screen in Google Cardboard VR app for IOS

What worked for me:

Downgrade your version of unity to 2018.3

Check for internet connection with Swift

To solve the 4G issue mentioned in the comments I have used @AshleyMills reachability implementation as a reference and rewritten Reachability for Swift 3.1:

updated: Xcode 10.1 • Swift 4 or later


Reachability.swift file

import Foundation
import SystemConfiguration

class Reachability {
var hostname: String?
var isRunning = false
var isReachableOnWWAN: Bool
var reachability: SCNetworkReachability?
var reachabilityFlags = SCNetworkReachabilityFlags()
let reachabilitySerialQueue = DispatchQueue(label: "ReachabilityQueue")
init(hostname: String) throws {
guard let reachability = SCNetworkReachabilityCreateWithName(nil, hostname) else {
throw Network.Error.failedToCreateWith(hostname)
}
self.reachability = reachability
self.hostname = hostname
isReachableOnWWAN = true
try start()
}
init() throws {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let reachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
throw Network.Error.failedToInitializeWith(zeroAddress)
}
self.reachability = reachability
isReachableOnWWAN = true
try start()
}
var status: Network.Status {
return !isConnectedToNetwork ? .unreachable :
isReachableViaWiFi ? .wifi :
isRunningOnDevice ? .wwan : .unreachable
}
var isRunningOnDevice: Bool = {
#if targetEnvironment(simulator)
return false
#else
return true
#endif
}()
deinit { stop() }
}

extension Reachability {

func start() throws {
guard let reachability = reachability, !isRunning else { return }
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = Unmanaged<Reachability>.passUnretained(self).toOpaque()
guard SCNetworkReachabilitySetCallback(reachability, callout, &context) else { stop()
throw Network.Error.failedToSetCallout
}
guard SCNetworkReachabilitySetDispatchQueue(reachability, reachabilitySerialQueue) else { stop()
throw Network.Error.failedToSetDispatchQueue
}
reachabilitySerialQueue.async { self.flagsChanged() }
isRunning = true
}

func stop() {
defer { isRunning = false }
guard let reachability = reachability else { return }
SCNetworkReachabilitySetCallback(reachability, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachability, nil)
self.reachability = nil
}

var isConnectedToNetwork: Bool {
return isReachable &&
!isConnectionRequiredAndTransientConnection &&
!(isRunningOnDevice && isWWAN && !isReachableOnWWAN)
}

var isReachableViaWiFi: Bool {
return isReachable && isRunningOnDevice && !isWWAN
}

/// Flags that indicate the reachability of a network node name or address, including whether a connection is required, and whether some user intervention might be required when establishing a connection.
var flags: SCNetworkReachabilityFlags? {
guard let reachability = reachability else { return nil }
var flags = SCNetworkReachabilityFlags()
return withUnsafeMutablePointer(to: &flags) {
SCNetworkReachabilityGetFlags(reachability, UnsafeMutablePointer($0))
} ? flags : nil
}

/// compares the current flags with the previous flags and if changed posts a flagsChanged notification
func flagsChanged() {
guard let flags = flags, flags != reachabilityFlags else { return }
reachabilityFlags = flags
NotificationCenter.default.post(name: .flagsChanged, object: self)
}

/// The specified node name or address can be reached via a transient connection, such as PPP.
var transientConnection: Bool { return flags?.contains(.transientConnection) == true }

/// The specified node name or address can be reached using the current network configuration.
var isReachable: Bool { return flags?.contains(.reachable) == true }

/// The specified node name or address can be reached using the current network configuration, but a connection must first be established. If this flag is set, the kSCNetworkReachabilityFlagsConnectionOnTraffic flag, kSCNetworkReachabilityFlagsConnectionOnDemand flag, or kSCNetworkReachabilityFlagsIsWWAN flag is also typically set to indicate the type of connection required. If the user must manually make the connection, the kSCNetworkReachabilityFlagsInterventionRequired flag is also set.
var connectionRequired: Bool { return flags?.contains(.connectionRequired) == true }

/// The specified node name or address can be reached using the current network configuration, but a connection must first be established. Any traffic directed to the specified name or address will initiate the connection.
var connectionOnTraffic: Bool { return flags?.contains(.connectionOnTraffic) == true }

/// The specified node name or address can be reached using the current network configuration, but a connection must first be established.
var interventionRequired: Bool { return flags?.contains(.interventionRequired) == true }

/// The specified node name or address can be reached using the current network configuration, but a connection must first be established. The connection will be established "On Demand" by the CFSocketStream programming interface (see CFStream Socket Additions for information on this). Other functions will not establish the connection.
var connectionOnDemand: Bool { return flags?.contains(.connectionOnDemand) == true }

/// The specified node name or address is one that is associated with a network interface on the current system.
var isLocalAddress: Bool { return flags?.contains(.isLocalAddress) == true }

/// Network traffic to the specified node name or address will not go through a gateway, but is routed directly to one of the interfaces in the system.
var isDirect: Bool { return flags?.contains(.isDirect) == true }

/// The specified node name or address can be reached via a cellular connection, such as EDGE or GPRS.
var isWWAN: Bool { return flags?.contains(.isWWAN) == true }

/// The specified node name or address can be reached using the current network configuration, but a connection must first be established. If this flag is set
/// The specified node name or address can be reached via a transient connection, such as PPP.
var isConnectionRequiredAndTransientConnection: Bool {
return (flags?.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]) == true
}
}

func callout(reachability: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) {
guard let info = info else { return }
DispatchQueue.main.async {
Unmanaged<Reachability>
.fromOpaque(info)
.takeUnretainedValue()
.flagsChanged()
}
}

extension Notification.Name {
static let flagsChanged = Notification.Name("FlagsChanged")
}

struct Network {
static var reachability: Reachability!
enum Status: String {
case unreachable, wifi, wwan
}
enum Error: Swift.Error {
case failedToSetCallout
case failedToSetDispatchQueue
case failedToCreateWith(String)
case failedToInitializeWith(sockaddr_in)
}
}

Usage

Initialize it in your AppDelegate.swift didFinishLaunchingWithOptions method and handle any errors that might occur:

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
do {
try Network.reachability = Reachability(hostname: "www.google.com")
}
catch {
switch error as? Network.Error {
case let .failedToCreateWith(hostname)?:
print("Network error:\nFailed to create reachability object With host named:", hostname)
case let .failedToInitializeWith(address)?:
print("Network error:\nFailed to initialize reachability object With address:", address)
case .failedToSetCallout?:
print("Network error:\nFailed to set callout")
case .failedToSetDispatchQueue?:
print("Network error:\nFailed to set DispatchQueue")
case .none:
print(error)
}
}
return true
}
}

And a view controller sample:

import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default
.addObserver(self,
selector: #selector(statusManager),
name: .flagsChanged,
object: nil)
updateUserInterface()
}
func updateUserInterface() {
switch Network.reachability.status {
case .unreachable:
view.backgroundColor = .red
case .wwan:
view.backgroundColor = .yellow
case .wifi:
view.backgroundColor = .green
}
print("Reachability Summary")
print("Status:", Network.reachability.status)
print("HostName:", Network.reachability.hostname ?? "nil")
print("Reachable:", Network.reachability.isReachable)
print("Wifi:", Network.reachability.isReachableViaWiFi)
}
@objc func statusManager(_ notification: Notification) {
updateUserInterface()
}
}

Sample Project

Static analyser issues with command line tools

I just ran into this issue and assume it is a bug with Clang. I think I found a workaround though.

Try replacing this

-w -Xanalyzer -analyzer-disable-checker

with this ridiculously long line (keep scrolling to the right to see it all):

-w -Xanalyzer -analyzer-disable-checker -Xanalyzer alpha -Xanalyzer -analyzer-disable-checker -Xanalyzer core -Xanalyzer -analyzer-disable-checker -Xanalyzer cplusplus -Xanalyzer -analyzer-disable-checker -Xanalyzer deadcode -Xanalyzer -analyzer-disable-checker -Xanalyzer debug -Xanalyzer -analyzer-disable-checker -Xanalyzer llvm -Xanalyzer -analyzer-disable-checker -Xanalyzer osx -Xanalyzer -analyzer-disable-checker -Xanalyzer security -Xanalyzer -analyzer-disable-checker -Xanalyzer unix -Xanalyzer -analyzer-disable-checker -Xanalyzer insecureAPI

OK, so here is how I got to that. It looks like Clang has a hierarchy of "Static Analyzer Checkers" and you can disable them individually or by group.

As an example the DeadStore checker is "deadcode.DeadStores" so you can disable it like this:

-Xanalyzer -analyzer-disable-checker -Xanalyzer deadcode.DeadStores

Alternatively you can disable ALL deadcode related checkers by specifying just "deadcode" like this:

-Xanalyzer -analyzer-disable-checker -Xanalyzer deadcode

You can get a list of all the checkers with this command:

clang -cc1 -analyzer-checker-help

It currently outputs the following:

OVERVIEW: Clang Static Analyzer Checkers List

USAGE: -analyzer-checker <CHECKER or PACKAGE,...>

CHECKERS:
alpha.core.BoolAssignment Warn about assigning non-{0,1} values to Boolean variables
alpha.core.CastSize Check when casting a malloc'ed type T, whether the size is a multiple of the size of T
alpha.core.CastToStruct Check for cast from non-struct pointer to struct pointer
alpha.core.FixedAddr Check for assignment of a fixed address to a pointer
alpha.core.PointerArithm Check for pointer arithmetic on locations other than array elements
alpha.core.PointerSub Check for pointer subtractions on two pointers pointing to different memory chunks
alpha.core.SizeofPtr Warn about unintended use of sizeof() on pointer expressions
alpha.cplusplus.NewDeleteLeaks Check for memory leaks. Traces memory managed by new/delete.
alpha.cplusplus.VirtualCall Check virtual function calls during construction or destruction
alpha.deadcode.IdempotentOperations
Warn about idempotent operations
alpha.deadcode.UnreachableCode Check unreachable code
alpha.osx.cocoa.Dealloc Warn about Objective-C classes that lack a correct implementation of -dealloc
alpha.osx.cocoa.DirectIvarAssignment
Check for direct assignments to instance variables
alpha.osx.cocoa.DirectIvarAssignmentForAnnotatedFunctions
Check for direct assignments to instance variables in the methods annotated with objc_no_direct_instance_variable_assignment
alpha.osx.cocoa.InstanceVariableInvalidation
Check that the invalidatable instance variables are invalidated in the methods annotated with objc_instance_variable_invalidator
alpha.osx.cocoa.MissingInvalidationMethod
Check that the invalidation methods are present in classes that contain invalidatable instance variables
alpha.osx.cocoa.MissingSuperCall
Warn about Objective-C methods that lack a necessary call to super
alpha.security.ArrayBound Warn about buffer overflows (older checker)
alpha.security.ArrayBoundV2 Warn about buffer overflows (newer checker)
alpha.security.MallocOverflow Check for overflows in the arguments to malloc()
alpha.security.ReturnPtrRange Check for an out-of-bound pointer being returned to callers
alpha.security.taint.TaintPropagation
Generate taint information used by other checkers
alpha.unix.Chroot Check improper use of chroot
alpha.unix.MallocWithAnnotations
Check for memory leaks, double free, and use-after-free problems. Traces memory managed by malloc()/free(). Assumes that all user-defined functions which might free a pointer are annotated.
alpha.unix.PthreadLock Simple lock -> unlock checker
alpha.unix.SimpleStream Check for misuses of stream APIs
alpha.unix.Stream Check stream handling functions
alpha.unix.cstring.BufferOverlap
Checks for overlap in two buffer arguments
alpha.unix.cstring.NotNullTerminated
Check for arguments which are not null-terminating strings
alpha.unix.cstring.OutOfBounds Check for out-of-bounds access in string functions
core.CallAndMessage Check for logical errors for function calls and Objective-C message expressions (e.g., uninitialized arguments, null function pointers)
core.DivideZero Check for division by zero
core.DynamicTypePropagation Generate dynamic type information
core.NonNullParamChecker Check for null pointers passed as arguments to a function whose arguments are references or marked with the 'nonnull' attribute
core.NullDereference Check for dereferences of null pointers
core.StackAddressEscape Check that addresses to stack memory do not escape the function
core.UndefinedBinaryOperatorResult
Check for undefined results of binary operators
core.VLASize Check for declarations of VLA of undefined or zero size
core.builtin.BuiltinFunctions Evaluate compiler builtin functions (e.g., alloca())
core.builtin.NoReturnFunctions Evaluate "panic" functions that are known to not return to the caller
core.uninitialized.ArraySubscript
Check for uninitialized values used as array subscripts
core.uninitialized.Assign Check for assigning uninitialized values
core.uninitialized.Branch Check for uninitialized values used as branch conditions
core.uninitialized.CapturedBlockVariable
Check for blocks that capture uninitialized values
core.uninitialized.UndefReturn Check for uninitialized values being returned to the caller
cplusplus.NewDelete Check for double-free and use-after-free problems. Traces memory managed by new/delete.
deadcode.DeadStores Check for values stored to variables that are never read afterwards
debug.ConfigDumper Dump config table
debug.DumpCFG Display Control-Flow Graphs
debug.DumpCallGraph Display Call Graph
debug.DumpCalls Print calls as they are traversed by the engine
debug.DumpDominators Print the dominance tree for a given CFG
debug.DumpLiveVars Print results of live variable analysis
debug.DumpTraversal Print branch conditions as they are traversed by the engine
debug.ExprInspection Check the analyzer's understanding of expressions
debug.Stats Emit warnings with analyzer statistics
debug.TaintTest Mark tainted symbols as such.
debug.ViewCFG View Control-Flow Graphs using GraphViz
debug.ViewCallGraph View Call Graph using GraphViz
llvm.Conventions Check code for LLVM codebase conventions
osx.API Check for proper uses of various Apple APIs
osx.SecKeychainAPI Check for proper uses of Secure Keychain APIs
osx.cocoa.AtSync Check for nil pointers used as mutexes for @synchronized
osx.cocoa.ClassRelease Check for sending 'retain', 'release', or 'autorelease' directly to a Class
osx.cocoa.IncompatibleMethodTypes
Warn about Objective-C method signatures with type incompatibilities
osx.cocoa.Loops Improved modeling of loops using Cocoa collection types
osx.cocoa.NSAutoreleasePool Warn for suboptimal uses of NSAutoreleasePool in Objective-C GC mode
osx.cocoa.NSError Check usage of NSError** parameters
osx.cocoa.NilArg Check for prohibited nil arguments to ObjC method calls
osx.cocoa.NonNilReturnValue Model the APIs that are guaranteed to return a non-nil value
osx.cocoa.RetainCount Check for leaks and improper reference count management
osx.cocoa.SelfInit Check that 'self' is properly initialized inside an initializer method
osx.cocoa.UnusedIvars Warn about private ivars that are never used
osx.cocoa.VariadicMethodTypes Check for passing non-Objective-C types to variadic collection initialization methods that expect only Objective-C types
osx.coreFoundation.CFError Check usage of CFErrorRef* parameters
osx.coreFoundation.CFNumber Check for proper uses of CFNumberCreate
osx.coreFoundation.CFRetainRelease
Check for null arguments to CFRetain/CFRelease/CFMakeCollectable
osx.coreFoundation.containers.OutOfBounds
Checks for index out-of-bounds when using 'CFArray' API
osx.coreFoundation.containers.PointerSizedValues
Warns if 'CFArray', 'CFDictionary', 'CFSet' are created with non-pointer-size values
security.FloatLoopCounter Warn on using a floating point value as a loop counter (CERT: FLP30-C, FLP30-CPP)
security.insecureAPI.UncheckedReturn
Warn on uses of functions whose return values must be always checked
security.insecureAPI.getpw Warn on uses of the 'getpw' function
security.insecureAPI.gets Warn on uses of the 'gets' function
security.insecureAPI.mkstemp Warn when 'mkstemp' is passed fewer than 6 X's in the format string
security.insecureAPI.mktemp Warn on uses of the 'mktemp' function
security.insecureAPI.rand Warn on uses of the 'rand', 'random', and related functions
security.insecureAPI.strcpy Warn on uses of the 'strcpy' and 'strcat' functions
security.insecureAPI.vfork Warn on uses of the 'vfork' function
unix.API Check calls to various UNIX/Posix functions
unix.Malloc Check for memory leaks, double free, and use-after-free problems. Traces memory managed by malloc()/free().
unix.MallocSizeof Check for dubious malloc arguments involving sizeof
unix.MismatchedDeallocator Check for mismatched deallocators.
unix.cstring.BadSizeArg Check the size argument passed into C string functions for common erroneous patterns
unix.cstring.NullArg Check for null pointers being passed as arguments to C string functions

The long command line I provided above in my answer disables all 9 top level checkers:
alpha, core, cplusplus, deadcode, debug, llvm, osx, security, and unix PLUS "insecureAPI" based on the comments below as it seems disabling security doesn't also disable security.insecureAPI.

Hopefully this is equivalent to not running the analyzer at all.

For more info see the Checker Developer Manual here: http://clang-analyzer.llvm.org/checker_dev_manual.html

What are best practices that you use when writing Objective-C and Cocoa?

There are a few things I have started to do that I do not think are standard:

1) With the advent of properties, I no longer use "_" to prefix "private" class variables. After all, if a variable can be accessed by other classes shouldn't there be a property for it? I always disliked the "_" prefix for making code uglier, and now I can leave it out.

2) Speaking of private things, I prefer to place private method definitions within the .m file in a class extension like so:

#import "MyClass.h"

@interface MyClass ()
- (void) someMethod;
- (void) someOtherMethod;
@end

@implementation MyClass

Why clutter up the .h file with things outsiders should not care about? The empty () works for private categories in the .m file, and issues compile warnings if you do not implement the methods declared.

3) I have taken to putting dealloc at the top of the .m file, just below the @synthesize directives. Shouldn't what you dealloc be at the top of the list of things you want to think about in a class? That is especially true in an environment like the iPhone.

3.5) In table cells, make every element (including the cell itself) opaque for performance. That means setting the appropriate background color in everything.

3.6) When using an NSURLConnection, as a rule you may well want to implement the delegate method:

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return nil;
}

I find most web calls are very singular and it's more the exception than the rule you'll be wanting responses cached, especially for web service calls. Implementing the method as shown disables caching of responses.

Also of interest, are some good iPhone specific tips from Joseph Mattiello (received in an iPhone mailing list). There are more, but these were the most generally useful I thought (note that a few bits have now been slightly edited from the original to include details offered in responses):

4) Only use double precision if you have to, such as when working with CoreLocation. Make sure you end your constants in 'f' to make gcc store them as floats.

float val = someFloat * 2.2f;

This is mostly important when someFloat may actually be a double, you don't need the mixed-mode math, since you're losing precision in 'val' on storage. While floating-point numbers are supported in hardware on iPhones, it may still take more time to do double-precision arithmetic as opposed to single precision. References:

  • Double vs float on the iPhone
  • iPhone/iPad double precision math

On the older phones supposedly calculations operate at the same speed but you can have more single precision components in registers than doubles, so for many calculations single precision will end up being faster.

5) Set your properties as nonatomic. They're atomic by default and upon synthesis, semaphore code will be created to prevent multi-threading problems. 99% of you probably don't need to worry about this and the code is much less bloated and more memory-efficient when set to nonatomic.

6) SQLite can be a very, very fast way to cache large data sets. A map application for instance can cache its tiles into SQLite files. The most expensive part is disk I/O. Avoid many small writes by sending BEGIN; and COMMIT; between large blocks. We use a 2 second timer for instance that resets on each new submit. When it expires, we send COMMIT; , which causes all your writes to go in one large chunk. SQLite stores transaction data to disk and doing this Begin/End wrapping avoids creation of many transaction files, grouping all of the transactions into one file.

Also, SQL will block your GUI if it's on your main thread. If you have a very long query, It's a good idea to store your queries as static objects, and run your SQL on a separate thread. Make sure to wrap anything that modifies the database for query strings in @synchronize() {} blocks. For short queries just leave things on the main thread for easier convenience.

More SQLite optimization tips are here, though the document appears out of date many of the points are probably still good;

http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html



Related Topics



Leave a reply



Submit