├── .gitignore ├── docs └── images │ ├── final.png │ ├── package_back2.png │ └── XcodeKotlinFileReferencesSteps.png ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties └── libs.versions.toml ├── LLDBPlugin ├── touchlab_kotlin_lldb │ ├── util │ │ ├── DebuggerException.py │ │ ├── __init__.py │ │ ├── log.py │ │ ├── kotlin_object_to_cstring.py │ │ ├── expression.py │ │ └── konan_debug.h │ ├── commands │ │ ├── __init__.py │ │ ├── SymbolByNameCommand.py │ │ ├── TypeByAddressCommand.py │ │ ├── FieldTypeCommand.py │ │ ├── KonanGlobalsCommand.py │ │ └── GCCollectCommand.py │ ├── types │ │ ├── KonanNullSyntheticProvider.py │ │ ├── KonanNotInitializedObjectSyntheticProvider.py │ │ ├── KonanStringSyntheticProvider.py │ │ ├── KonanZerroSyntheticProvider.py │ │ ├── summary.py │ │ ├── KonanBaseSyntheticProvider.py │ │ ├── KonanObjectSyntheticProvider.py │ │ ├── proxy.py │ │ ├── KonanArraySyntheticProvider.py │ │ ├── KonanListSyntheticProvider.py │ │ ├── select_provider.py │ │ ├── KonanMapSyntheticProvider.py │ │ └── base.py │ ├── stepping │ │ ├── KonanStepOut.py │ │ ├── KonanStepIn.py │ │ ├── KonanStepOver.py │ │ ├── KonanStep.py │ │ └── KonanHook.py │ ├── cache │ │ └── __init__.py │ └── __init__.py ├── test_project │ ├── gradle │ │ ├── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ │ └── libs.versions.toml │ ├── settings.gradle.kts │ ├── main.swift │ ├── gradle.properties │ ├── build.gradle.kts │ ├── src │ │ └── commonMain │ │ │ └── kotlin │ │ │ └── main.kt │ ├── gradlew.bat │ └── gradlew └── run.py ├── data └── Kotlin.ideplugin │ └── Contents │ ├── Resources │ ├── lldbinit │ └── Kotlin.xcplugindata │ └── Info.plist ├── settings.gradle.kts ├── gradle.properties ├── src └── macosMain │ └── kotlin │ └── co │ └── touchlab │ └── xcode │ └── cli │ ├── command │ ├── Enable.kt │ ├── Disable.kt │ ├── FixXcode15.kt │ ├── XcodeKotlinPlugin.kt │ ├── Uninstall.kt │ ├── Install.kt │ ├── Sync.kt │ ├── BaseXcodeListSubcommand.kt │ └── Info.kt │ ├── util │ ├── BackupHelper.kt │ ├── StringBridge.kt │ ├── DelegatingTerminalRecorder.kt │ ├── Console.kt │ ├── CrashHelper.kt │ ├── Path.kt │ ├── File.kt │ ├── Shell.kt │ ├── PropertyList.kt │ └── SemVer.kt │ ├── LangSpecManager.kt │ ├── main.kt │ ├── LLDBInitManager.kt │ ├── InstallationFacade.kt │ ├── PluginManager.kt │ └── XcodeHelper.kt ├── README.md ├── .github ├── PULL_REQUEST_TEMPLATE.md └── ISSUE_TEMPLATE.md ├── .run ├── info.run.xml ├── repair.run.xml ├── uninstall.run.xml └── install.run.xml ├── ABOUT.md ├── MANUAL_INSTALL.md ├── CONTRIBUTING.md ├── gradlew.bat ├── BUILDING.md ├── gradlew └── LICENSE.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | .DS_Store 4 | .gradle 5 | build/ 6 | cmake-build-debug/ 7 | .kotlin 8 | -------------------------------------------------------------------------------- /docs/images/final.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/touchlab/xcode-kotlin/HEAD/docs/images/final.png -------------------------------------------------------------------------------- /docs/images/package_back2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/touchlab/xcode-kotlin/HEAD/docs/images/package_back2.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/touchlab/xcode-kotlin/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /docs/images/XcodeKotlinFileReferencesSteps.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/touchlab/xcode-kotlin/HEAD/docs/images/XcodeKotlinFileReferencesSteps.png -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/util/DebuggerException.py: -------------------------------------------------------------------------------- 1 | class DebuggerException(Exception): 2 | def __init__(self, msg: str): 3 | self.msg: str = msg 4 | -------------------------------------------------------------------------------- /data/Kotlin.ideplugin/Contents/Resources/lldbinit: -------------------------------------------------------------------------------- 1 | command script import ~/Library/Developer/Xcode/Plug-ins/Kotlin.ideplugin/Contents/Resources/touchlab_kotlin_lldb 2 | -------------------------------------------------------------------------------- /LLDBPlugin/test_project/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/touchlab/xcode-kotlin/HEAD/LLDBPlugin/test_project/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | 2 | rootProject.name = "xcode-kotlin" 3 | 4 | dependencyResolutionManagement { 5 | repositories { 6 | mavenCentral() 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-XX:+UseParallelGC 2 | 3 | kotlin.code.style=official 4 | kotlin.native.binary.memoryModel=experimental 5 | kotlin.mpp.stability.nowarn=true 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/commands/__init__.py: -------------------------------------------------------------------------------- 1 | from .FieldTypeCommand import FieldTypeCommand 2 | from .TypeByAddressCommand import TypeByAddressCommand 3 | from .SymbolByNameCommand import SymbolByNameCommand 4 | from .KonanGlobalsCommand import KonanGlobalsCommand 5 | from .GCCollectCommand import GCCollectCommand -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/types/KonanNullSyntheticProvider.py: -------------------------------------------------------------------------------- 1 | from .KonanZerroSyntheticProvider import KonanZerroSyntheticProvider 2 | 3 | 4 | class KonanNullSyntheticProvider(KonanZerroSyntheticProvider): 5 | def __init__(self, valobj): 6 | super(KonanNullSyntheticProvider, self).__init__(valobj) 7 | -------------------------------------------------------------------------------- /LLDBPlugin/test_project/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/types/KonanNotInitializedObjectSyntheticProvider.py: -------------------------------------------------------------------------------- 1 | from .KonanZerroSyntheticProvider import KonanZerroSyntheticProvider 2 | 3 | 4 | class KonanNotInitializedObjectSyntheticProvider(KonanZerroSyntheticProvider): 5 | def __init__(self, valobj): 6 | super(KonanNotInitializedObjectSyntheticProvider, self).__init__(valobj) 7 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/command/Enable.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.command 2 | 3 | import co.touchlab.xcode.cli.InstallationFacade 4 | 5 | class Enable: BaseXcodeListSubcommand("enable", "Enables Xcode Kotlin plugin") { 6 | override suspend fun run() { 7 | InstallationFacade.enable(xcodeInstallations()) 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/stepping/KonanStepOut.py: -------------------------------------------------------------------------------- 1 | from .KonanStep import KonanStep 2 | 3 | 4 | class KonanStepOut(KonanStep): 5 | def __init__(self, thread_plan, dict, *args): 6 | KonanStep.__init__(self, thread_plan) 7 | 8 | def do_queue_thread_plan(self, address, offset): 9 | return self.thread_plan.QueueThreadPlanForStepOut(0) 10 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/stepping/KonanStepIn.py: -------------------------------------------------------------------------------- 1 | from .KonanStep import KonanStep 2 | 3 | 4 | class KonanStepIn(KonanStep): 5 | def __init__(self, thread_plan, dict, *args): 6 | KonanStep.__init__(self, thread_plan) 7 | 8 | def do_queue_thread_plan(self, address, offset): 9 | return self.thread_plan.QueueThreadPlanForStepInRange(address, offset) 10 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/command/Disable.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.command 2 | 3 | import co.touchlab.xcode.cli.InstallationFacade 4 | 5 | class Disable: BaseXcodeListSubcommand("disable", "Disables Xcode Kotlin plugin without uninstalling") { 6 | override suspend fun run() { 7 | InstallationFacade.disable(xcodeInstallations()) 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/stepping/KonanStepOver.py: -------------------------------------------------------------------------------- 1 | from .KonanStep import KonanStep 2 | 3 | 4 | class KonanStepOver(KonanStep): 5 | def __init__(self, thread_plan, dict, *args): 6 | KonanStep.__init__(self, thread_plan) 7 | 8 | def do_queue_thread_plan(self, address, offset): 9 | return self.thread_plan.QueueThreadPlanForStepOverRange(address, offset) 10 | -------------------------------------------------------------------------------- /LLDBPlugin/test_project/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | mavenCentral() 4 | gradlePluginPortal() 5 | google() 6 | } 7 | } 8 | 9 | dependencyResolutionManagement { 10 | @Suppress("UnstableApiUsage") 11 | repositories { 12 | google() 13 | mavenCentral() 14 | } 15 | } 16 | 17 | rootProject.name = "S_h_A_r_e___D" -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/util/__init__.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from .log import log 4 | from .kotlin_object_to_cstring import kotlin_object_to_string 5 | from .DebuggerException import DebuggerException 6 | from .expression import evaluate 7 | 8 | NULL = 'null' 9 | 10 | 11 | def strip_quotes(name: Optional[str]): 12 | return "" if (name is None) else name.strip('"') 13 | -------------------------------------------------------------------------------- /LLDBPlugin/test_project/gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | kotlin = "2.0.0" 3 | 4 | coroutines = "1.8.1" 5 | 6 | skie = "0.8.2" 7 | 8 | [libraries] 9 | coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" } 10 | 11 | [plugins] 12 | kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } 13 | skie = { id = "co.touchlab.skie", version.ref = "skie" } 14 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/command/FixXcode15.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.command 2 | 3 | import co.touchlab.xcode.cli.InstallationFacade 4 | 5 | class FixXcode15: BaseXcodeListSubcommand( 6 | name = "fix-xcode15", 7 | actionDescription = "Temporarily workarounds Xcode 15 crash that happens when using any non-Apple Xcode plugins.", 8 | ) { 9 | override suspend fun run() { 10 | InstallationFacade.fixXcode15(xcodeInstallations()) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/util/BackupHelper.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.util 2 | 3 | object BackupHelper { 4 | private val backupRoot = File(Path.home / ".xcode-kotlin" / "backup") 5 | 6 | fun backupPath(filename: String): Path { 7 | ensureBackupRootExists() 8 | return backupRoot.path / filename 9 | } 10 | 11 | fun ensureBackupRootExists() { 12 | if (!backupRoot.exists()) { 13 | backupRoot.mkdirs() 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/command/XcodeKotlinPlugin.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.command 2 | 3 | import com.github.ajalt.clikt.command.SuspendingCliktCommand 4 | import com.github.ajalt.clikt.core.terminal 5 | import com.github.ajalt.mordant.terminal.muted 6 | 7 | class XcodeKotlinPlugin( 8 | private val args: Array, 9 | ): SuspendingCliktCommand() { 10 | override suspend fun run() { 11 | terminal.muted("Running xcode-cli with arguments: ${args.joinToString()}") 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/util/StringBridge.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.util 2 | 3 | import platform.Foundation.NSString 4 | 5 | val String.objc: NSString 6 | // String can be casted to NSString, for some reason the Kotlin compiler doesn't know. 7 | @Suppress("CAST_NEVER_SUCCEEDS") 8 | get() = this as NSString 9 | 10 | val NSString.kt: String 11 | // NSString can be casted back to NSString, for some reason the Kotlin compiler doesn't know. 12 | @Suppress("CAST_NEVER_SUCCEEDS") 13 | get() = this as String -------------------------------------------------------------------------------- /LLDBPlugin/test_project/main.swift: -------------------------------------------------------------------------------- 1 | // import test_project 2 | import S_h_A_r_e___D 3 | import Foundation 4 | 5 | MainKt.main() 6 | 7 | print("Hello world!") 8 | 9 | // test_project.Foo 10 | // Test_projectFoo 11 | 12 | let basic = Foo() 13 | let data = DataFoo(foo: basic) 14 | let dataObject = DataObject.shared 15 | let basicList = [basic] 16 | let dataList = [data] 17 | let dataMap = ["hello": data] 18 | let test = Test() 19 | let testList = [test] 20 | 21 | let nsBasic = basic as NSObject 22 | 23 | 24 | struct Test { 25 | let x = Foo() 26 | } 27 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/command/Uninstall.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.command 2 | 3 | import co.touchlab.xcode.cli.InstallationFacade 4 | import com.github.ajalt.clikt.command.SuspendingCliktCommand 5 | import com.github.ajalt.clikt.core.Context 6 | 7 | class Uninstall: SuspendingCliktCommand("uninstall") { 8 | override fun help(context: Context): String { 9 | return "Uninstalls Xcode Kotlin plugin" 10 | } 11 | 12 | override suspend fun run() { 13 | InstallationFacade.uninstallAll() 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/util/log.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | from typing import Callable 4 | 5 | logging = False 6 | exe_logging = os.getenv('GLOG_log_dir') is not None 7 | 8 | 9 | def log(msg: Callable[[], str]): 10 | if logging: 11 | sys.stderr.write(msg()) 12 | sys.stderr.write('\n') 13 | exelog(msg) 14 | 15 | 16 | def exelog(stmt: Callable[[], str]): 17 | if exe_logging: 18 | f = open(os.getenv('GLOG_log_dir', '') + "/konan_lldb.log", "a") 19 | f.write(stmt()) 20 | f.write("\n") 21 | f.close() 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kotlin Native Xcode Support 2 | 3 | *The xcode-kotlin plugin allows debugging of Kotlin code running in an iOS application, directly from Xcode.* 4 | 5 | This enables a smoother development and integration experience for iOS developers using shared code from Kotlin, and a more accessible experience for larger teams where everyone may not be editing the shared code directly. 6 | 7 | ## [Documentation](https://touchlab.co/xcodekotlin) 8 | 9 | The main documentation for Xcode Kotlin lives [here](https://touchlab.co/xcodekotlin). For info on contributing, see [CONTRIBUTING.md](CONTRIBUTING.md). -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/command/Install.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.command 2 | 3 | import co.touchlab.xcode.cli.InstallationFacade 4 | import com.github.ajalt.clikt.parameters.options.flag 5 | import com.github.ajalt.clikt.parameters.options.option 6 | 7 | class Install: BaseXcodeListSubcommand("install", "Installs Xcode Kotlin plugin") { 8 | private val noFixXcode15 by option( 9 | "--no-fix-xcode15", 10 | help = "Do not apply Xcode 15 workaround.", 11 | ).flag(default = false) 12 | 13 | override suspend fun run() { 14 | InstallationFacade.installAll(xcodeInstallations(), !noFixXcode15) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/command/Sync.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.command 2 | 3 | import co.touchlab.xcode.cli.InstallationFacade 4 | import com.github.ajalt.clikt.parameters.options.flag 5 | import com.github.ajalt.clikt.parameters.options.option 6 | 7 | class Sync: BaseXcodeListSubcommand("sync", "Adds IDs of Xcode installations to the currently installed Xcode Kotlin plugin") { 8 | private val noFixXcode15 by option( 9 | "--no-fix-xcode15", 10 | help = "Do not apply Xcode 15 workaround." 11 | ).flag() 12 | 13 | override suspend fun run() { 14 | InstallationFacade.sync(xcodeInstallations(), !noFixXcode15) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /LLDBPlugin/test_project/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx6g 10 | # Kotlin code style for this project: "official" or "obsolete": 11 | kotlin.code.style=official 12 | 13 | org.gradle.configuration-cache=true 14 | org.gradle.caching=true 15 | org.gradle.parallel=true 16 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Issue: https://github.com/touchlab/xcode-kotlin/issues/[issue number] 5 | 6 | ## Summary 7 | 8 | 9 | ## Fix 10 | 11 | 12 | ## Pull Request Labels 13 | 14 | 15 | 16 | - [ ] has-reproduction 17 | - [ ] feature 18 | - [ ] blocking 19 | - [ ] good first review 20 | 21 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/types/KonanStringSyntheticProvider.py: -------------------------------------------------------------------------------- 1 | import lldb 2 | 3 | from .base import array_header_type 4 | from .KonanBaseSyntheticProvider import KonanBaseSyntheticProvider 5 | from ..util import kotlin_object_to_string, log 6 | 7 | 8 | class KonanStringSyntheticProvider(KonanBaseSyntheticProvider): 9 | def __init__(self, valobj: lldb.SBValue, type_info: lldb.value): 10 | super().__init__(valobj.Cast(array_header_type()), type_info) 11 | 12 | def update(self): 13 | return True 14 | 15 | def num_children(self): 16 | return 0 17 | 18 | def has_children(self): 19 | return False 20 | 21 | def get_child_index(self, _): 22 | return None 23 | 24 | def get_child_at_index(self, _): 25 | return None 26 | 27 | def to_string(self): 28 | s = kotlin_object_to_string(self._process, self._valobj.unsigned) 29 | if s is None: 30 | return self._valobj.GetValue() 31 | else: 32 | return '"{}"'.format(s) 33 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | kotlin = "2.1.10" 3 | kotlinx-coroutines = "1.7.3" 4 | kotlinx-serialization = "1.6.0" 5 | kermit = "1.2.2" 6 | gradle-doctor = "0.9.2" 7 | clikt = "5.0.3" 8 | mordant = "3.0.1" 9 | 10 | [libraries] 11 | kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" } 12 | kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization" } 13 | kermit = { module = "co.touchlab:kermit", version.ref = "kermit" } 14 | clikt = { module = "com.github.ajalt.clikt:clikt", version.ref = "clikt" } 15 | mordant = { module = "com.github.ajalt.mordant:mordant", version.ref = "mordant" } 16 | 17 | [plugins] 18 | kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } 19 | kotlin-plugin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } 20 | 21 | gradle-doctor = { id = "com.osacky.doctor", version.ref = "gradle-doctor" } 22 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/util/DelegatingTerminalRecorder.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.util 2 | 3 | import com.github.ajalt.mordant.rendering.AnsiLevel 4 | import com.github.ajalt.mordant.terminal.PrintRequest 5 | import com.github.ajalt.mordant.terminal.TerminalInfo 6 | import com.github.ajalt.mordant.terminal.TerminalInterface 7 | import com.github.ajalt.mordant.terminal.TerminalRecorder 8 | 9 | class DelegatingTerminalRecorder( 10 | val delegate: TerminalInterface, 11 | ): TerminalInterface { 12 | val recorder = TerminalRecorder() 13 | 14 | override fun completePrintRequest(request: PrintRequest) { 15 | delegate.completePrintRequest(request) 16 | recorder.completePrintRequest(request) 17 | } 18 | 19 | override fun info( 20 | ansiLevel: AnsiLevel?, 21 | hyperlinks: Boolean?, 22 | outputInteractive: Boolean?, 23 | inputInteractive: Boolean? 24 | ): TerminalInfo = delegate.info(ansiLevel, hyperlinks, outputInteractive, inputInteractive) 25 | 26 | override fun readLineOrNull(hideInput: Boolean): String? = delegate.readLineOrNull(hideInput) 27 | } 28 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/cache/__init__.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | import lldb 4 | 5 | __lldb_cache_instance: 'LLDBCache' 6 | 7 | 8 | class LLDBCache: 9 | @classmethod 10 | def reset(cls): 11 | global __lldb_cache_instance 12 | __lldb_cache_instance = LLDBCache() 13 | 14 | @classmethod 15 | def instance(cls): 16 | global __lldb_cache_instance 17 | return __lldb_cache_instance 18 | 19 | def __init__(self): 20 | self._debug_buffer_addr: Optional[int] = None 21 | self._debug_buffer_size: Optional[int] = None 22 | self._string_symbol_value: Optional[lldb.value] = None 23 | self._list_symbol_value: Optional[lldb.value] = None 24 | self._map_symbol_value: Optional[lldb.value] = None 25 | self._helper_types_declared: bool = False 26 | self._type_info_type: Optional[lldb.SBType] = None 27 | self._obj_header_type: Optional[lldb.SBType] = None 28 | self._array_header_type: Optional[lldb.SBType] = None 29 | self._runtime_type_size: Optional[lldb.value] = None 30 | self._runtime_type_alignment: Optional[lldb.value] = None 31 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/commands/SymbolByNameCommand.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | from lldb import SBDebugger, SBExecutionContext, SBCommandReturnObject 4 | 5 | 6 | class SymbolByNameCommand: 7 | program = 'symbol_by_name' 8 | 9 | def __init__(self, debugger, unused): 10 | pass 11 | 12 | def __call__( 13 | self, 14 | debugger: SBDebugger, 15 | command, 16 | exe_ctx: SBExecutionContext, 17 | result: SBCommandReturnObject, 18 | ): 19 | target = debugger.GetSelectedTarget() 20 | process = target.GetProcess() 21 | thread = process.GetSelectedThread() 22 | frame = thread.GetSelectedFrame() 23 | tokens = command.split() 24 | mask = re.compile(tokens[0]) 25 | symbols = list(filter(lambda v: mask.match(v.name), frame.GetModule().symbols)) 26 | visited = list() 27 | for symbol in symbols: 28 | name = symbol.name 29 | if name in visited: 30 | continue 31 | visited.append(name) 32 | result.AppendMessage("{}: {:#x}".format(name, symbol.GetStartAddress().GetLoadAddress(target))) 33 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/types/KonanZerroSyntheticProvider.py: -------------------------------------------------------------------------------- 1 | import lldb 2 | from ..util import log, NULL 3 | from .KonanBaseSyntheticProvider import KonanBaseSyntheticProvider 4 | 5 | 6 | class KonanZerroSyntheticProvider(object): 7 | def __init__(self, valobj: lldb.SBValue): 8 | super().__init__() 9 | log(lambda: "KonanZerroSyntheticProvider::__init__ {}".format(valobj.name)) 10 | 11 | def update(self): 12 | return True 13 | 14 | def num_children(self): 15 | log(lambda: "KonanZerroSyntheticProvider::num_children") 16 | return 0 17 | 18 | def has_children(self): 19 | log(lambda: "KonanZerroSyntheticProvider::has_children") 20 | return False 21 | 22 | def get_child_index(self, name): 23 | log(lambda: "KonanZerroSyntheticProvider::get_child_index") 24 | return 0 25 | 26 | def get_child_at_index(self, index): 27 | log(lambda: "KonanZerroSyntheticProvider::get_child_at_index") 28 | return None 29 | 30 | def to_string(self): 31 | log(lambda: "KonanZerroSyntheticProvider::to_string") 32 | return NULL 33 | 34 | def __getattr__(self, item): 35 | pass 36 | -------------------------------------------------------------------------------- /LLDBPlugin/test_project/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | alias(libs.plugins.kotlin.multiplatform) 3 | alias(libs.plugins.skie) 4 | application 5 | } 6 | 7 | version = "1.0" 8 | 9 | kotlin { 10 | jvm() 11 | listOf( 12 | macosArm64(), 13 | macosX64(), 14 | ).forEach { 15 | it.binaries.framework { 16 | isStatic = true 17 | } 18 | } 19 | 20 | sourceSets { 21 | commonMain.dependencies { 22 | // implementation(libs.coroutines.core) 23 | } 24 | } 25 | } 26 | 27 | skie { 28 | isEnabled = true 29 | } 30 | 31 | tasks.register("compileSwift") { 32 | group = "build" 33 | 34 | dependsOn("linkDebugFrameworkMacosArm64") 35 | 36 | doFirst { 37 | workingDir.mkdirs() 38 | } 39 | 40 | workingDir(layout.buildDirectory.dir("swift")) 41 | commandLine( 42 | "/usr/bin/xcrun", 43 | "swiftc", 44 | "-g", 45 | "-F", 46 | layout.projectDirectory.dir("build/bin/macosArm64/debugFramework"), 47 | "-o", 48 | "app", 49 | "-Xlinker", 50 | "-dead_strip", 51 | layout.projectDirectory.file("main.swift") 52 | ) 53 | } 54 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/LangSpecManager.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli 2 | 3 | import co.touchlab.xcode.cli.util.Console 4 | import co.touchlab.xcode.cli.util.File 5 | import co.touchlab.xcode.cli.util.Path 6 | 7 | object LangSpecManager { 8 | private val specName = "Kotlin.xclangspec" 9 | private val specSourceFile = File(Path.dataDir / specName) 10 | private val specsDirectory = File(XcodeHelper.xcodeLibraryPath / "Specifications") 11 | private val specTargetFile = File(specsDirectory.path / specName) 12 | 13 | val isInstalled: Boolean 14 | get() = specTargetFile.exists() 15 | 16 | fun install() { 17 | check(!specTargetFile.exists()) { "Language spec file exists at path ${specTargetFile.path}! Delete it first." } 18 | Console.muted("Ensuring language specification directory exists at ${specsDirectory.path}") 19 | specsDirectory.mkdirs() 20 | Console.muted("Copying language specification to target path ${specTargetFile.path}") 21 | specSourceFile.copy(specTargetFile.path) 22 | } 23 | 24 | fun uninstall() { 25 | Console.muted("Deleting language specification from ${specTargetFile.path}.") 26 | specTargetFile.delete() 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /.run/info.run.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 17 | 18 | -------------------------------------------------------------------------------- /.run/repair.run.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 17 | 18 | -------------------------------------------------------------------------------- /.run/uninstall.run.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 17 | 18 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Summary 2 | 3 | 4 | 5 | ## Details 6 | 7 | 8 | 9 | ## Reproduction 10 | 11 | 12 | 13 | ## Expected result 14 | 15 | 16 | 17 | ## Current state 18 | 19 | 20 | 21 | ## Possible Fix 22 | 23 | 24 | 25 | ## Screenshots 26 | 27 | 28 | 29 | fix in action 30 | 31 | ## Issue Labels 32 | 33 | 34 | 35 | - [ ] has-reproduction 36 | - [ ] feature 37 | - [ ] blocking 38 | - [ ] good first issue 39 | 40 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/commands/TypeByAddressCommand.py: -------------------------------------------------------------------------------- 1 | import lldb 2 | 3 | from ..util import log 4 | 5 | 6 | class TypeByAddressCommand: 7 | program = 'type_by_address' 8 | 9 | def __init__(self, debugger, internal_dict): 10 | pass 11 | 12 | def __call__( 13 | self, 14 | debugger: lldb.SBDebugger, 15 | command, 16 | exe_ctx: lldb.SBExecutionContext, 17 | result: lldb.SBCommandReturnObject 18 | ): 19 | log(lambda: "type_by_address_command:{}".format(command)) 20 | result.AppendMessage("DEBUG: {}".format(command)) 21 | tokens = command.split() 22 | target = debugger.GetSelectedTarget() 23 | types = _type_info_by_address(tokens[0], debugger) 24 | result.AppendMessage("DEBUG: {}".format(types)) 25 | for t in types: 26 | result.AppendMessage("{}: {:#x}".format(t.name, t.GetStartAddress().GetLoadAddress(target))) 27 | 28 | 29 | def _type_info_by_address(address, debugger: lldb.SBDebugger): 30 | target = debugger.GetSelectedTarget() 31 | process = target.GetProcess() 32 | thread = process.GetSelectedThread() 33 | frame = thread.GetSelectedFrame() 34 | candidates = list(filter(lambda x: x.GetStartAddress().GetLoadAddress(target) == address, frame.module.symbols)) 35 | return candidates 36 | -------------------------------------------------------------------------------- /.run/install.run.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 17 | 18 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/types/summary.py: -------------------------------------------------------------------------------- 1 | import lldb 2 | 3 | from .select_provider import select_provider 4 | from .base import get_type_info, obj_header_pointer, single_pointer 5 | from ..util import log, evaluate 6 | 7 | 8 | def kotlin_object_type_summary(valobj: lldb.SBValue, internal_dict): 9 | """Hook that is run by lldb to display a Kotlin object.""" 10 | log(lambda: "kotlin_object_type_summary({:#x}: {}: {})".format(valobj.unsigned, valobj.name, valobj.type.name)) 11 | cast_value = obj_header_pointer(valobj) 12 | 13 | type_info = internal_dict["type_info"] if "type_info" in internal_dict.keys() else get_type_info(cast_value) 14 | 15 | if not type_info: 16 | return cast_value.GetValue() 17 | 18 | provider = select_provider(cast_value, type_info) 19 | log(lambda: "kotlin_object_type_summary({:#x} - {})".format(cast_value.unsigned, type(provider).__name__)) 20 | provider.update() 21 | return provider.to_string() 22 | 23 | 24 | def kotlin_objc_class_summary(objc_obj: lldb.SBValue, internal_dict): 25 | # """Hook that is run by lldb to display a Kotlin ObjC class wrapper.""" 26 | objc_obj = single_pointer(objc_obj) 27 | 28 | konan_obj = evaluate( 29 | 'void* __result = 0; (ObjHeader*)Kotlin_ObjCExport_refFromObjC((void*){:#x}, &__result)', 30 | objc_obj.unsigned 31 | ) 32 | return kotlin_object_type_summary(konan_obj, internal_dict) -------------------------------------------------------------------------------- /ABOUT.md: -------------------------------------------------------------------------------- 1 | # Sources 2 | 3 | Setting up the Plugin has been an amalgam of various source projects, as Xcode "Plugins" are undocumented. The most significant piece, the language color file came from other color files shipped with Xcode. Xcode plugin file from [GraphQL](https://github.com/apollographql/xcode-graphql/blob/master/GraphQL.ideplugin/Contents/Resources/GraphQL.xcplugindata) 4 | 5 | LLDB formatting originally comes from the Kotlin/Native project, source [konan_lldb.py](https://github.com/JetBrains/kotlin/blob/master/kotlin-native/llvmDebugInfoC/src/scripts/konan_lldb.py), although the way data is grabbed has been heavily modified to better support an interactive debugger. 6 | 7 | # llvm/lldb Scripts 8 | 9 | Our Xcode plugin uses standard lldb integrations. The Kotlin language ships an [lldb script](https://github.com/JetBrains/kotlin/blob/master/kotlin-native/llvmDebugInfoC/src/scripts/konan_lldb.py) to format Kotlin objects for debugging. It is the same script used across tools in the Kotlin ecosystem for debugging Kotlin native. The performance of the debugger (and lack thereof) is directly tied to this script. We have contributed optimizations in the past, but there is certainly more that can be done. If you have interesting ideas, please submit a PR and we'll see if the main Kotlin team is interested as well... 10 | 11 | # Possible Future Stuff 12 | 13 | Check out the [Discussions](https://github.com/touchlab/xcode-kotlin/discussions/). 14 | 15 | -------------------------------------------------------------------------------- /LLDBPlugin/test_project/src/commonMain/kotlin/main.kt: -------------------------------------------------------------------------------- 1 | //import platform.Foundation.NSURL 2 | //import platform.darwin.NSObject 3 | 4 | fun main() { 5 | val int_ = 0 6 | val void_ = Unit 7 | val string = "Hello world" 8 | val basic = Foo() 9 | val data = DataFoo(basic) 10 | val dataObject = DataObject 11 | val intList = listOf(1, 2, 3, 4) 12 | val basicList = listOf(basic) 13 | val dataList = listOf(data) 14 | val dataMap = mapOf("hello" to data) 15 | // val obj = NSObject() 16 | // val nsChild = NSObjectChild() 17 | 18 | // val nsBasic = basic as NSObject 19 | 20 | dataList.let { 21 | println(it) 22 | } 23 | 24 | dataList.forEach { help -> 25 | println() 26 | } 27 | 28 | basic.bar() 29 | 30 | println() 31 | } 32 | 33 | //class NSObjectChild: NSObject() { 34 | // val foo = Foo() 35 | //} 36 | 37 | class Foo { 38 | val int: Int = -8 39 | 40 | val boolean: Boolean = false 41 | 42 | val string: String = "Hello world" 43 | 44 | val double: Double = 3.14 45 | 46 | val float: Float = 1.23f 47 | 48 | fun bar() { 49 | val something = "no" 50 | 51 | fun what() { 52 | val hello = "yo" 53 | println() 54 | } 55 | 56 | something.let { 57 | println() 58 | } 59 | what() 60 | println() 61 | } 62 | } 63 | 64 | data class DataFoo( 65 | val foo: Foo 66 | ) 67 | 68 | data object DataObject { 69 | val child = DataFoo(Foo()) 70 | } 71 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/commands/FieldTypeCommand.py: -------------------------------------------------------------------------------- 1 | from lldb import SBDebugger, SBExecutionContext, SBCommandReturnObject 2 | 3 | from ..types.proxy import KonanProxyTypeProvider 4 | from ..types.base import get_runtime_type 5 | 6 | 7 | class FieldTypeCommand: 8 | program = 'field_type' 9 | 10 | def __init__(self, debugger, unused): 11 | pass 12 | 13 | def __call__( 14 | self, 15 | debugger: SBDebugger, 16 | command, 17 | exe_ctx: SBExecutionContext, 18 | result: SBCommandReturnObject, 19 | ): 20 | """ 21 | Returns runtime type of foo.bar.baz field in the form "(foo.bar.baz )". 22 | If requested field could not be traced, then "" plug is used for type name. 23 | """ 24 | fields = command.split('.') 25 | 26 | variable = exe_ctx.GetFrame().FindVariable(fields[0]) 27 | 28 | for field_name in fields[1:]: 29 | if variable is not None: 30 | provider = KonanProxyTypeProvider(variable, {}) 31 | field_index = provider.get_child_index(field_name) 32 | variable = provider.get_child_at_index(field_index) 33 | else: 34 | break 35 | 36 | desc = "" 37 | 38 | if variable is not None: 39 | rt = get_runtime_type(variable) 40 | if len(rt) > 0: 41 | desc = rt 42 | 43 | result.write("{}".format(desc)) 44 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/command/BaseXcodeListSubcommand.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.command 2 | 3 | import co.touchlab.xcode.cli.XcodeHelper 4 | import co.touchlab.xcode.cli.util.Path 5 | import com.github.ajalt.clikt.command.SuspendingCliktCommand 6 | import com.github.ajalt.clikt.core.Context 7 | import com.github.ajalt.clikt.parameters.arguments.argument 8 | import com.github.ajalt.clikt.parameters.arguments.multiple 9 | import com.github.ajalt.clikt.parameters.options.flag 10 | import com.github.ajalt.clikt.parameters.options.option 11 | 12 | 13 | abstract class BaseXcodeListSubcommand( 14 | name: String, 15 | private val actionDescription: String, 16 | ): SuspendingCliktCommand(name) { 17 | protected val onlyProvidedXcodeInstallations by option( 18 | "--only", 19 | help = "Do not auto-discover Xcode installations, use only those provided.", 20 | ).flag(default = false, defaultForHelp = "disabled") 21 | protected val providedXcodePaths by argument().multiple() 22 | 23 | override fun help(context: Context): String { 24 | return actionDescription 25 | } 26 | 27 | protected suspend fun xcodeInstallations(): List { 28 | val providedXcodeInstallations = providedXcodePaths.map { XcodeHelper.installationAt(Path(it)) } 29 | return if (onlyProvidedXcodeInstallations) { 30 | providedXcodeInstallations 31 | } else { 32 | XcodeHelper.allXcodeInstallations() + providedXcodeInstallations 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/stepping/KonanStep.py: -------------------------------------------------------------------------------- 1 | class KonanStep(object): 2 | def __init__(self, thread_plan): 3 | self.thread_plan = thread_plan 4 | self.step_thread_plan = self.queue_thread_plan() 5 | 6 | debugger = thread_plan.GetThread().GetProcess().GetTarget().GetDebugger() 7 | self.avoid_no_debug = debugger.GetInternalVariableValue('target.process.thread.step-in-avoid-nodebug', 8 | debugger.GetInstanceName()).GetStringAtIndex(0) 9 | 10 | def explains_stop(self, event): 11 | return True 12 | 13 | def should_stop(self, event): 14 | frame = self.thread_plan.GetThread().GetFrameAtIndex(0) 15 | source_file = frame.GetLineEntry().GetFileSpec().GetFilename() 16 | 17 | if self.avoid_no_debug == 'true' and source_file in [None, '']: 18 | self.step_thread_plan = self.queue_thread_plan() 19 | return False 20 | 21 | self.thread_plan.SetPlanComplete(True) 22 | return True 23 | 24 | def should_step(self): 25 | return True 26 | 27 | def queue_thread_plan(self): 28 | address = self.thread_plan.GetThread().GetFrameAtIndex(0).GetPCAddress() 29 | line_entry = self.thread_plan.GetThread().GetFrameAtIndex(0).GetLineEntry() 30 | begin_address = line_entry.GetStartAddress().GetFileAddress() 31 | end_address = line_entry.GetEndAddress().GetFileAddress() 32 | return self.do_queue_thread_plan(address, end_address - begin_address) 33 | -------------------------------------------------------------------------------- /MANUAL_INSTALL.md: -------------------------------------------------------------------------------- 1 | # Manual Installation 2 | 3 | For advanced users, or if you have issues, you may want to install manually. There are 2 parts to Kotlin support: 1) debugging support and 2) language color and style formatting. 4 | 5 | To follow the original install process, [clone the repo](https://github.com/touchlab/xcode-kotlin) and check out the [legacy branch](https://github.com/touchlab/xcode-kotlin/tree/legacy). You can follow the README instructions there. Basically, run: 6 | 7 | ```shell 8 | ./setup.sh 9 | ``` 10 | 11 | Alternatively, to manually install, you can follow the steps in `setup.sh`. You'll see the folders that the parts of the Xcode plugin need to be copied into. 12 | 13 | If the Xcode version is newer than 13.3, you'll likely need to find and append the UUID for that version to the `Info.plist` file. 14 | 15 | See the next section, [Xcode Updates](#xcode-updates), for instructions on getting the UUID. See [this merged PR](https://github.com/touchlab/xcode-kotlin/pull/46/files) for an example of appending the UUID to the `Info.plist` file. 16 | 17 | ## Xcode Updates 18 | 19 | When Xcode is updated, you may need to add the UUID to `Kotlin.ideplugin/Contents/Info.plist`. To find the UUID of your version of Xcode, run the following: 20 | 21 | ``` 22 | defaults read /Applications/Xcode.app/Contents/Info DVTPlugInCompatibilityUUID 23 | ``` 24 | 25 | Info [from here](https://www.mokacoding.com/blog/xcode-plugins-update/) 26 | 27 | The new CLI tool manages all of that locally, so it's generally a better idea to use that. See the main [README](README.md) for more info. -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/util/Console.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("invisible_reference", "invisible_member") 2 | 3 | package co.touchlab.xcode.cli.util 4 | 5 | import com.github.ajalt.mordant.internal.STANDARD_TERM_INTERFACE 6 | import com.github.ajalt.mordant.terminal.Terminal 7 | import com.github.ajalt.mordant.terminal.YesNoPrompt 8 | import com.github.ajalt.mordant.terminal.danger 9 | import com.github.ajalt.mordant.terminal.info 10 | import com.github.ajalt.mordant.terminal.muted 11 | import com.github.ajalt.mordant.terminal.success 12 | import com.github.ajalt.mordant.terminal.warning 13 | 14 | object Console { 15 | val terminalRecorder = DelegatingTerminalRecorder(delegate = STANDARD_TERM_INTERFACE) 16 | val terminal = Terminal(terminalInterface = terminalRecorder) 17 | 18 | fun echo(text: String = "") { 19 | terminal.println(text) 20 | } 21 | 22 | fun confirm(text: String): Boolean { 23 | while (true) { 24 | val result = YesNoPrompt(text, terminal).ask() 25 | if (result != null) { 26 | return result 27 | } 28 | } 29 | } 30 | 31 | fun muted(message: String) { 32 | terminal.muted(message) 33 | } 34 | 35 | fun info(message: String) { 36 | terminal.info(message) 37 | } 38 | 39 | fun warning(message: String) { 40 | terminal.warning(message) 41 | } 42 | 43 | fun danger(message: String) { 44 | terminal.danger(message, stderr = true) 45 | } 46 | 47 | fun success(message: String) { 48 | terminal.success(message) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/types/KonanBaseSyntheticProvider.py: -------------------------------------------------------------------------------- 1 | import lldb 2 | 3 | from ..util import DebuggerException, kotlin_object_to_string 4 | 5 | 6 | class KonanBaseSyntheticProvider(object): 7 | def __init__(self, valobj: lldb.SBValue, type_info: lldb.value): 8 | super().__init__() 9 | 10 | self._valobj: lldb.SBValue = valobj 11 | self._val: lldb.value = lldb.value(valobj.GetNonSyntheticValue()) 12 | self._type_info: lldb.value = type_info 13 | self._process: lldb.SBProcess = lldb.debugger.GetSelectedTarget().process 14 | 15 | def update(self) -> bool: 16 | return False 17 | 18 | def get_type_name(self) -> str: 19 | package_name = kotlin_object_to_string(self._process, self._type_info.packageName_.sbvalue.unsigned) 20 | relative_name = kotlin_object_to_string(self._process, self._type_info.relativeName_.sbvalue.unsigned) 21 | return '{}.{}'.format(package_name, relative_name) 22 | 23 | def read_cstring(self, address: int) -> str: 24 | error = lldb.SBError() 25 | result = self._process.ReadCStringFromMemory( 26 | address, 27 | 0x1000, 28 | error, 29 | ) 30 | if not error.Success(): 31 | raise DebuggerException( 32 | 'Could not read cstring at address {:#x} (error: {})'.format( 33 | address, 34 | error.description, 35 | ) 36 | ) 37 | return result 38 | 39 | def to_string(self): 40 | return kotlin_object_to_string(self._process, self._valobj.unsigned) 41 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/util/kotlin_object_to_cstring.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from lldb import SBProcess, SBError 4 | 5 | from .DebuggerException import DebuggerException 6 | from .expression import evaluate 7 | from .log import log 8 | from ..cache import LLDBCache 9 | 10 | 11 | def get_debug_buffer_addr() -> int: 12 | self = LLDBCache.instance() 13 | if self._debug_buffer_addr is None: 14 | self._debug_buffer_addr = int(evaluate("(__konan_safe_void_t *)Konan_DebugBuffer()").unsigned) 15 | return self._debug_buffer_addr 16 | 17 | 18 | def get_debug_buffer_size() -> int: 19 | self = LLDBCache.instance() 20 | if self._debug_buffer_size is None: 21 | self._debug_buffer_size = int(evaluate("(__konan_safe_int_t)Konan_DebugBufferSize()").unsigned) 22 | return self._debug_buffer_size 23 | 24 | 25 | def kotlin_object_to_string(process: SBProcess, object_addr: int) -> Optional[str]: 26 | debug_buffer_addr = get_debug_buffer_addr() 27 | debug_buffer_size = get_debug_buffer_size() 28 | string_len = evaluate( 29 | '(__konan_safe_int_t)Konan_DebugObjectToUtf8Array((__konan_safe_void_t*){:#x}, (__konan_safe_void_t *){:#x}, {});', 30 | object_addr, 31 | debug_buffer_addr, 32 | debug_buffer_size, 33 | ).signed 34 | 35 | if not string_len: 36 | return None 37 | 38 | error = SBError() 39 | s = process.ReadCStringFromMemory(debug_buffer_addr, int(string_len), error) 40 | if not error.Success(): 41 | raise DebuggerException("Couldn't read object description Error: {}.".format(error.description)) 42 | return s 43 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/types/KonanObjectSyntheticProvider.py: -------------------------------------------------------------------------------- 1 | import lldb 2 | 3 | 4 | from .base import _TYPE_CONVERSION, type_info_type 5 | from .KonanBaseSyntheticProvider import KonanBaseSyntheticProvider 6 | 7 | 8 | class KonanObjectSyntheticProvider(KonanBaseSyntheticProvider): 9 | def __init__(self, valobj: lldb.SBValue, type_info: lldb.value): 10 | self._children_count = 0 11 | self._children_names = [] 12 | self._was_updated = False 13 | 14 | super().__init__(valobj, type_info) 15 | 16 | def update(self) -> bool: 17 | self._was_updated = True 18 | self._children_count = int(self._type_info.extendedInfo_.fieldsCount_) 19 | if self._children_count < 0: 20 | self._children_count = 0 21 | if self._children_count > 0: 22 | field_names = self._type_info.extendedInfo_.fieldNames_ 23 | self._children_names = [ 24 | self.read_cstring(int(field_names[i])) for i in range(self._children_count) 25 | ] 26 | return False 27 | 28 | def num_children(self): 29 | return self._children_count 30 | 31 | def has_children(self): 32 | return True 33 | 34 | def get_child_index(self, name): 35 | # if self._children is None: 36 | return self._children_names.index(name) 37 | 38 | def get_child_at_index(self, index): 39 | value_type = self._type_info.extendedInfo_.fieldTypes_[index] 40 | address = self.get_child_address_at_index(index) 41 | return _TYPE_CONVERSION[int(value_type)](self, self._valobj, address, self._children_names[index]) 42 | 43 | def get_child_address_at_index(self, index): 44 | return self._valobj.unsigned + int(self._type_info.extendedInfo_.fieldOffsets_[index]) 45 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/stepping/KonanHook.py: -------------------------------------------------------------------------------- 1 | import lldb 2 | 3 | from .KonanStepIn import KonanStepIn 4 | from .KonanStepOut import KonanStepOut 5 | from .KonanStepOver import KonanStepOver 6 | 7 | KONAN_LLDB_DONT_SKIP_BRIDGING_FUNCTIONS = 'KONAN_LLDB_DONT_SKIP_BRIDGING_FUNCTIONS' 8 | MAX_SIZE_FOR_STOP_REASON = 20 9 | PLAN_FROM_STOP_REASON = { 10 | 'step in': KonanStepIn.__name__, 11 | 'step out': KonanStepOut.__name__, 12 | 'step over': KonanStepOver.__name__, 13 | } 14 | 15 | 16 | class KonanHook: 17 | def __init__(self, target: lldb.SBTarget, extra_args, _): 18 | pass 19 | 20 | def handle_stop(self, execution_context: lldb.SBExecutionContext, stream: lldb.SBStream) -> bool: 21 | is_bridging_functions_skip_enabled = not execution_context.target.GetEnvironment().Get( 22 | KONAN_LLDB_DONT_SKIP_BRIDGING_FUNCTIONS 23 | ) 24 | 25 | def is_kotlin_bridging_function() -> bool: 26 | addr = execution_context.frame.addr 27 | function_name = addr.function.name 28 | if function_name is None: 29 | return False 30 | file_name = addr.line_entry.file.basename 31 | if file_name is None: 32 | return False 33 | return function_name.startswith('objc2kotlin_') and file_name == '' 34 | 35 | if is_bridging_functions_skip_enabled and is_kotlin_bridging_function(): 36 | stop_reason = execution_context.frame.thread.GetStopDescription(MAX_SIZE_FOR_STOP_REASON) 37 | plan = PLAN_FROM_STOP_REASON.get(stop_reason) 38 | if plan is not None: 39 | execution_context.thread.StepUsingScriptedThreadPlan('{}.{}'.format(__name__, plan), False) 40 | return False 41 | return True 42 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/types/proxy.py: -------------------------------------------------------------------------------- 1 | from typing import Optional, Union 2 | 3 | import lldb 4 | 5 | from ..util import evaluate 6 | from .KonanNotInitializedObjectSyntheticProvider import KonanNotInitializedObjectSyntheticProvider 7 | from .KonanBaseSyntheticProvider import KonanBaseSyntheticProvider 8 | from .KonanZerroSyntheticProvider import KonanZerroSyntheticProvider 9 | from .base import get_type_info, obj_header_pointer, single_pointer 10 | from .select_provider import select_provider 11 | 12 | 13 | class KonanProxyTypeProvider: 14 | def __init__(self, valobj: lldb.SBValue, internal_dict): 15 | self._valobj = valobj 16 | self._proxy: Optional[Union[KonanBaseSyntheticProvider, KonanZerroSyntheticProvider]] = None 17 | 18 | def __getattr__(self, item): 19 | if self._proxy is None: 20 | cast_value = obj_header_pointer(self._valobj) 21 | type_info = get_type_info(cast_value) 22 | 23 | if not type_info: 24 | self._proxy = KonanNotInitializedObjectSyntheticProvider(self._valobj) 25 | return 26 | 27 | self._proxy = select_provider(cast_value, type_info) 28 | 29 | return getattr(self._proxy, item) 30 | 31 | 32 | class KonanObjcProxyTypeProvider: 33 | def __init__(self, objc_obj: lldb.SBValue, internal_dict): 34 | self._objc_obj = objc_obj 35 | self._proxy: Optional[KonanProxyTypeProvider] = None 36 | 37 | def __getattr__(self, item): 38 | if self._proxy is None: 39 | objc_obj = single_pointer(self._objc_obj) 40 | 41 | konan_obj = evaluate( 42 | 'void* __result = 0; (ObjHeader*)Kotlin_ObjCExport_refFromObjC((void*){:#x}, &__result)', 43 | objc_obj.unsigned 44 | ) 45 | self._proxy = KonanProxyTypeProvider(konan_obj, {}) 46 | return getattr(self._proxy, item) 47 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/types/KonanArraySyntheticProvider.py: -------------------------------------------------------------------------------- 1 | import lldb 2 | 3 | from ..util import log, evaluate 4 | from .base import _TYPE_CONVERSION, array_header_type, runtime_type_alignment, runtime_type_size 5 | from .KonanBaseSyntheticProvider import KonanBaseSyntheticProvider 6 | 7 | 8 | class KonanArraySyntheticProvider(KonanBaseSyntheticProvider): 9 | def __init__(self, valobj: lldb.SBValue, type_info: lldb.value): 10 | self._children_count = 0 11 | 12 | super().__init__(valobj.Cast(array_header_type()), type_info) 13 | 14 | def update(self) -> bool: 15 | super().update() 16 | self._children_count = int(self._val.count_) 17 | return False 18 | 19 | def num_children(self): 20 | return self._children_count 21 | 22 | def has_children(self): 23 | return True 24 | 25 | def get_child_index(self, name): 26 | log(lambda: "KonanArraySyntheticProvider::get_child_index({})".format(name)) 27 | index = int(name.removeprefix('[').removesuffix(']')) 28 | return index if (0 <= index < self._children_count) else -1 29 | 30 | def get_child_at_index(self, index): 31 | 32 | value_type = -int(self._type_info.extendedInfo_.fieldsCount_) 33 | address = self._valobj.unsigned + self._align_up( 34 | self._valobj.type.GetPointeeType().GetByteSize(), 35 | int(runtime_type_alignment()[value_type]) 36 | ) + index * int(runtime_type_size()[value_type]) 37 | return _TYPE_CONVERSION[int(value_type)](self, self._valobj, address, '[{}]'.format(index)) 38 | 39 | def to_string(self): 40 | if self._children_count == 1: 41 | return '1 value' 42 | else: 43 | return '{} values'.format(self._children_count) 44 | 45 | @staticmethod 46 | def _align_up(size, alignment): 47 | return (size + alignment - 1) & ~(alignment - 1) 48 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/main.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli 2 | 3 | import co.touchlab.xcode.cli.command.Disable 4 | import co.touchlab.xcode.cli.command.Enable 5 | import co.touchlab.xcode.cli.command.FixXcode15 6 | import co.touchlab.xcode.cli.command.Info 7 | import co.touchlab.xcode.cli.command.Install 8 | import co.touchlab.xcode.cli.command.Sync 9 | import co.touchlab.xcode.cli.command.Uninstall 10 | import co.touchlab.xcode.cli.command.XcodeKotlinPlugin 11 | import co.touchlab.xcode.cli.util.Console 12 | import co.touchlab.xcode.cli.util.CrashHelper 13 | import com.github.ajalt.clikt.command.main 14 | import com.github.ajalt.clikt.core.context 15 | import com.github.ajalt.clikt.core.subcommands 16 | import com.github.ajalt.clikt.core.terminal 17 | import kotlinx.coroutines.runBlocking 18 | import platform.posix.exit 19 | 20 | fun main(args: Array) { 21 | val crashHelper = CrashHelper() 22 | 23 | try { 24 | val command = XcodeKotlinPlugin(args) 25 | .context { 26 | this.terminal = Console.terminal 27 | } 28 | .subcommands( 29 | Install(), 30 | Uninstall(), 31 | Sync(), 32 | Info(), 33 | FixXcode15(), 34 | Enable(), 35 | Disable(), 36 | ) 37 | 38 | runBlocking { 39 | command.main(args) 40 | } 41 | } catch (e: Throwable) { 42 | if (Console.confirm("xcode-kotlin has crashed, do you want to upload the crash report to Touchlab?")) { 43 | Console.echo("Uploading crash report.") 44 | try { 45 | crashHelper.upload(e, Console.terminalRecorder.recorder) 46 | Console.success("Upload successful") 47 | exit(1) 48 | } catch (uploadException: Throwable) { 49 | Console.danger("Uploading crash report failed!") 50 | e.addSuppressed(uploadException) 51 | throw e 52 | } 53 | } else { 54 | throw e 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/util/expression.py: -------------------------------------------------------------------------------- 1 | import lldb 2 | from .log import log 3 | from ..cache import LLDBCache 4 | 5 | 6 | def initialize_expression_options(): 7 | options = lldb.SBExpressionOptions() 8 | options.SetIgnoreBreakpoints(True) 9 | options.SetAutoApplyFixIts(False) 10 | options.SetFetchDynamicValue(False) 11 | options.SetGenerateDebugInfo(False) 12 | options.SetSuppressPersistentResult(True) 13 | options.SetREPLMode(False) 14 | options.SetAllowJIT(True) 15 | options.SetLanguage(lldb.eLanguageTypeC_plus_plus_20) 16 | return options 17 | 18 | 19 | def initialize_top_level_expression_options(): 20 | options = initialize_expression_options() 21 | options.SetTopLevel(True) 22 | options.SetSuppressPersistentResult(False) 23 | return options 24 | 25 | 26 | EXPRESSION_OPTIONS = initialize_expression_options() 27 | TOP_LEVEL_EXPRESSION_OPTIONS = initialize_top_level_expression_options() 28 | 29 | 30 | def evaluate(expression: str, *args, **kwargs) -> lldb.SBValue: 31 | declare_helper_types() 32 | formatted_expression = expression.format(*args, **kwargs) 33 | result = lldb.debugger.GetSelectedTarget().EvaluateExpression(formatted_expression, EXPRESSION_OPTIONS) 34 | log(lambda: "evaluate: {} => {}".format(formatted_expression, result)) 35 | return result 36 | 37 | 38 | def top_level_evaluate(expr) -> lldb.SBValue: 39 | log(lambda: "top_level_evaluate: target={}".format(lldb.debugger.GetSelectedTarget())) 40 | result = lldb.debugger.GetSelectedTarget().EvaluateExpression(expr, TOP_LEVEL_EXPRESSION_OPTIONS) 41 | log(lambda: "top_level_evaluate: {} => {}".format(expr, result)) 42 | return result 43 | 44 | 45 | def declare_helper_types(): 46 | self = LLDBCache.instance() 47 | if not self._helper_types_declared: 48 | import pathlib 49 | script_dir = pathlib.Path(__file__).parent.resolve() 50 | expression = '#include "{}/konan_debug.h"'.format(script_dir) 51 | result = top_level_evaluate(expression) 52 | log(lambda: '{} => {}'.format(expression, result)) 53 | 54 | self._helper_types_declared = True 55 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | In the first place, thank you for thinking about contributing to **xcode-kotlin**! 4 | Here you can find a set of guidelines for pitching in. 5 | 6 | ## Questions 7 | 8 | If you have any questions, please, contact us in the Kotlin [Community Slack](https://kotlinlang.slack.com/) in 9 | [the #touchlab-tools channel](https://kotlinlang.slack.com/archives/CTJB58X7X). To join the Kotlin Community Slack, 10 | [request access here](http://slack.kotlinlang.org/). 11 | 12 | For direct assistance, please [reach out to Touchlab](https://touchlab.co/contact-us/) to discuss support options. 13 | 14 | ## Set up environment 15 | 16 | For instructions on how to set up your environment and run the project, refer to the 17 | [README](https://github.com/touchlab/xcode-kotlin/blob/main/README.md) and 18 | [BUILDING](https://github.com/touchlab/xcode-kotlin/blob/main/BUILDING.md). 19 | 20 | ## Create an issue 21 | 22 | If you have stumbled across a bug or have a good feature suggestion / enhancement, you can create an 23 | [issue](https://github.com/touchlab/xcode-kotlin/issues), but please don't mistake it for the general helpline. You can 24 | get answers for general questions in Slack. Please, fill in carefully all the info the issue template suggests. It will 25 | save us time when investigating the problem. There might be a bit of a delay until we get to your ticket, so we ask for 26 | your patience. 27 | 28 | ## Submit a merge request 29 | 30 | If you wish to participate in submitting code changes, to start with, you can look for issues tagged with **good first 31 | issue**. In case you feel like making significant changes or adding features, please discuss with the team first before 32 | you start working on it, to ensure we are on the same page. When your fix / feature is ready, create a merge request 33 | using the pull request template and fill in as much information as possible. All merge requests need to pass a code 34 | review from our team member, and subsequently they are approved or rejected with a reason. It might take some time 35 | before we get to your merge request, but don’t worry, it didn't get lost. 36 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/types/KonanListSyntheticProvider.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | import lldb 4 | 5 | from .base import get_type_info 6 | from ..util import log, DebuggerException 7 | from .KonanObjectSyntheticProvider import KonanObjectSyntheticProvider 8 | from .KonanArraySyntheticProvider import KonanArraySyntheticProvider 9 | 10 | 11 | class KonanListSyntheticProvider(KonanObjectSyntheticProvider): 12 | __possible_backing_properties = {'backing', '$this_asList', 'backingArray'} 13 | 14 | def __init__(self, valobj: lldb.SBValue, type_info: lldb.value): 15 | self._backing: KonanArraySyntheticProvider = None # type: ignore 16 | 17 | super().__init__(valobj, type_info) 18 | 19 | def update(self): 20 | super().update() 21 | 22 | if self._backing is None: 23 | backing: Optional[KonanArraySyntheticProvider] = None 24 | for index, name in enumerate(self._children_names): 25 | if name in KonanListSyntheticProvider.__possible_backing_properties: 26 | backing = self._create_backing(index, name) 27 | if backing is not None: 28 | break 29 | 30 | if backing is None: 31 | raise DebuggerException( 32 | "Couldn't find backing for list {:#x}, name: {}".format(self._valobj.unsigned, self._valobj.name) 33 | ) 34 | 35 | self._backing = backing 36 | 37 | self._backing.update() 38 | return False 39 | 40 | def num_children(self): 41 | return self._backing.num_children() 42 | 43 | def has_children(self): 44 | return True 45 | 46 | def get_child_index(self, name): 47 | return self._backing.get_child_index(name) 48 | 49 | def get_child_at_index(self, index): 50 | return self._backing.get_child_at_index(index) 51 | 52 | def to_string(self): 53 | return self._backing.to_string() 54 | 55 | def _create_backing(self, index: int, name: str) -> Optional[KonanArraySyntheticProvider]: 56 | address = self.get_child_address_at_index(index) 57 | backing_value = self._valobj.CreateValueFromAddress( 58 | name, 59 | address, 60 | self._valobj.type, 61 | ) 62 | child_type_info = get_type_info(backing_value) 63 | if child_type_info is None: 64 | return None 65 | else: 66 | return KonanArraySyntheticProvider(backing_value, child_type_info) 67 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/util/CrashHelper.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.util 2 | 3 | import com.github.ajalt.mordant.terminal.TerminalRecorder 4 | import kotlinx.coroutines.CompletableDeferred 5 | import kotlinx.coroutines.runBlocking 6 | import platform.Foundation.NSError 7 | import platform.Foundation.NSMutableURLRequest 8 | import platform.Foundation.NSURL 9 | import platform.Foundation.NSURLSession 10 | import platform.Foundation.NSURLSessionConfiguration.Companion.defaultSessionConfiguration 11 | import platform.Foundation.NSUTF8StringEncoding 12 | import platform.Foundation.dataTaskWithRequest 13 | import platform.Foundation.dataUsingEncoding 14 | import platform.Foundation.setHTTPBody 15 | import platform.Foundation.setHTTPMethod 16 | import platform.Foundation.setValue 17 | 18 | class CrashHelper { 19 | fun upload(e: Throwable, recorder: TerminalRecorder) { 20 | upload(capture(e, recorder.output())) 21 | } 22 | 23 | private fun upload(crashReport: String) { 24 | val tagQuery = "?tag=xcode-kotlin" + if (Platform.isDebugBinary) "-DEBUG" else "" 25 | val url = "https://api.touchlab.dev/crash/report$tagQuery".let { urlString -> 26 | checkNotNull(NSURL.URLWithString(urlString)) { 27 | "Couldn't construct NSURL from $urlString" 28 | } 29 | } 30 | val request = NSMutableURLRequest.requestWithURL(url).apply { 31 | setHTTPMethod("POST") 32 | setValue("text/plain", "Content-Type") 33 | setHTTPBody(crashReport.objc.dataUsingEncoding(NSUTF8StringEncoding)) 34 | } 35 | 36 | val uploadComplete = CompletableDeferred() 37 | val session = NSURLSession 38 | .sessionWithConfiguration(defaultSessionConfiguration) 39 | .dataTaskWithRequest(request) { _, _, error -> 40 | if (error != null) { 41 | uploadComplete.completeExceptionally(CrashReportUploadException(error)) 42 | } else { 43 | uploadComplete.complete(Unit) 44 | } 45 | } 46 | 47 | runBlocking { 48 | session.resume() 49 | uploadComplete.await() 50 | } 51 | } 52 | 53 | private fun capture(e: Throwable, recorderOutput: String): String = buildString { 54 | if (recorderOutput.isNotBlank()) { 55 | append("BREADCRUMBS\n===========\n\n") 56 | append(recorderOutput) 57 | append("\n\n") 58 | } 59 | 60 | append("FINAL CRASH\n===========\n\n") 61 | append(e.stackTraceToString()) 62 | } 63 | 64 | class CrashReportUploadException(val error: NSError): Exception("Crash report upload failed: ${error.localizedDescription}") 65 | } 66 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/types/select_provider.py: -------------------------------------------------------------------------------- 1 | import lldb 2 | 3 | from .base import get_string_symbol, get_list_symbol, get_map_symbol 4 | from .KonanStringSyntheticProvider import KonanStringSyntheticProvider 5 | from .KonanArraySyntheticProvider import KonanArraySyntheticProvider 6 | from .KonanListSyntheticProvider import KonanListSyntheticProvider 7 | from .KonanObjectSyntheticProvider import KonanObjectSyntheticProvider 8 | from .KonanBaseSyntheticProvider import KonanBaseSyntheticProvider 9 | from .KonanMapSyntheticProvider import KonanMapSyntheticProvider 10 | from ..util import log 11 | 12 | 13 | def _is_subtype(obj_type_info: lldb.value, type_info: lldb.value) -> bool: 14 | try: 15 | # noinspection PyPep8Naming 16 | TF_INTERFACE = 1 << 2 17 | # If it is an interface - check in list of implemented interfaces. 18 | if (int(type_info.flags_) & TF_INTERFACE) != 0: 19 | for i in range(int(obj_type_info.implementedInterfacesCount_)): 20 | if obj_type_info.implementedInterfaces_[i] == type_info: 21 | return True 22 | return False 23 | while obj_type_info != 0 and obj_type_info != type_info: 24 | obj_type_info = obj_type_info.superType_ 25 | 26 | return obj_type_info != 0 27 | except BaseException as e: 28 | import traceback 29 | traceback.print_exc() 30 | return False 31 | 32 | 33 | def select_provider(valobj: lldb.SBValue, type_info: lldb.value) -> KonanBaseSyntheticProvider: 34 | log(lambda: "[BEGIN] select_provider") 35 | 36 | try: 37 | if _is_subtype(type_info, get_string_symbol()): 38 | provider = KonanStringSyntheticProvider(valobj, type_info) 39 | elif _is_subtype(type_info, get_list_symbol()): 40 | provider = KonanListSyntheticProvider(valobj, type_info) 41 | elif _is_subtype(type_info, get_map_symbol()): 42 | provider = KonanMapSyntheticProvider(valobj, type_info) 43 | elif int(type_info.instanceSize_) < 0: 44 | provider = KonanArraySyntheticProvider(valobj, type_info) 45 | else: 46 | provider = KonanObjectSyntheticProvider(valobj, type_info) 47 | 48 | except: 49 | import traceback 50 | import sys 51 | sys.stderr.write( 52 | "Couldn't select provider for value {:#x} (name={}).\n".format( 53 | valobj.unsigned, 54 | valobj.name, 55 | ) 56 | ) 57 | traceback.print_exc() 58 | sys.stderr.write('\nFalling back to KonanObjectSyntheticProvider.\n') 59 | provider = KonanObjectSyntheticProvider(valobj, type_info) 60 | 61 | log(lambda: "[END] select_provider = {}".format( 62 | provider, 63 | )) 64 | return provider 65 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/command/Info.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.command 2 | 3 | import co.touchlab.xcode.cli.LLDBInitManager 4 | import co.touchlab.xcode.cli.LangSpecManager 5 | import co.touchlab.xcode.cli.PluginManager 6 | import co.touchlab.xcode.cli.util.Console 7 | 8 | class Info: BaseXcodeListSubcommand("info", "Shows information about the plugin") { 9 | 10 | override suspend fun run() = with(Console) { 11 | val installedVersion = PluginManager.installedVersion 12 | val bundledVersion = PluginManager.bundledVersion 13 | 14 | if (installedVersion != null && bundledVersion > installedVersion) { 15 | echo("Update available! Run 'xcode-kotlin install' to update.") 16 | echo() 17 | } else if (installedVersion == null) { 18 | echo("Plugin not installed. Run 'xcode-kotlin install' to install it.") 19 | echo() 20 | } 21 | 22 | val lldbInstalled = LLDBInitManager.isInstalled 23 | val legacyLldbInstalled = LLDBInitManager.Legacy.isInstalled 24 | val lldbInstalledString = if (lldbInstalled) { 25 | "Yes" 26 | } else if (legacyLldbInstalled) { 27 | "Legacy" 28 | } else { 29 | "No" 30 | } 31 | 32 | echo("Installed plugin version:\t${installedVersion ?: "none"}") 33 | echo("Bundled plugin version:\t\t${bundledVersion}") 34 | echo() 35 | echo("Language spec installed: ${LangSpecManager.isInstalled.humanReadable}") 36 | echo("LLDB init installed: $lldbInstalledString") 37 | echo("LLDB Xcode init sources main LLDB init: ${LLDBInitManager.sourcesMainLlvmInit.humanReadable}") 38 | 39 | val xcodeInstallations = xcodeInstallations() 40 | if (xcodeInstallations.isNotEmpty()) { 41 | val supportedXcodeUuids = PluginManager.targetSupportedXcodeUUIds.toSet() 42 | echo() 43 | echo("Installed Xcode versions:") 44 | val longestNameLength = xcodeInstallations.maxOf { it.name.length } 45 | for (install in xcodeInstallations) { 46 | val spacesAfterName = 47 | (1..(longestNameLength - install.name.length)).joinToString(separator = "") { " " } 48 | val compatibilityMark = if (install.supported(supportedXcodeUuids)) "✔" else "x" 49 | echo("$compatibilityMark\t${install.name}$spacesAfterName\t${install.pluginCompatabilityId}\t${install.path}") 50 | } 51 | 52 | echo() 53 | echo("✔ - plugin is compatible, x - plugin is not compatible") 54 | echo("Run 'xcode-kotlin sync' to add compatibility for all listed Xcode versions.") 55 | } 56 | } 57 | 58 | private val Boolean.humanReadable: String 59 | get() = if (this) "Yes" else "No" 60 | } 61 | -------------------------------------------------------------------------------- /LLDBPlugin/run.py: -------------------------------------------------------------------------------- 1 | # Before running this, add LLDB to your PYTHONPATH (e.g. PYTHONPATH=`lldb -P`) 2 | 3 | import os 4 | import subprocess 5 | import sys 6 | 7 | import lldb 8 | 9 | 10 | def tracefunc(frame, event, arg, indent=[0]): 11 | if event == "call": 12 | indent[0] += 2 13 | print("-" * indent[0] + "> call function", frame.f_code.co_name) 14 | elif event == "return": 15 | print("<" + "-" * indent[0], "exit function", frame.f_code.co_name) 16 | indent[0] -= 2 17 | return tracefunc 18 | 19 | # sys.setprofile(tracefunc) 20 | 21 | gradle_invoke = subprocess.Popen(['./gradlew', 'compileSwift'], cwd='test_project') 22 | gradle_exit_code = gradle_invoke.wait() 23 | 24 | if gradle_exit_code != 0: 25 | exit(gradle_exit_code) 26 | 27 | exe = 'test_project/build/swift/app' 28 | framework_path = 'test_project/build/bin/macosArm64/debugFramework' 29 | 30 | # Initialize the debugger before making any API calls. 31 | lldb.SBDebugger.Initialize() 32 | # Create a new debugger instance in your module if your module 33 | # can be run from the command line. When we run a script from 34 | # the command line, we won't have any debugger object in 35 | # lldb.debugger, so we can just create it if it will be needed 36 | debugger: lldb.SBDebugger = lldb.SBDebugger.Create() 37 | 38 | # When we step or continue, don't return from the function until the process 39 | # stops. Otherwise we would have to handle the process events ourselves which, while doable is 40 | # a little tricky. We do this by setting the async mode to false. 41 | debugger.SetAsync(False) 42 | 43 | # debugger.HandleCommand('log enable lldb default') 44 | # debugger.HandleCommand('log enable lldb default') 45 | debugger.HandleCommand('log enable lldb commands') 46 | debugger.HandleCommand('log enable lldb types') 47 | 48 | # Import our module 49 | debugger.HandleCommand('command script import touchlab_kotlin_lldb') 50 | 51 | target: lldb.SBTarget = debugger.CreateTargetWithFileAndArch(exe, lldb.LLDB_ARCH_DEFAULT) 52 | 53 | if target: 54 | # target.BreakpointCreateByLocation("main.swift", 14) 55 | target.BreakpointCreateByLocation('main.kt', 30) 56 | 57 | process: lldb.SBProcess = target.LaunchSimple(None, ["DYLD_FRAMEWORK_PATH={}".format(framework_path)], os.getcwd()) 58 | 59 | if process: 60 | import time 61 | 62 | start = time.perf_counter() 63 | debugger.HandleCommand('fr v -T --ptr-depth 16') 64 | print('HandleCommand took {:.6}s'.format(time.perf_counter() - start)) 65 | process.Continue() 66 | # debugger.HandleCommand('fr v --ptr-depth 16 -- data') 67 | # debugger.HandleCommand('fr v --ptr-depth 16') 68 | 69 | process.Kill() 70 | 71 | # Finally, dispose of the debugger you just made. 72 | lldb.SBDebugger.Destroy(debugger) 73 | # Terminate the debug session 74 | lldb.SBDebugger.Terminate() 75 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/util/Path.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.util 2 | 3 | import platform.Foundation.NSBundle 4 | import platform.Foundation.NSFileManager 5 | import platform.Foundation.NSHomeDirectory 6 | import platform.Foundation.NSString 7 | import platform.Foundation.stringByAppendingPathComponent 8 | import platform.Foundation.stringByDeletingLastPathComponent 9 | import platform.Foundation.stringByResolvingSymlinksInPath 10 | 11 | data class Path( 12 | val value: String, 13 | ) { 14 | val parent: Path 15 | get() = deletingLastPathComponent() 16 | 17 | constructor(basePath: Path, vararg components: String): this(basePath.value, *components) 18 | 19 | constructor(basePath: String, vararg components: String): this(components.fold(basePath) { path, component -> 20 | path.appendingPathComponent(component) 21 | }) 22 | 23 | operator fun div(component: String): Path { 24 | return appendingPathComponent(component) 25 | } 26 | 27 | fun appendingPathComponent(component: String): Path { 28 | return Path(value.appendingPathComponent(component)) 29 | } 30 | 31 | fun deletingLastPathComponent(): Path { 32 | return Path(value.deletingLastPathComponent()) 33 | } 34 | 35 | fun resolvingSymlinksInPath(): Path { 36 | return Path(value.resolvingSymlinksInPath()) 37 | } 38 | 39 | fun exists(): Boolean = NSFileManager.defaultManager.fileExistsAtPath(value) 40 | 41 | override fun toString(): String { 42 | return value 43 | } 44 | 45 | companion object { 46 | val home: Path 47 | get() = Path(NSHomeDirectory()) 48 | 49 | val workDir: Path 50 | get() = Path(NSFileManager.defaultManager.currentDirectoryPath) 51 | 52 | val binaryDir: Path 53 | get() = Path(NSBundle.mainBundle.bundlePath) 54 | 55 | val dataDir: Path 56 | get() = if (Platform.isDebugBinary) { 57 | // TODO: This requires running the debug binary with working directory set to the project's root after running `./gradlew preparePlugin`. 58 | workDir / "build" / "share" 59 | } else { 60 | // TODO: This will only be true when installing through Homebrew. Do we want to have different configurations? 61 | binaryDir.parent / "share" 62 | } 63 | 64 | private fun String.appendingPathComponent(component: String): String { 65 | return this.objc.stringByAppendingPathComponent(component) 66 | } 67 | 68 | private fun String.deletingLastPathComponent(): String { 69 | return this.objc.stringByDeletingLastPathComponent() 70 | } 71 | 72 | private fun String.resolvingSymlinksInPath(): String { 73 | return this.objc.stringByResolvingSymlinksInPath() 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/commands/KonanGlobalsCommand.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | from lldb import SBDebugger, SBExecutionContext, SBCommandReturnObject 4 | 5 | from ..types.summary import kotlin_object_type_summary 6 | from ..util.expression import evaluate 7 | 8 | 9 | __KONAN_VARIABLE = re.compile('kvar:(.*)#internal') 10 | __KONAN_VARIABLE_TYPE = re.compile('^kfun:\\(\\)(.*)$') 11 | __TYPES_KONAN_TO_C = { 12 | 'kotlin.Byte': ('int8_t', lambda v: v.signed), 13 | 'kotlin.Short': ('short', lambda v: v.signed), 14 | 'kotlin.Int': ('int', lambda v: v.signed), 15 | 'kotlin.Long': ('long', lambda v: v.signed), 16 | 'kotlin.UByte': ('int8_t', lambda v: v.unsigned), 17 | 'kotlin.UShort': ('short', lambda v: v.unsigned), 18 | 'kotlin.UInt': ('int', lambda v: v.unsigned), 19 | 'kotlin.ULong': ('long', lambda v: v.unsigned), 20 | 'kotlin.Char': ('short', lambda v: v.signed), 21 | 'kotlin.Boolean': ('bool', lambda v: v.signed), 22 | 'kotlin.Float': ('float', lambda v: v.value), 23 | 'kotlin.Double': ('double', lambda v: v.value) 24 | } 25 | 26 | 27 | class KonanGlobalsCommand: 28 | program = 'konan_globals' 29 | 30 | def __init__(self, debugger, unused): 31 | pass 32 | 33 | def __call__( 34 | self, 35 | debugger: SBDebugger, 36 | command, 37 | exe_ctx: SBExecutionContext, 38 | result: SBCommandReturnObject, 39 | ): 40 | global __KONAN_VARIABLE, __KONAN_VARIABLE_TYPE, __TYPES_KONAN_TO_C 41 | target = debugger.GetSelectedTarget() 42 | process = target.GetProcess() 43 | thread = process.GetSelectedThread() 44 | frame = thread.GetSelectedFrame() 45 | 46 | konan_variable_symbols = list(filter(lambda v: __KONAN_VARIABLE.match(v.name), frame.GetModule().symbols)) 47 | visited = list() 48 | for symbol in konan_variable_symbols: 49 | name = __KONAN_VARIABLE.search(symbol.name).group(1) 50 | 51 | if name in visited: 52 | continue 53 | visited.append(name) 54 | 55 | getters = list( 56 | filter(lambda v: re.match('^kfun:\\(\\).*$'.format(name), v.name), frame.module.symbols)) 57 | if not getters: 58 | result.AppendMessage("storage not found for name:{}".format(name)) 59 | continue 60 | 61 | getter_functions = frame.module.FindFunctions(getters[0].name) 62 | if not getter_functions: 63 | continue 64 | 65 | address = getter_functions[0].function.GetStartAddress().GetLoadAddress(target) 66 | type = __KONAN_VARIABLE_TYPE.search(getters[0].name).group(2) 67 | (c_type, extractor) = __TYPES_KONAN_TO_C[type] if type in __TYPES_KONAN_TO_C.keys() else ('ObjHeader *', lambda v: kotlin_object_type_summary(v)) 68 | value = evaluate('(({0} (*)()){1:#x})()', c_type, address) 69 | str_value = extractor(value) 70 | result.AppendMessage('{} {}: {}'.format(type, name, str_value)) 71 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/util/File.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.util 2 | 3 | import co.touchlab.xcode.cli.LLDBInitManager 4 | import kotlinx.cinterop.* 5 | import platform.Foundation.NSData 6 | import platform.Foundation.NSDataWritingAtomic 7 | import platform.Foundation.NSError 8 | import platform.Foundation.NSFileManager 9 | import platform.Foundation.NSString 10 | import platform.Foundation.NSUTF8StringEncoding 11 | import platform.Foundation.create 12 | import platform.Foundation.writeToFile 13 | 14 | @OptIn(ExperimentalForeignApi::class) 15 | class File(private val providedPath: Path, private val resolveSymlinks: Boolean = true) { 16 | val path: Path 17 | get() = if (resolveSymlinks) { 18 | providedPath.resolvingSymlinksInPath() 19 | } else { 20 | providedPath 21 | } 22 | 23 | fun dataContents(): NSData = throwingIOException { errorPointer -> 24 | NSData.create(contentsOfFile = path.value, options = 0u, error = errorPointer.ptr) 25 | } ?: error("Couldn't load data contents of file $path. This shouldn't have been thrown, because we should receive a NSError!") 26 | 27 | fun stringContents(): NSString = throwingIOException { errorPointer -> 28 | NSString.create(contentsOfFile = path.value, encoding = NSUTF8StringEncoding, error = errorPointer.ptr) 29 | } ?: error("Couldn't load UTF8 content of file $path. This shouldn't have been thrown, because we should receive a NSError!") 30 | 31 | fun exists(): Boolean = NSFileManager.defaultManager.fileExistsAtPath(path.value) 32 | 33 | fun write(data: NSData): Boolean = throwingIOException { errorPointer -> 34 | data.writeToFile(path.value, options = NSDataWritingAtomic, error = errorPointer.ptr) 35 | } 36 | 37 | fun write(string: NSString): Boolean = throwingIOException { errorPointer -> 38 | string.writeToFile(path.value, true, NSUTF8StringEncoding, errorPointer.ptr) 39 | } 40 | 41 | fun copy(destination: Path): Boolean = throwingIOException { errorPointer -> 42 | NSFileManager.defaultManager.copyItemAtPath(path.value, destination.value, errorPointer.ptr) 43 | } 44 | 45 | fun mkdirs(): Boolean = throwingIOException { errorPointer -> 46 | NSFileManager.defaultManager.createDirectoryAtPath(path.value, true, null, errorPointer.ptr) 47 | } 48 | 49 | fun delete(): Boolean { 50 | if (!exists()) { 51 | return false 52 | } 53 | return throwingIOException { errorPointer -> 54 | NSFileManager.defaultManager.removeItemAtPath(path.value, errorPointer.ptr) 55 | } 56 | } 57 | 58 | override fun toString(): String { 59 | return "File($path)" 60 | } 61 | 62 | private inline fun throwingIOException(crossinline block: (ObjCObjectVar) -> T): T { 63 | return memScoped { 64 | val errorPointer: ObjCObjectVar = alloc() 65 | val result = block(errorPointer) 66 | val error = errorPointer.value 67 | if (error != null) { 68 | throw IOException(error) 69 | } 70 | result 71 | } 72 | } 73 | 74 | class IOException(nsError: NSError): Exception(nsError.description) 75 | } 76 | -------------------------------------------------------------------------------- /LLDBPlugin/test_project/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/types/KonanMapSyntheticProvider.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | import lldb 4 | 5 | from .KonanArraySyntheticProvider import KonanArraySyntheticProvider 6 | from .KonanObjectSyntheticProvider import KonanObjectSyntheticProvider 7 | from .base import get_type_info 8 | from ..util import DebuggerException 9 | from ..util.expression import EXPRESSION_OPTIONS 10 | 11 | 12 | class KonanMapSyntheticProvider(KonanObjectSyntheticProvider): 13 | def __init__(self, valobj: lldb.SBValue, type_info: lldb.value): 14 | self._keys: KonanArraySyntheticProvider = None # type: ignore 15 | self._values: KonanArraySyntheticProvider = None # type: ignore 16 | 17 | super().__init__(valobj, type_info) 18 | 19 | def update(self): 20 | super().update() 21 | 22 | if self._keys is None or self._values is None: 23 | keys: Optional[KonanArraySyntheticProvider] = None 24 | values: Optional[KonanArraySyntheticProvider] = None 25 | 26 | for index, name in enumerate(self._children_names): 27 | if name == 'keysArray': 28 | keys = self._create_backing(index, name) 29 | elif name == 'valuesArray': 30 | values = self._create_backing(index, name) 31 | 32 | if keys is None or values is None: 33 | raise DebuggerException( 34 | "Couldn't find backing for map {:#x}, name: {}".format(self._valobj.unsigned, self._valobj.name) 35 | ) 36 | else: 37 | self._keys = keys 38 | self._values = values 39 | 40 | self._keys.update() 41 | self._values.update() 42 | 43 | return False 44 | 45 | def num_children(self): 46 | return self._keys.num_children() 47 | 48 | def has_children(self): 49 | return True 50 | 51 | def get_child_index(self, name): 52 | # TODO: Not correct, we need to look at the values which this doesn't do 53 | return self._keys.get_child_index(name) 54 | 55 | def get_child_at_index(self, index): 56 | lldb.debugger.GetSelectedTarget().GetProcess() 57 | return self._valobj.CreateValueFromExpression( 58 | f'[{index}]', 59 | '(MapEntry){{ (ObjHeader*){:#x}, (ObjHeader*){:#x} }};'.format( 60 | self._keys.get_child_at_index(index).unsigned, 61 | self._values.get_child_at_index(index).unsigned, 62 | ), 63 | EXPRESSION_OPTIONS, 64 | ) 65 | 66 | def to_string(self): 67 | children_count = self._keys.num_children() 68 | if children_count == 1: 69 | return '1 key/value pair' 70 | else: 71 | return '{} key/value pairs'.format(children_count) 72 | 73 | def _create_backing(self, index: int, name: str) -> Optional[KonanArraySyntheticProvider]: 74 | address = self.get_child_address_at_index(index) 75 | backing_value = self._valobj.CreateValueFromAddress( 76 | name, 77 | address, 78 | self._valobj.type, 79 | ) 80 | child_type_info = get_type_info(backing_value) 81 | if child_type_info is None: 82 | return None 83 | else: 84 | return KonanArraySyntheticProvider(backing_value, child_type_info) 85 | -------------------------------------------------------------------------------- /data/Kotlin.ideplugin/Contents/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleInfoDictionaryVersion 6 | 6.0 7 | CFBundleIdentifier 8 | org.kotlinlang.xcode.kotlin 9 | CFBundleName 10 | Kotlin Xcode Plug-in 11 | CFBundleShortVersionString 12 | @version@ 13 | CFBundleVersion 14 | @version@ 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleSignature 18 | ???? 19 | CFBundleDevelopmentRegion 20 | English 21 | CFBundleSupportedPlatforms 22 | 23 | MacOSX 24 | 25 | DVTPlugInCompatibilityUUIDs 26 | 27 | 426A087B-D3AA-431A-AFDF-F135EC00DE1C 28 | 8B9F56A7-4D8B-41AA-A65D-D4906CDF1539 29 | 8A66E736-A720-4B3C-92F1-33D9962C69DF 30 | 65C57D32-1E9B-44B8-8C04-A27BA7AAE2C4 31 | DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 32 | E0A62D1F-3C18-4D74-BFE5-A4167D643966 33 | DFFB3951-EB0A-4C09-9DAC-5F2D28CC839C 34 | CA351AD8-3176-41CB-875C-42A05C7CDEC7 35 | DF11C142-1584-4A99-87AC-1925D5F5652A 36 | 89CB8A86-8683-4928-AF66-11A6CE26A829 37 | C3998872-68CC-42C2-847C-B44D96AB2691 38 | B395D63E-9166-4CD6-9287-6889D507AD6A 39 | 26355AE5-C605-4A56-A79B-AD4207EA18DD 40 | D7881182-AD00-4C36-A94D-F45FC9B0CF85 41 | 72F7D751-F810-43B8-A53F-1F1DFD74FC54 42 | 43 | B89EAABF-783E-4EBF-80D4-A9EAC69F77F2 44 | 07BAA045-2DD3-489F-B232-D1D4F8B92D2D 45 | 46 | 2FD51EF8-522D-4532-9698-980C4C497FD1 47 | 48 | 92CB09D8-3B74-4EF7-849C-99816039F0E7 49 | 50 | A74FBA51-FFEA-4409-B976-6FC3225A6F64 51 | 52 | BAB79788-ACEE-4291-826B-EC4667A6BEC5 53 | 54 | C80A9C11-3902-4885-944E-A035869BA910 55 | 56 | 6C8909A0-F208-4C21-9224-504F9A70056E 57 | 58 | DF12405B-55B4-4E00-8029-6AEFA7DBAD0F 59 | 60 | 3928AC50-EA32-404F-9CAF-49710A35483C 61 | 62 | 2F1A5FFF-BFEB-4498-B2AC-1296A7454F81 63 | 64 | F56A1938-53DE-493D-9D64-87EE6C415E4D 65 | 66 | 8BAA96B4-5225-471B-B124-D32A349B8106 67 | 68 | 7A3A18B7-4C08-46F0-A96A-AB686D315DF0 69 | 70 | 18B7-4C08-46F0-A96A-AB686D315DF0 71 | 72 | BD431FF2-C78B-4953-A3A9-0E42593C2D32 73 | 74 | XCPluginHasUI 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/LLDBInitManager.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli 2 | 3 | import co.touchlab.xcode.cli.util.Console 4 | import co.touchlab.xcode.cli.util.File 5 | import co.touchlab.xcode.cli.util.Path 6 | import co.touchlab.xcode.cli.util.kt 7 | import co.touchlab.xcode.cli.util.objc 8 | import platform.Foundation.containsString 9 | import platform.Foundation.stringByReplacingOccurrencesOfString 10 | 11 | object LLDBInitManager { 12 | private val pluginInitFile = File(PluginManager.pluginTargetFile.path / "Contents" / "Resources" / "lldbinit") 13 | private val sourcePluginInit = "command source ${pluginInitFile.path}" 14 | private val sourceMainLlvmInit = "command source ~/.lldbinit" 15 | private val lldbInitFile = File(Path.home / ".lldbinit") 16 | private val lldbInitXcodeFile = File(Path.home / ".lldbinit-Xcode") 17 | 18 | val isInstalled: Boolean 19 | get() { 20 | if (!lldbInitXcodeFile.exists()) { 21 | return false 22 | } 23 | return lldbInitXcodeFile.stringContents().containsString(sourcePluginInit) 24 | } 25 | 26 | val sourcesMainLlvmInit: Boolean 27 | get() { 28 | if (!lldbInitXcodeFile.exists()) { 29 | return true 30 | } 31 | return lldbInitXcodeFile.stringContents().containsString(sourceMainLlvmInit) 32 | } 33 | 34 | fun install() { 35 | check(!isInstalled) { "LLDB init is already installed" } 36 | 37 | val oldContents = when { 38 | lldbInitXcodeFile.exists() -> { 39 | Console.muted("${lldbInitXcodeFile.path} exists, will append LLDB init into it.") 40 | lldbInitXcodeFile.stringContents().kt 41 | } 42 | lldbInitFile.exists() -> { 43 | Console.echo(""" 44 | This installer will create a new file at '~/.lldbinit-Xcode'. This file takes precedence over the '~/.lldbinit' file. 45 | To keep using configuration from '~/.lldbinit' file, it needs to be sourced by the newly created '~/.lldbinit-Xcode' file. 46 | """.trimIndent()) 47 | if (Console.confirm("Do you want to source the '~/.lldbinit' file?")) { 48 | Console.muted("Will source ~/.lldbinit.") 49 | sourceMainLlvmInit 50 | } else { 51 | "" 52 | } 53 | } 54 | else -> { 55 | "" 56 | } 57 | } 58 | 59 | val oldAndNewContentsSeparator = if (!oldContents.endsWith("\n")) "\n" else "" 60 | val newContents = oldContents + oldAndNewContentsSeparator + sourcePluginInit 61 | Console.muted("Saving new LLDB init to ${lldbInitXcodeFile.path}.") 62 | lldbInitXcodeFile.write(newContents.objc) 63 | } 64 | 65 | fun uninstall() { 66 | if (isInstalled) { 67 | Console.muted("LLDB init script found, removing.") 68 | val oldContents = lldbInitXcodeFile.stringContents() 69 | val newContents = oldContents.stringByReplacingOccurrencesOfString(target = sourcePluginInit, withString = "") 70 | lldbInitXcodeFile.write(newContents.objc) 71 | } 72 | Legacy.uninstall() 73 | } 74 | 75 | object Legacy { 76 | private val legacyImport = """ 77 | command script import ~/Library/Developer/Xcode/Plug-ins/Kotlin.ideplugin/Contents/Resources/konan_lldb_config.py 78 | command script import ~/Library/Developer/Xcode/Plug-ins/Kotlin.ideplugin/Contents/Resources/konan_lldb.py 79 | """.trimIndent() 80 | 81 | val isInstalled: Boolean 82 | get() { 83 | if (!lldbInitXcodeFile.exists()) { 84 | return false 85 | } 86 | return lldbInitXcodeFile.stringContents().containsString(legacyImport) 87 | } 88 | 89 | fun uninstall() { 90 | if (isInstalled) { 91 | Console.muted("Legacy LLDB script initialization found, removing.") 92 | val oldContents = lldbInitXcodeFile.stringContents() 93 | val newContents = oldContents.stringByReplacingOccurrencesOfString(target = legacyImport, withString = "") 94 | lldbInitXcodeFile.write(newContents.objc) 95 | } 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /data/Kotlin.ideplugin/Contents/Resources/Kotlin.xcplugindata: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | plug-in 6 | 7 | extensions 8 | 9 | Xcode.FileDataType.Kotlin 10 | 11 | id 12 | Xcode.FileDataType.Kotlin 13 | localizedDescription 14 | Kotlin Document 15 | name 16 | File type for Kotlin 17 | point 18 | Xcode.FileDataType 19 | typeConformedTo 20 | 21 | 22 | typeIdentifier 23 | public.source-code 24 | 25 | 26 | typeIdentifier 27 | public.kotlin-source 28 | version 29 | 1.0 30 | 31 | Xcode.FileDataTypeDetector.Kotlin 32 | 33 | detectedTypeIdentifier 34 | public.kotlin-source 35 | id 36 | Xcode.FileDataTypeDetector.Kotlin 37 | matchesExtension 38 | kt 39 | point 40 | Xcode.FileDataTypeDetector 41 | 42 | Xcode.SourceCodeLanguage.Kotlin 43 | 44 | commentSyntax 45 | 46 | 47 | prefix 48 | // 49 | 50 | 51 | conformsTo 52 | 53 | 54 | identifier 55 | Xcode.SourceCodeLanguage.Generic 56 | 57 | 58 | fileDataType 59 | 60 | 61 | identifier 62 | public.kotlin-source 63 | 64 | 65 | id 66 | Xcode.SourceCodeLanguage.Kotlin 67 | languageName 68 | Kotlin 69 | languageSpecification 70 | xcode.lang.kotlin 71 | name 72 | Kotlin Language 73 | point 74 | Xcode.SourceCodeLanguage 75 | version 76 | 1.0 77 | 78 | Xcode.IDEKit.Inspector.FileIdentityAndType.public.kotlin-source 79 | 80 | fileDataType 81 | public.kotlin-source 82 | group 83 | Xcode.IDEKit.Inspector.FileInspectorTypeGroup.Sourcecode.Various 84 | id 85 | Xcode.IDEKit.Inspector.FileIdentityAndType.public.kotlin-source 86 | name 87 | File Inspector Entry - Kotlin Document 88 | point 89 | Xcode.IDEKit.FileInspectorTypeGroupEntry 90 | version 91 | 0.1 92 | 93 | 94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /BUILDING.md: -------------------------------------------------------------------------------- 1 | # Building 2 | 3 | The xcode-kotlin plugin is written in **Kotlin**. It uses 4 | [Kotlin/Native](https://kotlinlang.org/docs/native-overview.html) for compiling Kotlin code to native binaries. 5 | 6 | Building environment: **IntelliJ IDEA** 7 | 8 | ## Build Local Development Version 9 | 10 | As this is a tool for Xcode, you'll need to run the build on a mac machine. We'll assume your machine is an ARM, Mx 11 | chip and not Intel. Replace the calls with X64 versions if needed. 12 | 13 | To build, open a terminal in the root project folder and run: 14 | 15 | ```shell 16 | ./gradlew preparePlugin linkDebugExecutableMacosArm64 17 | ``` 18 | 19 | To test the local build, run the following: 20 | 21 | ```shell 22 | ./build/bin/macosArm64/debugExecutable/xcode-kotlin.kexe [command] 23 | ``` 24 | 25 | ## Libraries 26 | 27 | - [kotlinx-cli](org.jetbrains.kotlinx:kotlinx-cli) - a generic command-line parser used to create user-friendly and flexible command-line interfaces 28 | - [kotlinx-serialization-json](https://kotlinlang.org/docs/serialization.html) - JSON serialization for Kotlin projects 29 | - [kotlinx-coroutines](https://github.com/Kotlin/kotlinx.coroutines) - library support for Kotlin coroutines with multiplatform support 30 | - [Kermit](https://github.com/touchlab/Kermit) - logging utility with composable log outputs 31 | 32 | ## Project structure 33 | 34 | In the `command` directory the commands users can call are implemented: *info*, *install*, *sync* and *uninstall*. 35 | Each has an `execute` function with the implementation, that calls classes like `Installer` or `Uninstaller`. 36 | - `BaseXcodeListSubcommand` is an abstract class overriden by the following classes (Info, Install and Sync). It 37 | provides them with a protected method for getting a list of Xcode installations. 38 | - `Info` checks for an available update or if the plugin is not yet installed, writes information about the plugin to 39 | the console, such as installed and bundles versions, if Language spec and LLDB is installed and if LLDB for Xcode has 40 | been initialized, also Xcode version and the plugin compatibility. 41 | - `Install` checks for current version and offers updating, reinstalling or downgrading if it is already installed or 42 | installs it if not. 43 | - `Sync` adds IDs of Xcode installations to the currently installed Xcode Kotlin plugin. 44 | - `Uninstall` uninstalls the plugin. 45 | 46 | In the `util` directory are, as the name suggests, util classes. 47 | - `Console` provides convenience functions for prompting user for confirmation or value and printing output to the 48 | console. 49 | - `CrashHelper` provides functions for logging, capturing and uploading errors (crash reports). 50 | - `File` is a class for holding a file path and providing methods for working with a file. 51 | - `Path` holds a string value and provides methods for appending and deleting path components and resolving sym links. 52 | It also provides convenience methods for creating Paths to home, work, binary and data directories in its companion 53 | object. 54 | - `PropertyList` is a class for converting to and from Swift classes. 55 | - `Shell` is a helper for executing shell tasks. 56 | 57 | The other classes in the `cli` directory are mainly managers and helpers that provide methods for installing and 58 | uninstalling various parts of the plugin. 59 | - `Installer` has an `installAll` method for calling install on all the managers. 60 | - `LangSpecManager` provides `install` and `uninstall` methods and `isInstalled` check for the Kotlin.xclangspec. 61 | - `LLDBInitManager` provides `install` and `uninstall` methods and `isInstalled` and `sourcesMainLlvmInit` checks for 62 | the LLDB init. 63 | - `PluginManager` provides `install`, `sync` and `uninstall` methods,`isInstalled` check and `bundledVersion`, 64 | `installedVersion` and `targetSupportedXcodeUUIds` properties for the plugin. 65 | - `Uninstaller` has an `uninstallAll` method for calling uninstall on all the managers. 66 | - `XcodeHelper` provides methods for interacting with Xcode installations: `ensureXcodeNotRunning` to check and 67 | optionally shut down running Xcode instances, `allXcodeInstallations` that returns a list of found Xcode installations, 68 | `addKotlinPluginToDefaults` for adding a plugin to allowed list in Xcode defaults and `removeKotlinPluginFromDefaults` 69 | for removing it. 70 | 71 | In `build.gradle` there are two gradle tasks added: `assembleReleaseExecutableMacos` for building a universal macOS 72 | binary and `preparePlugin` for preparing the plugin and language specification to build dir. 73 | 74 | This project uses Object classes instead of dependency injection (DI) because of its small size. -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/commands/GCCollectCommand.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from lldb import SBDebugger, SBExecutionContext, SBCommandReturnObject, SBTarget, SBSymbol, SBInstructionList 4 | from touchlab_kotlin_lldb.util import evaluate, DebuggerException 5 | 6 | import re 7 | 8 | 9 | class GCCollectCommand: 10 | program = 'force_gc' 11 | 12 | def __init__(self, debugger, unused): 13 | pass 14 | 15 | def __call__(self, debugger: SBDebugger, command, exe_ctx: SBExecutionContext, result: SBCommandReturnObject): 16 | try: 17 | target = debugger.GetSelectedTarget() 18 | schedule_gc_function = self._find_single_function_symbol('kotlin::gcScheduler::GCScheduler::scheduleAndWaitFinalized()', target, result) 19 | deinit_memory_function = self._find_single_function_symbol('DeinitMemory', target, result) 20 | global_data_symbol = self._find_single_symbol("(anonymous namespace)::globalDataInstance", target, result) 21 | 22 | gc_scheduler_offset = self._find_gc_scheduler_offset(deinit_memory_function, schedule_gc_function, target) 23 | 24 | schedule_gc_function_addr = schedule_gc_function.addr.GetLoadAddress(target) 25 | global_data_addr = global_data_symbol.addr.GetLoadAddress(target) 26 | gc_scheduler_addr = global_data_addr + gc_scheduler_offset 27 | 28 | evaluate( 29 | '((void (*)(void*)){:#x})((void*){:#x})', 30 | schedule_gc_function_addr, 31 | gc_scheduler_addr 32 | ) 33 | evaluate( 34 | '((void (*)(void*)){:#x})((void*){:#x})', 35 | schedule_gc_function_addr, 36 | gc_scheduler_addr 37 | ) 38 | 39 | except DebuggerException as e: 40 | result.SetError("{} Please report this to the xcode-kotlin GitHub.".format(e.msg)) 41 | return 42 | 43 | 44 | @staticmethod 45 | def _find_single_function_symbol(symbol_name: str, target: SBTarget, result: SBCommandReturnObject) -> SBSymbol: 46 | functions = target.FindFunctions(symbol_name) 47 | if functions.GetSize() >= 1: 48 | if not functions.GetSize() == 1: 49 | result.AppendWarning("Multiple ({}) symbols found for function {}".format(functions.GetSize(), symbol_name)) 50 | return functions[0].GetSymbol() 51 | else: 52 | raise DebuggerException("Could not find symbol for function {}.".format(symbol_name)) 53 | 54 | @staticmethod 55 | def _find_single_symbol(symbol_name: str, target: SBTarget, result: SBCommandReturnObject) -> SBSymbol: 56 | symbols = target.FindSymbols(symbol_name) 57 | if symbols.GetSize() >= 1: 58 | if not symbols.GetSize() == 1: 59 | result.AppendWarning( 60 | "Multiple ({}) symbols found for function {}".format(symbols.GetSize(), symbol_name)) 61 | return symbols[0].GetSymbol() 62 | else: 63 | raise DebuggerException("Could not find symbol for function {}.".format(symbol_name)) 64 | 65 | @staticmethod 66 | def _find_gc_scheduler_offset(deinit_memory: SBSymbol, schedule_gc: SBSymbol, target: SBTarget) -> int: 67 | instructions = deinit_memory.GetInstructions(target) 68 | load_addr = "{:#x}".format(schedule_gc.addr.GetLoadAddress(target)) 69 | 70 | previous_branch_instruction_index: int = 0 71 | schedule_gc_branch_instruction_index: Optional[int] = None 72 | for i in range(len(instructions)): 73 | instruction = instructions[i] 74 | if instruction.DoesBranch(): 75 | if instruction.GetOperands(target) == load_addr: 76 | schedule_gc_branch_instruction_index = i 77 | break 78 | else: 79 | previous_branch_instruction_index = i 80 | 81 | if not schedule_gc_branch_instruction_index: 82 | raise DebuggerException( 83 | "Could not find a branch instruction to {} inside {}.".format( 84 | schedule_gc.GetDisplayName(), deinit_memory.GetDisplayName())) 85 | 86 | match_pattern = "\\(anonymous namespace\\)::globalDataInstance\\s+\\+\\s+(\\d+)" 87 | gc_scheduler_offset: Optional[int] = None 88 | for i in range(previous_branch_instruction_index, schedule_gc_branch_instruction_index): 89 | instruction = instructions[i] 90 | match = re.search(match_pattern, instruction.GetComment(target)) 91 | if match: 92 | gc_scheduler_offset = int(match.group(1)) 93 | break 94 | 95 | if not gc_scheduler_offset: 96 | raise DebuggerException("Could not find gc_scheduler offset for globalDataInstance.") 97 | 98 | return gc_scheduler_offset -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/InstallationFacade.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli 2 | 3 | import co.touchlab.xcode.cli.util.Console 4 | 5 | object InstallationFacade { 6 | suspend fun installAll(xcodeInstallations: List, fixXcode15: Boolean) { 7 | XcodeHelper.ensureXcodeNotRunning() 8 | 9 | val bundledVersion = PluginManager.bundledVersion 10 | Console.muted("Bundled plugin version = $bundledVersion") 11 | val installedVersion = PluginManager.installedVersion 12 | Console.muted("Installed plugin version = ${installedVersion ?: "N/A"}") 13 | 14 | if (installedVersion != null) { 15 | val (confirmation, notification) = when { 16 | bundledVersion > installedVersion -> { 17 | "Do you want to update from $installedVersion to $bundledVersion?" to "Updating to $bundledVersion" 18 | } 19 | bundledVersion == installedVersion -> { 20 | "Do you want to reinstall version $installedVersion?" to "Reinstalling $installedVersion" 21 | } 22 | bundledVersion < installedVersion -> { 23 | "Do you want to downgrade from $installedVersion to $bundledVersion?" to "Downgrading to $bundledVersion" 24 | } 25 | else -> error("Unhandled comparison possibility!") 26 | } 27 | 28 | if (!Console.confirm(confirmation)) { 29 | return 30 | } 31 | 32 | Console.muted("Installation confirmed.") 33 | Console.info(notification) 34 | uninstallAll() 35 | } else { 36 | Console.info("Installing $bundledVersion.") 37 | } 38 | 39 | PluginManager.install() 40 | PluginManager.disable(bundledVersion, xcodeInstallations) 41 | if (fixXcode15) { 42 | PluginManager.fixXcode15(xcodeInstallations) 43 | } 44 | PluginManager.sync(xcodeInstallations) 45 | LangSpecManager.install() 46 | LLDBInitManager.install() 47 | PluginManager.enable(bundledVersion, xcodeInstallations) 48 | 49 | Console.info("Installation complete.") 50 | } 51 | 52 | suspend fun enable(xcodeInstallations: List) { 53 | XcodeHelper.ensureXcodeNotRunning() 54 | 55 | val installedVersion = PluginManager.installedVersion ?: run { 56 | Console.warning("Plugin not installed, nothing to enable.") 57 | return 58 | } 59 | 60 | PluginManager.enable(installedVersion, xcodeInstallations) 61 | 62 | Console.info("Plugin enabled.") 63 | } 64 | 65 | suspend fun disable(xcodeInstallations: List) { 66 | XcodeHelper.ensureXcodeNotRunning() 67 | 68 | val installedVersion = PluginManager.installedVersion ?: run { 69 | Console.warning("Plugin not installed, nothing to disable.") 70 | return 71 | } 72 | 73 | PluginManager.disable(installedVersion, xcodeInstallations) 74 | 75 | Console.info("Plugin disabled.") 76 | } 77 | 78 | suspend fun fixXcode15(xcodeInstallations: List) { 79 | XcodeHelper.ensureXcodeNotRunning() 80 | 81 | val installedVersion = PluginManager.installedVersion 82 | try { 83 | if (installedVersion != null) { 84 | PluginManager.disable(installedVersion, xcodeInstallations) 85 | } 86 | 87 | PluginManager.fixXcode15(xcodeInstallations) 88 | } finally { 89 | if (installedVersion != null) { 90 | PluginManager.enable(installedVersion, xcodeInstallations) 91 | } 92 | } 93 | 94 | Console.info("Xcode 15 fix applied.") 95 | } 96 | 97 | suspend fun sync(xcodeInstallations: List, fixXcode15: Boolean) { 98 | XcodeHelper.ensureXcodeNotRunning() 99 | 100 | val installedVersion = PluginManager.installedVersion ?: run { 101 | Console.warning("Plugin not installed, nothing to synchronize.") 102 | return 103 | } 104 | 105 | PluginManager.disable(installedVersion, xcodeInstallations) 106 | PluginManager.sync(xcodeInstallations) 107 | if (fixXcode15) { 108 | PluginManager.fixXcode15(xcodeInstallations) 109 | } 110 | PluginManager.enable(installedVersion, xcodeInstallations) 111 | 112 | Console.info("Synchronization complete.") 113 | } 114 | 115 | suspend fun uninstallAll() { 116 | Console.muted("Will uninstall all plugin components.") 117 | XcodeHelper.ensureXcodeNotRunning() 118 | PluginManager.uninstall() 119 | LangSpecManager.uninstall() 120 | LLDBInitManager.uninstall() 121 | 122 | Console.info("Uninstallation complete.") 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | from typing import Optional 3 | 4 | import lldb 5 | 6 | from .stepping.KonanHook import KonanHook 7 | from .types.base import KOTLIN_CATEGORY, KOTLIN_OBJ_HEADER_TYPE, KOTLIN_ARRAY_HEADER_TYPE 8 | from .util.log import log 9 | from .commands import FieldTypeCommand, SymbolByNameCommand, TypeByAddressCommand, GCCollectCommand 10 | 11 | from .types.summary import kotlin_object_type_summary, kotlin_objc_class_summary 12 | from .types.proxy import KonanProxyTypeProvider, KonanObjcProxyTypeProvider 13 | 14 | from .cache import LLDBCache 15 | 16 | os.environ['CLIENT_TYPE'] = 'Xcode' 17 | 18 | KONAN_INIT_PREFIX = '_Konan_init_' 19 | KONAN_INIT_MODULE_NAME = '[0-9a-zA-Z_]+' 20 | KONAN_INIT_SUFFIX = '_kexe' 21 | 22 | def __lldb_init_module(debugger: lldb.SBDebugger, _): 23 | log(lambda: "init start") 24 | 25 | reset_cache() 26 | configure_types(debugger) 27 | register_commands(debugger) 28 | register_hooks(debugger) 29 | 30 | configure_objc_types_init(debugger) 31 | 32 | log(lambda: "init end") 33 | 34 | 35 | def reset_cache(): 36 | """Xcode reuses LLDB between program runs, so we need to clear any symbol references we made as they are no 37 | longer valid.""" 38 | LLDBCache.reset() 39 | 40 | 41 | def configure_objc_types_init(debugger: lldb.SBDebugger): 42 | target = debugger.GetDummyTarget() 43 | breakpoint = target.BreakpointCreateByRegex( 44 | "^{}({})({})?$".format(KONAN_INIT_PREFIX, KONAN_INIT_MODULE_NAME, KONAN_INIT_SUFFIX) 45 | ) 46 | breakpoint.SetOneShot(True) 47 | breakpoint.SetAutoContinue(True) 48 | breakpoint.SetScriptCallbackFunction('{}.{}'.format(__name__, configure_objc_types_breakpoint.__name__)) 49 | 50 | 51 | def configure_objc_types_breakpoint(frame: lldb.SBFrame, bp_loc: lldb.SBBreakpointLocation, internal_dict): 52 | process = frame.thread.process 53 | target = process.target 54 | 55 | symbols = target.FindSymbols('_OBJC_CLASS_RO_$_KotlinBase') 56 | 57 | base_class_name: Optional[str] = None 58 | for symbol_context in symbols: 59 | error = lldb.SBError() 60 | name_addr = process.ReadPointerFromMemory(symbol_context.symbol.addr.GetLoadAddress(target) + 6 * 4, error) 61 | # TODO: Log error? 62 | if not error.success: 63 | continue 64 | base_class_name = process.ReadCStringFromMemory(name_addr, 128, error) 65 | # TODO: Log error? 66 | if not error.success: 67 | continue 68 | 69 | break 70 | 71 | module_name = frame.symbol.name.removeprefix(KONAN_INIT_PREFIX).removesuffix(KONAN_INIT_SUFFIX) 72 | if module_name == "stdlib": 73 | return False 74 | 75 | specifiers_to_register = [ 76 | lldb.SBTypeNameSpecifier( 77 | '^{}\\.'.format(module_name), 78 | lldb.eMatchTypeRegex, 79 | ), 80 | ] 81 | 82 | if base_class_name is not None: 83 | objc_class_prefix = base_class_name.removesuffix("Base") 84 | specifiers_to_register.append( 85 | lldb.SBTypeNameSpecifier( 86 | '^{}'.format(objc_class_prefix), 87 | lldb.eMatchTypeRegex, 88 | ) 89 | ) 90 | 91 | category = target.debugger.GetCategory(KOTLIN_CATEGORY) 92 | 93 | for type_specifier in specifiers_to_register: 94 | category.AddTypeSummary( 95 | type_specifier, 96 | lldb.SBTypeSummary.CreateWithFunctionName( 97 | '{}.{}'.format(__name__, kotlin_objc_class_summary.__name__), 98 | lldb.eTypeOptionHideValue, 99 | ) 100 | ) 101 | category.AddTypeSynthetic( 102 | type_specifier, 103 | lldb.SBTypeSynthetic.CreateWithClassName( 104 | '{}.{}'.format(__name__, KonanObjcProxyTypeProvider.__name__), 105 | ) 106 | ) 107 | 108 | bp_loc.GetBreakpoint().SetEnabled(False) 109 | 110 | return False 111 | 112 | 113 | def configure_types(debugger: lldb.SBDebugger): 114 | category = debugger.CreateCategory(KOTLIN_CATEGORY) 115 | 116 | types_to_register = [ 117 | KOTLIN_OBJ_HEADER_TYPE, 118 | KOTLIN_ARRAY_HEADER_TYPE, 119 | ] 120 | 121 | for type_to_register in types_to_register: 122 | category.AddTypeSummary( 123 | type_to_register, 124 | lldb.SBTypeSummary.CreateWithFunctionName( 125 | '{}.{}'.format(__name__, kotlin_object_type_summary.__name__), 126 | lldb.eTypeOptionHideValue 127 | ) 128 | ) 129 | category.AddTypeSynthetic( 130 | type_to_register, 131 | lldb.SBTypeSynthetic.CreateWithClassName( 132 | '{}.{}'.format(__name__, KonanProxyTypeProvider.__name__), 133 | ) 134 | ) 135 | 136 | category.SetEnabled(True) 137 | 138 | 139 | def register_commands(debugger: lldb.SBDebugger): 140 | commands_to_register = [ 141 | FieldTypeCommand, 142 | SymbolByNameCommand, 143 | TypeByAddressCommand, 144 | GCCollectCommand, 145 | ] 146 | 147 | for command in commands_to_register: 148 | debugger.HandleCommand( 149 | 'command script add -c {}.{} {}'.format(__name__, command.__name__, command.program) 150 | ) 151 | 152 | 153 | def register_hooks(debugger: lldb.SBDebugger): 154 | # Avoid Kotlin/Native runtime 155 | debugger.HandleCommand('settings set target.process.thread.step-avoid-regexp ^::Kotlin_') 156 | 157 | hooks_to_register = [ 158 | KonanHook, 159 | ] 160 | 161 | for hook in hooks_to_register: 162 | debugger.HandleCommand('target stop-hook add -P {}.{}'.format(__name__, hook.__name__)) 163 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/util/Shell.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.util 2 | 3 | import kotlinx.cinterop.ExperimentalForeignApi 4 | import kotlinx.cinterop.ObjCObjectVar 5 | import kotlinx.cinterop.alloc 6 | import kotlinx.cinterop.memScoped 7 | import kotlinx.cinterop.ptr 8 | import kotlinx.coroutines.suspendCancellableCoroutine 9 | import platform.Foundation.NSData 10 | import platform.Foundation.NSError 11 | import platform.Foundation.NSMutableData 12 | import platform.Foundation.NSPipe 13 | import platform.Foundation.NSString 14 | import platform.Foundation.NSTask 15 | import platform.Foundation.NSTaskTerminationReason 16 | import platform.Foundation.NSUTF8StringEncoding 17 | import platform.Foundation.appendData 18 | import platform.Foundation.closeFile 19 | import platform.Foundation.create 20 | import platform.Foundation.launchPath 21 | import platform.Foundation.readabilityHandler 22 | import platform.Foundation.waitUntilExit 23 | import platform.Foundation.writeData 24 | import platform.Foundation.writeabilityHandler 25 | import platform.posix.EXIT_SUCCESS 26 | import kotlin.coroutines.resume 27 | 28 | object Shell { 29 | suspend fun exec(launchPath: String, vararg arguments: String, input: NSData? = null): ExecutionResult { 30 | return exec(launchPath, arguments.toList(), input) 31 | } 32 | 33 | suspend fun exec(launchPath: String, arguments: List, input: NSData? = null): ExecutionResult { 34 | return exec(Task(launchPath, arguments, input)) 35 | } 36 | 37 | @OptIn(ExperimentalForeignApi::class) 38 | suspend fun exec(task: Task): ExecutionResult { 39 | val nsTask = NSTask() 40 | nsTask.launchPath = task.launchPath 41 | nsTask.arguments = task.arguments 42 | 43 | val inputFile = if (task.input != null) { 44 | val inputPipe = NSPipe() 45 | val inputFile = inputPipe.fileHandleForWriting 46 | nsTask.standardInput = inputPipe 47 | inputFile.writeabilityHandler = { 48 | inputFile.writeData(task.input) 49 | inputFile.closeFile() 50 | inputFile.writeabilityHandler = null 51 | } 52 | inputFile 53 | } else { 54 | null 55 | } 56 | 57 | val taskOutput = NSMutableData() 58 | val outputPipe = NSPipe() 59 | val outputFile = outputPipe.fileHandleForReading 60 | nsTask.standardOutput = outputPipe 61 | outputFile.readabilityHandler = { 62 | taskOutput.appendData(outputFile.availableData) 63 | } 64 | 65 | val taskError = NSMutableData() 66 | val errorPipe = NSPipe() 67 | val errorFile = errorPipe.fileHandleForReading 68 | nsTask.standardError = errorPipe 69 | errorFile.readabilityHandler = { 70 | taskError.appendData(errorFile.availableData) 71 | } 72 | 73 | suspendCancellableCoroutine { continuation -> 74 | nsTask.terminationHandler = { 75 | inputFile?.writeabilityHandler = null 76 | outputFile.readabilityHandler = null 77 | errorFile.readabilityHandler = null 78 | continuation.resume(Unit) 79 | } 80 | 81 | memScoped { 82 | val error = alloc>() 83 | nsTask.launchAndReturnError(error.ptr) 84 | } 85 | 86 | continuation.invokeOnCancellation { 87 | nsTask.terminate() 88 | nsTask.waitUntilExit() 89 | } 90 | } 91 | 92 | val result = ExecutionResult( 93 | task = task, 94 | outputData = taskOutput, 95 | output = NSString.create(taskOutput, NSUTF8StringEncoding) as String?, 96 | errorData = taskError, 97 | error = NSString.create(taskError, NSUTF8StringEncoding) as String?, 98 | status = nsTask.terminationStatus, 99 | reason = nsTask.terminationReason, 100 | ) 101 | 102 | if (!result.error.isNullOrBlank()) { 103 | Console.warning("Task $nsTask had non-empty error output:\n\n${result.error}\n") 104 | } 105 | 106 | return result 107 | } 108 | 109 | class Task( 110 | val launchPath: String, 111 | val arguments: List, 112 | val input: NSData? 113 | ) { 114 | override fun toString(): String { 115 | return "$launchPath ${arguments.joinToString(" ")} (input: ${input?.length ?: 0} bytes)" 116 | } 117 | } 118 | 119 | class ExecutionResult( 120 | val task: Task, 121 | val outputData: NSData, 122 | val output: String?, 123 | val errorData: NSData, 124 | val error: String?, 125 | val status: Int, 126 | val reason: NSTaskTerminationReason, 127 | ) { 128 | val success: Boolean 129 | get() = status == EXIT_SUCCESS 130 | 131 | fun checkSuccessful(lazyMessage: () -> String): ExecutionResult { 132 | check(success) { 133 | """ 134 | |${lazyMessage}. Task $task exited with code $status (reason $reason). 135 | | 136 | |Standard input: 137 | ${task.input?.let { NSString.create(data = it, encoding = NSUTF8StringEncoding) }?.kt?.lines()?.joinToString("\n") { "|\t$it" } ?: ""} 138 | | 139 | |Standard output: 140 | ${output?.lines()?.joinToString("\n") { "|\t$it" } ?: ""} 141 | | 142 | |Standard error: 143 | ${error?.lines()?.joinToString("\n") { "|\t$it" } ?: ""} 144 | """.trimMargin() 145 | } 146 | return this 147 | } 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/util/konan_debug.h: -------------------------------------------------------------------------------- 1 | #ifndef KONAN_DEBUG_H 2 | #define KONAN_DEBUG_H 3 | 4 | // This is true for K/N runtime that supports ObjC, so for our case it should always be 1. 5 | #define KONAN_TYPE_INFO_HAS_WRITABLE_PART 1 6 | 7 | #if KONAN_TYPE_INFO_HAS_WRITABLE_PART 8 | struct WritableTypeInfo; 9 | #endif 10 | 11 | struct ObjHeader; 12 | struct TypeInfo; 13 | 14 | struct AssociatedObjectTableRecord { 15 | const TypeInfo* key; 16 | ObjHeader* (*getAssociatedObjectInstance)(ObjHeader**); 17 | }; 18 | 19 | // Type for runtime representation of Konan object. 20 | // Keep in sync with runtimeTypeMap in RTTIGenerator. 21 | enum Konan_RuntimeType { 22 | RT_INVALID = 0, 23 | RT_OBJECT = 1, 24 | RT_INT8 = 2, 25 | RT_INT16 = 3, 26 | RT_INT32 = 4, 27 | RT_INT64 = 5, 28 | RT_FLOAT32 = 6, 29 | RT_FLOAT64 = 7, 30 | RT_NATIVE_PTR = 8, 31 | RT_BOOLEAN = 9, 32 | RT_VECTOR128 = 10 33 | }; 34 | 35 | // Flags per type. 36 | // Keep in sync with constants in RTTIGenerator. 37 | enum Konan_TypeFlags { 38 | TF_IMMUTABLE = 1 << 0, 39 | TF_ACYCLIC = 1 << 1, 40 | TF_INTERFACE = 1 << 2, 41 | TF_OBJC_DYNAMIC = 1 << 3, 42 | TF_LEAK_DETECTOR_CANDIDATE = 1 << 4, 43 | TF_SUSPEND_FUNCTION = 1 << 5, 44 | TF_HAS_FINALIZER = 1 << 6, 45 | TF_HAS_FREEZE_HOOK = 1 << 7, 46 | TF_REFLECTION_SHOW_PKG_NAME = 1 << 8, // If package name is available in reflection, e.g. in `KClass.qualifiedName`. 47 | TF_REFLECTION_SHOW_REL_NAME = 1 << 9 // If relative name is available in reflection, e.g. in `KClass.simpleName`. 48 | }; 49 | 50 | // Flags per object instance. 51 | enum Konan_MetaFlags { 52 | // If freeze attempt happens on such an object - throw an exception. 53 | MF_NEVER_FROZEN = 1 << 0, 54 | }; 55 | 56 | 57 | typedef signed char int8_t; 58 | typedef unsigned char uint8_t; 59 | 60 | typedef short int16_t; 61 | 62 | typedef int int32_t; 63 | typedef unsigned int uint32_t; 64 | 65 | typedef long long int64_t; 66 | 67 | typedef unsigned long uintptr_t; 68 | 69 | // Extended information about a type. 70 | struct ExtendedTypeInfo { 71 | // Number of fields (negated Konan_RuntimeType for array types). 72 | int32_t fieldsCount_; 73 | // Offsets of all fields. 74 | const int32_t* fieldOffsets_; 75 | // Types of all fields. 76 | const uint8_t* fieldTypes_; 77 | // Names of all fields. 78 | const char** fieldNames_; 79 | // Number of supported debug operations. 80 | int32_t debugOperationsCount_; 81 | // Table of supported debug operations functions. 82 | void** debugOperations_; 83 | }; 84 | 85 | typedef void const* VTableElement; 86 | 87 | typedef int32_t ClassId; 88 | 89 | const ClassId kInvalidInterfaceId = 0; 90 | 91 | struct InterfaceTableRecord { 92 | ClassId id; 93 | uint32_t vtableSize; 94 | VTableElement const* vtable; 95 | }; 96 | 97 | // This struct represents runtime type information and by itself is the compile time 98 | // constant. 99 | // When adding a field here do not forget to adjust: 100 | // 1. RTTIGenerator 101 | // 2. ObjectTestSupport TypeInfoHolder 102 | // 3. createTypeInfo in ObjcExport.mm 103 | struct TypeInfo { 104 | // Reference to self, to allow simple obtaining TypeInfo via meta-object. 105 | const TypeInfo* typeInfo_; 106 | // Extended RTTI, to retain cross-version debuggability, since ABI version 5 shall always be at the second position. 107 | const ExtendedTypeInfo* extendedInfo_; 108 | // Unused field. 109 | uint32_t unused_; 110 | // Negative value marks array class/string, and it is negated element size. 111 | int32_t instanceSize_; 112 | // Must be pointer to Any for array classes, and null for Any. 113 | const TypeInfo* superType_; 114 | // All object reference fields inside this object. 115 | const int32_t* objOffsets_; 116 | // Count of object reference fields inside this object. 117 | // 1 for kotlin.Array to mark it as non-leaf. 118 | int32_t objOffsetsCount_; 119 | const TypeInfo* const* implementedInterfaces_; 120 | int32_t implementedInterfacesCount_; 121 | int32_t interfaceTableSize_; 122 | InterfaceTableRecord const* interfaceTable_; 123 | 124 | // String for the fully qualified dot-separated name of the package containing class. 125 | ObjHeader* packageName_; 126 | 127 | // String for the qualified class name relative to the containing package 128 | // (e.g. TopLevel.Nested1.Nested2) or the effective class name computed for 129 | // local class or anonymous object (e.g. listOf$1). 130 | ObjHeader* relativeName_; 131 | 132 | // Various flags. 133 | int32_t flags_; 134 | 135 | // Class id built with the whole class hierarchy taken into account. The details are in ClassLayoutBuilder. 136 | ClassId classId_; 137 | 138 | #if KONAN_TYPE_INFO_HAS_WRITABLE_PART 139 | WritableTypeInfo* writableInfo_; 140 | #endif 141 | 142 | // Null-terminated array. 143 | const AssociatedObjectTableRecord* associatedObjects; 144 | 145 | // Invoked on an object during mark phase. 146 | // TODO: Consider providing a generic traverse method instead. 147 | void (*processObjectInMark)(void*,ObjHeader*); 148 | 149 | // Required alignment of instance 150 | uint32_t instanceAlignment_; 151 | 152 | 153 | // vtable starts just after declared contents of the TypeInfo: 154 | // void* const vtable_[]; 155 | }; 156 | 157 | struct ObjHeader { 158 | TypeInfo* typeInfoOrMeta_; 159 | }; 160 | 161 | // Header of value type array objects. Keep layout in sync with that of object header. 162 | struct ArrayHeader { 163 | TypeInfo* typeInfoOrMeta_; 164 | 165 | // Elements count. Element size is stored in instanceSize_ field of TypeInfo, negated. 166 | uint32_t count_; 167 | }; 168 | 169 | typedef void __konan_safe_void_t; 170 | typedef int __konan_safe_int_t; 171 | typedef char __konan_safe_char_t; 172 | typedef bool __konan_safe_bool_t; 173 | typedef float __konan_safe_float_t; 174 | typedef double __konan_safe_double_t; 175 | 176 | typedef struct MapEntry { ObjHeader* key; ObjHeader* value; } MapEntry; 177 | 178 | int runtimeTypeSize[] = { 179 | -1, // INVALID 180 | sizeof(ObjHeader*), // OBJECT 181 | 1, // INT8 182 | 2, // INT16 183 | 4, // INT32 184 | 8, // INT64 185 | 4, // FLOAT32 186 | 8, // FLOAT64 187 | sizeof(void*), // NATIVE_PTR 188 | 1, // BOOLEAN 189 | 16 // VECTOR128 190 | }; 191 | 192 | int runtimeTypeAlignment[] = { 193 | -1, // INVALID 194 | alignof(ObjHeader*), // OBJECT 195 | alignof(int8_t), // INT8 196 | alignof(int16_t), // INT16 197 | alignof(int32_t), // INT32 198 | alignof(int64_t), // INT64 199 | alignof(float), // FLOAT32 200 | alignof(double), // FLOAT64 201 | alignof(void*), // NATIVE_PTR 202 | 1, // BOOLEAN 203 | 16 // VECTOR128 204 | }; 205 | 206 | class BackRefFromAssociatedObject { 207 | public: 208 | union { 209 | void* ref_; // Regular object. 210 | ObjHeader* permanentObj_; // Permanent object. 211 | }; 212 | }; 213 | 214 | #endif // KONAN_DEBUG_H 215 | -------------------------------------------------------------------------------- /LLDBPlugin/touchlab_kotlin_lldb/types/base.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | import lldb 4 | 5 | from ..util import strip_quotes, log, evaluate 6 | from ..cache import LLDBCache 7 | 8 | KOTLIN_OBJ_HEADER_TYPE = lldb.SBTypeNameSpecifier('ObjHeader', lldb.eMatchTypeNormal) 9 | KOTLIN_ARRAY_HEADER_TYPE = lldb.SBTypeNameSpecifier('ArrayHeader', lldb.eMatchTypeNormal) 10 | KOTLIN_CATEGORY = 'Kotlin' 11 | 12 | _TYPE_CONVERSION = [ 13 | # INVALID 14 | lambda obj, value, address, name: value.synthetic_child_from_address( 15 | name, address, lldb.debugger.GetSelectedTarget().GetBasicType(lldb.eBasicTypeVoid).GetPointerType() 16 | ), 17 | # OBJECT 18 | lambda obj, value, address, name: value.synthetic_child_from_address( 19 | name, address, obj_header_type() 20 | ), 21 | # INT8 22 | lambda obj, value, address, name: value.synthetic_child_from_address( 23 | name, address, lldb.debugger.GetSelectedTarget().GetBasicType(lldb.eBasicTypeChar) 24 | ), 25 | # INT16 26 | lambda obj, value, address, name: value.synthetic_child_from_address( 27 | name, address, lldb.debugger.GetSelectedTarget().GetBasicType(lldb.eBasicTypeShort) 28 | ), 29 | # INT32 30 | lambda obj, value, address, name: value.synthetic_child_from_address( 31 | name, address, lldb.debugger.GetSelectedTarget().GetBasicType(lldb.eBasicTypeInt) 32 | ), 33 | # INT64 34 | lambda obj, value, address, name: value.synthetic_child_from_address( 35 | name, address, lldb.debugger.GetSelectedTarget().GetBasicType(lldb.eBasicTypeLongLong) 36 | ), 37 | # FLOAT32 38 | lambda obj, value, address, name: value.synthetic_child_from_address( 39 | name, address, lldb.debugger.GetSelectedTarget().GetBasicType(lldb.eBasicTypeFloat) 40 | ), 41 | # FLOAT64 42 | lambda obj, value, address, name: value.synthetic_child_from_address( 43 | name, address, lldb.debugger.GetSelectedTarget().GetBasicType(lldb.eBasicTypeDouble) 44 | ), 45 | # NATIVE_PTR 46 | lambda obj, value, address, name: value.synthetic_child_from_address( 47 | name, address, lldb.debugger.GetSelectedTarget().GetBasicType(lldb.eBasicTypeVoid).GetPointerType() 48 | ), 49 | # BOOLEAN 50 | lambda obj, value, address, name: value.synthetic_child_from_address( 51 | name, address, lldb.debugger.GetSelectedTarget().GetBasicType(lldb.eBasicTypeBool) 52 | ), 53 | # TODO: VECTOR128 54 | lambda obj, value, address, name: None, 55 | ] 56 | 57 | 58 | def single_pointer(valobj: lldb.SBValue) -> lldb.SBValue: 59 | non_synthetic_value = valobj.GetNonSyntheticValue() 60 | 61 | # TODO: Test how this behaves when stopped in C++ 62 | # In case we've stopped in Swift, this will be true. 63 | if non_synthetic_value.type.IsReferenceType(): 64 | return non_synthetic_value 65 | 66 | while non_synthetic_value.type.GetPointeeType().IsPointerType(): 67 | non_synthetic_value = non_synthetic_value.Dereference() 68 | 69 | if not non_synthetic_value.type.IsPointerType(): 70 | non_synthetic_value = non_synthetic_value.AddressOf() 71 | 72 | return non_synthetic_value 73 | 74 | 75 | def obj_header_pointer(valobj: lldb.SBValue) -> lldb.SBValue: 76 | return single_pointer(valobj).Cast(obj_header_type()) 77 | 78 | 79 | def get_runtime_type(variable): 80 | return strip_quotes(evaluate("(char *)Konan_DebugGetTypeName({:#x})", variable.unsigned).summary) 81 | 82 | 83 | def type_info_type() -> lldb.SBType: 84 | self = LLDBCache.instance() 85 | if self._type_info_type is None: 86 | self._type_info_type = evaluate('(TypeInfo*)0x0').GetNonSyntheticValue().type 87 | return self._type_info_type 88 | 89 | 90 | def obj_header_type() -> lldb.SBType: 91 | self = LLDBCache.instance() 92 | if self._obj_header_type is None: 93 | self._obj_header_type = evaluate('(ObjHeader*)0x0').GetNonSyntheticValue().type 94 | return self._obj_header_type 95 | 96 | 97 | def array_header_type() -> lldb.SBType: 98 | self = LLDBCache.instance() 99 | if self._array_header_type is None: 100 | self._array_header_type = evaluate('(ArrayHeader*)0x0').GetNonSyntheticValue().type 101 | return self._array_header_type 102 | 103 | 104 | def runtime_type_size() -> lldb.value: 105 | self = LLDBCache.instance() 106 | if self._runtime_type_size is None: 107 | self._runtime_type_size = lldb.value(evaluate('runtimeTypeSize')) 108 | return self._runtime_type_size 109 | 110 | 111 | def runtime_type_alignment() -> lldb.value: 112 | self = LLDBCache.instance() 113 | if self._runtime_type_alignment is None: 114 | self._runtime_type_alignment = lldb.value( 115 | evaluate('runtimeTypeAlignment') 116 | ) 117 | return self._runtime_type_alignment 118 | 119 | 120 | def _symbol_loaded_address(name: str, target: lldb.SBTarget) -> int: 121 | candidates = target.FindSymbols(name) 122 | # take first 123 | for candidate in candidates: 124 | address = candidate.symbol.GetStartAddress().GetLoadAddress(target) 125 | log(lambda: "_symbol_loaded_address:{} {:#x}".format(name, address)) 126 | return address 127 | 128 | return 0 129 | 130 | 131 | def _get_konan_class_symbol_value(cls_name: str) -> lldb.value: 132 | target = lldb.debugger.GetSelectedTarget() 133 | address = _symbol_loaded_address(f'kclass:{cls_name}', target) 134 | return lldb.value( 135 | target.CreateValueFromAddress( 136 | cls_name, 137 | lldb.SBAddress(address, target), 138 | type_info_type(), 139 | ) 140 | ) 141 | 142 | 143 | def get_string_symbol() -> lldb.value: 144 | self = LLDBCache.instance() 145 | if self._string_symbol_value is None: 146 | self._string_symbol_value = _get_konan_class_symbol_value('kotlin.String') 147 | return self._string_symbol_value 148 | 149 | 150 | def get_list_symbol() -> lldb.value: 151 | self = LLDBCache.instance() 152 | if self._list_symbol_value is None: 153 | self._list_symbol_value = _get_konan_class_symbol_value('kotlin.collections.List') 154 | return self._list_symbol_value 155 | 156 | 157 | def get_map_symbol() -> lldb.value: 158 | self = LLDBCache.instance() 159 | if self._map_symbol_value is None: 160 | self._map_symbol_value = _get_konan_class_symbol_value('kotlin.collections.Map') 161 | return self._map_symbol_value 162 | 163 | 164 | class KnownValueType: 165 | ANY = 0 166 | STRING = 1 167 | ARRAY = 2 168 | LIST = 3 169 | MAP = 4 170 | 171 | entries = [ANY, STRING, ARRAY, LIST, MAP] 172 | 173 | @staticmethod 174 | def value_of(raw: int): 175 | assert KnownValueType.ANY <= raw <= KnownValueType.MAP 176 | return KnownValueType.entries[raw] 177 | 178 | 179 | def void_type() -> lldb.SBType: 180 | return lldb.debugger.GetSelectedTarget().GetBasicType(lldb.eBasicTypeVoid) 181 | 182 | 183 | def get_type_info(obj: lldb.SBValue) -> Optional[lldb.value]: 184 | possible_type_info = obj.CreateValueFromAddress( 185 | "typeInfoOrMeta_", 186 | obj.Cast(void_type().GetPointerType().GetPointerType()).Dereference().unsigned & ~0x3, 187 | type_info_type(), 188 | ) 189 | verification = possible_type_info.Cast(possible_type_info.type.GetPointerType()).Dereference() 190 | 191 | if possible_type_info.unsigned == verification.unsigned and possible_type_info.IsValid() and possible_type_info.unsigned != 0: 192 | return lldb.value(possible_type_info) 193 | else: 194 | return None 195 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/util/PropertyList.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli.util 2 | 3 | import kotlinx.cinterop.ExperimentalForeignApi 4 | import kotlinx.cinterop.ObjCObjectVar 5 | import kotlinx.cinterop.alloc 6 | import kotlinx.cinterop.memScoped 7 | import kotlinx.cinterop.ptr 8 | import kotlinx.cinterop.value 9 | import platform.Foundation.NSArray 10 | import platform.Foundation.NSData 11 | import platform.Foundation.NSDate 12 | import platform.Foundation.NSDictionary 13 | import platform.Foundation.NSError 14 | import platform.Foundation.NSMutableArray 15 | import platform.Foundation.NSMutableDictionary 16 | import platform.Foundation.NSNumber 17 | import platform.Foundation.NSPropertyListBinaryFormat_v1_0 18 | import platform.Foundation.NSPropertyListFormat 19 | import platform.Foundation.NSPropertyListImmutable 20 | import platform.Foundation.NSPropertyListOpenStepFormat 21 | import platform.Foundation.NSPropertyListSerialization 22 | import platform.Foundation.NSPropertyListXMLFormat_v1_0 23 | import platform.Foundation.NSString 24 | import platform.Foundation.valueForKey 25 | import platform.darwin.NSObject 26 | import kotlin.collections.List 27 | import kotlin.collections.Map 28 | import kotlin.collections.MutableList 29 | import kotlin.collections.MutableMap 30 | import kotlin.collections.component1 31 | import kotlin.collections.component2 32 | import kotlin.collections.iterator 33 | import kotlin.collections.map 34 | import kotlin.collections.mutableListOf 35 | import kotlin.collections.mutableMapOf 36 | import kotlin.collections.set 37 | import kotlin.collections.toMutableList 38 | import kotlin.collections.toMutableMap 39 | 40 | @OptIn(ExperimentalForeignApi::class) 41 | class PropertyList(val root: Object) { 42 | enum class Format { 43 | XML, OpenStep, Binary; 44 | 45 | val objc: NSPropertyListFormat 46 | get() = when (this) { 47 | XML -> NSPropertyListXMLFormat_v1_0 48 | OpenStep -> NSPropertyListOpenStepFormat 49 | Binary -> NSPropertyListBinaryFormat_v1_0 50 | } 51 | } 52 | sealed interface Object { 53 | val array: Array get() = this as Array 54 | val arrayOrNull: Array? get() = this as? Array 55 | val dictionary: Dictionary get() = this as Dictionary 56 | val dictionaryOrNull: Dictionary? get() = this as? Dictionary 57 | val string: String get() = this as String 58 | val stringOrNull: String? get() = this as? String 59 | val data: Data get() = this as Data 60 | val dataOrNull: Data? get() = this as? Data 61 | val date: Date get() = this as Date 62 | val dateOrNull: Date? get() = this as? Date 63 | val number: Number get() = this as Number 64 | val numberOrNull: Number? get() = this as? Number 65 | 66 | class Array( 67 | val items: MutableList = mutableListOf(), 68 | ): Object, MutableList by items 69 | 70 | class Dictionary( 71 | val items: MutableMap = mutableMapOf(), 72 | ): Object, MutableMap by items 73 | 74 | class String( 75 | val value: kotlin.String 76 | ): Object 77 | 78 | class Data( 79 | val value: NSData, 80 | ): Object 81 | 82 | class Date( 83 | val value: NSDate, 84 | ): Object 85 | 86 | class Number( 87 | val value: NSNumber 88 | ): Object 89 | } 90 | 91 | fun toData(format: Format = Format.Binary): NSData { 92 | return memScoped { 93 | val errorPointer: ObjCObjectVar = alloc() 94 | val data = NSPropertyListSerialization.dataWithPropertyList( 95 | plist = recursiveReverseBridge(root), 96 | format = format.objc, 97 | options = 0u, 98 | error = errorPointer.ptr, 99 | ) 100 | val error = errorPointer.value 101 | if (error != null) { 102 | throw SerializationException(error) 103 | } 104 | checkNotNull(data) { "Serialized plist data were null even though error was null too. This should never happen!" } 105 | } 106 | } 107 | 108 | private fun recursiveReverseBridge(obj: Object): NSObject = when (obj) { 109 | is Object.Dictionary -> { 110 | val dictionary = NSMutableDictionary(capacity = obj.size.toULong()) 111 | for ((key, value) in obj) { 112 | dictionary.setObject(recursiveReverseBridge(value), key.objc) 113 | } 114 | dictionary 115 | } 116 | is Object.Array -> { 117 | val array = NSMutableArray(capacity = obj.size.toULong()) 118 | for (item in obj) { 119 | array.addObject(recursiveReverseBridge(item)) 120 | } 121 | array 122 | } 123 | is Object.Data -> obj.value 124 | is Object.Date -> obj.value 125 | is Object.Number -> obj.value 126 | is Object.String -> obj.value.objc 127 | } 128 | 129 | class UnsupportedObjectTypeException(nsObject: NSObject): Exception("Unsupported property list value: $nsObject") 130 | class DeserializationException(error: NSError): Exception("Could not deserialize property list. Error: ${error.description}.") 131 | class SerializationException(error: NSError): Exception("Could not serialize property list. Error: ${error.description}.") 132 | 133 | companion object { 134 | fun create(path: Path): PropertyList { 135 | Console.muted("Loading property list from $path.") 136 | return create(File(path).dataContents()) 137 | } 138 | 139 | fun create(file: File): PropertyList { 140 | Console.muted("Loading property list from file at ${file.path}") 141 | return create(file.dataContents()) 142 | } 143 | 144 | fun create(data: NSData): PropertyList { 145 | val rawPropertyList = memScoped { 146 | val errorPointer: ObjCObjectVar = alloc() 147 | val propertyList = NSPropertyListSerialization.propertyListWithData( 148 | data = data, 149 | options = NSPropertyListImmutable, 150 | format = null, 151 | error = errorPointer.ptr, 152 | ) 153 | val error = errorPointer.value 154 | if (error != null) { 155 | throw DeserializationException(error) 156 | } 157 | checkNotNull(propertyList) { "Deserialized plist was null even though error was null too. This should never happen!" } 158 | } as NSObject 159 | 160 | val root = recursiveBridge(rawPropertyList) 161 | return PropertyList(root) 162 | } 163 | 164 | private fun recursiveBridge(nsObject: NSObject): Object = when (nsObject) { 165 | is NSDictionary -> Object.Dictionary( 166 | nsObject.map { key, value -> key to recursiveBridge(value) }.toMutableMap() 167 | ) 168 | is NSArray -> Object.Array( 169 | nsObject.map { item -> recursiveBridge(item) }.toMutableList() 170 | ) 171 | is NSString -> Object.String(nsObject.kt) 172 | is NSData -> Object.Data(nsObject) 173 | is NSDate -> Object.Date(nsObject) 174 | is NSNumber -> Object.Number(nsObject) 175 | else -> throw UnsupportedObjectTypeException(nsObject) 176 | } 177 | 178 | private fun NSArray.map(transform: (value: NSObject) -> T): List { 179 | return (0UL until count).map { index -> 180 | transform(objectAtIndex(index) as NSObject) 181 | } 182 | } 183 | 184 | private fun NSDictionary.map(transform: (key: String, value: NSObject) -> Pair): Map { 185 | val result = mutableMapOf() 186 | val enumerator = keyEnumerator() 187 | while (true) { 188 | val nsKey = enumerator.nextObject() as String? ?: break 189 | val nsValue = valueForKey(nsKey) as NSObject? ?: continue 190 | 191 | val (key, value) = transform(nsKey, nsValue) 192 | result[key] = value 193 | } 194 | return result 195 | } 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/PluginManager.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli 2 | 3 | import co.touchlab.xcode.cli.util.* 4 | import kotlinx.coroutines.CoroutineScope 5 | import kotlinx.coroutines.Dispatchers 6 | import kotlinx.coroutines.IO 7 | import kotlinx.coroutines.Job 8 | import kotlinx.coroutines.async 9 | import kotlinx.coroutines.cancelAndJoin 10 | import kotlinx.coroutines.coroutineScope 11 | import kotlinx.coroutines.delay 12 | import kotlinx.coroutines.launch 13 | import kotlinx.coroutines.withContext 14 | import platform.posix.nice 15 | import kotlin.coroutines.coroutineContext 16 | import kotlin.time.Duration.Companion.seconds 17 | 18 | object PluginManager { 19 | val pluginName = "Kotlin.ideplugin" 20 | val pluginSourceFile = File(Path.dataDir / pluginName) 21 | val pluginsDirectory = File(XcodeHelper.xcodeLibraryPath / "Plug-ins") 22 | val pluginTargetFile = File(pluginsDirectory.path / pluginName) 23 | 24 | private val pluginSourceInfoFile = File(pluginSourceFile.path / "Contents" / "Info.plist") 25 | private val pluginTargetInfoFile = File(pluginTargetFile.path / "Contents" / "Info.plist") 26 | private val pluginVersionInfoKey = "CFBundleShortVersionString" 27 | private val pluginCompatibilityInfoKey = "DVTPlugInCompatibilityUUIDs" 28 | private val fixXcode15Timeout = 10 29 | 30 | val bundledVersion: SemVer 31 | get() { 32 | val pluginInfo = PropertyList.create(pluginSourceInfoFile) 33 | return SemVer.parse(pluginInfo.root.dictionary.getValue(pluginVersionInfoKey).string.value) 34 | } 35 | 36 | val installedVersion: SemVer? 37 | get() = if (pluginTargetFile.exists()) { 38 | val pluginInfo = PropertyList.create(pluginTargetInfoFile) 39 | pluginInfo.root.dictionaryOrNull?.get(pluginVersionInfoKey)?.stringOrNull?.value?.let(SemVer::parseOrNull) 40 | } else { 41 | null 42 | } 43 | 44 | val isInstalled: Boolean 45 | get() = pluginTargetFile.exists() 46 | 47 | val targetSupportedXcodeUUIds: List 48 | get() = if (pluginTargetFile.exists()) { 49 | PropertyList.create(pluginTargetInfoFile) 50 | .root 51 | .dictionaryOrNull 52 | ?.get(pluginCompatibilityInfoKey) 53 | ?.arrayOrNull 54 | ?.mapNotNull { it.stringOrNull?.value } 55 | ?: emptyList() 56 | } else { 57 | emptyList() 58 | } 59 | 60 | fun install() { 61 | Console.muted("Ensuring plugins directory exists at ${pluginsDirectory.path}") 62 | pluginsDirectory.mkdirs() 63 | Console.muted("Copying Xcode plugin to target path ${pluginTargetFile.path}") 64 | pluginSourceFile.copy(pluginTargetFile.path) 65 | } 66 | 67 | suspend fun enable(version: SemVer, xcodeInstallations: List) { 68 | Console.info("Removing Kotlin Plugin defaults so we can add it to allowed.") 69 | XcodeHelper.removeKotlinPluginFromDefaults() 70 | Console.info("Allowing Kotlin Plugin") 71 | XcodeHelper.allowKotlinPlugin(version, xcodeInstallations) 72 | } 73 | suspend fun disable(version: SemVer, xcodeInstallations: List) { 74 | nice(420) 75 | Console.info("Removing Kotlin Plugin defaults so we can add it to skipped.") 76 | XcodeHelper.removeKotlinPluginFromDefaults() 77 | Console.info("We need Xcode to skip the plugin, so it doesn't crash.") 78 | XcodeHelper.skipKotlinPlugin(version, xcodeInstallations) 79 | } 80 | 81 | fun sync(xcodeInstallations: List) { 82 | check(isInstalled) { "Plugin is not installed!" } 83 | 84 | Console.echo("Synchronizing plugin compatibility list.") 85 | val additionalPluginCompatibilityIds = 86 | xcodeInstallations.mapNotNull { it.pluginCompatabilityId?.let { PropertyList.Object.String(it) } } 87 | Console.muted("Xcode installation IDs to include: ${additionalPluginCompatibilityIds.joinToString { it.value }}") 88 | val infoPlist = PropertyList.create(pluginTargetInfoFile) 89 | val rootDictionary = infoPlist.root.dictionary 90 | val oldPluginCompatibilityIds = rootDictionary 91 | .getOrPut(pluginCompatibilityInfoKey) { PropertyList.Object.Array(mutableListOf()) } 92 | .array 93 | Console.muted( 94 | "Previous Xcode installation IDs: ${ 95 | oldPluginCompatibilityIds.mapNotNull { it.stringOrNull?.value }.joinToString() 96 | }" 97 | ) 98 | oldPluginCompatibilityIds.addAll(additionalPluginCompatibilityIds) 99 | val distinctPluginCompatibilityIds = 100 | oldPluginCompatibilityIds.distinctBy { it.stringOrNull?.value }.toMutableList() 101 | Console.muted( 102 | "Xcode installation IDs to save: ${ 103 | distinctPluginCompatibilityIds.mapNotNull { it.stringOrNull?.value }.joinToString() 104 | }" 105 | ) 106 | rootDictionary[pluginCompatibilityInfoKey] = PropertyList.Object.Array(distinctPluginCompatibilityIds) 107 | pluginTargetInfoFile.write(infoPlist.toData(PropertyList.Format.XML)) 108 | } 109 | 110 | suspend fun uninstall() { 111 | Console.info("Deleting Xcode plugin from ${pluginTargetFile.path}") 112 | pluginTargetFile.delete() 113 | XcodeHelper.removeKotlinPluginFromDefaults() 114 | } 115 | 116 | suspend fun fixXcode15(xcodeInstallations: List): Unit = try { 117 | val cacheDir = Path(Shell.exec("/usr/bin/getconf", "DARWIN_USER_CACHE_DIR").output.orEmpty().trim()) 118 | Console.info("Enabling IDEPerformanceDebugger built-in plugin.") 119 | XcodeHelper.setIDEPerformanceDebuggerEnabled(true) 120 | 121 | xcodeInstallations 122 | .filter { it.version.startsWith("15.") } 123 | .forEach { installation -> 124 | Console.info("Opening ${installation.name} in background to generate plugin cache") 125 | val xcodeRunning = CoroutineScope(coroutineContext + Dispatchers.IO).launch { 126 | XcodeHelper.openInBackground(installation) 127 | } 128 | 129 | try { 130 | for (i in 1..fixXcode15Timeout) { 131 | delay(1.seconds) 132 | 133 | val pluginCachePath = 134 | cacheDir / "com.apple.DeveloperTools" / "${installation.version}-${installation.build}" / "Xcode" / "PlugInCache-Debug.xcplugincache" 135 | 136 | if (pluginCachePath.exists()) { 137 | Console.info("${installation.name} plugin cache file exists, checking if it contains IDEPerformanceDebugger entry yet") 138 | val pluginCache = PropertyList.create(pluginCachePath) 139 | val containsIDEPerformanceDebuggerInfo = with(XcodeHelper.PlugInCache) { 140 | pluginCache.scanRecords.contains { record -> 141 | record.bundlePath.endsWith("IDEPerformanceDebugger.framework") 142 | } 143 | } 144 | 145 | if (containsIDEPerformanceDebuggerInfo) { 146 | // Xcode updated the cache and should work now, we're done. 147 | Console.info("${installation.name} updated the plugin cache and should work now.") 148 | break 149 | } else { 150 | Console.info("${installation.name} plugin cache doesn't contain IDEPerformanceDebugger entry yet.") 151 | } 152 | } else { 153 | Console.info("${installation.name} plugin cache file doesn't exist yet.") 154 | } 155 | 156 | if (i == fixXcode15Timeout) { 157 | error("IDEPerformanceDebugger.framework was not found in ${installation.name} plugin cache after waiting $fixXcode15Timeout seconds. Please try again, or report an issue in the xcode-kotlin repository.") 158 | } 159 | } 160 | } finally { 161 | Console.info("Killing ${installation.name}") 162 | xcodeRunning.cancelAndJoin() 163 | } 164 | } 165 | } finally { 166 | Console.info("Disabling IDEPerformanceDebugger built-in plugin.") 167 | XcodeHelper.setIDEPerformanceDebuggerEnabled(false) 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /LLDBPlugin/test_project/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 87 | 88 | # Use the maximum available, or set MAX_FD != -1 to use that value. 89 | MAX_FD=maximum 90 | 91 | warn () { 92 | echo "$*" 93 | } >&2 94 | 95 | die () { 96 | echo 97 | echo "$*" 98 | echo 99 | exit 1 100 | } >&2 101 | 102 | # OS specific support (must be 'true' or 'false'). 103 | cygwin=false 104 | msys=false 105 | darwin=false 106 | nonstop=false 107 | case "$( uname )" in #( 108 | CYGWIN* ) cygwin=true ;; #( 109 | Darwin* ) darwin=true ;; #( 110 | MSYS* | MINGW* ) msys=true ;; #( 111 | NONSTOP* ) nonstop=true ;; 112 | esac 113 | 114 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 115 | 116 | 117 | # Determine the Java command to use to start the JVM. 118 | if [ -n "$JAVA_HOME" ] ; then 119 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 120 | # IBM's JDK on AIX uses strange locations for the executables 121 | JAVACMD=$JAVA_HOME/jre/sh/java 122 | else 123 | JAVACMD=$JAVA_HOME/bin/java 124 | fi 125 | if [ ! -x "$JAVACMD" ] ; then 126 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 127 | 128 | Please set the JAVA_HOME variable in your environment to match the 129 | location of your Java installation." 130 | fi 131 | else 132 | JAVACMD=java 133 | if ! command -v java >/dev/null 2>&1 134 | then 135 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 136 | 137 | Please set the JAVA_HOME variable in your environment to match the 138 | location of your Java installation." 139 | fi 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 147 | # shellcheck disable=SC3045 148 | MAX_FD=$( ulimit -H -n ) || 149 | warn "Could not query maximum file descriptor limit" 150 | esac 151 | case $MAX_FD in #( 152 | '' | soft) :;; #( 153 | *) 154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 155 | # shellcheck disable=SC3045 156 | ulimit -n "$MAX_FD" || 157 | warn "Could not set maximum file descriptor limit to $MAX_FD" 158 | esac 159 | fi 160 | 161 | # Collect all arguments for the java command, stacking in reverse order: 162 | # * args from the command line 163 | # * the main class name 164 | # * -classpath 165 | # * -D...appname settings 166 | # * --module-path (only if needed) 167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 168 | 169 | # For Cygwin or MSYS, switch paths to Windows format before running java 170 | if "$cygwin" || "$msys" ; then 171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 173 | 174 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 175 | 176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 177 | for arg do 178 | if 179 | case $arg in #( 180 | -*) false ;; # don't mess with options #( 181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 182 | [ -e "$t" ] ;; #( 183 | *) false ;; 184 | esac 185 | then 186 | arg=$( cygpath --path --ignore --mixed "$arg" ) 187 | fi 188 | # Roll the args list around exactly as many times as the number of 189 | # args, so each arg winds up back in the position where it started, but 190 | # possibly modified. 191 | # 192 | # NB: a `for` loop captures its iteration list before it begins, so 193 | # changing the positional parameters here affects neither the number of 194 | # iterations, nor the values presented in `arg`. 195 | shift # remove old arg 196 | set -- "$@" "$arg" # push replacement arg 197 | done 198 | fi 199 | 200 | 201 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 202 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 203 | 204 | # Collect all arguments for the java command; 205 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 206 | # shell script including quotes and variable substitutions, so put them in 207 | # double quotes to make sure that they get re-expanded; and 208 | # * put everything else in single quotes, so that it's not re-expanded. 209 | 210 | set -- \ 211 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 212 | -classpath "$CLASSPATH" \ 213 | org.gradle.wrapper.GradleWrapperMain \ 214 | "$@" 215 | 216 | # Stop when "xargs" is not available. 217 | if ! command -v xargs >/dev/null 2>&1 218 | then 219 | die "xargs is not available" 220 | fi 221 | 222 | # Use "xargs" to parse quoted args. 223 | # 224 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 225 | # 226 | # In Bash we could simply go: 227 | # 228 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 229 | # set -- "${ARGS[@]}" "$@" 230 | # 231 | # but POSIX shell has neither arrays nor command substitution, so instead we 232 | # post-process each arg (as a line of input to sed) to backslash-escape any 233 | # character that might be a shell metacharacter, then use eval to reverse 234 | # that process (while maintaining the separation between arguments), and wrap 235 | # the whole thing up as a single "set" statement. 236 | # 237 | # This will of course break if any of these variables contains a newline or 238 | # an unmatched quote. 239 | # 240 | 241 | eval "set -- $( 242 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 243 | xargs -n1 | 244 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 245 | tr '\n' ' ' 246 | )" '"$@"' 247 | 248 | exec "$JAVACMD" "$@" 249 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/util/SemVer.kt: -------------------------------------------------------------------------------- 1 | /* 2 | MIT License 3 | 4 | Copyright (c) 2017 Eric Li 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | */ 24 | package co.touchlab.xcode.cli.util 25 | 26 | import kotlin.math.min 27 | 28 | /** 29 | * Version number in [Semantic Versioning 2.0.0](http://semver.org/spec/v2.0.0.html) specification (SemVer). 30 | * 31 | * @property major major version, increment it when you make incompatible API changes. 32 | * @property minor minor version, increment it when you add functionality in a backwards-compatible manner. 33 | * @property patch patch version, increment it when you make backwards-compatible bug fixes. 34 | * @property preRelease pre-release version. 35 | * @property buildMetadata build metadata. 36 | */ 37 | public data class SemVer( 38 | val major: Int, 39 | val minor: Int = 0, 40 | val patch: Int = 0, 41 | val preRelease: String? = null, 42 | val buildMetadata: String? = null, 43 | ) : Comparable { 44 | 45 | init { 46 | require(major >= 0) { "Major version must be a positive number" } 47 | require(minor >= 0) { "Minor version must be a positive number" } 48 | require(patch >= 0) { "Patch version must be a positive number" } 49 | if (preRelease != null) require(PreReleasePattern matches preRelease) { "Pre-release version is not valid" } 50 | if (buildMetadata != null) require(BuildMetadataPattern matches buildMetadata) { "Build metadata is not valid" } 51 | } 52 | 53 | /** 54 | * Create a new [SemVer] with the next major number. Minor and patch number becomes 0. 55 | * Pre-release and build metadata information is not applied to the new version. 56 | * 57 | * @return next major version 58 | * @throws NumberFormatException if the next major number exceed [Int] range. 59 | */ 60 | public fun nextMajor(): SemVer { 61 | return SemVer(major = major + 1) 62 | } 63 | 64 | /** 65 | * Create a new [SemVer] with the same major number and the next minor number. Patch number becomes 0. 66 | * Pre-release and build metadata information is not applied to the new version. 67 | * 68 | * @return next minor version 69 | * @throws NumberFormatException if the next minor number exceed [Int] range. 70 | */ 71 | public fun nextMinor(): SemVer { 72 | return SemVer(major = major, minor = minor + 1) 73 | } 74 | 75 | /** 76 | * Create a new [SemVer] with the same major and minor number and the next patch number. 77 | * Pre-release and build metadata information is not applied to the new version. 78 | * 79 | * @return next patch version 80 | * @throws NumberFormatException if the next patch number exceed [Int] range. 81 | */ 82 | public fun nextPatch(): SemVer { 83 | return SemVer(major = major, minor = minor, patch = patch + 1) 84 | } 85 | 86 | @Suppress("CyclomaticComplexMethod", "ReturnCount") 87 | override fun compareTo(other: SemVer): Int { 88 | if (major > other.major) return 1 89 | if (major < other.major) return -1 90 | if (minor > other.minor) return 1 91 | if (minor < other.minor) return -1 92 | if (patch > other.patch) return 1 93 | if (patch < other.patch) return -1 94 | 95 | // When major, minor, and patch are equal, a pre-release version has lower precedence than a normal version 96 | if (preRelease != null && other.preRelease == null) return -1 97 | if (preRelease == null && other.preRelease != null) return 1 98 | if (preRelease == null && other.preRelease == null) return 0 99 | 100 | // Precedence for two pre-release versions with the same major, minor, and patch version MUST be determined by 101 | // comparing each dot separated identifier from left to right until a difference is found 102 | val parts = preRelease!!.split(".") 103 | val otherParts = other.preRelease!!.split(".") 104 | 105 | val smallerSize = min(parts.size, otherParts.size) 106 | for (i in 0 until smallerSize) { 107 | val part = parts[i] 108 | val otherPart = otherParts[i] 109 | if (part == otherPart) continue 110 | val partIsNumeric = part.isNumeric() 111 | val otherPartIsNumeric = otherPart.isNumeric() 112 | 113 | return when { 114 | partIsNumeric && !otherPartIsNumeric -> -1 115 | !partIsNumeric && otherPartIsNumeric -> 1 116 | !partIsNumeric && !otherPartIsNumeric -> part.compareTo(otherPart) 117 | else -> try { 118 | val partLong = part.toLong() 119 | val otherPartLong = otherPart.toLong() 120 | partLong.compareTo(otherPartLong) 121 | } catch (_: NumberFormatException) { 122 | // When part or otherPart doesn't fit in an Long, compare as String 123 | // It is not the standard way but because there are no proper BigDecimal class for Kotlin 124 | // Multiplatform we have to use this way 125 | part.compareTo(otherPart) 126 | } 127 | } 128 | } 129 | return when { 130 | parts.size == smallerSize && otherParts.size > smallerSize -> { 131 | // parts is ended and otherParts is not ended 132 | -1 133 | } 134 | 135 | parts.size > smallerSize && otherParts.size == smallerSize -> { 136 | // parts is not ended and otherParts is ended 137 | 1 138 | } 139 | 140 | else -> 0 141 | } 142 | } 143 | 144 | /** 145 | * Check the version number is in initial development. 146 | * 147 | * @return true if it is in initial development. 148 | */ 149 | public fun isInitialDevelopmentPhase(): Boolean = major == 0 150 | 151 | /** 152 | * Build the version name string. 153 | * 154 | * @return version name string in Semantic Versioning 2.0.0 specification. 155 | */ 156 | override fun toString(): String = buildString { 157 | append(major) 158 | append('.') 159 | append(minor) 160 | append('.') 161 | append(patch) 162 | if (preRelease != null) { 163 | append('-') 164 | append(preRelease) 165 | } 166 | if (buildMetadata != null) { 167 | append('+') 168 | append(buildMetadata) 169 | } 170 | } 171 | 172 | private fun String.isNumeric(): Boolean = numericPattern.matches(this) 173 | 174 | public companion object { 175 | private val numericPattern = Regex("""\d+""") 176 | 177 | /** 178 | * Parse the version string to [SemVer]. 179 | * 180 | * @param version version string to be parsed. 181 | * @return parsed [SemVer]. 182 | * @throws IllegalArgumentException if the given string is not a valid version. 183 | * @throws NumberFormatException if [major], [minor], [patch] values exceed [Int] range. 184 | */ 185 | @Suppress("DestructuringDeclarationWithTooManyEntries") 186 | public fun parse(version: String): SemVer { 187 | val (major, minor, patch, preRelease, buildMetadata) = ( 188 | FullPattern.matchEntire(version) 189 | ?: throw IllegalArgumentException("Invalid version string [$version]") 190 | ).destructured 191 | return SemVer( 192 | major = major.toInt(), 193 | minor = minor.toInt(), 194 | patch = patch.toIntOrNull() ?: 0, 195 | preRelease = preRelease.ifEmpty { null }, 196 | buildMetadata = buildMetadata.ifEmpty { null }, 197 | ) 198 | } 199 | 200 | /** 201 | * Parse the version string to [SemVer]. 202 | * 203 | * @param version version string to be parsed. 204 | * @return parsed [SemVer] or null if it cannot be parsed. 205 | */ 206 | public fun parseOrNull(version: String): SemVer? = try { 207 | parse(version = version) 208 | } catch (_: IllegalArgumentException) { 209 | null 210 | } 211 | } 212 | } 213 | 214 | internal val PreReleasePattern: Regex 215 | get() = 216 | Regex("""(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*""") 217 | internal val BuildMetadataPattern: Regex 218 | get() = 219 | Regex("""[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*""") 220 | 221 | @Suppress("MaxLineLength") 222 | internal val FullPattern: Regex 223 | get() = 224 | Regex( 225 | """(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?""" 226 | ) 227 | -------------------------------------------------------------------------------- /src/macosMain/kotlin/co/touchlab/xcode/cli/XcodeHelper.kt: -------------------------------------------------------------------------------- 1 | package co.touchlab.xcode.cli 2 | 3 | import co.touchlab.xcode.cli.util.BackupHelper 4 | import co.touchlab.xcode.cli.util.Console 5 | import co.touchlab.xcode.cli.util.File 6 | import co.touchlab.xcode.cli.util.Path 7 | import co.touchlab.xcode.cli.util.PropertyList 8 | import co.touchlab.xcode.cli.util.SemVer 9 | import co.touchlab.xcode.cli.util.Shell 10 | import kotlinx.serialization.SerialName 11 | import kotlinx.serialization.Serializable 12 | import kotlinx.serialization.json.Json 13 | import platform.Foundation.NSNumber 14 | import platform.Foundation.numberWithBool 15 | import platform.posix.exit 16 | 17 | object XcodeHelper { 18 | val xcodeLibraryPath = Path.home / "Library" / "Developer" / "Xcode" 19 | 20 | private val xcodeProcessName = "Xcode" 21 | private val xcodeVersionRegex = Regex("(\\S+) \\((\\S+)\\)") 22 | 23 | suspend fun ensureXcodeNotRunning() { 24 | Console.muted("Checking if any Xcode runs.") 25 | val result = Shell.exec("/usr/bin/pgrep", "-xq", "--", xcodeProcessName) 26 | if (result.success) { 27 | Console.muted("Found running Xcode instance.") 28 | val shutdown = Console.confirm("Xcode is running. Attempt to shut down?") 29 | if (shutdown) { 30 | Console.muted("Shutting down Xcode.") 31 | Console.echo("Shutting down Xcode...") 32 | killRunningXcode().checkSuccessful { 33 | "Couldn't shut down Xcode!" 34 | } 35 | } else { 36 | Console.danger("Xcode needs to be closed!") 37 | exit(1) 38 | } 39 | } else { 40 | Console.muted("No running Xcode found.") 41 | } 42 | } 43 | 44 | suspend fun openInBackground(installation: XcodeInstallation) { 45 | val xcodeBinaryPath = installation.path / "Contents" / "MacOS" / "Xcode" 46 | Console.info("Opening Xcode binary in background ($xcodeBinaryPath).") 47 | // Console.echo("Opening realXcodePath in background.") 48 | 49 | // Shell.exec("/usr/bin/open", "-gjF", xcodeBinaryPath.value) 50 | Shell.exec(xcodeBinaryPath.value).checkSuccessful { 51 | "Couldn't open ${installation.name} at $xcodeBinaryPath!" 52 | } 53 | } 54 | 55 | suspend fun killRunningXcode(): Shell.ExecutionResult { 56 | return Shell.exec("/usr/bin/pkill", "-x", xcodeProcessName) 57 | } 58 | 59 | suspend fun allXcodeInstallations(): List { 60 | val result = Shell.exec("/usr/sbin/system_profiler", "-json", "SPDeveloperToolsDataType") 61 | .checkSuccessful { "Couldn't get list of installed developer tools." } 62 | 63 | val json = Json { 64 | ignoreUnknownKeys = true 65 | } 66 | 67 | if (result.output == null) { 68 | error("Missing output from system_profiler!") 69 | } 70 | val output = json.decodeFromString(SystemProfilerOutput.serializer(), result.output) 71 | return output.developerTools 72 | .map { 73 | installationAt(Path(it.path)) 74 | } 75 | } 76 | 77 | suspend fun installationAt(path: Path): XcodeInstallation { 78 | val xcodeFile = File(path) 79 | require(xcodeFile.exists()) { "Path $path doesn't exist!" } 80 | val versionPlist = PropertyList.create(path / "Contents" / "version.plist") 81 | val version = with(XcodeVersion) { 82 | checkNotNull(versionPlist.version?.trim()) { "Couldn't get version of Xcode at $path." } 83 | } 84 | val build = with(XcodeVersion) { 85 | checkNotNull(versionPlist.build?.trim()) { "Couldn't get build number of Xcode at $path." } 86 | } 87 | 88 | if (version15_3_orHigher(version)) { 89 | return XcodeInstallation( 90 | version = version, 91 | build = build, 92 | path = path 93 | ) 94 | } 95 | 96 | val xcodeInfoPath = path / "Contents" / "Info" 97 | val pluginCompatabilityIdResult = 98 | Shell.exec("/usr/bin/defaults", "read", xcodeInfoPath.value, "DVTPlugInCompatibilityUUID") 99 | .checkSuccessful { 100 | "Couldn't get plugin compatibility UUID from Xcode at ${path}." 101 | } 102 | val pluginCompatabilityId = checkNotNull(pluginCompatabilityIdResult.output?.trim()) { 103 | "Couldn't get plugin compatibility ID of Xcode at path: ${path}." 104 | } 105 | return XcodeInstallation( 106 | version = version, 107 | build = build, 108 | path = path, 109 | pluginCompatabilityId = pluginCompatabilityId, 110 | ) 111 | } 112 | 113 | suspend fun allowKotlinPlugin(pluginVersion: SemVer, xcodeInstallations: List) { 114 | Console.info("Adding plugin to allowed list in Xcode defaults.") 115 | modifyingXcodeDefaults("BeforeAdd") { 116 | for (installation in xcodeInstallations) { 117 | it.nonApplePlugins(installation.version).allowed.add(xcodeKotlinBundleId, pluginVersion.toString()) 118 | } 119 | } 120 | } 121 | 122 | suspend fun skipKotlinPlugin(pluginVersion: SemVer, xcodeInstallations: List) { 123 | Console.info("Adding plugin to skipped list in Xcode defaults.") 124 | modifyingXcodeDefaults("BeforeSkip") { 125 | for (installation in xcodeInstallations) { 126 | it.nonApplePlugins(installation.version).skipped.add(xcodeKotlinBundleId, pluginVersion.toString()) 127 | } 128 | } 129 | } 130 | 131 | suspend fun removeKotlinPluginFromDefaults() { 132 | Console.info("Removing plugin from allowed/skipped list in Xcode defaults.") 133 | modifyingXcodeDefaults("BeforeRemove") { properties -> 134 | properties.allNonApplePlugins().forEach { 135 | it.allowed.remove(xcodeKotlinBundleId) 136 | it.skipped.remove(xcodeKotlinBundleId) 137 | } 138 | } 139 | } 140 | 141 | suspend fun setIDEPerformanceDebuggerEnabled(enabled: Boolean) { 142 | Console.info("Setting IDEPerformanceDebuggerEnabled to $enabled in Xcode defaults.") 143 | modifyingXcodeDefaults("BeforeIDEPerformanceDebuggerEnabled-$enabled") { 144 | it.root.dictionary["IDEPerformanceDebuggerEnabled"] = PropertyList.Object.Number( 145 | NSNumber.numberWithBool(enabled) 146 | ) 147 | } 148 | } 149 | 150 | private suspend inline fun modifyingXcodeDefaults(backupTag: String, modify: Defaults.(PropertyList) -> Unit) { 151 | val backupPath = BackupHelper.backupPath("XcodeDefaults_$backupTag.plist") 152 | Console.info("Saving a backup of com.apple.dt.Xcode defaults to `$backupPath`") 153 | Shell.exec("/usr/bin/defaults", "export", "com.apple.dt.Xcode", backupPath.value).checkSuccessful { 154 | "Couldn't export Xcode defaults." 155 | } 156 | val defaultsPlist = PropertyList.create(backupPath) 157 | Defaults.modify(defaultsPlist) 158 | val newPlistData = defaultsPlist.toData(PropertyList.Format.XML) 159 | Shell.exec("/usr/bin/defaults", "import", "com.apple.dt.Xcode", "-", input = newPlistData).checkSuccessful { 160 | "Couldn't import new Xcode defaults." 161 | } 162 | } 163 | 164 | data class XcodeInstallation( 165 | val version: String, 166 | val build: String, 167 | val path: Path, 168 | val pluginCompatabilityId: String? = null, 169 | ) { 170 | val name: String = "Xcode $version ($build)" 171 | 172 | fun supported(supportedXcodeUuids: Set): Boolean = version15_3_orHigher(version) || 173 | supportedXcodeUuids.contains(pluginCompatabilityId) 174 | } 175 | 176 | fun version15_3_orHigher(version: String) = SemVer.parse(version) >= SemVer.parse("15.3") 177 | 178 | @Serializable 179 | private data class SystemProfilerOutput( 180 | @SerialName("SPDeveloperToolsDataType") 181 | val developerTools: List 182 | ) { 183 | @Serializable 184 | data class DeveloperTool( 185 | @SerialName("spdevtools_path") 186 | val path: String, 187 | @SerialName("spdevtools_version") 188 | val version: String, 189 | ) 190 | } 191 | 192 | private object XcodeVersion { 193 | val PropertyList.version: String? 194 | get() = root.dictionary["CFBundleShortVersionString"]?.stringOrNull?.value 195 | 196 | val PropertyList.build: String? 197 | get() = root.dictionary["ProductBuildVersion"]?.stringOrNull?.value 198 | } 199 | 200 | object PlugInCache { 201 | val PropertyList.scanRecords: DVTScanRecords 202 | get() = DVTScanRecords(root.dictionary["DVTScanRecords"]?.arrayOrNull ?: PropertyList.Object.Array()) 203 | 204 | class DVTScanRecords(private val backingArray: PropertyList.Object.Array) { 205 | fun contains(block: (Record) -> Boolean): Boolean { 206 | return backingArray.any { block(Record(it.dictionary)) } 207 | } 208 | 209 | class Record(private val backingDictionary: PropertyList.Object.Dictionary) { 210 | val bundlePath: String 211 | get() = backingDictionary["bundlePath"]?.stringOrNull?.value ?: "" 212 | } 213 | } 214 | } 215 | 216 | private object Defaults { 217 | val xcodeKotlinBundleId = "org.kotlinlang.xcode.kotlin" 218 | private val nonApplePluginsKeyPrefix = "DVTPlugInManagerNonApplePlugIns-Xcode-" 219 | 220 | fun PropertyList.allNonApplePlugins(): List { 221 | return root.dictionary.filter { (key, _) -> key.startsWith(nonApplePluginsKeyPrefix) }.map { (_, value) -> 222 | NonApplePlugins(value.dictionary) 223 | } 224 | } 225 | 226 | fun PropertyList.nonApplePlugins(xcodeVersion: String): NonApplePlugins { 227 | val backingDictionary = root.dictionary.getOrPut(nonApplePluginsKeyPrefix + xcodeVersion) { 228 | PropertyList.Object.Dictionary( 229 | mutableMapOf( 230 | "allowed" to PropertyList.Object.Dictionary(), 231 | "skipped" to PropertyList.Object.Dictionary(), 232 | ) 233 | ) 234 | }.dictionary 235 | return NonApplePlugins(backingDictionary) 236 | } 237 | 238 | class NonApplePlugins(private val backingDictionary: PropertyList.Object.Dictionary) { 239 | val allowed: PluginEntries 240 | get() = entries("allowed") 241 | val skipped: PluginEntries 242 | get() = entries("skipped") 243 | 244 | private fun entries(key: String): PluginEntries { 245 | return PluginEntries( 246 | backingDictionary.getOrPut(key) { PropertyList.Object.Dictionary() }.dictionary 247 | ) 248 | } 249 | 250 | class PluginEntries(private val backingDictionary: PropertyList.Object.Dictionary) { 251 | fun add(bundleId: String, version: String) { 252 | backingDictionary[bundleId] = PropertyList.Object.Dictionary( 253 | mutableMapOf( 254 | "version" to PropertyList.Object.String(version) 255 | ) 256 | ) 257 | } 258 | 259 | fun remove(bundleId: String) { 260 | backingDictionary.remove(bundleId) 261 | } 262 | } 263 | } 264 | } 265 | } 266 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Touchlab 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------