summary refs log tree commit diff stats
path: root/lib/pure/includes/oserr.nim
blob: 138aa127d050c1a798e69020a7d753e5da48dc41 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# Include file that implements 'osErrorMsg' and friends. Do not import it!

when not declared(os) and not declared(ospaths):
  {.error: "This is an include file for os.nim!".}

when not defined(nimscript):
  var errno {.importc, header: "<errno.h>".}: cint

  proc c_strerror(errnum: cint): cstring {.
    importc: "strerror", header: "<string.h>".}

  when defined(windows):
    import winlean

proc `==`*(err1, err2: OSErrorCode): bool {.borrow.}
proc `$`*(err: OSErrorCode): string {.borrow.}

proc osErrorMsg*(errorCode: OSErrorCode): string =
  ## Converts an OS error code into a human readable string.
  ##
  ## The error code can be retrieved using the `osLastError proc <#osLastError>`_.
  ##
  ## If conversion fails, or ``errorCode`` is ``0`` then ``""`` will be
  ## returned.
  ##
  ## On Windows, the ``-d:useWinAnsi`` compilation flag can be used to
  ## make this procedure use the non-unicode Win API calls to retrieve the
  ## message.
  ##
  ## See also:
  ## * `raiseOSError proc <#raiseOSError,OSErrorCode,string>`_
  ## * `osLastError proc <#osLastError>`_
  runnableExamples:
    when defined(linux):
      assert osErrorMsg(OSErrorCode(0)) == ""
      assert osErrorMsg(OSErrorCode(1)) == "Operation not permitted"
      assert osErrorMsg(OSErrorCode(2)) == "No such file or directory"

  result = ""
  when defined(nimscript):
    discard
  elif defined(Windows):
    if errorCode != OSErrorCode(0'i32):
      when useWinUnicode:
        var msgbuf: WideCString
        if formatMessageW(0x00000100 or 0x00001000 or 0x00000200,
                        nil, errorCode.int32, 0, addr(msgbuf), 0, nil) != 0'i32:
          result = $msgbuf
          if msgbuf != nil: localFree(cast[pointer](msgbuf))
      else:
        var msgbuf: cstring
        if formatMessageA(0x00000100 or 0x00001000 or 0x00000200,
                        nil, errorCode.int32, 0, addr(msgbuf), 0, nil) != 0'i32:
          result = $msgbuf
          if msgbuf != nil: localFree(msgbuf)
  else:
    if errorCode != OSErrorCode(0'i32):
      result = $c_strerror(errorCode.int32)

proc newOSError*(
  errorCode: OSErrorCode, additionalInfo = ""
): owned(ref OSError) {.noinline.} =
  ## Creates a new `OSError exception <system.html#OSError>`_.
  ##
  ## The ``errorCode`` will determine the
  ## message, `osErrorMsg proc <#osErrorMsg,OSErrorCode>`_ will be used
  ## to get this message.
  ##
  ## The error code can be retrieved using the `osLastError proc
  ## <#osLastError>`_.
  ##
  ## If the error code is ``0`` or an error message could not be retrieved,
  ## the message ``unknown OS error`` will be used.
  ##
  ## See also:
  ## * `osErrorMsg proc <#osErrorMsg,OSErrorCode>`_
  ## * `osLastError proc <#osLastError>`_
  var e: owned(ref OSError); new(e)
  e.errorCode = errorCode.int32
  e.msg = osErrorMsg(errorCode)
  if additionalInfo.len > 0:
    if e.msg.len > 0 and e.msg[^1] != '\n': e.msg.add '\n'
    e.msg.add  "Additional info: "
    e.msg.addQuoted additionalInfo
  if e.msg == "":
    e.msg = "unknown OS error"
  return e

proc raiseOSError*(errorCode: OSErrorCode, additionalInfo = "") {.noinline.} =
  ## Raises an `OSError exception <system.html#OSError>`_.
  ##
  ## Read the description of the `newOSError proc <#newOSError,OSErrorCode,string>`_ to learn
  ## how the exception object is created.
  raise newOSError(errorCode, additionalInfo)

{.push stackTrace:off.}
proc osLastError*(): OSErrorCode {.sideEffect.} =
  ## Retrieves the last operating system error code.
  ##
  ## This procedure is useful in the event when an OS call fails. In that case
  ## this procedure will return the error code describing the reason why the
  ## OS call failed. The ``OSErrorMsg`` procedure can then be used to convert
  ## this code into a string.
  ##
  ## **Warning**:
  ## The behaviour of this procedure varies between Windows and POSIX systems.
  ## On Windows some OS calls can reset the error code to ``0`` causing this
  ## procedure to return ``0``. It is therefore advised to call this procedure
  ## immediately after an OS call fails. On POSIX systems this is not a problem.
  ##
  ## See also:
  ## * `osErrorMsg proc <#osErrorMsg,OSErrorCode>`_
  ## * `raiseOSError proc <#raiseOSError,OSErrorCode,string>`_
  when defined(nimscript):
    discard
  elif defined(windows):
    result = OSErrorCode(getLastError())
  else:
    result = OSErrorCode(errno)
{.pop.}
flicts*: CountTable[string] TTypeSeq* = seq[PType] TypeCache* = Table[SigHash, Rope] TypeCacheWithOwner* = Table[SigHash, tuple[str: Rope, owner: int32]] CodegenFlag* = enum preventStackTrace, # true if stack traces need to be prevented usesThreadVars, # true if the module uses a thread var frameDeclared, # hack for ROD support so that we don't declare # a frame var twice in an init proc isHeaderFile, # C source file is the header file includesStringh, # C source file already includes ``<string.h>`` objHasKidsValid # whether we can rely on tfObjHasKids useAliveDataFromDce # use the `alive: IntSet` field instead of # computing alive data on our own. BModuleList* = ref object of RootObj mainModProcs*, mainModInit*, otherModsInit*, mainDatInit*: Rope mapping*: Rope # the generated mapping file (if requested) modules*: seq[BModule] # list of all compiled modules modulesClosed*: seq[BModule] # list of the same compiled modules, but in the order they were closed forwardedProcs*: seq[PSym] # proc:s that did not yet have a body generatedHeader*: BModule typeInfoMarker*: TypeCacheWithOwner typeInfoMarkerV2*: TypeCacheWithOwner config*: ConfigRef graph*: ModuleGraph strVersion*, seqVersion*: int # version of the string/seq implementation to use nimtv*: Rope # Nim thread vars; the struct body nimtvDeps*: seq[PType] # type deps: every module needs whole struct nimtvDeclared*: IntSet # so that every var/field exists only once # in the struct # 'nimtv' is incredibly hard to modularize! Best # effort is to store all thread vars in a ROD # section and with their type deps and load them # unconditionally... # nimtvDeps is VERY hard to cache because it's # not a list of IDs nor can it be made to be one. TCGen = object of PPassContext # represents a C source file s*: TCFileSections # sections of the C file flags*: set[CodegenFlag] module*: PSym filename*: AbsoluteFile cfilename*: AbsoluteFile # filename of the module (including path, # without extension) tmpBase*: Rope # base for temp identifier generation typeCache*: TypeCache # cache the generated types typeABICache*: HashSet[SigHash] # cache for ABI checks; reusing typeCache # would be ideal but for some reason enums # don't seem to get cached so it'd generate # 1 ABI check per occurence in code forwTypeCache*: TypeCache # cache for forward declarations of types declaredThings*: IntSet # things we have declared in this .c file declaredProtos*: IntSet # prototypes we have declared in this .c file alive*: IntSet # symbol IDs of alive data as computed by `dce.nim` headerFiles*: seq[string] # needed headers to include typeInfoMarker*: TypeCache # needed for generating type information typeInfoMarkerV2*: TypeCache initProc*: BProc # code for init procedure preInitProc*: BProc # code executed before the init proc hcrCreateTypeInfosProc*: Rope # type info globals are in here when HCR=on inHcrInitGuard*: bool # We are currently within a HCR reloading guard. typeStack*: TTypeSeq # used for type generation dataCache*: TNodeTable typeNodes*, nimTypes*: int # used for type info generation typeNodesName*, nimTypesName*: Rope # used for type info generation labels*: Natural # for generating unique module-scope names extensionLoaders*: array['0'..'9', Rope] # special procs for the # OpenGL wrapper injectStmt*: Rope sigConflicts*: CountTable[SigHash] g*: BModuleList ndi*: NdiFile template config*(m: BModule): ConfigRef = m.g.config template config*(p: BProc): ConfigRef = p.module.g.config proc includeHeader*(this: BModule; header: string) = if not this.headerFiles.contains header: this.headerFiles.add header proc s*(p: BProc, s: TCProcSection): var Rope {.inline.} = # section in the current block result = p.blocks[^1].sections[s] proc procSec*(p: BProc, s: TCProcSection): var Rope {.inline.} = # top level proc sections result = p.blocks[0].sections[s] proc newProc*(prc: PSym, module: BModule): BProc = new(result) result.prc = prc result.module = module result.options = if prc != nil: prc.options else: module.config.options newSeq(result.blocks, 1) result.nestedTryStmts = @[] result.finallySafePoints = @[] result.sigConflicts = initCountTable[string]() proc newModuleList*(g: ModuleGraph): BModuleList = BModuleList(typeInfoMarker: initTable[SigHash, tuple[str: Rope, owner: int32]](), config: g.config, graph: g, nimtvDeclared: initIntSet()) iterator cgenModules*(g: BModuleList): BModule = for m in g.modulesClosed: # iterate modules in the order they were closed yield m