dynlib.nim 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements the ability to access symbols from shared
  10. ## libraries. On POSIX this uses the `dlsym` mechanism, on
  11. ## Windows `LoadLibrary`.
  12. ##
  13. ## Examples
  14. ## ========
  15. ##
  16. ## Loading a simple C function
  17. ## ---------------------------
  18. ##
  19. ## The following example demonstrates loading a function called `greet`
  20. ## from a library that is determined at runtime based upon a language choice.
  21. ## If the library fails to load or the function `greet` is not found,
  22. ## it quits with a failure error code.
  23. ##
  24. runnableExamples:
  25. type
  26. GreetFunction = proc (): cstring {.gcsafe, stdcall.}
  27. proc loadGreet(lang: string) =
  28. let lib =
  29. case lang
  30. of "french":
  31. loadLib("french.dll")
  32. else:
  33. loadLib("english.dll")
  34. assert lib != nil, "Error loading library"
  35. let greet = cast[GreetFunction](lib.symAddr("greet"))
  36. assert greet != nil, "Error loading 'greet' function from library"
  37. echo greet()
  38. unloadLib(lib)
  39. import std/strutils
  40. type
  41. LibHandle* = pointer ## A handle to a dynamically loaded library.
  42. proc loadLib*(path: string, globalSymbols = false): LibHandle {.gcsafe.}
  43. ## Loads a library from `path`. Returns nil if the library could not
  44. ## be loaded.
  45. proc loadLib*(): LibHandle {.gcsafe.}
  46. ## Gets the handle from the current executable. Returns nil if the
  47. ## library could not be loaded.
  48. proc unloadLib*(lib: LibHandle) {.gcsafe.}
  49. ## Unloads the library `lib`.
  50. proc raiseInvalidLibrary*(name: cstring) {.noinline, noreturn.} =
  51. ## Raises a `LibraryError` exception.
  52. raise newException(LibraryError, "could not find symbol: " & $name)
  53. proc symAddr*(lib: LibHandle, name: cstring): pointer {.gcsafe.}
  54. ## Retrieves the address of a procedure/variable from `lib`. Returns nil
  55. ## if the symbol could not be found.
  56. proc checkedSymAddr*(lib: LibHandle, name: cstring): pointer =
  57. ## Retrieves the address of a procedure/variable from `lib`. Raises
  58. ## `LibraryError` if the symbol could not be found.
  59. result = symAddr(lib, name)
  60. if result == nil: raiseInvalidLibrary(name)
  61. proc libCandidates*(s: string, dest: var seq[string]) =
  62. ## Given a library name pattern `s`, write possible library names to `dest`.
  63. var le = strutils.find(s, '(')
  64. var ri = strutils.find(s, ')', le+1)
  65. if le >= 0 and ri > le:
  66. var prefix = substr(s, 0, le - 1)
  67. var suffix = substr(s, ri + 1)
  68. for middle in split(substr(s, le + 1, ri - 1), '|'):
  69. libCandidates(prefix & middle & suffix, dest)
  70. else:
  71. add(dest, s)
  72. proc loadLibPattern*(pattern: string, globalSymbols = false): LibHandle =
  73. ## Loads a library with name matching `pattern`, similar to what the `dynlib`
  74. ## pragma does. Returns nil if the library could not be loaded.
  75. ##
  76. ## .. warning:: this proc uses the GC and so cannot be used to load the GC.
  77. var candidates = newSeq[string]()
  78. libCandidates(pattern, candidates)
  79. for c in candidates:
  80. result = loadLib(c, globalSymbols)
  81. if not result.isNil: break
  82. when defined(posix) and not defined(nintendoswitch):
  83. #
  84. # =========================================================================
  85. # This is an implementation based on the dlfcn interface.
  86. # The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
  87. # NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
  88. # as an emulation layer on top of native functions.
  89. # =========================================================================
  90. #
  91. import posix
  92. proc loadLib(path: string, globalSymbols = false): LibHandle =
  93. let flags =
  94. if globalSymbols: RTLD_NOW or RTLD_GLOBAL
  95. else: RTLD_NOW
  96. dlopen(path, flags)
  97. proc loadLib(): LibHandle = dlopen(nil, RTLD_NOW)
  98. proc unloadLib(lib: LibHandle) = discard dlclose(lib)
  99. proc symAddr(lib: LibHandle, name: cstring): pointer = dlsym(lib, name)
  100. elif defined(nintendoswitch):
  101. #
  102. # =========================================================================
  103. # Nintendo switch DevkitPro sdk does not have these. Raise an error if called.
  104. # =========================================================================
  105. #
  106. proc dlclose(lib: LibHandle) =
  107. raise newException(OSError, "dlclose not implemented on Nintendo Switch!")
  108. proc dlopen(path: cstring, mode: int): LibHandle =
  109. raise newException(OSError, "dlopen not implemented on Nintendo Switch!")
  110. proc dlsym(lib: LibHandle, name: cstring): pointer =
  111. raise newException(OSError, "dlsym not implemented on Nintendo Switch!")
  112. proc loadLib(path: string, global_symbols = false): LibHandle =
  113. raise newException(OSError, "loadLib not implemented on Nintendo Switch!")
  114. proc loadLib(): LibHandle =
  115. raise newException(OSError, "loadLib not implemented on Nintendo Switch!")
  116. proc unloadLib(lib: LibHandle) =
  117. raise newException(OSError, "unloadLib not implemented on Nintendo Switch!")
  118. proc symAddr(lib: LibHandle, name: cstring): pointer =
  119. raise newException(OSError, "symAddr not implemented on Nintendo Switch!")
  120. elif defined(genode):
  121. #
  122. # =========================================================================
  123. # Not implemented for Genode without POSIX. Raise an error if called.
  124. # =========================================================================
  125. #
  126. template raiseErr(prc: string) =
  127. raise newException(OSError, prc & " not implemented, compile with POSIX suport")
  128. proc dlclose(lib: LibHandle) =
  129. raiseErr(OSError, "dlclose")
  130. proc dlopen(path: cstring, mode: int): LibHandle =
  131. raiseErr(OSError, "dlopen")
  132. proc dlsym(lib: LibHandle, name: cstring): pointer =
  133. raiseErr(OSError, "dlsym")
  134. proc loadLib(path: string, global_symbols = false): LibHandle =
  135. raiseErr(OSError, "loadLib")
  136. proc loadLib(): LibHandle =
  137. raiseErr(OSError, "loadLib")
  138. proc unloadLib(lib: LibHandle) =
  139. raiseErr(OSError, "unloadLib")
  140. proc symAddr(lib: LibHandle, name: cstring): pointer =
  141. raiseErr(OSError, "symAddr")
  142. elif defined(windows) or defined(dos):
  143. #
  144. # =======================================================================
  145. # Native Windows Implementation
  146. # =======================================================================
  147. #
  148. type
  149. HMODULE {.importc: "HMODULE".} = pointer
  150. FARPROC {.importc: "FARPROC".} = pointer
  151. proc FreeLibrary(lib: HMODULE) {.importc, header: "<windows.h>", stdcall.}
  152. proc winLoadLibrary(path: cstring): HMODULE {.
  153. importc: "LoadLibraryA", header: "<windows.h>", stdcall.}
  154. proc getProcAddress(lib: HMODULE, name: cstring): FARPROC {.
  155. importc: "GetProcAddress", header: "<windows.h>", stdcall.}
  156. proc loadLib(path: string, globalSymbols = false): LibHandle =
  157. result = cast[LibHandle](winLoadLibrary(path))
  158. proc loadLib(): LibHandle =
  159. result = cast[LibHandle](winLoadLibrary(nil))
  160. proc unloadLib(lib: LibHandle) = FreeLibrary(cast[HMODULE](lib))
  161. proc symAddr(lib: LibHandle, name: cstring): pointer =
  162. result = cast[pointer](getProcAddress(cast[HMODULE](lib), name))
  163. else:
  164. {.error: "no implementation for dynlib".}