RNCryptor/RNCryptor

Leak or strange behavior

Z--EN opened this issue · 5 comments

Z--EN commented

I tried use RNCryptor for encrypt big data in the CoreData + SQLite. Here my part source:

    let url = Bundle.main.url(forResource: "test", withExtension: "bin")!
    let dataObject = NSManagedObject(entity: entity, insertInto: managedContext)
    
    do {
        let binData = try NSData(contentsOf: url, options: NSData.ReadingOptions.mappedIfSafe)
        
        autoreleasepool {
            let cipherData = RNCryptor.encrypt(data: binData as Foundation.Data, withPassword: self.key) as NSData
            
            dataObject.setValue(index, forKeyPath: "id")
            dataObject.setValue(cipherData, forKeyPath: "data")
        }
        
        try managedContext.save()
        self.data.append(dataObject)
        
        NSLog("added data \(index) to data")
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }

The memory are increasing until out of memory if this source is running a lot times. I tried without your library all were ok.

I would expect the above code to grow in memory without bound. You're saving all the cipher texts onto data:

    self.data.append(dataObject)

Is there any point where you remove them? That doesn't sound like a leak.

Z--EN commented

Thanks for your reply. You are right, but why this source work without drain memory:

let url = Bundle.main.url(forResource: "test", withExtension: "bin")!
let dataObject = NSManagedObject(entity: entity, insertInto: managedContext)

do {
    let binData = try NSData(contentsOf: url, options: NSData.ReadingOptions.mappedIfSafe)
    
    autoreleasepool {
        //let cipherData = RNCryptor.encrypt(data: binData as Foundation.Data, withPassword: self.key) as NSData
        
        dataObject.setValue(index, forKeyPath: "id")
        dataObject.setValue(binData  as Foundation.Data, forKeyPath: "data")
    }
    
    try managedContext.save()
    self.data.append(dataObject)
    
    NSLog("added data \(index) to data")
} catch let error as NSError {
    print("Could not save. \(error), \(error.userInfo)")
}

Do you think system work with Data more carefully? First source is using a lot memory but last source use limit memory only 54 MB for 300 binary data, first source is using 1.36 GB. The different is only with one line. Seems in second source data are saving to disk but in first source data retained in RNCryptor library and don't want unload or clear (

Z--EN commented

But in second source I am working with NSData too. If it is possible don't drain memory first time I think it is possible don't drain memory in both times.

Your code uses memory mapping to the disk. If the data isn’t modified, it doesn’t have to create any dirty pages (it can just reload them from disk when needed). When you encrypt, you’re creating non-mapped pages because they don’t match what’s on disk anymore.

Z--EN commented

Ok, thanks