From 5e9571995faddefacd341a85cd97875c9e354c6a Mon Sep 17 00:00:00 2001 From: Igor Makarov Date: Mon, 19 Jul 2021 17:40:15 +0300 Subject: [PATCH] init --- .github/workflows/main.yml | 18 +++ .gitignore | 11 ++ .rspec | 3 + .rubocop.yml | 24 ++++ CODE_OF_CONDUCT.md | 84 ++++++++++++++ Gemfile | 9 ++ Gemfile.lock | 139 ++++++++++++++++++++++ LICENSE.txt | 21 ++++ README.md | 43 +++++++ Rakefile | 12 ++ bin/setup | 8 ++ bin/xcfconvert | 12 ++ lib/arm2sim.swift | 166 +++++++++++++++++++++++++++ lib/xcframework_converter.rb | 124 ++++++++++++++++++++ lib/xcframework_converter/version.rb | 5 + lib/xcframework_template.plist | 41 +++++++ spec/spec_helper.rb | 15 +++ spec/xcframework_converter_spec.rb | 7 ++ xcframework_converter.gemspec | 28 +++++ 19 files changed, 770 insertions(+) create mode 100644 .github/workflows/main.yml create mode 100644 .gitignore create mode 100644 .rspec create mode 100644 .rubocop.yml create mode 100644 CODE_OF_CONDUCT.md create mode 100644 Gemfile create mode 100644 Gemfile.lock create mode 100644 LICENSE.txt create mode 100644 README.md create mode 100644 Rakefile create mode 100755 bin/setup create mode 100755 bin/xcfconvert create mode 100644 lib/arm2sim.swift create mode 100644 lib/xcframework_converter.rb create mode 100644 lib/xcframework_converter/version.rb create mode 100644 lib/xcframework_template.plist create mode 100644 spec/spec_helper.rb create mode 100644 spec/xcframework_converter_spec.rb create mode 100644 xcframework_converter.gemspec diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..dbe7069 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,18 @@ +name: Ruby + +on: [push,pull_request] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: 2.7.2 + - name: Run the default task + run: | + gem install bundler -v 2.2.3 + bundle install + bundle exec rake diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b04a8c8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +/.bundle/ +/.yardoc +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ + +# rspec failure tracking +.rspec_status diff --git a/.rspec b/.rspec new file mode 100644 index 0000000..34c5164 --- /dev/null +++ b/.rspec @@ -0,0 +1,3 @@ +--format documentation +--color +--require spec_helper diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..62ad893 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,24 @@ +AllCops: + NewCops: disable + +Metrics/ClassLength: + Max: 1000 +Style/StringLiterals: + Enabled: true + EnforcedStyle: single_quotes + +Style/StringLiteralsInInterpolation: + Enabled: true + EnforcedStyle: single_quotes + +Metrics/MethodLength: + Max: 30 + +Layout/LineLength: + Max: 150 + Exclude: + - 'spec/**/*' + +Metrics/BlockLength: + Exclude: + - 'spec/**/*' diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..8d30db8 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,84 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at igormaka@gmail.com. All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, +available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..f1764c6 --- /dev/null +++ b/Gemfile @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +source 'https://rubygems.org' + +gemspec + +gem 'rake', '~> 13.0' +gem 'rspec', '~> 3.0' +gem 'rubocop', '~> 0.80' diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..d24cdd0 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,139 @@ +PATH + remote: . + specs: + xcframework_converter (0.1.0) + cocoapods (~> 1, >= 1.10.0) + xcodeproj (~> 1, >= 1.20.0) + +GEM + remote: https://rubygems.org/ + specs: + CFPropertyList (3.0.3) + activesupport (5.2.6) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 0.7, < 2) + minitest (~> 5.1) + tzinfo (~> 1.1) + addressable (2.8.0) + public_suffix (>= 2.0.2, < 5.0) + algoliasearch (1.27.5) + httpclient (~> 2.8, >= 2.8.3) + json (>= 1.5.1) + ast (2.4.2) + atomos (0.1.3) + claide (1.0.3) + cocoapods (1.10.1) + addressable (~> 2.6) + claide (>= 1.0.2, < 2.0) + cocoapods-core (= 1.10.1) + cocoapods-deintegrate (>= 1.0.3, < 2.0) + cocoapods-downloader (>= 1.4.0, < 2.0) + cocoapods-plugins (>= 1.0.0, < 2.0) + cocoapods-search (>= 1.0.0, < 2.0) + cocoapods-trunk (>= 1.4.0, < 2.0) + cocoapods-try (>= 1.1.0, < 2.0) + colored2 (~> 3.1) + escape (~> 0.0.4) + fourflusher (>= 2.3.0, < 3.0) + gh_inspector (~> 1.0) + molinillo (~> 0.6.6) + nap (~> 1.0) + ruby-macho (~> 1.4) + xcodeproj (>= 1.19.0, < 2.0) + cocoapods-core (1.10.1) + activesupport (> 5.0, < 6) + addressable (~> 2.6) + algoliasearch (~> 1.0) + concurrent-ruby (~> 1.1) + fuzzy_match (~> 2.0.4) + nap (~> 1.0) + netrc (~> 0.11) + public_suffix + typhoeus (~> 1.0) + cocoapods-deintegrate (1.0.4) + cocoapods-downloader (1.4.0) + cocoapods-plugins (1.0.0) + nap + cocoapods-search (1.0.0) + cocoapods-trunk (1.5.0) + nap (>= 0.8, < 2.0) + netrc (~> 0.11) + cocoapods-try (1.2.0) + colored2 (3.1.2) + concurrent-ruby (1.1.9) + diff-lcs (1.4.4) + escape (0.0.4) + ethon (0.14.0) + ffi (>= 1.15.0) + ffi (1.15.3) + fourflusher (2.3.1) + fuzzy_match (2.0.4) + gh_inspector (1.1.3) + httpclient (2.8.3) + i18n (1.8.10) + concurrent-ruby (~> 1.0) + json (2.5.1) + minitest (5.14.4) + molinillo (0.6.6) + nanaimo (0.3.0) + nap (1.1.0) + netrc (0.11.0) + parallel (1.20.1) + parser (3.0.2.0) + ast (~> 2.4.1) + public_suffix (4.0.6) + rainbow (3.0.0) + rake (13.0.6) + regexp_parser (2.1.1) + rexml (3.2.5) + rspec (3.10.0) + rspec-core (~> 3.10.0) + rspec-expectations (~> 3.10.0) + rspec-mocks (~> 3.10.0) + rspec-core (3.10.1) + rspec-support (~> 3.10.0) + rspec-expectations (3.10.1) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.10.0) + rspec-mocks (3.10.2) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.10.0) + rspec-support (3.10.2) + rubocop (0.93.1) + parallel (~> 1.10) + parser (>= 2.7.1.5) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 1.8) + rexml + rubocop-ast (>= 0.6.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 1.4.0, < 2.0) + rubocop-ast (1.8.0) + parser (>= 3.0.1.1) + ruby-macho (1.4.0) + ruby-progressbar (1.11.0) + thread_safe (0.3.6) + typhoeus (1.4.0) + ethon (>= 0.9.0) + tzinfo (1.2.9) + thread_safe (~> 0.1) + unicode-display_width (1.7.0) + xcodeproj (1.20.0) + CFPropertyList (>= 2.3.3, < 4.0) + atomos (~> 0.1.3) + claide (>= 1.0.2, < 2.0) + colored2 (~> 3.1) + nanaimo (~> 0.3.0) + rexml (~> 3.2.4) + +PLATFORMS + arm64-darwin-20 + +DEPENDENCIES + rake (~> 13.0) + rspec (~> 3.0) + rubocop (~> 0.80) + xcframework_converter! + +BUNDLED WITH + 2.2.3 diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..47a9d3a --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2021 Igor Makarov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..fe695e9 --- /dev/null +++ b/README.md @@ -0,0 +1,43 @@ +# XcframeworkConverter + +Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/xcframework_converter`. To experiment with that code, run `bin/console` for an interactive prompt. + +TODO: Delete this and the text above, and describe your gem + +## Installation + +Add this line to your application's Gemfile: + +```ruby +gem 'xcframework_converter' +``` + +And then execute: + + $ bundle install + +Or install it yourself as: + + $ gem install xcframework_converter + +## Usage + +TODO: Write usage instructions here + +## Development + +After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. + +To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org). + +## Contributing + +Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/xcframework_converter. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/xcframework_converter/blob/master/CODE_OF_CONDUCT.md). + +## License + +The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). + +## Code of Conduct + +Everyone interacting in the XcframeworkConverter project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/xcframework_converter/blob/master/CODE_OF_CONDUCT.md). diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..4964751 --- /dev/null +++ b/Rakefile @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +require 'bundler/gem_tasks' +require 'rspec/core/rake_task' + +RSpec::Core::RakeTask.new(:spec) + +require 'rubocop/rake_task' + +RuboCop::RakeTask.new + +task default: %i[spec rubocop] diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..dce67d8 --- /dev/null +++ b/bin/setup @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' +set -vx + +bundle install + +# Do any other automated setup that you need to do here diff --git a/bin/xcfconvert b/bin/xcfconvert new file mode 100755 index 0000000..ac50eb9 --- /dev/null +++ b/bin/xcfconvert @@ -0,0 +1,12 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require 'bundler/setup' +require 'xcframework_converter' + +if ARGV.empty? + warn 'Usage: xcfconvert ' + exit 1 +end + +XCFrameworkConverter.convert_framework_to_xcframework(Pathname.new(ARGV[0]).realpath) diff --git a/lib/arm2sim.swift b/lib/arm2sim.swift new file mode 100644 index 0000000..a3cf243 --- /dev/null +++ b/lib/arm2sim.swift @@ -0,0 +1,166 @@ +import Foundation +import MachO + +// support checking for Mach-O `cmd` and `cmdsize` properties +extension Data { + var loadCommand: UInt32 { + let lc: load_command = withUnsafeBytes { $0.load(as: load_command.self) } + return lc.cmd + } + + var commandSize: Int { + let lc: load_command = withUnsafeBytes { $0.load(as: load_command.self) } + return Int(lc.cmdsize) + } + + func asStruct(fromByteOffset offset: Int = 0) -> T { + return withUnsafeBytes { $0.load(fromByteOffset: offset, as: T.self) } + } +} + +extension Array where Element == Data { + func merge() -> Data { + return reduce(into: Data()) { $0.append($1) } + } +} + +// support peeking at Data contents +extension FileHandle { + func peek(upToCount count: Int) throws -> Data? { + // persist the current offset, since `upToCount` doesn't guarantee all bytes will be read + let originalOffset = offsetInFile + let data = try read(upToCount: count) + try seek(toOffset: originalOffset) + return data + } +} + +enum Transmogrifier { + private static func readBinary(atPath path: String) -> (Data, [Data], Data) { + guard let handle = FileHandle(forReadingAtPath: path) else { + fatalError("Cannot open a handle for the file at \(path). Aborting.") + } + + // chop up the file into a relevant number of segments + let headerData = try! handle.read(upToCount: MemoryLayout.stride)! + + let header: mach_header_64 = headerData.asStruct() + if header.magic != MH_MAGIC_64 || header.cputype != CPU_TYPE_ARM64 { + fatalError("The file is not a correct arm64 binary. Try thinning (via lipo) or unarchiving (via ar) first.") + } + + let loadCommandsData: [Data] = (0...stride) + return try! handle.read(upToCount: Int(loadCommandPeekData!.commandSize))! + } + + let programData = try! handle.readToEnd()! + + try! handle.close() + + return (headerData, loadCommandsData, programData) + } + + private static func updateSegment64(_ data: Data, _ offset: UInt32) -> Data { + // decode both the segment_command_64 and the subsequent section_64s + var segment: segment_command_64 = data.asStruct() + + let sections: [section_64] = (0...stride + index * MemoryLayout.stride + return data.asStruct(fromByteOffset: offset) + } + + // shift segment information by the offset + segment.fileoff += UInt64(offset) + segment.filesize += UInt64(offset) + segment.vmsize += UInt64(offset) + + let offsetSections = sections.map { section -> section_64 in + var section = section + section.offset += UInt32(offset) + section.reloff += section.reloff > 0 ? UInt32(offset) : 0 + return section + } + + var datas = [Data]() + datas.append(Data(bytes: &segment, count: MemoryLayout.stride)) + datas.append(contentsOf: offsetSections.map { section in + var section = section + return Data(bytes: §ion, count: MemoryLayout.stride) + }) + + return datas.merge() + } + + private static func updateVersionMin(_ data: Data, _ offset: UInt32, minos: UInt32, sdk: UInt32) -> Data { + var command = build_version_command(cmd: UInt32(LC_BUILD_VERSION), + cmdsize: UInt32(MemoryLayout.stride), + platform: UInt32(PLATFORM_IOSSIMULATOR), + minos: minos << 16 | 0 << 8 | 0, + sdk: sdk << 16 | 0 << 8 | 0, + ntools: 0) + + return Data(bytes: &command, count: MemoryLayout.stride) + } + + private static func updateDataInCode(_ data: Data, _ offset: UInt32) -> Data { + var command: linkedit_data_command = data.asStruct() + command.dataoff += offset + return Data(bytes: &command, count: data.commandSize) + } + + private static func updateSymTab(_ data: Data, _ offset: UInt32) -> Data { + var command: symtab_command = data.asStruct() + command.stroff += offset + command.symoff += offset + return Data(bytes: &command, count: data.commandSize) + } + + static func processBinary(atPath path: String, minos: UInt32 = 13, sdk: UInt32 = 13) { + guard CommandLine.arguments.count > 1 else { + fatalError("Please add a path to command!") + } + let (headerData, loadCommandsData, programData) = readBinary(atPath: path) + + // `offset` is kind of a magic number here, since we know that's the only meaningful change to binary size + // having a dynamic `offset` requires two passes over the load commands and is left as an exercise to the reader + let offset = UInt32(abs(MemoryLayout.stride - MemoryLayout.stride)) + + let editedCommandsData = loadCommandsData + .map { (lc) -> Data in + switch Int32(lc.loadCommand) { + case LC_SEGMENT_64: + return updateSegment64(lc, offset) + case LC_VERSION_MIN_IPHONEOS: + return updateVersionMin(lc, offset, minos: minos, sdk: sdk) + case LC_DATA_IN_CODE, LC_LINKER_OPTIMIZATION_HINT: + return updateDataInCode(lc, offset) + case LC_SYMTAB: + return updateSymTab(lc, offset) + case LC_BUILD_VERSION: + fatalError("This arm64 binary already contains an LC_BUILD_VERSION load command!") + default: + return lc + } + } + .merge() + + var header: mach_header_64 = headerData.asStruct() + header.sizeofcmds = UInt32(editedCommandsData.count) + + // reassemble the binary + let reworkedData = [ + Data(bytes: &header, count: MemoryLayout.stride), + editedCommandsData, + programData + ].merge() + + // save back to disk + try! reworkedData.write(to: URL(fileURLWithPath: path)) + } +} + +let binaryPath = CommandLine.arguments[1] +let minos = UInt32(CommandLine.arguments[2]) ?? 13 +let sdk = UInt32(CommandLine.arguments[3]) ?? 13 +Transmogrifier.processBinary(atPath: binaryPath, minos: minos, sdk: sdk) diff --git a/lib/xcframework_converter.rb b/lib/xcframework_converter.rb new file mode 100644 index 0000000..e47d3cf --- /dev/null +++ b/lib/xcframework_converter.rb @@ -0,0 +1,124 @@ +# frozen_string_literal: true + +require_relative 'xcframework_converter/version' + +require 'cocoapods' +require 'cocoapods/xcode/xcframework' +require 'fileutils' +require 'xcodeproj' + +# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity + +# Converts a framework (static or dynamic) to XCFrameworks, adding an arm64 simulator patch. +# For more info: +# static libs: https://bogo.wtf/arm64-to-sim.html +# dylibs: https://bogo.wtf/arm64-to-sim-dylibs.html +module XCFrameworkConverter + class << self + def convert_frameworks_to_xcframeworks!(installer) + installer.analysis_result.specifications.each do |spec| + next unless spec.attributes_hash['vendored_frameworks'] + + frameworks = Array(spec.attributes_hash['vendored_frameworks']) + unconverted_frameworks = frameworks.select { |f| File.extname(f) == '.framework' } + next if unconverted_frameworks.empty? + next if spec.local? + + pod_path = installer.sandbox.pod_dir(Pod::Specification.root_name(spec.name)) + convert_xcframeworks_if_present(pod_path) + + converted_frameworks = unconverted_frameworks.map do |path| + Pathname.new(path).sub_ext('.xcframework').to_s + end + spec.attributes_hash['vendored_frameworks'] = frameworks - unconverted_frameworks + converted_frameworks + # some pods put these as a way to NOT support arm64 sim + spec.attributes_hash['pod_target_xcconfig']&.delete('EXCLUDED_ARCHS[sdk=iphonesimulator*]') + spec.attributes_hash['user_target_xcconfig']&.delete('EXCLUDED_ARCHS[sdk=iphonesimulator*]') + end + end + + def convert_xcframeworks_if_present(pod_path) + unconverted_paths = Dir[pod_path.join('**/*.framework')] - Dir[pod_path.join('**/*.xcframework/**/*')] + unconverted_paths.each do |path| + convert_framework_to_xcframework(path) + end + end + + def plist_template_path + Pathname.new(__FILE__).dirname.join('xcframework_template.plist') + end + + def convert_framework_to_xcframework(path) + plist = Xcodeproj::Plist.read_from_path(plist_template_path) + xcframework_path = Pathname.new(path).sub_ext('.xcframework') + xcframework_path.mkdir + plist['AvailableLibraries'].each do |slice| + slice_path = xcframework_path.join(slice['LibraryIdentifier']) + slice_path.mkdir + slice['LibraryPath'] = File.basename(path) + FileUtils.cp_r(path, slice_path) + end + Xcodeproj::Plist.write_to_path(plist, xcframework_path.join('Info.plist')) + FileUtils.rm_rf(path) + final_framework = Pod::Xcode::XCFramework.new(xcframework_path.realpath) + final_framework.slices.each do |slice| + patch_arm_binary(slice) if slice.platform == :ios && slice.platform_variant == :simulator + cleanup_unused_archs(slice) + end + end + + def patch_arm_binary(slice) + require 'macho' + + case slice.build_type.linkage + when :dynamic + patch_arm_binary_dynamic(slice) + when :static + patch_arm_binary_static(slice) + end + end + + def patch_arm_binary_dynamic(slice) + extracted_path = slice.path.join('arm64.dylib') + `xcrun lipo \"#{slice.binary_path}\" -thin arm64 -output \"#{extracted_path}\"` + + file = MachO::MachOFile.new(extracted_path) + sdk_version = file[:LC_VERSION_MIN_IPHONEOS].first.version_string + `xcrun vtool -arch arm64 -set-build-version 7 #{sdk_version} #{sdk_version} -replace -output \"#{extracted_path}\" \"#{extracted_path}\"` + `xcrun lipo \"#{slice.binary_path}\" -replace arm64 \"#{extracted_path}\" -output \"#{slice.binary_path}\"` + extracted_path.rmtree + end + + def arm2sim_path + Pathname.new(__FILE__).dirname.join('arm2sim.swift') + end + + def patch_arm_binary_static(slice) + extracted_path = slice.path.join('arm64.a') + `xcrun lipo \"#{slice.binary_path}\" -thin arm64 -output \"#{extracted_path}\"` + extracted_path_dir = slice.path.join('arm64-objects') + extracted_path_dir.mkdir + `cd \"#{extracted_path_dir}\" ; ar x \"#{extracted_path}\"` + Dir[extracted_path_dir.join('*.o')].each do |object_file| + file = MachO::MachOFile.new(object_file) + sdk_version = file[:LC_VERSION_MIN_IPHONEOS].first.version_string.to_i + `xcrun swift \"#{arm2sim_path}\" \"#{object_file}\" \"#{sdk_version}\" \"#{sdk_version}\"` + end + `cd \"#{extracted_path_dir}\" ; ar crv \"#{extracted_path}\" *.o` + + `xcrun lipo \"#{slice.binary_path}\" -replace arm64 \"#{extracted_path}\" -output \"#{slice.binary_path}\"` + extracted_path_dir.rmtree + extracted_path.rmtree + end + + def cleanup_unused_archs(slice) + supported_archs = slice.supported_archs + unsupported_archs = `xcrun lipo \"#{slice.binary_path}\" -archs`.split - supported_archs + unsupported_archs.each do |arch| + `xcrun lipo \"#{slice.binary_path}\" -remove \"#{arch}\" -output \"#{slice.binary_path}\"` + end + end + end +end + +# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity diff --git a/lib/xcframework_converter/version.rb b/lib/xcframework_converter/version.rb new file mode 100644 index 0000000..633b83e --- /dev/null +++ b/lib/xcframework_converter/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +module XCFrameworkConverter + VERSION = '0.1.0' +end diff --git a/lib/xcframework_template.plist b/lib/xcframework_template.plist new file mode 100644 index 0000000..a209abd --- /dev/null +++ b/lib/xcframework_template.plist @@ -0,0 +1,41 @@ + + + + + AvailableLibraries + + + LibraryIdentifier + ios-arm64_x86_64-simulator + LibraryPath + Placeholder.framework + SupportedArchitectures + + arm64 + x86_64 + + SupportedPlatform + ios + SupportedPlatformVariant + simulator + + + LibraryIdentifier + ios-arm64_armv7 + LibraryPath + Placeholder.framework + SupportedArchitectures + + arm64 + armv7 + + SupportedPlatform + ios + + + CFBundlePackageType + XFWK + XCFrameworkFormatVersion + 1.0 + + diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..aa5b900 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +require 'xcframework_converter' + +RSpec.configure do |config| + # Enable flags like --only-failures and --next-failure + config.example_status_persistence_file_path = '.rspec_status' + + # Disable RSpec exposing methods globally on `Module` and `main` + config.disable_monkey_patching! + + config.expect_with :rspec do |c| + c.syntax = :expect + end +end diff --git a/spec/xcframework_converter_spec.rb b/spec/xcframework_converter_spec.rb new file mode 100644 index 0000000..b8b4488 --- /dev/null +++ b/spec/xcframework_converter_spec.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +RSpec.describe XCFrameworkConverter do + it 'has a version number' do + expect(XCFrameworkConverter::VERSION).not_to be nil + end +end diff --git a/xcframework_converter.gemspec b/xcframework_converter.gemspec new file mode 100644 index 0000000..2a88269 --- /dev/null +++ b/xcframework_converter.gemspec @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +require_relative 'lib/xcframework_converter/version' + +Gem::Specification.new do |spec| + spec.name = 'xcframework_converter' + spec.version = XCFrameworkConverter::VERSION + spec.authors = ['Igor Makarov'] + spec.email = ['igormaka@gmail.com'] + + spec.summary = 'Convert an ancient .framework to an .xcframework.' + spec.description = 'Convert an ancient .framework (dynamic or static) to an .xcframework. Add an arm64 Simulator patch.' + spec.homepage = 'https://github.com/igor-makarov/XCFrameworkConverter' + spec.license = 'MIT' + spec.required_ruby_version = Gem::Requirement.new('>= 2.4.0') + + spec.metadata['homepage_uri'] = spec.homepage + spec.metadata['source_code_uri'] = 'https://github.com/igor-makarov/XCFrameworkConverter' + + # Specify which files should be added to the gem when it is released. + # The `git ls-files -z` loads the files in the RubyGem that have been added into git. + spec.files = %w[README.md] + Dir['lib/**/*.{plist,rb,swift}'] + spec.executables = ['xcfconvert'] + spec.require_paths = ['lib'] + + spec.add_runtime_dependency 'cocoapods', '>= 1.10.0', '~> 1' + spec.add_runtime_dependency 'xcodeproj', '>= 1.20.0', '~> 1' +end