【问题标题】:Swift: How to make sure that code is not optimized out?Swift:如何确保代码没有被优化?
【发布时间】:2015-11-20 09:09:42
【问题描述】:

我想在 Swift 中将 UnsafeMutablePointer 的内容归零。

在 C 中你通常有这样的东西:

void freeSecure(void *buffer, uint64_t size) {
    // Create volatile pointer to make sure that the code won't be optimized away
    volatile uint8_t *ptr = buffer;
    for (uint64_t i = 0; i < size; i++) ptr[i] = 0x00;
    free(buffer);
}

如何在 Swift 中实现同样的功能?

// Is extension of `UnsafeMutablePointer`
public func KC_dealloc(allocated: Int) {
    if num == 0 {
        self.destroy()
        self.dealloc(allocated)
        return
    }

    let byteCount = sizeof(Memory) * allocated
    let ptr = UnsafeMutablePointer<UInt8>(self) // volatile???
    for var i = 0; i < byteCount; i++ {
        ptr[i] = 0x00
    }
    self.destroy()
    self.dealloc(allocated)
}

【问题讨论】:

  • 你试过了吗?
  • 这是我的实际代码,但我不知道它是否真的将数据清零或者是否删除了部分,因为数据将不再被读取...... ????

标签: swift compiler-optimization volatile


【解决方案1】:

好的,我在 Apple-developer-forum 上问了同样的问题,那里的某个人向我指出了 memset_s-function,它可以满足我的需求。

所以我的 Swift 代码应该是这样的:

// Is extension of `UnsafeMutablePointer`
public func KC_dealloc(allocated: Int) {
    if num == 0 {
        self.destroy()
        self.dealloc(allocated)
        return
    }

    let byteCount = sizeof(Memory) * allocated
    let ptr = UnsafeMutablePointer<UInt8>(self) // volatile???
    memset_s(ptr, byteCount, 0x00, byteCount) // Defined in C11
    self.destroy()
    self.dealloc(allocated)
}

【讨论】:

  • 什么是num?应该是allocated
  • 老实说,我已经不知道了——我的意思是 allocated 或者它是 UnsafeMutablePointer 的属性...对不起?
猜你喜欢
  • 2019-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多