dynlib.nim 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. ## .. code-block::nim
  25. ##
  26. ## import dynlib
  27. ##
  28. ## type
  29. ## greetFunction = proc(): cstring {.gcsafe, stdcall.}
  30. ##
  31. ## let lang = stdin.readLine()
  32. ##
  33. ## let lib = case lang
  34. ## of "french":
  35. ## loadLib("french.dll")
  36. ## else:
  37. ## loadLib("english.dll")
  38. ##
  39. ## if lib == nil:
  40. ## echo "Error loading library"
  41. ## quit(QuitFailure)
  42. ##
  43. ## let greet = cast[greetFunction](lib.symAddr("greet"))
  44. ##
  45. ## if greet == nil:
  46. ## echo "Error loading 'greet' function from library"
  47. ## quit(QuitFailure)
  48. ##
  49. ## let greeting = greet()
  50. ##
  51. ## echo greeting
  52. ##
  53. ## unloadLib(lib)
  54. ##
  55. import strutils
  56. type
  57. LibHandle* = pointer ## a handle to a dynamically loaded library
  58. proc loadLib*(path: string, globalSymbols = false): LibHandle {.gcsafe.}
  59. ## loads a library from `path`. Returns nil if the library could not
  60. ## be loaded.
  61. proc loadLib*(): LibHandle {.gcsafe.}
  62. ## gets the handle from the current executable. Returns nil if the
  63. ## library could not be loaded.
  64. proc unloadLib*(lib: LibHandle) {.gcsafe.}
  65. ## unloads the library `lib`
  66. proc raiseInvalidLibrary*(name: cstring) {.noinline, noreturn.} =
  67. ## raises an `EInvalidLibrary` exception.
  68. raise newException(LibraryError, "could not find symbol: " & $name)
  69. proc symAddr*(lib: LibHandle, name: cstring): pointer {.gcsafe.}
  70. ## retrieves the address of a procedure/variable from `lib`. Returns nil
  71. ## if the symbol could not be found.
  72. proc checkedSymAddr*(lib: LibHandle, name: cstring): pointer =
  73. ## retrieves the address of a procedure/variable from `lib`. Raises
  74. ## `EInvalidLibrary` if the symbol could not be found.
  75. result = symAddr(lib, name)
  76. if result == nil: raiseInvalidLibrary(name)
  77. proc libCandidates*(s: string, dest: var seq[string]) =
  78. ## given a library name pattern `s` write possible library names to `dest`.
  79. var le = strutils.find(s, '(')
  80. var ri = strutils.find(s, ')', le+1)
  81. if le >= 0 and ri > le:
  82. var prefix = substr(s, 0, le - 1)
  83. var suffix = substr(s, ri + 1)
  84. for middle in split(substr(s, le + 1, ri - 1), '|'):
  85. libCandidates(prefix & middle & suffix, dest)
  86. else:
  87. add(dest, s)
  88. proc loadLibPattern*(pattern: string, globalSymbols = false): LibHandle =
  89. ## loads a library with name matching `pattern`, similar to what `dynlib`
  90. ## pragma does. Returns nil if the library could not be loaded.
  91. ## Warning: this proc uses the GC and so cannot be used to load the GC.
  92. var candidates = newSeq[string]()
  93. libCandidates(pattern, candidates)
  94. for c in candidates:
  95. result = loadLib(c, globalSymbols)
  96. if not result.isNil: break
  97. when defined(posix) and not defined(nintendoswitch):
  98. #
  99. # =========================================================================
  100. # This is an implementation based on the dlfcn interface.
  101. # The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
  102. # NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
  103. # as an emulation layer on top of native functions.
  104. # =========================================================================
  105. #
  106. import posix
  107. proc loadLib(path: string, globalSymbols = false): LibHandle =
  108. let flags =
  109. if globalSymbols: RTLD_NOW or RTLD_GLOBAL
  110. else: RTLD_NOW
  111. dlopen(path, flags)
  112. proc loadLib(): LibHandle = dlopen(nil, RTLD_NOW)
  113. proc unloadLib(lib: LibHandle) = discard dlclose(lib)
  114. proc symAddr(lib: LibHandle, name: cstring): pointer = dlsym(lib, name)
  115. elif defined(nintendoswitch):
  116. #
  117. # =========================================================================
  118. # Nintendo switch DevkitPro sdk does not have these. Raise an error if called.
  119. # =========================================================================
  120. #
  121. proc dlclose(lib: LibHandle) =
  122. raise newException(OSError, "dlclose not implemented on Nintendo Switch!")
  123. proc dlopen(path: cstring, mode: int): LibHandle =
  124. raise newException(OSError, "dlopen not implemented on Nintendo Switch!")
  125. proc dlsym(lib: LibHandle, name: cstring): pointer =
  126. raise newException(OSError, "dlsym not implemented on Nintendo Switch!")
  127. proc loadLib(path: string, global_symbols = false): LibHandle =
  128. raise newException(OSError, "loadLib not implemented on Nintendo Switch!")
  129. proc loadLib(): LibHandle =
  130. raise newException(OSError, "loadLib not implemented on Nintendo Switch!")
  131. proc unloadLib(lib: LibHandle) =
  132. raise newException(OSError, "unloadLib not implemented on Nintendo Switch!")
  133. proc symAddr(lib: LibHandle, name: cstring): pointer =
  134. raise newException(OSError, "symAddr not implemented on Nintendo Switch!")
  135. elif defined(windows) or defined(dos):
  136. #
  137. # =======================================================================
  138. # Native Windows Implementation
  139. # =======================================================================
  140. #
  141. type
  142. HMODULE {.importc: "HMODULE".} = pointer
  143. FARPROC {.importc: "FARPROC".} = pointer
  144. proc FreeLibrary(lib: HMODULE) {.importc, header: "<windows.h>", stdcall.}
  145. proc winLoadLibrary(path: cstring): HMODULE {.
  146. importc: "LoadLibraryA", header: "<windows.h>", stdcall.}
  147. proc getProcAddress(lib: HMODULE, name: cstring): FARPROC {.
  148. importc: "GetProcAddress", header: "<windows.h>", stdcall.}
  149. proc loadLib(path: string, globalSymbols = false): LibHandle =
  150. result = cast[LibHandle](winLoadLibrary(path))
  151. proc loadLib(): LibHandle =
  152. result = cast[LibHandle](winLoadLibrary(nil))
  153. proc unloadLib(lib: LibHandle) = FreeLibrary(cast[HMODULE](lib))
  154. proc symAddr(lib: LibHandle, name: cstring): pointer =
  155. result = cast[pointer](getProcAddress(cast[HMODULE](lib), name))
  156. else:
  157. {.error: "no implementation for dynlib".}