Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[KMP] Fix issue: memory leak found in Base58.decode in iOS #4031

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

10gic
Copy link
Contributor

@10gic 10gic commented Sep 18, 2024

Description

Fix issue #4030

How to test

Run Rust, C++, Kotlin, Swift tests

Types of changes

Checklist

  • Create pull request as draft initially, unless its complete.
  • Add tests to cover changes as needed.
  • Update documentation as needed.
  • If there is a related Issue, mention it in the description.

If you're adding a new blockchain

  • I have read the guidelines for adding a new blockchain.

Screenshots

Before fixing, run Base58.decode 100000 times, it takes up to 200 MB of memory:
Xnip2024-09-18_15-25-56

After fixing, run Base58.decode 100000 times, it takes up to 97.4 MB of memory:
Xnip2024-09-18_15-21-17

Solution

The generated code before fixing:

package com.trustwallet.core

actual object Base58 {

    // ......

    actual fun decode(string: String): ByteArray? =
        TWBase58Decode(string.toTwString()).readTwBytes()         // toTwString and readTwBytes leak memory!


    // ......
}

Definition of old readTwBytes:

internal fun COpaquePointer?.readTwBytes(): ByteArray? =
    TWDataBytes(this)?.readBytes(TWDataSize(this).toInt())

The generated code after fixing:

package com.trustwallet.core

actual object Base58 {

    // ......

    actual fun decode(string: String): ByteArray? {
        val stringString = TWStringCreateWithUTF8Bytes(string)
        val result = TWBase58Decode(stringString).readTwBytes()
        TWStringDelete(stringString)
        return result
    }

    // ......
}

Definition of new readTwBytes:

internal fun COpaquePointer?.readTwBytes(): ByteArray? =
    this?.let {
        val result = TWDataBytes(it)?.readBytes(TWDataSize(it).toInt())
        TWDataDelete(it)
        result
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant