What is build object file extension in iOS? - ios

When I build java object class in a project, build file will be created with .class extension and human unreadable; What about swift build files?
example:
car.java --> build --> car.class
what would be after build?
car.swift --> build --> ?

The compilation process is a bit different with Swift to Java, so there isn't necessarily a direct equivalent.
As the build proceeds though each Swift file will get compiled in to an 'Object' file, ending in a .o extension. Then once they're all built they get linked together to form the binary. If you unpick an iOS app's IPA file, you won't see the individual .o files like how you can see the .class files inside a Java jar file.

One thing I know is that Swift uses LLVM just like Objective-C.
So in Java, we have this (source: W3schools).
And here, for Swift (source: Swift.org)
I hope this helps!

Mach-O format
[LLVM]
In iOS world every sources file - .m, .h, .swift are compiled into executable byte code that is understandable by CPU. These files are also called Mach object(.o) - ABI Mach-O[About] file which contains nexts grouped bytes with a meta-information
Mach-O header - general information like cpu type(CPU_TYPE)
Load Commands - table of contents
Raw segment data - code
__LLVM - bitcode[About]
This groups are repeated for every architecture(Universal library)[About]
`*.swift` -> `*.o` (Mach-O object file)
For example if you created a static library - myLibrary.a. You can use nm[About] command to display name list (symbol table).
nm path/myLibrary.a
As a result you will see a list of *.o files with methods, variables names etc.
To investigate Mach-O file you can use otool[About]
[Mach-O Type]
[Xcode build process]

Related

Why Xcode 7 shows *.tbd instead of *.dylib?

Xcode 7
In Target > BuildPhases > Link Binary With Libraries > tap + button
When choosing frameworks to add, you cannot find *.dylib, you'll see *.tbd instead.
What is the reason for this?
**For people who need dylib, follow from this post
Choose "Add other"
Once in the file selection window do "CMD"+Shift+G (Go to folder) & type /usr/lib/
From /user/lib you can find the *.dylib files
I've scoured Google but the only thing I can find so far is the following quote from the Apple developer forums:
For those who are curious, the .tbd files are new "text-based stub
libraries", that provide a much more compact version of the stub
libraries for use in the SDK, and help to significantly reduce its
download size.
Hopefully more documentation will be coming soon.
Update
As an example, here is the entire contents of libsqlite3.tbd. It is just a text file. Note that the install-name is libsqlite3.dylib.
---
archs: [ armv7, armv7s, arm64 ]
platform: ios
install-name: /usr/lib/libsqlite3.dylib
current-version: 216.4
compatibility-version: 9.0
exports:
- archs: [ armv7, armv7s, arm64 ]
symbols: [ __sqlite3_lockstate, __sqlite3_purgeEligiblePagerCacheMemory,
__sqlite3_system_busy_handler, __sqlite_auto_profile,
__sqlite_auto_profile_syslog, __sqlite_auto_trace,
__sqlite_auto_trace_syslog, _sqlite3OsShmHasMultipleLinks,
_sqlite3OsShmRenamedWhileOpen, _sqlite3OsShmWasTruncated,
_sqlite3OsShmWasUnlinkedWhileOpen, _sqlite3VersionNumber,
_sqlite3VersionString, _sqlite3_aggregate_context,
_sqlite3_aggregate_count, _sqlite3_auto_extension,
_sqlite3_backup_finish, _sqlite3_backup_init, _sqlite3_backup_pagecount,
_sqlite3_backup_remaining, _sqlite3_backup_step,
_sqlite3_bind_blob, _sqlite3_bind_blob64, _sqlite3_bind_double,
_sqlite3_bind_int, _sqlite3_bind_int64, _sqlite3_bind_null,
_sqlite3_bind_parameter_count, _sqlite3_bind_parameter_index,
_sqlite3_bind_parameter_name, _sqlite3_bind_text,
_sqlite3_bind_text16, _sqlite3_bind_text64, _sqlite3_bind_value,
_sqlite3_bind_zeroblob, _sqlite3_blob_bytes, _sqlite3_blob_close,
_sqlite3_blob_open, _sqlite3_blob_read, _sqlite3_blob_reopen,
_sqlite3_blob_write, _sqlite3_busy_handler, _sqlite3_busy_timeout,
_sqlite3_cancel_auto_extension, _sqlite3_changes,
_sqlite3_clear_bindings, _sqlite3_close, _sqlite3_close_v2,
_sqlite3_collation_needed, _sqlite3_collation_needed16,
_sqlite3_column_blob, _sqlite3_column_bytes, _sqlite3_column_bytes16,
_sqlite3_column_count, _sqlite3_column_decltype,
_sqlite3_column_decltype16, _sqlite3_column_double,
_sqlite3_column_int, _sqlite3_column_int64, _sqlite3_column_name,
_sqlite3_column_name16, _sqlite3_column_text, _sqlite3_column_text16,
_sqlite3_column_type, _sqlite3_column_value, _sqlite3_commit_hook,
_sqlite3_compileoption_get, _sqlite3_compileoption_used,
_sqlite3_complete, _sqlite3_complete16, _sqlite3_config,
_sqlite3_context_db_handle, _sqlite3_create_collation,
_sqlite3_create_collation16, _sqlite3_create_collation_v2,
_sqlite3_create_function, _sqlite3_create_function16,
_sqlite3_create_function_v2, _sqlite3_create_module,
_sqlite3_create_module_v2, _sqlite3_data_count,
_sqlite3_data_directory, _sqlite3_db_config, _sqlite3_db_filename,
_sqlite3_db_handle, _sqlite3_db_mutex, _sqlite3_db_readonly,
_sqlite3_db_release_memory, _sqlite3_db_status,
_sqlite3_declare_vtab, _sqlite3_enable_shared_cache,
_sqlite3_errcode, _sqlite3_errmsg, _sqlite3_errmsg16,
_sqlite3_errstr, _sqlite3_exec, _sqlite3_expired,
_sqlite3_extended_errcode, _sqlite3_extended_result_codes,
_sqlite3_file_control, _sqlite3_finalize, _sqlite3_free,
_sqlite3_free_table, _sqlite3_get_autocommit, _sqlite3_get_auxdata,
_sqlite3_get_table, _sqlite3_global_recover, _sqlite3_initialize,
_sqlite3_intarray_bind, _sqlite3_intarray_create,
_sqlite3_interrupt, _sqlite3_last_insert_rowid,
_sqlite3_libversion, _sqlite3_libversion_number,
_sqlite3_limit, _sqlite3_log, _sqlite3_malloc, _sqlite3_malloc64,
_sqlite3_memory_alarm, _sqlite3_memory_highwater,
_sqlite3_memory_used, _sqlite3_mprintf, _sqlite3_msize,
_sqlite3_mutex_alloc, _sqlite3_mutex_enter, _sqlite3_mutex_free,
_sqlite3_mutex_leave, _sqlite3_mutex_try, _sqlite3_next_stmt,
_sqlite3_open, _sqlite3_open16, _sqlite3_open_v2,
_sqlite3_os_end, _sqlite3_os_init, _sqlite3_overload_function,
_sqlite3_prepare, _sqlite3_prepare16, _sqlite3_prepare16_v2,
_sqlite3_prepare_v2, _sqlite3_profile, _sqlite3_progress_handler,
_sqlite3_randomness, _sqlite3_realloc, _sqlite3_realloc64,
_sqlite3_release_memory, _sqlite3_reset, _sqlite3_reset_auto_extension,
_sqlite3_result_blob, _sqlite3_result_blob64, _sqlite3_result_double,
_sqlite3_result_error, _sqlite3_result_error16,
_sqlite3_result_error_code, _sqlite3_result_error_nomem,
_sqlite3_result_error_toobig, _sqlite3_result_int,
_sqlite3_result_int64, _sqlite3_result_null, _sqlite3_result_text,
_sqlite3_result_text16, _sqlite3_result_text16be,
_sqlite3_result_text16le, _sqlite3_result_text64,
_sqlite3_result_value, _sqlite3_result_zeroblob,
_sqlite3_rollback_hook, _sqlite3_rtree_geometry_callback,
_sqlite3_rtree_query_callback, _sqlite3_set_authorizer,
_sqlite3_set_auxdata, _sqlite3_shutdown, _sqlite3_sleep,
_sqlite3_snprintf, _sqlite3_soft_heap_limit, _sqlite3_soft_heap_limit64,
_sqlite3_sourceid, _sqlite3_sql, _sqlite3_status,
_sqlite3_status64, _sqlite3_step, _sqlite3_stmt_busy,
_sqlite3_stmt_readonly, _sqlite3_stmt_status, _sqlite3_strglob,
_sqlite3_stricmp, _sqlite3_strnicmp, _sqlite3_table_column_metadata,
_sqlite3_temp_directory, _sqlite3_test_control,
_sqlite3_thread_cleanup, _sqlite3_threadsafe, _sqlite3_total_changes,
_sqlite3_trace, _sqlite3_transfer_bindings, _sqlite3_update_hook,
_sqlite3_uri_boolean, _sqlite3_uri_int64, _sqlite3_uri_parameter,
_sqlite3_user_data, _sqlite3_value_blob, _sqlite3_value_bytes,
_sqlite3_value_bytes16, _sqlite3_value_double, _sqlite3_value_int,
_sqlite3_value_int64, _sqlite3_value_numeric_type,
_sqlite3_value_text, _sqlite3_value_text16, _sqlite3_value_text16be,
_sqlite3_value_text16le, _sqlite3_value_type, _sqlite3_version,
_sqlite3_vfs_find, _sqlite3_vfs_register, _sqlite3_vfs_unregister,
_sqlite3_vmprintf, _sqlite3_vsnprintf, _sqlite3_vtab_config,
_sqlite3_vtab_on_conflict, _sqlite3_wal_autocheckpoint,
_sqlite3_wal_checkpoint, _sqlite3_wal_checkpoint_v2,
_sqlite3_wal_hook ]
...
I found this and other .tbd files in
Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/lib/
You can also see a .tbd file if you go to the General tab of your Xcode project and then add a library under Linked Frameworks and Libraries. The .tbd file will be copied to your project.
So it appears that the .dylib file is the actual library of binary code that your project is using and is located in the /usr/lib/ directory on the user's device. The .tbd file, on the other hand, is just a text file that is included in your project and serves as a link to the required .dylib binary. Since this text file is much smaller than the binary library, it makes the SDK's download size smaller.
At this point I am only surmising from the information given, so please correct me if I am wrong.
.dylib is the compiled binary that contains the machine code. .tbd is a smaller text file, similar to a cross-platform module map.
Text Based dylib stubs(.tbd)
It is a kind of optimization that means you do not have to copy a .dylib file (which exists on a target) into your bundle (e.g. application). This file does not contain the binary code which has a major impact on the file size.
It is applicable only for:
Dynamic libraries because they are runtime-linked
File should have a relevant path on the target. As a result it is the best place for standard system libraries.
For iOS development you can find .tbd files which you can use here
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/lib
For example libiconv.tbd looks like
This file contains some meta information like:
.dylib location
symbols(class's properties, methods)
architecture
platform

Xcode "no such file or directory" if filename contains $$ sign?

Using xcode 6 and including files with names like Some$$Class.h and Some$$Class.m leads to problems. Xcode shows to error:
clang: error: no such file or directory: '/Users/test/Some$ClassX.m'
clang: error: no input files
How can I force Xcode to handle files with $$in its name correctly?
There is a very! dirty hack.
If you look to the error message, you can see that the build process of Xcode replaces the $$ of Some$$Class.m with a single $. (Obviously there is no problem with Some$$Class.h) It is an escape sequence.
Some$$Class.m -> Some$Class.m
Therefore you can use Some$$$$Class.m to get Some$$Class.m.
Simply add an (empty) File with the name Some$$$$Class.m to your project to show Xcode that it exists. You have to do this once.
Generate your Some$$Class.m as you did as many times as you want.
When building Xcode will believe that it compiles and links Some$$$$Class.m, but in fact compiles and builds Some$$Class.m.
But you should really, really avoid these names. If the files are generated automatically it should be possible to rename them automatically.

Importing CommonCrypto in a Swift framework

How do you import CommonCrypto in a Swift framework for iOS?
I understand how to use CommonCrypto in a Swift app:
You add #import <CommonCrypto/CommonCrypto.h> to the bridging header.
However, Swift frameworks don't support bridging headers. The documentation says:
You can import external frameworks that have a pure Objective-C codebase, a pure Swift codebase, or a mixed-language codebase. The
process for importing an external framework is the same whether the
framework is written in a single language or contains files from both
languages. When you import an external framework, make sure the
Defines Module build setting for the framework you’re importing is set
to Yes.
You can import a framework into any Swift file within a different
target using the following syntax:
import FrameworkName
Unfortunately, import CommonCrypto doesn't work. Neither does adding #import <CommonCrypto/CommonCrypto.h> to the umbrella header.
Something a little simpler and more robust is to create an Aggregate target called "CommonCryptoModuleMap" with a Run Script phase to generate the module map automatically and with the correct Xcode/SDK path:
The Run Script phase should contain this bash:
# This if-statement means we'll only run the main script if the CommonCryptoModuleMap directory doesn't exist
# Because otherwise the rest of the script causes a full recompile for anything where CommonCrypto is a dependency
# Do a "Clean Build Folder" to remove this directory and trigger the rest of the script to run
if [ -d "${BUILT_PRODUCTS_DIR}/CommonCryptoModuleMap" ]; then
echo "${BUILT_PRODUCTS_DIR}/CommonCryptoModuleMap directory already exists, so skipping the rest of the script."
exit 0
fi
mkdir -p "${BUILT_PRODUCTS_DIR}/CommonCryptoModuleMap"
cat <<EOF > "${BUILT_PRODUCTS_DIR}/CommonCryptoModuleMap/module.modulemap"
module CommonCrypto [system] {
header "${SDKROOT}/usr/include/CommonCrypto/CommonCrypto.h"
export *
}
EOF
Using shell code and ${SDKROOT} means you don't have to hard code the Xcode.app path which can vary system-to-system, especially if you use xcode-select to switch to a beta version, or are building on a CI server where multiple versions are installed in non-standard locations. You also don't need to hard code the SDK so this should work for iOS, macOS, etc. You also don't need to have anything sitting in your project's source directory.
After creating this target, make your library/framework depend on it with a Target Dependencies item:
This will ensure the module map is generated before your framework is built.
macOS note: If you're supporting macOS as well, you'll need to add macosx to the Supported Platforms build setting on the new aggregate target you just created, otherwise it won't put the module map in the correct Debug derived data folder with the rest of the framework products.
Next, add the module map's parent directory, ${BUILT_PRODUCTS_DIR}/CommonCryptoModuleMap, to the "Import Paths" build setting under the Swift section (SWIFT_INCLUDE_PATHS):
Remember to add a $(inherited) line if you have search paths defined at the project or xcconfig level.
That's it, you should now be able to import CommonCrypto
Update for Xcode 10
Xcode 10 now ships with a CommonCrypto module map making this workaround unnecessary. If you would like to support both Xcode 9 and 10 you can do a check in the Run Script phase to see if the module map exists or not, e.g.
COMMON_CRYPTO_DIR="${SDKROOT}/usr/include/CommonCrypto"
if [ -f "${COMMON_CRYPTO_DIR}/module.modulemap" ]
then
echo "CommonCrypto already exists, skipping"
else
# generate the module map, using the original code above
fi
You can actually build a solution that "just works" (no need to copy a module.modulemap and SWIFT_INCLUDE_PATHS settings over to your project, as required by other solutions here), but it does require you to create a dummy framework/module that you'll import into your framework proper. We can also ensure it works regardless of platform (iphoneos, iphonesimulator, or macosx).
Add a new framework target to your project and name it after the system library, e.g., "CommonCrypto". (You can delete the umbrella header, CommonCrypto.h.)
Add a new Configuration Settings File and name it, e.g., "CommonCrypto.xcconfig". (Don't check any of your targets for inclusion.) Populate it with the following:
MODULEMAP_FILE[sdk=iphoneos*] = \
$(SRCROOT)/CommonCrypto/iphoneos.modulemap
MODULEMAP_FILE[sdk=iphonesimulator*] = \
$(SRCROOT)/CommonCrypto/iphonesimulator.modulemap
MODULEMAP_FILE[sdk=macosx*] = \
$(SRCROOT)/CommonCrypto/macosx.modulemap
Create the three referenced module map files, above, and populate them with the following:
iphoneos.modulemap
module CommonCrypto [system] {
header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/CommonCrypto/CommonCrypto.h"
export *
}
iphonesimulator.modulemap
module CommonCrypto [system] {
header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/CommonCrypto/CommonCrypto.h"
export *
}
macosx.modulemap
module CommonCrypto [system] {
header "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/CommonCrypto/CommonCrypto.h"
export *
}
(Replace "Xcode.app" with "Xcode-beta.app" if you're running a beta version. Replace 10.11 with your current OS SDK if not running El Capitan.)
On the Info tab of your project settings, under Configurations, set the Debug and Release configurations of CommonCrypto to CommonCrypto (referencing CommonCrypto.xcconfig).
On your framework target's Build Phases tab, add the CommonCrypto framework to Target Dependencies. Additionally add libcommonCrypto.dylib to the Link Binary With Libraries build phase.
Select CommonCrypto.framework in Products and make sure its Target Membership for your wrapper is set to Optional.
You should now be able to build, run and import CommonCrypto in your wrapper framework.
For an example, see how SQLite.swift uses a dummy sqlite3.framework.
I found a GitHub project that successfully uses CommonCrypto in a Swift framework: SHA256-Swift. Also, this article about the same problem with sqlite3 was useful.
Based on the above, the steps are:
1) Create a CommonCrypto directory inside the project directory. Within, create a module.map file. The module map will allow us to use the CommonCrypto library as a module within Swift. Its contents are:
module CommonCrypto [system] {
header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk/usr/include/CommonCrypto/CommonCrypto.h"
link "CommonCrypto"
export *
}
2) In Build Settings, within Swift Compiler - Search Paths, add the CommonCrypto directory to Import Paths (SWIFT_INCLUDE_PATHS).
3) Finally, import CommonCrypto inside your Swift files as any other modules. For example:
import CommonCrypto
extension String {
func hnk_MD5String() -> String {
if let data = self.dataUsingEncoding(NSUTF8StringEncoding)
{
let result = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))
let resultBytes = UnsafeMutablePointer<CUnsignedChar>(result.mutableBytes)
CC_MD5(data.bytes, CC_LONG(data.length), resultBytes)
let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, length: result.length)
let MD5 = NSMutableString()
for c in resultEnumerator {
MD5.appendFormat("%02x", c)
}
return MD5
}
return ""
}
}
Limitations
Using the custom framework in another project fails at compile time with the error missing required module 'CommonCrypto'. This is because the CommonCrypto module does not appear to be included with the custom framework. A workaround is to repeat step 2 (setting Import Paths) in the project that uses the framework.
The module map is not platform independent (it currently points to a specific platform, the iOS 8 Simulator). I don't know how to make the header path relative to the current platform.
Updates for iOS 8 <= We should remove the line link "CommonCrypto", to get the successful compilation.
UPDATE / EDIT
I kept getting the following build error:
ld: library not found for -lCommonCrypto for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Unless I removed the line link "CommonCrypto" from the module.map file I created. Once I removed this line it built ok.
This answer discusses how to make it work inside a framework, and with Cocoapods and Carthage
🐟 modulemap approach
I use modulemap in my wrapper around CommonCrypto https://github.com/onmyway133/arcane, https://github.com/onmyway133/Reindeer
For those getting header not found, please take a look https://github.com/onmyway133/Arcane/issues/4 or run xcode-select --install
Make a folder CCommonCrypto containing module.modulemap
module CCommonCrypto {
header "/usr/include/CommonCrypto/CommonCrypto.h"
export *
}
Go to Built Settings -> Import Paths
${SRCROOT}/Sources/CCommonCrypto
🌳 Cocoapods with modulemap approach
Here is the podspec https://github.com/onmyway133/Arcane/blob/master/Arcane.podspec
s.source_files = 'Sources/**/*.swift'
s.xcconfig = { 'SWIFT_INCLUDE_PATHS' =>
'$(PODS_ROOT)/CommonCryptoSwift/Sources/CCommonCrypto' }
s.preserve_paths = 'Sources/CCommonCrypto/module.modulemap'
Using module_map does not work, see https://github.com/CocoaPods/CocoaPods/issues/5271
Using Local Development Pod with path does not work, see https://github.com/CocoaPods/CocoaPods/issues/809
That's why you see that my Example Podfile https://github.com/onmyway133/CommonCrypto.swift/blob/master/Example/CommonCryptoSwiftDemo/Podfile points to the git repo
target 'CommonCryptoSwiftDemo' do
pod 'CommonCryptoSwift', :git => 'https://github.com/onmyway133/CommonCrypto.swift'
end
🐘 public header approach
Ji is a wrapper around libxml2, and it uses public header approach
It has a header file https://github.com/honghaoz/Ji/blob/master/Source/Ji.h with Target Membership set to Public
It has a list of header files for libxml2 https://github.com/honghaoz/Ji/tree/master/Source/Ji-libxml
It has Build Settings -> Header Search Paths
$(SDKROOT)/usr/include/libxml2
It has Build Settings -> Other Linker Flags
-lxml2
🐏 Cocoapods with public header approach
Take a look at the podspec https://github.com/honghaoz/Ji/blob/master/Ji.podspec
s.libraries = "xml2"
s.xcconfig = { 'HEADER_SEARCH_PATHS' => '$(SDKROOT)/usr/include/libxml2', 'OTHER_LDFLAGS' => '-lxml2' }
🐝 Interesting related posts
How to call C from Swift?
https://spin.atomicobject.com/2015/02/23/c-libraries-swift/
Good news! Swift 4.2 (Xcode 10) finally provides CommonCrypto!
Just add import CommonCrypto in your swift file.
WARNING: iTunesConnect may reject apps that are using this method.
New member on my team accidentally broke the solution given by one of the top answers, so I decided to consolidate it in a small wrapper project called CommonCryptoModule. You can install it manually or via Cocoapods:
pod 'CommonCryptoModule', '~> 1.0.2'
Then, all you have to do is to import the module where you need CommonCrypto, like so:
import CommonCryptoModule
Hope someone else finds this useful.
I think I have an improvement to Mike Weller's excellent work.
Add a Run Script phase before the Compile Sources phase containing this bash:
# This if-statement means we'll only run the main script if the
# CommonCrypto.framework directory doesn't exist because otherwise
# the rest of the script causes a full recompile for anything
# where CommonCrypto is a dependency
# Do a "Clean Build Folder" to remove this directory and trigger
# the rest of the script to run
FRAMEWORK_DIR="${BUILT_PRODUCTS_DIR}/CommonCrypto.framework"
if [ -d "${FRAMEWORK_DIR}" ]; then
echo "${FRAMEWORK_DIR} already exists, so skipping the rest of the script."
exit 0
fi
mkdir -p "${FRAMEWORK_DIR}/Modules"
cat <<EOF > "${FRAMEWORK_DIR}/Modules/module.modulemap"
module CommonCrypto [system] {
header "${SDKROOT}/usr/include/CommonCrypto/CommonCrypto.h"
export *
}
EOF
ln -sf "${SDKROOT}/usr/include/CommonCrypto" "${FRAMEWORK_DIR}/Headers"
This script constructs a bare bones framework with the module.map in the correct place and then relies on Xcode's automatic search of BUILT_PRODUCTS_DIR for frameworks.
I linked the original CommonCrypto include folder as the framework's Headers folder so the result should also function for Objective C projects.
For anyone using swift 4.2 with Xcode 10:
CommonCrypto module is now provided by the system, so you can directly import it like any other system framework.
import CommonCrypto
#mogstad has been kind enough to wrap #stephencelis solution in a Cocoapod:
pod 'libCommonCrypto'
The other pods available did not work for me.
The modulemap solutions can be good, and are robust against SDK changes, but I've found them awkward to use in practice, and not as reliable as I'd like when handing things out to others. To try to make it all more foolproof, I went a different way:
Just copy the headers.
I know, fragile. But Apple almost never makes significant changes to CommonCrypto and I'm living the dream that they will not change it in any significant way without also finally making CommonCrypto a modular header.
By "copy the headers" I mean "cut and paste all of the headers you need into one massive header in your project just like the preprocessor would do." As an example of this that you can copy or adapt, see RNCryptor.h.
Note that all of these files are licensed under APSL 2.0, and this approach intentionally maintains the copyright and license notices. My concatenation step is licensed under MIT, and that only applies up to the next license notice).
I am not saying this is a beautiful solution, but so far it seems to have been an incredibly simple solution to both implement and support.
I know this is an old question. But I figure out an alternative way to use the library in Swift project, which might be helpful for those who don't want to import framework introduced in these answers.
In Swift project, create a Objective-C bridging header, create NSData category (or custom class that to use the library) in Objective-C. The only drawback would be that you have to write all implementation code in Objective-C.
For example:
#import "NSData+NSDataEncryptionExtension.h"
#import <CommonCrypto/CommonCryptor.h>
#implementation NSData (NSDataEncryptionExtension)
- (NSData *)AES256EncryptWithKey:(NSString *)key {
//do something
}
- (NSData *)AES256DecryptWithKey:(NSString *)key {
//do something
}
And then in your objective-c bridging header, add this
#import "NSData+NSDataEncryptionExtension.h"
And then in Swift class do similar thing:
public extension String {
func encryp(withKey key:String) -> String? {
if let data = self.data(using: .utf8), let encrypedData = NSData(data: data).aes256Encrypt(withKey: key) {
return encrypedData.base64EncodedString()
}
return nil
}
func decryp(withKey key:String) -> String? {
if let data = NSData(base64Encoded: self, options: []), let decrypedData = data.aes256Decrypt(withKey: key) {
return decrypedData.UTF8String
}
return nil
}
}
It works as expected.
I've added some cocoapods magic to jjrscott's answer in case you need to use CommonCrypto in your cocoapods library.
1) Add this line to your podspec:
s.script_phase = { :name => 'CommonCrypto', :script => 'sh $PROJECT_DIR/../../install_common_crypto.sh', :execution_position => :before_compile }
2) Save this in your library folder or wherever you like (however don't forget to change the script_phase accordingly ...)
# This if-statement means we'll only run the main script if the
# CommonCrypto.framework directory doesn't exist because otherwise
# the rest of the script causes a full recompile for anything
# where CommonCrypto is a dependency
# Do a "Clean Build Folder" to remove this directory and trigger
# the rest of the script to run
FRAMEWORK_DIR="${BUILT_PRODUCTS_DIR}/CommonCrypto.framework"
if [ -d "${FRAMEWORK_DIR}" ]; then
echo "${FRAMEWORK_DIR} already exists, so skipping the rest of the script."
exit 0
fi
mkdir -p "${FRAMEWORK_DIR}/Modules"
echo "module CommonCrypto [system] {
header "${SDKROOT}/usr/include/CommonCrypto/CommonCrypto.h"
export *
}" >> "${FRAMEWORK_DIR}/Modules/module.modulemap"
ln -sf "${SDKROOT}/usr/include/CommonCrypto" "${FRAMEWORK_DIR}/Headers"
Works like a charm :)
I'm not sure if something's changed with Xcode 9.2 but it's now much simpler to achieve this. The only things I had to do are create a folder called "CommonCrypto" in my framework project directory and create two files inside it, one called "cc.h" as follows:
#include <CommonCrypto/CommonCrypto.h>
#include <CommonCrypto/CommonRandom.h>
And another called module.modulemap:
module CommonCrypto {
export *
header "cc.h"
}
(I don't know why you can't reference header files from the SDKROOT area directly in a modulemap file but I couldn't get it to work)
The third thing is to find the "Import Paths" setting and set to $(SRCROOT).
In fact you can set it to whatever folder you want the CommonCrypto folder to be under, if you don't want it at the root level.
After this you should be able to use
import CommonCrypto
In any swift file and all the types/functions/etc. are available.
A word of warning though - if your app uses libCommonCrypto (or libcoreCrypto) it's exceptionally easy for a not-too-sophisticated hacker to attach a debugger to your app and find out what keys are being passed to these functions.
In case you have the below issue :
ld: library not found for -lapple_crypto
clang: error: linker command failed with exit code 1 (use -v to see invocation)
In Xcode 10, Swift 4.0. CommonCrypto is a part of the framework.
Add
import CommonCrypto
Remove
CommonCrpto lib file from link binary with libraries from Build
phases
import CommonCrypto from Bridging header
This worked for me!
It happened the same to me after updating Xcode.
I tried everything I can do such as reinstalling cocoapods and cleaning the project, but it didn't work.
Now it's been solved after restart the system.
It's very simple. Add
#import <CommonCrypto/CommonCrypto.h>
to a .h file (the bridging header file of your project). As a convention you can call it YourProjectName-Bridging-Header.h.
Then go to your project Build Settings and look for Swift Compiler - Code Generation. Under it, add the name of your bridging header to the entry "Objetive-C Bridging Header".
You're done. No imports required in your Swift code. Any public Objective-C headers listed in this bridging header file will be visible to Swift.

Remove the path in objcopy symbol names

I need to include a binary program in my project. I use objcopy to create an object file from a binary file. The object file can be linked in my program. objcopy creates appropriate symbols to access the binary data.
Example
objcopy -I binary -O elf32-littlearm --binary-architecture arm D:\Src\data.jpg data.o
The generated symbols are:
_binary_D__Src_data_jpg_end
_binary_D__Src_data_jpg_size
_binary_D__Src_data_jpg_start
The problem is that the symbols include the path to the binary file D__Src_. This may help when binary files are included from different location. But it bothers me that the symbols changes when I get the file from a different location. Since this shall run on several build stations, the path can't be stripped with the --redefine-sym option.
How do I get rid of the path in the symbol name?
I solved this problem by using this switch in objcopy:
--prefix-sections=abc
This gives a way to uniquely identify the data in your binary object file (ex. binary.o)
In your linker script you can then define your own labels around where you include the binary.o. Since you are no longer referencing anything in binary.o the binary will be thrown out by the linker if you use -gc-sections switch. The section in binary.o will now be abc.data. Use KEEP in your linker script to tell the linker not to throw out binary.o. Your linker script will contain the following:
__binary_start__ = .;
KEEP(*(abc.data))
binary.o
*(abc.data)
. = ALIGN(4);
__binary_end__ = .;
The switch --localize-symbols works for me.

LIB file output locations for Delphi 2009 packages

When building a Delphi 2009 component package, how do you specify which directory should contain the resulting .hpp and .lib files needed for C++ Builder users?
On the Project|Options|Delphi Compiler|Linking page, the first two items are C++Builder .hpp output directory and C++Buidler .obj output directory should do what you want. The .lib and .bpi files. However, it seems that there is a bit of a bug in how these options are passed to the compiler... I'll speak with the engineer responsible about it.
From the command-line DCC32 you can use the following to control where to place these items:
-N0<path> = unit .dcu output directory
-NH<path> = unit .hpp output directory
-NO<path> = unit .obj output directory
-NB<path> = unit .bpi output directory
Note that the -NB switch AFAICR, also controls where the .lib file goes as well.
There is a known bug: http://qc.embarcadero.com/wc/qcmain.aspx?d=67513
This is /expected/ to be fixed in the forthcoming Update 3. (Don't worry about the 10.0 resolved in build number, that is a mistake that will be corrected when Update 3 is released and all the bug fixes get synchronized back to QC)
As far as I know, you can't. None of the directory options seem to control it. However, you could probably define a post-build event (Project->Options->Build events) which would copy the files to where you wanted them.

Resources