[문제해결] Xcode Error "Command SwiftCompile failed with a nonzero exit code"

Young Bin Lee·2023년 1월 18일

목표

  • Xcode 컴파일 중 나타난 Command SwiftCompile failed with a nonzero exit code 에러를 해결해보자

상황

  • Tuist를 사용하는 프로젝트에서 타겟 중 하나가 Release build 시 상기 에러를 발생시킴
  • Debug build에서는 에러가 발생하지 않음
  • 에러 로그는 다음과 같음
1.	Apple Swift version 5.7.2 (swiftlang-5.7.2.135.5 clang-1400.0.29.51)
2.	Compiling with the current language version
3.	While evaluating request ExecuteSILPipelineRequest(Run pipelines { PrepareOptimizationPasses, EarlyModulePasses, HighLevel,Function+EarlyLoopOpt, HighLevel,Module+StackPromote, MidLevel,Function, ClosureSpecialize, LowLevel,Function, LateLoopOpt, SIL Debug Info Generator } on SIL for MorningBearStorage)
4.	While running pass #2355 SILFunctionTransform "EarlyInliner" on SILFunction "@$s18MorningBearStorage05LocalC7ManagerVyACyxq_Gq_cfcfA_".
 for expression at [/Users/youngbinlee/Documents/Github/MorningBear/Targets/MorningBearStorage/Sources/Local/LocalStorageManager.swift:43:43 - line:43:69] RangeText="MornerLocalStorageService("
 
Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it):
0  swift-frontend           0x00000001079175b0 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) + 56
1  swift-frontend           0x00000001079165b4 llvm::sys::RunSignalHandlers() + 112
2  swift-frontend           0x0000000107917c34 SignalHandler(int) + 344
3  libsystem_platform.dylib 0x00000001ae8a02a4 _sigtramp + 56
4  swift-frontend           0x00000001039d17e4 swift::getEligibleFunction(swift::FullApplySite, swift::InlineSelection) + 1576
5  swift-frontend           0x00000001038c35a0 (anonymous namespace)::SILPerformanceInlinerPass::run() + 2068
6  swift-frontend           0x0000000103818470 swift::SILPassManager::runFunctionPasses(unsigned int, unsigned int) + 4020
7  swift-frontend           0x00000001038150c4 swift::SILPassManager::executePassPipelinePlan(swift::SILPassPipelinePlan const&) + 148
8  swift-frontend           0x0000000103830670 swift::SimpleRequest<swift::ExecuteSILPipelineRequest, std::__1::tuple<> (swift::SILPipelineExecutionDescriptor), (swift::RequestFlags)1>::evaluateRequest(swift::ExecuteSILPipelineRequest const&, swift::Evaluator&) + 56
9  swift-frontend           0x000000010381d858 llvm::Expected<swift::ExecuteSILPipelineRequest::OutputType> swift::Evaluator::getResultUncached<swift::ExecuteSILPipelineRequest>(swift::ExecuteSILPipelineRequest const&) + 504
10 swift-frontend           0x000000010381f9a0 swift::runSILOptimizationPasses(swift::SILModule&) + 368
11 swift-frontend           0x0000000102fd1694 swift::CompilerInstance::performSILProcessing(swift::SILModule*) + 524
12 swift-frontend           0x0000000102f625cc performCompileStepsPostSILGen(swift::CompilerInstance&, std::__1::unique_ptr<swift::SILModule, std::__1::default_delete<swift::SILModule> >, llvm::PointerUnion<swift::ModuleDecl*, swift::SourceFile*>, swift::PrimarySpecificPaths const&, int&, swift::FrontendObserver*) + 1064
13 swift-frontend           0x0000000102f64ce8 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 7284
14 swift-frontend           0x0000000102f05294 swift::mainEntry(int, char const**) + 3940
15 dyld                     0x00000001ae547e50 start + 2544
Command SwiftCompile failed with a nonzero exit code

분석

  1. 패키지에 관한 에러일 것이라고 막연하게 추측함. 특히 주로 Firebase에서 에러가 발생했으므로 이에 관련된 것이라고 추측(objc build 등)
  2. 클린 빌드 후 다시 빌드 등 여러가지 작업 실행했으나 해결되지 않음
  3. 이름이 원래 존재하던 프레임워크와 같을 경우 발생한다는 이야기도 있어 수정하였으나 해결되지 않음.

재현

독립된 다른 환경에서 재현

public struct LocalStorageManager<Instance, Storage> where Instance: Codable, Storage: StorageType {
    private let localStorage: Storage
    private let coderSet: CoderSet
    
    public func save(_ instance: Instance, name: String) -> URL? {
        guard let data = try? coderSet.encoder.encode(instance) else {
            return nil
        }
        
        return localStorage.save(data: data, name: name)
    }
    
    public func load(path: URL) -> Instance? {
        guard let data = localStorage.download(with: path) else {
            return nil
        }
        
        guard let instance = try? coderSet.decoder.decode(Instance.self, from: data) else {
            return nil
        }
        
        return instance
    }
    
    public init(_ localStorage: Storage = LocalStorageService()) {
        self.localStorage = localStorage
        self.coderSet = CoderSet()
    }
}

fileprivate struct CoderSet {
    let encoder = JSONEncoder()
    let decoder = JSONDecoder()
}


struct LocalStorageService: StorageType {
    private let storage: FileManager
    
    init(_ storage: FileManager = FileManager.default) {
        self.storage = storage
    }
    
    func save(data: Data, name: String?) -> URL? {
        guard let name else { return nil }
        
        do {
            let filePath = fileURL(with: name)
            try data.write(to: filePath ?? URL(string: "www.google.com")!)
            
            return filePath
        } catch {
            return nil
        }
    }
    
    func download(with url: URL) -> Data? {
        do {
            guard storage.fileExists(atPath: url.relativeString) else {
                return nil
            }
            
            let data = try Data(contentsOf: url)
            return data
        } catch {
            return nil
        }
    }
}


extension LocalStorageService {
    var documentDirectory: URL? {
        return try? self.storage.url(for: .documentDirectory,
                                     in: .userDomainMask,
                                     appropriateFor: nil,
                                     create: false)
    }
    
    func fileURL(with name: String?) -> URL? {
        guard let documentDirectory = documentDirectory else {
            return nil
        }
        
        let parsedName = name ?? UUID().uuidString
        
        return documentDirectory.appendingPathComponent(parsedName)
    }
}


public protocol StorageType {
    func save(data: Data, name: String?) -> URL?
    func download(with url: URL) -> Data?
}
  • 새로운 static library 프로젝트를 만든 뒤 위 프레임워크를 release로 build할 경우 동일한 에러가 발생한다. 에러 로그는 다음 줄에 첨부한다.
/Users/youngbinlee/Documents/Github/CompileFailureTestFramework/CompileFailureTestFramework/CompileFailureTestFramework.swift:37:43 - line:37:63] RangeText="LocalStorageService("

해결법

  • 로그를 분석한 결과 다음 부분에서 에러가 있음을 알게 되었다.
public init(_ localStorage: Storage = LocalStorageService()) {
    self.localStorage = localStorage
    self.coderSet = CoderSet()
}
  • 위 코드를 다음과 같이 수정하면 에러가 발생하지 않는다.
public init(_ localStorage: Storage?) {
	if let localStorage {
    	self.localStorage = localStorage
    } else {
    	self.localStroage = LocalStorage()
    }
    
    self.coderSet = CoderSet()
}
  • 이유는 분석 중..

참고

0개의 댓글