-
Notifications
You must be signed in to change notification settings - Fork 49
[SwiftKit] Move 'selfPointer' to 'JNISwiftInstance' & downcall trace logs #322
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
c41bfb0
e444700
21e409d
f20c103
7ca6bc9
17197e2
4092f36
4dffc5f
602a6ac
49e95c6
e7c0635
52d4d92
b9fd0a4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -131,6 +131,7 @@ extension FFMSwift2JavaGenerator { | |
} | ||
printer.print("import \(module)") | ||
} | ||
printer.println() | ||
} | ||
} | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -206,13 +206,15 @@ extension JNISwift2JavaGenerator { | |
printDeclDocumentation(&printer, decl) | ||
printer.printBraceBlock("public \(renderFunctionSignature(decl))") { printer in | ||
var arguments = translatedDecl.translatedFunctionSignature.parameters.map(\.name) | ||
arguments.append("selfPointer") | ||
|
||
let selfVarName = "self$" | ||
arguments.append(selfVarName) | ||
|
||
let returnKeyword = translatedDecl.translatedFunctionSignature.resultType.isVoid ? "" : "return " | ||
|
||
printer.print( | ||
""" | ||
long selfPointer = this.pointer(); | ||
long \(selfVarName) = this.$memoryAddress(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These are basically unsafe, so I figured we shoudl hide them using our $ pattern. |
||
\(returnKeyword)\(translatedDecl.parentName).$\(translatedDecl.name)(\(arguments.joined(separator: ", "))); | ||
""" | ||
) | ||
|
@@ -235,8 +237,8 @@ extension JNISwift2JavaGenerator { | |
let initArguments = translatedDecl.translatedFunctionSignature.parameters.map(\.name) | ||
printer.print( | ||
""" | ||
long selfPointer = \(type.qualifiedName).allocatingInit(\(initArguments.joined(separator: ", "))); | ||
return new \(type.qualifiedName)(selfPointer, swiftArena$); | ||
long self$ = \(type.qualifiedName).allocatingInit(\(initArguments.joined(separator: ", "))); | ||
return new \(type.qualifiedName)(self$, swiftArena$); | ||
""" | ||
) | ||
} | ||
|
@@ -262,15 +264,24 @@ extension JNISwift2JavaGenerator { | |
private func printDestroyFunction(_ printer: inout CodePrinter, _ type: ImportedNominalType) { | ||
printer.print("private static native void $destroy(long selfPointer);") | ||
|
||
let funcName = "$createDestroyFunction" | ||
printer.print("@Override") | ||
printer.printBraceBlock("protected Runnable $createDestroyFunction()") { printer in | ||
printer.printBraceBlock("protected Runnable \(funcName)()") { printer in | ||
printer.print( | ||
""" | ||
long $selfPointer = this.pointer(); | ||
long self$ = this.$memoryAddress(); | ||
if (CallTraces.TRACE_DOWNCALLS) { | ||
CallTraces.traceDowncall("\(type.swiftNominal.name).\(funcName)", | ||
"this", this, | ||
"self", self$); | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. a bit of downtracing helped diagnose issues |
||
return new Runnable() { | ||
@Override | ||
public void run() { | ||
\(type.swiftNominal.name).$destroy($selfPointer); | ||
if (CallTraces.TRACE_DOWNCALLS) { | ||
CallTraces.traceDowncall("\(type.swiftNominal.name).$destroy", "self", self$); | ||
} | ||
\(type.swiftNominal.name).$destroy(self$); | ||
} | ||
}; | ||
""" | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -138,9 +138,9 @@ extension JNISwift2JavaGenerator { | |
// TODO: Throwing initializers | ||
printer.print( | ||
""" | ||
let selfPointer = UnsafeMutablePointer<\(typeName)>.allocate(capacity: 1) | ||
selfPointer.initialize(to: \(typeName)(\(downcallArguments))) | ||
return Int64(Int(bitPattern: selfPointer)).getJNIValue(in: environment) | ||
let self$ = UnsafeMutablePointer<\(typeName)>.allocate(capacity: 1) | ||
self$.initialize(to: \(typeName)(\(downcallArguments))) | ||
return Int64(Int(bitPattern: self$)).getJNIValue(in: environment) | ||
""" | ||
) | ||
} | ||
|
@@ -184,22 +184,20 @@ extension JNISwift2JavaGenerator { | |
let translatedDecl = self.translatedDecl(for: decl)! // We will only call this method if can translate the decl. | ||
let swiftParentName = decl.parentType!.asNominalTypeDeclaration!.qualifiedName | ||
|
||
let selfPointerParam = JavaParameter(name: "selfPointer", type: .long) | ||
printCDecl( | ||
&printer, | ||
javaMethodName: "$\(translatedDecl.name)", | ||
parentName: translatedDecl.parentName, | ||
parameters: translatedDecl.translatedFunctionSignature.parameters + [ | ||
JavaParameter(name: "selfPointer", type: .long) | ||
selfPointerParam | ||
], | ||
isStatic: true, | ||
resultType: translatedDecl.translatedFunctionSignature.resultType | ||
) { printer in | ||
printer.print( | ||
""" | ||
let self$ = UnsafeMutablePointer<\(swiftParentName)>(bitPattern: Int(Int64(fromJNI: selfPointer, in: environment!)))! | ||
""" | ||
) | ||
self.printFunctionDowncall(&printer, decl, calleeName: "self$.pointee") | ||
let selfVar = self.printSelfJLongToUnsafeMutablePointer(&printer, | ||
swiftParentName: swiftParentName, selfPointerParam) | ||
self.printFunctionDowncall(&printer, decl, calleeName: "\(selfVar).pointee") | ||
} | ||
} | ||
|
||
|
@@ -320,28 +318,53 @@ extension JNISwift2JavaGenerator { | |
|
||
/// Prints the implementation of the destroy function. | ||
private func printDestroyFunctionThunk(_ printer: inout CodePrinter, _ type: ImportedNominalType) { | ||
let selfPointerParam = JavaParameter(name: "selfPointer", type: .long) | ||
printCDecl( | ||
&printer, | ||
javaMethodName: "$destroy", | ||
parentName: type.swiftNominal.name, | ||
parameters: [ | ||
JavaParameter(name: "selfPointer", type: .long) | ||
selfPointerParam | ||
], | ||
isStatic: true, | ||
resultType: .void | ||
) { printer in | ||
let parentName = type.qualifiedName | ||
let selfVar = self.printSelfJLongToUnsafeMutablePointer(&printer, swiftParentName: parentName, selfPointerParam) | ||
// Deinitialize the pointer allocated (which will call the VWT destroy method) | ||
// then deallocate the memory. | ||
printer.print( | ||
""" | ||
let pointer = UnsafeMutablePointer<\(type.qualifiedName)>(bitPattern: Int(Int64(fromJNI: selfPointer, in: environment!)))! | ||
pointer.deinitialize(count: 1) | ||
pointer.deallocate() | ||
\(selfVar).deinitialize(count: 1) | ||
\(selfVar).deallocate() | ||
""" | ||
) | ||
} | ||
} | ||
|
||
/// Print the necessary conversion logic to go from a `jlong` to a `UnsafeMutablePointer<Type>` | ||
/// | ||
/// - Returns: name of the created "self" variable | ||
private func printSelfJLongToUnsafeMutablePointer( | ||
_ printer: inout CodePrinter, | ||
swiftParentName: String, _ selfPointerParam: JavaParameter) -> String { | ||
let newSelfParamName = "self$" | ||
printer.print( | ||
""" | ||
guard let env$ = environment else { | ||
fatalError("Missing JNIEnv in downcall to \\(#function)") | ||
} | ||
assert(\(selfPointerParam.name) != 0, "\(selfPointerParam.name) memory address was null") | ||
let selfBits$ = Int(Int64(fromJNI: \(selfPointerParam.name), in: env$)) | ||
guard let \(newSelfParamName) = UnsafeMutablePointer<\(swiftParentName)>(bitPattern: selfBits$) else { | ||
fatalError("self memory address was null in call to \\(#function)!") | ||
} | ||
""" | ||
) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This code was repeated 2 times, so now it's in 1 place. The reason to split it up into more lines and not just the single line with multiple |
||
return newSelfParamName | ||
} | ||
|
||
|
||
/// Renders the arguments for making a downcall | ||
private func renderDowncallArguments( | ||
swiftFunctionSignature: SwiftFunctionSignature, | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2024 Apple Inc. and the Swift.org project authors | ||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of Swift.org project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
package org.swift.swiftkit.core; | ||
|
||
public class CallTraces { | ||
public static final boolean TRACE_DOWNCALLS = | ||
Boolean.getBoolean("jextract.trace.downcalls"); | ||
|
||
// Used to manually debug with complete backtraces on every traceDowncall | ||
public static final boolean TRACE_DOWNCALLS_FULL = false; | ||
|
||
public static void traceDowncall(Object... args) { | ||
RuntimeException ex = new RuntimeException(); | ||
|
||
String traceArgs = joinArgs(args); | ||
System.err.printf("[java][%s:%d] Downcall: %s.%s(%s)\n", | ||
ex.getStackTrace()[1].getFileName(), | ||
ex.getStackTrace()[1].getLineNumber(), | ||
ex.getStackTrace()[1].getClassName(), | ||
ex.getStackTrace()[1].getMethodName(), | ||
traceArgs); | ||
if (TRACE_DOWNCALLS_FULL) { | ||
ex.printStackTrace(); | ||
} | ||
} | ||
|
||
public static void trace(Object... args) { | ||
RuntimeException ex = new RuntimeException(); | ||
|
||
String traceArgs = joinArgs(args); | ||
System.err.printf("[java][%s:%d] %s: %s\n", | ||
ex.getStackTrace()[1].getFileName(), | ||
ex.getStackTrace()[1].getLineNumber(), | ||
ex.getStackTrace()[1].getMethodName(), | ||
traceArgs); | ||
} | ||
|
||
private static String joinArgs(Object[] args) { | ||
StringBuilder sb = new StringBuilder(); | ||
for (int i = 0; i < args.length; i++) { | ||
if (i > 0) { | ||
sb.append(", "); | ||
} | ||
sb.append(args[i].toString()); | ||
} | ||
return sb.toString(); | ||
} | ||
|
||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -14,17 +14,30 @@ | |
|
||
package org.swift.swiftkit.core; | ||
|
||
import java.util.Objects; | ||
import java.util.concurrent.atomic.AtomicBoolean; | ||
|
||
public abstract class JNISwiftInstance extends SwiftInstance { | ||
// Pointer to the "self". | ||
protected final long selfPointer; | ||
|
||
/** | ||
* The designated constructor of any imported Swift types. | ||
* | ||
* @param pointer a pointer to the memory containing the value | ||
* @param selfPointer a pointer to the memory containing the value | ||
* @param arena the arena this object belongs to. When the arena goes out of scope, this value is destroyed. | ||
*/ | ||
protected JNISwiftInstance(long pointer, SwiftArena arena) { | ||
super(pointer, arena); | ||
protected JNISwiftInstance(long selfPointer, SwiftArena arena) { | ||
SwiftObjects.requireNonZero(selfPointer, "selfPointer"); | ||
this.selfPointer = selfPointer; | ||
|
||
// Only register once we have fully initialized the object since this will need the object pointer. | ||
arena.register(this); | ||
} | ||
|
||
@Override | ||
public long $memoryAddress() { | ||
return this.selfPointer; | ||
} | ||
|
||
/** | ||
|
@@ -42,7 +55,7 @@ protected JNISwiftInstance(long pointer, SwiftArena arena) { | |
protected abstract Runnable $createDestroyFunction(); | ||
|
||
@Override | ||
public SwiftInstanceCleanup createCleanupAction() { | ||
public SwiftInstanceCleanup $createCleanup() { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Also not a method end users should be invoking explicitly, so changed it while at it. |
||
final AtomicBoolean statusDestroyedFlag = $statusDestroyedFlag(); | ||
Runnable markAsDestroyed = new Runnable() { | ||
@Override | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The reason we're doing
$
in names in bodies is so they don't clash with any parameter name that someone can come up with, so I moved to self$ here -- FYI @madsodgaardThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
good idea!