We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Some Windows and MSVC fixes
ref: https://github.com/apache/incubator-tvm/issues/4529

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `python/tvm/_ffi/base.py`
Content:
```
1 # Licensed to the Apache Software Foundation (ASF) under one
2 # or more contributor license agreements.  See the NOTICE file
3 # distributed with this work for additional information
4 # regarding copyright ownership.  The ASF licenses this file
5 # to you under the Apache License, Version 2.0 (the
6 # "License"); you may not use this file except in compliance
7 # with the License.  You may obtain a copy of the License at
8 #
9 #   http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing,
12 # software distributed under the License is distributed on an
13 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 # KIND, either express or implied.  See the License for the
15 # specific language governing permissions and limitations
16 # under the License.
17 # coding: utf-8
18 # pylint: disable=invalid-name
19 """Base library for TVM FFI."""
20 from __future__ import absolute_import
21 
22 import sys
23 import os
24 import ctypes
25 import numpy as np
26 from . import libinfo
27 
28 #----------------------------
29 # library loading
30 #----------------------------
31 if sys.version_info[0] == 3:
32     string_types = (str,)
33     integer_types = (int, np.int32)
34     numeric_types = integer_types + (float, np.float32)
35     # this function is needed for python3
36     # to convert ctypes.char_p .value back to python str
37     if sys.platform == "win32":
38         encoding = 'cp' + str(ctypes.cdll.kernel32.GetACP())
39         py_str = lambda x: x.decode(encoding)
40     else:
41         py_str = lambda x: x.decode('utf-8')
42 else:
43     string_types = (basestring,)
44     integer_types = (int, long, np.int32)
45     numeric_types = integer_types + (float, np.float32)
46     py_str = lambda x: x
47 
48 
49 def _load_lib():
50     """Load libary by searching possible path."""
51     lib_path = libinfo.find_lib_path()
52     lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_GLOBAL)
53     # DMatrix functions
54     lib.TVMGetLastError.restype = ctypes.c_char_p
55     return lib, os.path.basename(lib_path[0])
56 
57 try:
58     import readline  # pylint: disable=unused-import
59 except ImportError:
60     pass
61 
62 # version number
63 __version__ = libinfo.__version__
64 # library instance of nnvm
65 _LIB, _LIB_NAME = _load_lib()
66 
67 # Whether we are runtime only
68 _RUNTIME_ONLY = "runtime" in _LIB_NAME
69 
70 # The FFI mode of TVM
71 _FFI_MODE = os.environ.get("TVM_FFI", "auto")
72 
73 #----------------------------
74 # helper function in ctypes.
75 #----------------------------
76 def c_str(string):
77     """Create ctypes char * from a python string
78     Parameters
79     ----------
80     string : string type
81         python string
82 
83     Returns
84     -------
85     str : c_char_p
86         A char pointer that can be passed to C API
87     """
88     return ctypes.c_char_p(string.encode('utf-8'))
89 
90 
91 def c_array(ctype, values):
92     """Create ctypes array from a python array
93 
94     Parameters
95     ----------
96     ctype : ctypes data type
97         data type of the array we want to convert to
98 
99     values : tuple or list
100         data content
101 
102     Returns
103     -------
104     out : ctypes array
105         Created ctypes array
106     """
107     return (ctype * len(values))(*values)
108 
109 
110 def decorate(func, fwrapped):
111     """A wrapper call of decorator package, differs to call time
112 
113     Parameters
114     ----------
115     func : function
116         The original function
117 
118     fwrapped : function
119         The wrapped function
120     """
121     import decorator
122     return decorator.decorate(func, fwrapped)
123 
124 
125 #-----------------------------------------
126 # Base code for structured error handling.
127 #-----------------------------------------
128 # Maps error type to its constructor
129 ERROR_TYPE = {}
130 
131 
132 class TVMError(RuntimeError):
133     """Default error thrown by TVM functions.
134 
135     TVMError will be raised if you do not give any error type specification,
136     """
137 
138 
139 def register_error(func_name=None, cls=None):
140     """Register an error class so it can be recognized by the ffi error handler.
141 
142     Parameters
143     ----------
144     func_name : str or function or class
145         The name of the error function.
146 
147     cls : function
148         The function to create the class
149 
150     Returns
151     -------
152     fregister : function
153         Register function if f is not specified.
154 
155     Examples
156     --------
157     .. code-block:: python
158 
159       @tvm.error.register_error
160       class MyError(RuntimeError):
161           pass
162 
163       err_inst = tvm.error.create_ffi_error("MyError: xyz")
164       assert isinstance(err_inst, MyError)
165     """
166     if callable(func_name):
167         cls = func_name
168         func_name = cls.__name__
169 
170     def register(mycls):
171         """internal register function"""
172         err_name = func_name if isinstance(func_name, str) else mycls.__name__
173         ERROR_TYPE[err_name] = mycls
174         return mycls
175     if cls is None:
176         return register
177     return register(cls)
178 
179 
180 def _valid_error_name(name):
181     """Check whether name is a valid error name."""
182     return all(x.isalnum() or x in "_." for x in name)
183 
184 
185 def _find_error_type(line):
186     """Find the error name given the first line of the error message.
187 
188     Parameters
189     ----------
190     line : str
191         The first line of error message.
192 
193     Returns
194     -------
195     name : str The error name
196     """
197     end_pos = line.find(":")
198     if end_pos == -1:
199         return None
200     err_name = line[:end_pos]
201     if _valid_error_name(err_name):
202         return err_name
203     return None
204 
205 
206 def c2pyerror(err_msg):
207     """Translate C API error message to python style.
208 
209     Parameters
210     ----------
211     err_msg : str
212         The error message.
213 
214     Returns
215     -------
216     new_msg : str
217         Translated message.
218 
219     err_type : str
220         Detected error type.
221     """
222     arr = err_msg.split("\n")
223     if arr[-1] == "":
224         arr.pop()
225     err_type = _find_error_type(arr[0])
226     trace_mode = False
227     stack_trace = []
228     message = []
229     for line in arr:
230         if trace_mode:
231             if line.startswith("  "):
232                 stack_trace.append(line)
233             else:
234                 trace_mode = False
235         if not trace_mode:
236             if line.startswith("Stack trace"):
237                 trace_mode = True
238             else:
239                 message.append(line)
240     out_msg = ""
241     if stack_trace:
242         out_msg += "Traceback (most recent call last):\n"
243         out_msg += "\n".join(reversed(stack_trace)) + "\n"
244     out_msg += "\n".join(message)
245     return out_msg, err_type
246 
247 
248 def py2cerror(err_msg):
249     """Translate python style error message to C style.
250 
251     Parameters
252     ----------
253     err_msg : str
254         The error message.
255 
256     Returns
257     -------
258     new_msg : str
259         Translated message.
260     """
261     arr = err_msg.split("\n")
262     if arr[-1] == "":
263         arr.pop()
264     trace_mode = False
265     stack_trace = []
266     message = []
267     for line in arr:
268         if trace_mode:
269             if line.startswith("  "):
270                 stack_trace.append(line)
271             else:
272                 trace_mode = False
273         if not trace_mode:
274             if line.find("Traceback") != -1:
275                 trace_mode = True
276             else:
277                 message.append(line)
278     # Remove the first error name if there are two of them.
279     # RuntimeError: MyErrorName: message => MyErrorName: message
280     head_arr = message[0].split(":", 3)
281     if len(head_arr) >= 3 and _valid_error_name(head_arr[1].strip()):
282         head_arr[1] = head_arr[1].strip()
283         message[0] = ":".join(head_arr[1:])
284     # reverse the stack trace.
285     out_msg = "\n".join(message)
286     if stack_trace:
287         out_msg += "\nStack trace:\n"
288         out_msg += "\n".join(reversed(stack_trace)) + "\n"
289     return out_msg
290 
291 
292 def get_last_ffi_error():
293     """Create error object given result of TVMGetLastError.
294 
295     Returns
296     -------
297     err : object
298         The error object based on the err_msg
299     """
300     c_err_msg = py_str(_LIB.TVMGetLastError())
301     py_err_msg, err_type = c2pyerror(c_err_msg)
302     if err_type is not None and err_type.startswith("tvm.error."):
303         err_type = err_type[10:]
304     return ERROR_TYPE.get(err_type, TVMError)(py_err_msg)
305 
306 
307 def check_call(ret):
308     """Check the return value of C API call
309 
310     This function will raise exception when error occurs.
311     Wrap every API call with this function
312 
313     Parameters
314     ----------
315     ret : int
316         return value from API calls
317     """
318     if ret != 0:
319         raise get_last_ffi_error()
320
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/python/tvm/_ffi/base.py b/python/tvm/_ffi/base.py
--- a/python/tvm/_ffi/base.py
+++ b/python/tvm/_ffi/base.py
@@ -35,8 +35,13 @@
     # this function is needed for python3
     # to convert ctypes.char_p .value back to python str
     if sys.platform == "win32":
-        encoding = 'cp' + str(ctypes.cdll.kernel32.GetACP())
-        py_str = lambda x: x.decode(encoding)
+        def _py_str(x):
+            try:
+                return x.decode('utf-8')
+            except UnicodeDecodeError:
+                encoding = 'cp' + str(ctypes.cdll.kernel32.GetACP())
+                return x.decode(encoding)
+        py_str = _py_str
     else:
         py_str = lambda x: x.decode('utf-8')
 else:

{"golden_diff": "diff --git a/python/tvm/_ffi/base.py b/python/tvm/_ffi/base.py\n--- a/python/tvm/_ffi/base.py\n+++ b/python/tvm/_ffi/base.py\n@@ -35,8 +35,13 @@\n     # this function is needed for python3\n     # to convert ctypes.char_p .value back to python str\n     if sys.platform == \"win32\":\n-        encoding = 'cp' + str(ctypes.cdll.kernel32.GetACP())\n-        py_str = lambda x: x.decode(encoding)\n+        def _py_str(x):\n+            try:\n+                return x.decode('utf-8')\n+            except UnicodeDecodeError:\n+                encoding = 'cp' + str(ctypes.cdll.kernel32.GetACP())\n+                return x.decode(encoding)\n+        py_str = _py_str\n     else:\n         py_str = lambda x: x.decode('utf-8')\n else:\n", "issue": "Some Windows and MSVC fixes\nref: https://github.com/apache/incubator-tvm/issues/4529\n", "before_files": [{"content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# coding: utf-8\n# pylint: disable=invalid-name\n\"\"\"Base library for TVM FFI.\"\"\"\nfrom __future__ import absolute_import\n\nimport sys\nimport os\nimport ctypes\nimport numpy as np\nfrom . import libinfo\n\n#----------------------------\n# library loading\n#----------------------------\nif sys.version_info[0] == 3:\n    string_types = (str,)\n    integer_types = (int, np.int32)\n    numeric_types = integer_types + (float, np.float32)\n    # this function is needed for python3\n    # to convert ctypes.char_p .value back to python str\n    if sys.platform == \"win32\":\n        encoding = 'cp' + str(ctypes.cdll.kernel32.GetACP())\n        py_str = lambda x: x.decode(encoding)\n    else:\n        py_str = lambda x: x.decode('utf-8')\nelse:\n    string_types = (basestring,)\n    integer_types = (int, long, np.int32)\n    numeric_types = integer_types + (float, np.float32)\n    py_str = lambda x: x\n\n\ndef _load_lib():\n    \"\"\"Load libary by searching possible path.\"\"\"\n    lib_path = libinfo.find_lib_path()\n    lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_GLOBAL)\n    # DMatrix functions\n    lib.TVMGetLastError.restype = ctypes.c_char_p\n    return lib, os.path.basename(lib_path[0])\n\ntry:\n    import readline  # pylint: disable=unused-import\nexcept ImportError:\n    pass\n\n# version number\n__version__ = libinfo.__version__\n# library instance of nnvm\n_LIB, _LIB_NAME = _load_lib()\n\n# Whether we are runtime only\n_RUNTIME_ONLY = \"runtime\" in _LIB_NAME\n\n# The FFI mode of TVM\n_FFI_MODE = os.environ.get(\"TVM_FFI\", \"auto\")\n\n#----------------------------\n# helper function in ctypes.\n#----------------------------\ndef c_str(string):\n    \"\"\"Create ctypes char * from a python string\n    Parameters\n    ----------\n    string : string type\n        python string\n\n    Returns\n    -------\n    str : c_char_p\n        A char pointer that can be passed to C API\n    \"\"\"\n    return ctypes.c_char_p(string.encode('utf-8'))\n\n\ndef c_array(ctype, values):\n    \"\"\"Create ctypes array from a python array\n\n    Parameters\n    ----------\n    ctype : ctypes data type\n        data type of the array we want to convert to\n\n    values : tuple or list\n        data content\n\n    Returns\n    -------\n    out : ctypes array\n        Created ctypes array\n    \"\"\"\n    return (ctype * len(values))(*values)\n\n\ndef decorate(func, fwrapped):\n    \"\"\"A wrapper call of decorator package, differs to call time\n\n    Parameters\n    ----------\n    func : function\n        The original function\n\n    fwrapped : function\n        The wrapped function\n    \"\"\"\n    import decorator\n    return decorator.decorate(func, fwrapped)\n\n\n#-----------------------------------------\n# Base code for structured error handling.\n#-----------------------------------------\n# Maps error type to its constructor\nERROR_TYPE = {}\n\n\nclass TVMError(RuntimeError):\n    \"\"\"Default error thrown by TVM functions.\n\n    TVMError will be raised if you do not give any error type specification,\n    \"\"\"\n\n\ndef register_error(func_name=None, cls=None):\n    \"\"\"Register an error class so it can be recognized by the ffi error handler.\n\n    Parameters\n    ----------\n    func_name : str or function or class\n        The name of the error function.\n\n    cls : function\n        The function to create the class\n\n    Returns\n    -------\n    fregister : function\n        Register function if f is not specified.\n\n    Examples\n    --------\n    .. code-block:: python\n\n      @tvm.error.register_error\n      class MyError(RuntimeError):\n          pass\n\n      err_inst = tvm.error.create_ffi_error(\"MyError: xyz\")\n      assert isinstance(err_inst, MyError)\n    \"\"\"\n    if callable(func_name):\n        cls = func_name\n        func_name = cls.__name__\n\n    def register(mycls):\n        \"\"\"internal register function\"\"\"\n        err_name = func_name if isinstance(func_name, str) else mycls.__name__\n        ERROR_TYPE[err_name] = mycls\n        return mycls\n    if cls is None:\n        return register\n    return register(cls)\n\n\ndef _valid_error_name(name):\n    \"\"\"Check whether name is a valid error name.\"\"\"\n    return all(x.isalnum() or x in \"_.\" for x in name)\n\n\ndef _find_error_type(line):\n    \"\"\"Find the error name given the first line of the error message.\n\n    Parameters\n    ----------\n    line : str\n        The first line of error message.\n\n    Returns\n    -------\n    name : str The error name\n    \"\"\"\n    end_pos = line.find(\":\")\n    if end_pos == -1:\n        return None\n    err_name = line[:end_pos]\n    if _valid_error_name(err_name):\n        return err_name\n    return None\n\n\ndef c2pyerror(err_msg):\n    \"\"\"Translate C API error message to python style.\n\n    Parameters\n    ----------\n    err_msg : str\n        The error message.\n\n    Returns\n    -------\n    new_msg : str\n        Translated message.\n\n    err_type : str\n        Detected error type.\n    \"\"\"\n    arr = err_msg.split(\"\\n\")\n    if arr[-1] == \"\":\n        arr.pop()\n    err_type = _find_error_type(arr[0])\n    trace_mode = False\n    stack_trace = []\n    message = []\n    for line in arr:\n        if trace_mode:\n            if line.startswith(\"  \"):\n                stack_trace.append(line)\n            else:\n                trace_mode = False\n        if not trace_mode:\n            if line.startswith(\"Stack trace\"):\n                trace_mode = True\n            else:\n                message.append(line)\n    out_msg = \"\"\n    if stack_trace:\n        out_msg += \"Traceback (most recent call last):\\n\"\n        out_msg += \"\\n\".join(reversed(stack_trace)) + \"\\n\"\n    out_msg += \"\\n\".join(message)\n    return out_msg, err_type\n\n\ndef py2cerror(err_msg):\n    \"\"\"Translate python style error message to C style.\n\n    Parameters\n    ----------\n    err_msg : str\n        The error message.\n\n    Returns\n    -------\n    new_msg : str\n        Translated message.\n    \"\"\"\n    arr = err_msg.split(\"\\n\")\n    if arr[-1] == \"\":\n        arr.pop()\n    trace_mode = False\n    stack_trace = []\n    message = []\n    for line in arr:\n        if trace_mode:\n            if line.startswith(\"  \"):\n                stack_trace.append(line)\n            else:\n                trace_mode = False\n        if not trace_mode:\n            if line.find(\"Traceback\") != -1:\n                trace_mode = True\n            else:\n                message.append(line)\n    # Remove the first error name if there are two of them.\n    # RuntimeError: MyErrorName: message => MyErrorName: message\n    head_arr = message[0].split(\":\", 3)\n    if len(head_arr) >= 3 and _valid_error_name(head_arr[1].strip()):\n        head_arr[1] = head_arr[1].strip()\n        message[0] = \":\".join(head_arr[1:])\n    # reverse the stack trace.\n    out_msg = \"\\n\".join(message)\n    if stack_trace:\n        out_msg += \"\\nStack trace:\\n\"\n        out_msg += \"\\n\".join(reversed(stack_trace)) + \"\\n\"\n    return out_msg\n\n\ndef get_last_ffi_error():\n    \"\"\"Create error object given result of TVMGetLastError.\n\n    Returns\n    -------\n    err : object\n        The error object based on the err_msg\n    \"\"\"\n    c_err_msg = py_str(_LIB.TVMGetLastError())\n    py_err_msg, err_type = c2pyerror(c_err_msg)\n    if err_type is not None and err_type.startswith(\"tvm.error.\"):\n        err_type = err_type[10:]\n    return ERROR_TYPE.get(err_type, TVMError)(py_err_msg)\n\n\ndef check_call(ret):\n    \"\"\"Check the return value of C API call\n\n    This function will raise exception when error occurs.\n    Wrap every API call with this function\n\n    Parameters\n    ----------\n    ret : int\n        return value from API calls\n    \"\"\"\n    if ret != 0:\n        raise get_last_ffi_error()\n", "path": "python/tvm/_ffi/base.py"}], "after_files": [{"content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# coding: utf-8\n# pylint: disable=invalid-name\n\"\"\"Base library for TVM FFI.\"\"\"\nfrom __future__ import absolute_import\n\nimport sys\nimport os\nimport ctypes\nimport numpy as np\nfrom . import libinfo\n\n#----------------------------\n# library loading\n#----------------------------\nif sys.version_info[0] == 3:\n    string_types = (str,)\n    integer_types = (int, np.int32)\n    numeric_types = integer_types + (float, np.float32)\n    # this function is needed for python3\n    # to convert ctypes.char_p .value back to python str\n    if sys.platform == \"win32\":\n        def _py_str(x):\n            try:\n                return x.decode('utf-8')\n            except UnicodeDecodeError:\n                encoding = 'cp' + str(ctypes.cdll.kernel32.GetACP())\n                return x.decode(encoding)\n        py_str = _py_str\n    else:\n        py_str = lambda x: x.decode('utf-8')\nelse:\n    string_types = (basestring,)\n    integer_types = (int, long, np.int32)\n    numeric_types = integer_types + (float, np.float32)\n    py_str = lambda x: x\n\n\ndef _load_lib():\n    \"\"\"Load libary by searching possible path.\"\"\"\n    lib_path = libinfo.find_lib_path()\n    lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_GLOBAL)\n    # DMatrix functions\n    lib.TVMGetLastError.restype = ctypes.c_char_p\n    return lib, os.path.basename(lib_path[0])\n\ntry:\n    import readline  # pylint: disable=unused-import\nexcept ImportError:\n    pass\n\n# version number\n__version__ = libinfo.__version__\n# library instance of nnvm\n_LIB, _LIB_NAME = _load_lib()\n\n# Whether we are runtime only\n_RUNTIME_ONLY = \"runtime\" in _LIB_NAME\n\n# The FFI mode of TVM\n_FFI_MODE = os.environ.get(\"TVM_FFI\", \"auto\")\n\n#----------------------------\n# helper function in ctypes.\n#----------------------------\ndef c_str(string):\n    \"\"\"Create ctypes char * from a python string\n    Parameters\n    ----------\n    string : string type\n        python string\n\n    Returns\n    -------\n    str : c_char_p\n        A char pointer that can be passed to C API\n    \"\"\"\n    return ctypes.c_char_p(string.encode('utf-8'))\n\n\ndef c_array(ctype, values):\n    \"\"\"Create ctypes array from a python array\n\n    Parameters\n    ----------\n    ctype : ctypes data type\n        data type of the array we want to convert to\n\n    values : tuple or list\n        data content\n\n    Returns\n    -------\n    out : ctypes array\n        Created ctypes array\n    \"\"\"\n    return (ctype * len(values))(*values)\n\n\ndef decorate(func, fwrapped):\n    \"\"\"A wrapper call of decorator package, differs to call time\n\n    Parameters\n    ----------\n    func : function\n        The original function\n\n    fwrapped : function\n        The wrapped function\n    \"\"\"\n    import decorator\n    return decorator.decorate(func, fwrapped)\n\n\n#-----------------------------------------\n# Base code for structured error handling.\n#-----------------------------------------\n# Maps error type to its constructor\nERROR_TYPE = {}\n\n\nclass TVMError(RuntimeError):\n    \"\"\"Default error thrown by TVM functions.\n\n    TVMError will be raised if you do not give any error type specification,\n    \"\"\"\n\n\ndef register_error(func_name=None, cls=None):\n    \"\"\"Register an error class so it can be recognized by the ffi error handler.\n\n    Parameters\n    ----------\n    func_name : str or function or class\n        The name of the error function.\n\n    cls : function\n        The function to create the class\n\n    Returns\n    -------\n    fregister : function\n        Register function if f is not specified.\n\n    Examples\n    --------\n    .. code-block:: python\n\n      @tvm.error.register_error\n      class MyError(RuntimeError):\n          pass\n\n      err_inst = tvm.error.create_ffi_error(\"MyError: xyz\")\n      assert isinstance(err_inst, MyError)\n    \"\"\"\n    if callable(func_name):\n        cls = func_name\n        func_name = cls.__name__\n\n    def register(mycls):\n        \"\"\"internal register function\"\"\"\n        err_name = func_name if isinstance(func_name, str) else mycls.__name__\n        ERROR_TYPE[err_name] = mycls\n        return mycls\n    if cls is None:\n        return register\n    return register(cls)\n\n\ndef _valid_error_name(name):\n    \"\"\"Check whether name is a valid error name.\"\"\"\n    return all(x.isalnum() or x in \"_.\" for x in name)\n\n\ndef _find_error_type(line):\n    \"\"\"Find the error name given the first line of the error message.\n\n    Parameters\n    ----------\n    line : str\n        The first line of error message.\n\n    Returns\n    -------\n    name : str The error name\n    \"\"\"\n    end_pos = line.find(\":\")\n    if end_pos == -1:\n        return None\n    err_name = line[:end_pos]\n    if _valid_error_name(err_name):\n        return err_name\n    return None\n\n\ndef c2pyerror(err_msg):\n    \"\"\"Translate C API error message to python style.\n\n    Parameters\n    ----------\n    err_msg : str\n        The error message.\n\n    Returns\n    -------\n    new_msg : str\n        Translated message.\n\n    err_type : str\n        Detected error type.\n    \"\"\"\n    arr = err_msg.split(\"\\n\")\n    if arr[-1] == \"\":\n        arr.pop()\n    err_type = _find_error_type(arr[0])\n    trace_mode = False\n    stack_trace = []\n    message = []\n    for line in arr:\n        if trace_mode:\n            if line.startswith(\"  \"):\n                stack_trace.append(line)\n            else:\n                trace_mode = False\n        if not trace_mode:\n            if line.startswith(\"Stack trace\"):\n                trace_mode = True\n            else:\n                message.append(line)\n    out_msg = \"\"\n    if stack_trace:\n        out_msg += \"Traceback (most recent call last):\\n\"\n        out_msg += \"\\n\".join(reversed(stack_trace)) + \"\\n\"\n    out_msg += \"\\n\".join(message)\n    return out_msg, err_type\n\n\ndef py2cerror(err_msg):\n    \"\"\"Translate python style error message to C style.\n\n    Parameters\n    ----------\n    err_msg : str\n        The error message.\n\n    Returns\n    -------\n    new_msg : str\n        Translated message.\n    \"\"\"\n    arr = err_msg.split(\"\\n\")\n    if arr[-1] == \"\":\n        arr.pop()\n    trace_mode = False\n    stack_trace = []\n    message = []\n    for line in arr:\n        if trace_mode:\n            if line.startswith(\"  \"):\n                stack_trace.append(line)\n            else:\n                trace_mode = False\n        if not trace_mode:\n            if line.find(\"Traceback\") != -1:\n                trace_mode = True\n            else:\n                message.append(line)\n    # Remove the first error name if there are two of them.\n    # RuntimeError: MyErrorName: message => MyErrorName: message\n    head_arr = message[0].split(\":\", 3)\n    if len(head_arr) >= 3 and _valid_error_name(head_arr[1].strip()):\n        head_arr[1] = head_arr[1].strip()\n        message[0] = \":\".join(head_arr[1:])\n    # reverse the stack trace.\n    out_msg = \"\\n\".join(message)\n    if stack_trace:\n        out_msg += \"\\nStack trace:\\n\"\n        out_msg += \"\\n\".join(reversed(stack_trace)) + \"\\n\"\n    return out_msg\n\n\ndef get_last_ffi_error():\n    \"\"\"Create error object given result of TVMGetLastError.\n\n    Returns\n    -------\n    err : object\n        The error object based on the err_msg\n    \"\"\"\n    c_err_msg = py_str(_LIB.TVMGetLastError())\n    py_err_msg, err_type = c2pyerror(c_err_msg)\n    if err_type is not None and err_type.startswith(\"tvm.error.\"):\n        err_type = err_type[10:]\n    return ERROR_TYPE.get(err_type, TVMError)(py_err_msg)\n\n\ndef check_call(ret):\n    \"\"\"Check the return value of C API call\n\n    This function will raise exception when error occurs.\n    Wrap every API call with this function\n\n    Parameters\n    ----------\n    ret : int\n        return value from API calls\n    \"\"\"\n    if ret != 0:\n        raise get_last_ffi_error()\n", "path": "python/tvm/_ffi/base.py"}]}