Shared.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Runtime.CompilerServices;
  7. using System.Runtime.InteropServices;
  8. using System.Threading;
  9. using Avalonia.Platform;
  10. using Avalonia.Platform.Interop;
  11. using Avalonia.Utilities;
  12. namespace Avalonia.Shared.PlatformSupport
  13. {
  14. static class StandardRuntimePlatformServices
  15. {
  16. public static void Register(Assembly assembly = null)
  17. {
  18. var standardPlatform = new StandardRuntimePlatform();
  19. AssetLoader.RegisterResUriParsers();
  20. AvaloniaLocator.CurrentMutable
  21. .Bind<IRuntimePlatform>().ToConstant(standardPlatform)
  22. .Bind<IAssetLoader>().ToConstant(new AssetLoader(assembly))
  23. .Bind<IDynamicLibraryLoader>().ToConstant(
  24. #if __IOS__
  25. new IOSLoader()
  26. #else
  27. RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
  28. ? (IDynamicLibraryLoader)new Win32Loader()
  29. : new UnixLoader()
  30. #endif
  31. );
  32. }
  33. }
  34. internal partial class StandardRuntimePlatform : IRuntimePlatform
  35. {
  36. public IDisposable StartSystemTimer(TimeSpan interval, Action tick)
  37. {
  38. return new Timer(_ => tick(), null, interval, interval);
  39. }
  40. public IUnmanagedBlob AllocBlob(int size) => new UnmanagedBlob(this, size);
  41. class UnmanagedBlob : IUnmanagedBlob
  42. {
  43. private readonly StandardRuntimePlatform _plat;
  44. private IntPtr _address;
  45. private readonly object _lock = new object();
  46. #if DEBUG
  47. private static readonly List<string> Backtraces = new List<string>();
  48. private static Thread GCThread;
  49. private readonly string _backtrace;
  50. private static readonly object _btlock = new object();
  51. class GCThreadDetector
  52. {
  53. ~GCThreadDetector()
  54. {
  55. GCThread = Thread.CurrentThread;
  56. }
  57. }
  58. [MethodImpl(MethodImplOptions.NoInlining)]
  59. static void Spawn() => new GCThreadDetector();
  60. static UnmanagedBlob()
  61. {
  62. Spawn();
  63. GC.WaitForPendingFinalizers();
  64. }
  65. #endif
  66. public UnmanagedBlob(StandardRuntimePlatform plat, int size)
  67. {
  68. if (size <= 0)
  69. throw new ArgumentException("Positive number required", nameof(size));
  70. _plat = plat;
  71. _address = plat.Alloc(size);
  72. GC.AddMemoryPressure(size);
  73. Size = size;
  74. #if DEBUG
  75. _backtrace = Environment.StackTrace;
  76. lock (_btlock)
  77. Backtraces.Add(_backtrace);
  78. #endif
  79. }
  80. void DoDispose()
  81. {
  82. lock (_lock)
  83. {
  84. if (!IsDisposed)
  85. {
  86. #if DEBUG
  87. lock (_btlock)
  88. Backtraces.Remove(_backtrace);
  89. #endif
  90. _plat?.Free(_address, Size);
  91. GC.RemoveMemoryPressure(Size);
  92. IsDisposed = true;
  93. _address = IntPtr.Zero;
  94. Size = 0;
  95. }
  96. }
  97. }
  98. public void Dispose()
  99. {
  100. #if DEBUG
  101. if (Thread.CurrentThread.ManagedThreadId == GCThread?.ManagedThreadId)
  102. {
  103. lock (_lock)
  104. {
  105. if (!IsDisposed)
  106. {
  107. Console.Error.WriteLine("Native blob disposal from finalizer thread\nBacktrace: "
  108. + Environment.StackTrace
  109. + "\n\nBlob created by " + _backtrace);
  110. }
  111. }
  112. }
  113. #endif
  114. DoDispose();
  115. GC.SuppressFinalize(this);
  116. }
  117. ~UnmanagedBlob()
  118. {
  119. #if DEBUG
  120. Console.Error.WriteLine("Undisposed native blob created by " + _backtrace);
  121. #endif
  122. DoDispose();
  123. }
  124. public IntPtr Address => IsDisposed ? throw new ObjectDisposedException("UnmanagedBlob") : _address;
  125. public int Size { get; private set; }
  126. public bool IsDisposed { get; private set; }
  127. }
  128. #if NET462 || NETCOREAPP2_0
  129. [DllImport("libc", SetLastError = true)]
  130. private static extern IntPtr mmap(IntPtr addr, IntPtr length, int prot, int flags, int fd, IntPtr offset);
  131. [DllImport("libc", SetLastError = true)]
  132. private static extern int munmap(IntPtr addr, IntPtr length);
  133. [DllImport("libc", SetLastError = true)]
  134. private static extern long sysconf(int name);
  135. private bool? _useMmap;
  136. private bool UseMmap
  137. => _useMmap ?? ((_useMmap = GetRuntimeInfo().OperatingSystem == OperatingSystemType.Linux)).Value;
  138. IntPtr Alloc(int size)
  139. {
  140. if (UseMmap)
  141. {
  142. var rv = mmap(IntPtr.Zero, new IntPtr(size), 3, 0x22, -1, IntPtr.Zero);
  143. if (rv.ToInt64() == -1 || (ulong) rv.ToInt64() == 0xffffffff)
  144. {
  145. var errno = Marshal.GetLastWin32Error();
  146. throw new Exception("Unable to allocate memory: " + errno);
  147. }
  148. return rv;
  149. }
  150. else
  151. return Marshal.AllocHGlobal(size);
  152. }
  153. void Free(IntPtr ptr, int len)
  154. {
  155. if (UseMmap)
  156. {
  157. if (munmap(ptr, new IntPtr(len)) == -1)
  158. {
  159. var errno = Marshal.GetLastWin32Error();
  160. throw new Exception("Unable to free memory: " + errno);
  161. }
  162. }
  163. else
  164. Marshal.FreeHGlobal(ptr);
  165. }
  166. #else
  167. IntPtr Alloc(int size) => Marshal.AllocHGlobal(size);
  168. void Free(IntPtr ptr, int len) => Marshal.FreeHGlobal(ptr);
  169. #endif
  170. }
  171. internal class IOSLoader : IDynamicLibraryLoader
  172. {
  173. IntPtr IDynamicLibraryLoader.LoadLibrary(string dll)
  174. {
  175. throw new PlatformNotSupportedException();
  176. }
  177. IntPtr IDynamicLibraryLoader.GetProcAddress(IntPtr dll, string proc, bool optional)
  178. {
  179. throw new PlatformNotSupportedException();
  180. }
  181. }
  182. public class AssetLoader : IAssetLoader
  183. {
  184. private const string AvaloniaResourceName = "!AvaloniaResources";
  185. private static readonly Dictionary<string, AssemblyDescriptor> AssemblyNameCache
  186. = new Dictionary<string, AssemblyDescriptor>();
  187. private AssemblyDescriptor _defaultResmAssembly;
  188. /// <summary>
  189. /// Initializes a new instance of the <see cref="AssetLoader"/> class.
  190. /// </summary>
  191. /// <param name="assembly">
  192. /// The default assembly from which to load resm: assets for which no assembly is specified.
  193. /// </param>
  194. public AssetLoader(Assembly assembly = null)
  195. {
  196. if (assembly == null)
  197. assembly = Assembly.GetEntryAssembly();
  198. if (assembly != null)
  199. _defaultResmAssembly = new AssemblyDescriptor(assembly);
  200. }
  201. /// <summary>
  202. /// Sets the default assembly from which to load assets for which no assembly is specified.
  203. /// </summary>
  204. /// <param name="assembly">The default assembly.</param>
  205. public void SetDefaultAssembly(Assembly assembly)
  206. {
  207. _defaultResmAssembly = new AssemblyDescriptor(assembly);
  208. }
  209. /// <summary>
  210. /// Checks if an asset with the specified URI exists.
  211. /// </summary>
  212. /// <param name="uri">The URI.</param>
  213. /// <param name="baseUri">
  214. /// A base URI to use if <paramref name="uri"/> is relative.
  215. /// </param>
  216. /// <returns>True if the asset could be found; otherwise false.</returns>
  217. public bool Exists(Uri uri, Uri baseUri = null)
  218. {
  219. return GetAsset(uri, baseUri) != null;
  220. }
  221. /// <summary>
  222. /// Opens the asset with the requested URI.
  223. /// </summary>
  224. /// <param name="uri">The URI.</param>
  225. /// <param name="baseUri">
  226. /// A base URI to use if <paramref name="uri"/> is relative.
  227. /// </param>
  228. /// <returns>A stream containing the asset contents.</returns>
  229. /// <exception cref="FileNotFoundException">
  230. /// The asset could not be found.
  231. /// </exception>
  232. public Stream Open(Uri uri, Uri baseUri = null) => OpenAndGetAssembly(uri, baseUri).Item1;
  233. /// <summary>
  234. /// Opens the asset with the requested URI and returns the asset stream and the
  235. /// assembly containing the asset.
  236. /// </summary>
  237. /// <param name="uri">The URI.</param>
  238. /// <param name="baseUri">
  239. /// A base URI to use if <paramref name="uri"/> is relative.
  240. /// </param>
  241. /// <returns>
  242. /// The stream containing the resource contents together with the assembly.
  243. /// </returns>
  244. /// <exception cref="FileNotFoundException">
  245. /// The asset could not be found.
  246. /// </exception>
  247. public (Stream stream, Assembly assembly) OpenAndGetAssembly(Uri uri, Uri baseUri = null)
  248. {
  249. var asset = GetAsset(uri, baseUri);
  250. if (asset == null)
  251. {
  252. throw new FileNotFoundException($"The resource {uri} could not be found.");
  253. }
  254. return (asset.GetStream(), asset.Assembly);
  255. }
  256. public Assembly GetAssembly(Uri uri, Uri baseUri)
  257. {
  258. if (!uri.IsAbsoluteUri && baseUri != null)
  259. uri = new Uri(baseUri, uri);
  260. return GetAssembly(uri).Assembly;
  261. }
  262. /// <summary>
  263. /// Gets all assets of a folder and subfolders that match specified uri.
  264. /// </summary>
  265. /// <param name="uri">The URI.</param>
  266. /// <param name="baseUri">Base URI that is used if <paramref name="uri"/> is relative.</param>
  267. /// <returns>All matching assets as a tuple of the absolute path to the asset and the assembly containing the asset</returns>
  268. public IEnumerable<Uri> GetAssets(Uri uri, Uri baseUri)
  269. {
  270. if (uri.IsAbsoluteUri && uri.Scheme == "resm")
  271. {
  272. var assembly = GetAssembly(uri);
  273. return assembly?.Resources.Where(x => x.Key.Contains(uri.AbsolutePath))
  274. .Select(x =>new Uri($"resm:{x.Key}?assembly={assembly.Name}")) ??
  275. Enumerable.Empty<Uri>();
  276. }
  277. uri = EnsureAbsolute(uri, baseUri);
  278. if (uri.Scheme == "avares")
  279. {
  280. var (asm, path) = GetResAsmAndPath(uri);
  281. if (asm == null)
  282. {
  283. throw new ArgumentException(
  284. "No default assembly, entry assembly or explicit assembly specified; " +
  285. "don't know where to look up for the resource, try specifying assembly explicitly.");
  286. }
  287. if (asm?.AvaloniaResources == null)
  288. return Enumerable.Empty<Uri>();
  289. path = path.TrimEnd('/') + '/';
  290. return asm.AvaloniaResources.Where(r => r.Key.StartsWith(path))
  291. .Select(x => new Uri($"avares://{asm.Name}{x.Key}"));
  292. }
  293. return Enumerable.Empty<Uri>();
  294. }
  295. private Uri EnsureAbsolute(Uri uri, Uri baseUri)
  296. {
  297. if (uri.IsAbsoluteUri)
  298. return uri;
  299. if(baseUri == null)
  300. throw new ArgumentException($"Relative uri {uri} without base url");
  301. if (!baseUri.IsAbsoluteUri)
  302. throw new ArgumentException($"Base uri {baseUri} is relative");
  303. if (baseUri.Scheme == "resm")
  304. throw new ArgumentException(
  305. $"Relative uris for 'resm' scheme aren't supported; {baseUri} uses resm");
  306. return new Uri(baseUri, uri);
  307. }
  308. private IAssetDescriptor GetAsset(Uri uri, Uri baseUri)
  309. {
  310. if (uri.IsAbsoluteUri && uri.Scheme == "resm")
  311. {
  312. var asm = GetAssembly(uri) ?? GetAssembly(baseUri) ?? _defaultResmAssembly;
  313. if (asm == null)
  314. {
  315. throw new ArgumentException(
  316. "No default assembly, entry assembly or explicit assembly specified; " +
  317. "don't know where to look up for the resource, try specifying assembly explicitly.");
  318. }
  319. IAssetDescriptor rv;
  320. var resourceKey = uri.AbsolutePath;
  321. asm.Resources.TryGetValue(resourceKey, out rv);
  322. return rv;
  323. }
  324. uri = EnsureAbsolute(uri, baseUri);
  325. if (uri.Scheme == "avares")
  326. {
  327. var (asm, path) = GetResAsmAndPath(uri);
  328. if (asm.AvaloniaResources == null)
  329. return null;
  330. asm.AvaloniaResources.TryGetValue(path, out var desc);
  331. return desc;
  332. }
  333. throw new ArgumentException($"Unsupported url type: " + uri.Scheme, nameof(uri));
  334. }
  335. private (AssemblyDescriptor asm, string path) GetResAsmAndPath(Uri uri)
  336. {
  337. var asm = GetAssembly(uri.Authority);
  338. return (asm, uri.AbsolutePath);
  339. }
  340. private AssemblyDescriptor GetAssembly(Uri uri)
  341. {
  342. if (uri != null)
  343. {
  344. if (!uri.IsAbsoluteUri)
  345. return null;
  346. if (uri.Scheme == "avares")
  347. return GetResAsmAndPath(uri).asm;
  348. if (uri.Scheme == "resm")
  349. {
  350. var qs = ParseQueryString(uri);
  351. string assemblyName;
  352. if (qs.TryGetValue("assembly", out assemblyName))
  353. {
  354. return GetAssembly(assemblyName);
  355. }
  356. }
  357. }
  358. return null;
  359. }
  360. private AssemblyDescriptor GetAssembly(string name)
  361. {
  362. if (name == null)
  363. throw new ArgumentNullException(nameof(name));
  364. AssemblyDescriptor rv;
  365. if (!AssemblyNameCache.TryGetValue(name, out rv))
  366. {
  367. var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
  368. var match = loadedAssemblies.FirstOrDefault(a => a.GetName().Name == name);
  369. if (match != null)
  370. {
  371. AssemblyNameCache[name] = rv = new AssemblyDescriptor(match);
  372. }
  373. else
  374. {
  375. // iOS does not support loading assemblies dynamically!
  376. //
  377. #if __IOS__
  378. throw new InvalidOperationException(
  379. $"Assembly {name} needs to be referenced and explicitly loaded before loading resources");
  380. #else
  381. name = Uri.UnescapeDataString(name);
  382. AssemblyNameCache[name] = rv = new AssemblyDescriptor(Assembly.Load(name));
  383. #endif
  384. }
  385. }
  386. return rv;
  387. }
  388. private Dictionary<string, string> ParseQueryString(Uri uri)
  389. {
  390. return uri.Query.TrimStart('?')
  391. .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
  392. .Select(p => p.Split('='))
  393. .ToDictionary(p => p[0], p => p[1]);
  394. }
  395. private interface IAssetDescriptor
  396. {
  397. Stream GetStream();
  398. Assembly Assembly { get; }
  399. }
  400. private class AssemblyResourceDescriptor : IAssetDescriptor
  401. {
  402. private readonly Assembly _asm;
  403. private readonly string _name;
  404. public AssemblyResourceDescriptor(Assembly asm, string name)
  405. {
  406. _asm = asm;
  407. _name = name;
  408. }
  409. public Stream GetStream()
  410. {
  411. return _asm.GetManifestResourceStream(_name);
  412. }
  413. public Assembly Assembly => _asm;
  414. }
  415. private class AvaloniaResourceDescriptor : IAssetDescriptor
  416. {
  417. private readonly int _offset;
  418. private readonly int _length;
  419. public Assembly Assembly { get; }
  420. public AvaloniaResourceDescriptor(Assembly asm, int offset, int length)
  421. {
  422. _offset = offset;
  423. _length = length;
  424. Assembly = asm;
  425. }
  426. public Stream GetStream()
  427. {
  428. return new SlicedStream(Assembly.GetManifestResourceStream(AvaloniaResourceName), _offset, _length);
  429. }
  430. }
  431. class SlicedStream : Stream
  432. {
  433. private readonly Stream _baseStream;
  434. private readonly int _from;
  435. public SlicedStream(Stream baseStream, int from, int length)
  436. {
  437. Length = length;
  438. _baseStream = baseStream;
  439. _from = from;
  440. _baseStream.Position = from;
  441. }
  442. public override void Flush()
  443. {
  444. }
  445. public override int Read(byte[] buffer, int offset, int count)
  446. {
  447. return _baseStream.Read(buffer, offset, (int)Math.Min(count, Length - Position));
  448. }
  449. public override long Seek(long offset, SeekOrigin origin)
  450. {
  451. if (origin == SeekOrigin.Begin)
  452. Position = offset;
  453. if (origin == SeekOrigin.End)
  454. Position = _from + Length + offset;
  455. if (origin == SeekOrigin.Current)
  456. Position = Position + offset;
  457. return Position;
  458. }
  459. public override void SetLength(long value) => throw new NotSupportedException();
  460. public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
  461. public override bool CanRead => true;
  462. public override bool CanSeek => _baseStream.CanRead;
  463. public override bool CanWrite => false;
  464. public override long Length { get; }
  465. public override long Position
  466. {
  467. get => _baseStream.Position - _from;
  468. set => _baseStream.Position = value + _from;
  469. }
  470. protected override void Dispose(bool disposing)
  471. {
  472. if (disposing)
  473. _baseStream.Dispose();
  474. }
  475. public override void Close() => _baseStream.Close();
  476. }
  477. private class AssemblyDescriptor
  478. {
  479. public AssemblyDescriptor(Assembly assembly)
  480. {
  481. Assembly = assembly;
  482. if (assembly != null)
  483. {
  484. Resources = assembly.GetManifestResourceNames()
  485. .ToDictionary(n => n, n => (IAssetDescriptor)new AssemblyResourceDescriptor(assembly, n));
  486. Name = assembly.GetName().Name;
  487. using (var resources = assembly.GetManifestResourceStream(AvaloniaResourceName))
  488. {
  489. if (resources != null)
  490. {
  491. Resources.Remove(AvaloniaResourceName);
  492. var indexLength = new BinaryReader(resources).ReadInt32();
  493. var index = AvaloniaResourcesIndexReaderWriter.Read(new SlicedStream(resources, 4, indexLength));
  494. var baseOffset = indexLength + 4;
  495. AvaloniaResources = index.ToDictionary(r => "/" + r.Path.TrimStart('/'), r => (IAssetDescriptor)
  496. new AvaloniaResourceDescriptor(assembly, baseOffset + r.Offset, r.Size));
  497. }
  498. }
  499. }
  500. }
  501. public Assembly Assembly { get; }
  502. public Dictionary<string, IAssetDescriptor> Resources { get; }
  503. public Dictionary<string, IAssetDescriptor> AvaloniaResources { get; }
  504. public string Name { get; }
  505. }
  506. public static void RegisterResUriParsers()
  507. {
  508. if (!UriParser.IsKnownScheme("avares"))
  509. UriParser.Register(new GenericUriParser(
  510. GenericUriParserOptions.GenericAuthority |
  511. GenericUriParserOptions.NoUserInfo |
  512. GenericUriParserOptions.NoPort |
  513. GenericUriParserOptions.NoQuery |
  514. GenericUriParserOptions.NoFragment), "avares", -1);
  515. }
  516. }
  517. }