From a9aebc0cd4131e5ece4db30a7e04f79b84815f80 Mon Sep 17 00:00:00 2001 From: Eric Sink Date: Wed, 26 Jun 2019 15:00:57 -0500 Subject: [PATCH] make sz more robust in handling edge cases, null pointers #273 --- Directory.Build.props | 2 +- src/SQLitePCLRaw.core/util.cs | 42 +++++++++++++++++++++++++++++++---- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 2acfadf0..f35985a4 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -4,7 +4,7 @@ Copyright 2014-2019 SourceGear, LLC SourceGear Eric Sink - 2.0.0-pre20190626125110 + 2.0.0-pre20190626145402 2.0.0.541 2.0.0.541 SQLitePCLRaw is a Portable Class Library (PCL) for low-level (raw) access to SQLite diff --git a/src/SQLitePCLRaw.core/util.cs b/src/SQLitePCLRaw.core/util.cs index bc21756b..61c3ff55 100644 --- a/src/SQLitePCLRaw.core/util.cs +++ b/src/SQLitePCLRaw.core/util.cs @@ -41,7 +41,10 @@ public ref readonly byte GetPinnableReference() sz(ReadOnlySpan a) { - if (a[a.Length - 1] != 0) + if ( + (a.Length > 0) + && (a[a.Length - 1] != 0) + ) { throw new ArgumentException("zero terminated string required"); } @@ -50,7 +53,14 @@ public ref readonly byte GetPinnableReference() public static sz FromString(string s) { - return new sz(s.to_utf8_with_z()); + if (s == null) + { + return new sz(ReadOnlySpan.Empty); + } + else + { + return new sz(s.to_utf8_with_z()); + } } unsafe static long my_strlen(byte* p) @@ -76,16 +86,35 @@ unsafe static ReadOnlySpan to_span(IntPtr p) unsafe public static sz FromPtr(byte* p) { - return new sz(to_span(p)); + if (p == null) + { + return new sz(ReadOnlySpan.Empty); + } + else + { + return new sz(to_span(p)); + } } public static sz FromIntPtr(IntPtr p) { - return new sz(to_span(p)); + if (p == IntPtr.Zero) + { + return new sz(ReadOnlySpan.Empty); + } + else + { + return new sz(to_span(p)); + } } public override string ToString() { + if (sp.Length == 0) + { + return null; + } + unsafe { fixed (byte* q = sp) @@ -98,6 +127,11 @@ public override string ToString() static class util { + public static sz to_sz(this string s) + { + return sz.FromString(s); + } + public static byte[] to_utf8_with_z(this string sourceText) { if (sourceText == null)