Skip to content

Commit 473d6e5

Browse files
committed
Improve TDS RPC string encoding to prevent memory corruption/invalid byte sequences
1 parent 9ca8ed4 commit 473d6e5

1 file changed

Lines changed: 7 additions & 6 deletions

File tree

Sources/CosmoMSSQL/TDS/TDSRPCRequest.swift

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -188,16 +188,16 @@ struct TDSRPCRequest {
188188
// MARK: - PLP helpers
189189

190190
private func writePLPString(_ s: String, into buf: inout ByteBuffer) {
191-
let utf16 = Array(s.utf16)
192-
let byteLen = utf16.count * 2
191+
let utf16Bytes = s.data(using: .utf16LittleEndian) ?? Data()
192+
let byteLen = utf16Bytes.count
193193
if byteLen == 0 {
194194
buf.writeInteger(UInt64(0), endianness: .little) // empty (not null)
195195
buf.writeInteger(UInt32(0), endianness: .little) // terminator
196196
return
197197
}
198198
buf.writeInteger(UInt64(byteLen), endianness: .little) // total length
199199
buf.writeInteger(UInt32(byteLen), endianness: .little) // chunk length
200-
for unit in utf16 { buf.writeInteger(unit, endianness: .little) }
200+
buf.writeBytes(utf16Bytes)
201201
buf.writeInteger(UInt32(0), endianness: .little) // terminator
202202
}
203203

@@ -216,9 +216,10 @@ struct TDSRPCRequest {
216216
// MARK: - String helpers
217217

218218
private func writeBVarChar(_ s: String, into buf: inout ByteBuffer) {
219-
let utf16 = Array(s.utf16)
220-
buf.writeInteger(UInt8(utf16.count))
221-
for unit in utf16 { buf.writeInteger(unit, endianness: .little) }
219+
let utf16Bytes = s.data(using: .utf16LittleEndian) ?? Data()
220+
let charCount = utf16Bytes.count / 2
221+
buf.writeInteger(UInt8(charCount))
222+
buf.writeBytes(utf16Bytes)
222223
}
223224

224225
// MARK: - UUID mixed-endian (SQL Server format)

0 commit comments

Comments
 (0)