program tip

빌드시 신속한 컴파일러 세그멘테이션 오류

radiobox 2020. 8. 22. 08:30
반응형

빌드시 신속한 컴파일러 세그멘테이션 오류


파일 (편리한) 계산 된 height속성을 추가 하면 Swift 컴파일러가 segfault를하게됩니다. 여기서 무엇이 잘못 될 수 있습니까?UIViewUIViewExtension.swift

0  swift                    0x00000001061e5608 llvm::sys::PrintStackTrace(__sFILE*) + 40
1  swift                    0x00000001061e5af4 SignalHandler(int) + 452
2  libsystem_platform.dylib 0x00007fff894da5aa _sigtramp + 26
3  libsystem_platform.dylib 0xb03939841e997c88 _sigtramp + 2504775416
4  swift                    0x00000001064c8bb9 swift::NominalTypeDecl::getMembers(bool) const + 41
5  swift                    0x00000001055efab9 swift::irgen::ClassMetadataLayout<(anonymous namespace)::FindClassMethodIndex>::addClassMembers(swift::ClassDecl*) + 329
6  swift                    0x00000001055e97b2 swift::irgen::emitVirtualMethodValue(swift::irgen::IRGenFunction&, llvm::Value*, swift::SILType, swift::SILDeclRef, swift::CanTypeWrapper<swift::SILFunctionType>, swift::ResilienceExpansion) + 434
7  swift                    0x00000001056550d3 swift::SILVisitor<(anonymous namespace)::IRGenSILFunction, void>::visit(swift::ValueBase*) + 42611
8  swift                    0x000000010564a266 swift::irgen::IRGenModule::emitSILFunction(swift::SILFunction*) + 8678
9  swift                    0x00000001055cb6f8 swift::irgen::IRGenModule::emitGlobalTopLevel() + 184
10 swift                    0x00000001056376e3 performIRGeneration(swift::IRGenOptions&, swift::Module*, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, unsigned int) + 1859
11 swift                    0x0000000105638033 swift::performIRGeneration(swift::IRGenOptions&, swift::SourceFile&, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, unsigned int) + 51
12 swift                    0x00000001055aa65a frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 4842
13 swift                    0x00000001055a935d main + 1533
14 libdyld.dylib            0x00007fff8a82e5fd start + 1

 

1.  While emitting IR SIL function @_TFCSo6UIViewg6heightSd for 'anonname=0x7ff422892fd0' at <path redacted>/UIViewExtension.swift:60:5
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal (use -v to see invocation)
Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254

이 문제를 해결하는 데 더 많은 정보가 필요하면 의견을 말하십시오. 감사!

편집하다:

이 질문의 컴파일러 오류를 반환하는 관련 .xcodeproj가 있습니다. 여기에서 다운로드


이 작업을 수행했기 때문에이 오류가 발생했습니다.

if(currentMeal?.State == .Deleted){

}

대신에

if(currentMeal!.State == .Deleted){

}

그래서 조건 이이 오류를 일으킬 수 있다면 옵션으로 포장을 풀지 않은 것 같습니다.


Swift에서 컴파일러 segfault를 실행하면 편리한 줄 번호와 오류 메시지가 표시되지 않습니다. 문제를 추적하는 방법은 다음과 같습니다.

  1. SegFaultDebugger.swift프로젝트에서 라는 새 파일을 만듭니다 .
  2. 이 새 파일에서 문제를 일으키는 클래스의 확장자를 정의하십시오.
  3. 메서드 그룹을 기본 파일에서 SegFaultDebugger.swift.
  4. 엮다.

이 시점에서 다음 세 가지 중 하나가 발생합니다.

  • 여전히 원본 파일에서 segfault를 얻을 수 있습니다 . 방법을 SegFaultDebugger.swift다시 원본 파일로 이동하고 다른 방법 세트를 SegFaultDebugger.swift. 반복
  • 당신은에서 segfault를 얻습니다SegFaultDebugger.swift : 좋습니다 ! 이제 이진 검색을 사용하여 segfault를 특정 방법으로 고정하여 어떤 구조가 원인인지 파악할 수 있습니다.
  • 의미있는 컴파일러 오류가 발생합니다 . 좋습니다! 오류를 수정하십시오. 모든 것이 컴파일되면 메서드를 원래 파일로 다시 이동하십시오.

내 프로토콜 중 하나를 확장하고 잘못 입력 된 선택적 유형 인수를 확장하는 동안이 오류가 발생했습니다.

protocol SomeProtocolName: class {
    var someProtocolVariable: String { get set }

    func someProtocolFunction(someProtocolVariable: String)
}

// MARK:
extension SomeProtocolName {
    func someProtocolFunction(someProtocolVariable: String?) {
        self.someProtocolVariable = someProtocolVariable
    }
}

String프로토 타입과 String?확장 에서 함수 인수의 차이로 인해 Segmentation Fault 11이 발생했습니다 .


이 오류도 있었고 다음과 같이 수정했습니다.

프로젝트를 확인하고 두 번 사용 된 파일을 찾아서 하나를 제거하거나 모두 삭제하고 다시 추가하십시오.

내 Xcode의 오류 :

: 0 : 오류 : 파일 이름 "AttributedString.swift"두 번 사용 : '/Users/.../CNJOB/CNJOB/AttributedString.swift'및 '/Users/.../CNJOB/CNJOB/AttributedString.swift'

: 0 : 참고 : 파일 이름은 동일한 이름의 개인 선언을 구분하는 데 사용됩니다.

: 0 : 오류 : 파일 이름 "APIClient.swift"가 두 번 사용됨 : '/Users/.../CNJOB/CNJOB/APIClient.swift'및 '/Users/.../CNJOB/CNJOB/APIClient.swift'

: 0 : 참고 : 파일 이름은 동일한 이름의 개인 선언을 구분하는 데 사용됩니다.

/ Applications / Xcode 3.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc 명령이 종료 코드 1로 실패했습니다.


Xcode 7에서는 디버그 네비게이터에서 오류를 클릭하면 확장 된 충돌보기가 표시됩니다. 오른쪽에있는 햄버거 버튼을 클릭하면 오류가 확장되고 확장 된 오류 메시지의 맨 아래로 스크롤하면 오류가 발생한 위치를 볼 수 있습니다.

여기에 이미지 설명 입력

저에게는 두 가지 세분화 오류 오류가있었습니다. 위 그림에서 첫 번째는 접었을 때의 모습이고 두 번째는 햄버거 버튼을 펼쳤을 때의 모습입니다. 확장 된 회색 상자의 맨 아래에 컴파일러가 충돌 한 위치를 알려주는 메시지가 표시됩니다.

그러나 오류 메시지는 때때로 정보가 충분하지 않을 수 있으므로 오류가 발생한 위치를 알려 주지만 항상 원인과 해결 방법을 알려주지는 않습니다. 이 오류를 제거하는 것은 여전히 ​​추측의 문제입니다.


향후 Xcode / Swift 빌드에서 문제가 해결 될 때까지 간단한 해결 방법을 발견했습니다.

  • 문제를 일으키는 모든 확장자 .swift를 사용중인 파일에 넣으십시오.

제공된 예제 프로젝트에서의 내용 배치 UIViewExtension.swift CALayerExtension.swift AppDelegate.swift

문제가 해결 될 때까지 작동하는 Swift 코드 를 작성할 수 있기를 바랍니다 .


나를 private위해 정적 var fixed clang crash에 추가하십시오.

private static var taskId = 0

다음과 같은 명령문에 컴파일러 분할 오류가 있습니다.

someFunction(isFlagged ? "String1" : "String2")

대신 if-else 문을 수행했는데 작동합니다.


래핑되지 않은 Bool을 속성으로 사용하여 조건을 선언하는 경우에도이 문제가 발생할 수 있습니다.


필자의 경우 문자열 보간 중 잘못 배치 된 콜론이 내 문제를 해결했습니다 (XCode 6.1.1).

예:

println("\(value1:value2)") 

내가하려고했을 때 :

println("\(value1) : \(value2)")

이 오류는 부모 클래스에서 약한 변수를 재정의하려고 할 때 발생했습니다.

기본 클래스에서 :

weak var stripeViewDelegate : StripeViewDelegate? = nil    

파생 클래스 :

override weak var stripeViewDelegate : StripeViewDelegate? = nil {
    didSet {
        self.stripeView.delegate = stripeViewDelegate

    }

=nil파생 클래스에서 제거하면 오류가 사라졌습니다 .


오늘은 예외가 있어요

class func createByAny(instance: Any?) -> ApiCollectionResponse { ... }

그리고 이것은 그것을 해결했습니다.

class func createByAny(instance: Any) -> ApiCollectionResponse { ... }

"Any"유형은 모든 유형 이벤트 "nil", "AnyObject", 선택 사항, ... :) 선택 사항 일 수 없으며 이미 선택 사항입니다.

typealias Any = protocol<>

이 오류는 유형이 이름과 일치하는 변수를 실수로 선언 한 경우에도 발생합니다.

    var sectionGroup: sectionGroup? { ... }

연산자 함수에 대한 외부 제네릭 유형 때문에이 오류가 발생했습니다. 예 :

func ==<T>(lhs: Foo, rhs: Foo) -> Bool {
  return lhs.bar == rhs.bar
}

제 경우에는 제거 <T>하면 문제가 해결되었습니다.


제 경우 struct에는 func. struct수업 수준으로 이동하면 문제가 해결되었습니다.

이제 나는 이것을 작성 하기 전에 struct내부에 문제가 있었던 것을 기억 func합니다. 그것은 세그멘테이션 결함 (Swift 1.2 베타에서 악명 높은 것으로 보인다)과는 다른 무언가였습니다. OMG 애플, 거기서 뭐하는거야?


제 경우에는 변수에 클래스 이름을 사용하기 때문에이 오류

var MYClass : MYClass {
    get {
        return.....
    }
}

그리고 이것은 내 문제를 해결합니다.

var myClass : MYClass {
    get {
        return.....
    }
}

필자의 경우 이것은 프로토콜에서 잘못된 정적 초기화를 수행했을 때 발생했습니다. 나는 돌아 다니는 방법을 찾았지만 컴파일러는 빌드하는 동안 세그먼트 오류를 ​​생성 해서는 안됩니다 .

There are three files involved. A protocol NamedSegues.swift, a custom TableViewController that among other things implements the protocol which contains a callback, a custom TableViewCell that holds reference to this protocol to call the callback.

//file1
import Foundation
protocol NamedSegues {
    func  executeSegueWithId(id: String) -> Void
    static func getDefault() -> NamedSegues  // This was required because of init requirement in CustomCellView
}


//file2
class CustomController: UITableViewController, NamedSegues {
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCellWithIdentifier("CustomCellID", forIndexPath: indexPath ) as! CustomCellView

        // Configure the cell...
       //App logic...

        cell.parent = self
}

 //Mark: NamedSegues
     func executeSegueWithId(id: String) ->() {
        NSLog("Received callback to execute segue: \(id)")
        //
    }

    static func getDefault() -> NamedSegues { // I think this must be where it threw up.
        return self as! NamedSegues
    }

}


//file3

import UIKit

class CustomCellView: UITableViewCell {

    var id: String = "NoName"
    var parent: NamedSegues = NamedSegues.getDefault() // This is where it was needed.


override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        NSLog("Touched id: \(id)")


             parent.executeSegueWithId(id) // This is where parent was used.
     }
}

I got around it by using ?

In the protocol file, file1: delete the declaration of getDefault() In the CustomController file2: delete the implementation of getDefault. In the CustomCellView, file3:

    var parent: NamedSegues?
    ...
    parent?.executeSegueWithId(id)

The compiler should have caught this and given some error message instead of throwing a segmentation fault during build!


Seems like the Swift 2 compiler might not have been quite ready for prime-time! In case this helps anyone, I was getting a segmentation fault: 11 due to a mismatch with the variable type in a closure header, specifically in a Parse method, PFQuery.query.findObjectsInBackgroundWithBlock.

You can see the issue in more detail here: https://github.com/ParsePlatform/Parse-SDK-iOS-OSX/issues/280


Like @Fjohn said, this was an issue related to unwrapping an optional for me (broke in both Xcode 7.0 beta 6 and Xcode 7). In my case, I was not unwrapping optional of the optional (what tipped me off was double ?? in the descriptor. Using if let solved the issue

이중 선택적 원인 분할 오류


As others wrote above, for me this happened when I'm using an extension over a protocol but the signature of methods in the protocol don't match the implementations in an extension.

In my case, I had added a new parameter to the implementation (in the extension) but forgot to also add it to the method's signature in the protocol.


in my case, I tried to add a function parameter after a variadic parameter.

Reversing parameter sequence and making the variadic parameter the last parameter in the parameter list fixed it.


This typically happens when the compiler does not have enough information (despite what you think) to guarantee/determine the state of a statement or a variable within a statement.

For example, imagine you have a dictionary of type [String: String] which you populate with city names as keys and a comma separated list of corresponding zip codes/post codes.

Imagine that somewhere in your code you want to update the list of corresponding codes:

myDict[town] += newZipCode + ","

In this case, the compiler will respond with segmentation fault as town might not be in the dictionary and therefore it cannot guarantee that the above statement will have a valid value.

To resolve this, you should store the current state of myDict[town] in a separate variable allowing you to handle the case of key not in dict and then update the value for the given key:

myDict[town] = guaranteedValue + "," newZipCode + ","

Unfortunately, it is not always straightforward to determine the root cause so I hope this simple example helps.


Swift 3.0 (Xcode 8.1) exhibits this issue when a protocol declares an optional variable, and an implementer implements that variable as a lazy initialised one.

Bug is reported here: https://bugs.swift.org/browse/SR-1825


Xcode 8.2.

Adding @nonobjc protocol implementation into extension causing segmentation faults. Move @nonobjc protocol implementation into class implementation.


In my case the culprit was accidentally overloading a function expecting an array argument with one with a variadic argument:

public required init(_ args: Node...) {
}

When the superclass had it defined as an array:

public required init(_ args: [Node]) {
}

For me the following caused a segfault while type is an optional:

switch type {
    case .aType:
        // Do Something
    default:
        break
}

and this solved it:

switch type {
    case .Some(.aType):
        // Do Something
    default:
        break
}

I got this error with the following method signature in a custom UITableViewController.

func filterContentForSearchText(searchText: String)

changing to:

func filterContentForSearchText(searchText: String!)

fixed the problem.


I had the same problem in an extension. My extension had two convenience initializers:

convenience init(context: NSManagedObjectContext) {
    let entityDescription = NSEntityDescription.entityForName("PropertyEntity", inManagedObjectContext: context)!
    self.init(entity: entityDescription, insertIntoManagedObjectContext: context)
}

convenience init(dictionary: NSDictionary, context: NSManagedObjectContext) {
    self.init(context: context)
    property1 = (dictionary["key"] as? String) ?? ""
    // More properties...
}

To get rid of the error I added an instance method map(dictionary: NSDictionary) and the segmentation fault error disappeared.

convenience init(dictionary: NSDictionary, context: NSManagedObjectContext) {
    self.init(context: context)
    map(dictionary)
}

For me the issue was having my architectures not set to the standard. I had added i386 or something, just set it back to default xcodeproject arch and it compiled fine.


신속한 프로젝트에서 동일한 문제가 발생했습니다. 문제는 객체를 반환해야하지만 반환이없는 함수였습니다. 이런 종류의 오류는 Obj-C로 편집하는 동안 신호를 받았습니다. Swift에서는 그렇지 않은 것 같습니다.

참고 URL : https://stackoverflow.com/questions/24222644/swift-compiler-segmentation-fault-when-building

반응형