diff --git a/docs/library/collections.rst b/docs/library/collections.rst index 849e8b6944..b7a5fb1765 100644 --- a/docs/library/collections.rst +++ b/docs/library/collections.rst @@ -14,6 +14,33 @@ hold/accumulate various objects. Classes ------- +.. function:: deque(iterable, maxlen[, flags]) + + Deques (double-ended queues) are a list-like container that support O(1) + appends and pops from either side of the deque. New deques are created + using the following arguments: + + - *iterable* must be the empty tuple, and the new deque is created empty. + + - *maxlen* must be specified and the deque will be bounded to this + maximum length. Once the deque is full, any new items added will + discard items from the opposite end. + + - The optional *flags* can be 1 to check for overflow when adding items. + + As well as supporting `bool` and `len`, deque objects have the following + methods: + + .. method:: deque.append(x) + + Add *x* to the right side of the deque. + Raises IndexError if overflow checking is enabled and there is no more room left. + + .. method:: deque.popleft() + + Remove and return an item from the left side of the deque. + Raises IndexError if no items are present. + .. function:: namedtuple(name, fields) This is factory function to create a new namedtuple type with a specific diff --git a/docs/library/index.rst b/docs/library/index.rst index 181ff0109a..d490ae2277 100644 --- a/docs/library/index.rst +++ b/docs/library/index.rst @@ -39,8 +39,6 @@ with the ``u`` prefix dropped: sys.rst uctypes.rst uselect.rst - usocket.rst - ussl.rst uzlib.rst Omitted functions in the ``string`` library diff --git a/docs/library/micropython.rst b/docs/library/micropython.rst index 31065fbe55..6e39a24c64 100644 --- a/docs/library/micropython.rst +++ b/docs/library/micropython.rst @@ -81,6 +81,9 @@ Functions in a row and the lock-depth will increase, and then `heap_unlock()` must be called the same number of times to make the heap available again. + If the REPL becomes active with the heap locked then it will be forcefully + unlocked. + .. function:: kbd_intr(chr) Set the character that will raise a `KeyboardInterrupt` exception. By diff --git a/docs/library/re.rst b/docs/library/re.rst index bdcc9f52c1..9c266a6d8f 100644 --- a/docs/library/re.rst +++ b/docs/library/re.rst @@ -10,41 +10,101 @@ This module implements regular expression operations. Regular expression syntax supported is a subset of CPython ``re`` module (and actually is a subset of POSIX extended regular expressions). -Supported operators are: +Supported operators and special sequences are: -``'.'`` +``.`` Match any character. -``'[...]'`` +``[...]`` Match set of characters. Individual characters and ranges are supported, including negated sets (e.g. ``[^a-c]``). -``'^'`` +``^`` + Match the start of the string. -``'$'`` +``$`` + Match the end of the string. -``'?'`` +``?`` + Match zero or one of the previous sub-pattern. -``'*'`` +``*`` + Match zero or more of the previous sub-pattern. -``'+'`` +``+`` + Match one or more of the previous sub-pattern. -``'??'`` +``??`` + Non-greedy version of ``?``, match zero or one, with the preference + for zero. -``'*?'`` +``*?`` + Non-greedy version of ``*``, match zero or more, with the preference + for the shortest match. -``'+?'`` +``+?`` + Non-greedy version of ``+``, match one or more, with the preference + for the shortest match. -``'|'`` +``|`` + Match either the left-hand side or the right-hand side sub-patterns of + this operator. -``'(...)'`` +``(...)`` Grouping. Each group is capturing (a substring it captures can be accessed with `match.group()` method). -**NOT SUPPORTED**: Counted repetitions (``{m,n}``), more advanced assertions -(``\b``, ``\B``), named groups (``(?P...)``), non-capturing groups -(``(?:...)``), etc. +``\d`` + Matches digit. Equivalent to ``[0-9]``. +``\D`` + Matches non-digit. Equivalent to ``[^0-9]``. + +``\s`` + Matches whitespace. Equivalent to ``[ \t-\r]``. + +``\S`` + Matches non-whitespace. Equivalent to ``[^ \t-\r]``. + +``\w`` + Matches "word characters" (ASCII only). Equivalent to ``[A-Za-z0-9_]``. + +``\W`` + Matches non "word characters" (ASCII only). Equivalent to ``[^A-Za-z0-9_]``. + +``\`` + Escape character. Any other character following the backslash, except + for those listed above, is taken literally. For example, ``\*`` is + equivalent to literal ``*`` (not treated as the ``*`` operator). + Note that ``\r``, ``\n``, etc. are not handled specially, and will be + equivalent to literal letters ``r``, ``n``, etc. Due to this, it's + not recommended to use raw Python strings (``r""``) for regular + expressions. For example, ``r"\r\n"`` when used as the regular + expression is equivalent to ``"rn"``. To match CR character followed + by LF, use ``"\r\n"``. + +**NOT SUPPORTED**: + +* counted repetitions (``{m,n}``) +* named groups (``(?P...)``) +* non-capturing groups (``(?:...)``) +* more advanced assertions (``\b``, ``\B``) +* special character escapes like ``\r``, ``\n`` - use Python's own escaping + instead +* etc. + +Example:: + + import ure + + # As ure doesn't support escapes itself, use of r"" strings is not + # recommended. + regex = ure.compile("[\r\n]") + + regex.split("line1\rline2\nline3\r\n") + + # Result: + # ['line1', 'line2', 'line3', '', ''] Functions --------- @@ -64,6 +124,22 @@ Functions string for first position which matches regex (which still may be 0 if regex is anchored). +.. function:: sub(regex_str, replace, string, count=0, flags=0) + + Compile *regex_str* and search for it in *string*, replacing all matches + with *replace*, and returning the new string. + + *replace* can be a string or a function. If it is a string then escape + sequences of the form ``\`` and ``\g`` can be used to + expand to the corresponding group (or an empty string for unmatched groups). + If *replace* is a function then it must take a single argument (the match) + and should return a replacement string. + + If *count* is specified and non-zero then substitution will stop after + this many substitutions are made. The *flags* argument is ignored. + + Note: availability of this function depends on MicroPython port. + .. data:: DEBUG Flag value, display debug information about compiled expression. @@ -79,8 +155,10 @@ Compiled regular expression. Instances of this class are created using .. method:: regex.match(string) regex.search(string) + regex.sub(replace, string, count=0, flags=0) - Similar to the module-level functions :meth:`match` and :meth:`search`. + Similar to the module-level functions :meth:`match`, :meth:`search` + and :meth:`sub`. Using methods is (much) more efficient if the same regex is applied to multiple strings. @@ -93,9 +171,31 @@ Compiled regular expression. Instances of this class are created using Match objects ------------- -Match objects as returned by `match()` and `search()` methods. +Match objects as returned by `match()` and `search()` methods, and passed +to the replacement function in `sub()`. .. method:: match.group([index]) Return matching (sub)string. *index* is 0 for entire match, 1 and above for each capturing group. Only numeric groups are supported. + +.. method:: match.groups() + + Return a tuple containing all the substrings of the groups of the match. + + Note: availability of this method depends on MicroPython port. + +.. method:: match.start([index]) + match.end([index]) + + Return the index in the original string of the start or end of the + substring group that was matched. *index* defaults to the entire + group, otherwise it will select a group. + + Note: availability of these methods depends on MicroPython port. + +.. method:: match.span([index]) + + Returns the 2-tuple ``(match.start(index), match.end(index))``. + + Note: availability of this method depends on MicroPython port. diff --git a/docs/library/uctypes.rst b/docs/library/uctypes.rst index f71b00c1e4..fb81e3377e 100644 --- a/docs/library/uctypes.rst +++ b/docs/library/uctypes.rst @@ -13,19 +13,91 @@ module is to define data structure layout with about the same power as the C language allows, and then access it using familiar dot-syntax to reference sub-fields. +.. warning:: + + ``uctypes`` module allows access to arbitrary memory addresses of the + machine (including I/O and control registers). Uncareful usage of it + may lead to crashes, data loss, and even hardware malfunction. + .. seealso:: Module :mod:`struct` Standard Python way to access binary data structures (doesn't scale well to large and complex structures). +Usage examples:: + + import uctypes + + # Example 1: Subset of ELF file header + # https://wikipedia.org/wiki/Executable_and_Linkable_Format#File_header + ELF_HEADER = { + "EI_MAG": (0x0 | uctypes.ARRAY, 4 | uctypes.UINT8), + "EI_DATA": 0x5 | uctypes.UINT8, + "e_machine": 0x12 | uctypes.UINT16, + } + + # "f" is an ELF file opened in binary mode + buf = f.read(uctypes.sizeof(ELF_HEADER, uctypes.LITTLE_ENDIAN)) + header = uctypes.struct(uctypes.addressof(buf), ELF_HEADER, uctypes.LITTLE_ENDIAN) + assert header.EI_MAG == b"\x7fELF" + assert header.EI_DATA == 1, "Oops, wrong endianness. Could retry with uctypes.BIG_ENDIAN." + print("machine:", hex(header.e_machine)) + + + # Example 2: In-memory data structure, with pointers + COORD = { + "x": 0 | uctypes.FLOAT32, + "y": 4 | uctypes.FLOAT32, + } + + STRUCT1 = { + "data1": 0 | uctypes.UINT8, + "data2": 4 | uctypes.UINT32, + "ptr": (8 | uctypes.PTR, COORD), + } + + # Suppose you have address of a structure of type STRUCT1 in "addr" + # uctypes.NATIVE is optional (used by default) + struct1 = uctypes.struct(addr, STRUCT1, uctypes.NATIVE) + print("x:", struct1.ptr[0].x) + + + # Example 3: Access to CPU registers. Subset of STM32F4xx WWDG block + WWDG_LAYOUT = { + "WWDG_CR": (0, { + # BFUINT32 here means size of the WWDG_CR register + "WDGA": 7 << uctypes.BF_POS | 1 << uctypes.BF_LEN | uctypes.BFUINT32, + "T": 0 << uctypes.BF_POS | 7 << uctypes.BF_LEN | uctypes.BFUINT32, + }), + "WWDG_CFR": (4, { + "EWI": 9 << uctypes.BF_POS | 1 << uctypes.BF_LEN | uctypes.BFUINT32, + "WDGTB": 7 << uctypes.BF_POS | 2 << uctypes.BF_LEN | uctypes.BFUINT32, + "W": 0 << uctypes.BF_POS | 7 << uctypes.BF_LEN | uctypes.BFUINT32, + }), + } + + WWDG = uctypes.struct(0x40002c00, WWDG_LAYOUT) + + WWDG.WWDG_CFR.WDGTB = 0b10 + WWDG.WWDG_CR.WDGA = 1 + print("Current counter:", WWDG.WWDG_CR.T) + Defining structure layout ------------------------- Structure layout is defined by a "descriptor" - a Python dictionary which encodes field names as keys and other properties required to access them as -associated values. Currently, uctypes requires explicit specification of -offsets for each field. Offset are given in bytes from a structure start. +associated values:: + + { + "field1": , + "field2": , + ... + } + +Currently, ``uctypes`` requires explicit specification of offsets for each +field. Offset are given in bytes from the structure start. Following are encoding examples for various field types: @@ -33,7 +105,7 @@ Following are encoding examples for various field types: "field_name": offset | uctypes.UINT32 - in other words, value is scalar type identifier ORed with field offset + in other words, the value is a scalar type identifier ORed with a field offset (in bytes) from the start of the structure. * Recursive structures:: @@ -43,9 +115,11 @@ Following are encoding examples for various field types: "b1": 1 | uctypes.UINT8, }) - i.e. value is a 2-tuple, first element of which is offset, and second is + i.e. value is a 2-tuple, first element of which is an offset, and second is a structure descriptor dictionary (note: offsets in recursive descriptors - are relative to the structure it defines). + are relative to the structure it defines). Of course, recursive structures + can be specified not just by a literal dictionary, but by referring to a + structure descriptor dictionary (defined earlier) by name. * Arrays of primitive types:: @@ -53,42 +127,42 @@ Following are encoding examples for various field types: i.e. value is a 2-tuple, first element of which is ARRAY flag ORed with offset, and second is scalar element type ORed number of elements - in array. + in the array. * Arrays of aggregate types:: "arr2": (offset | uctypes.ARRAY, size, {"b": 0 | uctypes.UINT8}), i.e. value is a 3-tuple, first element of which is ARRAY flag ORed - with offset, second is a number of elements in array, and third is - descriptor of element type. + with offset, second is a number of elements in the array, and third is + a descriptor of element type. * Pointer to a primitive type:: "ptr": (offset | uctypes.PTR, uctypes.UINT8), i.e. value is a 2-tuple, first element of which is PTR flag ORed - with offset, and second is scalar element type. + with offset, and second is a scalar element type. * Pointer to an aggregate type:: "ptr2": (offset | uctypes.PTR, {"b": 0 | uctypes.UINT8}), i.e. value is a 2-tuple, first element of which is PTR flag ORed - with offset, second is descriptor of type pointed to. + with offset, second is a descriptor of type pointed to. * Bitfields:: "bitf0": offset | uctypes.BFUINT16 | lsbit << uctypes.BF_POS | bitsize << uctypes.BF_LEN, - i.e. value is type of scalar value containing given bitfield (typenames are - similar to scalar types, but prefixes with "BF"), ORed with offset for + i.e. value is a type of scalar value containing given bitfield (typenames are + similar to scalar types, but prefixes with ``BF``), ORed with offset for scalar value containing the bitfield, and further ORed with values for - bit offset and bit length of the bitfield within scalar value, shifted by - BF_POS and BF_LEN positions, respectively. Bitfield position is counted - from the least significant bit, and is the number of right-most bit of a - field (in other words, it's a number of bits a scalar needs to be shifted - right to extract the bitfield). + bit position and bit length of the bitfield within the scalar value, shifted by + BF_POS and BF_LEN bits, respectively. A bitfield position is counted + from the least significant bit of the scalar (having position of 0), and + is the number of right-most bit of a field (in other words, it's a number + of bits a scalar needs to be shifted right to extract the bitfield). In the example above, first a UINT16 value will be extracted at offset 0 (this detail may be important when accessing hardware registers, where @@ -128,10 +202,11 @@ Module contents Layout type for a native structure - with data endianness and alignment conforming to the ABI of the system on which MicroPython runs. -.. function:: sizeof(struct) +.. function:: sizeof(struct, layout_type=NATIVE) - Return size of data structure in bytes. Argument can be either structure - class or specific instantiated structure object (or its aggregate field). + Return size of data structure in bytes. The *struct* argument can be + either a structure class or a specific instantiated structure object + (or its aggregate field). .. function:: addressof(obj) @@ -153,6 +228,35 @@ Module contents so it can be both written too, and you will access current value at the given memory address. +.. data:: UINT8 + INT8 + UINT16 + INT16 + UINT32 + INT32 + UINT64 + INT64 + + Integer types for structure descriptors. Constants for 8, 16, 32, + and 64 bit types are provided, both signed and unsigned. + +.. data:: FLOAT32 + FLOAT64 + + Floating-point types for structure descriptors. + +.. data:: VOID + + ``VOID`` is an alias for ``UINT8``, and is provided to conviniently define + C's void pointers: ``(uctypes.PTR, uctypes.VOID)``. + +.. data:: PTR + ARRAY + + Type constants for pointers and arrays. Note that there is no explicit + constant for structures, it's implicit: an aggregate type without ``PTR`` + or ``ARRAY`` flags is a structure. + Structure descriptors and instantiating structure objects --------------------------------------------------------- @@ -165,7 +269,7 @@ following sources: system. Lookup these addresses in datasheet for a particular MCU/SoC. * As a return value from a call to some FFI (Foreign Function Interface) function. -* From uctypes.addressof(), when you want to pass arguments to an FFI +* From `uctypes.addressof()`, when you want to pass arguments to an FFI function, or alternatively, to access some data for I/O (for example, data read from a file or network socket). @@ -183,30 +287,41 @@ the standard subscript operator ``[]`` - both read and assigned to. If a field is a pointer, it can be dereferenced using ``[0]`` syntax (corresponding to C ``*`` operator, though ``[0]`` works in C too). -Subscripting a pointer with other integer values but 0 are supported too, +Subscripting a pointer with other integer values but 0 are also supported, with the same semantics as in C. -Summing up, accessing structure fields generally follows C syntax, +Summing up, accessing structure fields generally follows the C syntax, except for pointer dereference, when you need to use ``[0]`` operator instead of ``*``. Limitations ----------- -Accessing non-scalar fields leads to allocation of intermediate objects +1. Accessing non-scalar fields leads to allocation of intermediate objects to represent them. This means that special care should be taken to layout a structure which needs to be accessed when memory allocation is disabled (e.g. from an interrupt). The recommendations are: -* Avoid nested structures. For example, instead of +* Avoid accessing nested structures. For example, instead of ``mcu_registers.peripheral_a.register1``, define separate layout descriptors for each peripheral, to be accessed as - ``peripheral_a.register1``. -* Avoid other non-scalar data, like array. For example, instead of - ``peripheral_a.register[0]`` use ``peripheral_a.register0``. + ``peripheral_a.register1``. Or just cache a particular peripheral: + ``peripheral_a = mcu_registers.peripheral_a``. If a register + consists of multiple bitfields, you would need to cache references + to a particular register: ``reg_a = mcu_registers.peripheral_a.reg_a``. +* Avoid other non-scalar data, like arrays. For example, instead of + ``peripheral_a.register[0]`` use ``peripheral_a.register0``. Again, + an alternative is to cache intermediate values, e.g. + ``register0 = peripheral_a.register[0]``. -Note that these recommendations will lead to decreased readability -and conciseness of layouts, so they should be used only if the need -to access structure fields without allocation is anticipated (it's -even possible to define 2 parallel layouts - one for normal usage, -and a restricted one to use when memory allocation is prohibited). +2. Range of offsets supported by the ``uctypes`` module is limited. +The exact range supported is considered an implementation detail, +and the general suggestion is to split structure definitions to +cover from a few kilobytes to a few dozen of kilobytes maximum. +In most cases, this is a natural situation anyway, e.g. it doesn't make +sense to define all registers of an MCU (spread over 32-bit address +space) in one structure, but rather a peripheral block by peripheral +block. In some extreme cases, you may need to split a structure in +several parts artificially (e.g. if accessing native data structure +with multi-megabyte array in the middle, though that would be a very +synthetic case). diff --git a/docs/library/uselect.rst b/docs/library/uselect.rst index a2b408b206..cdf12fac26 100644 --- a/docs/library/uselect.rst +++ b/docs/library/uselect.rst @@ -47,13 +47,18 @@ Methods *eventmask* defaults to ``uselect.POLLIN | uselect.POLLOUT``. + It is OK to call this function multiple times for the same *obj*. + Successive calls will update *obj*'s eventmask to the value of + *eventmask* (i.e. will behave as `modify()`). + .. method:: poll.unregister(obj) Unregister *obj* from polling. .. method:: poll.modify(obj, eventmask) - Modify the *eventmask* for *obj*. + Modify the *eventmask* for *obj*. If *obj* is not registered, `OSError` + is raised with error of ENOENT. .. method:: poll.poll(timeout=-1) diff --git a/docs/library/usocket.rst b/docs/library/usocket.rst deleted file mode 100644 index 2115085a31..0000000000 --- a/docs/library/usocket.rst +++ /dev/null @@ -1,336 +0,0 @@ -******************************* -:mod:`usocket` -- socket module -******************************* - -.. include:: ../templates/unsupported_in_circuitpython.inc - -.. module:: usocket - :synopsis: socket module - -|see_cpython_module| :mod:`cpython:socket`. - -This module provides access to the BSD socket interface. - -.. admonition:: Difference to CPython - :class: attention - - For efficiency and consistency, socket objects in MicroPython implement a ``stream`` - (file-like) interface directly. In CPython, you need to convert a socket to - a file-like object using `makefile()` method. This method is still supported - by MicroPython (but is a no-op), so where compatibility with CPython matters, - be sure to use it. - -Socket address format(s) ------------------------- - -The native socket address format of the ``usocket`` module is an opaque data type -returned by `getaddrinfo` function, which must be used to resolve textual address -(including numeric addresses):: - - sockaddr = usocket.getaddrinfo('www.micropython.org', 80)[0][-1] - # You must use getaddrinfo() even for numeric addresses - sockaddr = usocket.getaddrinfo('127.0.0.1', 80)[0][-1] - # Now you can use that address - sock.connect(addr) - -Using `getaddrinfo` is the most efficient (both in terms of memory and processing -power) and portable way to work with addresses. - -However, ``socket`` module (note the difference with native MicroPython -``usocket`` module described here) provides CPython-compatible way to specify -addresses using tuples, as described below. - -Summing up: - -* Always use `getaddrinfo` when writing portable applications. -* Tuple addresses described below can be used as a shortcut for - quick hacks and interactive use, if your port supports them. - -Tuple address format for ``socket`` module: - -* IPv4: *(ipv4_address, port)*, where *ipv4_address* is a string with - dot-notation numeric IPv4 address, e.g. ``"8.8.8.8"``, and *port* is and - integer port number in the range 1-65535. Note the domain names are not - accepted as *ipv4_address*, they should be resolved first using - `usocket.getaddrinfo()`. -* IPv6: *(ipv6_address, port, flowinfo, scopeid)*, where *ipv6_address* - is a string with colon-notation numeric IPv6 address, e.g. ``"2001:db8::1"``, - and *port* is an integer port number in the range 1-65535. *flowinfo* - must be 0. *scopeid* is the interface scope identifier for link-local - addresses. Note the domain names are not accepted as *ipv6_address*, - they should be resolved first using `usocket.getaddrinfo()`. - -Functions ---------- - -.. function:: socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP) - - Create a new socket using the given address family, socket type and - protocol number. Note that specifying *proto* in most cases is not - required (and not recommended, as some MicroPython ports may omit - ``IPPROTO_*`` constants). Instead, *type* argument will select needed - protocol automatically:: - - # Create STREAM TCP socket - socket(AF_INET, SOCK_STREAM) - # Create DGRAM UDP socket - socket(AF_INET, SOCK_DGRAM) - -.. function:: getaddrinfo(host, port) - - Translate the host/port argument into a sequence of 5-tuples that contain all the - necessary arguments for creating a socket connected to that service. The list of - 5-tuples has following structure:: - - (family, type, proto, canonname, sockaddr) - - The following example shows how to connect to a given url:: - - s = usocket.socket() - s.connect(usocket.getaddrinfo('www.micropython.org', 80)[0][-1]) - - .. admonition:: Difference to CPython - :class: attention - - CPython raises a ``socket.gaierror`` exception (`OSError` subclass) in case - of error in this function. MicroPython doesn't have ``socket.gaierror`` - and raises OSError directly. Note that error numbers of `getaddrinfo()` - form a separate namespace and may not match error numbers from - :py:mod:`uerrno` module. To distinguish `getaddrinfo()` errors, they are - represented by negative numbers, whereas standard system errors are - positive numbers (error numbers are accessible using ``e.args[0]`` property - from an exception object). The use of negative values is a provisional - detail which may change in the future. - -.. function:: inet_ntop(af, bin_addr) - - Convert a binary network address *bin_addr* of the given address family *af* - to a textual representation:: - - >>> usocket.inet_ntop(usocket.AF_INET, b"\x7f\0\0\1") - '127.0.0.1' - -.. function:: inet_pton(af, txt_addr) - - Convert a textual network address *txt_addr* of the given address family *af* - to a binary representation:: - - >>> usocket.inet_pton(usocket.AF_INET, "1.2.3.4") - b'\x01\x02\x03\x04' - -Constants ---------- - -.. data:: AF_INET - AF_INET6 - - Address family types. Availability depends on a particular ``MicroPython port``. - -.. data:: SOCK_STREAM - SOCK_DGRAM - - Socket types. - -.. data:: IPPROTO_UDP - IPPROTO_TCP - - IP protocol numbers. Availability depends on a particular ``MicroPython port``. - Note that you don't need to specify these in a call to `usocket.socket()`, - because `SOCK_STREAM` socket type automatically selects `IPPROTO_TCP`, and - `SOCK_DGRAM` - `IPPROTO_UDP`. Thus, the only real use of these constants - is as an argument to `usocket.socket.setsockopt()`. - -.. data:: usocket.SOL_* - - Socket option levels (an argument to `usocket.socket.setsockopt()`). The exact - inventory depends on a ``MicroPython port``. - -.. data:: usocket.SO_* - - Socket options (an argument to `usocket.socket.setsockopt()`). The exact - inventory depends on a ``MicroPython port``. - -Constants specific to WiPy: - -.. data:: IPPROTO_SEC - - Special protocol value to create SSL-compatible socket. - -class socket -============ - -Methods -------- - -.. method:: socket.close() - - Mark the socket closed and release all resources. Once that happens, all future operations - on the socket object will fail. The remote end will receive EOF indication if - supported by protocol. - - Sockets are automatically closed when they are garbage-collected, but it is recommended - to `close()` them explicitly as soon you finished working with them. - -.. method:: socket.bind(address) - - Bind the socket to *address*. The socket must not already be bound. - -.. method:: socket.listen([backlog]) - - Enable a server to accept connections. If *backlog* is specified, it must be at least 0 - (if it's lower, it will be set to 0); and specifies the number of unaccepted connections - that the system will allow before refusing new connections. If not specified, a default - reasonable value is chosen. - -.. method:: socket.accept() - - Accept a connection. The socket must be bound to an address and listening for connections. - The return value is a pair (conn, address) where conn is a new socket object usable to send - and receive data on the connection, and address is the address bound to the socket on the - other end of the connection. - -.. method:: socket.connect(address) - - Connect to a remote socket at *address*. - -.. method:: socket.send(bytes) - - Send data to the socket. The socket must be connected to a remote socket. - Returns number of bytes sent, which may be smaller than the length of data - ("short write"). - -.. method:: socket.sendall(bytes) - - Send all data to the socket. The socket must be connected to a remote socket. - Unlike `send()`, this method will try to send all of data, by sending data - chunk by chunk consecutively. - - The behavior of this method on non-blocking sockets is undefined. Due to this, - on MicroPython, it's recommended to use `write()` method instead, which - has the same "no short writes" policy for blocking sockets, and will return - number of bytes sent on non-blocking sockets. - -.. method:: socket.recv(bufsize) - - Receive data from the socket. The return value is a bytes object representing the data - received. The maximum amount of data to be received at once is specified by bufsize. - -.. method:: socket.sendto(bytes, address) - - Send data to the socket. The socket should not be connected to a remote socket, since the - destination socket is specified by *address*. - -.. method:: socket.recvfrom(bufsize) - - Receive data from the socket. The return value is a pair *(bytes, address)* where *bytes* is a - bytes object representing the data received and *address* is the address of the socket sending - the data. - -.. method:: socket.setsockopt(level, optname, value) - - Set the value of the given socket option. The needed symbolic constants are defined in the - socket module (SO_* etc.). The *value* can be an integer or a bytes-like object representing - a buffer. - -.. method:: socket.settimeout(value) - - **Note**: Not every port supports this method, see below. - - Set a timeout on blocking socket operations. The value argument can be a nonnegative floating - point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations - will raise an `OSError` exception if the timeout period value has elapsed before the operation has - completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket - is put in blocking mode. - - Not every ``MicroPython port`` supports this method. A more portable and - generic solution is to use `uselect.poll` object. This allows to wait on - multiple objects at the same time (and not just on sockets, but on generic - ``stream`` objects which support polling). Example:: - - # Instead of: - s.settimeout(1.0) # time in seconds - s.read(10) # may timeout - - # Use: - poller = uselect.poll() - poller.register(s, uselect.POLLIN) - res = poller.poll(1000) # time in milliseconds - if not res: - # s is still not ready for input, i.e. operation timed out - - .. admonition:: Difference to CPython - :class: attention - - CPython raises a ``socket.timeout`` exception in case of timeout, - which is an `OSError` subclass. MicroPython raises an OSError directly - instead. If you use ``except OSError:`` to catch the exception, - your code will work both in MicroPython and CPython. - -.. method:: socket.setblocking(flag) - - Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking, - else to blocking mode. - - This method is a shorthand for certain `settimeout()` calls: - - * ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)`` - * ``sock.setblocking(False)`` is equivalent to ``sock.settimeout(0)`` - -.. method:: socket.makefile(mode='rb', buffering=0) - - Return a file object associated with the socket. The exact returned type depends on the arguments - given to makefile(). The support is limited to binary modes only ('rb', 'wb', and 'rwb'). - CPython's arguments: *encoding*, *errors* and *newline* are not supported. - - .. admonition:: Difference to CPython - :class: attention - - As MicroPython doesn't support buffered streams, values of *buffering* - parameter is ignored and treated as if it was 0 (unbuffered). - - .. admonition:: Difference to CPython - :class: attention - - Closing the file object returned by makefile() WILL close the - original socket as well. - -.. method:: socket.read([size]) - - Read up to size bytes from the socket. Return a bytes object. If *size* is not given, it - reads all data available from the socket until EOF; as such the method will not return until - the socket is closed. This function tries to read as much data as - requested (no "short reads"). This may be not possible with - non-blocking socket though, and then less data will be returned. - -.. method:: socket.readinto(buf[, nbytes]) - - Read bytes into the *buf*. If *nbytes* is specified then read at most - that many bytes. Otherwise, read at most *len(buf)* bytes. Just as - `read()`, this method follows "no short reads" policy. - - Return value: number of bytes read and stored into *buf*. - -.. method:: socket.readline() - - Read a line, ending in a newline character. - - Return value: the line read. - -.. method:: socket.write(buf) - - Write the buffer of bytes to the socket. This function will try to - write all data to a socket (no "short writes"). This may be not possible - with a non-blocking socket though, and returned value will be less than - the length of *buf*. - - Return value: number of bytes written. - -.. exception:: usocket.error - - MicroPython does NOT have this exception. - - .. admonition:: Difference to CPython - :class: attention - - CPython used to have a ``socket.error`` exception which is now deprecated, - and is an alias of `OSError`. In MicroPython, use `OSError` directly. diff --git a/docs/library/ussl.rst b/docs/library/ussl.rst deleted file mode 100644 index 91a64b025f..0000000000 --- a/docs/library/ussl.rst +++ /dev/null @@ -1,50 +0,0 @@ -:mod:`ussl` -- SSL/TLS module -============================= - -.. include:: ../templates/unsupported_in_circuitpython.inc - -.. module:: ussl - :synopsis: TLS/SSL wrapper for socket objects - -|see_cpython_module| :mod:`cpython:ssl`. - -This module provides access to Transport Layer Security (previously and -widely known as “Secure Sockets Layer”) encryption and peer authentication -facilities for network sockets, both client-side and server-side. - -Functions ---------- - -.. function:: ussl.wrap_socket(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=CERT_NONE, ca_certs=None) - - Takes a ``stream`` *sock* (usually usocket.socket instance of ``SOCK_STREAM`` type), - and returns an instance of ssl.SSLSocket, which wraps the underlying stream in - an SSL context. Returned object has the usual ``stream`` interface methods like - ``read()``, ``write()``, etc. In MicroPython, the returned object does not expose - socket interface and methods like ``recv()``, ``send()``. In particular, a - server-side SSL socket should be created from a normal socket returned from - :meth:`~usocket.socket.accept()` on a non-SSL listening server socket. - - Depending on the underlying module implementation in a particular - ``MicroPython port``, some or all keyword arguments above may be not supported. - -.. warning:: - - Some implementations of ``ussl`` module do NOT validate server certificates, - which makes an SSL connection established prone to man-in-the-middle attacks. - -Exceptions ----------- - -.. data:: ssl.SSLError - - This exception does NOT exist. Instead its base class, OSError, is used. - -Constants ---------- - -.. data:: ussl.CERT_NONE - ussl.CERT_OPTIONAL - ussl.CERT_REQUIRED - - Supported values for *cert_reqs* parameter. diff --git a/drivers/bus/qspi.h b/drivers/bus/qspi.h deleted file mode 100644 index 81587b08b3..0000000000 --- a/drivers/bus/qspi.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * SPDX-FileCopyrightText: Copyright (c) 2017-2018 Damien P. George - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -#ifndef MICROPY_INCLUDED_DRIVERS_BUS_QSPI_H -#define MICROPY_INCLUDED_DRIVERS_BUS_QSPI_H - -#include "py/mphal.h" - -enum { - MP_QSPI_IOCTL_INIT, - MP_QSPI_IOCTL_DEINIT, - MP_QSPI_IOCTL_BUS_ACQUIRE, - MP_QSPI_IOCTL_BUS_RELEASE, -}; - -typedef struct _mp_qspi_proto_t { - int (*ioctl)(void *self, uint32_t cmd); - void (*write_cmd_data)(void *self, uint8_t cmd, size_t len, uint32_t data); - void (*write_cmd_addr_data)(void *self, uint8_t cmd, uint32_t addr, size_t len, const uint8_t *src); - uint32_t (*read_cmd)(void *self, uint8_t cmd, size_t len); - void (*read_cmd_qaddr_qdata)(void *self, uint8_t cmd, uint32_t addr, size_t len, uint8_t *dest); -} mp_qspi_proto_t; - -typedef struct _mp_soft_qspi_obj_t { - mp_hal_pin_obj_t cs; - mp_hal_pin_obj_t clk; - mp_hal_pin_obj_t io0; - mp_hal_pin_obj_t io1; - mp_hal_pin_obj_t io2; - mp_hal_pin_obj_t io3; -} mp_soft_qspi_obj_t; - -extern const mp_qspi_proto_t mp_soft_qspi_proto; - -#endif // MICROPY_INCLUDED_DRIVERS_BUS_QSPI_H diff --git a/drivers/bus/softqspi.c b/drivers/bus/softqspi.c deleted file mode 100644 index c0aecf87d2..0000000000 --- a/drivers/bus/softqspi.c +++ /dev/null @@ -1,203 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * SPDX-FileCopyrightText: Copyright (c) 2017-2018 Damien P. George - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include "drivers/bus/qspi.h" - -#define CS_LOW(self) mp_hal_pin_write(self->cs, 0) -#define CS_HIGH(self) mp_hal_pin_write(self->cs, 1) - -#ifdef MICROPY_HW_SOFTQSPI_SCK_LOW - -// Use externally provided functions for SCK control and IO reading -#define SCK_LOW(self) MICROPY_HW_SOFTQSPI_SCK_LOW(self) -#define SCK_HIGH(self) MICROPY_HW_SOFTQSPI_SCK_HIGH(self) -#define NIBBLE_READ(self) MICROPY_HW_SOFTQSPI_NIBBLE_READ(self) - -#else - -// Use generic pin functions for SCK control and IO reading -#define SCK_LOW(self) mp_hal_pin_write(self->clk, 0) -#define SCK_HIGH(self) mp_hal_pin_write(self->clk, 1) -#define NIBBLE_READ(self) ( \ - mp_hal_pin_read(self->io0) \ - | (mp_hal_pin_read(self->io1) << 1) \ - | (mp_hal_pin_read(self->io2) << 2) \ - | (mp_hal_pin_read(self->io3) << 3)) - -#endif - -STATIC void nibble_write(mp_soft_qspi_obj_t *self, uint8_t v) { - mp_hal_pin_write(self->io0, v & 1); - mp_hal_pin_write(self->io1, (v >> 1) & 1); - mp_hal_pin_write(self->io2, (v >> 2) & 1); - mp_hal_pin_write(self->io3, (v >> 3) & 1); -} - -STATIC int mp_soft_qspi_ioctl(void *self_in, uint32_t cmd) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; - - switch (cmd) { - case MP_QSPI_IOCTL_INIT: - mp_hal_pin_high(self->cs); - mp_hal_pin_output(self->cs); - - // Configure pins - mp_hal_pin_write(self->clk, 0); - mp_hal_pin_output(self->clk); - // mp_hal_pin_write(self->clk, 1); - mp_hal_pin_output(self->io0); - mp_hal_pin_input(self->io1); - mp_hal_pin_write(self->io2, 1); - mp_hal_pin_output(self->io2); - mp_hal_pin_write(self->io3, 1); - mp_hal_pin_output(self->io3); - break; - } - - return 0; // success -} - -STATIC void mp_soft_qspi_transfer(mp_soft_qspi_obj_t *self, size_t len, const uint8_t *src, uint8_t *dest) { - // Will run as fast as possible, limited only by CPU speed and GPIO time - mp_hal_pin_input(self->io1); - mp_hal_pin_output(self->io0); - if (self->io3) { - mp_hal_pin_write(self->io2, 1); - mp_hal_pin_output(self->io2); - mp_hal_pin_write(self->io3, 1); - mp_hal_pin_output(self->io3); - } - if (src) { - for (size_t i = 0; i < len; ++i) { - uint8_t data_out = src[i]; - uint8_t data_in = 0; - for (int j = 0; j < 8; ++j, data_out <<= 1) { - mp_hal_pin_write(self->io0, (data_out >> 7) & 1); - mp_hal_pin_write(self->clk, 1); - data_in = (data_in << 1) | mp_hal_pin_read(self->io1); - mp_hal_pin_write(self->clk, 0); - } - if (dest != NULL) { - dest[i] = data_in; - } - } - } else { - for (size_t i = 0; i < len; ++i) { - uint8_t data_in = 0; - for (int j = 0; j < 8; ++j) { - mp_hal_pin_write(self->clk, 1); - data_in = (data_in << 1) | mp_hal_pin_read(self->io1); - mp_hal_pin_write(self->clk, 0); - } - if (dest != NULL) { - dest[i] = data_in; - } - } - } -} - -STATIC void mp_soft_qspi_qread(mp_soft_qspi_obj_t *self, size_t len, uint8_t *buf) { - // Make all IO lines input - mp_hal_pin_input(self->io2); - mp_hal_pin_input(self->io3); - mp_hal_pin_input(self->io0); - mp_hal_pin_input(self->io1); - - // Will run as fast as possible, limited only by CPU speed and GPIO time - while (len--) { - SCK_HIGH(self); - uint8_t data_in = NIBBLE_READ(self); - SCK_LOW(self); - SCK_HIGH(self); - *buf++ = (data_in << 4) | NIBBLE_READ(self); - SCK_LOW(self); - } -} - -STATIC void mp_soft_qspi_qwrite(mp_soft_qspi_obj_t *self, size_t len, const uint8_t *buf) { - // Make all IO lines output - mp_hal_pin_output(self->io2); - mp_hal_pin_output(self->io3); - mp_hal_pin_output(self->io0); - mp_hal_pin_output(self->io1); - - // Will run as fast as possible, limited only by CPU speed and GPIO time - for (size_t i = 0; i < len; ++i) { - nibble_write(self, buf[i] >> 4); - SCK_HIGH(self); - SCK_LOW(self); - - nibble_write(self, buf[i]); - SCK_HIGH(self); - SCK_LOW(self); - } - - // mp_hal_pin_input(self->io1); -} - -STATIC void mp_soft_qspi_write_cmd_data(void *self_in, uint8_t cmd, size_t len, uint32_t data) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; - uint32_t cmd_buf = cmd | data << 8; - CS_LOW(self); - mp_soft_qspi_transfer(self, 1 + len, (uint8_t *)&cmd_buf, NULL); - CS_HIGH(self); -} - -STATIC void mp_soft_qspi_write_cmd_addr_data(void *self_in, uint8_t cmd, uint32_t addr, size_t len, const uint8_t *src) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; - uint8_t cmd_buf[4] = {cmd, addr >> 16, addr >> 8, addr}; - CS_LOW(self); - mp_soft_qspi_transfer(self, 4, cmd_buf, NULL); - mp_soft_qspi_transfer(self, len, src, NULL); - CS_HIGH(self); -} - -STATIC uint32_t mp_soft_qspi_read_cmd(void *self_in, uint8_t cmd, size_t len) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; - uint32_t cmd_buf = cmd; - CS_LOW(self); - mp_soft_qspi_transfer(self, 1 + len, (uint8_t *)&cmd_buf, (uint8_t *)&cmd_buf); - CS_HIGH(self); - return cmd_buf >> 8; -} - -STATIC void mp_soft_qspi_read_cmd_qaddr_qdata(void *self_in, uint8_t cmd, uint32_t addr, size_t len, uint8_t *dest) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; - uint8_t cmd_buf[7] = {cmd, addr >> 16, addr >> 8, addr}; - CS_LOW(self); - mp_soft_qspi_transfer(self, 1, cmd_buf, NULL); - mp_soft_qspi_qwrite(self, 6, &cmd_buf[1]); // 3 addr bytes, 1 extra byte (0), 2 dummy bytes (4 dummy cycles) - mp_soft_qspi_qread(self, len, dest); - CS_HIGH(self); -} - -const mp_qspi_proto_t mp_soft_qspi_proto = { - .ioctl = mp_soft_qspi_ioctl, - .write_cmd_data = mp_soft_qspi_write_cmd_data, - .write_cmd_addr_data = mp_soft_qspi_write_cmd_addr_data, - .read_cmd = mp_soft_qspi_read_cmd, - .read_cmd_qaddr_qdata = mp_soft_qspi_read_cmd_qaddr_qdata, -}; diff --git a/drivers/bus/softspi.c b/drivers/bus/softspi.c deleted file mode 100644 index b0b1accd99..0000000000 --- a/drivers/bus/softspi.c +++ /dev/null @@ -1,105 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * SPDX-FileCopyrightText: Copyright (c) 2016-2018 Damien P. George - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include "drivers/bus/spi.h" - -int mp_soft_spi_ioctl(void *self_in, uint32_t cmd) { - mp_soft_spi_obj_t *self = (mp_soft_spi_obj_t *)self_in; - - switch (cmd) { - case MP_SPI_IOCTL_INIT: - mp_hal_pin_write(self->sck, self->polarity); - mp_hal_pin_output(self->sck); - mp_hal_pin_output(self->mosi); - mp_hal_pin_input(self->miso); - break; - - case MP_SPI_IOCTL_DEINIT: - break; - } - - return 0; -} - -void mp_soft_spi_transfer(void *self_in, size_t len, const uint8_t *src, uint8_t *dest) { - mp_soft_spi_obj_t *self = (mp_soft_spi_obj_t *)self_in; - uint32_t delay_half = self->delay_half; - - // only MSB transfer is implemented - - // If a port defines MICROPY_HW_SOFTSPI_MIN_DELAY, and the configured - // delay_half is equal to this value, then the software SPI implementation - // will run as fast as possible, limited only by CPU speed and GPIO time. - #ifdef MICROPY_HW_SOFTSPI_MIN_DELAY - if (delay_half == MICROPY_HW_SOFTSPI_MIN_DELAY) { - for (size_t i = 0; i < len; ++i) { - uint8_t data_out = src[i]; - uint8_t data_in = 0; - for (int j = 0; j < 8; ++j, data_out <<= 1) { - mp_hal_pin_write(self->mosi, (data_out >> 7) & 1); - mp_hal_pin_write(self->sck, 1 - self->polarity); - data_in = (data_in << 1) | mp_hal_pin_read(self->miso); - mp_hal_pin_write(self->sck, self->polarity); - } - if (dest != NULL) { - dest[i] = data_in; - } - } - return; - } - #endif - - for (size_t i = 0; i < len; ++i) { - uint8_t data_out = src[i]; - uint8_t data_in = 0; - for (int j = 0; j < 8; ++j, data_out <<= 1) { - mp_hal_pin_write(self->mosi, (data_out >> 7) & 1); - if (self->phase == 0) { - mp_hal_delay_us_fast(delay_half); - mp_hal_pin_write(self->sck, 1 - self->polarity); - } else { - mp_hal_pin_write(self->sck, 1 - self->polarity); - mp_hal_delay_us_fast(delay_half); - } - data_in = (data_in << 1) | mp_hal_pin_read(self->miso); - if (self->phase == 0) { - mp_hal_delay_us_fast(delay_half); - mp_hal_pin_write(self->sck, self->polarity); - } else { - mp_hal_pin_write(self->sck, self->polarity); - mp_hal_delay_us_fast(delay_half); - } - } - if (dest != NULL) { - dest[i] = data_in; - } - } -} - -const mp_spi_proto_t mp_soft_spi_proto = { - .ioctl = mp_soft_spi_ioctl, - .transfer = mp_soft_spi_transfer, -}; diff --git a/drivers/wiznet5k/README.md b/drivers/wiznet5k/README.md deleted file mode 100644 index 88f25a2b8d..0000000000 --- a/drivers/wiznet5k/README.md +++ /dev/null @@ -1,6 +0,0 @@ -This is the driver for the WIZnet5x00 series of Ethernet controllers. - -Adapted for MicroPython. - -Original source: https://github.com/Wiznet/W5500_EVB/tree/master/ioLibrary -Taken on: 30 August 2014 diff --git a/drivers/wiznet5k/ethernet/socket.c b/drivers/wiznet5k/ethernet/socket.c deleted file mode 100644 index 7a114aa1bc..0000000000 --- a/drivers/wiznet5k/ethernet/socket.c +++ /dev/null @@ -1,718 +0,0 @@ -//***************************************************************************** -// -//! \file socket.c -//! \brief SOCKET APIs Implements file. -//! \details SOCKET APIs like as Berkeley Socket APIs. -//! \version 1.0.3 -//! \date 2013/10/21 -//! \par Revision history -//! <2018/10/09> Nick Moore fixes for CircuitPython -//! <2014/05/01> V1.0.3. Refer to M20140501 -//! 1. Implicit type casting -> Explicit type casting. -//! 2. replace 0x01 with PACK_REMAINED in recvfrom() -//! 3. Validation a destination ip in connect() & sendto(): -//! It occurs a fatal error on converting unint32 address if uint8* addr parameter is not aligned by 4byte address. -//! Copy 4 byte addr value into temporary uint32 variable and then compares it. -//! <2013/12/20> V1.0.2 Refer to M20131220 -//! Remove Warning. -//! <2013/11/04> V1.0.1 2nd Release. Refer to "20131104". -//! In sendto(), Add to clear timeout interrupt status (Sn_IR_TIMEOUT) -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#include - -#include "py/mpthread.h" -#include "socket.h" - -#define SOCK_ANY_PORT_NUM 0xC000; - -static uint16_t sock_any_port = SOCK_ANY_PORT_NUM; -static uint16_t sock_io_mode = 0; -static uint16_t sock_is_sending = 0; -static uint16_t sock_remained_size[_WIZCHIP_SOCK_NUM_] = {0,0,}; -static uint8_t sock_pack_info[_WIZCHIP_SOCK_NUM_] = {0,}; - -#if _WIZCHIP_ == 5200 - static uint16_t sock_next_rd[_WIZCHIP_SOCK_NUM_] ={0,}; -#endif - -#define CHECK_SOCKNUM() \ - do{ \ - if(sn > _WIZCHIP_SOCK_NUM_) return SOCKERR_SOCKNUM; \ - }while(0); \ - -#define CHECK_SOCKMODE(mode) \ - do{ \ - if((getSn_MR(sn) & 0x0F) != mode) return SOCKERR_SOCKMODE; \ - }while(0); \ - -#define CHECK_SOCKINIT() \ - do{ \ - if((getSn_SR(sn) != SOCK_INIT)) return SOCKERR_SOCKINIT; \ - }while(0); \ - -#define CHECK_SOCKDATA() \ - do{ \ - if(len == 0) return SOCKERR_DATALEN; \ - }while(0); \ - -void WIZCHIP_EXPORT(socket_reset)(void) { - sock_any_port = SOCK_ANY_PORT_NUM; - sock_io_mode = 0; - sock_is_sending = 0; - /* - memset(sock_remained_size, 0, _WIZCHIP_SOCK_NUM_ * sizeof(uint16_t)); - memset(sock_pack_info, 0, _WIZCHIP_SOCK_NUM_ * sizeof(uint8_t)); - */ - -#if _WIZCHIP_ == 5200 - memset(sock_next_rd, 0, _WIZCHIP_SOCK_NUM_ * sizeof(uint16_t)); -#endif -} - -int8_t WIZCHIP_EXPORT(socket)(uint8_t sn, uint8_t protocol, uint16_t port, uint8_t flag) -{ - CHECK_SOCKNUM(); - switch(protocol) - { - case Sn_MR_TCP : - case Sn_MR_UDP : - case Sn_MR_MACRAW : - break; - #if ( _WIZCHIP_ < 5200 ) - case Sn_MR_IPRAW : - case Sn_MR_PPPoE : - break; - #endif - default : - return SOCKERR_SOCKMODE; - } - if((flag & 0x06) != 0) return SOCKERR_SOCKFLAG; -#if _WIZCHIP_ == 5200 - if(flag & 0x10) return SOCKERR_SOCKFLAG; -#endif - - if(flag != 0) - { - switch(protocol) - { - case Sn_MR_TCP: - if((flag & (SF_TCP_NODELAY|SF_IO_NONBLOCK))==0) return SOCKERR_SOCKFLAG; - break; - case Sn_MR_UDP: - if(flag & SF_IGMP_VER2) - { - if((flag & SF_MULTI_ENABLE)==0) return SOCKERR_SOCKFLAG; - } - #if _WIZCHIP_ == 5500 - if(flag & SF_UNI_BLOCK) - { - if((flag & SF_MULTI_ENABLE) == 0) return SOCKERR_SOCKFLAG; - } - #endif - break; - default: - break; - } - } - WIZCHIP_EXPORT(close)(sn); - setSn_MR(sn, (protocol | (flag & 0xF0))); - if(!port) - { - port = sock_any_port++; - if(sock_any_port == 0xFFF0) sock_any_port = SOCK_ANY_PORT_NUM; - } - setSn_PORT(sn,port); - setSn_CR(sn,Sn_CR_OPEN); - while(getSn_CR(sn)); - sock_io_mode |= ((flag & SF_IO_NONBLOCK) << sn); - sock_is_sending &= ~(1< freesize) len = freesize; // check size not to exceed MAX size. - while(1) - { - freesize = getSn_TX_FSR(sn); - tmp = getSn_SR(sn); - if ((tmp != SOCK_ESTABLISHED) && (tmp != SOCK_CLOSE_WAIT)) - { - WIZCHIP_EXPORT(close)(sn); - return SOCKERR_SOCKSTATUS; - } - if( (sock_io_mode & (1< freesize) ) return SOCK_BUSY; - if(len <= freesize) break; - MICROPY_THREAD_YIELD(); - } - wiz_send_data(sn, buf, len); - #if _WIZCHIP_ == 5200 - sock_next_rd[sn] = getSn_TX_RD(sn) + len; - #endif - setSn_CR(sn,Sn_CR_SEND); - /* wait to process the command... */ - while(getSn_CR(sn)); - sock_is_sending |= (1 << sn); - return len; -} - - -int32_t WIZCHIP_EXPORT(recv)(uint8_t sn, uint8_t * buf, uint16_t len) -{ - uint8_t tmp = 0; - uint16_t recvsize = 0; - CHECK_SOCKNUM(); - CHECK_SOCKMODE(Sn_MR_TCP); - CHECK_SOCKDATA(); - - recvsize = getSn_RxMAX(sn); - if(recvsize < len) len = recvsize; - while(1) - { - recvsize = getSn_RX_RSR(sn); - tmp = getSn_SR(sn); - if (tmp != SOCK_ESTABLISHED) - { - if(tmp == SOCK_CLOSE_WAIT) - { - if(recvsize != 0) break; - else if(getSn_TX_FSR(sn) == getSn_TxMAX(sn)) - { - // dpgeorge: Getting here seems to be an orderly shutdown of the - // socket, and trying to get POSIX behaviour we return 0 because: - // "If no messages are available to be received and the peer has per‐ - // formed an orderly shutdown, recv() shall return 0". - // TODO this return value clashes with SOCK_BUSY in non-blocking mode. - WIZCHIP_EXPORT(close)(sn); - return 0; - } - } - else - { - WIZCHIP_EXPORT(close)(sn); - return SOCKERR_SOCKSTATUS; - } - } - if((sock_io_mode & (1< freesize) len = freesize; // check size not to exceed MAX size. - while(1) - { - freesize = getSn_TX_FSR(sn); - if(getSn_SR(sn) == SOCK_CLOSED) return SOCKERR_SOCKCLOSED; - if( (sock_io_mode & (1< freesize) ) return SOCK_BUSY; - if(len <= freesize) break; - MICROPY_THREAD_YIELD(); - }; - wiz_send_data(sn, buf, len); - - #if _WIZCHIP_ == 5200 // for W5200 ARP errata - setSUBR(wizchip_getsubn()); - #endif - - setSn_CR(sn,Sn_CR_SEND); - /* wait to process the command... */ - while(getSn_CR(sn)); - while(1) - { - tmp = getSn_IR(sn); - if(tmp & Sn_IR_SENDOK) - { - setSn_IR(sn, Sn_IR_SENDOK); - break; - } - //M:20131104 - //else if(tmp & Sn_IR_TIMEOUT) return SOCKERR_TIMEOUT; - else if(tmp & Sn_IR_TIMEOUT) - { - setSn_IR(sn, Sn_IR_TIMEOUT); - #if _WIZCHIP_ == 5200 // for W5200 ARP errata - setSUBR((uint8_t*)"\x00\x00\x00\x00"); - #endif - return SOCKERR_TIMEOUT; - } - //////////// - MICROPY_THREAD_YIELD(); - } - #if _WIZCHIP_ == 5200 // for W5200 ARP errata - setSUBR((uint8_t*)"\x00\x00\x00\x00"); - #endif - return len; -} - - - -int32_t WIZCHIP_EXPORT(recvfrom)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t *port) -{ - uint8_t mr; - uint8_t head[8]; - uint16_t pack_len=0; - - CHECK_SOCKNUM(); - //CHECK_SOCKMODE(Sn_MR_UDP); - switch((mr=getSn_MR(sn)) & 0x0F) - { - case Sn_MR_UDP: - case Sn_MR_MACRAW: - break; - #if ( _WIZCHIP_ < 5200 ) - case Sn_MR_IPRAW: - case Sn_MR_PPPoE: - break; - #endif - default: - return SOCKERR_SOCKMODE; - } - CHECK_SOCKDATA(); - if(sock_remained_size[sn] == 0) - { - while(1) - { - pack_len = getSn_RX_RSR(sn); - if(getSn_SR(sn) == SOCK_CLOSED) return SOCKERR_SOCKCLOSED; - if( (sock_io_mode & (1< 1514) - { - WIZCHIP_EXPORT(close)(sn); - return SOCKFATAL_PACKLEN; - } - sock_pack_info[sn] = PACK_FIRST; - } - if(len < sock_remained_size[sn]) pack_len = len; - else pack_len = sock_remained_size[sn]; - wiz_recv_data(sn,buf,pack_len); - break; - #if ( _WIZCHIP_ < 5200 ) - case Sn_MR_IPRAW: - if(sock_remained_size[sn] == 0) - { - wiz_recv_data(sn, head, 6); - setSn_CR(sn,Sn_CR_RECV); - while(getSn_CR(sn)); - addr[0] = head[0]; - addr[1] = head[1]; - addr[2] = head[2]; - addr[3] = head[3]; - sock_remained_size[sn] = head[4]; - sock_remaiend_size[sn] = (sock_remained_size[sn] << 8) + head[5]; - sock_pack_info[sn] = PACK_FIRST; - } - // - // Need to packet length check - // - if(len < sock_remained_size[sn]) pack_len = len; - else pack_len = sock_remained_size[sn]; - wiz_recv_data(sn, buf, pack_len); // data copy. - break; - #endif - default: - wiz_recv_ignore(sn, pack_len); // data copy. - sock_remained_size[sn] = pack_len; - break; - } - setSn_CR(sn,Sn_CR_RECV); - /* wait to process the command... */ - while(getSn_CR(sn)) ; - sock_remained_size[sn] -= pack_len; - //M20140501 : replace 0x01 with PACK_REMAINED - //if(sock_remained_size[sn] != 0) sock_pack_info[sn] |= 0x01; - if(sock_remained_size[sn] != 0) sock_pack_info[sn] |= PACK_REMAINED; - // - return pack_len; -} - - -int8_t WIZCHIP_EXPORT(ctlsocket)(uint8_t sn, ctlsock_type cstype, void* arg) -{ - uint8_t tmp = 0; - CHECK_SOCKNUM(); - switch(cstype) - { - case CS_SET_IOMODE: - tmp = *((uint8_t*)arg); - if(tmp == SOCK_IO_NONBLOCK) sock_io_mode |= (1< explict type casting - //*((uint8_t*)arg) = (sock_io_mode >> sn) & 0x0001; - *((uint8_t*)arg) = (uint8_t)((sock_io_mode >> sn) & 0x0001); - // - break; - case CS_GET_MAXTXBUF: - *((uint16_t*)arg) = getSn_TxMAX(sn); - break; - case CS_GET_MAXRXBUF: - *((uint16_t*)arg) = getSn_RxMAX(sn); - break; - case CS_CLR_INTERRUPT: - if( (*(uint8_t*)arg) > SIK_ALL) return SOCKERR_ARG; - setSn_IR(sn,*(uint8_t*)arg); - break; - case CS_GET_INTERRUPT: - *((uint8_t*)arg) = getSn_IR(sn); - break; - case CS_SET_INTMASK: - if( (*(uint8_t*)arg) > SIK_ALL) return SOCKERR_ARG; - setSn_IMR(sn,*(uint8_t*)arg); - break; - case CS_GET_INTMASK: - *((uint8_t*)arg) = getSn_IMR(sn); - default: - return SOCKERR_ARG; - } - return SOCK_OK; -} - -int8_t WIZCHIP_EXPORT(setsockopt)(uint8_t sn, sockopt_type sotype, void* arg) -{ - // M20131220 : Remove warning - //uint8_t tmp; - CHECK_SOCKNUM(); - switch(sotype) - { - case SO_TTL: - setSn_TTL(sn,*(uint8_t*)arg); - break; - case SO_TOS: - setSn_TOS(sn,*(uint8_t*)arg); - break; - case SO_MSS: - setSn_MSSR(sn,*(uint16_t*)arg); - break; - case SO_DESTIP: - setSn_DIPR(sn, (uint8_t*)arg); - break; - case SO_DESTPORT: - setSn_DPORT(sn, *(uint16_t*)arg); - break; -#if _WIZCHIP_ != 5100 - case SO_KEEPALIVESEND: - CHECK_SOCKMODE(Sn_MR_TCP); - #if _WIZCHIP_ > 5200 - if(getSn_KPALVTR(sn) != 0) return SOCKERR_SOCKOPT; - #endif - setSn_CR(sn,Sn_CR_SEND_KEEP); - while(getSn_CR(sn) != 0) - { - // M20131220 - //if ((tmp = getSn_IR(sn)) & Sn_IR_TIMEOUT) - if (getSn_IR(sn) & Sn_IR_TIMEOUT) - { - setSn_IR(sn, Sn_IR_TIMEOUT); - return SOCKERR_TIMEOUT; - } - } - break; - #if _WIZCHIP_ > 5200 - case SO_KEEPALIVEAUTO: - CHECK_SOCKMODE(Sn_MR_TCP); - setSn_KPALVTR(sn,*(uint8_t*)arg); - break; - #endif -#endif - default: - return SOCKERR_ARG; - } - return SOCK_OK; -} - -int8_t WIZCHIP_EXPORT(getsockopt)(uint8_t sn, sockopt_type sotype, void* arg) -{ - CHECK_SOCKNUM(); - switch(sotype) - { - case SO_FLAG: - *(uint8_t*)arg = getSn_MR(sn) & 0xF0; - break; - case SO_TTL: - *(uint8_t*) arg = getSn_TTL(sn); - break; - case SO_TOS: - *(uint8_t*) arg = getSn_TOS(sn); - break; - case SO_MSS: - *(uint8_t*) arg = getSn_MSSR(sn); - case SO_DESTIP: - getSn_DIPR(sn, (uint8_t*)arg); - break; - case SO_DESTPORT: - *(uint16_t*) arg = getSn_DPORT(sn); - break; - #if _WIZCHIP_ > 5200 - case SO_KEEPALIVEAUTO: - CHECK_SOCKMODE(Sn_MR_TCP); - *(uint16_t*) arg = getSn_KPALVTR(sn); - break; - #endif - case SO_SENDBUF: - *(uint16_t*) arg = getSn_TX_FSR(sn); - case SO_RECVBUF: - *(uint16_t*) arg = getSn_RX_RSR(sn); - case SO_STATUS: - *(uint8_t*) arg = getSn_SR(sn); - break; - case SO_REMAINSIZE: - if(getSn_MR(sn) == Sn_MR_TCP) - *(uint16_t*)arg = getSn_RX_RSR(sn); - else - *(uint16_t*)arg = sock_remained_size[sn]; - break; - case SO_PACKINFO: - CHECK_SOCKMODE(Sn_MR_TCP); - *(uint8_t*)arg = sock_pack_info[sn]; - break; - default: - return SOCKERR_SOCKOPT; - } - return SOCK_OK; -} diff --git a/drivers/wiznet5k/ethernet/socket.h b/drivers/wiznet5k/ethernet/socket.h deleted file mode 100644 index 4f602e429c..0000000000 --- a/drivers/wiznet5k/ethernet/socket.h +++ /dev/null @@ -1,472 +0,0 @@ -//***************************************************************************** -// -//! \file socket.h -//! \brief SOCKET APIs Header file. -//! \details SOCKET APIs like as berkeley socket api. -//! \version 1.0.2 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.2. Refer to M20140501 -//! 1. Modify the comment : SO_REMAINED -> PACK_REMAINED -//! 2. Add the comment as zero byte udp data reception in getsockopt(). -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** -/** - * @defgroup WIZnet_socket_APIs 1. WIZnet socket APIs - * @brief WIZnet socket APIs are based on Berkeley socket APIs, thus it has much similar name and interface. - * But there is a little bit of difference. - * @details - * Comparison between WIZnet and Berkeley SOCKET APIs - * - * - * - * - * - * - * - * - * - * - * - * - *
API WIZnet Berkeley
socket() O O
bind() X O
listen() O O
connect() O O
accept() X O
recv() O O
send() O O
recvfrom() O O
sendto() O O
closesocket() O
close() & disconnect()
O
- * There are @b bind() and @b accept() functions in @b Berkeley SOCKET API but, - * not in @b WIZnet SOCKET API. Because socket() of WIZnet is not only creating a SOCKET but also binding a local port number, - * and listen() of WIZnet is not only listening to connection request from client but also accepting the connection request. \n - * When you program "TCP SERVER" with Berkeley SOCKET API, you can use only one listen port. - * When the listen SOCKET accepts a connection request from a client, it keeps listening. - * After accepting the connection request, a new SOCKET is created and the new SOCKET is used in communication with the client. \n - * Following figure shows network flow diagram by Berkeley SOCKET API. - * @image html Berkeley_SOCKET.jpg "" - * But, When you program "TCP SERVER" with WIZnet SOCKET API, you can use as many as 8 listen SOCKET with same port number. \n - * Because there's no accept() in WIZnet SOCKET APIs, when the listen SOCKET accepts a connection request from a client, - * it is changed in order to communicate with the client. - * And the changed SOCKET is not listening any more and is dedicated for communicating with the client. \n - * If there're many listen SOCKET with same listen port number and a client requests a connection, - * the SOCKET which has the smallest SOCKET number accepts the request and is changed as communication SOCKET. \n - * Following figure shows network flow diagram by WIZnet SOCKET API. - * @image html WIZnet_SOCKET.jpg "" - */ -#ifndef _WIZCHIP_SOCKET_H_ -#define _WIZCHIP_SOCKET_H_ - -// use this macro for exported names to avoid name clashes -#define WIZCHIP_EXPORT(name) wizchip_ ## name - -#include "wizchip_conf.h" - -#define SOCKET uint8_t ///< SOCKET type define for legacy driver - -#define SOCK_OK 1 ///< Result is OK about socket process. -#define SOCK_BUSY 0 ///< Socket is busy on processing the operation. Valid only Non-block IO Mode. -#define SOCK_FATAL -1000 ///< Result is fatal error about socket process. - -#define SOCK_ERROR 0 -#define SOCKERR_SOCKNUM (SOCK_ERROR - 1) ///< Invalid socket number -#define SOCKERR_SOCKOPT (SOCK_ERROR - 2) ///< Invalid socket option -#define SOCKERR_SOCKINIT (SOCK_ERROR - 3) ///< Socket is not initialized -#define SOCKERR_SOCKCLOSED (SOCK_ERROR - 4) ///< Socket unexpectedly closed. -#define SOCKERR_SOCKMODE (SOCK_ERROR - 5) ///< Invalid socket mode for socket operation. -#define SOCKERR_SOCKFLAG (SOCK_ERROR - 6) ///< Invalid socket flag -#define SOCKERR_SOCKSTATUS (SOCK_ERROR - 7) ///< Invalid socket status for socket operation. -#define SOCKERR_ARG (SOCK_ERROR - 10) ///< Invalid argument. -#define SOCKERR_PORTZERO (SOCK_ERROR - 11) ///< Port number is zero -#define SOCKERR_IPINVALID (SOCK_ERROR - 12) ///< Invalid IP address -#define SOCKERR_TIMEOUT (SOCK_ERROR - 13) ///< Timeout occurred -#define SOCKERR_DATALEN (SOCK_ERROR - 14) ///< Data length is zero or greater than buffer max size. -#define SOCKERR_BUFFER (SOCK_ERROR - 15) ///< Socket buffer is not enough for data communication. - -#define SOCKFATAL_PACKLEN (SOCK_FATAL - 1) ///< Invalid packet length. Fatal Error. - -/* - * SOCKET FLAG - */ -#define SF_ETHER_OWN (Sn_MR_MFEN) ///< In \ref Sn_MR_MACRAW, Receive only the packet as broadcast, multicast and own packet -#define SF_IGMP_VER2 (Sn_MR_MC) ///< In \ref Sn_MR_UDP with \ref SF_MULTI_ENABLE, Select IGMP version 2. -#define SF_TCP_NODELAY (Sn_MR_ND) ///< In \ref Sn_MR_TCP, Use to nodelayed ack. -#define SF_MULTI_ENABLE (Sn_MR_MULTI) ///< In \ref Sn_MR_UDP, Enable multicast mode. - -#if _WIZCHIP_ == 5500 - #define SF_BROAD_BLOCK (Sn_MR_BCASTB) ///< In \ref Sn_MR_UDP or \ref Sn_MR_MACRAW, Block broadcast packet. Valid only in W5500 - #define SF_MULTI_BLOCK (Sn_MR_MMB) ///< In \ref Sn_MR_MACRAW, Block multicast packet. Valid only in W5500 - #define SF_IPv6_BLOCK (Sn_MR_MIP6B) ///< In \ref Sn_MR_MACRAW, Block IPv6 packet. Valid only in W5500 - #define SF_UNI_BLOCK (Sn_MR_UCASTB) ///< In \ref Sn_MR_UDP with \ref SF_MULTI_ENABLE. Valid only in W5500 -#endif - -#define SF_IO_NONBLOCK 0x01 ///< Socket nonblock io mode. It used parameter in \ref socket(). - -/* - * UDP & MACRAW Packet Infomation - */ -#define PACK_FIRST 0x80 ///< In Non-TCP packet, It indicates to start receiving a packet. -#define PACK_REMAINED 0x01 ///< In Non-TCP packet, It indicates to remain a packet to be received. -#define PACK_COMPLETED 0x00 ///< In Non-TCP packet, It indicates to complete to receive a packet. - -// resets all global state associated with the socket interface -void WIZCHIP_EXPORT(socket_reset)(void); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Open a socket. - * @details Initializes the socket with 'sn' passed as parameter and open. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param protocol Protocol type to operate such as TCP, UDP and MACRAW. - * @param port Port number to be bined. - * @param flag Socket flags as \ref SF_ETHER_OWN, \ref SF_IGMP_VER2, \ref SF_TCP_NODELAY, \ref SF_MULTI_ENABLE, \ref SF_IO_NONBLOCK and so on.\n - * Valid flags only in W5500 : @ref SF_BROAD_BLOCK, @ref SF_MULTI_BLOCK, @ref SF_IPv6_BLOCK, and @ref SF_UNI_BLOCK. - * @sa Sn_MR - * - * @return @b Success : The socket number @b 'sn' passed as parameter\n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number\n - * @ref SOCKERR_SOCKMODE - Not support socket mode as TCP, UDP, and so on. \n - * @ref SOCKERR_SOCKFLAG - Invaild socket flag. - */ -int8_t WIZCHIP_EXPORT(socket)(uint8_t sn, uint8_t protocol, uint16_t port, uint8_t flag); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Close a socket. - * @details It closes the socket with @b'sn' passed as parameter. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * - * @return @b Success : @ref SOCK_OK \n - * @b Fail : @ref SOCKERR_SOCKNUM - Invalid socket number - */ -int8_t WIZCHIP_EXPORT(close)(uint8_t sn); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Listen to a connection request from a client. - * @details It is listening to a connection request from a client. - * If connection request is accepted successfully, the connection is established. Socket sn is used in passive(server) mode. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @return @b Success : @ref SOCK_OK \n - * @b Fail :\n @ref SOCKERR_SOCKINIT - Socket is not initialized \n - * @ref SOCKERR_SOCKCLOSED - Socket closed unexpectedly. - */ -int8_t WIZCHIP_EXPORT(listen)(uint8_t sn); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Try to connect a server. - * @details It requests connection to the server with destination IP address and port number passed as parameter.\n - * @note It is valid only in TCP client mode. - * In block io mode, it does not return until connection is completed. - * In Non-block io mode, it return @ref SOCK_BUSY immediately. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param addr Pointer variable of destination IP address. It should be allocated 4 bytes. - * @param port Destination port number. - * - * @return @b Success : @ref SOCK_OK \n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number\n - * @ref SOCKERR_SOCKMODE - Invalid socket mode\n - * @ref SOCKERR_SOCKINIT - Socket is not initialized\n - * @ref SOCKERR_IPINVALID - Wrong server IP address\n - * @ref SOCKERR_PORTZERO - Server port zero\n - * @ref SOCKERR_TIMEOUT - Timeout occurred during request connection\n - * @ref SOCK_BUSY - In non-block io mode, it returned immediately\n - */ -int8_t WIZCHIP_EXPORT(connect)(uint8_t sn, uint8_t * addr, uint16_t port); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Try to disconnect a connection socket. - * @details It sends request message to disconnect the TCP socket 'sn' passed as parameter to the server or client. - * @note It is valid only in TCP server or client mode. \n - * In block io mode, it does not return until disconnection is completed. \n - * In Non-block io mode, it return @ref SOCK_BUSY immediately. \n - - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @return @b Success : @ref SOCK_OK \n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_TIMEOUT - Timeout occurred \n - * @ref SOCK_BUSY - Socket is busy. - */ -int8_t WIZCHIP_EXPORT(disconnect)(uint8_t sn); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Send data to the connected peer in TCP socket. - * @details It is used to send outgoing data to the connected socket. - * @note It is valid only in TCP server or client mode. It can't send data greater than socket buffer size. \n - * In block io mode, It doesn't return until data send is completed - socket buffer size is greater than data. \n - * In non-block io mode, It return @ref SOCK_BUSY immediately when socket buffer is not enough. \n - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer containing data to be sent. - * @param len The byte length of data in buf. - * @return @b Success : The sent data size \n - * @b Fail : \n @ref SOCKERR_SOCKSTATUS - Invalid socket status for socket operation \n - * @ref SOCKERR_TIMEOUT - Timeout occurred \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCK_BUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(send)(uint8_t sn, uint8_t * buf, uint16_t len); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Receive data from the connected peer. - * @details It is used to read incoming data from the connected socket.\n - * It waits for data as much as the application wants to receive. - * @note It is valid only in TCP server or client mode. It can't receive data greater than socket buffer size. \n - * In block io mode, it doesn't return until data reception is completed - data is filled as len in socket buffer. \n - * In non-block io mode, it return @ref SOCK_BUSY immediately when len is greater than data size in socket buffer. \n - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer to read incoming data. - * @param len The max data length of data in buf. - * @return @b Success : The real received data size \n - * @b Fail :\n - * @ref SOCKERR_SOCKSTATUS - Invalid socket status for socket operation \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCK_BUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(recv)(uint8_t sn, uint8_t * buf, uint16_t len); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Sends datagram to the peer with destination IP address and port number passed as parameter. - * @details It sends datagram of UDP or MACRAW to the peer with destination IP address and port number passed as parameter.\n - * Even if the connectionless socket has been previously connected to a specific address, - * the address and port number parameters override the destination address for that particular datagram only. - * @note In block io mode, It doesn't return until data send is completed - socket buffer size is greater than len. - * In non-block io mode, It return @ref SOCK_BUSY immediately when socket buffer is not enough. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer to send outgoing data. - * @param len The byte length of data in buf. - * @param addr Pointer variable of destination IP address. It should be allocated 4 bytes. - * @param port Destination port number. - * - * @return @b Success : The sent data size \n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKSTATUS - Invalid socket status for socket operation \n - * @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCKERR_IPINVALID - Wrong server IP address\n - * @ref SOCKERR_PORTZERO - Server port zero\n - * @ref SOCKERR_SOCKCLOSED - Socket unexpectedly closed \n - * @ref SOCKERR_TIMEOUT - Timeout occurred \n - * @ref SOCK_BUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(sendto)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t port); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Receive datagram of UDP or MACRAW - * @details This function is an application I/F function which is used to receive the data in other then TCP mode. \n - * This function is used to receive UDP and MAC_RAW mode, and handle the header as well. - * This function can divide to received the packet data. - * On the MACRAW SOCKET, the addr and port parameters are ignored. - * @note In block io mode, it doesn't return until data reception is completed - data is filled as len in socket buffer - * In non-block io mode, it return @ref SOCK_BUSY immediately when len is greater than data size in socket buffer. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer to read incoming data. - * @param len The max data length of data in buf. - * When the received packet size <= len, receives data as packet sized. - * When others, receives data as len. - * @param addr Pointer variable of destination IP address. It should be allocated 4 bytes. - * It is valid only when the first call recvfrom for receiving the packet. - * When it is valid, @ref packinfo[7] should be set as '1' after call @ref getsockopt(sn, SO_PACKINFO, &packinfo). - * @param port Pointer variable of destination port number. - * It is valid only when the first call recvform for receiving the packet. -* When it is valid, @ref packinfo[7] should be set as '1' after call @ref getsockopt(sn, SO_PACKINFO, &packinfo). - * - * @return @b Success : This function return real received data size for success.\n - * @b Fail : @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKBUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(recvfrom)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t *port); - - -///////////////////////////// -// SOCKET CONTROL & OPTION // -///////////////////////////// -#define SOCK_IO_BLOCK 0 ///< Socket Block IO Mode in @ref setsockopt(). -#define SOCK_IO_NONBLOCK 1 ///< Socket Non-block IO Mode in @ref setsockopt(). - -/** - * @defgroup DATA_TYPE DATA TYPE - */ - -/** - * @ingroup DATA_TYPE - * @brief The kind of Socket Interrupt. - * @sa Sn_IR, Sn_IMR, setSn_IR(), getSn_IR(), setSn_IMR(), getSn_IMR() - */ -typedef enum -{ - SIK_CONNECTED = (1 << 0), ///< connected - SIK_DISCONNECTED = (1 << 1), ///< disconnected - SIK_RECEIVED = (1 << 2), ///< data received - SIK_TIMEOUT = (1 << 3), ///< timeout occurred - SIK_SENT = (1 << 4), ///< send ok - SIK_ALL = 0x1F, ///< all interrupt -}sockint_kind; - -/** - * @ingroup DATA_TYPE - * @brief The type of @ref ctlsocket(). - */ -typedef enum -{ - CS_SET_IOMODE, ///< set socket IO mode with @ref SOCK_IO_BLOCK or @ref SOCK_IO_NONBLOCK - CS_GET_IOMODE, ///< get socket IO mode - CS_GET_MAXTXBUF, ///< get the size of socket buffer allocated in TX memory - CS_GET_MAXRXBUF, ///< get the size of socket buffer allocated in RX memory - CS_CLR_INTERRUPT, ///< clear the interrupt of socket with @ref sockint_kind - CS_GET_INTERRUPT, ///< get the socket interrupt. refer to @ref sockint_kind - CS_SET_INTMASK, ///< set the interrupt mask of socket with @ref sockint_kind - CS_GET_INTMASK ///< get the masked interrupt of socket. refer to @ref sockint_kind -}ctlsock_type; - - -/** - * @ingroup DATA_TYPE - * @brief The type of socket option in @ref setsockopt() or @ref getsockopt() - */ -typedef enum -{ - SO_FLAG, ///< Valid only in getsockopt(), For set flag of socket refer to flag in @ref socket(). - SO_TTL, ///< Set/Get TTL. @ref Sn_TTL ( @ref setSn_TTL(), @ref getSn_TTL() ) - SO_TOS, ///< Set/Get TOS. @ref Sn_TOS ( @ref setSn_TOS(), @ref getSn_TOS() ) - SO_MSS, ///< Set/Get MSS. @ref Sn_MSSR ( @ref setSn_MSSR(), @ref getSn_MSSR() ) - SO_DESTIP, ///< Set/Get the destination IP address. @ref Sn_DIPR ( @ref setSn_DIPR(), @ref getSn_DIPR() ) - SO_DESTPORT, ///< Set/Get the destination Port number. @ref Sn_DPORT ( @ref setSn_DPORT(), @ref getSn_DPORT() ) -#if _WIZCHIP_ != 5100 - SO_KEEPALIVESEND, ///< Valid only in setsockopt. Manually send keep-alive packet in TCP mode - #if _WIZCHIP_ > 5200 - SO_KEEPALIVEAUTO, ///< Set/Get keep-alive auto transmission timer in TCP mode - #endif -#endif - SO_SENDBUF, ///< Valid only in getsockopt. Get the free data size of Socekt TX buffer. @ref Sn_TX_FSR, @ref getSn_TX_FSR() - SO_RECVBUF, ///< Valid only in getsockopt. Get the received data size in socket RX buffer. @ref Sn_RX_RSR, @ref getSn_RX_RSR() - SO_STATUS, ///< Valid only in getsockopt. Get the socket status. @ref Sn_SR, @ref getSn_SR() - SO_REMAINSIZE, ///< Valid only in getsockopt. Get the remained packet size in other then TCP mode. - SO_PACKINFO ///< Valid only in getsockopt. Get the packet information as @ref PACK_FIRST, @ref PACK_REMAINED, and @ref PACK_COMPLETED in other then TCP mode. -}sockopt_type; - -/** - * @ingroup WIZnet_socket_APIs - * @brief Control socket. - * @details Control IO mode, Interrupt & Mask of socket and get the socket buffer information. - * Refer to @ref ctlsock_type. - * @param sn socket number - * @param cstype type of control socket. refer to @ref ctlsock_type. - * @param arg Data type and value is determined according to @ref ctlsock_type. \n - * - * - * - * - * - *
@b cstype @b data type@b value
@ref CS_SET_IOMODE \n @ref CS_GET_IOMODE uint8_t @ref SOCK_IO_BLOCK @ref SOCK_IO_NONBLOCK
@ref CS_GET_MAXTXBUF \n @ref CS_GET_MAXRXBUF uint16_t 0 ~ 16K
@ref CS_CLR_INTERRUPT \n @ref CS_GET_INTERRUPT \n @ref CS_SET_INTMASK \n @ref CS_GET_INTMASK @ref sockint_kind @ref SIK_CONNECTED, etc.
- * @return @b Success @ref SOCK_OK \n - * @b fail @ref SOCKERR_ARG - Invalid argument\n - */ -int8_t WIZCHIP_EXPORT(ctlsocket)(uint8_t sn, ctlsock_type cstype, void* arg); - -/** - * @ingroup WIZnet_socket_APIs - * @brief set socket options - * @details Set socket option like as TTL, MSS, TOS, and so on. Refer to @ref sockopt_type. - * - * @param sn socket number - * @param sotype socket option type. refer to @ref sockopt_type - * @param arg Data type and value is determined according to sotype. \n - * - * - * - * - * - * - * - * - * - *
@b sotype @b data type@b value
@ref SO_TTL uint8_t 0 ~ 255
@ref SO_TOS uint8_t 0 ~ 255
@ref SO_MSS uint16_t 0 ~ 65535
@ref SO_DESTIP uint8_t[4]
@ref SO_DESTPORT uint16_t 0 ~ 65535
@ref SO_KEEPALIVESEND null null
@ref SO_KEEPALIVEAUTO uint8_t 0 ~ 255
- * @return - * - @b Success : @ref SOCK_OK \n - * - @b Fail - * - @ref SOCKERR_SOCKNUM - Invalid Socket number \n - * - @ref SOCKERR_SOCKMODE - Invalid socket mode \n - * - @ref SOCKERR_SOCKOPT - Invalid socket option or its value \n - * - @ref SOCKERR_TIMEOUT - Timeout occurred when sending keep-alive packet \n - */ -int8_t WIZCHIP_EXPORT(setsockopt)(uint8_t sn, sockopt_type sotype, void* arg); - -/** - * @ingroup WIZnet_socket_APIs - * @brief get socket options - * @details Get socket option like as FLAG, TTL, MSS, and so on. Refer to @ref sockopt_type - * @param sn socket number - * @param sotype socket option type. refer to @ref sockopt_type - * @param arg Data type and value is determined according to sotype. \n - * - * - * - * - * - * - * - * - * - * - * - * - * - *
@b sotype @b data type@b value
@ref SO_FLAG uint8_t @ref SF_ETHER_OWN, etc...
@ref SO_TOS uint8_t 0 ~ 255
@ref SO_MSS uint16_t 0 ~ 65535
@ref SO_DESTIP uint8_t[4]
@ref SO_DESTPORT uint16_t
@ref SO_KEEPALIVEAUTO uint8_t 0 ~ 255
@ref SO_SENDBUF uint16_t 0 ~ 65535
@ref SO_RECVBUF uint16_t 0 ~ 65535
@ref SO_STATUS uint8_t @ref SOCK_ESTABLISHED, etc..
@ref SO_REMAINSIZE uint16_t 0~ 65535
@ref SO_PACKINFO uint8_t @ref PACK_FIRST, etc...
- * @return - * - @b Success : @ref SOCK_OK \n - * - @b Fail - * - @ref SOCKERR_SOCKNUM - Invalid Socket number \n - * - @ref SOCKERR_SOCKOPT - Invalid socket option or its value \n - * - @ref SOCKERR_SOCKMODE - Invalid socket mode \n - * @note - * The option as PACK_REMAINED and SO_PACKINFO is valid only in NON-TCP mode and after call @ref recvfrom(). \n - * When SO_PACKINFO value is PACK_FIRST and the return value of recvfrom() is zero, - * This means the zero byte UDP data(UDP Header only) received. - */ -int8_t WIZCHIP_EXPORT(getsockopt)(uint8_t sn, sockopt_type sotype, void* arg); - -#endif // _WIZCHIP_SOCKET_H_ diff --git a/drivers/wiznet5k/ethernet/w5200/w5200.c b/drivers/wiznet5k/ethernet/w5200/w5200.c deleted file mode 100644 index cbcb136091..0000000000 --- a/drivers/wiznet5k/ethernet/w5200/w5200.c +++ /dev/null @@ -1,206 +0,0 @@ -// dpgeorge: this file taken from w5500/w5500.c and adapted to W5200 - -//***************************************************************************** -// -//! \file w5500.c -//! \brief W5500 HAL Interface. -//! \version 1.0.1 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.2 -//! 1. Implicit type casting -> Explicit type casting. Refer to M20140501 -//! Fixed the problem on porting into under 32bit MCU -//! Issued by Mathias ClauBen, wizwiki forum ID Think01 and bobh -//! Thank for your interesting and serious advices. -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.0.1 -//! 1. Remove warning -//! 2. WIZCHIP_READ_BUF WIZCHIP_WRITE_BUF in case _WIZCHIP_IO_MODE_SPI_FDM_ -//! for loop optimized(removed). refer to M20131220 -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#include "w5200.h" - -#define SMASK (0x7ff) /* tx buffer mask */ -#define RMASK (0x7ff) /* rx buffer mask */ -#define SSIZE (2048) /* max tx buffer size */ -#define RSIZE (2048) /* max rx buffer size */ - -#define TXBUF_BASE (0x8000) -#define RXBUF_BASE (0xc000) -#define SBASE(sn) (TXBUF_BASE + SSIZE * (sn)) /* tx buffer base for socket sn */ -#define RBASE(sn) (RXBUF_BASE + RSIZE * (sn)) /* rx buffer base for socket sn */ - -uint8_t WIZCHIP_READ(uint32_t AddrSel) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[4] = { - AddrSel >> 8, - AddrSel, - 0x00, - 0x01, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 4); - uint8_t ret; - WIZCHIP.IF.SPI._read_bytes(&ret, 1); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); - - return ret; -} - -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[5] = { - AddrSel >> 8, - AddrSel, - 0x80, - 0x01, - wb, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 5); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_READ_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[4] = { - AddrSel >> 8, - AddrSel, - 0x00 | ((len >> 8) & 0x7f), - len & 0xff, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 4); - WIZCHIP.IF.SPI._read_bytes(pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[4] = { - AddrSel >> 8, - AddrSel, - 0x80 | ((len >> 8) & 0x7f), - len & 0xff, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 4); - WIZCHIP.IF.SPI._write_bytes(pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -uint16_t getSn_TX_FSR(uint8_t sn) { - uint16_t val = 0, val1 = 0; - do { - val1 = (WIZCHIP_READ(Sn_TX_FSR(sn)) << 8) | WIZCHIP_READ(Sn_TX_FSR(sn) + 1); - if (val1 != 0) { - val = (WIZCHIP_READ(Sn_TX_FSR(sn)) << 8) | WIZCHIP_READ(Sn_TX_FSR(sn) + 1); - } - } while (val != val1); - return val; -} - -uint16_t getSn_RX_RSR(uint8_t sn) { - uint16_t val = 0, val1 = 0; - do { - val1 = (WIZCHIP_READ(Sn_RX_RSR(sn)) << 8) | WIZCHIP_READ(Sn_RX_RSR(sn) + 1); - if (val1 != 0) { - val = (WIZCHIP_READ(Sn_RX_RSR(sn)) << 8) | WIZCHIP_READ(Sn_RX_RSR(sn) + 1); - } - } while (val != val1); - return val; -} - -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len) { - if (len == 0) { - return; - } - - uint16_t ptr = getSn_TX_WR(sn); - uint16_t offset = ptr & SMASK; - uint32_t addr = offset + SBASE(sn); - - if (offset + len > SSIZE) { - // implement wrap-around circular buffer - uint16_t size = SSIZE - offset; - WIZCHIP_WRITE_BUF(addr, wizdata, size); - WIZCHIP_WRITE_BUF(SBASE(sn), wizdata + size, len - size); - } else { - WIZCHIP_WRITE_BUF(addr, wizdata, len); - } - - ptr += len; - setSn_TX_WR(sn, ptr); -} - -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len) { - if (len == 0) { - return; - } - - uint16_t ptr = getSn_RX_RD(sn); - uint16_t offset = ptr & RMASK; - uint16_t addr = RBASE(sn) + offset; - - if (offset + len > RSIZE) { - // implement wrap-around circular buffer - uint16_t size = RSIZE - offset; - WIZCHIP_READ_BUF(addr, wizdata, size); - WIZCHIP_READ_BUF(RBASE(sn), wizdata + size, len - size); - } else { - WIZCHIP_READ_BUF(addr, wizdata, len); - } - - ptr += len; - setSn_RX_RD(sn, ptr); -} - -void wiz_recv_ignore(uint8_t sn, uint16_t len) { - uint16_t ptr = getSn_RX_RD(sn); - ptr += len; - setSn_RX_RD(sn, ptr); -} diff --git a/drivers/wiznet5k/ethernet/w5200/w5200.h b/drivers/wiznet5k/ethernet/w5200/w5200.h deleted file mode 100644 index 988c8827fc..0000000000 --- a/drivers/wiznet5k/ethernet/w5200/w5200.h +++ /dev/null @@ -1,2092 +0,0 @@ -// dpgeorge: this file taken from w5500/w5500.h and adapted to W5200 - -//***************************************************************************** -// -//! \file w5500.h -//! \brief W5500 HAL Header File. -//! \version 1.0.0 -//! \date 2013/10/21 -//! \par Revision history -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#ifndef _W5200_H_ -#define _W5200_H_ - -#include -#include "../wizchip_conf.h" -//#include "board.h" - -#define _W5200_IO_BASE_ 0x00000000 - -#define WIZCHIP_CREG_ADDR(addr) (_W5200_IO_BASE_ + (addr)) - -#define WIZCHIP_CH_BASE (0x4000) -#define WIZCHIP_CH_SIZE (0x100) -#define WIZCHIP_SREG_ADDR(sn, addr) (_W5200_IO_BASE_ + WIZCHIP_CH_BASE + (sn) * WIZCHIP_CH_SIZE + (addr)) - -////////////////////////////// -//-------------------------- defgroup --------------------------------- -/** - * @defgroup W5500 W5500 - * - * @brief WHIZCHIP register defines and I/O functions of @b W5500. - * - * - @ref WIZCHIP_register : @ref Common_register_group and @ref Socket_register_group - * - @ref WIZCHIP_IO_Functions : @ref Basic_IO_function, @ref Common_register_access_function and @ref Socket_register_access_function - */ - - -/** - * @defgroup WIZCHIP_register WIZCHIP register - * @ingroup W5500 - * - * @brief WHIZCHIP register defines register group of @b W5500. - * - * - @ref Common_register_group : Common register group - * - @ref Socket_register_group : \c SOCKET n register group - */ - - -/** - * @defgroup WIZCHIP_IO_Functions WIZCHIP I/O functions - * @ingroup W5500 - * - * @brief This supports the basic I/O functions for @ref WIZCHIP_register. - * - * - Basic I/O function \n - * WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() \n\n - * - * - @ref Common_register_group access functions \n - * -# @b Mode \n - * getMR(), setMR() - * -# @b Interrupt \n - * getIR(), setIR(), getIMR(), setIMR(), getSIR(), setSIR(), getSIMR(), setSIMR(), getINTLEVEL(), setINTLEVEL() - * -# Network Information \n - * getSHAR(), setSHAR(), getGAR(), setGAR(), getSUBR(), setSUBR(), getSIPR(), setSIPR() - * -# @b Retransmission \n - * getRCR(), setRCR(), getRTR(), setRTR() - * -# @b PPPoE \n - * getPTIMER(), setPTIMER(), getPMAGIC(), getPMAGIC(), getPSID(), setPSID(), getPHAR(), setPHAR(), getPMRU(), setPMRU() - * -# ICMP packet \n - * getUIPR(), getUPORTR() - * -# @b etc. \n - * getPHYCFGR(), setPHYCFGR(), getVERSIONR() \n\n - * - * - \ref Socket_register_group access functions \n - * -# SOCKET control \n - * getSn_MR(), setSn_MR(), getSn_CR(), setSn_CR(), getSn_IMR(), setSn_IMR(), getSn_IR(), setSn_IR() - * -# SOCKET information \n - * getSn_SR(), getSn_DHAR(), setSn_DHAR(), getSn_PORT(), setSn_PORT(), getSn_DIPR(), setSn_DIPR(), getSn_DPORT(), setSn_DPORT() - * getSn_MSSR(), setSn_MSSR() - * -# SOCKET communication \n - * getSn_RXBUF_SIZE(), setSn_RXBUF_SIZE(), getSn_TXBUF_SIZE(), setSn_TXBUF_SIZE() \n - * getSn_TX_RD(), getSn_TX_WR(), setSn_TX_WR() \n - * getSn_RX_RD(), setSn_RX_RD(), getSn_RX_WR() \n - * getSn_TX_FSR(), getSn_RX_RSR(), getSn_KPALVTR(), setSn_KPALVTR() - * -# IP header field \n - * getSn_FRAG(), setSn_FRAG(), getSn_TOS(), setSn_TOS() \n - * getSn_TTL(), setSn_TTL() - */ - - - -/** - * @defgroup Common_register_group Common register - * @ingroup WIZCHIP_register - * - * @brief Common register group\n - * It set the basic for the networking\n - * It set the configuration such as interrupt, network information, ICMP, etc. - * @details - * @sa MR : Mode register. - * @sa GAR, SUBR, SHAR, SIPR - * @sa INTLEVEL, IR, IMR, SIR, SIMR : Interrupt. - * @sa RTR, RCR : Data retransmission. - * @sa PTIMER, PMAGIC, PHAR, PSID, PMRU : PPPoE. - * @sa UIPR, UPORTR : ICMP message. - * @sa PHYCFGR, VERSIONR : etc. - */ - - - -/** - * @defgroup Socket_register_group Socket register - * @ingroup WIZCHIP_register - * - * @brief Socket register group.\n - * Socket register configures and control SOCKETn which is necessary to data communication. - * @details - * @sa Sn_MR, Sn_CR, Sn_IR, Sn_IMR : SOCKETn Control - * @sa Sn_SR, Sn_PORT, Sn_DHAR, Sn_DIPR, Sn_DPORT : SOCKETn Information - * @sa Sn_MSSR, Sn_TOS, Sn_TTL, Sn_KPALVTR, Sn_FRAG : Internet protocol. - * @sa Sn_RXBUF_SIZE, Sn_TXBUF_SIZE, Sn_TX_FSR, Sn_TX_RD, Sn_TX_WR, Sn_RX_RSR, Sn_RX_RD, Sn_RX_WR : Data communication - */ - - - - /** - * @defgroup Basic_IO_function Basic I/O function - * @ingroup WIZCHIP_IO_Functions - * @brief These are basic input/output functions to read values from register or write values to register. - */ - -/** - * @defgroup Common_register_access_function Common register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access common registers. - */ - -/** - * @defgroup Socket_register_access_function Socket register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access socket registers. - */ - -//------------------------------- defgroup end -------------------------------------------- -//----------------------------- W5500 Common Registers IOMAP ----------------------------- -/** - * @ingroup Common_register_group - * @brief Mode Register address(R/W)\n - * @ref MR is used for S/W reset, ping block mode, PPPoE mode and etc. - * @details Each bit of @ref MR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
RST Reserved WOL PB PPPoE Reserved FARP Reserved
- * - \ref MR_RST : Reset - * - \ref MR_WOL : Wake on LAN - * - \ref MR_PB : Ping block - * - \ref MR_PPPOE : PPPoE mode - * - \ref MR_FARP : Force ARP mode - */ -#define MR WIZCHIP_CREG_ADDR(0x0000) - -/** - * @ingroup Common_register_group - * @brief Gateway IP Register address(R/W) - * @details @ref GAR configures the default gateway address. - */ -#define GAR WIZCHIP_CREG_ADDR(0x0001) - -/** - * @ingroup Common_register_group - * @brief Subnet mask Register address(R/W) - * @details @ref SUBR configures the subnet mask address. - */ -#define SUBR WIZCHIP_CREG_ADDR(0x0005) - -/** - * @ingroup Common_register_group - * @brief Source MAC Register address(R/W) - * @details @ref SHAR configures the source hardware address. - */ -#define SHAR WIZCHIP_CREG_ADDR(0x0009) - -/** - * @ingroup Common_register_group - * @brief Source IP Register address(R/W) - * @details @ref SIPR configures the source IP address. - */ -#define SIPR WIZCHIP_CREG_ADDR(0x000f) - -/** - * @ingroup Common_register_group - * @brief Set Interrupt low level timer register address(R/W) - * @details @ref INTLEVEL configures the Interrupt Assert Time. - */ -//#define INTLEVEL (_W5500_IO_BASE_ + (0x0013 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Interrupt Register(R/W) - * @details @ref IR indicates the interrupt status. Each bit of @ref IR will be still until the bit will be written to by the host. - * If @ref IR is not equal to x00 INTn PIN is asserted to low until it is x00\n\n - * Each bit of @ref IR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
CONFLICT UNREACH PPPoE MP Reserved Reserved Reserved Reserved
- * - \ref IR_CONFLICT : IP conflict - * - \ref IR_UNREACH : Destination unreachable - * - \ref IR_PPPoE : PPPoE connection close - * - \ref IR_MP : Magic packet - */ -#define IR WIZCHIP_CREG_ADDR(0x0015) - -/** - * @ingroup Common_register_group - * @brief Interrupt mask register(R/W) - * @details @ref IMR is used to mask interrupts. Each bit of @ref IMR corresponds to each bit of @ref IR. - * When a bit of @ref IMR is and the corresponding bit of @ref IR is an interrupt will be issued. In other words, - * if a bit of @ref IMR is an interrupt will not be issued even if the corresponding bit of @ref IR is \n\n - * Each bit of @ref IMR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
IM_IR7 IM_IR6 IM_IR5 IM_IR4 Reserved Reserved Reserved Reserved
- * - \ref IM_IR7 : IP Conflict Interrupt Mask - * - \ref IM_IR6 : Destination unreachable Interrupt Mask - * - \ref IM_IR5 : PPPoE Close Interrupt Mask - * - \ref IM_IR4 : Magic Packet Interrupt Mask - */ -#define IMR WIZCHIP_CREG_ADDR(0x0016) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Register(R/W) - * @details @ref SIR indicates the interrupt status of Socket.\n - * Each bit of @ref SIR be still until @ref Sn_IR is cleared by the host.\n - * If @ref Sn_IR is not equal to x00 the n-th bit of @ref SIR is and INTn PIN is asserted until @ref SIR is x00 */ -//#define SIR (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Mask Register(R/W) - * @details Each bit of @ref SIMR corresponds to each bit of @ref SIR. - * When a bit of @ref SIMR is and the corresponding bit of @ref SIR is Interrupt will be issued. - * In other words, if a bit of @ref SIMR is an interrupt will be not issued even if the corresponding bit of @ref SIR is - */ -//#define SIMR (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Timeout register address( 1 is 100us )(R/W) - * @details @ref RTR configures the retransmission timeout period. The unit of timeout period is 100us and the default of @ref RTR is x07D0or 000 - * And so the default timeout period is 200ms(100us X 2000). During the time configured by @ref RTR, W5500 waits for the peer response - * to the packet that is transmitted by \ref Sn_CR (CONNECT, DISCON, CLOSE, SEND, SEND_MAC, SEND_KEEP command). - * If the peer does not respond within the @ref RTR time, W5500 retransmits the packet or issues timeout. - */ -#define RTR WIZCHIP_CREG_ADDR(0x0017) - -/** - * @ingroup Common_register_group - * @brief Retry count register(R/W) - * @details @ref RCR configures the number of time of retransmission. - * When retransmission occurs as many as ref RCR+1 Timeout interrupt is issued (@ref Sn_IR[TIMEOUT] = . - */ -#define RCR WIZCHIP_CREG_ADDR(0x0019) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Request Timer register in PPPoE mode(R/W) - * @details @ref PTIMER configures the time for sending LCP echo request. The unit of time is 25ms. - */ -#define PTIMER WIZCHIP_CREG_ADDR(0x0028) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Magic number register in PPPoE mode(R/W) - * @details @ref PMAGIC configures the 4bytes magic number to be used in LCP negotiation. - */ -#define PMAGIC WIZCHIP_CREG_ADDR(0x0029) - -/** - * @ingroup Common_register_group - * @brief PPP Destination MAC Register address(R/W) - * @details @ref PHAR configures the PPPoE server hardware address that is acquired during PPPoE connection process. - */ -//#define PHAR (_W5500_IO_BASE_ + (0x001E << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Session Identification Register(R/W) - * @details @ref PSID configures the PPPoE sever session ID acquired during PPPoE connection process. - */ -//#define PSID (_W5500_IO_BASE_ + (0x0024 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Maximum Segment Size(MSS) register(R/W) - * @details @ref PMRU configures the maximum receive unit of PPPoE. - */ -//#define PMRU (_W5500_IO_BASE_ + (0x0026 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable IP register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR indicates - * the destination IP address & port number respectively. - */ -//#define UIPR (_W5500_IO_BASE_ + (0x002a << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable Port register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR - * indicates the destination IP address & port number respectively. - */ -//#define UPORTR (_W5500_IO_BASE_ + (0x002e << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PHY Status Register(R/W) - * @details @ref PHYCFGR configures PHY operation mode and resets PHY. In addition, @ref PHYCFGR indicates the status of PHY such as duplex, Speed, Link. - */ -//#define PHYCFGR (_W5500_IO_BASE_ + (0x002E << 8) + (WIZCHIP_CREG_BLOCK << 3)) -#define PHYSTATUS WIZCHIP_CREG_ADDR(0x0035) - -// Reserved (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0031 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0032 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0033 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0034 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0035 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0036 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0037 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0038 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief chip version register address(R) - * @details @ref VERSIONR always indicates the W5500 version as @b 0x04. - */ -//#define VERSIONR (_W5200_IO_BASE_ + (0x0039 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - - -//----------------------------- W5500 Socket Registers IOMAP ----------------------------- -/** - * @ingroup Socket_register_group - * @brief socket Mode register(R/W) - * @details @ref Sn_MR configures the option or protocol type of Socket n.\n\n - * Each bit of @ref Sn_MR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
MULTI/MFEN BCASTB ND/MC/MMB UCASTB/MIP6B Protocol[3] Protocol[2] Protocol[1] Protocol[0]
- * - @ref Sn_MR_MULTI : Support UDP Multicasting - * - @ref Sn_MR_BCASTB : Broadcast block in UDP Multicasting - * - @ref Sn_MR_ND : No Delayed Ack(TCP) flag - * - @ref Sn_MR_MC : IGMP version used in UDP mulitcasting - * - @ref Sn_MR_MMB : Multicast Blocking in @ref Sn_MR_MACRAW mode - * - @ref Sn_MR_UCASTB : Unicast Block in UDP Multicating - * - @ref Sn_MR_MIP6B : IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * - Protocol - * - * - * - * - * - * - *
Protocol[3] Protocol[2] Protocol[1] Protocol[0] @b Meaning
0 0 0 0 Closed
0 0 0 1 TCP
0 0 1 0 UDP
0 1 0 0 MACRAW
- * - @ref Sn_MR_MACRAW : MAC LAYER RAW SOCK \n - * - @ref Sn_MR_UDP : UDP - * - @ref Sn_MR_TCP : TCP - * - @ref Sn_MR_CLOSE : Unused socket - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR(N) WIZCHIP_SREG_ADDR(N, 0x0000) - -/** - * @ingroup Socket_register_group - * @brief Socket command register(R/W) - * @details This is used to set the command for Socket n such as OPEN, CLOSE, CONNECT, LISTEN, SEND, and RECEIVE.\n - * After W5500 accepts the command, the @ref Sn_CR register is automatically cleared to 0x00. - * Even though @ref Sn_CR is cleared to 0x00, the command is still being processed.\n - * To check whether the command is completed or not, please check the @ref Sn_IR or @ref Sn_SR. - * - @ref Sn_CR_OPEN : Initialize or open socket. - * - @ref Sn_CR_LISTEN : Wait connection request in TCP mode(Server mode) - * - @ref Sn_CR_CONNECT : Send connection request in TCP mode(Client mode) - * - @ref Sn_CR_DISCON : Send closing request in TCP mode. - * - @ref Sn_CR_CLOSE : Close socket. - * - @ref Sn_CR_SEND : Update TX buffer pointer and send data. - * - @ref Sn_CR_SEND_MAC : Send data with MAC address, so without ARP process. - * - @ref Sn_CR_SEND_KEEP : Send keep alive message. - * - @ref Sn_CR_RECV : Update RX buffer pointer and receive data. - */ -#define Sn_CR(N) WIZCHIP_SREG_ADDR(N, 0x0001) - -/** - * @ingroup Socket_register_group - * @brief Socket interrupt register(R) - * @details @ref Sn_IR indicates the status of Socket Interrupt such as establishment, termination, receiving data, timeout).\n - * When an interrupt occurs and the corresponding bit of @ref Sn_IMR is the corresponding bit of @ref Sn_IR becomes \n - * In order to clear the @ref Sn_IR bit, the host should write the bit to \n - * - * - * - *
7 6 5 4 3 2 1 0
Reserved Reserved Reserved SEND_OK TIMEOUT RECV DISCON CON
- * - \ref Sn_IR_SENDOK : SEND_OK Interrupt - * - \ref Sn_IR_TIMEOUT : TIMEOUT Interrupt - * - \ref Sn_IR_RECV : RECV Interrupt - * - \ref Sn_IR_DISCON : DISCON Interrupt - * - \ref Sn_IR_CON : CON Interrupt - */ -#define Sn_IR(N) WIZCHIP_SREG_ADDR(N, 0x0002) - -/** - * @ingroup Socket_register_group - * @brief Socket status register(R) - * @details @ref Sn_SR indicates the status of Socket n.\n - * The status of Socket n is changed by @ref Sn_CR or some special control packet as SYN, FIN packet in TCP. - * @par Normal status - * - @ref SOCK_CLOSED : Closed - * - @ref SOCK_INIT : Initiate state - * - @ref SOCK_LISTEN : Listen state - * - @ref SOCK_ESTABLISHED : Success to connect - * - @ref SOCK_CLOSE_WAIT : Closing state - * - @ref SOCK_UDP : UDP socket - * - @ref SOCK_MACRAW : MAC raw mode socket - *@par Temporary status during changing the status of Socket n. - * - @ref SOCK_SYNSENT : This indicates Socket n sent the connect-request packet (SYN packet) to a peer. - * - @ref SOCK_SYNRECV : It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer. - * - @ref SOCK_FIN_WAIT : Connection state - * - @ref SOCK_CLOSING : Closing state - * - @ref SOCK_TIME_WAIT : Closing state - * - @ref SOCK_LAST_ACK : Closing state - */ -#define Sn_SR(N) WIZCHIP_SREG_ADDR(N, 0x0003) - -/** - * @ingroup Socket_register_group - * @brief source port register(R/W) - * @details @ref Sn_PORT configures the source port number of Socket n. - * It is valid when Socket n is used in TCP/UPD mode. It should be set before OPEN command is ordered. - */ -#define Sn_PORT(N) WIZCHIP_SREG_ADDR(N, 0x0004) - -/** - * @ingroup Socket_register_group - * @brief Peer MAC register address(R/W) - * @details @ref Sn_DHAR configures the destination hardware address of Socket n when using SEND_MAC command in UDP mode or - * it indicates that it is acquired in ARP-process by CONNECT/SEND command. - */ -#define Sn_DHAR(N) WIZCHIP_SREG_ADDR(N, 0x0006) - -/** - * @ingroup Socket_register_group - * @brief Peer IP register address(R/W) - * @details @ref Sn_DIPR configures or indicates the destination IP address of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In TCP client mode, it configures an IP address of �TCP serverbefore CONNECT command. - * In TCP server mode, it indicates an IP address of �TCP clientafter successfully establishing connection. - * In UDP mode, it configures an IP address of peer to be received the UDP packet by SEND or SEND_MAC command. - */ -#define Sn_DIPR(N) WIZCHIP_SREG_ADDR(N, 0x000c) - -/** - * @ingroup Socket_register_group - * @brief Peer port register address(R/W) - * @details @ref Sn_DPORT configures or indicates the destination port number of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In �TCP clientmode, it configures the listen port number of �TCP serverbefore CONNECT command. - * In �TCP Servermode, it indicates the port number of TCP client after successfully establishing connection. - * In UDP mode, it configures the port number of peer to be transmitted the UDP packet by SEND/SEND_MAC command. - */ -#define Sn_DPORT(N) WIZCHIP_SREG_ADDR(N, 0x0010) - -/** - * @ingroup Socket_register_group - * @brief Maximum Segment Size(Sn_MSSR0) register address(R/W) - * @details @ref Sn_MSSR configures or indicates the MTU(Maximum Transfer Unit) of Socket n. - */ -#define Sn_MSSR(N) WIZCHIP_SREG_ADDR(N, 0x0012) - -// Reserved (_W5500_IO_BASE_ + (0x0014 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief IP Type of Service(TOS) Register(R/W) - * @details @ref Sn_TOS configures the TOS(Type Of Service field in IP Header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TOS(N) WIZCHIP_SREG_ADDR(N, 0x0015) -/** - * @ingroup Socket_register_group - * @brief IP Time to live(TTL) Register(R/W) - * @details @ref Sn_TTL configures the TTL(Time To Live field in IP header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TTL(N) WIZCHIP_SREG_ADDR(N, 0x0016) -// Reserved (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001A << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Receive memory size register(R/W) - * @details @ref Sn_RXBUF_SIZE configures the RX buffer block size of Socket n. - * Socket n RX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data cannot be normally received from a peer. - * Although Socket n RX Buffer Block size is initially configured to 2Kbytes, - * user can re-configure its size using @ref Sn_RXBUF_SIZE. The total sum of @ref Sn_RXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data reception error is occurred. - */ -#define Sn_RXBUF_SIZE(N) WIZCHIP_SREG_ADDR(N, 0x001e) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory size register(R/W) - * @details @ref Sn_TXBUF_SIZE configures the TX buffer block size of Socket n. Socket n TX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data can�t be normally transmitted to a peer. - * Although Socket n TX Buffer Block size is initially configured to 2Kbytes, - * user can be re-configure its size using @ref Sn_TXBUF_SIZE. The total sum of @ref Sn_TXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data transmission error is occurred. - */ -#define Sn_TXBUF_SIZE(N) WIZCHIP_SREG_ADDR(N, 0x001f) - -/** - * @ingroup Socket_register_group - * @brief Transmit free memory size register(R) - * @details @ref Sn_TX_FSR indicates the free size of Socket n TX Buffer Block. It is initialized to the configured size by @ref Sn_TXBUF_SIZE. - * Data bigger than @ref Sn_TX_FSR should not be saved in the Socket n TX Buffer because the bigger data overwrites the previous saved data not yet sent. - * Therefore, check before saving the data to the Socket n TX Buffer, and if data is equal or smaller than its checked size, - * transmit the data with SEND/SEND_MAC command after saving the data in Socket n TX buffer. But, if data is bigger than its checked size, - * transmit the data after dividing into the checked size and saving in the Socket n TX buffer. - */ -#define Sn_TX_FSR(N) WIZCHIP_SREG_ADDR(N, 0x0020) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory read pointer register address(R) - * @details @ref Sn_TX_RD is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP. - * After its initialization, it is auto-increased by SEND command. - * SEND command transmits the saved data from the current @ref Sn_TX_RD to the @ref Sn_TX_WR in the Socket n TX Buffer. - * After transmitting the saved data, the SEND command increases the @ref Sn_TX_RD as same as the @ref Sn_TX_WR. - * If its increment value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_TX_RD(N) WIZCHIP_SREG_ADDR(N, 0x0022) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory write pointer register address(R/W) - * @details @ref Sn_TX_WR is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP.\n - * It should be read or be updated like as follows.\n - * 1. Read the starting address for saving the transmitting data.\n - * 2. Save the transmitting data from the starting address of Socket n TX buffer.\n - * 3. After saving the transmitting data, update @ref Sn_TX_WR to the increased value as many as transmitting data size. - * If the increment value exceeds the maximum value 0xFFFF(greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value.\n - * 4. Transmit the saved data in Socket n TX Buffer by using SEND/SEND command - */ -#define Sn_TX_WR(N) WIZCHIP_SREG_ADDR(N, 0x0024) - -/** - * @ingroup Socket_register_group - * @brief Received data size register(R) - * @details @ref Sn_RX_RSR indicates the data size received and saved in Socket n RX Buffer. - * @ref Sn_RX_RSR does not exceed the @ref Sn_RXBUF_SIZE and is calculated as the difference between - * �Socket n RX Write Pointer (@ref Sn_RX_WR)and �Socket n RX Read Pointer (@ref Sn_RX_RD) - */ -#define Sn_RX_RSR(N) WIZCHIP_SREG_ADDR(N, 0x0026) - -/** - * @ingroup Socket_register_group - * @brief Read point of Receive memory(R/W) - * @details @ref Sn_RX_RD is initialized by OPEN command. Make sure to be read or updated as follows.\n - * 1. Read the starting save address of the received data.\n - * 2. Read data from the starting address of Socket n RX Buffer.\n - * 3. After reading the received data, Update @ref Sn_RX_RD to the increased value as many as the reading size. - * If the increment value exceeds the maximum value 0xFFFF, that is, is greater than 0x10000 and the carry bit occurs, - * update with the lower 16bits value ignored the carry bit.\n - * 4. Order RECV command is for notifying the updated @ref Sn_RX_RD to W5500. - */ -#define Sn_RX_RD(N) WIZCHIP_SREG_ADDR(N, 0x0028) - -/** - * @ingroup Socket_register_group - * @brief Write point of Receive memory(R) - * @details @ref Sn_RX_WR is initialized by OPEN command and it is auto-increased by the data reception. - * If the increased value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_RX_WR(N) WIZCHIP_SREG_ADDR(N, 0x002a) - -/** - * @ingroup Socket_register_group - * @brief socket interrupt mask register(R) - * @details @ref Sn_IMR masks the interrupt of Socket n. - * Each bit corresponds to each bit of @ref Sn_IR. When a Socket n Interrupt is occurred and the corresponding bit of @ref Sn_IMR is - * the corresponding bit of @ref Sn_IR becomes When both the corresponding bit of @ref Sn_IMR and @ref Sn_IR are and the n-th bit of @ref IR is - * Host is interrupted by asserted INTn PIN to low. - */ -//#define Sn_IMR(N) (_W5500_IO_BASE_ + (0x002C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Fragment field value in IP header register(R/W) - * @details @ref Sn_FRAG configures the FRAG(Fragment field in IP header). - */ -//#define Sn_FRAG(N) (_W5500_IO_BASE_ + (0x002D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Keep Alive Timer register(R/W) - * @details @ref Sn_KPALVTR configures the transmitting timer of �KEEP ALIVE(KA)packet of SOCKETn. It is valid only in TCP mode, - * and ignored in other modes. The time unit is 5s. - * KA packet is transmittable after @ref Sn_SR is changed to SOCK_ESTABLISHED and after the data is transmitted or received to/from a peer at least once. - * In case of '@ref Sn_KPALVTR > 0', W5500 automatically transmits KA packet after time-period for checking the TCP connection (Auto-keepalive-process). - * In case of '@ref Sn_KPALVTR = 0', Auto-keep-alive-process will not operate, - * and KA packet can be transmitted by SEND_KEEP command by the host (Manual-keep-alive-process). - * Manual-keep-alive-process is ignored in case of '@ref Sn_KPALVTR > 0'. - */ -//#define Sn_KPALVTR(N) (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -//#define Sn_TSR(N) (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - - -//----------------------------- W5500 Register values ----------------------------- - -/* MODE register values */ -/** - * @brief Reset - * @details If this bit is All internal registers will be initialized. It will be automatically cleared as after S/W reset. - */ -#define MR_RST 0x80 - -/** - * @brief Wake on LAN - * @details 0 : Disable WOL mode\n - * 1 : Enable WOL mode\n - * If WOL mode is enabled and the received magic packet over UDP has been normally processed, the Interrupt PIN (INTn) asserts to low. - * When using WOL mode, the UDP Socket should be opened with any source port number. (Refer to Socket n Mode Register (@ref Sn_MR) for opening Socket.) - * @note The magic packet over UDP supported by W5500 consists of 6 bytes synchronization stream (xFFFFFFFFFFFF and - * 16 times Target MAC address stream in UDP payload. The options such like password are ignored. You can use any UDP source port number for WOL mode. - */ -#define MR_WOL 0x20 - -/** - * @brief Ping block - * @details 0 : Disable Ping block\n - * 1 : Enable Ping block\n - * If the bit is it blocks the response to a ping request. - */ -#define MR_PB 0x10 - -/** - * @brief Enable PPPoE - * @details 0 : DisablePPPoE mode\n - * 1 : EnablePPPoE mode\n - * If you use ADSL, this bit should be - */ -#define MR_PPPOE 0x08 - -/** - * @brief Enable UDP_FORCE_ARP CHECHK - * @details 0 : Disable Force ARP mode\n - * 1 : Enable Force ARP mode\n - * In Force ARP mode, It forces on sending ARP Request whenever data is sent. - */ -#define MR_FARP 0x02 - -/* IR register values */ -/** - * @brief Check IP conflict. - * @details Bit is set as when own source IP address is same with the sender IP address in the received ARP request. - */ -#define IR_CONFLICT 0x80 - -/** - * @brief Get the destination unreachable message in UDP sending. - * @details When receiving the ICMP (Destination port unreachable) packet, this bit is set as - * When this bit is Destination Information such as IP address and Port number may be checked with the corresponding @ref UIPR & @ref UPORTR. - */ -#define IR_UNREACH 0x40 - -/** - * @brief Get the PPPoE close message. - * @details When PPPoE is disconnected during PPPoE mode, this bit is set. - */ -#define IR_PPPoE 0x20 - -/** - * @brief Get the magic packet interrupt. - * @details When WOL mode is enabled and receives the magic packet over UDP, this bit is set. - */ -#define IR_MP 0x10 - - -/* PHYCFGR register value */ -#define PHYCFGR_RST ~(1<<7) //< For PHY reset, must operate AND mask. -#define PHYCFGR_OPMD (1<<6) // Configre PHY with OPMDC value -#define PHYCFGR_OPMDC_ALLA (7<<3) -#define PHYCFGR_OPMDC_PDOWN (6<<3) -#define PHYCFGR_OPMDC_NA (5<<3) -#define PHYCFGR_OPMDC_100FA (4<<3) -#define PHYCFGR_OPMDC_100F (3<<3) -#define PHYCFGR_OPMDC_100H (2<<3) -#define PHYCFGR_OPMDC_10F (1<<3) -#define PHYCFGR_OPMDC_10H (0<<3) -#define PHYCFGR_DPX_FULL (1<<2) -#define PHYCFGR_DPX_HALF (0<<2) -#define PHYCFGR_SPD_100 (1<<1) -#define PHYCFGR_SPD_10 (0<<1) -#define PHYCFGR_LNK_ON (1<<0) -#define PHYCFGR_LNK_OFF (0<<0) - -// PHYSTATUS register -#define PHYSTATUS_POWERDOWN (0x08) -#define PHYSTATUS_LINK (0x20) - -/* IMR register values */ -/** - * @brief IP Conflict Interrupt Mask. - * @details 0: Disable IP Conflict Interrupt\n - * 1: Enable IP Conflict Interrupt - */ -#define IM_IR7 0x80 - -/** - * @brief Destination unreachable Interrupt Mask. - * @details 0: Disable Destination unreachable Interrupt\n - * 1: Enable Destination unreachable Interrupt - */ -#define IM_IR6 0x40 - -/** - * @brief PPPoE Close Interrupt Mask. - * @details 0: Disable PPPoE Close Interrupt\n - * 1: Enable PPPoE Close Interrupt - */ -#define IM_IR5 0x20 - -/** - * @brief Magic Packet Interrupt Mask. - * @details 0: Disable Magic Packet Interrupt\n - * 1: Enable Magic Packet Interrupt - */ -#define IM_IR4 0x10 - -/* Sn_MR Default values */ -/** - * @brief Support UDP Multicasting - * @details 0 : disable Multicasting\n - * 1 : enable Multicasting\n - * This bit is applied only during UDP mode(P[3:0] = 010.\n - * To use multicasting, @ref Sn_DIPR & @ref Sn_DPORT should be respectively configured with the multicast group IP address & port number - * before Socket n is opened by OPEN command of @ref Sn_CR. - */ -#define Sn_MR_MULTI 0x80 - -/** - * @brief Broadcast block in UDP Multicasting. - * @details 0 : disable Broadcast Blocking\n - * 1 : enable Broadcast Blocking\n - * This bit blocks to receive broadcasting packet during UDP mode(P[3:0] = 010.\m - * In addition, This bit does when MACRAW mode(P[3:0] = 100 - */ -//#define Sn_MR_BCASTB 0x40 - -/** - * @brief No Delayed Ack(TCP), Multicast flag - * @details 0 : Disable No Delayed ACK option\n - * 1 : Enable No Delayed ACK option\n - * This bit is applied only during TCP mode (P[3:0] = 001.\n - * When this bit is It sends the ACK packet without delay as soon as a Data packet is received from a peer.\n - * When this bit is It sends the ACK packet after waiting for the timeout time configured by @ref RTR. - */ -#define Sn_MR_ND 0x20 - -/** - * @brief Unicast Block in UDP Multicasting - * @details 0 : disable Unicast Blocking\n - * 1 : enable Unicast Blocking\n - * This bit blocks receiving the unicast packet during UDP mode(P[3:0] = 010 and MULTI = - */ -//#define Sn_MR_UCASTB 0x10 - -/** - * @brief MAC LAYER RAW SOCK - * @details This configures the protocol mode of Socket n. - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR_MACRAW 0x04 - -#define Sn_MR_IPRAW 0x03 /**< IP LAYER RAW SOCK */ - -/** - * @brief UDP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_UDP 0x02 - -/** - * @brief TCP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_TCP 0x01 - -/** - * @brief Unused socket - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_CLOSE 0x00 - -/* Sn_MR values used with Sn_MR_MACRAW */ -/** - * @brief MAC filter enable in @ref Sn_MR_MACRAW mode - * @details 0 : disable MAC Filtering\n - * 1 : enable MAC Filtering\n - * This bit is applied only during MACRAW mode(P[3:0] = 100.\n - * When set as W5500 can only receive broadcasting packet or packet sent to itself. - * When this bit is W5500 can receive all packets on Ethernet. - * If user wants to implement Hybrid TCP/IP stack, - * it is recommended that this bit is set as for reducing host overhead to process the all received packets. - */ -#define Sn_MR_MFEN Sn_MR_MULTI - -/** - * @brief Multicast Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : using IGMP version 2\n - * 1 : using IGMP version 1\n - * This bit is applied only during UDP mode(P[3:0] = 010 and MULTI = - * It configures the version for IGMP messages (Join/Leave/Report). - */ -#define Sn_MR_MMB Sn_MR_ND - -/** - * @brief IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : disable IPv6 Blocking\n - * 1 : enable IPv6 Blocking\n - * This bit is applied only during MACRAW mode (P[3:0] = 100. It blocks to receiving the IPv6 packet. - */ -#define Sn_MR_MIP6B Sn_MR_UCASTB - -/* Sn_MR value used with Sn_MR_UDP & Sn_MR_MULTI */ -/** - * @brief IGMP version used in UDP mulitcasting - * @details 0 : disable Multicast Blocking\n - * 1 : enable Multicast Blocking\n - * This bit is applied only when MACRAW mode(P[3:0] = 100. It blocks to receive the packet with multicast MAC address. - */ -#define Sn_MR_MC Sn_MR_ND - -/* Sn_MR alternate values */ -/** - * @brief For Berkeley Socket API - */ -#define SOCK_STREAM Sn_MR_TCP - -/** - * @brief For Berkeley Socket API - */ -#define SOCK_DGRAM Sn_MR_UDP - - -/* Sn_CR values */ -/** - * @brief Initialize or open socket - * @details Socket n is initialized and opened according to the protocol selected in Sn_MR(P3:P0). - * The table below shows the value of @ref Sn_SR corresponding to @ref Sn_MR.\n - * - * - * - * - * - * - *
\b Sn_MR (P[3:0]) \b Sn_SR
Sn_MR_CLOSE (000
Sn_MR_TCP (001 SOCK_INIT (0x13)
Sn_MR_UDP (010 SOCK_UDP (0x22)
S0_MR_MACRAW (100 SOCK_MACRAW (0x02)
- */ -#define Sn_CR_OPEN 0x01 - -/** - * @brief Wait connection request in TCP mode(Server mode) - * @details This is valid only in TCP mode (Sn_MR(P3:P0) = Sn_MR_TCP). - * In this mode, Socket n operates as a �TCP serverand waits for connection-request (SYN packet) from any �TCP client - * The @ref Sn_SR changes the state from SOCK_INIT to SOCKET_LISTEN. - * When a �TCP clientconnection request is successfully established, - * the @ref Sn_SR changes from SOCK_LISTEN to SOCK_ESTABLISHED and the Sn_IR(0) becomes - * But when a �TCP clientconnection request is failed, Sn_IR(3) becomes and the status of @ref Sn_SR changes to SOCK_CLOSED. - */ -#define Sn_CR_LISTEN 0x02 - -/** - * @brief Send connection request in TCP mode(Client mode) - * @details To connect, a connect-request (SYN packet) is sent to b>TCP serverconfigured by @ref Sn_DIPR & Sn_DPORT(destination address & port). - * If the connect-request is successful, the @ref Sn_SR is changed to @ref SOCK_ESTABLISHED and the Sn_IR(0) becomes \n\n - * The connect-request fails in the following three cases.\n - * 1. When a @b ARPTO occurs (@ref Sn_IR[3] = ) because destination hardware address is not acquired through the ARP-process.\n - * 2. When a @b SYN/ACK packet is not received and @b TCPTO (Sn_IR(3) = )\n - * 3. When a @b RST packet is received instead of a @b SYN/ACK packet. In these cases, @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note This is valid only in TCP mode and operates when Socket n acts as b>TCP client - */ -#define Sn_CR_CONNECT 0x04 - -/** - * @brief Send closing request in TCP mode - * @details Regardless of b>TCP serveror b>TCP client the DISCON command processes the disconnect-process (b>Active closeor b>Passive close.\n - * @par Active close - * it transmits disconnect-request(FIN packet) to the connected peer\n - * @par Passive close - * When FIN packet is received from peer, a FIN packet is replied back to the peer.\n - * @details When the disconnect-process is successful (that is, FIN/ACK packet is received successfully), @ref Sn_SR is changed to @ref SOCK_CLOSED.\n - * Otherwise, TCPTO occurs (Sn_IR(3)=)= and then @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note Valid only in TCP mode. - */ -#define Sn_CR_DISCON 0x08 - -/** - * @brief Close socket - * @details Sn_SR is changed to @ref SOCK_CLOSED. - */ -#define Sn_CR_CLOSE 0x10 - -/** - * @brief Update TX buffer pointer and send data - * @details SEND transmits all the data in the Socket n TX buffer.\n - * For more details, please refer to Socket n TX Free Size Register (@ref Sn_TX_FSR), Socket n, - * TX Write Pointer Register(@ref Sn_TX_WR), and Socket n TX Read Pointer Register(@ref Sn_TX_RD). - */ -#define Sn_CR_SEND 0x20 - -/** - * @brief Send data with MAC address, so without ARP process - * @details The basic operation is same as SEND.\n - * Normally SEND transmits data after destination hardware address is acquired by the automatic ARP-process(Address Resolution Protocol).\n - * But SEND_MAC transmits data without the automatic ARP-process.\n - * In this case, the destination hardware address is acquired from @ref Sn_DHAR configured by host, instead of APR-process. - * @note Valid only in UDP mode. - */ -#define Sn_CR_SEND_MAC 0x21 - -/** - * @brief Send keep alive message - * @details It checks the connection status by sending 1byte keep-alive packet.\n - * If the peer can not respond to the keep-alive packet during timeout time, the connection is terminated and the timeout interrupt will occur. - * @note Valid only in TCP mode. - */ -#define Sn_CR_SEND_KEEP 0x22 - -/** - * @brief Update RX buffer pointer and receive data - * @details RECV completes the processing of the received data in Socket n RX Buffer by using a RX read pointer register (@ref Sn_RX_RD).\n - * For more details, refer to Socket n RX Received Size Register (@ref Sn_RX_RSR), Socket n RX Write Pointer Register (@ref Sn_RX_WR), - * and Socket n RX Read Pointer Register (@ref Sn_RX_RD). - */ -#define Sn_CR_RECV 0x40 - -/* Sn_IR values */ -/** - * @brief SEND_OK Interrupt - * @details This is issued when SEND command is completed. - */ -#define Sn_IR_SENDOK 0x10 - -/** - * @brief TIMEOUT Interrupt - * @details This is issued when ARPTO or TCPTO occurs. - */ -#define Sn_IR_TIMEOUT 0x08 - -/** - * @brief RECV Interrupt - * @details This is issued whenever data is received from a peer. - */ -#define Sn_IR_RECV 0x04 - -/** - * @brief DISCON Interrupt - * @details This is issued when FIN or FIN/ACK packet is received from a peer. - */ -#define Sn_IR_DISCON 0x02 - -/** - * @brief CON Interrupt - * @details This is issued one time when the connection with peer is successful and then @ref Sn_SR is changed to @ref SOCK_ESTABLISHED. - */ -#define Sn_IR_CON 0x01 - -/* Sn_SR values */ -/** - * @brief Closed - * @details This indicates that Socket n is released.\N - * When DICON, CLOSE command is ordered, or when a timeout occurs, it is changed to @ref SOCK_CLOSED regardless of previous status. - */ -#define SOCK_CLOSED 0x00 - -/** - * @brief Initiate state - * @details This indicates Socket n is opened with TCP mode.\N - * It is changed to @ref SOCK_INIT when Sn_MR(P[3:0]) = 001and OPEN command is ordered.\N - * After @ref SOCK_INIT, user can use LISTEN /CONNECT command. - */ -#define SOCK_INIT 0x13 - -/** - * @brief Listen state - * @details This indicates Socket n is operating as b>TCP servermode and waiting for connection-request (SYN packet) from a peer (b>TCP client.\n - * It will change to @ref SOCK_ESTALBLISHED when the connection-request is successfully accepted.\n - * Otherwise it will change to @ref SOCK_CLOSED after TCPTO occurred (Sn_IR(TIMEOUT) = . - */ -#define SOCK_LISTEN 0x14 - -/** - * @brief Connection state - * @details This indicates Socket n sent the connect-request packet (SYN packet) to a peer.\n - * It is temporarily shown when @ref Sn_SR is changed from @ref SOCK_INIT to @ref SOCK_ESTABLISHED by CONNECT command.\n - * If connect-accept(SYN/ACK packet) is received from the peer at SOCK_SYNSENT, it changes to @ref SOCK_ESTABLISHED.\n - * Otherwise, it changes to @ref SOCK_CLOSED after TCPTO (@ref Sn_IR[TIMEOUT] = is occurred. - */ -#define SOCK_SYNSENT 0x15 - -/** - * @brief Connection state - * @details It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer.\n - * If socket n sends the response (SYN/ACK packet) to the peer successfully, it changes to @ref SOCK_ESTABLISHED. \n - * If not, it changes to @ref SOCK_CLOSED after timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_SYNRECV 0x16 - -/** - * @brief Success to connect - * @details This indicates the status of the connection of Socket n.\n - * It changes to @ref SOCK_ESTABLISHED when the b>TCP SERVERprocessed the SYN packet from the b>TCP CLIENTduring @ref SOCK_LISTEN, or - * when the CONNECT command is successful.\n - * During @ref SOCK_ESTABLISHED, DATA packet can be transferred using SEND or RECV command. - */ -#define SOCK_ESTABLISHED 0x17 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_FIN_WAIT 0x18 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_CLOSING 0x1A - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_TIME_WAIT 0x1B - -/** - * @brief Closing state - * @details This indicates Socket n received the disconnect-request (FIN packet) from the connected peer.\n - * This is half-closing status, and data can be transferred.\n - * For full-closing, DISCON command is used. But For just-closing, CLOSE command is used. - */ -#define SOCK_CLOSE_WAIT 0x1C - -/** - * @brief Closing state - * @details This indicates Socket n is waiting for the response (FIN/ACK packet) to the disconnect-request (FIN packet) by passive-close.\n - * It changes to @ref SOCK_CLOSED when Socket n received the response successfully, or when timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_LAST_ACK 0x1D - -/** - * @brief UDP socket - * @details This indicates Socket n is opened in UDP mode(Sn_MR(P[3:0]) = 010.\n - * It changes to SOCK_UPD when Sn_MR(P[3:0]) = 010 and OPEN command is ordered.\n - * Unlike TCP mode, data can be transfered without the connection-process. - */ -#define SOCK_UDP 0x22 - -//#define SOCK_IPRAW 0x32 /**< IP raw mode socket */ - -/** - * @brief MAC raw mode socket - * @details This indicates Socket 0 is opened in MACRAW mode (S0_MR(P[3:0]) = 100and is valid only in Socket 0.\n - * It changes to SOCK_MACRAW when S0_MR(P[3:0] = 100and OPEN command is ordered.\n - * Like UDP mode socket, MACRAW mode Socket 0 can transfer a MAC packet (Ethernet frame) without the connection-process. - */ -#define SOCK_MACRAW 0x42 - -//#define SOCK_PPPOE 0x5F - -/* IP PROTOCOL */ -#define IPPROTO_IP 0 //< Dummy for IP -#define IPPROTO_ICMP 1 //< Control message protocol -#define IPPROTO_IGMP 2 //< Internet group management protocol -#define IPPROTO_GGP 3 //< Gateway^2 (deprecated) -#define IPPROTO_TCP 6 //< TCP -#define IPPROTO_PUP 12 //< PUP -#define IPPROTO_UDP 17 //< UDP -#define IPPROTO_IDP 22 //< XNS idp -#define IPPROTO_ND 77 //< UNOFFICIAL net disk protocol -#define IPPROTO_RAW 255 //< Raw IP packet - - -/** - * @brief Enter a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n \n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt.\n - * In OS environment, You can replace it to critical section api supported by OS. - * - * \sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * \sa WIZCHIP_CRITICAL_EXIT() - */ -#define WIZCHIP_CRITICAL_ENTER() WIZCHIP.CRIS._enter() - -/** - * @brief Exit a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n\n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt. \n - * In OS environment, You can replace it to critical section api supported by OS. - * - * @sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * @sa WIZCHIP_CRITICAL_ENTER() - */ -#ifdef _exit -#undef _exit -#endif -#define WIZCHIP_CRITICAL_EXIT() WIZCHIP.CRIS._exit() - - - -//////////////////////// -// Basic I/O Function // -//////////////////////// - -/** - * @ingroup Basic_IO_function - * @brief It reads 1 byte value from a register. - * @param AddrSel Register address - * @return The value of register - */ -uint8_t WIZCHIP_READ (uint32_t AddrSel); - -/** - * @ingroup Basic_IO_function - * @brief It writes 1 byte value to a register. - * @param AddrSel Register address - * @param wb Write data - * @return void - */ -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb ); - -/** - * @ingroup Basic_IO_function - * @brief It reads sequence data from registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to read data - * @param len Data length - */ -void WIZCHIP_READ_BUF (uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It writes sequence data to registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to write data - * @param len Data length - */ -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -///////////////////////////////// -// Common Register I/O function // -///////////////////////////////// -/** - * @ingroup Common_register_access_function - * @brief Set Mode Register - * @param (uint8_t)mr The value to be set. - * @sa getMR() - */ -#define setMR(mr) \ - WIZCHIP_WRITE(MR,mr) - - -/** - * @ingroup Common_register_access_function - * @brief Get Mode Register - * @return uint8_t. The value of Mode register. - * @sa setMR() - */ -#define getMR() \ - WIZCHIP_READ(MR) - -/** - * @ingroup Common_register_access_function - * @brief Set gateway IP address - * @param (uint8_t*)gar Pointer variable to set gateway IP address. It should be allocated 4 bytes. - * @sa getGAR() - */ -#define setGAR(gar) \ - WIZCHIP_WRITE_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Get gateway IP address - * @param (uint8_t*)gar Pointer variable to get gateway IP address. It should be allocated 4 bytes. - * @sa setGAR() - */ -#define getGAR(gar) \ - WIZCHIP_READ_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Set subnet mask address - * @param (uint8_t*)subr Pointer variable to set subnet mask address. It should be allocated 4 bytes. - * @sa getSUBR() - */ -#define setSUBR(subr) \ - WIZCHIP_WRITE_BUF(SUBR, subr,4) - - -/** - * @ingroup Common_register_access_function - * @brief Get subnet mask address - * @param (uint8_t*)subr Pointer variable to get subnet mask address. It should be allocated 4 bytes. - * @sa setSUBR() - */ -#define getSUBR(subr) \ - WIZCHIP_READ_BUF(SUBR, subr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set local MAC address - * @param (uint8_t*)shar Pointer variable to set local MAC address. It should be allocated 6 bytes. - * @sa getSHAR() - */ -#define setSHAR(shar) \ - WIZCHIP_WRITE_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local MAC address - * @param (uint8_t*)shar Pointer variable to get local MAC address. It should be allocated 6 bytes. - * @sa setSHAR() - */ -#define getSHAR(shar) \ - WIZCHIP_READ_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set local IP address - * @param (uint8_t*)sipr Pointer variable to set local IP address. It should be allocated 4 bytes. - * @sa getSIPR() - */ -#define setSIPR(sipr) \ - WIZCHIP_WRITE_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)sipr Pointer variable to get local IP address. It should be allocated 4 bytes. - * @sa setSIPR() - */ -#define getSIPR(sipr) \ - WIZCHIP_READ_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set INTLEVEL register - * @param (uint16_t)intlevel Value to set @ref INTLEVEL register. - * @sa getINTLEVEL() - */ -// dpgeorge: not yet implemented -#define setINTLEVEL(intlevel) (void)intlevel -#if 0 -#define setINTLEVEL(intlevel) {\ - WIZCHIP_WRITE(INTLEVEL, (uint8_t)(intlevel >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(INTLEVEL,1), (uint8_t) intlevel); \ - } -#endif - - -/** - * @ingroup Common_register_access_function - * @brief Get INTLEVEL register - * @return uint16_t. Value of @ref INTLEVEL register. - * @sa setINTLEVEL() - */ -// dpgeorge: not yet implemented -#define getINTLEVEL() (0) -#if 0 -#define getINTLEVEL() \ - ((WIZCHIP_READ(INTLEVEL) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(INTLEVEL,1))) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Set @ref IR register - * @param (uint8_t)ir Value to set @ref IR register. - * @sa getIR() - */ -#define setIR(ir) \ - WIZCHIP_WRITE(IR, (ir & 0xF0)) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IR register - * @return uint8_t. Value of @ref IR register. - * @sa setIR() - */ -#define getIR() \ - (WIZCHIP_READ(IR) & 0xF0) -/** - * @ingroup Common_register_access_function - * @brief Set @ref IMR register - * @param (uint8_t)imr Value to set @ref IMR register. - * @sa getIMR() - */ -#define setIMR(imr) \ - WIZCHIP_WRITE(IMR, imr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IMR register - * @return uint8_t. Value of @ref IMR register. - * @sa setIMR() - */ -#define getIMR() \ - WIZCHIP_READ(IMR) - - -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIR register - * @param (uint8_t)sir Value to set @ref SIR register. - * @sa getSIR() - */ -// dpgeorge: not yet implemented -#define setSIR(sir) ((void)sir) -#if 0 -#define setSIR(sir) \ - WIZCHIP_WRITE(SIR, sir) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIR register - * @return uint8_t. Value of @ref SIR register. - * @sa setSIR() - */ -// dpgeorge: not yet implemented -#define getSIR() (0) -#if 0 -#define getSIR() \ - WIZCHIP_READ(SIR) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIMR register - * @param (uint8_t)simr Value to set @ref SIMR register. - * @sa getSIMR() - */ -// dpgeorge: not yet implemented -#define setSIMR(simr) ((void)simr) -#if 0 -#define setSIMR(simr) \ - WIZCHIP_WRITE(SIMR, simr) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIMR register - * @return uint8_t. Value of @ref SIMR register. - * @sa setSIMR() - */ -// dpgeorge: not yet implemented -#define getSIMR() (0) -#if 0 -#define getSIMR() \ - WIZCHIP_READ(SIMR) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RTR register - * @param (uint16_t)rtr Value to set @ref RTR register. - * @sa getRTR() - */ -#define setRTR(rtr) {\ - WIZCHIP_WRITE(RTR, (uint8_t)(rtr >> 8)); \ - WIZCHIP_WRITE(RTR + 1, (uint8_t) rtr); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RTR register - * @return uint16_t. Value of @ref RTR register. - * @sa setRTR() - */ -#define getRTR() \ - ((WIZCHIP_READ(RTR) << 8) + WIZCHIP_READ(RTR + 1)) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RCR register - * @param (uint8_t)rcr Value to set @ref RCR register. - * @sa getRCR() - */ -#define setRCR(rcr) \ - WIZCHIP_WRITE(RCR, rcr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RCR register - * @return uint8_t. Value of @ref RCR register. - * @sa setRCR() - */ -#define getRCR() \ - WIZCHIP_READ(RCR) - -//================================================== test done =========================================================== - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PTIMER register - * @param (uint8_t)ptimer Value to set @ref PTIMER register. - * @sa getPTIMER() - */ -#define setPTIMER(ptimer) \ - WIZCHIP_WRITE(PTIMER, ptimer) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PTIMER register - * @return uint8_t. Value of @ref PTIMER register. - * @sa setPTIMER() - */ -#define getPTIMER() \ - WIZCHIP_READ(PTIMER) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMAGIC register - * @param (uint8_t)pmagic Value to set @ref PMAGIC register. - * @sa getPMAGIC() - */ -#define setPMAGIC(pmagic) \ - WIZCHIP_WRITE(PMAGIC, pmagic) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMAGIC register - * @return uint8_t. Value of @ref PMAGIC register. - * @sa setPMAGIC() - */ -#define getPMAGIC() \ - WIZCHIP_READ(PMAGIC) - -/** - * @ingroup Common_register_access_function - * @brief Set PHAR address - * @param (uint8_t*)phar Pointer variable to set PPP destination MAC register address. It should be allocated 6 bytes. - * @sa getPHAR() - */ -#if 0 -#define setPHAR(phar) \ - WIZCHIP_WRITE_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)phar Pointer variable to PPP destination MAC register address. It should be allocated 6 bytes. - * @sa setPHAR() - */ -#define getPHAR(phar) \ - WIZCHIP_READ_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PSID register - * @param (uint16_t)psid Value to set @ref PSID register. - * @sa getPSID() - */ -#define setPSID(psid) {\ - WIZCHIP_WRITE(PSID, (uint8_t)(psid >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PSID,1), (uint8_t) psid); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PSID register - * @return uint16_t. Value of @ref PSID register. - * @sa setPSID() - */ -//uint16_t getPSID(void); -#define getPSID() \ - ((WIZCHIP_READ(PSID) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PSID,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMRU register - * @param (uint16_t)pmru Value to set @ref PMRU register. - * @sa getPMRU() - */ -#define setPMRU(pmru) { \ - WIZCHIP_WRITE(PMRU, (uint8_t)(pmru>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PMRU,1), (uint8_t) pmru); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMRU register - * @return uint16_t. Value of @ref PMRU register. - * @sa setPMRU() - */ -#define getPMRU() \ - ((WIZCHIP_READ(PMRU) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PMRU,1))) - -/** - * @ingroup Common_register_access_function - * @brief Get unreachable IP address - * @param (uint8_t*)uipr Pointer variable to get unreachable IP address. It should be allocated 4 bytes. - */ -#define getUIPR(uipr) \ - WIZCHIP_READ_BUF(UIPR,uipr,6) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref UPORTR register - * @return uint16_t. Value of @ref UPORTR register. - */ -#define getUPORTR() \ - ((WIZCHIP_READ(UPORTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(UPORTR,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PHYCFGR register - * @param (uint8_t)phycfgr Value to set @ref PHYCFGR register. - * @sa getPHYCFGR() - */ -#define setPHYCFGR(phycfgr) \ - WIZCHIP_WRITE(PHYCFGR, phycfgr) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PHYCFGR register - * @return uint8_t. Value of @ref PHYCFGR register. - * @sa setPHYCFGR() - */ -#define getPHYSTATUS() \ - WIZCHIP_READ(PHYSTATUS) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref VERSIONR register - * @return uint8_t. Value of @ref VERSIONR register. - */ -/* -#define getVERSIONR() \ - WIZCHIP_READ(VERSIONR) - */ -///////////////////////////////////// - -/////////////////////////////////// -// Socket N register I/O function // -/////////////////////////////////// -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)mr Value to set @ref Sn_MR - * @sa getSn_MR() - */ -#define setSn_MR(sn, mr) \ - WIZCHIP_WRITE(Sn_MR(sn),mr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_MR. - * @sa setSn_MR() - */ -#define getSn_MR(sn) \ - WIZCHIP_READ(Sn_MR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)cr Value to set @ref Sn_CR - * @sa getSn_CR() - */ -#define setSn_CR(sn, cr) \ - WIZCHIP_WRITE(Sn_CR(sn), cr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_CR. - * @sa setSn_CR() - */ -#define getSn_CR(sn) \ - WIZCHIP_READ(Sn_CR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ir Value to set @ref Sn_IR - * @sa getSn_IR() - */ -#define setSn_IR(sn, ir) \ - WIZCHIP_WRITE(Sn_IR(sn), (ir & 0x1F)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IR. - * @sa setSn_IR() - */ -#define getSn_IR(sn) \ - (WIZCHIP_READ(Sn_IR(sn)) & 0x1F) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)imr Value to set @ref Sn_IMR - * @sa getSn_IMR() - */ -// dpgeorge: not yet implemented -#define setSn_IMR(sn, imr) (void)sn; (void)imr -#if 0 -#define setSn_IMR(sn, imr) \ - WIZCHIP_WRITE(Sn_IMR(sn), (imr & 0x1F)) -#endif - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IMR. - * @sa setSn_IMR() - */ -// dpgeorge: not yet implemented -#define getSn_IMR(sn) (0) -#if 0 -#define getSn_IMR(sn) \ - (WIZCHIP_READ(Sn_IMR(sn)) & 0x1F) -#endif - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_SR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_SR. - */ -#define getSn_SR(sn) \ - WIZCHIP_READ(Sn_SR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)port Value to set @ref Sn_PORT. - * @sa getSn_PORT() - */ -#define setSn_PORT(sn, port) { \ - WIZCHIP_WRITE(Sn_PORT(sn), (uint8_t)(port >> 8)); \ - WIZCHIP_WRITE(Sn_PORT(sn) + 1, (uint8_t) port); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_PORT. - * @sa setSn_PORT() - */ -#define getSn_PORT(sn) \ - ((WIZCHIP_READ(Sn_PORT(sn)) << 8) | WIZCHIP_READ(Sn_PORT(sn) + 1)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DHAR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to set socket n destination hardware address. It should be allocated 6 bytes. - * @sa getSn_DHAR() - */ -#define setSn_DHAR(sn, dhar) \ - WIZCHIP_WRITE_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to get socket n destination hardware address. It should be allocated 6 bytes. - * @sa setSn_DHAR() - */ -#define getSn_DHAR(sn, dhar) \ - WIZCHIP_READ_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to set socket n destination IP address. It should be allocated 4 bytes. - * @sa getSn_DIPR() - */ -#define setSn_DIPR(sn, dipr) \ - WIZCHIP_WRITE_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to get socket n destination IP address. It should be allocated 4 bytes. - * @sa SetSn_DIPR() - */ -#define getSn_DIPR(sn, dipr) \ - WIZCHIP_READ_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)dport Value to set @ref Sn_DPORT - * @sa getSn_DPORT() - */ -#define setSn_DPORT(sn, dport) { \ - WIZCHIP_WRITE(Sn_DPORT(sn), (uint8_t) (dport>>8)); \ - WIZCHIP_WRITE(Sn_DPORT(sn) + 1, (uint8_t) dport); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_DPORT. - * @sa setSn_DPORT() - */ -#define getSn_DPORT(sn) \ - ((WIZCHIP_READ(Sn_DPORT(sn)) << 8) + WIZCHIP_READ((Sn_DPORT(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)mss Value to set @ref Sn_MSSR - * @sa setSn_MSSR() - */ -#define setSn_MSSR(sn, mss) { \ - WIZCHIP_WRITE(Sn_MSSR(sn), (uint8_t)(mss>>8)); \ - WIZCHIP_WRITE((Sn_MSSR(sn)+1), (uint8_t) mss); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_MSSR. - * @sa setSn_MSSR() - */ -#define getSn_MSSR(sn) \ - ((WIZCHIP_READ(Sn_MSSR(sn)) << 8) + WIZCHIP_READ((Sn_MSSR(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)tos Value to set @ref Sn_TOS - * @sa getSn_TOS() - */ -#define setSn_TOS(sn, tos) \ - WIZCHIP_WRITE(Sn_TOS(sn), tos) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of Sn_TOS. - * @sa setSn_TOS() - */ -#define getSn_TOS(sn) \ - WIZCHIP_READ(Sn_TOS(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ttl Value to set @ref Sn_TTL - * @sa getSn_TTL() - */ -#define setSn_TTL(sn, ttl) \ - WIZCHIP_WRITE(Sn_TTL(sn), ttl) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TTL. - * @sa setSn_TTL() - */ -#define getSn_TTL(sn) \ - WIZCHIP_READ(Sn_TTL(sn)) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)rxbufsize Value to set @ref Sn_RXBUF_SIZE - * @sa getSn_RXBUF_SIZE() - */ -#define setSn_RXBUF_SIZE(sn, rxbufsize) \ - WIZCHIP_WRITE(Sn_RXBUF_SIZE(sn),rxbufsize) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_RXBUF_SIZE. - * @sa setSn_RXBUF_SIZE() - */ -#define getSn_RXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_RXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)txbufsize Value to set @ref Sn_TXBUF_SIZE - * @sa getSn_TXBUF_SIZE() - */ -#define setSn_TXBUF_SIZE(sn, txbufsize) \ - WIZCHIP_WRITE(Sn_TXBUF_SIZE(sn), txbufsize) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TXBUF_SIZE. - * @sa setSn_TXBUF_SIZE() - */ -#define getSn_TXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_TXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_FSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_FSR. - */ -uint16_t getSn_TX_FSR(uint8_t sn); - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_RD. - */ -#define getSn_TX_RD(sn) \ - ((WIZCHIP_READ(Sn_TX_RD(sn)) << 8) + WIZCHIP_READ((Sn_TX_RD(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)txwr Value to set @ref Sn_TX_WR - * @sa GetSn_TX_WR() - */ -#define setSn_TX_WR(sn, txwr) { \ - WIZCHIP_WRITE(Sn_TX_WR(sn), (uint8_t)(txwr>>8)); \ - WIZCHIP_WRITE((Sn_TX_WR(sn)+1), (uint8_t) txwr); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_WR. - * @sa setSn_TX_WR() - */ -#define getSn_TX_WR(sn) \ - ((WIZCHIP_READ(Sn_TX_WR(sn)) << 8) + WIZCHIP_READ((Sn_TX_WR(sn)+1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_RSR. - */ -uint16_t getSn_RX_RSR(uint8_t sn); - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)rxrd Value to set @ref Sn_RX_RD - * @sa getSn_RX_RD() - */ -#define setSn_RX_RD(sn, rxrd) { \ - WIZCHIP_WRITE(Sn_RX_RD(sn), (uint8_t)(rxrd>>8)); \ - WIZCHIP_WRITE((Sn_RX_RD(sn)+1), (uint8_t) rxrd); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @regurn uint16_t. Value of @ref Sn_RX_RD. - * @sa setSn_RX_RD() - */ -#define getSn_RX_RD(sn) \ - ((WIZCHIP_READ(Sn_RX_RD(sn)) << 8) + WIZCHIP_READ((Sn_RX_RD(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_WR. - */ -#define getSn_RX_WR(sn) \ - ((WIZCHIP_READ(Sn_RX_WR(sn)) << 8) + WIZCHIP_READ((Sn_RX_WR(sn)+1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)frag Value to set @ref Sn_FRAG - * @sa getSn_FRAD() - */ -#if 0 // dpgeorge -#define setSn_FRAG(sn, frag) { \ - WIZCHIP_WRITE(Sn_FRAG(sn), (uint8_t)(frag >>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1), (uint8_t) frag); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_FRAG. - * @sa setSn_FRAG() - */ -#define getSn_FRAG(sn) \ - ((WIZCHIP_READ(Sn_FRAG(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)kpalvt Value to set @ref Sn_KPALVTR - * @sa getSn_KPALVTR() - */ -#define setSn_KPALVTR(sn, kpalvt) \ - WIZCHIP_WRITE(Sn_KPALVTR(sn), kpalvt) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_KPALVTR. - * @sa setSn_KPALVTR() - */ -#define getSn_KPALVTR(sn) \ - WIZCHIP_READ(Sn_KPALVTR(sn)) - -////////////////////////////////////// -#endif - -///////////////////////////////////// -// Sn_TXBUF & Sn_RXBUF IO function // -///////////////////////////////////// -/** - * @brief Gets the max buffer size of socket sn passed as parameter. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n RX max buffer size. - */ -#define getSn_RxMAX(sn) \ - (getSn_RXBUF_SIZE(sn) << 10) - -/** - * @brief Gets the max buffer size of socket sn passed as parameters. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n TX max buffer size. - */ -//uint16_t getSn_TxMAX(uint8_t sn); -#define getSn_TxMAX(sn) \ - (getSn_TXBUF_SIZE(sn) << 10) - -void wiz_init(void); - -/** - * @ingroup Basic_IO_function - * @brief It copies data to internal TX memory - * - * @details This function reads the Tx write pointer register and after that, - * it copies the wizdata(pointer buffer) of the length of len(variable) bytes to internal TX memory - * and updates the Tx write pointer register. - * This function is being called by send() and sendto() function also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to write data - * @param len Data length - * @sa wiz_recv_data() - */ -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It copies data to your buffer from internal RX memory - * - * @details This function read the Rx read pointer register and after that, - * it copies the received data from internal RX memory - * to wizdata(pointer variable) of the length of len(variable) bytes. - * This function is being called by recv() also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to read data - * @param len Data length - * @sa wiz_send_data() - */ -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It discard the received data in RX memory. - * @details It discards the data of the length of len(variable) bytes in internal RX memory. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param len Data length - */ -void wiz_recv_ignore(uint8_t sn, uint16_t len); - -#endif // _W5500_H_ diff --git a/drivers/wiznet5k/ethernet/w5500/w5500.c b/drivers/wiznet5k/ethernet/w5500/w5500.c deleted file mode 100644 index fef08e2e3e..0000000000 --- a/drivers/wiznet5k/ethernet/w5500/w5500.c +++ /dev/null @@ -1,246 +0,0 @@ -//***************************************************************************** -// -//! \file w5500.c -//! \brief W5500 HAL Interface. -//! \version 1.0.1 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.2 -//! 1. Implicit type casting -> Explicit type casting. Refer to M20140501 -//! Fixed the problem on porting into under 32bit MCU -//! Issued by Mathias ClauBen, wizwiki forum ID Think01 and bobh -//! Thank for your interesting and serious advices. -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.0.1 -//! 1. Remove warning -//! 2. WIZCHIP_READ_BUF WIZCHIP_WRITE_BUF in case _WIZCHIP_IO_MODE_SPI_FDM_ -//! for loop optimized(removed). refer to M20131220 -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** -//#include -#include "w5500.h" - -#define _W5500_SPI_VDM_OP_ 0x00 -#define _W5500_SPI_FDM_OP_LEN1_ 0x01 -#define _W5500_SPI_FDM_OP_LEN2_ 0x02 -#define _W5500_SPI_FDM_OP_LEN4_ 0x03 - -//////////////////////////////////////////////////// - -#define LPC_SSP0 (0) - -static void Chip_SSP_ReadFrames_Blocking(int dummy, uint8_t *buf, uint32_t len) { - WIZCHIP.IF.SPI._read_bytes(buf, len); -} - -static void Chip_SSP_WriteFrames_Blocking(int dummy, const uint8_t *buf, uint32_t len) { - WIZCHIP.IF.SPI._write_bytes(buf, len); -} - -uint8_t WIZCHIP_READ(uint32_t AddrSel) -{ - uint8_t ret; - uint8_t spi_data[3]; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_READ_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //ret = WIZCHIP.IF.SPI._read_byte(); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 3); - Chip_SSP_ReadFrames_Blocking(LPC_SSP0, &ret, 1); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); - return ret; -} - -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb ) -{ - uint8_t spi_data[4]; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_WRITE_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //WIZCHIP.IF.SPI._write_byte(wb); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - spi_data[3] = wb; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 4); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_READ_BUF (uint32_t AddrSel, uint8_t* pBuf, uint16_t len) -{ - uint8_t spi_data[3]; - //uint16_t i; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_READ_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //for(i = 0; i < len; i++) - // pBuf[i] = WIZCHIP.IF.SPI._read_byte(); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 3); - Chip_SSP_ReadFrames_Blocking(LPC_SSP0, pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len) -{ - uint8_t spi_data[3]; - //uint16_t i; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_WRITE_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //for(i = 0; i < len; i++) - // WIZCHIP.IF.SPI._write_byte(pBuf[i]); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 3); - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - - -uint16_t getSn_TX_FSR(uint8_t sn) -{ - uint16_t val=0,val1=0; - - do - { - val1 = WIZCHIP_READ(Sn_TX_FSR(sn)); - val1 = (val1 << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_FSR(sn),1)); - if (val1 != 0) - { - val = WIZCHIP_READ(Sn_TX_FSR(sn)); - val = (val << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_FSR(sn),1)); - } - }while (val != val1); - return val; -} - - -uint16_t getSn_RX_RSR(uint8_t sn) -{ - uint16_t val=0,val1=0; - - do - { - val1 = WIZCHIP_READ(Sn_RX_RSR(sn)); - val1 = (val1 << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_RSR(sn),1)); - if (val1 != 0) - { - val = WIZCHIP_READ(Sn_RX_RSR(sn)); - val = (val << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_RSR(sn),1)); - } - }while (val != val1); - return val; -} - -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len) -{ - uint16_t ptr = 0; - uint32_t addrsel = 0; - - if(len == 0) return; - ptr = getSn_TX_WR(sn); - //M20140501 : implict type casting -> explict type casting - //addrsel = (ptr << 8) + (WIZCHIP_TXBUF_BLOCK(sn) << 3); - addrsel = ((uint32_t)ptr << 8) + (WIZCHIP_TXBUF_BLOCK(sn) << 3); - // - WIZCHIP_WRITE_BUF(addrsel,wizdata, len); - - ptr += len; - setSn_TX_WR(sn,ptr); -} - -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len) -{ - uint16_t ptr = 0; - uint32_t addrsel = 0; - - if(len == 0) return; - ptr = getSn_RX_RD(sn); - //M20140501 : implict type casting -> explict type casting - //addrsel = ((ptr << 8) + (WIZCHIP_RXBUF_BLOCK(sn) << 3); - addrsel = ((uint32_t)ptr << 8) + (WIZCHIP_RXBUF_BLOCK(sn) << 3); - // - WIZCHIP_READ_BUF(addrsel, wizdata, len); - ptr += len; - - setSn_RX_RD(sn,ptr); -} - - -void wiz_recv_ignore(uint8_t sn, uint16_t len) -{ - uint16_t ptr = 0; - - ptr = getSn_RX_RD(sn); - ptr += len; - setSn_RX_RD(sn,ptr); -} diff --git a/drivers/wiznet5k/ethernet/w5500/w5500.h b/drivers/wiznet5k/ethernet/w5500/w5500.h deleted file mode 100644 index f94eed3aff..0000000000 --- a/drivers/wiznet5k/ethernet/w5500/w5500.h +++ /dev/null @@ -1,2057 +0,0 @@ -//***************************************************************************** -// -//! \file w5500.h -//! \brief W5500 HAL Header File. -//! \version 1.0.0 -//! \date 2013/10/21 -//! \par Revision history -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#ifndef _W5500_H_ -#define _W5500_H_ - -#include -#include "../wizchip_conf.h" - -#define _W5500_IO_BASE_ 0x00000000 - -#define _W5500_SPI_READ_ (0x00 << 2) //< SPI interface Read operation in Control Phase -#define _W5500_SPI_WRITE_ (0x01 << 2) //< SPI interface Write operation in Control Phase - -#define WIZCHIP_CREG_BLOCK 0x00 //< Common register block -#define WIZCHIP_SREG_BLOCK(N) (1+4*N) //< Socket N register block -#define WIZCHIP_TXBUF_BLOCK(N) (2+4*N) //< Socket N Tx buffer address block -#define WIZCHIP_RXBUF_BLOCK(N) (3+4*N) //< Socket N Rx buffer address block - -#define WIZCHIP_OFFSET_INC(ADDR, N) (ADDR + (N<<8)) //< Increase offset address - - -/////////////////////////////////////// -// Definition For Legacy Chip Driver // -/////////////////////////////////////// -#define IINCHIP_READ(ADDR) WIZCHIP_READ(ADDR) ///< The defined for legacy chip driver -#define IINCHIP_WRITE(ADDR,VAL) WIZCHIP_WRITE(ADDR,VAL) ///< The defined for legacy chip driver -#define IINCHIP_READ_BUF(ADDR,BUF,LEN) WIZCHIP_READ_BUF(ADDR,BUF,LEN) ///< The defined for legacy chip driver -#define IINCHIP_WRITE_BUF(ADDR,BUF,LEN) WIZCHIP_WRITE(ADDR,BUF,LEN) ///< The defined for legacy chip driver - -////////////////////////////// -//-------------------------- defgroup --------------------------------- -/** - * @defgroup W5500 W5500 - * - * @brief WHIZCHIP register defines and I/O functions of @b W5500. - * - * - @ref WIZCHIP_register : @ref Common_register_group and @ref Socket_register_group - * - @ref WIZCHIP_IO_Functions : @ref Basic_IO_function, @ref Common_register_access_function and @ref Socket_register_access_function - */ - - -/** - * @defgroup WIZCHIP_register WIZCHIP register - * @ingroup W5500 - * - * @brief WHIZCHIP register defines register group of @b W5500. - * - * - @ref Common_register_group : Common register group - * - @ref Socket_register_group : \c SOCKET n register group - */ - - -/** - * @defgroup WIZCHIP_IO_Functions WIZCHIP I/O functions - * @ingroup W5500 - * - * @brief This supports the basic I/O functions for @ref WIZCHIP_register. - * - * - Basic I/O function \n - * WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() \n\n - * - * - @ref Common_register_group access functions \n - * -# @b Mode \n - * getMR(), setMR() - * -# @b Interrupt \n - * getIR(), setIR(), getIMR(), setIMR(), getSIR(), setSIR(), getSIMR(), setSIMR(), getINTLEVEL(), setINTLEVEL() - * -# Network Information \n - * getSHAR(), setSHAR(), getGAR(), setGAR(), getSUBR(), setSUBR(), getSIPR(), setSIPR() - * -# @b Retransmission \n - * getRCR(), setRCR(), getRTR(), setRTR() - * -# @b PPPoE \n - * getPTIMER(), setPTIMER(), getPMAGIC(), getPMAGIC(), getPSID(), setPSID(), getPHAR(), setPHAR(), getPMRU(), setPMRU() - * -# ICMP packet \n - * getUIPR(), getUPORTR() - * -# @b etc. \n - * getPHYCFGR(), setPHYCFGR(), getVERSIONR() \n\n - * - * - \ref Socket_register_group access functions \n - * -# SOCKET control \n - * getSn_MR(), setSn_MR(), getSn_CR(), setSn_CR(), getSn_IMR(), setSn_IMR(), getSn_IR(), setSn_IR() - * -# SOCKET information \n - * getSn_SR(), getSn_DHAR(), setSn_DHAR(), getSn_PORT(), setSn_PORT(), getSn_DIPR(), setSn_DIPR(), getSn_DPORT(), setSn_DPORT() - * getSn_MSSR(), setSn_MSSR() - * -# SOCKET communication \n - * getSn_RXBUF_SIZE(), setSn_RXBUF_SIZE(), getSn_TXBUF_SIZE(), setSn_TXBUF_SIZE() \n - * getSn_TX_RD(), getSn_TX_WR(), setSn_TX_WR() \n - * getSn_RX_RD(), setSn_RX_RD(), getSn_RX_WR() \n - * getSn_TX_FSR(), getSn_RX_RSR(), getSn_KPALVTR(), setSn_KPALVTR() - * -# IP header field \n - * getSn_FRAG(), setSn_FRAG(), getSn_TOS(), setSn_TOS() \n - * getSn_TTL(), setSn_TTL() - */ - - - -/** - * @defgroup Common_register_group Common register - * @ingroup WIZCHIP_register - * - * @brief Common register group\n - * It set the basic for the networking\n - * It set the configuration such as interrupt, network information, ICMP, etc. - * @details - * @sa MR : Mode register. - * @sa GAR, SUBR, SHAR, SIPR - * @sa INTLEVEL, IR, IMR, SIR, SIMR : Interrupt. - * @sa RTR, RCR : Data retransmission. - * @sa PTIMER, PMAGIC, PHAR, PSID, PMRU : PPPoE. - * @sa UIPR, UPORTR : ICMP message. - * @sa PHYCFGR, VERSIONR : etc. - */ - - - -/** - * @defgroup Socket_register_group Socket register - * @ingroup WIZCHIP_register - * - * @brief Socket register group.\n - * Socket register configures and control SOCKETn which is necessary to data communication. - * @details - * @sa Sn_MR, Sn_CR, Sn_IR, Sn_IMR : SOCKETn Control - * @sa Sn_SR, Sn_PORT, Sn_DHAR, Sn_DIPR, Sn_DPORT : SOCKETn Information - * @sa Sn_MSSR, Sn_TOS, Sn_TTL, Sn_KPALVTR, Sn_FRAG : Internet protocol. - * @sa Sn_RXBUF_SIZE, Sn_TXBUF_SIZE, Sn_TX_FSR, Sn_TX_RD, Sn_TX_WR, Sn_RX_RSR, Sn_RX_RD, Sn_RX_WR : Data communication - */ - - - - /** - * @defgroup Basic_IO_function Basic I/O function - * @ingroup WIZCHIP_IO_Functions - * @brief These are basic input/output functions to read values from register or write values to register. - */ - -/** - * @defgroup Common_register_access_function Common register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access common registers. - */ - -/** - * @defgroup Socket_register_access_function Socket register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access socket registers. - */ - -//------------------------------- defgroup end -------------------------------------------- -//----------------------------- W5500 Common Registers IOMAP ----------------------------- -/** - * @ingroup Common_register_group - * @brief Mode Register address(R/W)\n - * @ref MR is used for S/W reset, ping block mode, PPPoE mode and etc. - * @details Each bit of @ref MR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
RST Reserved WOL PB PPPoE Reserved FARP Reserved
- * - \ref MR_RST : Reset - * - \ref MR_WOL : Wake on LAN - * - \ref MR_PB : Ping block - * - \ref MR_PPPOE : PPPoE mode - * - \ref MR_FARP : Force ARP mode - */ -#define MR (_W5500_IO_BASE_ + (0x0000 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Gateway IP Register address(R/W) - * @details @ref GAR configures the default gateway address. - */ -#define GAR (_W5500_IO_BASE_ + (0x0001 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Subnet mask Register address(R/W) - * @details @ref SUBR configures the subnet mask address. - */ -#define SUBR (_W5500_IO_BASE_ + (0x0005 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Source MAC Register address(R/W) - * @details @ref SHAR configures the source hardware address. - */ -#define SHAR (_W5500_IO_BASE_ + (0x0009 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Source IP Register address(R/W) - * @details @ref SIPR configures the source IP address. - */ -#define SIPR (_W5500_IO_BASE_ + (0x000F << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Set Interrupt low level timer register address(R/W) - * @details @ref INTLEVEL configures the Interrupt Assert Time. - */ -#define INTLEVEL (_W5500_IO_BASE_ + (0x0013 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Interrupt Register(R/W) - * @details @ref IR indicates the interrupt status. Each bit of @ref IR will be still until the bit will be written to by the host. - * If @ref IR is not equal to x00 INTn PIN is asserted to low until it is x00\n\n - * Each bit of @ref IR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
CONFLICT UNREACH PPPoE MP Reserved Reserved Reserved Reserved
- * - \ref IR_CONFLICT : IP conflict - * - \ref IR_UNREACH : Destination unreachable - * - \ref IR_PPPoE : PPPoE connection close - * - \ref IR_MP : Magic packet - */ -#define IR (_W5500_IO_BASE_ + (0x0015 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Interrupt mask register(R/W) - * @details @ref IMR is used to mask interrupts. Each bit of @ref IMR corresponds to each bit of @ref IR. - * When a bit of @ref IMR is and the corresponding bit of @ref IR is an interrupt will be issued. In other words, - * if a bit of @ref IMR is an interrupt will not be issued even if the corresponding bit of @ref IR is \n\n - * Each bit of @ref IMR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
IM_IR7 IM_IR6 IM_IR5 IM_IR4 Reserved Reserved Reserved Reserved
- * - \ref IM_IR7 : IP Conflict Interrupt Mask - * - \ref IM_IR6 : Destination unreachable Interrupt Mask - * - \ref IM_IR5 : PPPoE Close Interrupt Mask - * - \ref IM_IR4 : Magic Packet Interrupt Mask - */ -#define IMR (_W5500_IO_BASE_ + (0x0016 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Register(R/W) - * @details @ref SIR indicates the interrupt status of Socket.\n - * Each bit of @ref SIR be still until @ref Sn_IR is cleared by the host.\n - * If @ref Sn_IR is not equal to x00 the n-th bit of @ref SIR is and INTn PIN is asserted until @ref SIR is x00 */ -#define SIR (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Mask Register(R/W) - * @details Each bit of @ref SIMR corresponds to each bit of @ref SIR. - * When a bit of @ref SIMR is and the corresponding bit of @ref SIR is Interrupt will be issued. - * In other words, if a bit of @ref SIMR is an interrupt will be not issued even if the corresponding bit of @ref SIR is - */ -#define SIMR (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Timeout register address( 1 is 100us )(R/W) - * @details @ref RTR configures the retransmission timeout period. The unit of timeout period is 100us and the default of @ref RTR is x07D0or 000 - * And so the default timeout period is 200ms(100us X 2000). During the time configured by @ref RTR, W5500 waits for the peer response - * to the packet that is transmitted by \ref Sn_CR (CONNECT, DISCON, CLOSE, SEND, SEND_MAC, SEND_KEEP command). - * If the peer does not respond within the @ref RTR time, W5500 retransmits the packet or issues timeout. - */ -#define RTR (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Retry count register(R/W) - * @details @ref RCR configures the number of time of retransmission. - * When retransmission occurs as many as ref RCR+1 Timeout interrupt is issued (@ref Sn_IR[TIMEOUT] = . - */ -#define RCR (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Request Timer register in PPPoE mode(R/W) - * @details @ref PTIMER configures the time for sending LCP echo request. The unit of time is 25ms. - */ -#define PTIMER (_W5500_IO_BASE_ + (0x001C << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Magic number register in PPPoE mode(R/W) - * @details @ref PMAGIC configures the 4bytes magic number to be used in LCP negotiation. - */ -#define PMAGIC (_W5500_IO_BASE_ + (0x001D << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Destination MAC Register address(R/W) - * @details @ref PHAR configures the PPPoE server hardware address that is acquired during PPPoE connection process. - */ -#define PHAR (_W5500_IO_BASE_ + (0x001E << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Session Identification Register(R/W) - * @details @ref PSID configures the PPPoE sever session ID acquired during PPPoE connection process. - */ -#define PSID (_W5500_IO_BASE_ + (0x0024 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Maximum Segment Size(MSS) register(R/W) - * @details @ref PMRU configures the maximum receive unit of PPPoE. - */ -#define PMRU (_W5500_IO_BASE_ + (0x0026 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable IP register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR indicates - * the destination IP address & port number respectively. - */ -#define UIPR (_W5500_IO_BASE_ + (0x0028 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable Port register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR - * indicates the destination IP address & port number respectively. - */ -#define UPORTR (_W5500_IO_BASE_ + (0x002C << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PHY Status Register(R/W) - * @details @ref PHYCFGR configures PHY operation mode and resets PHY. In addition, @ref PHYCFGR indicates the status of PHY such as duplex, Speed, Link. - */ -#define PHYCFGR (_W5500_IO_BASE_ + (0x002E << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -// Reserved (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0031 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0032 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0033 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0034 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0035 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0036 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0037 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0038 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief chip version register address(R) - * @details @ref VERSIONR always indicates the W5500 version as @b 0x04. - */ -#define VERSIONR (_W5500_IO_BASE_ + (0x0039 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - - -//----------------------------- W5500 Socket Registers IOMAP ----------------------------- -/** - * @ingroup Socket_register_group - * @brief socket Mode register(R/W) - * @details @ref Sn_MR configures the option or protocol type of Socket n.\n\n - * Each bit of @ref Sn_MR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
MULTI/MFEN BCASTB ND/MC/MMB UCASTB/MIP6B Protocol[3] Protocol[2] Protocol[1] Protocol[0]
- * - @ref Sn_MR_MULTI : Support UDP Multicasting - * - @ref Sn_MR_BCASTB : Broadcast block in UDP Multicasting - * - @ref Sn_MR_ND : No Delayed Ack(TCP) flag - * - @ref Sn_MR_MC : IGMP version used in UDP mulitcasting - * - @ref Sn_MR_MMB : Multicast Blocking in @ref Sn_MR_MACRAW mode - * - @ref Sn_MR_UCASTB : Unicast Block in UDP Multicating - * - @ref Sn_MR_MIP6B : IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * - Protocol - * - * - * - * - * - * - *
Protocol[3] Protocol[2] Protocol[1] Protocol[0] @b Meaning
0 0 0 0 Closed
0 0 0 1 TCP
0 0 1 0 UDP
0 1 0 0 MACRAW
- * - @ref Sn_MR_MACRAW : MAC LAYER RAW SOCK \n - * - @ref Sn_MR_UDP : UDP - * - @ref Sn_MR_TCP : TCP - * - @ref Sn_MR_CLOSE : Unused socket - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR(N) (_W5500_IO_BASE_ + (0x0000 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Socket command register(R/W) - * @details This is used to set the command for Socket n such as OPEN, CLOSE, CONNECT, LISTEN, SEND, and RECEIVE.\n - * After W5500 accepts the command, the @ref Sn_CR register is automatically cleared to 0x00. - * Even though @ref Sn_CR is cleared to 0x00, the command is still being processed.\n - * To check whether the command is completed or not, please check the @ref Sn_IR or @ref Sn_SR. - * - @ref Sn_CR_OPEN : Initialize or open socket. - * - @ref Sn_CR_LISTEN : Wait connection request in TCP mode(Server mode) - * - @ref Sn_CR_CONNECT : Send connection request in TCP mode(Client mode) - * - @ref Sn_CR_DISCON : Send closing request in TCP mode. - * - @ref Sn_CR_CLOSE : Close socket. - * - @ref Sn_CR_SEND : Update TX buffer pointer and send data. - * - @ref Sn_CR_SEND_MAC : Send data with MAC address, so without ARP process. - * - @ref Sn_CR_SEND_KEEP : Send keep alive message. - * - @ref Sn_CR_RECV : Update RX buffer pointer and receive data. - */ -#define Sn_CR(N) (_W5500_IO_BASE_ + (0x0001 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Socket interrupt register(R) - * @details @ref Sn_IR indicates the status of Socket Interrupt such as establishment, termination, receiving data, timeout).\n - * When an interrupt occurs and the corresponding bit of @ref Sn_IMR is the corresponding bit of @ref Sn_IR becomes \n - * In order to clear the @ref Sn_IR bit, the host should write the bit to \n - * - * - * - *
7 6 5 4 3 2 1 0
Reserved Reserved Reserved SEND_OK TIMEOUT RECV DISCON CON
- * - \ref Sn_IR_SENDOK : SEND_OK Interrupt - * - \ref Sn_IR_TIMEOUT : TIMEOUT Interrupt - * - \ref Sn_IR_RECV : RECV Interrupt - * - \ref Sn_IR_DISCON : DISCON Interrupt - * - \ref Sn_IR_CON : CON Interrupt - */ -#define Sn_IR(N) (_W5500_IO_BASE_ + (0x0002 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Socket status register(R) - * @details @ref Sn_SR indicates the status of Socket n.\n - * The status of Socket n is changed by @ref Sn_CR or some special control packet as SYN, FIN packet in TCP. - * @par Normal status - * - @ref SOCK_CLOSED : Closed - * - @ref SOCK_INIT : Initiate state - * - @ref SOCK_LISTEN : Listen state - * - @ref SOCK_ESTABLISHED : Success to connect - * - @ref SOCK_CLOSE_WAIT : Closing state - * - @ref SOCK_UDP : UDP socket - * - @ref SOCK_MACRAW : MAC raw mode socket - *@par Temporary status during changing the status of Socket n. - * - @ref SOCK_SYNSENT : This indicates Socket n sent the connect-request packet (SYN packet) to a peer. - * - @ref SOCK_SYNRECV : It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer. - * - @ref SOCK_FIN_WAIT : Connection state - * - @ref SOCK_CLOSING : Closing state - * - @ref SOCK_TIME_WAIT : Closing state - * - @ref SOCK_LAST_ACK : Closing state - */ -#define Sn_SR(N) (_W5500_IO_BASE_ + (0x0003 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief source port register(R/W) - * @details @ref Sn_PORT configures the source port number of Socket n. - * It is valid when Socket n is used in TCP/UPD mode. It should be set before OPEN command is ordered. - */ -#define Sn_PORT(N) (_W5500_IO_BASE_ + (0x0004 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Peer MAC register address(R/W) - * @details @ref Sn_DHAR configures the destination hardware address of Socket n when using SEND_MAC command in UDP mode or - * it indicates that it is acquired in ARP-process by CONNECT/SEND command. - */ -#define Sn_DHAR(N) (_W5500_IO_BASE_ + (0x0006 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Peer IP register address(R/W) - * @details @ref Sn_DIPR configures or indicates the destination IP address of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In TCP client mode, it configures an IP address of �TCP serverbefore CONNECT command. - * In TCP server mode, it indicates an IP address of �TCP clientafter successfully establishing connection. - * In UDP mode, it configures an IP address of peer to be received the UDP packet by SEND or SEND_MAC command. - */ -#define Sn_DIPR(N) (_W5500_IO_BASE_ + (0x000C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Peer port register address(R/W) - * @details @ref Sn_DPORT configures or indicates the destination port number of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In �TCP clientmode, it configures the listen port number of �TCP serverbefore CONNECT command. - * In �TCP Servermode, it indicates the port number of TCP client after successfully establishing connection. - * In UDP mode, it configures the port number of peer to be transmitted the UDP packet by SEND/SEND_MAC command. - */ -#define Sn_DPORT(N) (_W5500_IO_BASE_ + (0x0010 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Maximum Segment Size(Sn_MSSR0) register address(R/W) - * @details @ref Sn_MSSR configures or indicates the MTU(Maximum Transfer Unit) of Socket n. - */ -#define Sn_MSSR(N) (_W5500_IO_BASE_ + (0x0012 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -// Reserved (_W5500_IO_BASE_ + (0x0014 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief IP Type of Service(TOS) Register(R/W) - * @details @ref Sn_TOS configures the TOS(Type Of Service field in IP Header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TOS(N) (_W5500_IO_BASE_ + (0x0015 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -/** - * @ingroup Socket_register_group - * @brief IP Time to live(TTL) Register(R/W) - * @details @ref Sn_TTL configures the TTL(Time To Live field in IP header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TTL(N) (_W5500_IO_BASE_ + (0x0016 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001A << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Receive memory size register(R/W) - * @details @ref Sn_RXBUF_SIZE configures the RX buffer block size of Socket n. - * Socket n RX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data cannot be normally received from a peer. - * Although Socket n RX Buffer Block size is initially configured to 2Kbytes, - * user can re-configure its size using @ref Sn_RXBUF_SIZE. The total sum of @ref Sn_RXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data reception error is occurred. - */ -#define Sn_RXBUF_SIZE(N) (_W5500_IO_BASE_ + (0x001E << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory size register(R/W) - * @details @ref Sn_TXBUF_SIZE configures the TX buffer block size of Socket n. Socket n TX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data can�t be normally transmitted to a peer. - * Although Socket n TX Buffer Block size is initially configured to 2Kbytes, - * user can be re-configure its size using @ref Sn_TXBUF_SIZE. The total sum of @ref Sn_TXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data transmission error is occurred. - */ -#define Sn_TXBUF_SIZE(N) (_W5500_IO_BASE_ + (0x001F << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit free memory size register(R) - * @details @ref Sn_TX_FSR indicates the free size of Socket n TX Buffer Block. It is initialized to the configured size by @ref Sn_TXBUF_SIZE. - * Data bigger than @ref Sn_TX_FSR should not be saved in the Socket n TX Buffer because the bigger data overwrites the previous saved data not yet sent. - * Therefore, check before saving the data to the Socket n TX Buffer, and if data is equal or smaller than its checked size, - * transmit the data with SEND/SEND_MAC command after saving the data in Socket n TX buffer. But, if data is bigger than its checked size, - * transmit the data after dividing into the checked size and saving in the Socket n TX buffer. - */ -#define Sn_TX_FSR(N) (_W5500_IO_BASE_ + (0x0020 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory read pointer register address(R) - * @details @ref Sn_TX_RD is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP. - * After its initialization, it is auto-increased by SEND command. - * SEND command transmits the saved data from the current @ref Sn_TX_RD to the @ref Sn_TX_WR in the Socket n TX Buffer. - * After transmitting the saved data, the SEND command increases the @ref Sn_TX_RD as same as the @ref Sn_TX_WR. - * If its increment value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_TX_RD(N) (_W5500_IO_BASE_ + (0x0022 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory write pointer register address(R/W) - * @details @ref Sn_TX_WR is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP.\n - * It should be read or be updated like as follows.\n - * 1. Read the starting address for saving the transmitting data.\n - * 2. Save the transmitting data from the starting address of Socket n TX buffer.\n - * 3. After saving the transmitting data, update @ref Sn_TX_WR to the increased value as many as transmitting data size. - * If the increment value exceeds the maximum value 0xFFFF(greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value.\n - * 4. Transmit the saved data in Socket n TX Buffer by using SEND/SEND command - */ -#define Sn_TX_WR(N) (_W5500_IO_BASE_ + (0x0024 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Received data size register(R) - * @details @ref Sn_RX_RSR indicates the data size received and saved in Socket n RX Buffer. - * @ref Sn_RX_RSR does not exceed the @ref Sn_RXBUF_SIZE and is calculated as the difference between - * �Socket n RX Write Pointer (@ref Sn_RX_WR)and �Socket n RX Read Pointer (@ref Sn_RX_RD) - */ -#define Sn_RX_RSR(N) (_W5500_IO_BASE_ + (0x0026 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Read point of Receive memory(R/W) - * @details @ref Sn_RX_RD is initialized by OPEN command. Make sure to be read or updated as follows.\n - * 1. Read the starting save address of the received data.\n - * 2. Read data from the starting address of Socket n RX Buffer.\n - * 3. After reading the received data, Update @ref Sn_RX_RD to the increased value as many as the reading size. - * If the increment value exceeds the maximum value 0xFFFF, that is, is greater than 0x10000 and the carry bit occurs, - * update with the lower 16bits value ignored the carry bit.\n - * 4. Order RECV command is for notifying the updated @ref Sn_RX_RD to W5500. - */ -#define Sn_RX_RD(N) (_W5500_IO_BASE_ + (0x0028 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Write point of Receive memory(R) - * @details @ref Sn_RX_WR is initialized by OPEN command and it is auto-increased by the data reception. - * If the increased value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_RX_WR(N) (_W5500_IO_BASE_ + (0x002A << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief socket interrupt mask register(R) - * @details @ref Sn_IMR masks the interrupt of Socket n. - * Each bit corresponds to each bit of @ref Sn_IR. When a Socket n Interrupt is occurred and the corresponding bit of @ref Sn_IMR is - * the corresponding bit of @ref Sn_IR becomes When both the corresponding bit of @ref Sn_IMR and @ref Sn_IR are and the n-th bit of @ref IR is - * Host is interrupted by asserted INTn PIN to low. - */ -#define Sn_IMR(N) (_W5500_IO_BASE_ + (0x002C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Fragment field value in IP header register(R/W) - * @details @ref Sn_FRAG configures the FRAG(Fragment field in IP header). - */ -#define Sn_FRAG(N) (_W5500_IO_BASE_ + (0x002D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Keep Alive Timer register(R/W) - * @details @ref Sn_KPALVTR configures the transmitting timer of �KEEP ALIVE(KA)packet of SOCKETn. It is valid only in TCP mode, - * and ignored in other modes. The time unit is 5s. - * KA packet is transmittable after @ref Sn_SR is changed to SOCK_ESTABLISHED and after the data is transmitted or received to/from a peer at least once. - * In case of '@ref Sn_KPALVTR > 0', W5500 automatically transmits KA packet after time-period for checking the TCP connection (Auto-keepalive-process). - * In case of '@ref Sn_KPALVTR = 0', Auto-keep-alive-process will not operate, - * and KA packet can be transmitted by SEND_KEEP command by the host (Manual-keep-alive-process). - * Manual-keep-alive-process is ignored in case of '@ref Sn_KPALVTR > 0'. - */ -#define Sn_KPALVTR(N) (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -//#define Sn_TSR(N) (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - - -//----------------------------- W5500 Register values ----------------------------- - -/* MODE register values */ -/** - * @brief Reset - * @details If this bit is All internal registers will be initialized. It will be automatically cleared as after S/W reset. - */ -#define MR_RST 0x80 - -/** - * @brief Wake on LAN - * @details 0 : Disable WOL mode\n - * 1 : Enable WOL mode\n - * If WOL mode is enabled and the received magic packet over UDP has been normally processed, the Interrupt PIN (INTn) asserts to low. - * When using WOL mode, the UDP Socket should be opened with any source port number. (Refer to Socket n Mode Register (@ref Sn_MR) for opening Socket.) - * @note The magic packet over UDP supported by W5500 consists of 6 bytes synchronization stream (xFFFFFFFFFFFF and - * 16 times Target MAC address stream in UDP payload. The options such like password are ignored. You can use any UDP source port number for WOL mode. - */ -#define MR_WOL 0x20 - -/** - * @brief Ping block - * @details 0 : Disable Ping block\n - * 1 : Enable Ping block\n - * If the bit is it blocks the response to a ping request. - */ -#define MR_PB 0x10 - -/** - * @brief Enable PPPoE - * @details 0 : DisablePPPoE mode\n - * 1 : EnablePPPoE mode\n - * If you use ADSL, this bit should be - */ -#define MR_PPPOE 0x08 - -/** - * @brief Enable UDP_FORCE_ARP CHECHK - * @details 0 : Disable Force ARP mode\n - * 1 : Enable Force ARP mode\n - * In Force ARP mode, It forces on sending ARP Request whenever data is sent. - */ -#define MR_FARP 0x02 - -/* IR register values */ -/** - * @brief Check IP conflict. - * @details Bit is set as when own source IP address is same with the sender IP address in the received ARP request. - */ -#define IR_CONFLICT 0x80 - -/** - * @brief Get the destination unreachable message in UDP sending. - * @details When receiving the ICMP (Destination port unreachable) packet, this bit is set as - * When this bit is Destination Information such as IP address and Port number may be checked with the corresponding @ref UIPR & @ref UPORTR. - */ -#define IR_UNREACH 0x40 - -/** - * @brief Get the PPPoE close message. - * @details When PPPoE is disconnected during PPPoE mode, this bit is set. - */ -#define IR_PPPoE 0x20 - -/** - * @brief Get the magic packet interrupt. - * @details When WOL mode is enabled and receives the magic packet over UDP, this bit is set. - */ -#define IR_MP 0x10 - - -/* PHYCFGR register value */ -#define PHYCFGR_RST ~(1<<7) //< For PHY reset, must operate AND mask. -#define PHYCFGR_OPMD (1<<6) // Configre PHY with OPMDC value -#define PHYCFGR_OPMDC_ALLA (7<<3) -#define PHYCFGR_OPMDC_PDOWN (6<<3) -#define PHYCFGR_OPMDC_NA (5<<3) -#define PHYCFGR_OPMDC_100FA (4<<3) -#define PHYCFGR_OPMDC_100F (3<<3) -#define PHYCFGR_OPMDC_100H (2<<3) -#define PHYCFGR_OPMDC_10F (1<<3) -#define PHYCFGR_OPMDC_10H (0<<3) -#define PHYCFGR_DPX_FULL (1<<2) -#define PHYCFGR_DPX_HALF (0<<2) -#define PHYCFGR_SPD_100 (1<<1) -#define PHYCFGR_SPD_10 (0<<1) -#define PHYCFGR_LNK_ON (1<<0) -#define PHYCFGR_LNK_OFF (0<<0) - -/* IMR register values */ -/** - * @brief IP Conflict Interrupt Mask. - * @details 0: Disable IP Conflict Interrupt\n - * 1: Enable IP Conflict Interrupt - */ -#define IM_IR7 0x80 - -/** - * @brief Destination unreachable Interrupt Mask. - * @details 0: Disable Destination unreachable Interrupt\n - * 1: Enable Destination unreachable Interrupt - */ -#define IM_IR6 0x40 - -/** - * @brief PPPoE Close Interrupt Mask. - * @details 0: Disable PPPoE Close Interrupt\n - * 1: Enable PPPoE Close Interrupt - */ -#define IM_IR5 0x20 - -/** - * @brief Magic Packet Interrupt Mask. - * @details 0: Disable Magic Packet Interrupt\n - * 1: Enable Magic Packet Interrupt - */ -#define IM_IR4 0x10 - -/* Sn_MR Default values */ -/** - * @brief Support UDP Multicasting - * @details 0 : disable Multicasting\n - * 1 : enable Multicasting\n - * This bit is applied only during UDP mode(P[3:0] = 010.\n - * To use multicasting, @ref Sn_DIPR & @ref Sn_DPORT should be respectively configured with the multicast group IP address & port number - * before Socket n is opened by OPEN command of @ref Sn_CR. - */ -#define Sn_MR_MULTI 0x80 - -/** - * @brief Broadcast block in UDP Multicasting. - * @details 0 : disable Broadcast Blocking\n - * 1 : enable Broadcast Blocking\n - * This bit blocks to receive broadcasting packet during UDP mode(P[3:0] = 010.\m - * In addition, This bit does when MACRAW mode(P[3:0] = 100 - */ -#define Sn_MR_BCASTB 0x40 - -/** - * @brief No Delayed Ack(TCP), Multicast flag - * @details 0 : Disable No Delayed ACK option\n - * 1 : Enable No Delayed ACK option\n - * This bit is applied only during TCP mode (P[3:0] = 001.\n - * When this bit is It sends the ACK packet without delay as soon as a Data packet is received from a peer.\n - * When this bit is It sends the ACK packet after waiting for the timeout time configured by @ref RTR. - */ -#define Sn_MR_ND 0x20 - -/** - * @brief Unicast Block in UDP Multicasting - * @details 0 : disable Unicast Blocking\n - * 1 : enable Unicast Blocking\n - * This bit blocks receiving the unicast packet during UDP mode(P[3:0] = 010 and MULTI = - */ -#define Sn_MR_UCASTB 0x10 - -/** - * @brief MAC LAYER RAW SOCK - * @details This configures the protocol mode of Socket n. - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR_MACRAW 0x04 - -//#define Sn_MR_IPRAW 0x03 /**< IP LAYER RAW SOCK */ - -/** - * @brief UDP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_UDP 0x02 - -/** - * @brief TCP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_TCP 0x01 - -/** - * @brief Unused socket - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_CLOSE 0x00 - -/* Sn_MR values used with Sn_MR_MACRAW */ -/** - * @brief MAC filter enable in @ref Sn_MR_MACRAW mode - * @details 0 : disable MAC Filtering\n - * 1 : enable MAC Filtering\n - * This bit is applied only during MACRAW mode(P[3:0] = 100.\n - * When set as W5500 can only receive broadcasting packet or packet sent to itself. - * When this bit is W5500 can receive all packets on Ethernet. - * If user wants to implement Hybrid TCP/IP stack, - * it is recommended that this bit is set as for reducing host overhead to process the all received packets. - */ -#define Sn_MR_MFEN Sn_MR_MULTI - -/** - * @brief Multicast Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : using IGMP version 2\n - * 1 : using IGMP version 1\n - * This bit is applied only during UDP mode(P[3:0] = 010 and MULTI = - * It configures the version for IGMP messages (Join/Leave/Report). - */ -#define Sn_MR_MMB Sn_MR_ND - -/** - * @brief IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : disable IPv6 Blocking\n - * 1 : enable IPv6 Blocking\n - * This bit is applied only during MACRAW mode (P[3:0] = 100. It blocks to receiving the IPv6 packet. - */ -#define Sn_MR_MIP6B Sn_MR_UCASTB - -/* Sn_MR value used with Sn_MR_UDP & Sn_MR_MULTI */ -/** - * @brief IGMP version used in UDP mulitcasting - * @details 0 : disable Multicast Blocking\n - * 1 : enable Multicast Blocking\n - * This bit is applied only when MACRAW mode(P[3:0] = 100. It blocks to receive the packet with multicast MAC address. - */ -#define Sn_MR_MC Sn_MR_ND - -/* Sn_MR alternate values */ -/** - * @brief For Berkeley Socket API - */ -#define SOCK_STREAM Sn_MR_TCP - -/** - * @brief For Berkeley Socket API - */ -#define SOCK_DGRAM Sn_MR_UDP - - -/* Sn_CR values */ -/** - * @brief Initialize or open socket - * @details Socket n is initialized and opened according to the protocol selected in Sn_MR(P3:P0). - * The table below shows the value of @ref Sn_SR corresponding to @ref Sn_MR.\n - * - * - * - * - * - * - *
\b Sn_MR (P[3:0]) \b Sn_SR
Sn_MR_CLOSE (000
Sn_MR_TCP (001 SOCK_INIT (0x13)
Sn_MR_UDP (010 SOCK_UDP (0x22)
S0_MR_MACRAW (100 SOCK_MACRAW (0x02)
- */ -#define Sn_CR_OPEN 0x01 - -/** - * @brief Wait connection request in TCP mode(Server mode) - * @details This is valid only in TCP mode (Sn_MR(P3:P0) = Sn_MR_TCP). - * In this mode, Socket n operates as a �TCP serverand waits for connection-request (SYN packet) from any �TCP client - * The @ref Sn_SR changes the state from SOCK_INIT to SOCKET_LISTEN. - * When a �TCP clientconnection request is successfully established, - * the @ref Sn_SR changes from SOCK_LISTEN to SOCK_ESTABLISHED and the Sn_IR(0) becomes - * But when a �TCP clientconnection request is failed, Sn_IR(3) becomes and the status of @ref Sn_SR changes to SOCK_CLOSED. - */ -#define Sn_CR_LISTEN 0x02 - -/** - * @brief Send connection request in TCP mode(Client mode) - * @details To connect, a connect-request (SYN packet) is sent to b>TCP serverconfigured by @ref Sn_DIPR & Sn_DPORT(destination address & port). - * If the connect-request is successful, the @ref Sn_SR is changed to @ref SOCK_ESTABLISHED and the Sn_IR(0) becomes \n\n - * The connect-request fails in the following three cases.\n - * 1. When a @b ARPTO occurs (@ref Sn_IR[3] = ) because destination hardware address is not acquired through the ARP-process.\n - * 2. When a @b SYN/ACK packet is not received and @b TCPTO (Sn_IR(3) = )\n - * 3. When a @b RST packet is received instead of a @b SYN/ACK packet. In these cases, @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note This is valid only in TCP mode and operates when Socket n acts as b>TCP client - */ -#define Sn_CR_CONNECT 0x04 - -/** - * @brief Send closing request in TCP mode - * @details Regardless of b>TCP serveror b>TCP client the DISCON command processes the disconnect-process (b>Active closeor b>Passive close.\n - * @par Active close - * it transmits disconnect-request(FIN packet) to the connected peer\n - * @par Passive close - * When FIN packet is received from peer, a FIN packet is replied back to the peer.\n - * @details When the disconnect-process is successful (that is, FIN/ACK packet is received successfully), @ref Sn_SR is changed to @ref SOCK_CLOSED.\n - * Otherwise, TCPTO occurs (Sn_IR(3)=)= and then @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note Valid only in TCP mode. - */ -#define Sn_CR_DISCON 0x08 - -/** - * @brief Close socket - * @details Sn_SR is changed to @ref SOCK_CLOSED. - */ -#define Sn_CR_CLOSE 0x10 - -/** - * @brief Update TX buffer pointer and send data - * @details SEND transmits all the data in the Socket n TX buffer.\n - * For more details, please refer to Socket n TX Free Size Register (@ref Sn_TX_FSR), Socket n, - * TX Write Pointer Register(@ref Sn_TX_WR), and Socket n TX Read Pointer Register(@ref Sn_TX_RD). - */ -#define Sn_CR_SEND 0x20 - -/** - * @brief Send data with MAC address, so without ARP process - * @details The basic operation is same as SEND.\n - * Normally SEND transmits data after destination hardware address is acquired by the automatic ARP-process(Address Resolution Protocol).\n - * But SEND_MAC transmits data without the automatic ARP-process.\n - * In this case, the destination hardware address is acquired from @ref Sn_DHAR configured by host, instead of APR-process. - * @note Valid only in UDP mode. - */ -#define Sn_CR_SEND_MAC 0x21 - -/** - * @brief Send keep alive message - * @details It checks the connection status by sending 1byte keep-alive packet.\n - * If the peer can not respond to the keep-alive packet during timeout time, the connection is terminated and the timeout interrupt will occur. - * @note Valid only in TCP mode. - */ -#define Sn_CR_SEND_KEEP 0x22 - -/** - * @brief Update RX buffer pointer and receive data - * @details RECV completes the processing of the received data in Socket n RX Buffer by using a RX read pointer register (@ref Sn_RX_RD).\n - * For more details, refer to Socket n RX Received Size Register (@ref Sn_RX_RSR), Socket n RX Write Pointer Register (@ref Sn_RX_WR), - * and Socket n RX Read Pointer Register (@ref Sn_RX_RD). - */ -#define Sn_CR_RECV 0x40 - -/* Sn_IR values */ -/** - * @brief SEND_OK Interrupt - * @details This is issued when SEND command is completed. - */ -#define Sn_IR_SENDOK 0x10 - -/** - * @brief TIMEOUT Interrupt - * @details This is issued when ARPTO or TCPTO occurs. - */ -#define Sn_IR_TIMEOUT 0x08 - -/** - * @brief RECV Interrupt - * @details This is issued whenever data is received from a peer. - */ -#define Sn_IR_RECV 0x04 - -/** - * @brief DISCON Interrupt - * @details This is issued when FIN or FIN/ACK packet is received from a peer. - */ -#define Sn_IR_DISCON 0x02 - -/** - * @brief CON Interrupt - * @details This is issued one time when the connection with peer is successful and then @ref Sn_SR is changed to @ref SOCK_ESTABLISHED. - */ -#define Sn_IR_CON 0x01 - -/* Sn_SR values */ -/** - * @brief Closed - * @details This indicates that Socket n is released.\N - * When DICON, CLOSE command is ordered, or when a timeout occurs, it is changed to @ref SOCK_CLOSED regardless of previous status. - */ -#define SOCK_CLOSED 0x00 - -/** - * @brief Initiate state - * @details This indicates Socket n is opened with TCP mode.\N - * It is changed to @ref SOCK_INIT when Sn_MR(P[3:0]) = 001and OPEN command is ordered.\N - * After @ref SOCK_INIT, user can use LISTEN /CONNECT command. - */ -#define SOCK_INIT 0x13 - -/** - * @brief Listen state - * @details This indicates Socket n is operating as b>TCP servermode and waiting for connection-request (SYN packet) from a peer (b>TCP client.\n - * It will change to @ref SOCK_ESTALBLISHED when the connection-request is successfully accepted.\n - * Otherwise it will change to @ref SOCK_CLOSED after TCPTO occurred (Sn_IR(TIMEOUT) = . - */ -#define SOCK_LISTEN 0x14 - -/** - * @brief Connection state - * @details This indicates Socket n sent the connect-request packet (SYN packet) to a peer.\n - * It is temporarily shown when @ref Sn_SR is changed from @ref SOCK_INIT to @ref SOCK_ESTABLISHED by CONNECT command.\n - * If connect-accept(SYN/ACK packet) is received from the peer at SOCK_SYNSENT, it changes to @ref SOCK_ESTABLISHED.\n - * Otherwise, it changes to @ref SOCK_CLOSED after TCPTO (@ref Sn_IR[TIMEOUT] = is occurred. - */ -#define SOCK_SYNSENT 0x15 - -/** - * @brief Connection state - * @details It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer.\n - * If socket n sends the response (SYN/ACK packet) to the peer successfully, it changes to @ref SOCK_ESTABLISHED. \n - * If not, it changes to @ref SOCK_CLOSED after timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_SYNRECV 0x16 - -/** - * @brief Success to connect - * @details This indicates the status of the connection of Socket n.\n - * It changes to @ref SOCK_ESTABLISHED when the b>TCP SERVERprocessed the SYN packet from the b>TCP CLIENTduring @ref SOCK_LISTEN, or - * when the CONNECT command is successful.\n - * During @ref SOCK_ESTABLISHED, DATA packet can be transferred using SEND or RECV command. - */ -#define SOCK_ESTABLISHED 0x17 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_FIN_WAIT 0x18 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_CLOSING 0x1A - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_TIME_WAIT 0x1B - -/** - * @brief Closing state - * @details This indicates Socket n received the disconnect-request (FIN packet) from the connected peer.\n - * This is half-closing status, and data can be transferred.\n - * For full-closing, DISCON command is used. But For just-closing, CLOSE command is used. - */ -#define SOCK_CLOSE_WAIT 0x1C - -/** - * @brief Closing state - * @details This indicates Socket n is waiting for the response (FIN/ACK packet) to the disconnect-request (FIN packet) by passive-close.\n - * It changes to @ref SOCK_CLOSED when Socket n received the response successfully, or when timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_LAST_ACK 0x1D - -/** - * @brief UDP socket - * @details This indicates Socket n is opened in UDP mode(Sn_MR(P[3:0]) = 010.\n - * It changes to SOCK_UPD when Sn_MR(P[3:0]) = 010 and OPEN command is ordered.\n - * Unlike TCP mode, data can be transfered without the connection-process. - */ -#define SOCK_UDP 0x22 - -//#define SOCK_IPRAW 0x32 /**< IP raw mode socket */ - -/** - * @brief MAC raw mode socket - * @details This indicates Socket 0 is opened in MACRAW mode (S0_MR(P[3:0]) = 100and is valid only in Socket 0.\n - * It changes to SOCK_MACRAW when S0_MR(P[3:0] = 100and OPEN command is ordered.\n - * Like UDP mode socket, MACRAW mode Socket 0 can transfer a MAC packet (Ethernet frame) without the connection-process. - */ -#define SOCK_MACRAW 0x42 - -//#define SOCK_PPPOE 0x5F - -/* IP PROTOCOL */ -#define IPPROTO_IP 0 //< Dummy for IP -#define IPPROTO_ICMP 1 //< Control message protocol -#define IPPROTO_IGMP 2 //< Internet group management protocol -#define IPPROTO_GGP 3 //< Gateway^2 (deprecated) -#define IPPROTO_TCP 6 //< TCP -#define IPPROTO_PUP 12 //< PUP -#define IPPROTO_UDP 17 //< UDP -#define IPPROTO_IDP 22 //< XNS idp -#define IPPROTO_ND 77 //< UNOFFICIAL net disk protocol -#define IPPROTO_RAW 255 //< Raw IP packet - - -/** - * @brief Enter a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n \n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt.\n - * In OS environment, You can replace it to critical section api supported by OS. - * - * \sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * \sa WIZCHIP_CRITICAL_EXIT() - */ -#define WIZCHIP_CRITICAL_ENTER() WIZCHIP.CRIS._enter() - -/** - * @brief Exit a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n\n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt. \n - * In OS environment, You can replace it to critical section api supported by OS. - * - * @sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * @sa WIZCHIP_CRITICAL_ENTER() - */ -#ifdef _exit -#undef _exit -#endif -#define WIZCHIP_CRITICAL_EXIT() WIZCHIP.CRIS._exit() - - - -//////////////////////// -// Basic I/O Function // -//////////////////////// - -/** - * @ingroup Basic_IO_function - * @brief It reads 1 byte value from a register. - * @param AddrSel Register address - * @return The value of register - */ -uint8_t WIZCHIP_READ (uint32_t AddrSel); - -/** - * @ingroup Basic_IO_function - * @brief It writes 1 byte value to a register. - * @param AddrSel Register address - * @param wb Write data - * @return void - */ -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb ); - -/** - * @ingroup Basic_IO_function - * @brief It reads sequence data from registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to read data - * @param len Data length - */ -void WIZCHIP_READ_BUF (uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It writes sequence data to registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to write data - * @param len Data length - */ -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -///////////////////////////////// -// Common Register I/O function // -///////////////////////////////// -/** - * @ingroup Common_register_access_function - * @brief Set Mode Register - * @param (uint8_t)mr The value to be set. - * @sa getMR() - */ -#define setMR(mr) \ - WIZCHIP_WRITE(MR,mr) - - -/** - * @ingroup Common_register_access_function - * @brief Get Mode Register - * @return uint8_t. The value of Mode register. - * @sa setMR() - */ -#define getMR() \ - WIZCHIP_READ(MR) - -/** - * @ingroup Common_register_access_function - * @brief Set gateway IP address - * @param (uint8_t*)gar Pointer variable to set gateway IP address. It should be allocated 4 bytes. - * @sa getGAR() - */ -#define setGAR(gar) \ - WIZCHIP_WRITE_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Get gateway IP address - * @param (uint8_t*)gar Pointer variable to get gateway IP address. It should be allocated 4 bytes. - * @sa setGAR() - */ -#define getGAR(gar) \ - WIZCHIP_READ_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Set subnet mask address - * @param (uint8_t*)subr Pointer variable to set subnet mask address. It should be allocated 4 bytes. - * @sa getSUBR() - */ -#define setSUBR(subr) \ - WIZCHIP_WRITE_BUF(SUBR, subr,4) - - -/** - * @ingroup Common_register_access_function - * @brief Get subnet mask address - * @param (uint8_t*)subr Pointer variable to get subnet mask address. It should be allocated 4 bytes. - * @sa setSUBR() - */ -#define getSUBR(subr) \ - WIZCHIP_READ_BUF(SUBR, subr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set local MAC address - * @param (uint8_t*)shar Pointer variable to set local MAC address. It should be allocated 6 bytes. - * @sa getSHAR() - */ -#define setSHAR(shar) \ - WIZCHIP_WRITE_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local MAC address - * @param (uint8_t*)shar Pointer variable to get local MAC address. It should be allocated 6 bytes. - * @sa setSHAR() - */ -#define getSHAR(shar) \ - WIZCHIP_READ_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set local IP address - * @param (uint8_t*)sipr Pointer variable to set local IP address. It should be allocated 4 bytes. - * @sa getSIPR() - */ -#define setSIPR(sipr) \ - WIZCHIP_WRITE_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)sipr Pointer variable to get local IP address. It should be allocated 4 bytes. - * @sa setSIPR() - */ -#define getSIPR(sipr) \ - WIZCHIP_READ_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set INTLEVEL register - * @param (uint16_t)intlevel Value to set @ref INTLEVEL register. - * @sa getINTLEVEL() - */ -#define setINTLEVEL(intlevel) {\ - WIZCHIP_WRITE(INTLEVEL, (uint8_t)(intlevel >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(INTLEVEL,1), (uint8_t) intlevel); \ - } - - -/** - * @ingroup Common_register_access_function - * @brief Get INTLEVEL register - * @return uint16_t. Value of @ref INTLEVEL register. - * @sa setINTLEVEL() - */ -#define getINTLEVEL() \ - ((WIZCHIP_READ(INTLEVEL) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(INTLEVEL,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref IR register - * @param (uint8_t)ir Value to set @ref IR register. - * @sa getIR() - */ -#define setIR(ir) \ - WIZCHIP_WRITE(IR, (ir & 0xF0)) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IR register - * @return uint8_t. Value of @ref IR register. - * @sa setIR() - */ -#define getIR() \ - (WIZCHIP_READ(IR) & 0xF0) -/** - * @ingroup Common_register_access_function - * @brief Set @ref IMR register - * @param (uint8_t)imr Value to set @ref IMR register. - * @sa getIMR() - */ -#define setIMR(imr) \ - WIZCHIP_WRITE(IMR, imr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IMR register - * @return uint8_t. Value of @ref IMR register. - * @sa setIMR() - */ -#define getIMR() \ - WIZCHIP_READ(IMR) - - -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIR register - * @param (uint8_t)sir Value to set @ref SIR register. - * @sa getSIR() - */ -#define setSIR(sir) \ - WIZCHIP_WRITE(SIR, sir) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIR register - * @return uint8_t. Value of @ref SIR register. - * @sa setSIR() - */ -#define getSIR() \ - WIZCHIP_READ(SIR) -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIMR register - * @param (uint8_t)simr Value to set @ref SIMR register. - * @sa getSIMR() - */ -#define setSIMR(simr) \ - WIZCHIP_WRITE(SIMR, simr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIMR register - * @return uint8_t. Value of @ref SIMR register. - * @sa setSIMR() - */ -#define getSIMR() \ - WIZCHIP_READ(SIMR) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RTR register - * @param (uint16_t)rtr Value to set @ref RTR register. - * @sa getRTR() - */ -#define setRTR(rtr) {\ - WIZCHIP_WRITE(RTR, (uint8_t)(rtr >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(RTR,1), (uint8_t) rtr); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RTR register - * @return uint16_t. Value of @ref RTR register. - * @sa setRTR() - */ -#define getRTR() \ - ((WIZCHIP_READ(RTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(RTR,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RCR register - * @param (uint8_t)rcr Value to set @ref RCR register. - * @sa getRCR() - */ -#define setRCR(rcr) \ - WIZCHIP_WRITE(RCR, rcr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RCR register - * @return uint8_t. Value of @ref RCR register. - * @sa setRCR() - */ -#define getRCR() \ - WIZCHIP_READ(RCR) - -//================================================== test done =========================================================== - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PTIMER register - * @param (uint8_t)ptimer Value to set @ref PTIMER register. - * @sa getPTIMER() - */ -#define setPTIMER(ptimer) \ - WIZCHIP_WRITE(PTIMER, ptimer) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PTIMER register - * @return uint8_t. Value of @ref PTIMER register. - * @sa setPTIMER() - */ -#define getPTIMER() \ - WIZCHIP_READ(PTIMER) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMAGIC register - * @param (uint8_t)pmagic Value to set @ref PMAGIC register. - * @sa getPMAGIC() - */ -#define setPMAGIC(pmagic) \ - WIZCHIP_WRITE(PMAGIC, pmagic) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMAGIC register - * @return uint8_t. Value of @ref PMAGIC register. - * @sa setPMAGIC() - */ -#define getPMAGIC() \ - WIZCHIP_READ(PMAGIC) - -/** - * @ingroup Common_register_access_function - * @brief Set PHAR address - * @param (uint8_t*)phar Pointer variable to set PPP destination MAC register address. It should be allocated 6 bytes. - * @sa getPHAR() - */ -#define setPHAR(phar) \ - WIZCHIP_WRITE_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)phar Pointer variable to PPP destination MAC register address. It should be allocated 6 bytes. - * @sa setPHAR() - */ -#define getPHAR(phar) \ - WIZCHIP_READ_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PSID register - * @param (uint16_t)psid Value to set @ref PSID register. - * @sa getPSID() - */ -#define setPSID(psid) {\ - WIZCHIP_WRITE(PSID, (uint8_t)(psid >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PSID,1), (uint8_t) psid); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PSID register - * @return uint16_t. Value of @ref PSID register. - * @sa setPSID() - */ -//uint16_t getPSID(void); -#define getPSID() \ - ((WIZCHIP_READ(PSID) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PSID,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMRU register - * @param (uint16_t)pmru Value to set @ref PMRU register. - * @sa getPMRU() - */ -#define setPMRU(pmru) { \ - WIZCHIP_WRITE(PMRU, (uint8_t)(pmru>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PMRU,1), (uint8_t) pmru); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMRU register - * @return uint16_t. Value of @ref PMRU register. - * @sa setPMRU() - */ -#define getPMRU() \ - ((WIZCHIP_READ(PMRU) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PMRU,1))) - -/** - * @ingroup Common_register_access_function - * @brief Get unreachable IP address - * @param (uint8_t*)uipr Pointer variable to get unreachable IP address. It should be allocated 4 bytes. - */ -#define getUIPR(uipr) \ - WIZCHIP_READ_BUF(UIPR,uipr,6) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref UPORTR register - * @return uint16_t. Value of @ref UPORTR register. - */ -#define getUPORTR() \ - ((WIZCHIP_READ(UPORTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(UPORTR,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PHYCFGR register - * @param (uint8_t)phycfgr Value to set @ref PHYCFGR register. - * @sa getPHYCFGR() - */ -#define setPHYCFGR(phycfgr) \ - WIZCHIP_WRITE(PHYCFGR, phycfgr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PHYCFGR register - * @return uint8_t. Value of @ref PHYCFGR register. - * @sa setPHYCFGR() - */ -#define getPHYCFGR() \ - WIZCHIP_READ(PHYCFGR) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref VERSIONR register - * @return uint8_t. Value of @ref VERSIONR register. - */ -#define getVERSIONR() \ - WIZCHIP_READ(VERSIONR) - -///////////////////////////////////// - -/////////////////////////////////// -// Socket N register I/O function // -/////////////////////////////////// -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)mr Value to set @ref Sn_MR - * @sa getSn_MR() - */ -#define setSn_MR(sn, mr) \ - WIZCHIP_WRITE(Sn_MR(sn),mr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_MR. - * @sa setSn_MR() - */ -#define getSn_MR(sn) \ - WIZCHIP_READ(Sn_MR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)cr Value to set @ref Sn_CR - * @sa getSn_CR() - */ -#define setSn_CR(sn, cr) \ - WIZCHIP_WRITE(Sn_CR(sn), cr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_CR. - * @sa setSn_CR() - */ -#define getSn_CR(sn) \ - WIZCHIP_READ(Sn_CR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ir Value to set @ref Sn_IR - * @sa getSn_IR() - */ -#define setSn_IR(sn, ir) \ - WIZCHIP_WRITE(Sn_IR(sn), (ir & 0x1F)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IR. - * @sa setSn_IR() - */ -#define getSn_IR(sn) \ - (WIZCHIP_READ(Sn_IR(sn)) & 0x1F) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)imr Value to set @ref Sn_IMR - * @sa getSn_IMR() - */ -#define setSn_IMR(sn, imr) \ - WIZCHIP_WRITE(Sn_IMR(sn), (imr & 0x1F)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IMR. - * @sa setSn_IMR() - */ -#define getSn_IMR(sn) \ - (WIZCHIP_READ(Sn_IMR(sn)) & 0x1F) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_SR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_SR. - */ -#define getSn_SR(sn) \ - WIZCHIP_READ(Sn_SR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)port Value to set @ref Sn_PORT. - * @sa getSn_PORT() - */ -#define setSn_PORT(sn, port) { \ - WIZCHIP_WRITE(Sn_PORT(sn), (uint8_t)(port >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_PORT(sn),1), (uint8_t) port); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_PORT. - * @sa setSn_PORT() - */ -#define getSn_PORT(sn) \ - ((WIZCHIP_READ(Sn_PORT(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_PORT(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DHAR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to set socket n destination hardware address. It should be allocated 6 bytes. - * @sa getSn_DHAR() - */ -#define setSn_DHAR(sn, dhar) \ - WIZCHIP_WRITE_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to get socket n destination hardware address. It should be allocated 6 bytes. - * @sa setSn_DHAR() - */ -#define getSn_DHAR(sn, dhar) \ - WIZCHIP_READ_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to set socket n destination IP address. It should be allocated 4 bytes. - * @sa getSn_DIPR() - */ -#define setSn_DIPR(sn, dipr) \ - WIZCHIP_WRITE_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to get socket n destination IP address. It should be allocated 4 bytes. - * @sa SetSn_DIPR() - */ -#define getSn_DIPR(sn, dipr) \ - WIZCHIP_READ_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)dport Value to set @ref Sn_DPORT - * @sa getSn_DPORT() - */ -#define setSn_DPORT(sn, dport) { \ - WIZCHIP_WRITE(Sn_DPORT(sn), (uint8_t) (dport>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_DPORT(sn),1), (uint8_t) dport); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_DPORT. - * @sa setSn_DPORT() - */ -#define getSn_DPORT(sn) \ - ((WIZCHIP_READ(Sn_DPORT(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_DPORT(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)mss Value to set @ref Sn_MSSR - * @sa setSn_MSSR() - */ -#define setSn_MSSR(sn, mss) { \ - WIZCHIP_WRITE(Sn_MSSR(sn), (uint8_t)(mss>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_MSSR(sn),1), (uint8_t) mss); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_MSSR. - * @sa setSn_MSSR() - */ -#define getSn_MSSR(sn) \ - ((WIZCHIP_READ(Sn_MSSR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_MSSR(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)tos Value to set @ref Sn_TOS - * @sa getSn_TOS() - */ -#define setSn_TOS(sn, tos) \ - WIZCHIP_WRITE(Sn_TOS(sn), tos) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of Sn_TOS. - * @sa setSn_TOS() - */ -#define getSn_TOS(sn) \ - WIZCHIP_READ(Sn_TOS(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ttl Value to set @ref Sn_TTL - * @sa getSn_TTL() - */ -#define setSn_TTL(sn, ttl) \ - WIZCHIP_WRITE(Sn_TTL(sn), ttl) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TTL. - * @sa setSn_TTL() - */ -#define getSn_TTL(sn) \ - WIZCHIP_READ(Sn_TTL(sn)) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)rxbufsize Value to set @ref Sn_RXBUF_SIZE - * @sa getSn_RXBUF_SIZE() - */ -#define setSn_RXBUF_SIZE(sn, rxbufsize) \ - WIZCHIP_WRITE(Sn_RXBUF_SIZE(sn),rxbufsize) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_RXBUF_SIZE. - * @sa setSn_RXBUF_SIZE() - */ -#define getSn_RXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_RXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)txbufsize Value to set @ref Sn_TXBUF_SIZE - * @sa getSn_TXBUF_SIZE() - */ -#define setSn_TXBUF_SIZE(sn, txbufsize) \ - WIZCHIP_WRITE(Sn_TXBUF_SIZE(sn), txbufsize) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TXBUF_SIZE. - * @sa setSn_TXBUF_SIZE() - */ -#define getSn_TXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_TXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_FSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_FSR. - */ -uint16_t getSn_TX_FSR(uint8_t sn); - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_RD. - */ -#define getSn_TX_RD(sn) \ - ((WIZCHIP_READ(Sn_TX_RD(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_RD(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)txwr Value to set @ref Sn_TX_WR - * @sa GetSn_TX_WR() - */ -#define setSn_TX_WR(sn, txwr) { \ - WIZCHIP_WRITE(Sn_TX_WR(sn), (uint8_t)(txwr>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_TX_WR(sn),1), (uint8_t) txwr); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_WR. - * @sa setSn_TX_WR() - */ -#define getSn_TX_WR(sn) \ - ((WIZCHIP_READ(Sn_TX_WR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_WR(sn),1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_RSR. - */ -uint16_t getSn_RX_RSR(uint8_t sn); - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)rxrd Value to set @ref Sn_RX_RD - * @sa getSn_RX_RD() - */ -#define setSn_RX_RD(sn, rxrd) { \ - WIZCHIP_WRITE(Sn_RX_RD(sn), (uint8_t)(rxrd>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_RX_RD(sn),1), (uint8_t) rxrd); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @regurn uint16_t. Value of @ref Sn_RX_RD. - * @sa setSn_RX_RD() - */ -#define getSn_RX_RD(sn) \ - ((WIZCHIP_READ(Sn_RX_RD(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_RD(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_WR. - */ -#define getSn_RX_WR(sn) \ - ((WIZCHIP_READ(Sn_RX_WR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_WR(sn),1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)frag Value to set @ref Sn_FRAG - * @sa getSn_FRAD() - */ -#define setSn_FRAG(sn, frag) { \ - WIZCHIP_WRITE(Sn_FRAG(sn), (uint8_t)(frag >>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1), (uint8_t) frag); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_FRAG. - * @sa setSn_FRAG() - */ -#define getSn_FRAG(sn) \ - ((WIZCHIP_READ(Sn_FRAG(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)kpalvt Value to set @ref Sn_KPALVTR - * @sa getSn_KPALVTR() - */ -#define setSn_KPALVTR(sn, kpalvt) \ - WIZCHIP_WRITE(Sn_KPALVTR(sn), kpalvt) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_KPALVTR. - * @sa setSn_KPALVTR() - */ -#define getSn_KPALVTR(sn) \ - WIZCHIP_READ(Sn_KPALVTR(sn)) - -////////////////////////////////////// - -///////////////////////////////////// -// Sn_TXBUF & Sn_RXBUF IO function // -///////////////////////////////////// -/** - * @brief Gets the max buffer size of socket sn passed as parameter. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n RX max buffer size. - */ -#define getSn_RxMAX(sn) \ - (getSn_RXBUF_SIZE(sn) << 10) - -/** - * @brief Gets the max buffer size of socket sn passed as parameters. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n TX max buffer size. - */ -//uint16_t getSn_TxMAX(uint8_t sn); -#define getSn_TxMAX(sn) \ - (getSn_TXBUF_SIZE(sn) << 10) - -/** - * @ingroup Basic_IO_function - * @brief It copies data to internal TX memory - * - * @details This function reads the Tx write pointer register and after that, - * it copies the wizdata(pointer buffer) of the length of len(variable) bytes to internal TX memory - * and updates the Tx write pointer register. - * This function is being called by send() and sendto() function also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to write data - * @param len Data length - * @sa wiz_recv_data() - */ -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It copies data to your buffer from internal RX memory - * - * @details This function read the Rx read pointer register and after that, - * it copies the received data from internal RX memory - * to wizdata(pointer variable) of the length of len(variable) bytes. - * This function is being called by recv() also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to read data - * @param len Data length - * @sa wiz_send_data() - */ -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It discard the received data in RX memory. - * @details It discards the data of the length of len(variable) bytes in internal RX memory. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param len Data length - */ -void wiz_recv_ignore(uint8_t sn, uint16_t len); - -#endif // _W5500_H_ diff --git a/drivers/wiznet5k/ethernet/wizchip_conf.c b/drivers/wiznet5k/ethernet/wizchip_conf.c deleted file mode 100644 index c7a2f50f04..0000000000 --- a/drivers/wiznet5k/ethernet/wizchip_conf.c +++ /dev/null @@ -1,662 +0,0 @@ -//****************************************************************************/ -//! -//! \file wizchip_conf.c -//! \brief WIZCHIP Config Header File. -//! \version 1.0.1 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.1 Refer to M20140501 -//! 1. Explicit type casting in wizchip_bus_readbyte() & wizchip_bus_writebyte() -// Issued by Mathias ClauBen. -//! uint32_t type converts into ptrdiff_t first. And then recoverting it into uint8_t* -//! For remove the warning when pointer type size is not 32bit. -//! If ptrdiff_t doesn't support in your complier, You should must replace ptrdiff_t into your suitable pointer type. -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//*****************************************************************************/ -//A20140501 : for use the type - ptrdiff_t -#include -// - -#include "wizchip_conf.h" -#include "socket.h" - -/** - * @brief Default function to enable interrupt. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cris_enter(void) {}; -/** - * @brief Default function to disable interrupt. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cris_exit(void) {}; -/** - * @brief Default function to select chip. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cs_select(void) {}; -/** - * @brief Default function to deselect chip. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cs_deselect(void) {}; -/** - * @brief Default function to read in direct or indirect interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ - //M20140501 : Explict pointer type casting -//uint8_t wizchip_bus_readbyte(uint32_t AddrSel) { return * ((volatile uint8_t *) AddrSel); }; -uint8_t wizchip_bus_readbyte(uint32_t AddrSel) { return * ((volatile uint8_t *)((ptrdiff_t) AddrSel)); }; -/** - * @brief Default function to write in direct or indirect interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ - -//M20140501 : Explict pointer type casting -//void wizchip_bus_writebyte(uint32_t AddrSel, uint8_t wb) { *((volatile uint8_t*) AddrSel) = wb; }; -void wizchip_bus_writebyte(uint32_t AddrSel, uint8_t wb) { *((volatile uint8_t*)((ptrdiff_t)AddrSel)) = wb; }; - -/** - * @brief Default function to read in SPI interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_spi_readbytes(uint8_t *buf, uint32_t len) {} -/** - * @brief Default function to write in SPI interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_spi_writebytes(const uint8_t *buf, uint32_t len) {} - -/** - * @\ref _WIZCHIP instance - */ -_WIZCHIP WIZCHIP = - { - .id = _WIZCHIP_ID_, - .if_mode = _WIZCHIP_IO_MODE_, - .CRIS._enter = wizchip_cris_enter, - .CRIS._exit = wizchip_cris_exit, - .CS._select = wizchip_cs_select, - .CS._deselect = wizchip_cs_deselect, - .IF.BUS._read_byte = wizchip_bus_readbyte, - .IF.BUS._write_byte = wizchip_bus_writebyte -// .IF.SPI._read_byte = wizchip_spi_readbyte, -// .IF.SPI._write_byte = wizchip_spi_writebyte - }; - -#if _WIZCHIP_ == 5200 // for W5200 ARP errata -static uint8_t _SUBN_[4]; // subnet -#endif -static uint8_t _DNS_[4]; // DNS server ip address -static dhcp_mode _DHCP_; // DHCP mode - -void reg_wizchip_cris_cbfunc(void(*cris_en)(void), void(*cris_ex)(void)) -{ - if(!cris_en || !cris_ex) - { - WIZCHIP.CRIS._enter = wizchip_cris_enter; - WIZCHIP.CRIS._exit = wizchip_cris_exit; - } - else - { - WIZCHIP.CRIS._enter = cris_en; - WIZCHIP.CRIS._exit = cris_ex; - } -} - -void reg_wizchip_cs_cbfunc(void(*cs_sel)(void), void(*cs_desel)(void)) -{ - if(!cs_sel || !cs_desel) - { - WIZCHIP.CS._select = wizchip_cs_select; - WIZCHIP.CS._deselect = wizchip_cs_deselect; - } - else - { - WIZCHIP.CS._select = cs_sel; - WIZCHIP.CS._deselect = cs_desel; - } -} - -void reg_wizchip_bus_cbfunc(uint8_t(*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, uint8_t wb)) -{ - while(!(WIZCHIP.if_mode & _WIZCHIP_IO_MODE_BUS_)); - - if(!bus_rb || !bus_wb) - { - WIZCHIP.IF.BUS._read_byte = wizchip_bus_readbyte; - WIZCHIP.IF.BUS._write_byte = wizchip_bus_writebyte; - } - else - { - WIZCHIP.IF.BUS._read_byte = bus_rb; - WIZCHIP.IF.BUS._write_byte = bus_wb; - } -} - -void reg_wizchip_spi_cbfunc(void (*spi_rb)(uint8_t *, uint32_t), void (*spi_wb)(const uint8_t *, uint32_t)) -{ - while(!(WIZCHIP.if_mode & _WIZCHIP_IO_MODE_SPI_)); - - if(!spi_rb || !spi_wb) - { - WIZCHIP.IF.SPI._read_bytes = wizchip_spi_readbytes; - WIZCHIP.IF.SPI._write_bytes = wizchip_spi_writebytes; - } - else - { - WIZCHIP.IF.SPI._read_bytes = spi_rb; - WIZCHIP.IF.SPI._write_bytes = spi_wb; - } -} - -int8_t ctlwizchip(ctlwizchip_type cwtype, void* arg) -{ - uint8_t tmp = 0; - uint8_t* ptmp[2] = {0,0}; - switch(cwtype) - { - case CW_RESET_WIZCHIP: - wizchip_sw_reset(); - break; - case CW_INIT_WIZCHIP: - if(arg != 0) - { - ptmp[0] = (uint8_t*)arg; - ptmp[1] = ptmp[0] + _WIZCHIP_SOCK_NUM_; - } - return wizchip_init(ptmp[0], ptmp[1]); - case CW_CLR_INTERRUPT: - wizchip_clrinterrupt(*((intr_kind*)arg)); - break; - case CW_GET_INTERRUPT: - *((intr_kind*)arg) = wizchip_getinterrupt(); - break; - case CW_SET_INTRMASK: - wizchip_setinterruptmask(*((intr_kind*)arg)); - break; - case CW_GET_INTRMASK: - *((intr_kind*)arg) = wizchip_getinterruptmask(); - break; - #if _WIZCHIP_ > 5100 - case CW_SET_INTRTIME: - setINTLEVEL(*(uint16_t*)arg); - break; - case CW_GET_INTRTIME: - *(uint16_t*)arg = getINTLEVEL(); - break; - #endif - case CW_GET_ID: - ((uint8_t*)arg)[0] = WIZCHIP.id[0]; - ((uint8_t*)arg)[1] = WIZCHIP.id[1]; - ((uint8_t*)arg)[2] = WIZCHIP.id[2]; - ((uint8_t*)arg)[3] = WIZCHIP.id[3]; - ((uint8_t*)arg)[4] = WIZCHIP.id[4]; - ((uint8_t*)arg)[5] = 0; - break; - #if _WIZCHIP_ == 5500 - case CW_RESET_PHY: - wizphy_reset(); - break; - case CW_SET_PHYCONF: - wizphy_setphyconf((wiz_PhyConf*)arg); - break; - case CW_GET_PHYCONF: - wizphy_getphyconf((wiz_PhyConf*)arg); - break; - case CW_GET_PHYSTATUS: - break; - case CW_SET_PHYPOWMODE: - return wizphy_setphypmode(*(uint8_t*)arg); - #endif - case CW_GET_PHYPOWMODE: - tmp = wizphy_getphypmode(); - if((int8_t)tmp == -1) return -1; - *(uint8_t*)arg = tmp; - break; - case CW_GET_PHYLINK: - tmp = wizphy_getphylink(); - if((int8_t)tmp == -1) return -1; - *(uint8_t*)arg = tmp; - break; - default: - return -1; - } - return 0; -} - - -int8_t ctlnetwork(ctlnetwork_type cntype, void* arg) -{ - - switch(cntype) - { - case CN_SET_NETINFO: - wizchip_setnetinfo((wiz_NetInfo*)arg); - break; - case CN_GET_NETINFO: - wizchip_getnetinfo((wiz_NetInfo*)arg); - break; - case CN_SET_NETMODE: - return wizchip_setnetmode(*(netmode_type*)arg); - case CN_GET_NETMODE: - *(netmode_type*)arg = wizchip_getnetmode(); - break; - case CN_SET_TIMEOUT: - wizchip_settimeout((wiz_NetTimeout*)arg); - break; - case CN_GET_TIMEOUT: - wizchip_gettimeout((wiz_NetTimeout*)arg); - break; - default: - return -1; - } - return 0; -} - -void wizchip_sw_reset(void) -{ - uint8_t gw[4], sn[4], sip[4]; - uint8_t mac[6]; - getSHAR(mac); - getGAR(gw); getSUBR(sn); getSIPR(sip); - setMR(MR_RST); - getMR(); // for delay - setSHAR(mac); - setGAR(gw); - setSUBR(sn); - setSIPR(sip); -} - -int8_t wizchip_init(uint8_t* txsize, uint8_t* rxsize) -{ - int8_t i; - int8_t tmp = 0; - wizchip_sw_reset(); - if(txsize) - { - tmp = 0; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - tmp += txsize[i]; - if(tmp > 16) return -1; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - setSn_TXBUF_SIZE(i, txsize[i]); - } - if(rxsize) - { - tmp = 0; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - tmp += rxsize[i]; - if(tmp > 16) return -1; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - setSn_RXBUF_SIZE(i, rxsize[i]); - } - - WIZCHIP_EXPORT(socket_reset)(); - - return 0; -} - -void wizchip_clrinterrupt(intr_kind intr) -{ - uint8_t ir = (uint8_t)intr; - uint8_t sir = (uint8_t)((uint16_t)intr >> 8); -#if _WIZCHIP_ < 5500 - ir |= (1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - ir |= (1 << 6); -#endif - -#if _WIZCHIP_ < 5200 - sir &= 0x0F; -#endif - -#if _WIZCHIP_ == 5100 - ir |= sir; - setIR(ir); -#else - setIR(ir); - setSIR(sir); -#endif -} - -intr_kind wizchip_getinterrupt(void) -{ - uint8_t ir = 0; - uint8_t sir = 0; - uint16_t ret = 0; -#if _WIZCHIP_ == 5100 - ir = getIR(); - sir = ir 0x0F; -#else - ir = getIR(); - sir = getSIR(); -#endif - -#if _WIZCHIP_ < 5500 - ir &= ~(1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - ir &= ~(1 << 6); -#endif - ret = sir; - ret = (ret << 8) + ir; - return (intr_kind)ret; -} - -void wizchip_setinterruptmask(intr_kind intr) -{ - uint8_t imr = (uint8_t)intr; - uint8_t simr = (uint8_t)((uint16_t)intr >> 8); -#if _WIZCHIP_ < 5500 - imr &= ~(1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - imr &= ~(1 << 6); -#endif - -#if _WIZCHIP_ < 5200 - simr &= 0x0F; -#endif - -#if _WIZCHIP_ == 5100 - imr |= simr; - setIMR(imr); -#else - setIMR(imr); - setSIMR(simr); -#endif -} - -intr_kind wizchip_getinterruptmask(void) -{ - uint8_t imr = 0; - uint8_t simr = 0; - uint16_t ret = 0; -#if _WIZCHIP_ == 5100 - imr = getIMR(); - simr = imr 0x0F; -#else - imr = getIMR(); - simr = getSIMR(); -#endif - -#if _WIZCHIP_ < 5500 - imr &= ~(1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - imr &= ~(1 << 6); // IK_DEST_UNREACH -#endif - ret = simr; - ret = (ret << 8) + imr; - return (intr_kind)ret; -} - -int8_t wizphy_getphylink(void) -{ - int8_t tmp; -#if _WIZCHIP_ == 5200 - if(getPHYSTATUS() & PHYSTATUS_LINK) - tmp = PHY_LINK_ON; - else - tmp = PHY_LINK_OFF; -#elif _WIZCHIP_ == 5500 - if(getPHYCFGR() & PHYCFGR_LNK_ON) - tmp = PHY_LINK_ON; - else - tmp = PHY_LINK_OFF; -#else - tmp = -1; -#endif - return tmp; -} - -#if _WIZCHIP_ > 5100 - -int8_t wizphy_getphypmode(void) -{ - int8_t tmp = 0; - #if _WIZCHIP_ == 5200 - if(getPHYSTATUS() & PHYSTATUS_POWERDOWN) - tmp = PHY_POWER_DOWN; - else - tmp = PHY_POWER_NORM; - #elif _WIZCHIP_ == 5500 - if(getPHYCFGR() & PHYCFGR_OPMDC_PDOWN) - tmp = PHY_POWER_DOWN; - else - tmp = PHY_POWER_NORM; - #else - tmp = -1; - #endif - return tmp; -} -#endif - -#if _WIZCHIP_ == 5500 -void wizphy_reset(void) -{ - uint8_t tmp = getPHYCFGR(); - tmp &= PHYCFGR_RST; - setPHYCFGR(tmp); - tmp = getPHYCFGR(); - tmp |= ~PHYCFGR_RST; - setPHYCFGR(tmp); -} - -void wizphy_setphyconf(wiz_PhyConf* phyconf) -{ - uint8_t tmp = 0; - if(phyconf->by == PHY_CONFBY_SW) - tmp |= PHYCFGR_OPMD; - else - tmp &= ~PHYCFGR_OPMD; - if(phyconf->mode == PHY_MODE_AUTONEGO) - tmp |= PHYCFGR_OPMDC_ALLA; - else - { - if(phyconf->duplex == PHY_DUPLEX_FULL) - { - if(phyconf->speed == PHY_SPEED_100) - tmp |= PHYCFGR_OPMDC_100F; - else - tmp |= PHYCFGR_OPMDC_10F; - } - else - { - if(phyconf->speed == PHY_SPEED_100) - tmp |= PHYCFGR_OPMDC_100H; - else - tmp |= PHYCFGR_OPMDC_10H; - } - } - setPHYCFGR(tmp); - wizphy_reset(); -} - -void wizphy_getphyconf(wiz_PhyConf* phyconf) -{ - uint8_t tmp = 0; - tmp = getPHYCFGR(); - phyconf->by = (tmp & PHYCFGR_OPMD) ? PHY_CONFBY_SW : PHY_CONFBY_HW; - switch(tmp & PHYCFGR_OPMDC_ALLA) - { - case PHYCFGR_OPMDC_ALLA: - case PHYCFGR_OPMDC_100FA: - phyconf->mode = PHY_MODE_AUTONEGO; - break; - default: - phyconf->mode = PHY_MODE_MANUAL; - break; - } - switch(tmp & PHYCFGR_OPMDC_ALLA) - { - case PHYCFGR_OPMDC_100FA: - case PHYCFGR_OPMDC_100F: - case PHYCFGR_OPMDC_100H: - phyconf->speed = PHY_SPEED_100; - break; - default: - phyconf->speed = PHY_SPEED_10; - break; - } - switch(tmp & PHYCFGR_OPMDC_ALLA) - { - case PHYCFGR_OPMDC_100FA: - case PHYCFGR_OPMDC_100F: - case PHYCFGR_OPMDC_10F: - phyconf->duplex = PHY_DUPLEX_FULL; - break; - default: - phyconf->duplex = PHY_DUPLEX_HALF; - break; - } -} - -void wizphy_getphystat(wiz_PhyConf* phyconf) -{ - uint8_t tmp = getPHYCFGR(); - phyconf->duplex = (tmp & PHYCFGR_DPX_FULL) ? PHY_DUPLEX_FULL : PHY_DUPLEX_HALF; - phyconf->speed = (tmp & PHYCFGR_SPD_100) ? PHY_SPEED_100 : PHY_SPEED_10; -} - -int8_t wizphy_setphypmode(uint8_t pmode) -{ - uint8_t tmp = 0; - tmp = getPHYCFGR(); - if((tmp & PHYCFGR_OPMD)== 0) return -1; - tmp &= ~PHYCFGR_OPMDC_ALLA; - if( pmode == PHY_POWER_DOWN) - tmp |= PHYCFGR_OPMDC_PDOWN; - else - tmp |= PHYCFGR_OPMDC_ALLA; - setPHYCFGR(tmp); - wizphy_reset(); - tmp = getPHYCFGR(); - if( pmode == PHY_POWER_DOWN) - { - if(tmp & PHYCFGR_OPMDC_PDOWN) return 0; - } - else - { - if(tmp & PHYCFGR_OPMDC_ALLA) return 0; - } - return -1; -} -#endif - - -void wizchip_setnetinfo(wiz_NetInfo* pnetinfo) -{ - setSHAR(pnetinfo->mac); - setGAR(pnetinfo->gw); - setSUBR(pnetinfo->sn); - setSIPR(pnetinfo->ip); -#if _WIZCHIP_ == 5200 // for W5200 ARP errata - _SUBN_[0] = pnetinfo->sn[0]; - _SUBN_[1] = pnetinfo->sn[1]; - _SUBN_[2] = pnetinfo->sn[2]; - _SUBN_[3] = pnetinfo->sn[3]; -#endif - _DNS_[0] = pnetinfo->dns[0]; - _DNS_[1] = pnetinfo->dns[1]; - _DNS_[2] = pnetinfo->dns[2]; - _DNS_[3] = pnetinfo->dns[3]; - _DHCP_ = pnetinfo->dhcp; -} - -void wizchip_getnetinfo(wiz_NetInfo* pnetinfo) -{ - getSHAR(pnetinfo->mac); - getGAR(pnetinfo->gw); - getSUBR(pnetinfo->sn); - getSIPR(pnetinfo->ip); -#if _WIZCHIP_ == 5200 // for W5200 ARP errata - pnetinfo->sn[0] = _SUBN_[0]; - pnetinfo->sn[1] = _SUBN_[1]; - pnetinfo->sn[2] = _SUBN_[2]; - pnetinfo->sn[3] = _SUBN_[3]; -#endif - pnetinfo->dns[0]= _DNS_[0]; - pnetinfo->dns[1]= _DNS_[1]; - pnetinfo->dns[2]= _DNS_[2]; - pnetinfo->dns[3]= _DNS_[3]; - pnetinfo->dhcp = _DHCP_; -} - -#if _WIZCHIP_ == 5200 // for W5200 ARP errata -uint8_t *wizchip_getsubn(void) { - return _SUBN_; -} -#endif - -int8_t wizchip_setnetmode(netmode_type netmode) -{ - uint8_t tmp = 0; -#if _WIZCHIP_ != 5500 - if(netmode & ~(NM_WAKEONLAN | NM_PPPOE | NM_PINGBLOCK)) return -1; -#else - if(netmode & ~(NM_WAKEONLAN | NM_PPPOE | NM_PINGBLOCK | NM_FORCEARP)) return -1; -#endif - tmp = getMR(); - tmp |= (uint8_t)netmode; - setMR(tmp); - return 0; -} - -netmode_type wizchip_getnetmode(void) -{ - return (netmode_type) getMR(); -} - -void wizchip_settimeout(wiz_NetTimeout* nettime) -{ - setRCR(nettime->retry_cnt); - setRTR(nettime->time_100us); -} - -void wizchip_gettimeout(wiz_NetTimeout* nettime) -{ - nettime->retry_cnt = getRCR(); - nettime->time_100us = getRTR(); -} diff --git a/drivers/wiznet5k/ethernet/wizchip_conf.h b/drivers/wiznet5k/ethernet/wizchip_conf.h deleted file mode 100644 index 509ba0668a..0000000000 --- a/drivers/wiznet5k/ethernet/wizchip_conf.h +++ /dev/null @@ -1,554 +0,0 @@ -//***************************************************************************** -// -//! \file wizchip_conf.h -//! \brief WIZCHIP Config Header File. -//! \version 1.0.0 -//! \date 2013/10/21 -//! \par Revision history -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -/** - * @defgroup extra_functions 2. WIZnet Extra Functions - * - * @brief These functions is optional function. It could be replaced at WIZCHIP I/O function because they were made by WIZCHIP I/O functions. - * @details There are functions of configuring WIZCHIP, network, interrupt, phy, network information and timer. \n - * - */ - -#ifndef _WIZCHIP_CONF_H_ -#define _WIZCHIP_CONF_H_ - -#include -/** - * @brief Select WIZCHIP. - * @todo You should select one, \b 5100, \b 5200 ,\b 5500 or etc. \n\n - * ex> #define \_WIZCHIP_ 5500 - */ -#ifndef _WIZCHIP_ -#define _WIZCHIP_ 5200 // 5100, 5200, 5500 -#endif - -#define _WIZCHIP_IO_MODE_NONE_ 0x0000 -#define _WIZCHIP_IO_MODE_BUS_ 0x0100 /**< Bus interface mode */ -#define _WIZCHIP_IO_MODE_SPI_ 0x0200 /**< SPI interface mode */ -//#define _WIZCHIP_IO_MODE_IIC_ 0x0400 -//#define _WIZCHIP_IO_MODE_SDIO_ 0x0800 -// Add to -// - -#define _WIZCHIP_IO_MODE_BUS_DIR_ (_WIZCHIP_IO_MODE_BUS_ + 1) /**< BUS interface mode for direct */ -#define _WIZCHIP_IO_MODE_BUS_INDIR_ (_WIZCHIP_IO_MODE_BUS_ + 2) /**< BUS interface mode for indirect */ - -#define _WIZCHIP_IO_MODE_SPI_VDM_ (_WIZCHIP_IO_MODE_SPI_ + 1) /**< SPI interface mode for variable length data*/ -#define _WIZCHIP_IO_MODE_SPI_FDM_ (_WIZCHIP_IO_MODE_SPI_ + 2) /**< SPI interface mode for fixed length data mode*/ - - -#if (_WIZCHIP_ == 5100) - #define _WIZCHIP_ID_ "W5100\0" -/** - * @brief Define interface mode. - * @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ , @ref \_WIZCHIP_IO_MODE_BUS_DIR_ or @ref \_WIZCHIP_IO_MODE_BUS_INDIR_ - */ - -// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_DIR_ -// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_ - #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_ - -#elif (_WIZCHIP_ == 5200) - #define _WIZCHIP_ID_ "W5200\0" -/** - * @brief Define interface mode. - * @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ or @ref \_WIZCHIP_IO_MODE_BUS_INDIR_ - */ -// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_ - #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_ - #include "w5200/w5200.h" -#elif (_WIZCHIP_ == 5500) - #define _WIZCHIP_ID_ "W5500\0" - -/** - * @brief Define interface mode. \n - * @todo Should select interface mode as chip. - * - @ref \_WIZCHIP_IO_MODE_SPI_ \n - * -@ref \_WIZCHIP_IO_MODE_SPI_VDM_ : Valid only in @ref \_WIZCHIP_ == 5500 \n - * -@ref \_WIZCHIP_IO_MODE_SPI_FDM_ : Valid only in @ref \_WIZCHIP_ == 5500 \n - * - @ref \_WIZCHIP_IO_MODE_BUS_ \n - * - @ref \_WIZCHIP_IO_MODE_BUS_DIR_ \n - * - @ref \_WIZCHIP_IO_MODE_BUS_INDIR_ \n - * - Others will be defined in future. \n\n - * ex> #define \_WIZCHIP_IO_MODE_ \_WIZCHIP_IO_MODE_SPI_VDM_ - * - */ - //#define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_FDM_ - #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_VDM_ - #include "w5500/w5500.h" -#else - #error "Unknown defined _WIZCHIP_. You should define one of 5100, 5200, and 5500 !!!" -#endif - -#ifndef _WIZCHIP_IO_MODE_ - #error "Undefined _WIZCHIP_IO_MODE_. You should define it !!!" -#endif - -/** - * @brief Define I/O base address when BUS IF mode. - * @todo Should re-define it to fit your system when BUS IF Mode (@ref \_WIZCHIP_IO_MODE_BUS_, - * @ref \_WIZCHIP_IO_MODE_BUS_DIR_, @ref \_WIZCHIP_IO_MODE_BUS_INDIR_). \n\n - * ex> #define \_WIZCHIP_IO_BASE_ 0x00008000 - */ -#define _WIZCHIP_IO_BASE_ 0x00000000 // - -#if _WIZCHIP_IO_MODE_ & _WIZCHIP_IO_MODE_BUS_ - #ifndef _WIZCHIP_IO_BASE_ - #error "You should be define _WIZCHIP_IO_BASE to fit your system memory map." - #endif -#endif - -#if _WIZCHIP_ > 5100 - #define _WIZCHIP_SOCK_NUM_ 8 ///< The count of independant socket of @b WIZCHIP -#else - #define _WIZCHIP_SOCK_NUM_ 4 ///< The count of independant socket of @b WIZCHIP -#endif - - -/******************************************************** -* WIZCHIP BASIC IF functions for SPI, SDIO, I2C , ETC. -*********************************************************/ -/** - * @ingroup DATA_TYPE - * @brief The set of callback functions for W5500:@ref WIZCHIP_IO_Functions W5200:@ref WIZCHIP_IO_Functions_W5200 - */ -typedef struct __WIZCHIP -{ - uint16_t if_mode; ///< host interface mode - uint8_t id[6]; ///< @b WIZCHIP ID such as @b 5100, @b 5200, @b 5500, and so on. - /** - * The set of critical section callback func. - */ - struct _CRIS - { - void (*_enter) (void); ///< crtical section enter - void (*_exit) (void); ///< critial section exit - }CRIS; - /** - * The set of @ref\_WIZCHIP_ select control callback func. - */ - struct _CS - { - void (*_select) (void); ///< @ref \_WIZCHIP_ selected - void (*_deselect)(void); ///< @ref \_WIZCHIP_ deselected - }CS; - /** - * The set of interface IO callback func. - */ - union _IF - { - /** - * For BUS interface IO - */ - struct - { - uint8_t (*_read_byte) (uint32_t AddrSel); - void (*_write_byte) (uint32_t AddrSel, uint8_t wb); - }BUS; - /** - * For SPI interface IO - */ - struct - { - void (*_read_bytes) (uint8_t *buf, uint32_t len); - void (*_write_bytes) (const uint8_t *buf, uint32_t len); - }SPI; - // To be added - // - }IF; -}_WIZCHIP; - -extern _WIZCHIP WIZCHIP; - -/** - * @ingroup DATA_TYPE - * WIZCHIP control type enumration used in @ref ctlwizchip(). - */ -typedef enum -{ - CW_RESET_WIZCHIP, ///< Resets WIZCHIP by softly - CW_INIT_WIZCHIP, ///< Inializes to WIZCHIP with SOCKET buffer size 2 or 1 dimension array typed uint8_t. - CW_GET_INTERRUPT, ///< Get Interrupt status of WIZCHIP - CW_CLR_INTERRUPT, ///< Clears interrupt - CW_SET_INTRMASK, ///< Masks interrupt - CW_GET_INTRMASK, ///< Get interrupt mask - CW_SET_INTRTIME, ///< Set interval time between the current and next interrupt. - CW_GET_INTRTIME, ///< Set interval time between the current and next interrupt. - CW_GET_ID, ///< Gets WIZCHIP name. - -#if _WIZCHIP_ == 5500 - CW_RESET_PHY, ///< Resets internal PHY. Valid Only W5000 - CW_SET_PHYCONF, ///< When PHY configured by interal register, PHY operation mode (Manual/Auto, 10/100, Half/Full). Valid Only W5000 - CW_GET_PHYCONF, ///< Get PHY operation mode in interal register. Valid Only W5000 - CW_GET_PHYSTATUS, ///< Get real PHY status on operating. Valid Only W5000 - CW_SET_PHYPOWMODE, ///< Set PHY power mode as noraml and down when PHYSTATUS.OPMD == 1. Valid Only W5000 -#endif - CW_GET_PHYPOWMODE, ///< Get PHY Power mode as down or normal - CW_GET_PHYLINK ///< Get PHY Link status -}ctlwizchip_type; - -/** - * @ingroup DATA_TYPE - * Network control type enumration used in @ref ctlnetwork(). - */ -typedef enum -{ - CN_SET_NETINFO, ///< Set Network with @ref wiz_NetInfo - CN_GET_NETINFO, ///< Get Network with @ref wiz_NetInfo - CN_SET_NETMODE, ///< Set network mode as WOL, PPPoE, Ping Block, and Force ARP mode - CN_GET_NETMODE, ///< Get network mode as WOL, PPPoE, Ping Block, and Force ARP mode - CN_SET_TIMEOUT, ///< Set network timeout as retry count and time. - CN_GET_TIMEOUT, ///< Get network timeout as retry count and time. -}ctlnetwork_type; - -/** - * @ingroup DATA_TYPE - * Interrupt kind when CW_SET_INTRRUPT, CW_GET_INTERRUPT, CW_SET_INTRMASK - * and CW_GET_INTRMASK is used in @ref ctlnetwork(). - * It can be used with OR operation. - */ -typedef enum -{ -#if _WIZCHIP_ > 5200 - IK_WOL = (1 << 4), ///< Wake On Lan by receiving the magic packet. Valid in W500. -#endif - - IK_PPPOE_TERMINATED = (1 << 5), ///< PPPoE Disconnected - -#if _WIZCHIP_ != 5200 - IK_DEST_UNREACH = (1 << 6), ///< Destination IP & Port Unreable, No use in W5200 -#endif - - IK_IP_CONFLICT = (1 << 7), ///< IP conflict occurred - - IK_SOCK_0 = (1 << 8), ///< Socket 0 interrupt - IK_SOCK_1 = (1 << 9), ///< Socket 1 interrupt - IK_SOCK_2 = (1 << 10), ///< Socket 2 interrupt - IK_SOCK_3 = (1 << 11), ///< Socket 3 interrupt -#if _WIZCHIP_ > 5100 - IK_SOCK_4 = (1 << 12), ///< Socket 4 interrupt, No use in 5100 - IK_SOCK_5 = (1 << 13), ///< Socket 5 interrupt, No use in 5100 - IK_SOCK_6 = (1 << 14), ///< Socket 6 interrupt, No use in 5100 - IK_SOCK_7 = (1 << 15), ///< Socket 7 interrupt, No use in 5100 -#endif - -#if _WIZCHIP_ > 5100 - IK_SOCK_ALL = (0xFF << 8) ///< All Socket interrpt -#else - IK_SOCK_ALL = (0x0F << 8) ///< All Socket interrpt -#endif -}intr_kind; - -#define PHY_CONFBY_HW 0 ///< Configured PHY operation mode by HW pin -#define PHY_CONFBY_SW 1 ///< Configured PHY operation mode by SW register -#define PHY_MODE_MANUAL 0 ///< Configured PHY operation mode with user setting. -#define PHY_MODE_AUTONEGO 1 ///< Configured PHY operation mode with auto-negotiation -#define PHY_SPEED_10 0 ///< Link Speed 10 -#define PHY_SPEED_100 1 ///< Link Speed 100 -#define PHY_DUPLEX_HALF 0 ///< Link Half-Duplex -#define PHY_DUPLEX_FULL 1 ///< Link Full-Duplex -#define PHY_LINK_OFF 0 ///< Link Off -#define PHY_LINK_ON 1 ///< Link On -#define PHY_POWER_NORM 0 ///< PHY power normal mode -#define PHY_POWER_DOWN 1 ///< PHY power down mode - - -#if _WIZCHIP_ == 5500 -/** - * @ingroup DATA_TYPE - * It configures PHY configuration when CW_SET PHYCONF or CW_GET_PHYCONF in W5500, - * and it indicates the real PHY status configured by HW or SW in all WIZCHIP. \n - * Valid only in W5500. - */ -typedef struct wiz_PhyConf_t -{ - uint8_t by; ///< set by @ref PHY_CONFBY_HW or @ref PHY_CONFBY_SW - uint8_t mode; ///< set by @ref PHY_MODE_MANUAL or @ref PHY_MODE_AUTONEGO - uint8_t speed; ///< set by @ref PHY_SPEED_10 or @ref PHY_SPEED_100 - uint8_t duplex; ///< set by @ref PHY_DUPLEX_HALF @ref PHY_DUPLEX_FULL - //uint8_t power; ///< set by @ref PHY_POWER_NORM or @ref PHY_POWER_DOWN - //uint8_t link; ///< Valid only in CW_GET_PHYSTATUS. set by @ref PHY_LINK_ON or PHY_DUPLEX_OFF - }wiz_PhyConf; -#endif - -/** - * @ingroup DATA_TYPE - * It used in setting dhcp_mode of @ref wiz_NetInfo. - */ -typedef enum -{ - NETINFO_STATIC = 1, ///< Static IP configuration by manually. - NETINFO_DHCP ///< Dynamic IP configruation from a DHCP sever -}dhcp_mode; - -/** - * @ingroup DATA_TYPE - * Network Information for WIZCHIP - */ -typedef struct wiz_NetInfo_t -{ - uint8_t mac[6]; ///< Source Mac Address - uint8_t ip[4]; ///< Source IP Address - uint8_t sn[4]; ///< Subnet Mask - uint8_t gw[4]; ///< Gateway IP Address - uint8_t dns[4]; ///< DNS server IP Address - dhcp_mode dhcp; ///< 1 - Static, 2 - DHCP -}wiz_NetInfo; - -/** - * @ingroup DATA_TYPE - * Network mode - */ -typedef enum -{ -#if _WIZCHIP_ == 5500 - NM_FORCEARP = (1<<1), ///< Force to APP send whenever udp data is sent. Valid only in W5500 -#endif - NM_WAKEONLAN = (1<<5), ///< Wake On Lan - NM_PINGBLOCK = (1<<4), ///< Block ping-request - NM_PPPOE = (1<<3), ///< PPPoE mode -}netmode_type; - -/** - * @ingroup DATA_TYPE - * Used in CN_SET_TIMEOUT or CN_GET_TIMEOUT of @ref ctlwizchip() for timeout configruation. - */ -typedef struct wiz_NetTimeout_t -{ - uint8_t retry_cnt; ///< retry count - uint16_t time_100us; ///< time unit 100us -}wiz_NetTimeout; - -/** - *@brief Registers call back function for critical section of I/O functions such as - *\ref WIZCHIP_READ, @ref WIZCHIP_WRITE, @ref WIZCHIP_READ_BUF and @ref WIZCHIP_WRITE_BUF. - *@param cris_en : callback function for critical section enter. - *@param cris_ex : callback function for critical section exit. - *@todo Describe @ref WIZCHIP_CRITICAL_ENTER and @ref WIZCHIP_CRITICAL_EXIT marco or register your functions. - *@note If you do not describe or register, default functions(@ref wizchip_cris_enter & @ref wizchip_cris_exit) is called. - */ -void reg_wizchip_cris_cbfunc(void(*cris_en)(void), void(*cris_ex)(void)); - - -/** - *@brief Registers call back function for WIZCHIP select & deselect. - *@param cs_sel : callback function for WIZCHIP select - *@param cs_desel : callback fucntion for WIZCHIP deselect - *@todo Describe @ref wizchip_cs_select and @ref wizchip_cs_deselect function or register your functions. - *@note If you do not describe or register, null function is called. - */ -void reg_wizchip_cs_cbfunc(void(*cs_sel)(void), void(*cs_desel)(void)); - -/** - *@brief Registers call back function for bus interface. - *@param bus_rb : callback function to read byte data using system bus - *@param bus_wb : callback function to write byte data using system bus - *@todo Describe @ref wizchip_bus_readbyte and @ref wizchip_bus_writebyte function - *or register your functions. - *@note If you do not describe or register, null function is called. - */ -void reg_wizchip_bus_cbfunc(uint8_t (*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, uint8_t wb)); - -/** - *@brief Registers call back function for SPI interface. - *@param spi_rb : callback function to read byte usig SPI - *@param spi_wb : callback function to write byte usig SPI - *@todo Describe \ref wizchip_spi_readbyte and \ref wizchip_spi_writebyte function - *or register your functions. - *@note If you do not describe or register, null function is called. - */ -void reg_wizchip_spi_cbfunc(void (*spi_rb)(uint8_t *, uint32_t), void (*spi_wb)(const uint8_t *, uint32_t)); - -/** - * @ingroup extra_functions - * @brief Controls to the WIZCHIP. - * @details Resets WIZCHIP & internal PHY, Configures PHY mode, Monitor PHY(Link,Speed,Half/Full/Auto), - * controls interrupt & mask and so on. - * @param cwtype : Decides to the control type - * @param arg : arg type is dependent on cwtype. - * @return 0 : Success \n - * -1 : Fail because of invalid \ref ctlwizchip_type or unsupported \ref ctlwizchip_type in WIZCHIP - */ -int8_t ctlwizchip(ctlwizchip_type cwtype, void* arg); - -/** - * @ingroup extra_functions - * @brief Controls to network. - * @details Controls to network environment, mode, timeout and so on. - * @param cntype : Input. Decides to the control type - * @param arg : Inout. arg type is dependent on cntype. - * @return -1 : Fail because of invalid \ref ctlnetwork_type or unsupported \ref ctlnetwork_type in WIZCHIP \n - * 0 : Success - */ -int8_t ctlnetwork(ctlnetwork_type cntype, void* arg); - - -/* - * The following functions are implemented for internal use. - * but You can call these functions for code size reduction instead of ctlwizchip() and ctlnetwork(). - */ - -/** - * @ingroup extra_functions - * @brief Reset WIZCHIP by softly. - */ -void wizchip_sw_reset(void); - -/** - * @ingroup extra_functions - * @brief Initializes WIZCHIP with socket buffer size - * @param txsize Socket tx buffer sizes. If null, initialized the default size 2KB. - * @param rxsize Socket rx buffer sizes. If null, initialized the default size 2KB. - * @return 0 : succcess \n - * -1 : fail. Invalid buffer size - */ -int8_t wizchip_init(uint8_t* txsize, uint8_t* rxsize); - -/** - * @ingroup extra_functions - * @brief Clear Interrupt of WIZCHIP. - * @param intr : @ref intr_kind value operated OR. It can type-cast to uint16_t. - */ -void wizchip_clrinterrupt(intr_kind intr); - -/** - * @ingroup extra_functions - * @brief Get Interrupt of WIZCHIP. - * @return @ref intr_kind value operated OR. It can type-cast to uint16_t. - */ -intr_kind wizchip_getinterrupt(void); - -/** - * @ingroup extra_functions - * @brief Mask or Unmask Interrupt of WIZCHIP. - * @param intr : @ref intr_kind value operated OR. It can type-cast to uint16_t. - */ -void wizchip_setinterruptmask(intr_kind intr); - -/** - * @ingroup extra_functions - * @brief Get Interrupt mask of WIZCHIP. - * @return : The operated OR vaule of @ref intr_kind. It can type-cast to uint16_t. - */ -intr_kind wizchip_getinterruptmask(void); - -#if _WIZCHIP_ > 5100 - int8_t wizphy_getphylink(void); ///< get the link status of phy in WIZCHIP. No use in W5100 - int8_t wizphy_getphypmode(void); ///< get the power mode of PHY in WIZCHIP. No use in W5100 -#endif - -#if _WIZCHIP_ == 5500 - void wizphy_reset(void); ///< Reset phy. Vailid only in W5500 -/** - * @ingroup extra_functions - * @brief Set the phy information for WIZCHIP without power mode - * @param phyconf : @ref wiz_PhyConf - */ - void wizphy_setphyconf(wiz_PhyConf* phyconf); - /** - * @ingroup extra_functions - * @brief Get phy configuration information. - * @param phyconf : @ref wiz_PhyConf - */ - void wizphy_getphyconf(wiz_PhyConf* phyconf); - /** - * @ingroup extra_functions - * @brief Get phy status. - * @param phyconf : @ref wiz_PhyConf - */ - void wizphy_getphystat(wiz_PhyConf* phyconf); - /** - * @ingroup extra_functions - * @brief set the power mode of phy inside WIZCHIP. Refer to @ref PHYCFGR in W5500, @ref PHYSTATUS in W5200 - * @param pmode Settig value of power down mode. - */ - int8_t wizphy_setphypmode(uint8_t pmode); -#endif - -/** -* @ingroup extra_functions - * @brief Set the network information for WIZCHIP - * @param pnetinfo : @ref wizNetInfo - */ -void wizchip_setnetinfo(wiz_NetInfo* pnetinfo); - -/** - * @ingroup extra_functions - * @brief Get the network information for WIZCHIP - * @param pnetinfo : @ref wizNetInfo - */ -void wizchip_getnetinfo(wiz_NetInfo* pnetinfo); - -#if _WIZCHIP_ == 5200 // for W5200 ARP errata -uint8_t *wizchip_getsubn(void); -#endif - -/** - * @ingroup extra_functions - * @brief Set the network mode such WOL, PPPoE, Ping Block, and etc. - * @param pnetinfo Value of network mode. Refer to @ref netmode_type. - */ -int8_t wizchip_setnetmode(netmode_type netmode); - -/** - * @ingroup extra_functions - * @brief Get the network mode such WOL, PPPoE, Ping Block, and etc. - * @return Value of network mode. Refer to @ref netmode_type. - */ -netmode_type wizchip_getnetmode(void); - -/** - * @ingroup extra_functions - * @brief Set retry time value(@ref RTR) and retry count(@ref RCR). - * @details @ref RTR configures the retransmission timeout period and @ref RCR configures the number of time of retransmission. - * @param nettime @ref RTR value and @ref RCR value. Refer to @ref wiz_NetTimeout. - */ -void wizchip_settimeout(wiz_NetTimeout* nettime); - -/** - * @ingroup extra_functions - * @brief Get retry time value(@ref RTR) and retry count(@ref RCR). - * @details @ref RTR configures the retransmission timeout period and @ref RCR configures the number of time of retransmission. - * @param nettime @ref RTR value and @ref RCR value. Refer to @ref wiz_NetTimeout. - */ -void wizchip_gettimeout(wiz_NetTimeout* nettime); - -#endif // _WIZCHIP_CONF_H_ diff --git a/drivers/wiznet5k/internet/dhcp/dhcp.c b/drivers/wiznet5k/internet/dhcp/dhcp.c deleted file mode 100644 index 00f41c3c72..0000000000 --- a/drivers/wiznet5k/internet/dhcp/dhcp.c +++ /dev/null @@ -1,975 +0,0 @@ -//***************************************************************************** -// -//! \file dhcp.c -//! \brief DHCP APIs implement file. -//! \details Processig DHCP protocol as DISCOVER, OFFER, REQUEST, ACK, NACK and DECLINE. -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2018/10/09> Modified by Nick Moore for CircuitPython -//! <2013/11/18> 1st Release -//! <2012/12/20> V1.1.0 -//! 1. Optimize code -//! 2. Add reg_dhcp_cbfunc() -//! 3. Add DHCP_stop() -//! 4. Integrate check_DHCP_state() & DHCP_run() to DHCP_run() -//! 5. Don't care system endian -//! 6. Add comments -//! <2012/12/26> V1.1.1 -//! 1. Modify variable declaration: dhcp_tick_1s is declared volatile for code optimization -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -//#include "Ethernet/socket.h" -//#include "Internet/DHCP/dhcp.h" -#include "../../ethernet/socket.h" -#include "dhcp.h" - -/* If you want to display debug & processing message, Define _DHCP_DEBUG_ in dhcp.h */ - -#ifdef _DHCP_DEBUG_ - #include -#endif - -/* DHCP state machine. */ -#define STATE_DHCP_INIT 0 ///< Initialize -#define STATE_DHCP_DISCOVER 1 ///< send DISCOVER and wait OFFER -#define STATE_DHCP_REQUEST 2 ///< send REQEUST and wait ACK or NACK -#define STATE_DHCP_LEASED 3 ///< ReceiveD ACK and IP leased -#define STATE_DHCP_REREQUEST 4 ///< send REQUEST for maintaining leased IP -#define STATE_DHCP_RELEASE 5 ///< No use -#define STATE_DHCP_STOP 6 ///< Stop processing DHCP - -#define DHCP_FLAGSBROADCAST 0x8000 ///< The broadcast value of flags in @ref RIP_MSG -#define DHCP_FLAGSUNICAST 0x0000 ///< The unicast value of flags in @ref RIP_MSG - -/* DHCP message OP code */ -#define DHCP_BOOTREQUEST 1 ///< Request Message used in op of @ref RIP_MSG -#define DHCP_BOOTREPLY 2 ///< Reply Message used i op of @ref RIP_MSG - -/* DHCP message type */ -#define DHCP_DISCOVER 1 ///< DISCOVER message in OPT of @ref RIP_MSG -#define DHCP_OFFER 2 ///< OFFER message in OPT of @ref RIP_MSG -#define DHCP_REQUEST 3 ///< REQUEST message in OPT of @ref RIP_MSG -#define DHCP_DECLINE 4 ///< DECLINE message in OPT of @ref RIP_MSG -#define DHCP_ACK 5 ///< ACK message in OPT of @ref RIP_MSG -#define DHCP_NAK 6 ///< NACK message in OPT of @ref RIP_MSG -#define DHCP_RELEASE 7 ///< RELEASE message in OPT of @ref RIP_MSG. No use -#define DHCP_INFORM 8 ///< INFORM message in OPT of @ref RIP_MSG. No use - -#define DHCP_HTYPE10MB 1 ///< Used in type of @ref RIP_MSG -#define DHCP_HTYPE100MB 2 ///< Used in type of @ref RIP_MSG - -#define DHCP_HLENETHERNET 6 ///< Used in hlen of @ref RIP_MSG -#define DHCP_HOPS 0 ///< Used in hops of @ref RIP_MSG -#define DHCP_SECS 0 ///< Used in secs of @ref RIP_MSG - -#define INFINITE_LEASETIME 0xffffffff ///< Infinite lease time - -#define OPT_SIZE 312 /// Max OPT size of @ref RIP_MSG -#define RIP_MSG_SIZE (236+OPT_SIZE) /// Max size of @ref RIP_MSG - -/* - * @brief DHCP option and value (cf. RFC1533) - */ -enum -{ - padOption = 0, - subnetMask = 1, - timerOffset = 2, - routersOnSubnet = 3, - timeServer = 4, - nameServer = 5, - dns = 6, - logServer = 7, - cookieServer = 8, - lprServer = 9, - impressServer = 10, - resourceLocationServer = 11, - hostName = 12, - bootFileSize = 13, - meritDumpFile = 14, - domainName = 15, - swapServer = 16, - rootPath = 17, - extentionsPath = 18, - IPforwarding = 19, - nonLocalSourceRouting = 20, - policyFilter = 21, - maxDgramReasmSize = 22, - defaultIPTTL = 23, - pathMTUagingTimeout = 24, - pathMTUplateauTable = 25, - ifMTU = 26, - allSubnetsLocal = 27, - broadcastAddr = 28, - performMaskDiscovery = 29, - maskSupplier = 30, - performRouterDiscovery = 31, - routerSolicitationAddr = 32, - staticRoute = 33, - trailerEncapsulation = 34, - arpCacheTimeout = 35, - ethernetEncapsulation = 36, - tcpDefaultTTL = 37, - tcpKeepaliveInterval = 38, - tcpKeepaliveGarbage = 39, - nisDomainName = 40, - nisServers = 41, - ntpServers = 42, - vendorSpecificInfo = 43, - netBIOSnameServer = 44, - netBIOSdgramDistServer = 45, - netBIOSnodeType = 46, - netBIOSscope = 47, - xFontServer = 48, - xDisplayManager = 49, - dhcpRequestedIPaddr = 50, - dhcpIPaddrLeaseTime = 51, - dhcpOptionOverload = 52, - dhcpMessageType = 53, - dhcpServerIdentifier = 54, - dhcpParamRequest = 55, - dhcpMsg = 56, - dhcpMaxMsgSize = 57, - dhcpT1value = 58, - dhcpT2value = 59, - dhcpClassIdentifier = 60, - dhcpClientIdentifier = 61, - endOption = 255 -}; - -/* - * @brief DHCP message format - */ -typedef struct { - uint8_t op; ///< @ref DHCP_BOOTREQUEST or @ref DHCP_BOOTREPLY - uint8_t htype; ///< @ref DHCP_HTYPE10MB or @ref DHCP_HTYPE100MB - uint8_t hlen; ///< @ref DHCP_HLENETHERNET - uint8_t hops; ///< @ref DHCP_HOPS - uint32_t xid; ///< @ref DHCP_XID This increase one every DHCP transaction. - uint16_t secs; ///< @ref DHCP_SECS - uint16_t flags; ///< @ref DHCP_FLAGSBROADCAST or @ref DHCP_FLAGSUNICAST - uint8_t ciaddr[4]; ///< @ref Request IP to DHCP sever - uint8_t yiaddr[4]; ///< @ref Offered IP from DHCP server - uint8_t siaddr[4]; ///< No use - uint8_t giaddr[4]; ///< No use - uint8_t chaddr[16]; ///< DHCP client 6bytes MAC address. Others is filled to zero - uint8_t sname[64]; ///< No use - uint8_t file[128]; ///< No use - uint8_t OPT[OPT_SIZE]; ///< Option -} RIP_MSG; - - - -uint8_t DHCP_SOCKET; // Socket number for DHCP - -uint8_t DHCP_SIP[4]; // DHCP Server IP address - -// Network information from DHCP Server -uint8_t OLD_allocated_ip[4] = {0, }; // Previous IP address -uint8_t DHCP_allocated_ip[4] = {0, }; // IP address from DHCP -uint8_t DHCP_allocated_gw[4] = {0, }; // Gateway address from DHCP -uint8_t DHCP_allocated_sn[4] = {0, }; // Subnet mask from DHCP -uint8_t DHCP_allocated_dns[4] = {0, }; // DNS address from DHCP - - -int8_t dhcp_state = STATE_DHCP_INIT; // DHCP state -int8_t dhcp_retry_count = 0; - -uint32_t dhcp_lease_time = INFINITE_LEASETIME; -volatile uint32_t dhcp_tick_1s = 0; // unit 1 second -uint32_t dhcp_tick_next = DHCP_WAIT_TIME ; - -uint32_t DHCP_XID; // Any number - -RIP_MSG* pDHCPMSG; // Buffer pointer for DHCP processing - -uint8_t HOST_NAME[] = DCHP_HOST_NAME; - -uint8_t DHCP_CHADDR[6]; // DHCP Client MAC address. - -/* The default callback function */ -void default_ip_assign(void); -void default_ip_update(void); -void default_ip_conflict(void); - -/* Callback handler */ -void (*dhcp_ip_assign)(void) = default_ip_assign; /* handler to be called when the IP address from DHCP server is first assigned */ -void (*dhcp_ip_update)(void) = default_ip_update; /* handler to be called when the IP address from DHCP server is updated */ -void (*dhcp_ip_conflict)(void) = default_ip_conflict; /* handler to be called when the IP address from DHCP server is conflict */ - -void reg_dhcp_cbfunc(void(*ip_assign)(void), void(*ip_update)(void), void(*ip_conflict)(void)); - - -/* send DISCOVER message to DHCP server */ -void send_DHCP_DISCOVER(void); - -/* send REQEUST message to DHCP server */ -void send_DHCP_REQUEST(void); - -/* send DECLINE message to DHCP server */ -void send_DHCP_DECLINE(void); - -/* IP conflict check by sending ARP-request to leased IP and wait ARP-response. */ -int8_t check_DHCP_leasedIP(void); - -/* check the timeout in DHCP process */ -uint8_t check_DHCP_timeout(void); - -/* Intialize to timeout process. */ -void reset_DHCP_timeout(void); - -/* Parse message as OFFER and ACK and NACK from DHCP server.*/ -int8_t parseDHCPCMSG(void); - -/* The default handler of ip assign first */ -void default_ip_assign(void) -{ - setSIPR(DHCP_allocated_ip); - setSUBR(DHCP_allocated_sn); - setGAR (DHCP_allocated_gw); -} - -/* The default handler of ip changed */ -void default_ip_update(void) -{ - /* WIZchip Software Reset */ - setMR(MR_RST); - getMR(); // for delay - default_ip_assign(); - setSHAR(DHCP_CHADDR); -} - -/* The default handler of ip changed */ -void default_ip_conflict(void) -{ - // WIZchip Software Reset - setMR(MR_RST); - getMR(); // for delay - setSHAR(DHCP_CHADDR); -} - -/* register the call back func. */ -void reg_dhcp_cbfunc(void(*ip_assign)(void), void(*ip_update)(void), void(*ip_conflict)(void)) -{ - dhcp_ip_assign = default_ip_assign; - dhcp_ip_update = default_ip_update; - dhcp_ip_conflict = default_ip_conflict; - if(ip_assign) dhcp_ip_assign = ip_assign; - if(ip_update) dhcp_ip_update = ip_update; - if(ip_conflict) dhcp_ip_conflict = ip_conflict; -} - -/* make the common DHCP message */ -void makeDHCPMSG(void) -{ - uint8_t bk_mac[6]; - uint8_t* ptmp; - uint8_t i; - getSHAR(bk_mac); - pDHCPMSG->op = DHCP_BOOTREQUEST; - pDHCPMSG->htype = DHCP_HTYPE10MB; - pDHCPMSG->hlen = DHCP_HLENETHERNET; - pDHCPMSG->hops = DHCP_HOPS; - ptmp = (uint8_t*)(&pDHCPMSG->xid); - *(ptmp+0) = (uint8_t)((DHCP_XID & 0xFF000000) >> 24); - *(ptmp+1) = (uint8_t)((DHCP_XID & 0x00FF0000) >> 16); - *(ptmp+2) = (uint8_t)((DHCP_XID & 0x0000FF00) >> 8); - *(ptmp+3) = (uint8_t)((DHCP_XID & 0x000000FF) >> 0); - pDHCPMSG->secs = DHCP_SECS; - ptmp = (uint8_t*)(&pDHCPMSG->flags); - *(ptmp+0) = (uint8_t)((DHCP_FLAGSBROADCAST & 0xFF00) >> 8); - *(ptmp+1) = (uint8_t)((DHCP_FLAGSBROADCAST & 0x00FF) >> 0); - - pDHCPMSG->ciaddr[0] = 0; - pDHCPMSG->ciaddr[1] = 0; - pDHCPMSG->ciaddr[2] = 0; - pDHCPMSG->ciaddr[3] = 0; - - pDHCPMSG->yiaddr[0] = 0; - pDHCPMSG->yiaddr[1] = 0; - pDHCPMSG->yiaddr[2] = 0; - pDHCPMSG->yiaddr[3] = 0; - - pDHCPMSG->siaddr[0] = 0; - pDHCPMSG->siaddr[1] = 0; - pDHCPMSG->siaddr[2] = 0; - pDHCPMSG->siaddr[3] = 0; - - pDHCPMSG->giaddr[0] = 0; - pDHCPMSG->giaddr[1] = 0; - pDHCPMSG->giaddr[2] = 0; - pDHCPMSG->giaddr[3] = 0; - - pDHCPMSG->chaddr[0] = DHCP_CHADDR[0]; - pDHCPMSG->chaddr[1] = DHCP_CHADDR[1]; - pDHCPMSG->chaddr[2] = DHCP_CHADDR[2]; - pDHCPMSG->chaddr[3] = DHCP_CHADDR[3]; - pDHCPMSG->chaddr[4] = DHCP_CHADDR[4]; - pDHCPMSG->chaddr[5] = DHCP_CHADDR[5]; - - for (i = 6; i < 16; i++) pDHCPMSG->chaddr[i] = 0; - for (i = 0; i < 64; i++) pDHCPMSG->sname[i] = 0; - for (i = 0; i < 128; i++) pDHCPMSG->file[i] = 0; - - // MAGIC_COOKIE - pDHCPMSG->OPT[0] = (uint8_t)((MAGIC_COOKIE & 0xFF000000) >> 24); - pDHCPMSG->OPT[1] = (uint8_t)((MAGIC_COOKIE & 0x00FF0000) >> 16); - pDHCPMSG->OPT[2] = (uint8_t)((MAGIC_COOKIE & 0x0000FF00) >> 8); - pDHCPMSG->OPT[3] = (uint8_t) (MAGIC_COOKIE & 0x000000FF) >> 0; -} - -/* SEND DHCP DISCOVER */ -void send_DHCP_DISCOVER(void) -{ - uint16_t i; - uint8_t ip[4]; - uint16_t k = 0; - - makeDHCPMSG(); - - k = 4; // because MAGIC_COOKIE already made by makeDHCPMSG() - - // Option Request Param - pDHCPMSG->OPT[k++] = dhcpMessageType; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_DISCOVER; - - // Client identifier - pDHCPMSG->OPT[k++] = dhcpClientIdentifier; - pDHCPMSG->OPT[k++] = 0x07; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[0]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[1]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[2]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - - // host name - pDHCPMSG->OPT[k++] = hostName; - pDHCPMSG->OPT[k++] = 0; // fill zero length of hostname - for(i = 0 ; HOST_NAME[i] != 0; i++) - pDHCPMSG->OPT[k++] = HOST_NAME[i]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - pDHCPMSG->OPT[k - (i+3+1)] = i+3; // length of hostname - - pDHCPMSG->OPT[k++] = dhcpParamRequest; - pDHCPMSG->OPT[k++] = 0x06; // length of request - pDHCPMSG->OPT[k++] = subnetMask; - pDHCPMSG->OPT[k++] = routersOnSubnet; - pDHCPMSG->OPT[k++] = dns; - pDHCPMSG->OPT[k++] = domainName; - pDHCPMSG->OPT[k++] = dhcpT1value; - pDHCPMSG->OPT[k++] = dhcpT2value; - pDHCPMSG->OPT[k++] = endOption; - - for (i = k; i < OPT_SIZE; i++) pDHCPMSG->OPT[i] = 0; - - // send broadcasting packet - ip[0] = 255; - ip[1] = 255; - ip[2] = 255; - ip[3] = 255; - -#ifdef _DHCP_DEBUG_ - printf("> Send DHCP_DISCOVER\r\n"); -#endif - - WIZCHIP_EXPORT(sendto)(DHCP_SOCKET, (uint8_t *)pDHCPMSG, RIP_MSG_SIZE, ip, DHCP_SERVER_PORT); -} - -/* SEND DHCP REQUEST */ -void send_DHCP_REQUEST(void) -{ - int i; - uint8_t ip[4]; - uint16_t k = 0; - - makeDHCPMSG(); - - if(dhcp_state == STATE_DHCP_LEASED || dhcp_state == STATE_DHCP_REREQUEST) - { - *((uint8_t*)(&pDHCPMSG->flags)) = ((DHCP_FLAGSUNICAST & 0xFF00)>> 8); - *((uint8_t*)(&pDHCPMSG->flags)+1) = (DHCP_FLAGSUNICAST & 0x00FF); - pDHCPMSG->ciaddr[0] = DHCP_allocated_ip[0]; - pDHCPMSG->ciaddr[1] = DHCP_allocated_ip[1]; - pDHCPMSG->ciaddr[2] = DHCP_allocated_ip[2]; - pDHCPMSG->ciaddr[3] = DHCP_allocated_ip[3]; - ip[0] = DHCP_SIP[0]; - ip[1] = DHCP_SIP[1]; - ip[2] = DHCP_SIP[2]; - ip[3] = DHCP_SIP[3]; - } - else - { - ip[0] = 255; - ip[1] = 255; - ip[2] = 255; - ip[3] = 255; - } - - k = 4; // because MAGIC_COOKIE already made by makeDHCPMSG() - - // Option Request Param. - pDHCPMSG->OPT[k++] = dhcpMessageType; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_REQUEST; - - pDHCPMSG->OPT[k++] = dhcpClientIdentifier; - pDHCPMSG->OPT[k++] = 0x07; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[0]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[1]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[2]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - - if(ip[3] == 255) // if(dchp_state == STATE_DHCP_LEASED || dchp_state == DHCP_REREQUEST_STATE) - { - pDHCPMSG->OPT[k++] = dhcpRequestedIPaddr; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[0]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[1]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[2]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[3]; - - pDHCPMSG->OPT[k++] = dhcpServerIdentifier; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_SIP[0]; - pDHCPMSG->OPT[k++] = DHCP_SIP[1]; - pDHCPMSG->OPT[k++] = DHCP_SIP[2]; - pDHCPMSG->OPT[k++] = DHCP_SIP[3]; - } - - // host name - pDHCPMSG->OPT[k++] = hostName; - pDHCPMSG->OPT[k++] = 0; // length of hostname - for(i = 0 ; HOST_NAME[i] != 0; i++) - pDHCPMSG->OPT[k++] = HOST_NAME[i]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - pDHCPMSG->OPT[k - (i+3+1)] = i+3; // length of hostname - - pDHCPMSG->OPT[k++] = dhcpParamRequest; - pDHCPMSG->OPT[k++] = 0x08; - pDHCPMSG->OPT[k++] = subnetMask; - pDHCPMSG->OPT[k++] = routersOnSubnet; - pDHCPMSG->OPT[k++] = dns; - pDHCPMSG->OPT[k++] = domainName; - pDHCPMSG->OPT[k++] = dhcpT1value; - pDHCPMSG->OPT[k++] = dhcpT2value; - pDHCPMSG->OPT[k++] = performRouterDiscovery; - pDHCPMSG->OPT[k++] = staticRoute; - pDHCPMSG->OPT[k++] = endOption; - - for (i = k; i < OPT_SIZE; i++) pDHCPMSG->OPT[i] = 0; - -#ifdef _DHCP_DEBUG_ - printf("> Send DHCP_REQUEST\r\n"); -#endif - - WIZCHIP_EXPORT(sendto)(DHCP_SOCKET, (uint8_t *)pDHCPMSG, RIP_MSG_SIZE, ip, DHCP_SERVER_PORT); - -} - -/* SEND DHCP DHCPDECLINE */ -void send_DHCP_DECLINE(void) -{ - int i; - uint8_t ip[4]; - uint16_t k = 0; - - makeDHCPMSG(); - - k = 4; // because MAGIC_COOKIE already made by makeDHCPMSG() - - *((uint8_t*)(&pDHCPMSG->flags)) = ((DHCP_FLAGSUNICAST & 0xFF00)>> 8); - *((uint8_t*)(&pDHCPMSG->flags)+1) = (DHCP_FLAGSUNICAST & 0x00FF); - - // Option Request Param. - pDHCPMSG->OPT[k++] = dhcpMessageType; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_DECLINE; - - pDHCPMSG->OPT[k++] = dhcpClientIdentifier; - pDHCPMSG->OPT[k++] = 0x07; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[0]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[1]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[2]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - - pDHCPMSG->OPT[k++] = dhcpRequestedIPaddr; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[0]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[1]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[2]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[3]; - - pDHCPMSG->OPT[k++] = dhcpServerIdentifier; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_SIP[0]; - pDHCPMSG->OPT[k++] = DHCP_SIP[1]; - pDHCPMSG->OPT[k++] = DHCP_SIP[2]; - pDHCPMSG->OPT[k++] = DHCP_SIP[3]; - - pDHCPMSG->OPT[k++] = endOption; - - for (i = k; i < OPT_SIZE; i++) pDHCPMSG->OPT[i] = 0; - - //send broadcasting packet - ip[0] = 0xFF; - ip[1] = 0xFF; - ip[2] = 0xFF; - ip[3] = 0xFF; - -#ifdef _DHCP_DEBUG_ - printf("\r\n> Send DHCP_DECLINE\r\n"); -#endif - - WIZCHIP_EXPORT(sendto)(DHCP_SOCKET, (uint8_t *)pDHCPMSG, RIP_MSG_SIZE, ip, DHCP_SERVER_PORT); -} - -/* PARSE REPLY pDHCPMSG */ -int8_t parseDHCPMSG(void) -{ - uint8_t svr_addr[6]; - uint16_t svr_port; - uint16_t len; - - uint8_t * p; - uint8_t * e; - uint8_t type = 0; - uint8_t opt_len; - - if((len = getSn_RX_RSR(DHCP_SOCKET)) > 0) - { - len = WIZCHIP_EXPORT(recvfrom)(DHCP_SOCKET, (uint8_t *)pDHCPMSG, len, svr_addr, &svr_port); - #ifdef _DHCP_DEBUG_ - printf("DHCP message : %d.%d.%d.%d(%d) %d received. \r\n",svr_addr[0],svr_addr[1],svr_addr[2], svr_addr[3],svr_port, len); - #endif - } - else return 0; - if (svr_port == DHCP_SERVER_PORT) { - // compare mac address - if ( (pDHCPMSG->chaddr[0] != DHCP_CHADDR[0]) || (pDHCPMSG->chaddr[1] != DHCP_CHADDR[1]) || - (pDHCPMSG->chaddr[2] != DHCP_CHADDR[2]) || (pDHCPMSG->chaddr[3] != DHCP_CHADDR[3]) || - (pDHCPMSG->chaddr[4] != DHCP_CHADDR[4]) || (pDHCPMSG->chaddr[5] != DHCP_CHADDR[5]) ) - return 0; - type = 0; - p = (uint8_t *)(&pDHCPMSG->op); - p = p + 240; // 240 = sizeof(RIP_MSG) + MAGIC_COOKIE size in RIP_MSG.opt - sizeof(RIP_MSG.opt) - e = p + (len - 240); - - while ( p < e ) { - - switch ( *p ) { - - case endOption : - p = e; // for break while(p < e) - break; - case padOption : - p++; - break; - case dhcpMessageType : - p++; - p++; - type = *p++; - break; - case subnetMask : - p++; - p++; - DHCP_allocated_sn[0] = *p++; - DHCP_allocated_sn[1] = *p++; - DHCP_allocated_sn[2] = *p++; - DHCP_allocated_sn[3] = *p++; - break; - case routersOnSubnet : - p++; - opt_len = *p++; - DHCP_allocated_gw[0] = *p++; - DHCP_allocated_gw[1] = *p++; - DHCP_allocated_gw[2] = *p++; - DHCP_allocated_gw[3] = *p++; - p = p + (opt_len - 4); - break; - case dns : - p++; - opt_len = *p++; - DHCP_allocated_dns[0] = *p++; - DHCP_allocated_dns[1] = *p++; - DHCP_allocated_dns[2] = *p++; - DHCP_allocated_dns[3] = *p++; - p = p + (opt_len - 4); - break; - case dhcpIPaddrLeaseTime : - p++; - opt_len = *p++; - dhcp_lease_time = *p++; - dhcp_lease_time = (dhcp_lease_time << 8) + *p++; - dhcp_lease_time = (dhcp_lease_time << 8) + *p++; - dhcp_lease_time = (dhcp_lease_time << 8) + *p++; - #ifdef _DHCP_DEBUG_ - dhcp_lease_time = 10; - #endif - break; - case dhcpServerIdentifier : - p++; - opt_len = *p++; - DHCP_SIP[0] = *p++; - DHCP_SIP[1] = *p++; - DHCP_SIP[2] = *p++; - DHCP_SIP[3] = *p++; - break; - default : - p++; - opt_len = *p++; - p += opt_len; - break; - } // switch - } // while - } // if - return type; -} - -uint8_t DHCP_run(void) -{ - uint8_t type; - uint8_t ret; - - if(dhcp_state == STATE_DHCP_STOP) return DHCP_STOPPED; - - if(getSn_SR(DHCP_SOCKET) != SOCK_UDP) - WIZCHIP_EXPORT(socket)(DHCP_SOCKET, Sn_MR_UDP, DHCP_CLIENT_PORT, 0x00); - - ret = DHCP_RUNNING; - type = parseDHCPMSG(); - - switch ( dhcp_state ) { - case STATE_DHCP_INIT : - DHCP_allocated_ip[0] = 0; - DHCP_allocated_ip[1] = 0; - DHCP_allocated_ip[2] = 0; - DHCP_allocated_ip[3] = 0; - send_DHCP_DISCOVER(); - dhcp_state = STATE_DHCP_DISCOVER; - break; - case STATE_DHCP_DISCOVER : - if (type == DHCP_OFFER){ -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_OFFER\r\n"); -#endif - DHCP_allocated_ip[0] = pDHCPMSG->yiaddr[0]; - DHCP_allocated_ip[1] = pDHCPMSG->yiaddr[1]; - DHCP_allocated_ip[2] = pDHCPMSG->yiaddr[2]; - DHCP_allocated_ip[3] = pDHCPMSG->yiaddr[3]; - - send_DHCP_REQUEST(); - dhcp_state = STATE_DHCP_REQUEST; - } else ret = check_DHCP_timeout(); - break; - - case STATE_DHCP_REQUEST : - if (type == DHCP_ACK) { - -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_ACK\r\n"); -#endif - if (check_DHCP_leasedIP()) { - // Network info assignment from DHCP - dhcp_ip_assign(); - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_LEASED; - } else { - // IP address conflict occurred - reset_DHCP_timeout(); - dhcp_ip_conflict(); - dhcp_state = STATE_DHCP_INIT; - } - } else if (type == DHCP_NAK) { - -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_NACK\r\n"); -#endif - - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_DISCOVER; - } else ret = check_DHCP_timeout(); - break; - - case STATE_DHCP_LEASED : - ret = DHCP_IP_LEASED; - if ((dhcp_lease_time != INFINITE_LEASETIME) && ((dhcp_lease_time/2) < dhcp_tick_1s)) { - -#ifdef _DHCP_DEBUG_ - printf("> Maintains the IP address \r\n"); -#endif - - type = 0; - OLD_allocated_ip[0] = DHCP_allocated_ip[0]; - OLD_allocated_ip[1] = DHCP_allocated_ip[1]; - OLD_allocated_ip[2] = DHCP_allocated_ip[2]; - OLD_allocated_ip[3] = DHCP_allocated_ip[3]; - - DHCP_XID++; - - send_DHCP_REQUEST(); - - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_REREQUEST; - } - break; - - case STATE_DHCP_REREQUEST : - ret = DHCP_IP_LEASED; - if (type == DHCP_ACK) { - dhcp_retry_count = 0; - if (OLD_allocated_ip[0] != DHCP_allocated_ip[0] || - OLD_allocated_ip[1] != DHCP_allocated_ip[1] || - OLD_allocated_ip[2] != DHCP_allocated_ip[2] || - OLD_allocated_ip[3] != DHCP_allocated_ip[3]) - { - ret = DHCP_IP_CHANGED; - dhcp_ip_update(); - #ifdef _DHCP_DEBUG_ - printf(">IP changed.\r\n"); - #endif - - } - #ifdef _DHCP_DEBUG_ - else printf(">IP is continued.\r\n"); - #endif - reset_DHCP_timeout(); - dhcp_state = STATE_DHCP_LEASED; - } else if (type == DHCP_NAK) { - -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_NACK, Failed to maintain ip\r\n"); -#endif - - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_DISCOVER; - } else ret = check_DHCP_timeout(); - break; - default : - break; - } - - return ret; -} - -void DHCP_stop(void) -{ - WIZCHIP_EXPORT(close)(DHCP_SOCKET); - dhcp_state = STATE_DHCP_STOP; -} - -uint8_t check_DHCP_timeout(void) -{ - uint8_t ret = DHCP_RUNNING; - - if (dhcp_retry_count < MAX_DHCP_RETRY) { - if (dhcp_tick_next < dhcp_tick_1s) { - - switch ( dhcp_state ) { - case STATE_DHCP_DISCOVER : -// printf("<> state : STATE_DHCP_DISCOVER\r\n"); - send_DHCP_DISCOVER(); - break; - - case STATE_DHCP_REQUEST : -// printf("<> state : STATE_DHCP_REQUEST\r\n"); - - send_DHCP_REQUEST(); - break; - - case STATE_DHCP_REREQUEST : -// printf("<> state : STATE_DHCP_REREQUEST\r\n"); - - send_DHCP_REQUEST(); - break; - - default : - break; - } - - dhcp_tick_1s = 0; - dhcp_tick_next = dhcp_tick_1s + DHCP_WAIT_TIME; - dhcp_retry_count++; - } - } else { // timeout occurred - - switch(dhcp_state) { - case STATE_DHCP_DISCOVER: - dhcp_state = STATE_DHCP_INIT; - ret = DHCP_FAILED; - break; - case STATE_DHCP_REQUEST: - case STATE_DHCP_REREQUEST: - send_DHCP_DISCOVER(); - dhcp_state = STATE_DHCP_DISCOVER; - break; - default : - break; - } - reset_DHCP_timeout(); - } - return ret; -} - -int8_t check_DHCP_leasedIP(void) -{ - uint8_t tmp; - int32_t ret; - - //WIZchip RCR value changed for ARP Timeout count control - tmp = getRCR(); - setRCR(0x03); - - // IP conflict detection : ARP request - ARP reply - // Broadcasting ARP Request for check the IP conflict using UDP sendto() function - ret = WIZCHIP_EXPORT(sendto)(DHCP_SOCKET, (uint8_t *)"CHECK_IP_CONFLICT", 17, DHCP_allocated_ip, 5000); - - // RCR value restore - setRCR(tmp); - - if(ret == SOCKERR_TIMEOUT) { - // UDP send Timeout occurred : allocated IP address is unique, DHCP Success - -#ifdef _DHCP_DEBUG_ - printf("\r\n> Check leased IP - OK\r\n"); -#endif - - return 1; - } else { - // Received ARP reply or etc : IP address conflict occur, DHCP Failed - send_DHCP_DECLINE(); - - ret = dhcp_tick_1s; - while((dhcp_tick_1s - ret) < 2) ; // wait for 1s over; wait to complete to send DECLINE message; - - return 0; - } -} - -void DHCP_init(uint8_t s, DHCP_INIT_BUFFER_TYPE* buf) -{ - uint8_t zeroip[4] = {0,0,0,0}; - getSHAR(DHCP_CHADDR); - if((DHCP_CHADDR[0] | DHCP_CHADDR[1] | DHCP_CHADDR[2] | DHCP_CHADDR[3] | DHCP_CHADDR[4] | DHCP_CHADDR[5]) == 0x00) - { - // assign temporary mac address, you should be set SHAR before call this function. - DHCP_CHADDR[0] = 0x00; - DHCP_CHADDR[1] = 0x08; - DHCP_CHADDR[2] = 0xdc; - DHCP_CHADDR[3] = 0x00; - DHCP_CHADDR[4] = 0x00; - DHCP_CHADDR[5] = 0x00; - setSHAR(DHCP_CHADDR); - } - - DHCP_SOCKET = s; // SOCK_DHCP - pDHCPMSG = (RIP_MSG*)buf; - DHCP_XID = 0x12345678; - - // WIZchip Netinfo Clear - setSIPR(zeroip); - setSIPR(zeroip); - setGAR(zeroip); - - reset_DHCP_timeout(); - dhcp_state = STATE_DHCP_INIT; -} - - -/* Rset the DHCP timeout count and retry count. */ -void reset_DHCP_timeout(void) -{ - dhcp_tick_1s = 0; - dhcp_tick_next = DHCP_WAIT_TIME; - dhcp_retry_count = 0; -} - -void DHCP_time_handler(void) -{ - dhcp_tick_1s++; -} - -void getIPfromDHCP(uint8_t* ip) -{ - ip[0] = DHCP_allocated_ip[0]; - ip[1] = DHCP_allocated_ip[1]; - ip[2] = DHCP_allocated_ip[2]; - ip[3] = DHCP_allocated_ip[3]; -} - -void getGWfromDHCP(uint8_t* ip) -{ - ip[0] =DHCP_allocated_gw[0]; - ip[1] =DHCP_allocated_gw[1]; - ip[2] =DHCP_allocated_gw[2]; - ip[3] =DHCP_allocated_gw[3]; -} - -void getSNfromDHCP(uint8_t* ip) -{ - ip[0] = DHCP_allocated_sn[0]; - ip[1] = DHCP_allocated_sn[1]; - ip[2] = DHCP_allocated_sn[2]; - ip[3] = DHCP_allocated_sn[3]; -} - -void getDNSfromDHCP(uint8_t* ip) -{ - ip[0] = DHCP_allocated_dns[0]; - ip[1] = DHCP_allocated_dns[1]; - ip[2] = DHCP_allocated_dns[2]; - ip[3] = DHCP_allocated_dns[3]; -} - -uint32_t getDHCPLeasetime(void) -{ - return dhcp_lease_time; -} diff --git a/drivers/wiznet5k/internet/dhcp/dhcp.h b/drivers/wiznet5k/internet/dhcp/dhcp.h deleted file mode 100644 index 618a91498b..0000000000 --- a/drivers/wiznet5k/internet/dhcp/dhcp.h +++ /dev/null @@ -1,152 +0,0 @@ -//***************************************************************************** -// -//! \file dhcp.h -//! \brief DHCP APIs Header file. -//! \details Processig DHCP protocol as DISCOVER, OFFER, REQUEST, ACK, NACK and DECLINE. -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2013/11/18> 1st Release -//! <2012/12/20> V1.1.0 -//! 1. Move unreferenced DEFINE to dhcp.c -//! <2012/12/26> V1.1.1 -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** -#ifndef _DHCP_H_ -#define _DHCP_H_ - -/* - * @brief - * @details If you want to display debug & processing message, Define _DHCP_DEBUG_ - * @note If defined, it depends on - */ - -//#define _DHCP_DEBUG_ - -/* Retry to processing DHCP */ -#define MAX_DHCP_RETRY 2 ///< Maximum retry count -#define DHCP_WAIT_TIME 3 ///< Wait Time 3s (was 10s) - -/* UDP port numbers for DHCP */ -#define DHCP_SERVER_PORT 67 ///< DHCP server port number -#define DHCP_CLIENT_PORT 68 ///< DHCP client port number - -#define MAGIC_COOKIE 0x63825363 ///< Any number. You can be modified it any number - -#define DCHP_HOST_NAME "WIZnet\0" - -/* - * @brief return value of @ref DHCP_run() - */ -enum -{ - DHCP_FAILED = 0, ///< Processing Fail - DHCP_RUNNING, ///< Processing DHCP protocol - DHCP_IP_ASSIGN, ///< First Occupy IP from DHPC server (if cbfunc == null, act as default default_ip_assign) - DHCP_IP_CHANGED, ///< Change IP address by new IP address from DHCP (if cbfunc == null, act as default default_ip_update) - DHCP_IP_LEASED, ///< Stand by - DHCP_STOPPED ///< Stop processing DHCP protocol -}; - -#define DHCP_INIT_BUFFER_TYPE uint32_t -#define DHCP_INIT_BUFFER_SIZE (137) -/* - * @brief DHCP client initialization (outside of the main loop) - * @param s - socket number - * @param buf - buffer for processing DHCP message - */ -void DHCP_init(uint8_t s, DHCP_INIT_BUFFER_TYPE* buf); - -/* - * @brief DHCP 1s Tick Timer handler - * @note SHOULD BE register to your system 1s Tick timer handler - */ -void DHCP_time_handler(void); - -/* - * @brief Register call back function - * @param ip_assign - callback func when IP is assigned from DHCP server first - * @param ip_update - callback func when IP is changed - * @prarm ip_conflict - callback func when the assigned IP is conflict with others. - */ -void reg_dhcp_cbfunc(void(*ip_assign)(void), void(*ip_update)(void), void(*ip_conflict)(void)); - -/* - * @brief DHCP client in the main loop - * @return The value is as the follow \n - * @ref DHCP_FAILED \n - * @ref DHCP_RUNNING \n - * @ref DHCP_IP_ASSIGN \n - * @ref DHCP_IP_CHANGED \n - * @ref DHCP_IP_LEASED \n - * @ref DHCP_STOPPED \n - * - * @note This function is always called by you main task. - */ -uint8_t DHCP_run(void); - -/* - * @brief Stop DHCP processing - * @note If you want to restart. call DHCP_init() and DHCP_run() - */ -void DHCP_stop(void); - -/* Get Network information assigned from DHCP server */ -/* - * @brief Get IP address - * @param ip - IP address to be returned - */ -void getIPfromDHCP(uint8_t* ip); -/* - * @brief Get Gateway address - * @param ip - Gateway address to be returned - */ -void getGWfromDHCP(uint8_t* ip); -/* - * @brief Get Subnet mask value - * @param ip - Subnet mask to be returned - */ -void getSNfromDHCP(uint8_t* ip); -/* - * @brief Get DNS address - * @param ip - DNS address to be returned - */ -void getDNSfromDHCP(uint8_t* ip); - -/* - * @brief Get the leased time by DHCP sever - * @return unit 1s - */ -uint32_t getDHCPLeasetime(void); - -#endif /* _DHCP_H_ */ diff --git a/drivers/wiznet5k/internet/dns/dns.c b/drivers/wiznet5k/internet/dns/dns.c deleted file mode 100644 index aa3a738091..0000000000 --- a/drivers/wiznet5k/internet/dns/dns.c +++ /dev/null @@ -1,572 +0,0 @@ -//***************************************************************************** -// -//! \file dns.c -//! \brief DNS APIs Implement file. -//! \details Send DNS query & Receive DNS reponse. \n -//! It depends on stdlib.h & string.h in ansi-c library -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.1.0 -//! 1. Remove secondary DNS server in DNS_run -//! If 1st DNS_run failed, call DNS_run with 2nd DNS again -//! 2. DNS_timerHandler -> DNS_time_handler -//! 3. Remove the unused define -//! 4. Integrated dns.h dns.c & dns_parse.h dns_parse.c into dns.h & dns.c -//! <2013/12/20> V1.1.0 -//! <2018/10/04> Modified HAL_GetTick for use with CircuitPython by Nick Moore -//! -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#include -#include -#include "supervisor/shared/tick.h" - -//#include "Ethernet/socket.h" -//#include "Internet/DNS/dns.h" -#include "../../ethernet/socket.h" -#include "dns.h" - -#ifdef _DNS_DEBUG_ - #include -#endif - -#define INITRTT 2000L /* Initial smoothed response time */ -#define MAXCNAME (MAX_DOMAIN_NAME + (MAX_DOMAIN_NAME>>1)) /* Maximum amount of cname recursion */ - -#define TYPE_A 1 /* Host address */ -#define TYPE_NS 2 /* Name server */ -#define TYPE_MD 3 /* Mail destination (obsolete) */ -#define TYPE_MF 4 /* Mail forwarder (obsolete) */ -#define TYPE_CNAME 5 /* Canonical name */ -#define TYPE_SOA 6 /* Start of Authority */ -#define TYPE_MB 7 /* Mailbox name (experimental) */ -#define TYPE_MG 8 /* Mail group member (experimental) */ -#define TYPE_MR 9 /* Mail rename name (experimental) */ -#define TYPE_NULL 10 /* Null (experimental) */ -#define TYPE_WKS 11 /* Well-known sockets */ -#define TYPE_PTR 12 /* Pointer record */ -#define TYPE_HINFO 13 /* Host information */ -#define TYPE_MINFO 14 /* Mailbox information (experimental)*/ -#define TYPE_MX 15 /* Mail exchanger */ -#define TYPE_TXT 16 /* Text strings */ -#define TYPE_ANY 255 /* Matches any type */ - -#define CLASS_IN 1 /* The ARPA Internet */ - -/* Round trip timing parameters */ -#define AGAIN 8 /* Average RTT gain = 1/8 */ -#define LAGAIN 3 /* Log2(AGAIN) */ -#define DGAIN 4 /* Mean deviation gain = 1/4 */ -#define LDGAIN 2 /* log2(DGAIN) */ - -/* Header for all domain messages */ -struct dhdr -{ - uint16_t id; /* Identification */ - uint8_t qr; /* Query/Response */ -#define QUERY 0 -#define RESPONSE 1 - uint8_t opcode; -#define IQUERY 1 - uint8_t aa; /* Authoratative answer */ - uint8_t tc; /* Truncation */ - uint8_t rd; /* Recursion desired */ - uint8_t ra; /* Recursion available */ - uint8_t rcode; /* Response code */ -#define NO_ERROR 0 -#define FORMAT_ERROR 1 -#define SERVER_FAIL 2 -#define NAME_ERROR 3 -#define NOT_IMPL 4 -#define REFUSED 5 - uint16_t qdcount; /* Question count */ - uint16_t ancount; /* Answer count */ - uint16_t nscount; /* Authority (name server) count */ - uint16_t arcount; /* Additional record count */ -}; - - -uint8_t* pDNSMSG; // DNS message buffer -uint8_t DNS_SOCKET; // SOCKET number for DNS -uint16_t DNS_MSGID; // DNS message ID - - -uint32_t HAL_GetTick(void) { - return supervisor_ticks_ms32(); -} - -uint32_t hal_sys_tick; - -/* converts uint16_t from network buffer to a host byte order integer. */ -uint16_t get16(uint8_t * s) -{ - uint16_t i; - i = *s++ << 8; - i = i + *s; - return i; -} - -/* copies uint16_t to the network buffer with network byte order. */ -uint8_t * put16(uint8_t * s, uint16_t i) -{ - *s++ = i >> 8; - *s++ = i; - return s; -} - - -/* - * CONVERT A DOMAIN NAME TO THE HUMAN-READABLE FORM - * - * Description : This function converts a compressed domain name to the human-readable form - * Arguments : msg - is a pointer to the reply message - * compressed - is a pointer to the domain name in reply message. - * buf - is a pointer to the buffer for the human-readable form name. - * len - is the MAX. size of buffer. - * Returns : the length of compressed message - */ -int parse_name(uint8_t * msg, uint8_t * compressed, char * buf, int16_t len) -{ - uint16_t slen; /* Length of current segment */ - uint8_t * cp; - int clen = 0; /* Total length of compressed name */ - int indirect = 0; /* Set if indirection encountered */ - int nseg = 0; /* Total number of segments in name */ - - cp = compressed; - - for (;;) - { - slen = *cp++; /* Length of this segment */ - - if (!indirect) clen++; - - if ((slen & 0xc0) == 0xc0) - { - if (!indirect) - clen++; - indirect = 1; - /* Follow indirection */ - cp = &msg[((slen & 0x3f)<<8) + *cp]; - slen = *cp++; - } - - if (slen == 0) /* zero length == all done */ - break; - - len -= slen + 1; - - if (len < 0) return -1; - - if (!indirect) clen += slen; - - while (slen-- != 0) *buf++ = (char)*cp++; - *buf++ = '.'; - nseg++; - } - - if (nseg == 0) - { - /* Root name; represent as single dot */ - *buf++ = '.'; - len--; - } - - *buf++ = '\0'; - len--; - - return clen; /* Length of compressed message */ -} - -/* - * PARSE QUESTION SECTION - * - * Description : This function parses the question record of the reply message. - * Arguments : msg - is a pointer to the reply message - * cp - is a pointer to the question record. - * Returns : a pointer the to next record. - */ -uint8_t * dns_question(uint8_t * msg, uint8_t * cp) -{ - int len; - char name[MAXCNAME]; - - len = parse_name(msg, cp, name, MAXCNAME); - - - if (len == -1) return 0; - - cp += len; - cp += 2; /* type */ - cp += 2; /* class */ - - return cp; -} - - -/* - * PARSE ANSER SECTION - * - * Description : This function parses the answer record of the reply message. - * Arguments : msg - is a pointer to the reply message - * cp - is a pointer to the answer record. - * Returns : a pointer the to next record. - */ -uint8_t * dns_answer(uint8_t * msg, uint8_t * cp, uint8_t * ip_from_dns) -{ - int len, type; - char name[MAXCNAME]; - - len = parse_name(msg, cp, name, MAXCNAME); - - if (len == -1) return 0; - - cp += len; - type = get16(cp); - cp += 2; /* type */ - cp += 2; /* class */ - cp += 4; /* ttl */ - cp += 2; /* len */ - - - switch (type) - { - case TYPE_A: - /* Just read the address directly into the structure */ - ip_from_dns[0] = *cp++; - ip_from_dns[1] = *cp++; - ip_from_dns[2] = *cp++; - ip_from_dns[3] = *cp++; - break; - case TYPE_CNAME: - case TYPE_MB: - case TYPE_MG: - case TYPE_MR: - case TYPE_NS: - case TYPE_PTR: - /* These types all consist of a single domain name */ - /* convert it to ASCII format */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - break; - case TYPE_HINFO: - len = *cp++; - cp += len; - - len = *cp++; - cp += len; - break; - case TYPE_MX: - cp += 2; - /* Get domain name of exchanger */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - break; - case TYPE_SOA: - /* Get domain name of name server */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - - /* Get domain name of responsible person */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - - cp += 4; - cp += 4; - cp += 4; - cp += 4; - cp += 4; - break; - case TYPE_TXT: - /* Just stash */ - break; - default: - /* Ignore */ - break; - } - - return cp; -} - -/* - * PARSE THE DNS REPLY - * - * Description : This function parses the reply message from DNS server. - * Arguments : dhdr - is a pointer to the header for DNS message - * buf - is a pointer to the reply message. - * len - is the size of reply message. - * Returns : -1 - Domain name length is too big - * 0 - Fail (Timeout or parse error) - * 1 - Success, - */ -int8_t parseDNSMSG(struct dhdr * pdhdr, uint8_t * pbuf, uint8_t * ip_from_dns) -{ - uint16_t tmp; - uint16_t i; - uint8_t * msg; - uint8_t * cp; - - msg = pbuf; - memset(pdhdr, 0, sizeof(*pdhdr)); - - pdhdr->id = get16(&msg[0]); - tmp = get16(&msg[2]); - if (tmp & 0x8000) pdhdr->qr = 1; - - pdhdr->opcode = (tmp >> 11) & 0xf; - - if (tmp & 0x0400) pdhdr->aa = 1; - if (tmp & 0x0200) pdhdr->tc = 1; - if (tmp & 0x0100) pdhdr->rd = 1; - if (tmp & 0x0080) pdhdr->ra = 1; - - pdhdr->rcode = tmp & 0xf; - pdhdr->qdcount = get16(&msg[4]); - pdhdr->ancount = get16(&msg[6]); - pdhdr->nscount = get16(&msg[8]); - pdhdr->arcount = get16(&msg[10]); - - - /* Now parse the variable length sections */ - cp = &msg[12]; - - /* Question section */ - for (i = 0; i < pdhdr->qdcount; i++) - { - cp = dns_question(msg, cp); - if(!cp) - { -#ifdef _DNS_DEBUG_ - printf("MAX_DOMAIN_NAME is too small, it should be redefined in dns.h\r\n"); -#endif - return -1; - } - } - - /* Answer section */ - for (i = 0; i < pdhdr->ancount; i++) - { - cp = dns_answer(msg, cp, ip_from_dns); - if(!cp) - { -#ifdef _DNS_DEBUG_ - printf("MAX_DOMAIN_NAME is too small, it should be redefined in dns.h\r\n"); -#endif - return -1; - } - - } - - /* Name server (authority) section */ - for (i = 0; i < pdhdr->nscount; i++) - { - ; - } - - /* Additional section */ - for (i = 0; i < pdhdr->arcount; i++) - { - ; - } - - if(pdhdr->rcode == 0) return 1; // No error - else return 0; -} - - -/* - * MAKE DNS QUERY MESSAGE - * - * Description : This function makes DNS query message. - * Arguments : op - Recursion desired - * name - is a pointer to the domain name. - * buf - is a pointer to the buffer for DNS message. - * len - is the MAX. size of buffer. - * Returns : the pointer to the DNS message. - */ -int16_t dns_makequery(uint16_t op, char * name, uint8_t * buf, uint16_t len) -{ - uint8_t *cp; - char *cp1; - char sname[MAXCNAME]; - char *dname; - uint16_t p; - uint16_t dlen; - - cp = buf; - - DNS_MSGID++; - cp = put16(cp, DNS_MSGID); - p = (op << 11) | 0x0100; /* Recursion desired */ - cp = put16(cp, p); - cp = put16(cp, 1); - cp = put16(cp, 0); - cp = put16(cp, 0); - cp = put16(cp, 0); - - strcpy(sname, name); - dname = sname; - dlen = strlen(dname); - for (;;) - { - /* Look for next dot */ - cp1 = strchr(dname, '.'); - - if (cp1 != NULL) len = cp1 - dname; /* More to come */ - else len = dlen; /* Last component */ - - *cp++ = len; /* Write length of component */ - if (len == 0) break; - - /* Copy component up to (but not including) dot */ - memcpy(cp, dname, len); - cp += len; - if (cp1 == NULL) - { - *cp++ = 0; /* Last one; write null and finish */ - break; - } - dname += len+1; - dlen -= len+1; - } - - cp = put16(cp, 0x0001); /* type */ - cp = put16(cp, 0x0001); /* class */ - - return ((int16_t)((uint32_t)(cp) - (uint32_t)(buf))); -} - -/* - * CHECK DNS TIMEOUT - * - * Description : This function check the DNS timeout - * Arguments : None. - * Returns : -1 - timeout occurred, 0 - timer over, but no timeout, 1 - no timer over, no timeout occur - * Note : timeout : retry count and timer both over. - */ - -int8_t check_DNS_timeout(void) -{ - static uint8_t retry_count; - - uint32_t tick = HAL_GetTick(); - if(tick - hal_sys_tick >= DNS_WAIT_TIME * 1000) - { - hal_sys_tick = tick; - if(retry_count >= MAX_DNS_RETRY) { - retry_count = 0; - return -1; // timeout occurred - } - retry_count++; - return 0; // timer over, but no timeout - } - - return 1; // no timer over, no timeout occur -} - - - -/* DNS CLIENT INIT */ -void DNS_init(uint8_t s, uint8_t * buf) -{ - DNS_SOCKET = s; // SOCK_DNS - pDNSMSG = buf; // User's shared buffer - DNS_MSGID = DNS_MSG_ID; -} - -/* DNS CLIENT RUN */ -int8_t DNS_run(uint8_t * dns_ip, uint8_t * name, uint8_t * ip_from_dns) -{ - int8_t ret; - struct dhdr dhp; - uint8_t ip[4]; - uint16_t len, port; - int8_t ret_check_timeout; - - hal_sys_tick = HAL_GetTick(); - - // Socket open - WIZCHIP_EXPORT(socket)(DNS_SOCKET, Sn_MR_UDP, 0, 0); - -#ifdef _DNS_DEBUG_ - printf("> DNS Query to DNS Server : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]); -#endif - - len = dns_makequery(0, (char *)name, pDNSMSG, MAX_DNS_BUF_SIZE); - WIZCHIP_EXPORT(sendto)(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN); - - while (1) - { - if ((len = getSn_RX_RSR(DNS_SOCKET)) > 0) - { - if (len > MAX_DNS_BUF_SIZE) len = MAX_DNS_BUF_SIZE; - len = WIZCHIP_EXPORT(recvfrom)(DNS_SOCKET, pDNSMSG, len, ip, &port); - #ifdef _DNS_DEBUG_ - printf("> Receive DNS message from %d.%d.%d.%d(%d). len = %d\r\n", ip[0], ip[1], ip[2], ip[3],port,len); - #endif - ret = parseDNSMSG(&dhp, pDNSMSG, ip_from_dns); - break; - } - // Check Timeout - ret_check_timeout = check_DNS_timeout(); - if (ret_check_timeout < 0) { - -#ifdef _DNS_DEBUG_ - printf("> DNS Server is not responding : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]); -#endif - return 0; // timeout occurred - } - else if (ret_check_timeout == 0) { - -#ifdef _DNS_DEBUG_ - printf("> DNS Timeout\r\n"); -#endif - WIZCHIP_EXPORT(sendto)(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN); - } - } - WIZCHIP_EXPORT(close)(DNS_SOCKET); - // Return value - // 0 > : failed / 1 - success - return ret; -} diff --git a/drivers/wiznet5k/internet/dns/dns.h b/drivers/wiznet5k/internet/dns/dns.h deleted file mode 100644 index 574b632a6a..0000000000 --- a/drivers/wiznet5k/internet/dns/dns.h +++ /dev/null @@ -1,96 +0,0 @@ -//***************************************************************************** -// -//! \file dns.h -//! \brief DNS APIs Header file. -//! \details Send DNS query & Receive DNS reponse. -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.1.0 -//! 1. Remove secondary DNS server in DNS_run -//! If 1st DNS_run failed, call DNS_run with 2nd DNS again -//! 2. DNS_timerHandler -> DNS_time_handler -//! 3. Move the no reference define to dns.c -//! 4. Integrated dns.h dns.c & dns_parse.h dns_parse.c into dns.h & dns.c -//! <2013/12/20> V1.1.0 -//! -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#ifndef _DNS_H_ -#define _DNS_H_ - -#include -/* - * @brief Define it for Debug & Monitor DNS processing. - * @note If defined, it depends on - */ - -//#define _DNS_DEBUG_ - -#define MAX_DNS_BUF_SIZE 256 ///< maximum size of DNS buffer. */ -/* - * @brief Maximum length of your queried Domain name - * @todo SHOULD BE defined it equal as or greater than your Domain name length + null character(1) - * @note SHOULD BE careful to stack overflow because it is allocated 1.5 times as MAX_DOMAIN_NAME in stack. - */ -#define MAX_DOMAIN_NAME 32 // for example "www.google.com" - -#define MAX_DNS_RETRY 2 ///< Requery Count -#define DNS_WAIT_TIME 4 ///< Wait response time. unit 1s. - -#define IPPORT_DOMAIN 53 ///< DNS server port number - -#define DNS_MSG_ID 0x1122 ///< ID for DNS message. You can be modified it any number -/* - * @brief DNS process initialize - * @param s : Socket number for DNS - * @param buf : Buffer for DNS message - */ -void DNS_init(uint8_t s, uint8_t * buf); - -/* - * @brief DNS process - * @details Send DNS query and receive DNS response - * @param dns_ip : DNS server ip address - * @param name : Domain name to be queried - * @param ip_from_dns : IP address from DNS server - * @return -1 : failed. @ref MAX_DOMIN_NAME is too small \n - * 0 : failed (Timeout or Parse error)\n - * 1 : success - * @note This function blocks until success or fail. max time = @ref MAX_DNS_RETRY * @ref DNS_WAIT_TIME - */ -int8_t DNS_run(uint8_t * dns_ip, uint8_t * name, uint8_t * ip_from_dns); - -#endif /* _DNS_H_ */ diff --git a/extmod/axtls-include/config.h b/extmod/axtls-include/config.h new file mode 100644 index 0000000000..4cb1aed9ca --- /dev/null +++ b/extmod/axtls-include/config.h @@ -0,0 +1,117 @@ +/* + * Automatically generated header file: don't edit + */ + +#define HAVE_DOT_CONFIG 1 +#define CONFIG_PLATFORM_LINUX 1 +#undef CONFIG_PLATFORM_CYGWIN +#undef CONFIG_PLATFORM_WIN32 + +/* + * General Configuration + */ +#define PREFIX "/usr/local" +#undef CONFIG_DEBUG +#undef CONFIG_STRIP_UNWANTED_SECTIONS +#undef CONFIG_VISUAL_STUDIO_7_0 +#undef CONFIG_VISUAL_STUDIO_8_0 +#undef CONFIG_VISUAL_STUDIO_10_0 +#define CONFIG_VISUAL_STUDIO_7_0_BASE "" +#define CONFIG_VISUAL_STUDIO_8_0_BASE "" +#define CONFIG_VISUAL_STUDIO_10_0_BASE "" +#define CONFIG_EXTRA_CFLAGS_OPTIONS "" +#define CONFIG_EXTRA_LDFLAGS_OPTIONS "" + +/* + * SSL Library + */ +#undef CONFIG_SSL_SERVER_ONLY +#undef CONFIG_SSL_CERT_VERIFICATION +#undef CONFIG_SSL_FULL_MODE +#define CONFIG_SSL_SKELETON_MODE 1 +#define CONFIG_SSL_ENABLE_SERVER 1 +#define CONFIG_SSL_ENABLE_CLIENT 1 +#undef CONFIG_SSL_DIAGNOSTICS +#define CONFIG_SSL_PROT_LOW 1 +#undef CONFIG_SSL_PROT_MEDIUM +#undef CONFIG_SSL_PROT_HIGH +#define CONFIG_SSL_AES 1 +#define CONFIG_SSL_USE_DEFAULT_KEY 1 +#define CONFIG_SSL_PRIVATE_KEY_LOCATION "" +#define CONFIG_SSL_PRIVATE_KEY_PASSWORD "" +#define CONFIG_SSL_X509_CERT_LOCATION "" +#undef CONFIG_SSL_GENERATE_X509_CERT +#define CONFIG_SSL_X509_COMMON_NAME "" +#define CONFIG_SSL_X509_ORGANIZATION_NAME "" +#define CONFIG_SSL_X509_ORGANIZATION_UNIT_NAME "" +#undef CONFIG_SSL_HAS_PEM +#undef CONFIG_SSL_USE_PKCS12 +#define CONFIG_SSL_EXPIRY_TIME +#define CONFIG_X509_MAX_CA_CERTS 0 +#define CONFIG_SSL_MAX_CERTS 3 +#undef CONFIG_SSL_CTX_MUTEXING +#undef CONFIG_USE_DEV_URANDOM +#undef CONFIG_WIN32_USE_CRYPTO_LIB +#undef CONFIG_OPENSSL_COMPATIBLE +#undef CONFIG_PERFORMANCE_TESTING +#undef CONFIG_SSL_TEST +#undef CONFIG_AXTLSWRAP +#undef CONFIG_AXHTTPD +#undef CONFIG_HTTP_STATIC_BUILD +#define CONFIG_HTTP_PORT +#define CONFIG_HTTP_HTTPS_PORT +#define CONFIG_HTTP_SESSION_CACHE_SIZE +#define CONFIG_HTTP_WEBROOT "" +#define CONFIG_HTTP_TIMEOUT +#undef CONFIG_HTTP_HAS_CGI +#define CONFIG_HTTP_CGI_EXTENSIONS "" +#undef CONFIG_HTTP_ENABLE_LUA +#define CONFIG_HTTP_LUA_PREFIX "" +#undef CONFIG_HTTP_BUILD_LUA +#define CONFIG_HTTP_CGI_LAUNCHER "" +#undef CONFIG_HTTP_DIRECTORIES +#undef CONFIG_HTTP_HAS_AUTHORIZATION +#undef CONFIG_HTTP_HAS_IPV6 +#undef CONFIG_HTTP_ENABLE_DIFFERENT_USER +#define CONFIG_HTTP_USER "" +#undef CONFIG_HTTP_VERBOSE +#undef CONFIG_HTTP_IS_DAEMON + +/* + * Language Bindings + */ +#undef CONFIG_BINDINGS +#undef CONFIG_CSHARP_BINDINGS +#undef CONFIG_VBNET_BINDINGS +#define CONFIG_DOT_NET_FRAMEWORK_BASE "" +#undef CONFIG_JAVA_BINDINGS +#define CONFIG_JAVA_HOME "" +#undef CONFIG_PERL_BINDINGS +#define CONFIG_PERL_CORE "" +#define CONFIG_PERL_LIB "" +#undef CONFIG_LUA_BINDINGS +#define CONFIG_LUA_CORE "" + +/* + * Samples + */ +#undef CONFIG_SAMPLES +#undef CONFIG_C_SAMPLES +#undef CONFIG_CSHARP_SAMPLES +#undef CONFIG_VBNET_SAMPLES +#undef CONFIG_JAVA_SAMPLES +#undef CONFIG_PERL_SAMPLES +#undef CONFIG_LUA_SAMPLES +#undef CONFIG_BIGINT_CLASSICAL +#undef CONFIG_BIGINT_MONTGOMERY +#undef CONFIG_BIGINT_BARRETT +#undef CONFIG_BIGINT_CRT +#undef CONFIG_BIGINT_KARATSUBA +#define MUL_KARATSUBA_THRESH +#define SQU_KARATSUBA_THRESH +#undef CONFIG_BIGINT_SLIDING_WINDOW +#undef CONFIG_BIGINT_SQUARE +#undef CONFIG_BIGINT_CHECK_ON +#undef CONFIG_INTEGER_32BIT +#undef CONFIG_INTEGER_16BIT +#undef CONFIG_INTEGER_8BIT diff --git a/extmod/axtls-include/version.h b/extmod/axtls-include/version.h new file mode 100644 index 0000000000..df2260e4c6 --- /dev/null +++ b/extmod/axtls-include/version.h @@ -0,0 +1 @@ +#define AXTLS_VERSION "(no version)" diff --git a/extmod/machine_mem.c b/extmod/machine_mem.c deleted file mode 100644 index 9597b32e6c..0000000000 --- a/extmod/machine_mem.c +++ /dev/null @@ -1,94 +0,0 @@ -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George -// -// SPDX-License-Identifier: MIT - -#include "py/runtime.h" -#include "extmod/machine_mem.h" - -#if MICROPY_PY_MACHINE - -// If you wish to override the functions for mapping the machine_mem read/write -// address, then add a #define for MICROPY_MACHINE_MEM_GET_READ_ADDR and/or -// MICROPY_MACHINE_MEM_GET_WRITE_ADDR in your mpconfigport.h. Since the -// prototypes are identical, it is allowable for both of the macros to evaluate -// the to same function. -// -// It is expected that the modmachine.c file for a given port will provide the -// implementations, if the default implementation isn't used. - -#if !defined(MICROPY_MACHINE_MEM_GET_READ_ADDR) || !defined(MICROPY_MACHINE_MEM_GET_WRITE_ADDR) -STATIC uintptr_t machine_mem_get_addr(mp_obj_t addr_o, uint align) { - uintptr_t addr = mp_obj_int_get_truncated(addr_o); - if ((addr & (align - 1)) != 0) { - mp_raise_ValueError_varg(translate("address %08x is not aligned to %d bytes"), addr, align); - } - return addr; -} -#if !defined(MICROPY_MACHINE_MEM_GET_READ_ADDR) -#define MICROPY_MACHINE_MEM_GET_READ_ADDR machine_mem_get_addr -#endif -#if !defined(MICROPY_MACHINE_MEM_GET_WRITE_ADDR) -#define MICROPY_MACHINE_MEM_GET_WRITE_ADDR machine_mem_get_addr -#endif -#endif - -STATIC void machine_mem_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - (void)kind; - machine_mem_obj_t *self = MP_OBJ_TO_PTR(self_in); - mp_printf(print, "<%u-bit memory>", 8 * self->elem_size); -} - -STATIC mp_obj_t machine_mem_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { - // TODO support slice index to read/write multiple values at once - machine_mem_obj_t *self = MP_OBJ_TO_PTR(self_in); - if (value == MP_OBJ_NULL) { - // delete - return MP_OBJ_NULL; // op not supported - } else if (value == MP_OBJ_SENTINEL) { - // load - uintptr_t addr = MICROPY_MACHINE_MEM_GET_READ_ADDR(index, self->elem_size); - uint32_t val; - switch (self->elem_size) { - case 1: - val = (*(uint8_t *)addr); - break; - case 2: - val = (*(uint16_t *)addr); - break; - default: - val = (*(uint32_t *)addr); - break; - } - return mp_obj_new_int(val); - } else { - // store - uintptr_t addr = MICROPY_MACHINE_MEM_GET_WRITE_ADDR(index, self->elem_size); - uint32_t val = mp_obj_get_int_truncated(value); - switch (self->elem_size) { - case 1: - (*(uint8_t *)addr) = val; - break; - case 2: - (*(uint16_t *)addr) = val; - break; - default: - (*(uint32_t *)addr) = val; - break; - } - return mp_const_none; - } -} - -const mp_obj_type_t machine_mem_type = { - { &mp_type_type }, - .name = MP_QSTR_mem, - .print = machine_mem_print, - .subscr = machine_mem_subscr, -}; - -const machine_mem_obj_t machine_mem8_obj = {{&machine_mem_type}, 1}; -const machine_mem_obj_t machine_mem16_obj = {{&machine_mem_type}, 2}; -const machine_mem_obj_t machine_mem32_obj = {{&machine_mem_type}, 4}; - -#endif // MICROPY_PY_MACHINE diff --git a/extmod/machine_mem.h b/extmod/machine_mem.h deleted file mode 100644 index 735887c60e..0000000000 --- a/extmod/machine_mem.h +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2015 Damien P. George -// -// SPDX-License-Identifier: MIT - -#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H -#define MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H - -#include "py/obj.h" - -typedef struct _machine_mem_obj_t { - mp_obj_base_t base; - unsigned elem_size; // in bytes -} machine_mem_obj_t; - -extern const mp_obj_type_t machine_mem_type; - -extern const machine_mem_obj_t machine_mem8_obj; -extern const machine_mem_obj_t machine_mem16_obj; -extern const machine_mem_obj_t machine_mem32_obj; - -#if defined(MICROPY_MACHINE_MEM_GET_READ_ADDR) -uintptr_t MICROPY_MACHINE_MEM_GET_READ_ADDR(mp_obj_t addr_o, uint align); -#endif -#if defined(MICROPY_MACHINE_MEM_GET_WRITE_ADDR) -uintptr_t MICROPY_MACHINE_MEM_GET_WRITE_ADDR(mp_obj_t addr_o, uint align); -#endif - -#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H diff --git a/extmod/machine_pinbase.c b/extmod/machine_pinbase.c deleted file mode 100644 index a5e33c5602..0000000000 --- a/extmod/machine_pinbase.c +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) 2016 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// -// SPDX-License-Identifier: MIT - -#include "py/mpconfig.h" -#if MICROPY_PY_MACHINE - -#include "py/obj.h" -#include "py/runtime.h" -#include "extmod/virtpin.h" -#include "extmod/machine_pinbase.h" - -// PinBase class - -// As this is abstract class, its instance is null. -// But there should be an instance, as the rest of instance code -// expects that there will be concrete object for inheritance. -typedef struct _mp_pinbase_t { - mp_obj_base_t base; -} mp_pinbase_t; - -STATIC const mp_pinbase_t pinbase_singleton = { - .base = { &machine_pinbase_type }, -}; - -STATIC mp_obj_t pinbase_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { - (void)type; - (void)n_args; - (void)args; - (void)kw_args; - return MP_OBJ_FROM_PTR(&pinbase_singleton); -} - -mp_uint_t pinbase_ioctl(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode); -mp_uint_t pinbase_ioctl(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode) { - (void)errcode; - switch (request) { - case MP_PIN_READ: { - mp_obj_t dest[2]; - mp_load_method(obj, MP_QSTR_value, dest); - return mp_obj_get_int(mp_call_method_n_kw(0, 0, dest)); - } - case MP_PIN_WRITE: { - mp_obj_t dest[3]; - mp_load_method(obj, MP_QSTR_value, dest); - dest[2] = (arg == 0 ? mp_const_false : mp_const_true); - mp_call_method_n_kw(1, 0, dest); - return 0; - } - } - return -1; -} - -STATIC const mp_pin_p_t pinbase_pin_p = { - MP_PROTO_IMPLEMENT(MP_QSTR_protocol_pin) - .ioctl = pinbase_ioctl, -}; - -const mp_obj_type_t machine_pinbase_type = { - { &mp_type_type }, - .name = MP_QSTR_PinBase, - .make_new = pinbase_make_new, - .protocol = &pinbase_pin_p, -}; - -#endif // MICROPY_PY_MACHINE diff --git a/extmod/machine_pinbase.h b/extmod/machine_pinbase.h deleted file mode 100644 index b747563a1e..0000000000 --- a/extmod/machine_pinbase.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) 2016 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// -// SPDX-License-Identifier: MIT - -#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H -#define MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H - -#include "py/obj.h" - -extern const mp_obj_type_t machine_pinbase_type; - -#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H diff --git a/extmod/machine_pulse.c b/extmod/machine_pulse.c deleted file mode 100644 index eaee12b367..0000000000 --- a/extmod/machine_pulse.c +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2016 Damien P. George -// -// SPDX-License-Identifier: MIT - -#include "py/runtime.h" -#include "py/mperrno.h" -#include "extmod/machine_pulse.h" - -#if MICROPY_PY_MACHINE_PULSE - -mp_uint_t machine_time_pulse_us(mp_hal_pin_obj_t pin, int pulse_level, mp_uint_t timeout_us) { - mp_uint_t start = mp_hal_ticks_us(); - while (mp_hal_pin_read(pin) != pulse_level) { - if ((mp_uint_t)(mp_hal_ticks_us() - start) >= timeout_us) { - return (mp_uint_t)-2; - } - } - start = mp_hal_ticks_us(); - while (mp_hal_pin_read(pin) == pulse_level) { - if ((mp_uint_t)(mp_hal_ticks_us() - start) >= timeout_us) { - return (mp_uint_t)-1; - } - } - return mp_hal_ticks_us() - start; -} - -STATIC mp_obj_t machine_time_pulse_us_(size_t n_args, const mp_obj_t *args) { - mp_hal_pin_obj_t pin = mp_hal_get_pin_obj(args[0]); - int level = 0; - if (mp_obj_is_true(args[1])) { - level = 1; - } - mp_uint_t timeout_us = 1000000; - if (n_args > 2) { - timeout_us = mp_obj_get_int(args[2]); - } - mp_uint_t us = machine_time_pulse_us(pin, level, timeout_us); - // May return -1 or -2 in case of timeout - return mp_obj_new_int(us); -} -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_time_pulse_us_obj, 2, 3, machine_time_pulse_us_); - -#endif diff --git a/extmod/machine_pulse.h b/extmod/machine_pulse.h deleted file mode 100644 index a9b0ebc1b4..0000000000 --- a/extmod/machine_pulse.h +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2016 Damien P. George -// -// SPDX-License-Identifier: MIT - -#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H -#define MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H - -#include "py/obj.h" -#include "py/mphal.h" - -mp_uint_t machine_time_pulse_us(mp_hal_pin_obj_t pin, int pulse_level, mp_uint_t timeout_us); - -MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(machine_time_pulse_us_obj); - -#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H diff --git a/extmod/machine_signal.c b/extmod/machine_signal.c deleted file mode 100644 index a8e5ebc928..0000000000 --- a/extmod/machine_signal.c +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (c) 2017 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// -// SPDX-License-Identifier: MIT - -#include "py/mpconfig.h" -#if MICROPY_PY_MACHINE - -#include - -#include "py/obj.h" -#include "py/runtime.h" -#include "extmod/virtpin.h" -#include "extmod/machine_signal.h" - -// Signal class - -typedef struct _machine_signal_t { - mp_obj_base_t base; - mp_obj_t pin; - bool invert; -} machine_signal_t; - -STATIC mp_obj_t signal_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { - mp_obj_t pin = args[0]; - bool invert = false; - - #if defined(MICROPY_PY_MACHINE_PIN_MAKE_NEW) - mp_pin_p_t *pin_p = (mp_pin_t *)mp_proto_get(QSTR_pin_protocol, pin); - - if (pin_p == NULL) { - // If first argument isn't a Pin-like object, we filter out "invert" - // from keyword arguments and pass them all to the exported Pin - // constructor to create one. - mp_obj_t *pin_args = mp_local_alloc((n_args + n_kw * 2) * sizeof(mp_obj_t)); - memcpy(pin_args, args, n_args * sizeof(mp_obj_t)); - const mp_obj_t *src = args + n_args; - mp_obj_t *dst = pin_args + n_args; - mp_obj_t *sig_value = NULL; - for (size_t cnt = n_kw; cnt; cnt--) { - if (*src == MP_OBJ_NEW_QSTR(MP_QSTR_invert)) { - invert = mp_obj_is_true(src[1]); - n_kw--; - } else { - *dst++ = *src; - *dst++ = src[1]; - } - if (*src == MP_OBJ_NEW_QSTR(MP_QSTR_value)) { - // Value is pertained to Signal, so we should invert - // it for Pin if needed, and we should do it only when - // inversion status is guaranteedly known. - sig_value = dst - 1; - } - src += 2; - } - - if (invert && sig_value != NULL) { - *sig_value = mp_obj_is_true(*sig_value) ? MP_OBJ_NEW_SMALL_INT(0) : MP_OBJ_NEW_SMALL_INT(1); - } - - // Here we pass NULL as a type, hoping that mp_pin_make_new() - // will just ignore it as set a concrete type. If not, we'd need - // to expose port's "default" pin type too. - pin = MICROPY_PY_MACHINE_PIN_MAKE_NEW(NULL, n_args, n_kw, pin_args); - - mp_local_free(pin_args); - } else - #endif - // Otherwise there should be 1 or 2 args - { - if (n_args == 1) { - if (kw_args == NULL || kw_args->used == 0) { - } else if (kw_args->used == 1 && kw_args->table[0].key == MP_OBJ_NEW_QSTR(MP_QSTR_invert)) { - invert = mp_obj_is_true(kw_args->table[0].value); - } else { - goto error; - } - } else { - error: - mp_raise_TypeError(NULL); - } - } - - machine_signal_t *o = m_new_obj(machine_signal_t); - o->base.type = type; - o->pin = pin; - o->invert = invert; - return MP_OBJ_FROM_PTR(o); -} - -STATIC mp_uint_t signal_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { - (void)errcode; - machine_signal_t *self = MP_OBJ_TO_PTR(self_in); - - switch (request) { - case MP_PIN_READ: { - return mp_virtual_pin_read(self->pin) ^ self->invert; - } - case MP_PIN_WRITE: { - mp_virtual_pin_write(self->pin, arg ^ self->invert); - return 0; - } - } - return -1; -} - -// fast method for getting/setting signal value -STATIC mp_obj_t signal_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - mp_arg_check_num_kw_array(n_args, n_kw, 0, 1, false); - if (n_args == 0) { - // get pin - return MP_OBJ_NEW_SMALL_INT(mp_virtual_pin_read(self_in)); - } else { - // set pin - mp_virtual_pin_write(self_in, mp_obj_is_true(args[0])); - return mp_const_none; - } -} - -STATIC mp_obj_t signal_value(size_t n_args, const mp_obj_t *args) { - return signal_call(args[0], n_args - 1, 0, args + 1); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(signal_value_obj, 1, 2, signal_value); - -STATIC mp_obj_t signal_on(mp_obj_t self_in) { - mp_virtual_pin_write(self_in, 1); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(signal_on_obj, signal_on); - -STATIC mp_obj_t signal_off(mp_obj_t self_in) { - mp_virtual_pin_write(self_in, 0); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(signal_off_obj, signal_off); - -STATIC const mp_rom_map_elem_t signal_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&signal_value_obj) }, - { MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&signal_on_obj) }, - { MP_ROM_QSTR(MP_QSTR_off), MP_ROM_PTR(&signal_off_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(signal_locals_dict, signal_locals_dict_table); - -STATIC const mp_pin_p_t signal_pin_p = { - MP_PROTO_IMPLEMENT(MP_QSTR_protocol_pin) - .ioctl = signal_ioctl, -}; - -const mp_obj_type_t machine_signal_type = { - { &mp_type_type }, - .name = MP_QSTR_Signal, - .make_new = signal_make_new, - .call = signal_call, - .protocol = &signal_pin_p, - .locals_dict = (void *)&signal_locals_dict, -}; - -#endif // MICROPY_PY_MACHINE diff --git a/extmod/machine_signal.h b/extmod/machine_signal.h deleted file mode 100644 index 17ffe5563f..0000000000 --- a/extmod/machine_signal.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) 2017 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// -// SPDX-License-Identifier: MIT - -#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H -#define MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H - -#include "py/obj.h" - -extern const mp_obj_type_t machine_signal_type; - -#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H diff --git a/extmod/modbtree.c b/extmod/modbtree.c index ac996218ce..96b60018fe 100644 --- a/extmod/modbtree.c +++ b/extmod/modbtree.c @@ -331,7 +331,7 @@ STATIC mp_obj_t mod_btree_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t openinfo.psize = args.pagesize.u_int; openinfo.minkeypage = args.minkeypage.u_int; - DB *db = __bt_open(pos_args[0], &btree_stream_fvtable, &openinfo, /*dflags*/ 0); + DB *db = __bt_open(MP_OBJ_TO_PTR(pos_args[0]), &btree_stream_fvtable, &openinfo, /*dflags*/ 0); if (db == NULL) { mp_raise_OSError(errno); } diff --git a/extmod/modlwip.c b/extmod/modlwip.c deleted file mode 100644 index 6eb68d3fb9..0000000000 --- a/extmod/modlwip.c +++ /dev/null @@ -1,1449 +0,0 @@ -// Copyright (c) 2015 Galen Hazelwood -// Copyright (c) 2015-2017 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George -// -// SPDX-License-Identifier: MIT - -#include -#include - -#include "py/objlist.h" -#include "py/runtime.h" -#include "py/stream.h" -#include "py/mperrno.h" -#include "py/mphal.h" - -#include "lib/netutils/netutils.h" - -#include "lwip/init.h" -#include "lwip/tcp.h" -#include "lwip/udp.h" -// #include "lwip/raw.h" -#include "lwip/dns.h" -#include "lwip/igmp.h" -#if LWIP_VERSION_MAJOR < 2 -#include "lwip/timers.h" -#include "lwip/tcp_impl.h" -#else -#include "lwip/timeouts.h" -#include "lwip/priv/tcp_priv.h" -#endif - -#if 0 // print debugging info -#define DEBUG_printf DEBUG_printf -#else // don't print debugging info -#define DEBUG_printf(...) (void)0 -#endif - -// All socket options should be globally distinct, -// because we ignore option levels for efficiency. -#define IP_ADD_MEMBERSHIP 0x400 - -// For compatibilily with older lwIP versions. -#ifndef ip_set_option -#define ip_set_option(pcb, opt) ((pcb)->so_options |= (opt)) -#endif -#ifndef ip_reset_option -#define ip_reset_option(pcb, opt) ((pcb)->so_options &= ~(opt)) -#endif - -#if MICROPY_PY_LWIP_SLIP -#include "netif/slipif.h" -#include "lwip/sio.h" -#endif - -#if MICROPY_PY_LWIP_SLIP -/******************************************************************************/ -// Slip object for modlwip. Requires a serial driver for the port that supports -// the lwip serial callback functions. - -typedef struct _lwip_slip_obj_t { - mp_obj_base_t base; - struct netif lwip_netif; -} lwip_slip_obj_t; - -// Slip object is unique for now. Possibly can fix this later. FIXME -STATIC lwip_slip_obj_t lwip_slip_obj; - -// Declare these early. -void mod_lwip_register_poll(void (*poll)(void *arg), void *poll_arg); -void mod_lwip_deregister_poll(void (*poll)(void *arg), void *poll_arg); - -STATIC void slip_lwip_poll(void *netif) { - slipif_poll((struct netif *)netif); -} - -STATIC const mp_obj_type_t lwip_slip_type; - -// lwIP SLIP callback functions -sio_fd_t sio_open(u8_t dvnum) { - // We support singleton SLIP interface, so just return any truish value. - return (sio_fd_t)1; -} - -void sio_send(u8_t c, sio_fd_t fd) { - mp_obj_type_t *type = mp_obj_get_type(MP_STATE_VM(lwip_slip_stream)); - int error; - type->stream_p->write(MP_STATE_VM(lwip_slip_stream), &c, 1, &error); -} - -u32_t sio_tryread(sio_fd_t fd, u8_t *data, u32_t len) { - mp_obj_type_t *type = mp_obj_get_type(MP_STATE_VM(lwip_slip_stream)); - int error; - mp_uint_t out_sz = type->stream_p->read(MP_STATE_VM(lwip_slip_stream), data, len, &error); - if (out_sz == MP_STREAM_ERROR) { - if (mp_is_nonblocking_error(error)) { - return 0; - } - // Can't do much else, can we? - return 0; - } - return out_sz; -} - -// constructor lwip.slip(device=integer, iplocal=string, ipremote=string) -STATIC mp_obj_t lwip_slip_make_new(mp_obj_t type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - mp_arg_check_num(n_args, n_kw, 3, 3, false); - - lwip_slip_obj.base.type = &lwip_slip_type; - - MP_STATE_VM(lwip_slip_stream) = args[0]; - - ip_addr_t iplocal, ipremote; - if (!ipaddr_aton(mp_obj_str_get_str(args[1]), &iplocal)) { - mp_raise_ValueError("not a valid local IP"); - } - if (!ipaddr_aton(mp_obj_str_get_str(args[2]), &ipremote)) { - mp_raise_ValueError("not a valid remote IP"); - } - - struct netif *n = &lwip_slip_obj.lwip_netif; - if (netif_add(n, &iplocal, IP_ADDR_BROADCAST, &ipremote, NULL, slipif_init, ip_input) == NULL) { - mp_raise_ValueError("out of memory"); - } - netif_set_up(n); - netif_set_default(n); - mod_lwip_register_poll(slip_lwip_poll, n); - - return (mp_obj_t)&lwip_slip_obj; -} - -STATIC mp_obj_t lwip_slip_status(mp_obj_t self_in) { - // Null function for now. - return mp_const_none; -} - -STATIC MP_DEFINE_CONST_FUN_OBJ_1(lwip_slip_status_obj, lwip_slip_status); - -STATIC const mp_rom_map_elem_t lwip_slip_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&lwip_slip_status_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(lwip_slip_locals_dict, lwip_slip_locals_dict_table); - -STATIC const mp_obj_type_t lwip_slip_type = { - { &mp_type_type }, - .name = MP_QSTR_slip, - .make_new = lwip_slip_make_new, - .locals_dict = (mp_obj_dict_t *)&lwip_slip_locals_dict, -}; - -#endif // MICROPY_PY_LWIP_SLIP - -/******************************************************************************/ -// Table to convert lwIP err_t codes to socket errno codes, from the lwIP -// socket API. - -// lwIP 2 changed LWIP_VERSION and it can no longer be used in macros, -// so we define our own equivalent version that can. -#define LWIP_VERSION_MACRO (LWIP_VERSION_MAJOR << 24 | LWIP_VERSION_MINOR << 16 \ - | LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC) - -// Extension to lwIP error codes -#define _ERR_BADF -16 -// TODO: We just know that change happened somewhere between 1.4.0 and 1.4.1, -// investigate in more detail. -#if LWIP_VERSION_MACRO < 0x01040100 -static const int error_lookup_table[] = { - 0, /* ERR_OK 0 No error, everything OK. */ - MP_ENOMEM, /* ERR_MEM -1 Out of memory error. */ - MP_ENOBUFS, /* ERR_BUF -2 Buffer error. */ - MP_EWOULDBLOCK, /* ERR_TIMEOUT -3 Timeout */ - MP_EHOSTUNREACH, /* ERR_RTE -4 Routing problem. */ - MP_EINPROGRESS, /* ERR_INPROGRESS -5 Operation in progress */ - MP_EINVAL, /* ERR_VAL -6 Illegal value. */ - MP_EWOULDBLOCK, /* ERR_WOULDBLOCK -7 Operation would block. */ - - MP_ECONNABORTED, /* ERR_ABRT -8 Connection aborted. */ - MP_ECONNRESET, /* ERR_RST -9 Connection reset. */ - MP_ENOTCONN, /* ERR_CLSD -10 Connection closed. */ - MP_ENOTCONN, /* ERR_CONN -11 Not connected. */ - MP_EIO, /* ERR_ARG -12 Illegal argument. */ - MP_EADDRINUSE, /* ERR_USE -13 Address in use. */ - -1, /* ERR_IF -14 Low-level netif error */ - MP_EALREADY, /* ERR_ISCONN -15 Already connected. */ - MP_EBADF, /* _ERR_BADF -16 Closed socket (null pcb) */ -}; -#elif LWIP_VERSION_MACRO < 0x02000000 -static const int error_lookup_table[] = { - 0, /* ERR_OK 0 No error, everything OK. */ - MP_ENOMEM, /* ERR_MEM -1 Out of memory error. */ - MP_ENOBUFS, /* ERR_BUF -2 Buffer error. */ - MP_EWOULDBLOCK, /* ERR_TIMEOUT -3 Timeout */ - MP_EHOSTUNREACH, /* ERR_RTE -4 Routing problem. */ - MP_EINPROGRESS, /* ERR_INPROGRESS -5 Operation in progress */ - MP_EINVAL, /* ERR_VAL -6 Illegal value. */ - MP_EWOULDBLOCK, /* ERR_WOULDBLOCK -7 Operation would block. */ - - MP_EADDRINUSE, /* ERR_USE -8 Address in use. */ - MP_EALREADY, /* ERR_ISCONN -9 Already connected. */ - MP_ECONNABORTED, /* ERR_ABRT -10 Connection aborted. */ - MP_ECONNRESET, /* ERR_RST -11 Connection reset. */ - MP_ENOTCONN, /* ERR_CLSD -12 Connection closed. */ - MP_ENOTCONN, /* ERR_CONN -13 Not connected. */ - MP_EIO, /* ERR_ARG -14 Illegal argument. */ - -1, /* ERR_IF -15 Low-level netif error */ - MP_EBADF, /* _ERR_BADF -16 Closed socket (null pcb) */ -}; -#else -// Matches lwIP 2.0.3 -#undef _ERR_BADF -#define _ERR_BADF -17 -static const int error_lookup_table[] = { - 0, /* ERR_OK 0 No error, everything OK */ - MP_ENOMEM, /* ERR_MEM -1 Out of memory error */ - MP_ENOBUFS, /* ERR_BUF -2 Buffer error */ - MP_EWOULDBLOCK, /* ERR_TIMEOUT -3 Timeout */ - MP_EHOSTUNREACH, /* ERR_RTE -4 Routing problem */ - MP_EINPROGRESS, /* ERR_INPROGRESS -5 Operation in progress */ - MP_EINVAL, /* ERR_VAL -6 Illegal value */ - MP_EWOULDBLOCK, /* ERR_WOULDBLOCK -7 Operation would block */ - MP_EADDRINUSE, /* ERR_USE -8 Address in use */ - MP_EALREADY, /* ERR_ALREADY -9 Already connecting */ - MP_EALREADY, /* ERR_ISCONN -10 Conn already established */ - MP_ENOTCONN, /* ERR_CONN -11 Not connected */ - -1, /* ERR_IF -12 Low-level netif error */ - MP_ECONNABORTED, /* ERR_ABRT -13 Connection aborted */ - MP_ECONNRESET, /* ERR_RST -14 Connection reset */ - MP_ENOTCONN, /* ERR_CLSD -15 Connection closed */ - MP_EIO, /* ERR_ARG -16 Illegal argument. */ - MP_EBADF, /* _ERR_BADF -17 Closed socket (null pcb) */ -}; -#endif - -/*******************************************************************************/ -// The socket object provided by lwip.socket. - -#define MOD_NETWORK_AF_INET (2) -#define MOD_NETWORK_AF_INET6 (10) - -#define MOD_NETWORK_SOCK_STREAM (1) -#define MOD_NETWORK_SOCK_DGRAM (2) -#define MOD_NETWORK_SOCK_RAW (3) - -typedef struct _lwip_socket_obj_t { - mp_obj_base_t base; - - volatile union { - struct tcp_pcb *tcp; - struct udp_pcb *udp; - } pcb; - volatile union { - struct pbuf *pbuf; - struct tcp_pcb *connection; - } incoming; - mp_obj_t callback; - byte peer[4]; - mp_uint_t peer_port; - mp_uint_t timeout; - uint16_t recv_offset; - - uint8_t domain; - uint8_t type; - - #define STATE_NEW 0 - #define STATE_CONNECTING 1 - #define STATE_CONNECTED 2 - #define STATE_PEER_CLOSED 3 - // Negative value is lwIP error - int8_t state; -} lwip_socket_obj_t; - -static inline void poll_sockets(void) { - #ifdef MICROPY_EVENT_POLL_HOOK - MICROPY_EVENT_POLL_HOOK; - #else - mp_hal_delay_ms(1); - #endif -} - -/*******************************************************************************/ -// Callback functions for the lwIP raw API. - -static inline void exec_user_callback(lwip_socket_obj_t *socket) { - if (socket->callback != MP_OBJ_NULL) { - mp_call_function_1_protected(socket->callback, socket); - } -} - -// Callback for incoming UDP packets. We simply stash the packet and the source address, -// in case we need it for recvfrom. -#if LWIP_VERSION_MAJOR < 2 -STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, ip_addr_t *addr, u16_t port) -#else -STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) -#endif -{ - lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; - - if (socket->incoming.pbuf != NULL) { - // That's why they call it "unreliable". No room in the inn, drop the packet. - pbuf_free(p); - } else { - socket->incoming.pbuf = p; - socket->peer_port = (mp_uint_t)port; - memcpy(&socket->peer, addr, sizeof(socket->peer)); - } -} - -// Callback for general tcp errors. -STATIC void _lwip_tcp_error(void *arg, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; - - // Pass the error code back via the connection variable. - socket->state = err; - // If we got here, the lwIP stack either has deallocated or will deallocate the pcb. - socket->pcb.tcp = NULL; -} - -// Callback for tcp connection requests. Error code err is unused. (See tcp.h) -STATIC err_t _lwip_tcp_connected(void *arg, struct tcp_pcb *tpcb, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; - - socket->state = STATE_CONNECTED; - return ERR_OK; -} - -// By default, a child socket of listen socket is created with recv -// handler which discards incoming pbuf's. We don't want to do that, -// so set this handler which requests lwIP to keep pbuf's and deliver -// them later. We cannot cache pbufs in child socket on Python side, -// until it is created in accept(). -STATIC err_t _lwip_tcp_recv_unaccepted(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) { - return ERR_BUF; -} - -// "Poll" (idle) callback to be called ASAP after accept callback -// to execute Python callback function, as it can't be executed -// from accept callback itself. -STATIC err_t _lwip_tcp_accept_finished(void *arg, struct tcp_pcb *pcb) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; - tcp_poll(pcb, NULL, 0); - exec_user_callback(socket); - return ERR_OK; -} - -// Callback for incoming tcp connections. -STATIC err_t _lwip_tcp_accept(void *arg, struct tcp_pcb *newpcb, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; - tcp_recv(newpcb, _lwip_tcp_recv_unaccepted); - - if (socket->incoming.connection != NULL) { - DEBUG_printf("_lwip_tcp_accept: Tried to queue >1 pcb waiting for accept\n"); - // We need to handle this better. This single-level structure makes the - // backlog setting kind of pointless. FIXME - return ERR_BUF; - } else { - socket->incoming.connection = newpcb; - if (socket->callback != MP_OBJ_NULL) { - // Schedule accept callback to be called when lwIP is done - // with processing this incoming connection on its side and - // is idle. - tcp_poll(newpcb, _lwip_tcp_accept_finished, 1); - } - return ERR_OK; - } -} - -// Callback for inbound tcp packets. -STATIC err_t _lwip_tcp_recv(void *arg, struct tcp_pcb *tcpb, struct pbuf *p, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; - - if (p == NULL) { - // Other side has closed connection. - DEBUG_printf("_lwip_tcp_recv[%p]: other side closed connection\n", socket); - socket->state = STATE_PEER_CLOSED; - exec_user_callback(socket); - return ERR_OK; - } - - if (socket->incoming.pbuf == NULL) { - socket->incoming.pbuf = p; - } else { - #ifdef SOCKET_SINGLE_PBUF - return ERR_BUF; - #else - pbuf_cat(socket->incoming.pbuf, p); - #endif - } - - exec_user_callback(socket); - - return ERR_OK; -} - -/*******************************************************************************/ -// Functions for socket send/receive operations. Socket send/recv and friends call -// these to do the work. - -// Helper function for send/sendto to handle UDP packets. -STATIC mp_uint_t lwip_udp_send(lwip_socket_obj_t *socket, const byte *buf, mp_uint_t len, byte *ip, mp_uint_t port, int *_errno) { - if (len > 0xffff) { - // Any packet that big is probably going to fail the pbuf_alloc anyway, but may as well try - len = 0xffff; - } - - // FIXME: maybe PBUF_ROM? - struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM); - if (p == NULL) { - *_errno = MP_ENOMEM; - return -1; - } - - memcpy(p->payload, buf, len); - - err_t err; - if (ip == NULL) { - err = udp_send(socket->pcb.udp, p); - } else { - ip_addr_t dest; - IP4_ADDR(&dest, ip[0], ip[1], ip[2], ip[3]); - err = udp_sendto(socket->pcb.udp, p, &dest, port); - } - - pbuf_free(p); - - // udp_sendto can return 1 on occasion for ESP8266 port. It's not known why - // but it seems that the send actually goes through without error in this case. - // So we treat such cases as a success until further investigation. - if (err != ERR_OK && err != 1) { - *_errno = error_lookup_table[-err]; - return -1; - } - - return len; -} - -// Helper function for recv/recvfrom to handle UDP packets -STATIC mp_uint_t lwip_udp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_t len, byte *ip, mp_uint_t *port, int *_errno) { - - if (socket->incoming.pbuf == NULL) { - if (socket->timeout != -1) { - for (mp_uint_t retries = socket->timeout / 100; retries--;) { - mp_hal_delay_ms(100); - if (socket->incoming.pbuf != NULL) { - break; - } - } - if (socket->incoming.pbuf == NULL) { - *_errno = MP_ETIMEDOUT; - return -1; - } - } else { - while (socket->incoming.pbuf == NULL) { - poll_sockets(); - } - } - } - - if (ip != NULL) { - memcpy(ip, &socket->peer, sizeof(socket->peer)); - *port = socket->peer_port; - } - - struct pbuf *p = socket->incoming.pbuf; - - u16_t result = pbuf_copy_partial(p, buf, ((p->tot_len > len) ? len : p->tot_len), 0); - pbuf_free(p); - socket->incoming.pbuf = NULL; - - return (mp_uint_t)result; -} - -// For use in stream virtual methods -#define STREAM_ERROR_CHECK(socket) \ - if (socket->state < 0) { \ - *_errno = error_lookup_table[-socket->state]; \ - return MP_STREAM_ERROR; \ - } \ - assert(socket->pcb.tcp); - - -// Helper function for send/sendto to handle TCP packets -STATIC mp_uint_t lwip_tcp_send(lwip_socket_obj_t *socket, const byte *buf, mp_uint_t len, int *_errno) { - // Check for any pending errors - STREAM_ERROR_CHECK(socket); - - u16_t available = tcp_sndbuf(socket->pcb.tcp); - - if (available == 0) { - // Non-blocking socket - if (socket->timeout == 0) { - *_errno = MP_EAGAIN; - return MP_STREAM_ERROR; - } - - mp_uint_t start = mp_hal_ticks_ms(); - // Assume that STATE_PEER_CLOSED may mean half-closed connection, where peer closed it - // sending direction, but not receiving. Consequently, check for both STATE_CONNECTED - // and STATE_PEER_CLOSED as normal conditions and still waiting for buffers to be sent. - // If peer fully closed socket, we would have socket->state set to ERR_RST (connection - // reset) by error callback. - // Avoid sending too small packets, so wait until at least 16 bytes available - while (socket->state >= STATE_CONNECTED && (available = tcp_sndbuf(socket->pcb.tcp)) < 16) { - if (socket->timeout != -1 && mp_hal_ticks_ms() - start > socket->timeout) { - *_errno = MP_ETIMEDOUT; - return MP_STREAM_ERROR; - } - poll_sockets(); - } - - // While we waited, something could happen - STREAM_ERROR_CHECK(socket); - } - - u16_t write_len = MIN(available, len); - - err_t err = tcp_write(socket->pcb.tcp, buf, write_len, TCP_WRITE_FLAG_COPY); - - // If the output buffer is getting full then send the data to the lower layers - if (err == ERR_OK && tcp_sndbuf(socket->pcb.tcp) < TCP_SND_BUF / 4) { - err = tcp_output(socket->pcb.tcp); - } - - if (err != ERR_OK) { - *_errno = error_lookup_table[-err]; - return MP_STREAM_ERROR; - } - - return write_len; -} - -// Helper function for recv/recvfrom to handle TCP packets -STATIC mp_uint_t lwip_tcp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_t len, int *_errno) { - // Check for any pending errors - STREAM_ERROR_CHECK(socket); - - if (socket->incoming.pbuf == NULL) { - - // Non-blocking socket - if (socket->timeout == 0) { - if (socket->state == STATE_PEER_CLOSED) { - return 0; - } - *_errno = MP_EAGAIN; - return -1; - } - - mp_uint_t start = mp_hal_ticks_ms(); - while (socket->state == STATE_CONNECTED && socket->incoming.pbuf == NULL) { - if (socket->timeout != -1 && mp_hal_ticks_ms() - start > socket->timeout) { - *_errno = MP_ETIMEDOUT; - return -1; - } - poll_sockets(); - } - - if (socket->state == STATE_PEER_CLOSED) { - if (socket->incoming.pbuf == NULL) { - // socket closed and no data left in buffer - return 0; - } - } else if (socket->state != STATE_CONNECTED) { - assert(socket->state < 0); - *_errno = error_lookup_table[-socket->state]; - return -1; - } - } - - assert(socket->pcb.tcp != NULL); - - struct pbuf *p = socket->incoming.pbuf; - - mp_uint_t remaining = p->len - socket->recv_offset; - if (len > remaining) { - len = remaining; - } - - memcpy(buf, (byte *)p->payload + socket->recv_offset, len); - - remaining -= len; - if (remaining == 0) { - socket->incoming.pbuf = p->next; - // If we don't ref here, free() will free the entire chain, - // if we ref, it does what we need: frees 1st buf, and decrements - // next buf's refcount back to 1. - pbuf_ref(p->next); - pbuf_free(p); - socket->recv_offset = 0; - } else { - socket->recv_offset += len; - } - tcp_recved(socket->pcb.tcp, len); - - return len; -} - -/*******************************************************************************/ -// The socket functions provided by lwip.socket. - -STATIC const mp_obj_type_t lwip_socket_type; - -STATIC void lwip_socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - lwip_socket_obj_t *self = self_in; - mp_printf(print, "", self->state, self->timeout, - self->incoming.pbuf, self->recv_offset); -} - -// FIXME: Only supports two arguments at present -STATIC mp_obj_t lwip_socket_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { - mp_arg_check_num(n_args, n_kw, 0, 4, false); - - lwip_socket_obj_t *socket = m_new_obj_with_finaliser(lwip_socket_obj_t); - socket->base.type = (mp_obj_t)&lwip_socket_type; - socket->domain = MOD_NETWORK_AF_INET; - socket->type = MOD_NETWORK_SOCK_STREAM; - socket->callback = MP_OBJ_NULL; - if (n_args >= 1) { - socket->domain = mp_obj_get_int(args[0]); - if (n_args >= 2) { - socket->type = mp_obj_get_int(args[1]); - } - } - - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: - socket->pcb.tcp = tcp_new(); - break; - case MOD_NETWORK_SOCK_DGRAM: - socket->pcb.udp = udp_new(); - break; - // case MOD_NETWORK_SOCK_RAW: socket->pcb.raw = raw_new(); break; - default: - mp_raise_OSError(MP_EINVAL); - } - - if (socket->pcb.tcp == NULL) { - mp_raise_OSError(MP_ENOMEM); - } - - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - // Register the socket object as our callback argument. - tcp_arg(socket->pcb.tcp, (void *)socket); - // Register our error callback. - tcp_err(socket->pcb.tcp, _lwip_tcp_error); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - // Register our receive callback now. Since UDP sockets don't require binding or connection - // before use, there's no other good time to do it. - udp_recv(socket->pcb.udp, _lwip_udp_incoming, (void *)socket); - break; - } - } - - socket->incoming.pbuf = NULL; - socket->timeout = -1; - socket->state = STATE_NEW; - socket->recv_offset = 0; - return socket; -} - -STATIC mp_obj_t lwip_socket_bind(mp_obj_t self_in, mp_obj_t addr_in) { - lwip_socket_obj_t *socket = self_in; - - uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; - mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_BIG); - - ip_addr_t bind_addr; - IP4_ADDR(&bind_addr, ip[0], ip[1], ip[2], ip[3]); - - err_t err = ERR_ARG; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - err = tcp_bind(socket->pcb.tcp, &bind_addr, port); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - err = udp_bind(socket->pcb.udp, &bind_addr, port); - break; - } - } - - if (err != ERR_OK) { - mp_raise_OSError(error_lookup_table[-err]); - } - - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_bind_obj, lwip_socket_bind); - -STATIC mp_obj_t lwip_socket_listen(mp_obj_t self_in, mp_obj_t backlog_in) { - lwip_socket_obj_t *socket = self_in; - mp_int_t backlog = mp_obj_get_int(backlog_in); - - if (socket->pcb.tcp == NULL) { - mp_raise_OSError(MP_EBADF); - } - if (socket->type != MOD_NETWORK_SOCK_STREAM) { - mp_raise_OSError(MP_EOPNOTSUPP); - } - - struct tcp_pcb *new_pcb = tcp_listen_with_backlog(socket->pcb.tcp, (u8_t)backlog); - if (new_pcb == NULL) { - mp_raise_OSError(MP_ENOMEM); - } - socket->pcb.tcp = new_pcb; - tcp_accept(new_pcb, _lwip_tcp_accept); - - // Socket is no longer considered "new" for purposes of polling - socket->state = STATE_CONNECTING; - - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_listen_obj, lwip_socket_listen); - -STATIC mp_obj_t lwip_socket_accept(mp_obj_t self_in) { - lwip_socket_obj_t *socket = self_in; - - if (socket->pcb.tcp == NULL) { - mp_raise_OSError(MP_EBADF); - } - if (socket->type != MOD_NETWORK_SOCK_STREAM) { - mp_raise_OSError(MP_EOPNOTSUPP); - } - // I need to do this because "tcp_accepted", later, is a macro. - struct tcp_pcb *listener = socket->pcb.tcp; - if (listener->state != LISTEN) { - mp_raise_OSError(MP_EINVAL); - } - - // accept incoming connection - if (socket->incoming.connection == NULL) { - if (socket->timeout == 0) { - mp_raise_OSError(MP_EAGAIN); - } else if (socket->timeout != -1) { - for (mp_uint_t retries = socket->timeout / 100; retries--;) { - mp_hal_delay_ms(100); - if (socket->incoming.connection != NULL) { - break; - } - } - if (socket->incoming.connection == NULL) { - mp_raise_OSError(MP_ETIMEDOUT); - } - } else { - while (socket->incoming.connection == NULL) { - poll_sockets(); - } - } - } - - // create new socket object - lwip_socket_obj_t *socket2 = m_new_obj_with_finaliser(lwip_socket_obj_t); - socket2->base.type = (mp_obj_t)&lwip_socket_type; - - // We get a new pcb handle... - socket2->pcb.tcp = socket->incoming.connection; - socket->incoming.connection = NULL; - - // ...and set up the new socket for it. - socket2->domain = MOD_NETWORK_AF_INET; - socket2->type = MOD_NETWORK_SOCK_STREAM; - socket2->incoming.pbuf = NULL; - socket2->timeout = socket->timeout; - socket2->state = STATE_CONNECTED; - socket2->recv_offset = 0; - socket2->callback = MP_OBJ_NULL; - tcp_arg(socket2->pcb.tcp, (void *)socket2); - tcp_err(socket2->pcb.tcp, _lwip_tcp_error); - tcp_recv(socket2->pcb.tcp, _lwip_tcp_recv); - - tcp_accepted(listener); - - // make the return value - uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; - memcpy(ip, &(socket2->pcb.tcp->remote_ip), sizeof(ip)); - mp_uint_t port = (mp_uint_t)socket2->pcb.tcp->remote_port; - mp_obj_tuple_t *client = mp_obj_new_tuple(2, NULL); - client->items[0] = socket2; - client->items[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG); - - return client; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(lwip_socket_accept_obj, lwip_socket_accept); - -STATIC mp_obj_t lwip_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) { - lwip_socket_obj_t *socket = self_in; - - if (socket->pcb.tcp == NULL) { - mp_raise_OSError(MP_EBADF); - } - - // get address - uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; - mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_BIG); - - ip_addr_t dest; - IP4_ADDR(&dest, ip[0], ip[1], ip[2], ip[3]); - - err_t err = ERR_ARG; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - if (socket->state != STATE_NEW) { - if (socket->state == STATE_CONNECTED) { - mp_raise_OSError(MP_EISCONN); - } else { - mp_raise_OSError(MP_EALREADY); - } - } - // Register our receive callback. - tcp_recv(socket->pcb.tcp, _lwip_tcp_recv); - socket->state = STATE_CONNECTING; - err = tcp_connect(socket->pcb.tcp, &dest, port, _lwip_tcp_connected); - if (err != ERR_OK) { - socket->state = STATE_NEW; - mp_raise_OSError(error_lookup_table[-err]); - } - socket->peer_port = (mp_uint_t)port; - memcpy(socket->peer, &dest, sizeof(socket->peer)); - // And now we wait... - if (socket->timeout != -1) { - for (mp_uint_t retries = socket->timeout / 100; retries--;) { - mp_hal_delay_ms(100); - if (socket->state != STATE_CONNECTING) { - break; - } - } - if (socket->state == STATE_CONNECTING) { - mp_raise_OSError(MP_EINPROGRESS); - } - } else { - while (socket->state == STATE_CONNECTING) { - poll_sockets(); - } - } - if (socket->state == STATE_CONNECTED) { - err = ERR_OK; - } else { - err = socket->state; - } - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - err = udp_connect(socket->pcb.udp, &dest, port); - break; - } - } - - if (err != ERR_OK) { - mp_raise_OSError(error_lookup_table[-err]); - } - - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_connect_obj, lwip_socket_connect); - -STATIC void lwip_socket_check_connected(lwip_socket_obj_t *socket) { - if (socket->pcb.tcp == NULL) { - // not connected - int _errno = error_lookup_table[-socket->state]; - socket->state = _ERR_BADF; - mp_raise_OSError(_errno); - } -} - -STATIC mp_obj_t lwip_socket_send(mp_obj_t self_in, mp_obj_t buf_in) { - lwip_socket_obj_t *socket = self_in; - int _errno; - - lwip_socket_check_connected(socket); - - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); - - mp_uint_t ret = 0; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - ret = lwip_tcp_send(socket, bufinfo.buf, bufinfo.len, &_errno); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_send(socket, bufinfo.buf, bufinfo.len, NULL, 0, &_errno); - break; - } - } - if (ret == -1) { - mp_raise_OSError(_errno); - } - - return mp_obj_new_int_from_uint(ret); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_send_obj, lwip_socket_send); - -STATIC mp_obj_t lwip_socket_recv(mp_obj_t self_in, mp_obj_t len_in) { - lwip_socket_obj_t *socket = self_in; - int _errno; - - lwip_socket_check_connected(socket); - - mp_int_t len = mp_obj_get_int(len_in); - vstr_t vstr; - vstr_init_len(&vstr, len); - - mp_uint_t ret = 0; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - ret = lwip_tcp_receive(socket, (byte *)vstr.buf, len, &_errno); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_receive(socket, (byte *)vstr.buf, len, NULL, NULL, &_errno); - break; - } - } - if (ret == -1) { - mp_raise_OSError(_errno); - } - - if (ret == 0) { - return mp_const_empty_bytes; - } - vstr.len = ret; - return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_recv_obj, lwip_socket_recv); - -STATIC mp_obj_t lwip_socket_sendto(mp_obj_t self_in, mp_obj_t data_in, mp_obj_t addr_in) { - lwip_socket_obj_t *socket = self_in; - int _errno; - - lwip_socket_check_connected(socket); - - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(data_in, &bufinfo, MP_BUFFER_READ); - - uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; - mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_BIG); - - mp_uint_t ret = 0; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - ret = lwip_tcp_send(socket, bufinfo.buf, bufinfo.len, &_errno); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_send(socket, bufinfo.buf, bufinfo.len, ip, port, &_errno); - break; - } - } - if (ret == -1) { - mp_raise_OSError(_errno); - } - - return mp_obj_new_int_from_uint(ret); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_3(lwip_socket_sendto_obj, lwip_socket_sendto); - -STATIC mp_obj_t lwip_socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in) { - lwip_socket_obj_t *socket = self_in; - int _errno; - - lwip_socket_check_connected(socket); - - mp_int_t len = mp_obj_get_int(len_in); - vstr_t vstr; - vstr_init_len(&vstr, len); - byte ip[4]; - mp_uint_t port; - - mp_uint_t ret = 0; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - memcpy(ip, &socket->peer, sizeof(socket->peer)); - port = (mp_uint_t)socket->peer_port; - ret = lwip_tcp_receive(socket, (byte *)vstr.buf, len, &_errno); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_receive(socket, (byte *)vstr.buf, len, ip, &port, &_errno); - break; - } - } - if (ret == -1) { - mp_raise_OSError(_errno); - } - - mp_obj_t tuple[2]; - if (ret == 0) { - tuple[0] = mp_const_empty_bytes; - } else { - vstr.len = ret; - tuple[0] = mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); - } - tuple[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG); - return mp_obj_new_tuple(2, tuple); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_recvfrom_obj, lwip_socket_recvfrom); - -STATIC mp_obj_t lwip_socket_sendall(mp_obj_t self_in, mp_obj_t buf_in) { - lwip_socket_obj_t *socket = self_in; - lwip_socket_check_connected(socket); - - int _errno; - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); - - mp_uint_t ret = 0; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - if (socket->timeout == 0) { - // Behavior of sendall() for non-blocking sockets isn't explicitly specified. - // But it's specified that "On error, an exception is raised, there is no - // way to determine how much data, if any, was successfully sent." Then, the - // most useful behavior is: check whether we will be able to send all of input - // data without EAGAIN, and if won't be, raise it without sending any. - if (bufinfo.len > tcp_sndbuf(socket->pcb.tcp)) { - mp_raise_OSError(MP_EAGAIN); - } - } - // TODO: In CPython3.5, socket timeout should apply to the - // entire sendall() operation, not to individual send() chunks. - while (bufinfo.len != 0) { - ret = lwip_tcp_send(socket, bufinfo.buf, bufinfo.len, &_errno); - if (ret == -1) { - mp_raise_OSError(_errno); - } - bufinfo.len -= ret; - bufinfo.buf = (char *)bufinfo.buf + ret; - } - break; - } - case MOD_NETWORK_SOCK_DGRAM: - mp_raise_NotImplementedError(NULL); - break; - } - - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_sendall_obj, lwip_socket_sendall); - -STATIC mp_obj_t lwip_socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) { - lwip_socket_obj_t *socket = self_in; - mp_uint_t timeout; - if (timeout_in == mp_const_none) { - timeout = -1; - } else { - #if MICROPY_PY_BUILTINS_FLOAT - timeout = 1000 * mp_obj_get_float(timeout_in); - #else - timeout = 1000 * mp_obj_get_int(timeout_in); - #endif - } - socket->timeout = timeout; - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_settimeout_obj, lwip_socket_settimeout); - -STATIC mp_obj_t lwip_socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) { - lwip_socket_obj_t *socket = self_in; - bool val = mp_obj_is_true(flag_in); - if (val) { - socket->timeout = -1; - } else { - socket->timeout = 0; - } - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_setblocking_obj, lwip_socket_setblocking); - -STATIC mp_obj_t lwip_socket_setsockopt(size_t n_args, const mp_obj_t *args) { - (void)n_args; // always 4 - lwip_socket_obj_t *socket = args[0]; - - int opt = mp_obj_get_int(args[2]); - if (opt == 20) { - if (args[3] == mp_const_none) { - socket->callback = MP_OBJ_NULL; - } else { - socket->callback = args[3]; - } - return mp_const_none; - } - - switch (opt) { - // level: SOL_SOCKET - case SOF_REUSEADDR: { - mp_int_t val = mp_obj_get_int(args[3]); - // Options are common for UDP and TCP pcb's. - if (val) { - ip_set_option(socket->pcb.tcp, SOF_REUSEADDR); - } else { - ip_reset_option(socket->pcb.tcp, SOF_REUSEADDR); - } - break; - } - - // level: IPPROTO_IP - case IP_ADD_MEMBERSHIP: { - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ); - if (bufinfo.len != sizeof(ip_addr_t) * 2) { - mp_raise_ValueError(NULL); - } - - // POSIX setsockopt has order: group addr, if addr, lwIP has it vice-versa - err_t err = igmp_joingroup((ip_addr_t *)bufinfo.buf + 1, bufinfo.buf); - if (err != ERR_OK) { - mp_raise_OSError(error_lookup_table[-err]); - } - break; - } - - default: - printf("Warning: lwip.setsockopt() not implemented\n"); - } - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_socket_setsockopt_obj, 4, 4, lwip_socket_setsockopt); - -STATIC mp_obj_t lwip_socket_makefile(size_t n_args, const mp_obj_t *args) { - (void)n_args; - return args[0]; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_socket_makefile_obj, 1, 3, lwip_socket_makefile); - -STATIC mp_uint_t lwip_socket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { - lwip_socket_obj_t *socket = self_in; - - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: - return lwip_tcp_receive(socket, buf, size, errcode); - case MOD_NETWORK_SOCK_DGRAM: - return lwip_udp_receive(socket, buf, size, NULL, NULL, errcode); - } - // Unreachable - return MP_STREAM_ERROR; -} - -STATIC mp_uint_t lwip_socket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { - lwip_socket_obj_t *socket = self_in; - - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: - return lwip_tcp_send(socket, buf, size, errcode); - case MOD_NETWORK_SOCK_DGRAM: - return lwip_udp_send(socket, buf, size, NULL, 0, errcode); - } - // Unreachable - return MP_STREAM_ERROR; -} - -STATIC mp_uint_t lwip_socket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { - lwip_socket_obj_t *socket = self_in; - mp_uint_t ret; - - if (request == MP_STREAM_POLL) { - uintptr_t flags = arg; - ret = 0; - - if (flags & MP_STREAM_POLL_RD && socket->incoming.pbuf != NULL) { - ret |= MP_STREAM_POLL_RD; - } - - // Note: pcb.tcp==NULL if state<0, and in this case we can't call tcp_sndbuf - if (flags & MP_STREAM_POLL_WR && socket->pcb.tcp != NULL && tcp_sndbuf(socket->pcb.tcp) > 0) { - ret |= MP_STREAM_POLL_WR; - } - - if (socket->state == STATE_NEW) { - // New sockets are not connected so set HUP - ret |= flags & MP_STREAM_POLL_HUP; - } else if (socket->state == STATE_PEER_CLOSED) { - // Peer-closed socket is both readable and writable: read will - // return EOF, write - error. Without this poll will hang on a - // socket which was closed by peer. - ret |= flags & (MP_STREAM_POLL_RD | MP_STREAM_POLL_WR); - } else if (socket->state == ERR_RST) { - // Socket was reset by peer, a write will return an error - ret |= flags & (MP_STREAM_POLL_WR | MP_STREAM_POLL_HUP); - } else if (socket->state < 0) { - // Socket in some other error state, use catch-all ERR flag - // TODO: may need to set other return flags here - ret |= flags & MP_STREAM_POLL_ERR; - } - - } else if (request == MP_STREAM_CLOSE) { - bool socket_is_listener = false; - - if (socket->pcb.tcp == NULL) { - return 0; - } - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - if (socket->pcb.tcp->state == LISTEN) { - socket_is_listener = true; - } - if (tcp_close(socket->pcb.tcp) != ERR_OK) { - DEBUG_printf("lwip_close: had to call tcp_abort()\n"); - tcp_abort(socket->pcb.tcp); - } - break; - } - case MOD_NETWORK_SOCK_DGRAM: - udp_remove(socket->pcb.udp); - break; - // case MOD_NETWORK_SOCK_RAW: raw_remove(socket->pcb.raw); break; - } - socket->pcb.tcp = NULL; - socket->state = _ERR_BADF; - if (socket->incoming.pbuf != NULL) { - if (!socket_is_listener) { - pbuf_free(socket->incoming.pbuf); - } else { - tcp_abort(socket->incoming.connection); - } - socket->incoming.pbuf = NULL; - } - ret = 0; - - } else { - *errcode = MP_EINVAL; - ret = MP_STREAM_ERROR; - } - - return ret; -} - -STATIC const mp_rom_map_elem_t lwip_socket_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) }, - { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, - { MP_ROM_QSTR(MP_QSTR_bind), MP_ROM_PTR(&lwip_socket_bind_obj) }, - { MP_ROM_QSTR(MP_QSTR_listen), MP_ROM_PTR(&lwip_socket_listen_obj) }, - { MP_ROM_QSTR(MP_QSTR_accept), MP_ROM_PTR(&lwip_socket_accept_obj) }, - { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&lwip_socket_connect_obj) }, - { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&lwip_socket_send_obj) }, - { MP_ROM_QSTR(MP_QSTR_recv), MP_ROM_PTR(&lwip_socket_recv_obj) }, - { MP_ROM_QSTR(MP_QSTR_sendto), MP_ROM_PTR(&lwip_socket_sendto_obj) }, - { MP_ROM_QSTR(MP_QSTR_recvfrom), MP_ROM_PTR(&lwip_socket_recvfrom_obj) }, - { MP_ROM_QSTR(MP_QSTR_sendall), MP_ROM_PTR(&lwip_socket_sendall_obj) }, - { MP_ROM_QSTR(MP_QSTR_settimeout), MP_ROM_PTR(&lwip_socket_settimeout_obj) }, - { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&lwip_socket_setblocking_obj) }, - { MP_ROM_QSTR(MP_QSTR_setsockopt), MP_ROM_PTR(&lwip_socket_setsockopt_obj) }, - { MP_ROM_QSTR(MP_QSTR_makefile), MP_ROM_PTR(&lwip_socket_makefile_obj) }, - - { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, - { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, - { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, - { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, -}; -STATIC MP_DEFINE_CONST_DICT(lwip_socket_locals_dict, lwip_socket_locals_dict_table); - -STATIC const mp_stream_p_t lwip_socket_stream_p = { - MP_PROTO_IMPLEMENT(MP_QSTR_protocol_stream) - .read = lwip_socket_read, - .write = lwip_socket_write, - .ioctl = lwip_socket_ioctl, -}; - -STATIC const mp_obj_type_t lwip_socket_type = { - { &mp_type_type }, - .name = MP_QSTR_socket, - .print = lwip_socket_print, - .make_new = lwip_socket_make_new, - .protocol = &lwip_socket_stream_p, - .locals_dict = (mp_obj_dict_t *)&lwip_socket_locals_dict, -}; - -/******************************************************************************/ -// Support functions for memory protection. lwIP has its own memory management -// routines for its internal structures, and since they might be called in -// interrupt handlers, they need some protection. -sys_prot_t sys_arch_protect() { - return (sys_prot_t)MICROPY_BEGIN_ATOMIC_SECTION(); -} - -void sys_arch_unprotect(sys_prot_t state) { - MICROPY_END_ATOMIC_SECTION((mp_uint_t)state); -} - -/******************************************************************************/ -// Polling callbacks for the interfaces connected to lwIP. Right now it calls -// itself a "list" but isn't; we only support a single interface. - -typedef struct nic_poll { - void (*poll)(void *arg); - void *poll_arg; -} nic_poll_t; - -STATIC nic_poll_t lwip_poll_list; - -void mod_lwip_register_poll(void (*poll)(void *arg), void *poll_arg) { - lwip_poll_list.poll = poll; - lwip_poll_list.poll_arg = poll_arg; -} - -void mod_lwip_deregister_poll(void (*poll)(void *arg), void *poll_arg) { - lwip_poll_list.poll = NULL; -} - -/******************************************************************************/ -// The lwip global functions. - -STATIC mp_obj_t mod_lwip_reset() { - lwip_init(); - lwip_poll_list.poll = NULL; - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_0(mod_lwip_reset_obj, mod_lwip_reset); - -STATIC mp_obj_t mod_lwip_callback() { - if (lwip_poll_list.poll != NULL) { - lwip_poll_list.poll(lwip_poll_list.poll_arg); - } - sys_check_timeouts(); - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_0(mod_lwip_callback_obj, mod_lwip_callback); - -typedef struct _getaddrinfo_state_t { - volatile int status; - volatile ip_addr_t ipaddr; -} getaddrinfo_state_t; - -// Callback for incoming DNS requests. -#if LWIP_VERSION_MAJOR < 2 -STATIC void lwip_getaddrinfo_cb(const char *name, ip_addr_t *ipaddr, void *arg) -#else -STATIC void lwip_getaddrinfo_cb(const char *name, const ip_addr_t *ipaddr, void *arg) -#endif -{ - getaddrinfo_state_t *state = arg; - if (ipaddr != NULL) { - state->status = 1; - state->ipaddr = *ipaddr; - } else { - // error - state->status = -2; - } -} - -// lwip.getaddrinfo -STATIC mp_obj_t lwip_getaddrinfo(size_t n_args, const mp_obj_t *args) { - mp_obj_t host_in = args[0], port_in = args[1]; - const char *host = mp_obj_str_get_str(host_in); - mp_int_t port = mp_obj_get_int(port_in); - - // If constraints were passed then check they are compatible with the supported params - if (n_args > 2) { - mp_int_t family = mp_obj_get_int(args[2]); - mp_int_t type = 0; - mp_int_t proto = 0; - mp_int_t flags = 0; - if (n_args > 3) { - type = mp_obj_get_int(args[3]); - if (n_args > 4) { - proto = mp_obj_get_int(args[4]); - if (n_args > 5) { - flags = mp_obj_get_int(args[5]); - } - } - } - if (!((family == 0 || family == MOD_NETWORK_AF_INET) - && (type == 0 || type == MOD_NETWORK_SOCK_STREAM) - && proto == 0 - && flags == 0)) { - mp_warning("unsupported getaddrinfo constraints"); - } - } - - getaddrinfo_state_t state; - state.status = 0; - - err_t ret = dns_gethostbyname(host, (ip_addr_t *)&state.ipaddr, lwip_getaddrinfo_cb, &state); - switch (ret) { - case ERR_OK: - // cached - state.status = 1; - break; - case ERR_INPROGRESS: - while (state.status == 0) { - poll_sockets(); - } - break; - default: - state.status = ret; - } - - if (state.status < 0) { - // TODO: CPython raises gaierror, we raise with native lwIP negative error - // values, to differentiate from normal errno's at least in such way. - mp_raise_OSError(state.status); - } - - mp_obj_tuple_t *tuple = mp_obj_new_tuple(5, NULL); - tuple->items[0] = MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_AF_INET); - tuple->items[1] = MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_SOCK_STREAM); - tuple->items[2] = MP_OBJ_NEW_SMALL_INT(0); - tuple->items[3] = MP_OBJ_NEW_QSTR(MP_QSTR_); - tuple->items[4] = netutils_format_inet_addr((uint8_t *)&state.ipaddr, port, NETUTILS_BIG); - return mp_obj_new_list(1, (mp_obj_t *)&tuple); -} -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_getaddrinfo_obj, 2, 6, lwip_getaddrinfo); - -// Debug functions - -STATIC mp_obj_t lwip_print_pcbs() { - tcp_debug_print_pcbs(); - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_0(lwip_print_pcbs_obj, lwip_print_pcbs); - -#if MICROPY_PY_LWIP - -STATIC const mp_rom_map_elem_t mp_module_lwip_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_lwip) }, - { MP_ROM_QSTR(MP_QSTR_reset), MP_ROM_PTR(&mod_lwip_reset_obj) }, - { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&mod_lwip_callback_obj) }, - { MP_ROM_QSTR(MP_QSTR_getaddrinfo), MP_ROM_PTR(&lwip_getaddrinfo_obj) }, - { MP_ROM_QSTR(MP_QSTR_print_pcbs), MP_ROM_PTR(&lwip_print_pcbs_obj) }, - // objects - { MP_ROM_QSTR(MP_QSTR_socket), MP_ROM_PTR(&lwip_socket_type) }, - #if MICROPY_PY_LWIP_SLIP - { MP_ROM_QSTR(MP_QSTR_slip), MP_ROM_PTR(&lwip_slip_type) }, - #endif - // class constants - { MP_ROM_QSTR(MP_QSTR_AF_INET), MP_ROM_INT(MOD_NETWORK_AF_INET) }, - { MP_ROM_QSTR(MP_QSTR_AF_INET6), MP_ROM_INT(MOD_NETWORK_AF_INET6) }, - - { MP_ROM_QSTR(MP_QSTR_SOCK_STREAM), MP_ROM_INT(MOD_NETWORK_SOCK_STREAM) }, - { MP_ROM_QSTR(MP_QSTR_SOCK_DGRAM), MP_ROM_INT(MOD_NETWORK_SOCK_DGRAM) }, - { MP_ROM_QSTR(MP_QSTR_SOCK_RAW), MP_ROM_INT(MOD_NETWORK_SOCK_RAW) }, - - { MP_ROM_QSTR(MP_QSTR_SOL_SOCKET), MP_ROM_INT(1) }, - { MP_ROM_QSTR(MP_QSTR_SO_REUSEADDR), MP_ROM_INT(SOF_REUSEADDR) }, - - { MP_ROM_QSTR(MP_QSTR_IPPROTO_IP), MP_ROM_INT(0) }, - { MP_ROM_QSTR(MP_QSTR_IP_ADD_MEMBERSHIP), MP_ROM_INT(IP_ADD_MEMBERSHIP) }, -}; - -STATIC MP_DEFINE_CONST_DICT(mp_module_lwip_globals, mp_module_lwip_globals_table); - -const mp_obj_module_t mp_module_lwip = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t *)&mp_module_lwip_globals, -}; - -#endif // MICROPY_PY_LWIP diff --git a/extmod/modonewire.c b/extmod/modonewire.c index 8b4ef86b0c..edb7e23cea 100644 --- a/extmod/modonewire.c +++ b/extmod/modonewire.c @@ -13,8 +13,8 @@ // Low-level 1-Wire routines #define TIMING_RESET1 (480) -#define TIMING_RESET2 (40) -#define TIMING_RESET3 (420) +#define TIMING_RESET2 (70) +#define TIMING_RESET3 (410) #define TIMING_READ1 (5) #define TIMING_READ2 (5) #define TIMING_READ3 (40) diff --git a/extmod/moductypes.c b/extmod/moductypes.c index 8499d1c29a..d093d39787 100644 --- a/extmod/moductypes.c +++ b/extmod/moductypes.c @@ -1,4 +1,4 @@ -// Copyright (c) 2014 Paul Sokolovsky +// Copyright (c) 2014-2018 Paul Sokolovsky // SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) // // SPDX-License-Identifier: MIT @@ -73,7 +73,7 @@ enum { #define AGG_TYPE_BITS 2 enum { - STRUCT, PTR, ARRAY, BITFIELD, + STRUCT, PTR, ARRAY, }; // Here we need to set sign bit right @@ -118,7 +118,11 @@ STATIC void uctypes_struct_print(const mp_print_t *print, mp_obj_t self_in, mp_p (void)kind; mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); const char *typen = "unk"; - if (MP_OBJ_IS_TYPE(self->desc, &mp_type_dict)) { + if (MP_OBJ_IS_TYPE(self->desc, &mp_type_dict) + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + || MP_OBJ_IS_TYPE(self->desc, &mp_type_ordereddict) + #endif + ) { typen = "STRUCT"; } else if (MP_OBJ_IS_TYPE(self->desc, &mp_type_tuple)) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc); @@ -191,7 +195,11 @@ STATIC mp_uint_t uctypes_struct_agg_size(mp_obj_tuple_t *t, int layout_type, mp_ } STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_t *max_field_size) { - if (!MP_OBJ_IS_TYPE(desc_in, &mp_type_dict)) { + if (!MP_OBJ_IS_TYPE(desc_in, &mp_type_dict) + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + && !MP_OBJ_IS_TYPE(desc_in, &mp_type_ordereddict) + #endif + ) { if (MP_OBJ_IS_TYPE(desc_in, &mp_type_tuple)) { return uctypes_struct_agg_size((mp_obj_tuple_t *)MP_OBJ_TO_PTR(desc_in), layout_type, max_field_size); } else if (MP_OBJ_IS_SMALL_INT(desc_in)) { @@ -246,7 +254,8 @@ STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_ return total_size; } -STATIC mp_obj_t uctypes_struct_sizeof(mp_obj_t obj_in) { +STATIC mp_obj_t uctypes_struct_sizeof(size_t n_args, const mp_obj_t *args) { + mp_obj_t obj_in = args[0]; mp_uint_t max_field_size = 0; if (MP_OBJ_IS_TYPE(obj_in, &mp_type_bytearray)) { return mp_obj_len(obj_in); @@ -255,15 +264,22 @@ STATIC mp_obj_t uctypes_struct_sizeof(mp_obj_t obj_in) { // We can apply sizeof either to structure definition (a dict) // or to instantiated structure if (MP_OBJ_IS_TYPE(obj_in, &uctypes_struct_type)) { + if (n_args != 1) { + mp_raise_TypeError(NULL); + } // Extract structure definition mp_obj_uctypes_struct_t *obj = MP_OBJ_TO_PTR(obj_in); obj_in = obj->desc; layout_type = obj->flags; + } else { + if (n_args == 2) { + layout_type = mp_obj_get_int(args[1]); + } } mp_uint_t size = uctypes_struct_size(obj_in, layout_type, &max_field_size); return MP_OBJ_NEW_SMALL_INT(size); } -STATIC MP_DEFINE_CONST_FUN_OBJ_1(uctypes_struct_sizeof_obj, uctypes_struct_sizeof); +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(uctypes_struct_sizeof_obj, 1, 2, uctypes_struct_sizeof); static inline mp_obj_t get_unaligned(uint val_type, byte *p, int big_endian) { char struct_type = big_endian ? '>' : '<'; @@ -325,7 +341,7 @@ STATIC mp_obj_t get_aligned(uint val_type, void *p, mp_int_t index) { return mp_obj_new_int_from_ll(((int64_t *)p)[index]); #if MICROPY_PY_BUILTINS_FLOAT case FLOAT32: - return mp_obj_new_float((mp_float_t)((float *)p)[index]); + return mp_obj_new_float(((float *)p)[index]); case FLOAT64: return mp_obj_new_float(((double *)p)[index]); #endif @@ -384,8 +400,11 @@ STATIC void set_aligned(uint val_type, void *p, mp_int_t index, mp_obj_t val) { STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set_val) { mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); - // TODO: Support at least OrderedDict in addition - if (!MP_OBJ_IS_TYPE(self->desc, &mp_type_dict)) { + if (!MP_OBJ_IS_TYPE(self->desc, &mp_type_dict) + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + && !MP_OBJ_IS_TYPE(self->desc, &mp_type_ordereddict) + #endif + ) { mp_raise_TypeError(translate("struct: no fields")); } @@ -589,6 +608,26 @@ STATIC mp_obj_t uctypes_struct_subscr(mp_obj_t base_in, mp_obj_t index_in, mp_ob } } +STATIC mp_obj_t uctypes_struct_unary_op(mp_unary_op_t op, mp_obj_t self_in) { + mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); + switch (op) { + case MP_UNARY_OP_INT: + if (MP_OBJ_IS_TYPE(self->desc, &mp_type_tuple)) { + mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc); + mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]); + uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS); + if (agg_type == PTR) { + byte *p = *(void **)self->addr; + return mp_obj_new_int((mp_int_t)(uintptr_t)p); + } + } + /* fallthru */ + + default: + return MP_OBJ_NULL; // op not supported + } +} + STATIC mp_int_t uctypes_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { (void)flags; mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); @@ -637,6 +676,7 @@ STATIC const mp_obj_type_t uctypes_struct_type = { .make_new = uctypes_struct_make_new, .attr = uctypes_struct_attr, .subscr = uctypes_struct_subscr, + .unary_op = uctypes_struct_unary_op, .buffer_p = { .get_buffer = uctypes_get_buffer }, }; @@ -695,6 +735,30 @@ STATIC const mp_rom_map_elem_t mp_module_uctypes_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_FLOAT64), MP_ROM_INT(TYPE2SMALLINT(FLOAT64, 4)) }, #endif + #if MICROPY_PY_UCTYPES_NATIVE_C_TYPES + // C native type aliases. These depend on GCC-compatible predefined + // preprocessor macros. + #if __SIZEOF_SHORT__ == 2 + { MP_ROM_QSTR(MP_QSTR_SHORT), MP_ROM_INT(TYPE2SMALLINT(INT16, 4)) }, + { MP_ROM_QSTR(MP_QSTR_USHORT), MP_ROM_INT(TYPE2SMALLINT(UINT16, 4)) }, + #endif + #if __SIZEOF_INT__ == 4 + { MP_ROM_QSTR(MP_QSTR_INT), MP_ROM_INT(TYPE2SMALLINT(INT32, 4)) }, + { MP_ROM_QSTR(MP_QSTR_UINT), MP_ROM_INT(TYPE2SMALLINT(UINT32, 4)) }, + #endif + #if __SIZEOF_LONG__ == 4 + { MP_ROM_QSTR(MP_QSTR_LONG), MP_ROM_INT(TYPE2SMALLINT(INT32, 4)) }, + { MP_ROM_QSTR(MP_QSTR_ULONG), MP_ROM_INT(TYPE2SMALLINT(UINT32, 4)) }, + #elif __SIZEOF_LONG__ == 8 + { MP_ROM_QSTR(MP_QSTR_LONG), MP_ROM_INT(TYPE2SMALLINT(INT64, 4)) }, + { MP_ROM_QSTR(MP_QSTR_ULONG), MP_ROM_INT(TYPE2SMALLINT(UINT64, 4)) }, + #endif + #if __SIZEOF_LONG_LONG__ == 8 + { MP_ROM_QSTR(MP_QSTR_LONGLONG), MP_ROM_INT(TYPE2SMALLINT(INT64, 4)) }, + { MP_ROM_QSTR(MP_QSTR_ULONGLONG), MP_ROM_INT(TYPE2SMALLINT(UINT64, 4)) }, + #endif + #endif // MICROPY_PY_UCTYPES_NATIVE_C_TYPES + { MP_ROM_QSTR(MP_QSTR_PTR), MP_ROM_INT(TYPE2SMALLINT(PTR, AGG_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_ARRAY), MP_ROM_INT(TYPE2SMALLINT(ARRAY, AGG_TYPE_BITS)) }, }; diff --git a/extmod/moduhashlib.c b/extmod/moduhashlib.c index e867aeb9ec..7069cc4792 100644 --- a/extmod/moduhashlib.c +++ b/extmod/moduhashlib.c @@ -12,6 +12,10 @@ #if MICROPY_PY_UHASHLIB +#if MICROPY_SSL_MBEDTLS +#include "mbedtls/version.h" +#endif + #if MICROPY_PY_UHASHLIB_SHA256 #if MICROPY_SSL_MBEDTLS @@ -22,13 +26,14 @@ #endif -#if MICROPY_PY_UHASHLIB_SHA1 +#if MICROPY_PY_UHASHLIB_SHA1 || MICROPY_PY_UHASHLIB_MD5 #if MICROPY_SSL_AXTLS #include "lib/axtls/crypto/crypto.h" #endif #if MICROPY_SSL_MBEDTLS +#include "mbedtls/md5.h" #include "mbedtls/sha1.h" #endif @@ -45,12 +50,18 @@ STATIC mp_obj_t uhashlib_sha256_update(mp_obj_t self_in, mp_obj_t arg); #if MICROPY_SSL_MBEDTLS -STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { - mp_arg_check_num(n_args, kw_args, 0, 1, false); +#if MBEDTLS_VERSION_NUMBER < 0x02070000 +#define mbedtls_sha256_starts_ret mbedtls_sha256_starts +#define mbedtls_sha256_update_ret mbedtls_sha256_update +#define mbedtls_sha256_finish_ret mbedtls_sha256_finish +#endif + +STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_sha256_context)); o->base.type = type; mbedtls_sha256_init((mbedtls_sha256_context *)&o->state); - mbedtls_sha256_starts((mbedtls_sha256_context *)&o->state, 0); + mbedtls_sha256_starts_ret((mbedtls_sha256_context *)&o->state, 0); if (n_args == 1) { uhashlib_sha256_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -61,7 +72,7 @@ STATIC mp_obj_t uhashlib_sha256_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - mbedtls_sha256_update((mbedtls_sha256_context *)&self->state, bufinfo.buf, bufinfo.len); + mbedtls_sha256_update_ret((mbedtls_sha256_context *)&self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -69,7 +80,7 @@ STATIC mp_obj_t uhashlib_sha256_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, 32); - mbedtls_sha256_finish((mbedtls_sha256_context *)&self->state, (unsigned char *)vstr.buf); + mbedtls_sha256_finish_ret((mbedtls_sha256_context *)&self->state, (unsigned char *)vstr.buf); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } @@ -164,12 +175,19 @@ STATIC mp_obj_t uhashlib_sha1_digest(mp_obj_t self_in) { #endif #if MICROPY_SSL_MBEDTLS + +#if MBEDTLS_VERSION_NUMBER < 0x02070000 +#define mbedtls_sha1_starts_ret mbedtls_sha1_starts +#define mbedtls_sha1_update_ret mbedtls_sha1_update +#define mbedtls_sha1_finish_ret mbedtls_sha1_finish +#endif + STATIC mp_obj_t uhashlib_sha1_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_sha1_context)); o->base.type = type; mbedtls_sha1_init((mbedtls_sha1_context *)o->state); - mbedtls_sha1_starts((mbedtls_sha1_context *)o->state); + mbedtls_sha1_starts_ret((mbedtls_sha1_context *)o->state); if (n_args == 1) { uhashlib_sha1_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -180,7 +198,7 @@ STATIC mp_obj_t uhashlib_sha1_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - mbedtls_sha1_update((mbedtls_sha1_context *)self->state, bufinfo.buf, bufinfo.len); + mbedtls_sha1_update_ret((mbedtls_sha1_context *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -188,7 +206,7 @@ STATIC mp_obj_t uhashlib_sha1_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, 20); - mbedtls_sha1_finish((mbedtls_sha1_context *)self->state, (byte *)vstr.buf); + mbedtls_sha1_finish_ret((mbedtls_sha1_context *)self->state, (byte *)vstr.buf); mbedtls_sha1_free((mbedtls_sha1_context *)self->state); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } @@ -211,6 +229,93 @@ STATIC const mp_obj_type_t uhashlib_sha1_type = { }; #endif +#if MICROPY_PY_UHASHLIB_MD5 +STATIC mp_obj_t uhashlib_md5_update(mp_obj_t self_in, mp_obj_t arg); + +#if MICROPY_SSL_AXTLS +STATIC mp_obj_t uhashlib_md5_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_arg_check_num(n_args, n_kw, 0, 1, false); + mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(MD5_CTX)); + o->base.type = type; + MD5_Init((MD5_CTX *)o->state); + if (n_args == 1) { + uhashlib_md5_update(MP_OBJ_FROM_PTR(o), args[0]); + } + return MP_OBJ_FROM_PTR(o); +} + +STATIC mp_obj_t uhashlib_md5_update(mp_obj_t self_in, mp_obj_t arg) { + mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); + MD5_Update((MD5_CTX *)self->state, bufinfo.buf, bufinfo.len); + return mp_const_none; +} + +STATIC mp_obj_t uhashlib_md5_digest(mp_obj_t self_in) { + mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); + vstr_t vstr; + vstr_init_len(&vstr, MD5_SIZE); + MD5_Final((byte *)vstr.buf, (MD5_CTX *)self->state); + return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); +} +#endif // MICROPY_SSL_AXTLS + +#if MICROPY_SSL_MBEDTLS + +#if MBEDTLS_VERSION_NUMBER < 0x02070000 +#define mbedtls_md5_starts_ret mbedtls_md5_starts +#define mbedtls_md5_update_ret mbedtls_md5_update +#define mbedtls_md5_finish_ret mbedtls_md5_finish +#endif + +STATIC mp_obj_t uhashlib_md5_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_arg_check_num(n_args, n_kw, 0, 1, false); + mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_md5_context)); + o->base.type = type; + mbedtls_md5_init((mbedtls_md5_context *)o->state); + mbedtls_md5_starts_ret((mbedtls_md5_context *)o->state); + if (n_args == 1) { + uhashlib_md5_update(MP_OBJ_FROM_PTR(o), args[0]); + } + return MP_OBJ_FROM_PTR(o); +} + +STATIC mp_obj_t uhashlib_md5_update(mp_obj_t self_in, mp_obj_t arg) { + mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); + mbedtls_md5_update_ret((mbedtls_md5_context *)self->state, bufinfo.buf, bufinfo.len); + return mp_const_none; +} + +STATIC mp_obj_t uhashlib_md5_digest(mp_obj_t self_in) { + mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); + vstr_t vstr; + vstr_init_len(&vstr, 16); + mbedtls_md5_finish_ret((mbedtls_md5_context *)self->state, (byte *)vstr.buf); + mbedtls_md5_free((mbedtls_md5_context *)self->state); + return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); +} +#endif // MICROPY_SSL_MBEDTLS + +STATIC MP_DEFINE_CONST_FUN_OBJ_2(uhashlib_md5_update_obj, uhashlib_md5_update); +STATIC MP_DEFINE_CONST_FUN_OBJ_1(uhashlib_md5_digest_obj, uhashlib_md5_digest); + +STATIC const mp_rom_map_elem_t uhashlib_md5_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&uhashlib_md5_update_obj) }, + { MP_ROM_QSTR(MP_QSTR_digest), MP_ROM_PTR(&uhashlib_md5_digest_obj) }, +}; +STATIC MP_DEFINE_CONST_DICT(uhashlib_md5_locals_dict, uhashlib_md5_locals_dict_table); + +STATIC const mp_obj_type_t uhashlib_md5_type = { + { &mp_type_type }, + .name = MP_QSTR_md5, + .make_new = uhashlib_md5_make_new, + .locals_dict = (void *)&uhashlib_md5_locals_dict, +}; +#endif // MICROPY_PY_UHASHLIB_MD5 + STATIC const mp_rom_map_elem_t mp_module_uhashlib_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_hashlib) }, #if MICROPY_PY_UHASHLIB_SHA256 @@ -219,6 +324,9 @@ STATIC const mp_rom_map_elem_t mp_module_uhashlib_globals_table[] = { #if MICROPY_PY_UHASHLIB_SHA1 { MP_ROM_QSTR(MP_QSTR_sha1), MP_ROM_PTR(&uhashlib_sha1_type) }, #endif + #if MICROPY_PY_UHASHLIB_MD5 + { MP_ROM_QSTR(MP_QSTR_md5), MP_ROM_PTR(&uhashlib_md5_type) }, + #endif }; STATIC MP_DEFINE_CONST_DICT(mp_module_uhashlib_globals, mp_module_uhashlib_globals_table); diff --git a/extmod/moduselect.c b/extmod/moduselect.c index bcdb45bd6d..e88494b279 100644 --- a/extmod/moduselect.c +++ b/extmod/moduselect.c @@ -25,7 +25,7 @@ typedef struct _poll_obj_t { mp_obj_t obj; - mp_uint_t (*ioctl)(mp_obj_t obj, mp_uint_t request, mp_uint_t arg, int *errcode); + mp_uint_t (*ioctl)(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode); mp_uint_t flags; mp_uint_t flags_ret; } poll_obj_t; @@ -33,7 +33,7 @@ typedef struct _poll_obj_t { STATIC void poll_map_add(mp_map_t *poll_map, const mp_obj_t *obj, mp_uint_t obj_len, mp_uint_t flags, bool or_flags) { for (mp_uint_t i = 0; i < obj_len; i++) { mp_map_elem_t *elem = mp_map_lookup(poll_map, mp_obj_id(obj[i]), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND); - if (elem->value == NULL) { + if (elem->value == MP_OBJ_NULL) { // object not found; get its ioctl and add it to the poll list const mp_stream_p_t *stream_p = mp_get_stream_raise(obj[i], MP_STREAM_OP_IOCTL); poll_obj_t *poll_obj = m_new_obj(poll_obj_t); @@ -41,27 +41,27 @@ STATIC void poll_map_add(mp_map_t *poll_map, const mp_obj_t *obj, mp_uint_t obj_ poll_obj->ioctl = stream_p->ioctl; poll_obj->flags = flags; poll_obj->flags_ret = 0; - elem->value = poll_obj; + elem->value = MP_OBJ_FROM_PTR(poll_obj); } else { // object exists; update its flags if (or_flags) { - ((poll_obj_t *)elem->value)->flags |= flags; + ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags |= flags; } else { - ((poll_obj_t *)elem->value)->flags = flags; + ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags = flags; } } } } // poll each object in the map -STATIC mp_uint_t poll_map_poll(mp_map_t *poll_map, mp_uint_t *rwx_num) { +STATIC mp_uint_t poll_map_poll(mp_map_t *poll_map, size_t *rwx_num) { mp_uint_t n_ready = 0; for (mp_uint_t i = 0; i < poll_map->alloc; ++i) { if (!MP_MAP_SLOT_IS_FILLED(poll_map, i)) { continue; } - poll_obj_t *poll_obj = (poll_obj_t *)poll_map->table[i].value; + poll_obj_t *poll_obj = MP_OBJ_TO_PTR(poll_map->table[i].value); int errcode; mp_int_t ret = poll_obj->ioctl(poll_obj->obj, MP_STREAM_POLL, poll_obj->flags, &errcode); poll_obj->flags_ret = ret; @@ -138,15 +138,15 @@ STATIC mp_obj_t select_select(uint n_args, const mp_obj_t *args) { if (!MP_MAP_SLOT_IS_FILLED(&poll_map, i)) { continue; } - poll_obj_t *poll_obj = (poll_obj_t *)poll_map.table[i].value; + poll_obj_t *poll_obj = MP_OBJ_TO_PTR(poll_map.table[i].value); if (poll_obj->flags_ret & MP_STREAM_POLL_RD) { - ((mp_obj_list_t *)list_array[0])->items[rwx_len[0]++] = poll_obj->obj; + ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[0]))->items[rwx_len[0]++] = poll_obj->obj; } if (poll_obj->flags_ret & MP_STREAM_POLL_WR) { - ((mp_obj_list_t *)list_array[1])->items[rwx_len[1]++] = poll_obj->obj; + ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[1]))->items[rwx_len[1]++] = poll_obj->obj; } if ((poll_obj->flags_ret & ~(MP_STREAM_POLL_RD | MP_STREAM_POLL_WR)) != 0) { - ((mp_obj_list_t *)list_array[2])->items[rwx_len[2]++] = poll_obj->obj; + ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[2]))->items[rwx_len[2]++] = poll_obj->obj; } } mp_map_deinit(&poll_map); @@ -171,7 +171,7 @@ typedef struct _mp_obj_poll_t { /// \method register(obj[, eventmask]) STATIC mp_obj_t poll_register(uint n_args, const mp_obj_t *args) { - mp_obj_poll_t *self = args[0]; + mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); mp_uint_t flags; if (n_args == 3) { flags = mp_obj_get_int(args[2]); @@ -185,7 +185,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(poll_register_obj, 2, 3, poll_register); /// \method unregister(obj) STATIC mp_obj_t poll_unregister(mp_obj_t self_in, mp_obj_t obj_in) { - mp_obj_poll_t *self = self_in; + mp_obj_poll_t *self = MP_OBJ_TO_PTR(self_in); mp_map_lookup(&self->poll_map, mp_obj_id(obj_in), MP_MAP_LOOKUP_REMOVE_IF_FOUND); // TODO raise KeyError if obj didn't exist in map return mp_const_none; @@ -194,18 +194,18 @@ MP_DEFINE_CONST_FUN_OBJ_2(poll_unregister_obj, poll_unregister); /// \method modify(obj, eventmask) STATIC mp_obj_t poll_modify(mp_obj_t self_in, mp_obj_t obj_in, mp_obj_t eventmask_in) { - mp_obj_poll_t *self = self_in; + mp_obj_poll_t *self = MP_OBJ_TO_PTR(self_in); mp_map_elem_t *elem = mp_map_lookup(&self->poll_map, mp_obj_id(obj_in), MP_MAP_LOOKUP); if (elem == NULL) { mp_raise_OSError(MP_ENOENT); } - ((poll_obj_t *)elem->value)->flags = mp_obj_get_int(eventmask_in); + ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags = mp_obj_get_int(eventmask_in); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_3(poll_modify_obj, poll_modify); STATIC mp_uint_t poll_poll_internal(uint n_args, const mp_obj_t *args) { - mp_obj_poll_t *self = args[0]; + mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); // work out timeout (its given already in ms) mp_uint_t timeout = -1; @@ -238,18 +238,18 @@ STATIC mp_uint_t poll_poll_internal(uint n_args, const mp_obj_t *args) { return n_ready; } -STATIC mp_obj_t poll_poll(uint n_args, const mp_obj_t *args) { - mp_obj_poll_t *self = args[0]; +STATIC mp_obj_t poll_poll(size_t n_args, const mp_obj_t *args) { + mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); mp_uint_t n_ready = poll_poll_internal(n_args, args); // one or more objects are ready, or we had a timeout - mp_obj_list_t *ret_list = mp_obj_new_list(n_ready, NULL); + mp_obj_list_t *ret_list = MP_OBJ_TO_PTR(mp_obj_new_list(n_ready, NULL)); n_ready = 0; for (mp_uint_t i = 0; i < self->poll_map.alloc; ++i) { if (!MP_MAP_SLOT_IS_FILLED(&self->poll_map, i)) { continue; } - poll_obj_t *poll_obj = (poll_obj_t *)self->poll_map.table[i].value; + poll_obj_t *poll_obj = MP_OBJ_TO_PTR(self->poll_map.table[i].value); if (poll_obj->flags_ret != 0) { mp_obj_t tuple[2] = {poll_obj->obj, MP_OBJ_NEW_SMALL_INT(poll_obj->flags_ret)}; ret_list->items[n_ready++] = mp_obj_new_tuple(2, tuple); @@ -259,7 +259,7 @@ STATIC mp_obj_t poll_poll(uint n_args, const mp_obj_t *args) { } } } - return ret_list; + return MP_OBJ_FROM_PTR(ret_list); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(poll_poll_obj, 1, 3, poll_poll); @@ -292,7 +292,7 @@ STATIC mp_obj_t poll_iternext(mp_obj_t self_in) { if (!MP_MAP_SLOT_IS_FILLED(&self->poll_map, i)) { continue; } - poll_obj_t *poll_obj = (poll_obj_t *)self->poll_map.table[i].value; + poll_obj_t *poll_obj = MP_OBJ_TO_PTR(self->poll_map.table[i].value); if (poll_obj->flags_ret != 0) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->ret_tuple); t->items[0] = poll_obj->obj; @@ -334,7 +334,7 @@ STATIC mp_obj_t select_poll(void) { mp_map_init(&poll->poll_map, 0); poll->iter_cnt = 0; poll->ret_tuple = MP_OBJ_NULL; - return poll; + return MP_OBJ_FROM_PTR(poll); } MP_DEFINE_CONST_FUN_OBJ_0(mp_select_poll_obj, select_poll); diff --git a/extmod/modussl_axtls.c b/extmod/modussl_axtls.c index 757210871b..673f480b2c 100644 --- a/extmod/modussl_axtls.c +++ b/extmod/modussl_axtls.c @@ -158,21 +158,13 @@ STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, in STATIC mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(o_in); - (void)arg; - switch (request) { - case MP_STREAM_CLOSE: - if (self->ssl_sock != NULL) { - ssl_free(self->ssl_sock); - ssl_ctx_free(self->ssl_ctx); - self->ssl_sock = NULL; - mp_stream_close(self->sock); - } - return 0; - - default: - *errcode = MP_EINVAL; - return MP_STREAM_ERROR; + if (request == MP_STREAM_CLOSE && self->ssl_sock != NULL) { + ssl_free(self->ssl_sock); + ssl_ctx_free(self->ssl_ctx); + self->ssl_sock = NULL; } + // Pass all requests down to the underlying socket + return mp_get_stream(self->sock)->ioctl(self->sock, request, arg, errcode); } STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) { @@ -220,10 +212,10 @@ STATIC const mp_obj_type_t ussl_socket_type = { STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { // TODO: Implement more args static const mp_arg_t allowed_args[] = { - { MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, - { MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} }, + { MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} }, { MP_QSTR_server_side, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, - { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} }, }; // TODO: Check that sock implements stream protocol diff --git a/extmod/modussl_mbedtls.c b/extmod/modussl_mbedtls.c index 830d6359aa..05d6047f9b 100644 --- a/extmod/modussl_mbedtls.c +++ b/extmod/modussl_mbedtls.c @@ -249,23 +249,17 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking); STATIC mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(o_in); - (void)arg; - switch (request) { - case MP_STREAM_CLOSE: - mbedtls_pk_free(&self->pkey); - mbedtls_x509_crt_free(&self->cert); - mbedtls_x509_crt_free(&self->cacert); - mbedtls_ssl_free(&self->ssl); - mbedtls_ssl_config_free(&self->conf); - mbedtls_ctr_drbg_free(&self->ctr_drbg); - mbedtls_entropy_free(&self->entropy); - mp_stream_close(self->sock); - return 0; - - default: - *errcode = MP_EINVAL; - return MP_STREAM_ERROR; + if (request == MP_STREAM_CLOSE) { + mbedtls_pk_free(&self->pkey); + mbedtls_x509_crt_free(&self->cert); + mbedtls_x509_crt_free(&self->cacert); + mbedtls_ssl_free(&self->ssl); + mbedtls_ssl_config_free(&self->conf); + mbedtls_ctr_drbg_free(&self->ctr_drbg); + mbedtls_entropy_free(&self->entropy); } + // Pass all requests down to the underlying socket + return mp_get_stream(self->sock)->ioctl(self->sock, request, arg, errcode); } STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = { diff --git a/extmod/modwebrepl.c b/extmod/modwebrepl.c index f34e14caf5..f470e26dba 100644 --- a/extmod/modwebrepl.c +++ b/extmod/modwebrepl.c @@ -14,7 +14,6 @@ #include "py/mphal.h" #endif #include "extmod/modwebsocket.h" -#include "genhdr/mpversion.h" #if MICROPY_PY_WEBREPL diff --git a/extmod/uos_dupterm.c b/extmod/uos_dupterm.c index bd2dc639c8..4668279bc8 100644 --- a/extmod/uos_dupterm.c +++ b/extmod/uos_dupterm.c @@ -66,7 +66,7 @@ int mp_uos_dupterm_rx_chr(void) { return buf[0]; } } else { - mp_uos_deactivate(idx, "dupterm: Exception in read() method, deactivating: ", nlr.ret_val); + mp_uos_deactivate(idx, "dupterm: Exception in read() method, deactivating: ", MP_OBJ_FROM_PTR(nlr.ret_val)); } } @@ -84,7 +84,7 @@ void mp_uos_dupterm_tx_strn(const char *str, size_t len) { mp_stream_write(MP_STATE_VM(dupterm_objs[idx]), str, len, MP_STREAM_RW_WRITE); nlr_pop(); } else { - mp_uos_deactivate(idx, "dupterm: Exception in write() method, deactivating: ", nlr.ret_val); + mp_uos_deactivate(idx, "dupterm: Exception in write() method, deactivating: ", MP_OBJ_FROM_PTR(nlr.ret_val)); } } } diff --git a/extmod/vfs.c b/extmod/vfs.c index b20b251938..cac51289fd 100644 --- a/extmod/vfs.c +++ b/extmod/vfs.c @@ -17,6 +17,10 @@ #include "extmod/vfs_fat.h" #endif +#if defined(MICROPY_VFS_POSIX) && MICROPY_VFS_POSIX +#include "extmod/vfs_posix.h" +#endif + // For mp_vfs_proxy_call, the maximum number of additional args that can be passed. // A fixed maximum size is used to avoid the need for a costly variable array. #define PROXY_MAX_ARGS (2) @@ -244,6 +248,13 @@ mp_obj_t mp_vfs_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + #if defined(MICROPY_VFS_POSIX) && MICROPY_VFS_POSIX + // If the file is an integer then delegate straight to the POSIX handler + if (MP_OBJ_IS_SMALL_INT(args[ARG_file].u_obj)) { + return mp_vfs_posix_file_open(&mp_type_textio, args[ARG_file].u_obj, args[ARG_mode].u_obj); + } + #endif + mp_vfs_mount_t *vfs = lookup_path(args[ARG_file].u_obj, &args[ARG_file].u_obj); return mp_vfs_proxy_call(vfs, MP_QSTR_open, 2, (mp_obj_t *)&args); } diff --git a/extmod/vfs_posix.c b/extmod/vfs_posix.c index 02f0e7cea9..ff2ed04715 100644 --- a/extmod/vfs_posix.c +++ b/extmod/vfs_posix.c @@ -172,6 +172,9 @@ STATIC mp_obj_t vfs_posix_ilistdir_it_iternext(mp_obj_t self_in) { } #ifdef _DIRENT_HAVE_D_TYPE + #ifdef DTTOIF + t->items[1] = MP_OBJ_NEW_SMALL_INT(DTTOIF(dirent->d_type)); + #else if (dirent->d_type == DT_DIR) { t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR); } else if (dirent->d_type == DT_REG) { @@ -179,10 +182,12 @@ STATIC mp_obj_t vfs_posix_ilistdir_it_iternext(mp_obj_t self_in) { } else { t->items[1] = MP_OBJ_NEW_SMALL_INT(dirent->d_type); } + #endif #else // DT_UNKNOWN should have 0 value on any reasonable system t->items[1] = MP_OBJ_NEW_SMALL_INT(0); #endif + #ifdef _DIRENT_HAVE_D_INO t->items[2] = MP_OBJ_NEW_SMALL_INT(dirent->d_ino); #else @@ -200,6 +205,9 @@ STATIC mp_obj_t vfs_posix_ilistdir(mp_obj_t self_in, mp_obj_t path_in) { iter->iternext = vfs_posix_ilistdir_it_iternext; iter->is_str = mp_obj_get_type(path_in) == &mp_type_str; const char *path = vfs_posix_get_path_str(self, path_in); + if (path[0] == '\0') { + path = "."; + } iter->dir = opendir(path); if (iter->dir == NULL) { mp_raise_OSError(errno); diff --git a/extmod/virtpin.c b/extmod/virtpin.c index bb4935a0bc..e19c05c812 100644 --- a/extmod/virtpin.c +++ b/extmod/virtpin.c @@ -1,4 +1,4 @@ -// Copyright (c) 2016 Paul Sokolovsky +// SPDX-FileCopyrightText: Copyright (c) 2016 Paul Sokolovsky // SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) // // SPDX-License-Identifier: MIT diff --git a/lib/libm/math.c b/lib/libm/math.c index 670d95ed2d..c3dbf657ff 100644 --- a/lib/libm/math.c +++ b/lib/libm/math.c @@ -30,12 +30,17 @@ typedef float float_t; typedef union { float f; struct { - uint64_t m : 23; - uint64_t e : 8; - uint64_t s : 1; + uint32_t m : 23; + uint32_t e : 8; + uint32_t s : 1; }; } float_s_t; +int __signbitf(float f) { + float_s_t u = {.f = f}; + return u.s; +} + #ifndef NDEBUG float copysignf(float x, float y) { float_s_t fx={.f = x}; @@ -55,10 +60,14 @@ static const float _M_LN2 = 0.6931472; float log2f(float x) { return logf(x) / (float)_M_LN2; } float tanhf(float x) { - if (isinf(x)) { - return copysignf(1, x); + int sign = 0; + if (x < 0) { + sign = 1; + x = -x; } - return sinhf(x) / coshf(x); + x = expm1f(-2 * x); + x = x / (x + 2); + return sign ? x : -x; } /*****************************************************************************/ diff --git a/lib/libm/wf_tgamma.c b/lib/libm/wf_tgamma.c index 64b2488d1d..3ff05f331d 100644 --- a/lib/libm/wf_tgamma.c +++ b/lib/libm/wf_tgamma.c @@ -35,6 +35,10 @@ { float y; int local_signgam; + if (!isfinite(x)) { + /* special cases: tgammaf(nan)=nan, tgammaf(inf)=inf, tgammaf(-inf)=nan */ + return x + INFINITY; + } y = expf(__ieee754_lgammaf_r(x,&local_signgam)); if (local_signgam < 0) y = -y; #ifdef _IEEE_LIBM diff --git a/lib/libm_dbl/README b/lib/libm_dbl/README index 512b328261..0ef01af815 100644 --- a/lib/libm_dbl/README +++ b/lib/libm_dbl/README @@ -4,6 +4,10 @@ functions. The files lgamma.c, log10.c and tanh.c are too small to have a meaningful copyright or license. +The file copysign.c contains a double version of the float copysignf provided +in libm/math.c for use in DEBUG builds where the standard library copy is +not available. + The rest of the files in this directory are copied from the musl library, v1.1.16, and, unless otherwise stated in the individual file, have the following copyright and MIT license: diff --git a/drivers/bus/spi.h b/lib/libm_dbl/copysign.c similarity index 57% rename from drivers/bus/spi.h rename to lib/libm_dbl/copysign.c index 5d150cd38f..f42b09bee5 100644 --- a/drivers/bus/spi.h +++ b/lib/libm_dbl/copysign.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2016-2018 Damien P. George + * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -23,33 +23,26 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef MICROPY_INCLUDED_DRIVERS_BUS_SPI_H -#define MICROPY_INCLUDED_DRIVERS_BUS_SPI_H -#include "py/mphal.h" +#include "libm.h" -enum { - MP_SPI_IOCTL_INIT, - MP_SPI_IOCTL_DEINIT, -}; +#ifndef NDEBUG +typedef union { + double d; + struct { + uint64_t m : 52; + uint64_t e : 11; + uint64_t s : 1; + }; +} double_s_t; -typedef struct _mp_spi_proto_t { - int (*ioctl)(void *self, uint32_t cmd); - void (*transfer)(void *self, size_t len, const uint8_t *src, uint8_t *dest); -} mp_spi_proto_t; +double copysign(double x, double y) { + double_s_t dx={.d = x}; + double_s_t dy={.d = y}; -typedef struct _mp_soft_spi_obj_t { - uint32_t delay_half; // microsecond delay for half SCK period - uint8_t polarity; - uint8_t phase; - mp_hal_pin_obj_t sck; - mp_hal_pin_obj_t mosi; - mp_hal_pin_obj_t miso; -} mp_soft_spi_obj_t; + // copy sign bit; + dx.s = dy.s; -extern const mp_spi_proto_t mp_soft_spi_proto; - -int mp_soft_spi_ioctl(void *self, uint32_t cmd); -void mp_soft_spi_transfer(void *self, size_t len, const uint8_t *src, uint8_t *dest); - -#endif // MICROPY_INCLUDED_DRIVERS_BUS_SPI_H + return dx.d; +} +#endif diff --git a/lib/libm_dbl/tanh.c b/lib/libm_dbl/tanh.c index 89743ba90f..6bdb7c3999 100644 --- a/lib/libm_dbl/tanh.c +++ b/lib/libm_dbl/tanh.c @@ -1,5 +1,12 @@ #include double tanh(double x) { - return sinh(x) / cosh(x); + int sign = 0; + if (x < 0) { + sign = 1; + x = -x; + } + x = expm1(-2 * x); + x = x / (x + 2); + return sign ? x : -x; } diff --git a/lib/utils/mpirq.c b/lib/utils/mpirq.c new file mode 100644 index 0000000000..dd0c220059 --- /dev/null +++ b/lib/utils/mpirq.c @@ -0,0 +1,124 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2015 Daniel Campora + * 2018 Tobias Badertscher + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "py/runtime.h" +#include "py/gc.h" +#include "lib/utils/mpirq.h" + +/****************************************************************************** + DECLARE PUBLIC DATA + ******************************************************************************/ + +const mp_arg_t mp_irq_init_args[] = { + { MP_QSTR_handler, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} }, + { MP_QSTR_trigger, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_hard, MP_ARG_BOOL, {.u_bool = false} }, +}; + +/****************************************************************************** + DECLARE PRIVATE DATA + ******************************************************************************/ + +/****************************************************************************** + DEFINE PUBLIC FUNCTIONS + ******************************************************************************/ + +mp_irq_obj_t *mp_irq_new(const mp_irq_methods_t *methods, mp_obj_t parent) { + mp_irq_obj_t *self = m_new0(mp_irq_obj_t, 1); + self->base.type = &mp_irq_type; + self->methods = (mp_irq_methods_t *)methods; + self->parent = parent; + self->handler = mp_const_none; + self->ishard = false; + return self; +} + +void mp_irq_handler(mp_irq_obj_t *self) { + if (self->handler != mp_const_none) { + if (self->ishard) { + // When executing code within a handler we must lock the GC to prevent + // any memory allocations. + gc_lock(); + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + mp_call_function_1(self->handler, self->parent); + nlr_pop(); + } else { + // Uncaught exception; disable the callback so that it doesn't run again + self->methods->trigger(self->parent, 0); + self->handler = mp_const_none; + printf("Uncaught exception in IRQ callback handler\n"); + mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); + } + gc_unlock(); + } else { + // Schedule call to user function + mp_sched_schedule(self->handler, self->parent); + } + } +} + +/******************************************************************************/ +// MicroPython bindings + +STATIC mp_obj_t mp_irq_flags(mp_obj_t self_in) { + mp_irq_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_int(self->methods->info(self->parent, MP_IRQ_INFO_FLAGS)); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_irq_flags_obj, mp_irq_flags); + +STATIC mp_obj_t mp_irq_trigger(size_t n_args, const mp_obj_t *args) { + mp_irq_obj_t *self = MP_OBJ_TO_PTR(args[0]); + mp_obj_t ret_obj = mp_obj_new_int(self->methods->info(self->parent, MP_IRQ_INFO_TRIGGERS)); + if (n_args == 2) { + // Set trigger + self->methods->trigger(self->parent, mp_obj_get_int(args[1])); + } + return ret_obj; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_irq_trigger_obj, 1, 2, mp_irq_trigger); + +STATIC mp_obj_t mp_irq_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_arg_check_num(n_args, n_kw, 0, 0, false); + mp_irq_handler(MP_OBJ_TO_PTR(self_in)); + return mp_const_none; +} + +STATIC const mp_rom_map_elem_t mp_irq_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_flags), MP_ROM_PTR(&mp_irq_flags_obj) }, + { MP_ROM_QSTR(MP_QSTR_trigger), MP_ROM_PTR(&mp_irq_trigger_obj) }, +}; +STATIC MP_DEFINE_CONST_DICT(mp_irq_locals_dict, mp_irq_locals_dict_table); + +const mp_obj_type_t mp_irq_type = { + { &mp_type_type }, + .name = MP_QSTR_irq, + .call = mp_irq_call, + .locals_dict = (mp_obj_dict_t *)&mp_irq_locals_dict, +}; diff --git a/lib/utils/mpirq.h b/lib/utils/mpirq.h new file mode 100644 index 0000000000..548185b531 --- /dev/null +++ b/lib/utils/mpirq.h @@ -0,0 +1,82 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2015 Daniel Campora + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#ifndef MICROPY_INCLUDED_LIB_UTILS_MPIRQ_H +#define MICROPY_INCLUDED_LIB_UTILS_MPIRQ_H + +/****************************************************************************** + DEFINE CONSTANTS + ******************************************************************************/ + +enum { + MP_IRQ_ARG_INIT_handler = 0, + MP_IRQ_ARG_INIT_trigger, + MP_IRQ_ARG_INIT_hard, + MP_IRQ_ARG_INIT_NUM_ARGS, +}; + +/****************************************************************************** + DEFINE TYPES + ******************************************************************************/ + +typedef mp_obj_t (*mp_irq_init_t)(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args); +typedef mp_uint_t (*mp_irq_uint_method_one_uint_para_t)(mp_obj_t self, mp_uint_t trigger); +typedef mp_uint_t (*mp_irq_int_method_one_para_t)(mp_obj_t self, mp_uint_t info_type); + +enum { + MP_IRQ_INFO_FLAGS, + MP_IRQ_INFO_TRIGGERS, + MP_IRQ_INFO_CNT +}; + +typedef struct _mp_irq_methods_t { + mp_irq_init_t init; + mp_irq_uint_method_one_uint_para_t trigger; + mp_irq_int_method_one_para_t info; +} mp_irq_methods_t; + +typedef struct _mp_irq_obj_t { + mp_obj_base_t base; + mp_irq_methods_t *methods; + mp_obj_t parent; + mp_obj_t handler; + bool ishard; +} mp_irq_obj_t; + +/****************************************************************************** + DECLARE EXPORTED DATA + ******************************************************************************/ + +extern const mp_arg_t mp_irq_init_args[]; +extern const mp_obj_type_t mp_irq_type; + +/****************************************************************************** + DECLARE PUBLIC FUNCTIONS + ******************************************************************************/ + +mp_irq_obj_t *mp_irq_new(const mp_irq_methods_t *methods, mp_obj_t parent); +void mp_irq_handler(mp_irq_obj_t *self); + +#endif // MICROPY_INCLUDED_LIB_UTILS_MPIRQ_H diff --git a/lib/utils/printf.c b/lib/utils/printf.c index 859c7e0017..dbf0c26744 100644 --- a/lib/utils/printf.c +++ b/lib/utils/printf.c @@ -26,8 +26,6 @@ #include "py/mpconfig.h" -#if MICROPY_USE_INTERNAL_PRINTF - #include #include #include @@ -39,6 +37,18 @@ #include "py/formatfloat.h" #endif +#if MICROPY_DEBUG_PRINTERS +int DEBUG_printf(const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + int ret = mp_vprintf(MICROPY_DEBUG_PRINTER, fmt, ap); + va_end(ap); + return ret; +} +#endif + +#if MICROPY_USE_INTERNAL_PRINTF + #undef putchar // Some stdlibs have a #define for putchar int printf(const char *fmt, ...); int vprintf(const char *fmt, va_list ap); @@ -59,20 +69,6 @@ int vprintf(const char *fmt, va_list ap) { return mp_vprintf(&mp_plat_print, fmt, ap); } -#if MICROPY_DEBUG_PRINTERS -extern const mp_print_t MICROPY_DEBUG_PRINTER_DEST; -int DEBUG_printf(const char *fmt, ...) { - va_list ap; - va_start(ap, fmt); - #ifndef MICROPY_DEBUG_PRINTER_DEST - #define MICROPY_DEBUG_PRINTER_DEST mp_plat_print - #endif - int ret = mp_vprintf(&MICROPY_DEBUG_PRINTER_DEST, fmt, ap); - va_end(ap); - return ret; -} -#endif - // need this because gcc optimises printf("%c", c) -> putchar(c), and printf("a") -> putchar('a') int putchar(int c) { char chr = c; diff --git a/lib/utils/pyexec.c b/lib/utils/pyexec.c index 450b5ae326..9a105a42ca 100644 --- a/lib/utils/pyexec.c +++ b/lib/utils/pyexec.c @@ -129,7 +129,7 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input mp_hal_stdout_tx_strn("\x04", 1); } // check for SystemExit - if (mp_obj_is_subclass_fast(mp_obj_get_type((mp_obj_t)nlr.ret_val), &mp_type_SystemExit)) { + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) { // at the moment, the value of SystemExit is unused ret = pyexec_system_exit; #if CIRCUITPY_ALARM @@ -138,7 +138,7 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input #endif } else { if ((mp_obj_t)nlr.ret_val != MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_reload_exception))) { - mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val); + mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); } ret = PYEXEC_EXCEPTION; } @@ -455,6 +455,12 @@ friendly_repl_reset: } #endif + // If the GC is locked at this point there is no way out except a reset, + // so force the GC to be unlocked to help the user debug what went wrong. + if (MP_STATE_MEM(gc_lock_depth) != 0) { + MP_STATE_MEM(gc_lock_depth) = 0; + } + vstr_reset(&line); int ret = readline(&line, ">>> "); mp_parse_input_kind_t parse_input_kind = MP_PARSE_SINGLE_INPUT; diff --git a/lib/utils/sys_stdio_mphal.c b/lib/utils/sys_stdio_mphal.c index e2e1999c25..c3757626c1 100644 --- a/lib/utils/sys_stdio_mphal.c +++ b/lib/utils/sys_stdio_mphal.c @@ -172,7 +172,7 @@ STATIC const mp_obj_type_t stdio_buffer_obj_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &stdio_buffer_obj_stream_p, - .locals_dict = (mp_obj_t)&stdio_locals_dict, + .locals_dict = (mp_obj_dict_t *)&stdio_locals_dict, }; STATIC const sys_stdio_obj_t stdio_buffer_obj = {{&stdio_buffer_obj_type}, .fd = 0}; // fd unused diff --git a/locale/circuitpython.pot b/locale/circuitpython.pot index 4342427b5b..7b019191e3 100644 --- a/locale/circuitpython.pot +++ b/locale/circuitpython.pot @@ -2304,10 +2304,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2387,11 +2383,6 @@ msgstr "" msgid "abort() called" msgstr "" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "" @@ -2400,6 +2391,10 @@ msgstr "" msgid "addresses is empty" msgstr "" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "" @@ -2582,6 +2577,10 @@ msgstr "" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "" @@ -2590,6 +2589,10 @@ msgstr "" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2993,7 +2996,7 @@ msgid "full" msgstr "" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "" #: py/argcheck.c @@ -3048,6 +3051,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "" @@ -3427,6 +3434,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3656,10 +3667,6 @@ msgstr "" msgid "palette_index should be an int" msgstr "" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3715,6 +3722,7 @@ msgstr "" #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -4098,7 +4106,7 @@ msgstr "" msgid "unknown type" msgstr "" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "" diff --git a/mpy-cross/Makefile b/mpy-cross/Makefile index 3ff379ed36..200080bbe5 100644 --- a/mpy-cross/Makefile +++ b/mpy-cross/Makefile @@ -9,6 +9,8 @@ ifneq ($(findstring undefine,$(.FEATURES)),) override undefine COPT override undefine CFLAGS_EXTRA override undefine LDFLAGS_EXTRA +override undefine MICROPY_FORCE_32BIT +override undefine CROSS_COMPILE override undefine FROZEN_DIR override undefine FROZEN_MPY_DIR override undefine BUILD diff --git a/mpy-cross/mphalport.h b/mpy-cross/mphalport.h index 245b99c4c3..b45ff339ba 100644 --- a/mpy-cross/mphalport.h +++ b/mpy-cross/mphalport.h @@ -2,4 +2,5 @@ // // SPDX-License-Identifier: MIT -// empty file +// prevent including extmod/virtpin.h +#define mp_hal_pin_obj_t diff --git a/mpy-cross/mpy-cross.mk b/mpy-cross/mpy-cross.mk index 629054af9e..c6ef9d8165 100644 --- a/mpy-cross/mpy-cross.mk +++ b/mpy-cross/mpy-cross.mk @@ -22,8 +22,8 @@ UNAME_S := $(shell uname -s) # include py core make definitions include $(TOP)/py/py.mk -INC += -I. -INC += -I$(TOP) +INC += -I. +INC += -I$(TOP) INC += -I$(BUILD) # compiler settings @@ -79,7 +79,7 @@ ifneq (,$(findstring mingw,$(COMPILER_TARGET))) SRC_C += fmode.c endif -OBJ = $(PY_O) +OBJ = $(PY_CORE_O) OBJ += $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) $(BUILD)/supervisor/shared/translate.o: $(HEADER_BUILD)/qstrdefs.generated.h diff --git a/ports/unix/Makefile b/ports/unix/Makefile index 305c0549d1..bb900a29b3 100644 --- a/ports/unix/Makefile +++ b/ports/unix/Makefile @@ -76,6 +76,9 @@ LDFLAGS_ARCH = -Wl,-Map=$@.map,--cref -Wl,--gc-sections endif LDFLAGS = -Lbuild $(LDFLAGS_MOD) $(LDFLAGS_ARCH) -lm $(LDFLAGS_EXTRA) +# Flags to link with pthread library +LIBPTHREAD = -lpthread + ifeq ($(MICROPY_FORCE_32BIT),1) # Note: you may need to install i386 versions of dependency packages, # starting with linux-libc-dev:i386 @@ -101,17 +104,17 @@ SRC_MOD += modusocket.c endif ifeq ($(MICROPY_PY_THREAD),1) CFLAGS_MOD += -DMICROPY_PY_THREAD=1 -DMICROPY_PY_THREAD_GIL=0 -LDFLAGS_MOD += -lpthread +LDFLAGS_MOD += $(LIBPTHREAD) endif ifeq ($(MICROPY_PY_FFI),1) ifeq ($(MICROPY_STANDALONE),1) -LIBFFI_CFLAGS_MOD := -I$(shell ls -1d $(TOP)/lib/libffi/build_dir/out/lib/libffi-*/include) +LIBFFI_CFLAGS_MOD := -I$(shell ls -1d $(BUILD)/lib/libffi/out/lib/libffi-*/include) ifeq ($(MICROPY_FORCE_32BIT),1) - LIBFFI_LDFLAGS_MOD = $(TOP)/lib/libffi/build_dir/out/lib32/libffi.a + LIBFFI_LDFLAGS_MOD = $(BUILD)/lib/libffi/out/lib32/libffi.a else - LIBFFI_LDFLAGS_MOD = $(TOP)/lib/libffi/build_dir/out/lib/libffi.a + LIBFFI_LDFLAGS_MOD = $(BUILD)/lib/libffi/out/lib/libffi.a endif else LIBFFI_CFLAGS_MOD := $(shell pkg-config --cflags libffi) @@ -141,7 +144,6 @@ SRC_C += \ mpthreadport.c \ input.c \ file.c \ - modmachine.c \ modos.c \ moduos_vfs.c \ modtime.c \ @@ -156,12 +158,6 @@ SRC_C += \ supervisor/shared/translate.c \ $(SRC_MOD) -PY_EXTMOD_O_BASENAME += \ - extmod/machine_mem.o \ - extmod/machine_pinbase.o \ - extmod/machine_signal.o \ - extmod/machine_pulse.o \ - LIB_SRC_C = $(addprefix lib/,\ $(LIB_SRC_C_EXTRA) \ timeutils/timeutils.c \ @@ -232,8 +228,7 @@ nanbox: CFLAGS_EXTRA='-DMP_CONFIGFILE=""' \ BUILD=build-nanbox \ PROG=micropython_nanbox \ - MICROPY_FORCE_32BIT=1 \ - MICROPY_PY_USSL=0 + MICROPY_FORCE_32BIT=1 freedos: $(MAKE) \ @@ -264,9 +259,9 @@ coverage: coverage_test: coverage $(eval DIRNAME=ports/$(notdir $(CURDIR))) - cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests --auto-jobs - cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests --auto-jobs -d thread - cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests --auto-jobs --emit native + cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests -j1 + cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests -j1 -d thread + cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests -j1 --emit native cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests -j1 --via-mpy -d basics float cat $(TOP)/tests/basics/0prelim.py | ./micropython_coverage | grep -q 'abc' gcov -o build-coverage/py $(TOP)/py/*.c @@ -297,23 +292,19 @@ endif deplibs: libffi axtls +libffi: $(BUILD)/lib/libffi/include/ffi.h + +$(TOP)/lib/libffi/configure: $(TOP)/lib/libffi/autogen.sh + cd $(TOP)/lib/libffi; ./autogen.sh + # install-exec-recursive & install-data-am targets are used to avoid building # docs and depending on makeinfo -libffi: - cd $(TOP)/lib/libffi; git clean -d -x -f - cd $(TOP)/lib/libffi; ./autogen.sh - mkdir -p $(TOP)/lib/libffi/build_dir; cd $(TOP)/lib/libffi/build_dir; \ - ../configure $(CROSS_COMPILE_HOST) --prefix=$$PWD/out --disable-structs CC="$(CC)" CXX="$(CXX)" LD="$(LD)" CFLAGS="-Os -fomit-frame-pointer -fstrict-aliasing -ffast-math -fno-exceptions"; \ +$(BUILD)/lib/libffi/include/ffi.h: $(TOP)/lib/libffi/configure + mkdir -p $(BUILD)/lib/libffi; cd $(BUILD)/lib/libffi; \ + $(abspath $(TOP))/lib/libffi/configure $(CROSS_COMPILE_HOST) --prefix=$$PWD/out --disable-structs CC="$(CC)" CXX="$(CXX)" LD="$(LD)" CFLAGS="-Os -fomit-frame-pointer -fstrict-aliasing -ffast-math -fno-exceptions"; \ $(MAKE) install-exec-recursive; $(MAKE) -C include install-data-am -axtls: $(BUILD)/libaxtls.a - -$(BUILD)/libaxtls.a: $(TOP)/lib/axtls/README | $(OBJ_DIRS) - cd $(TOP)/lib/axtls; cp config/upyconfig config/.config - cd $(TOP)/lib/axtls; $(MAKE) oldconfig -B - cd $(TOP)/lib/axtls; $(MAKE) clean - cd $(TOP)/lib/axtls; $(MAKE) all CC="$(CC)" LD="$(LD)" - cp $(TOP)/lib/axtls/_stage/libaxtls.a $@ +axtls: $(TOP)/lib/axtls/README $(TOP)/lib/axtls/README: @echo "You cloned without --recursive, fetching submodules for you." diff --git a/ports/unix/file.c b/ports/unix/file.c index 892457ed56..745593c81c 100644 --- a/ports/unix/file.c +++ b/ports/unix/file.c @@ -125,6 +125,8 @@ STATIC mp_uint_t fdfile_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, i o->fd = -1; #endif return 0; + case MP_STREAM_GET_FILENO: + return o->fd; default: *errcode = EINVAL; return MP_STREAM_ERROR; diff --git a/ports/unix/main.c b/ports/unix/main.c index eb7f7521fa..715ad56589 100644 --- a/ports/unix/main.c +++ b/ports/unix/main.c @@ -511,9 +511,6 @@ MP_NOINLINE int main_(int argc, char **argv) { } } - - - mp_obj_list_init(MP_OBJ_TO_PTR(mp_sys_argv), 0); #if defined(MICROPY_UNIX_COVERAGE) diff --git a/ports/unix/modffi.c b/ports/unix/modffi.c index a64d4a7b23..894702330f 100644 --- a/ports/unix/modffi.c +++ b/ports/unix/modffi.c @@ -117,6 +117,10 @@ STATIC ffi_type *char2ffi_type(char c) { return &ffi_type_slong; case 'L': return &ffi_type_ulong; + case 'q': + return &ffi_type_sint64; + case 'Q': + return &ffi_type_uint64; #if MICROPY_PY_BUILTINS_FLOAT case 'f': return &ffi_type_float; diff --git a/ports/unix/modjni.c b/ports/unix/modjni.c index a0d0cb1de6..3ff5c61f50 100644 --- a/ports/unix/modjni.c +++ b/ports/unix/modjni.c @@ -118,7 +118,7 @@ STATIC void print_jobject(const mp_print_t *print, jobject obj) { // jclass STATIC void jclass_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - mp_obj_jclass_t *self = self_in; + mp_obj_jclass_t *self = MP_OBJ_TO_PTR(self_in); if (kind == PRINT_REPR) { mp_printf(print, "cls); } @@ -131,7 +131,7 @@ STATIC void jclass_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kin STATIC void jclass_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { if (dest[0] == MP_OBJ_NULL) { // load attribute - mp_obj_jclass_t *self = self_in; + mp_obj_jclass_t *self = MP_OBJ_TO_PTR(self_in); const char *attr = qstr_str(attr_in); jstring field_name = JJ(NewStringUTF, attr); @@ -151,7 +151,7 @@ STATIC void jclass_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { o->meth = NULL; o->obj = self->cls; o->is_static = true; - dest[0] = o; + dest[0] = MP_OBJ_FROM_PTR(o); } } @@ -159,7 +159,7 @@ STATIC mp_obj_t jclass_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const if (n_kw != 0) { mp_raise_TypeError("kwargs not supported"); } - mp_obj_jclass_t *self = self_in; + mp_obj_jclass_t *self = MP_OBJ_TO_PTR(self_in); jarray methods = JJ(CallObjectMethod, self->cls, Class_getConstructors_mid); @@ -186,13 +186,13 @@ STATIC mp_obj_t new_jclass(jclass jc) { mp_obj_jclass_t *o = m_new_obj(mp_obj_jclass_t); o->base.type = &jclass_type; o->cls = jc; - return o; + return MP_OBJ_FROM_PTR(o); } // jobject STATIC void jobject_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - mp_obj_jobject_t *self = self_in; + mp_obj_jobject_t *self = MP_OBJ_TO_PTR(self_in); if (kind == PRINT_REPR) { mp_printf(print, "obj); } @@ -205,7 +205,7 @@ STATIC void jobject_print(const mp_print_t *print, mp_obj_t self_in, mp_print_ki STATIC void jobject_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { if (dest[0] == MP_OBJ_NULL) { // load attribute - mp_obj_jobject_t *self = self_in; + mp_obj_jobject_t *self = MP_OBJ_TO_PTR(self_in); const char *attr = qstr_str(attr_in); jclass obj_class = JJ(GetObjectClass, self->obj); @@ -229,7 +229,7 @@ STATIC void jobject_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { o->meth = NULL; o->obj = self->obj; o->is_static = false; - dest[0] = o; + dest[0] = MP_OBJ_FROM_PTR(o); } } @@ -242,7 +242,7 @@ STATIC void get_jclass_name(jobject obj, char *buf) { } STATIC mp_obj_t jobject_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { - mp_obj_jobject_t *self = self_in; + mp_obj_jobject_t *self = MP_OBJ_TO_PTR(self_in); mp_uint_t idx = mp_obj_get_int(index); char class_name[64]; get_jclass_name(self->obj, class_name); @@ -292,7 +292,7 @@ STATIC mp_obj_t jobject_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) } STATIC mp_obj_t jobject_unary_op(mp_unary_op_t op, mp_obj_t self_in) { - mp_obj_jobject_t *self = self_in; + mp_obj_jobject_t *self = MP_OBJ_TO_PTR(self_in); switch (op) { case MP_UNARY_OP_BOOL: case MP_UNARY_OP_LEN: { @@ -316,9 +316,9 @@ MP_DEFINE_CONST_FUN_OBJ_2(subscr_load_adaptor_obj, subscr_load_adaptor); // .getiter special method which returns iterator which works in terms // of object subscription. -STATIC mp_obj_t subscr_getiter(mp_obj_t self_in) { - mp_obj_t dest[2] = {(mp_obj_t)&subscr_load_adaptor_obj, self_in}; - return mp_obj_new_getitem_iter(dest); +STATIC mp_obj_t subscr_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) { + mp_obj_t dest[2] = {MP_OBJ_FROM_PTR(&subscr_load_adaptor_obj), self_in}; + return mp_obj_new_getitem_iter(dest, iter_buf); } STATIC const mp_obj_type_t jobject_type = { @@ -346,7 +346,7 @@ STATIC mp_obj_t new_jobject(jobject jo) { mp_obj_jobject_t *o = m_new_obj(mp_obj_jobject_t); o->base.type = &jobject_type; o->obj = jo; - return o; + return MP_OBJ_FROM_PTR(o); } } @@ -356,7 +356,7 @@ STATIC mp_obj_t new_jobject(jobject jo) { STATIC void jmethod_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; - mp_obj_jmethod_t *self = self_in; + mp_obj_jmethod_t *self = MP_OBJ_TO_PTR(self_in); // Variable value printed as cast to int mp_printf(print, "", qstr_str(self->name)); } @@ -408,7 +408,7 @@ STATIC bool py2jvalue(const char **jtypesig, mp_obj_t arg, jvalue *out) { if (!is_object) { return false; } - mp_obj_jobject_t *jo = arg; + mp_obj_jobject_t *jo = MP_OBJ_TO_PTR(arg); if (!MATCH(expected_type, "java.lang.Object")) { char class_name[64]; get_jclass_name(jo->obj, class_name); @@ -490,8 +490,8 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool // printf("name=%p meth_name=%s\n", name, meth_name); bool found = true; - for (int i = 0; i < n_args && *arg_types != ')'; i++) { - if (!py2jvalue(&arg_types, args[i], &jargs[i])) { + for (size_t j = 0; j < n_args && *arg_types != ')'; j++) { + if (!py2jvalue(&arg_types, args[j], &jargs[j])) { goto next_method; } @@ -507,13 +507,12 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool if (found) { // printf("found!\n"); jmethodID method_id = JJ(FromReflectedMethod, meth); - jobject res; - mp_obj_t ret; if (is_constr) { JJ(ReleaseStringUTFChars, name_o, decl); - res = JJ(NewObjectA, obj, method_id, jargs); + jobject res = JJ(NewObjectA, obj, method_id, jargs); return new_jobject(res); } else { + mp_obj_t ret; if (MATCH(ret_type, "void")) { JJ(CallVoidMethodA, obj, method_id, jargs); check_exception(); @@ -527,7 +526,7 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool check_exception(); ret = mp_obj_new_bool(res); } else if (is_object_type(ret_type)) { - res = JJ(CallObjectMethodA, obj, method_id, jargs); + jobject res = JJ(CallObjectMethodA, obj, method_id, jargs); check_exception(); ret = new_jobject(res); } else { @@ -556,7 +555,7 @@ STATIC mp_obj_t jmethod_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const if (n_kw != 0) { mp_raise_TypeError("kwargs not supported"); } - mp_obj_jmethod_t *self = self_in; + mp_obj_jmethod_t *self = MP_OBJ_TO_PTR(self_in); const char *name = qstr_str(self->name); // jstring meth_name = JJ(NewStringUTF, name); @@ -585,7 +584,7 @@ STATIC const mp_obj_type_t jmethod_type = { #define LIBJVM_SO "libjvm.so" #endif -STATIC void create_jvm() { +STATIC void create_jvm(void) { JavaVMInitArgs args; JavaVMOption options; options.optionString = "-Djava.class.path=."; @@ -648,7 +647,7 @@ STATIC mp_obj_t mod_jni_cls(mp_obj_t cls_name_in) { mp_obj_jclass_t *o = m_new_obj(mp_obj_jclass_t); o->base.type = &jclass_type; o->cls = cls; - return o; + return MP_OBJ_FROM_PTR(o); } MP_DEFINE_CONST_FUN_OBJ_1(mod_jni_cls_obj, mod_jni_cls); @@ -661,7 +660,7 @@ STATIC mp_obj_t mod_jni_array(mp_obj_t type_in, mp_obj_t size_in) { if (MP_OBJ_IS_TYPE(type_in, &jclass_type)) { - mp_obj_jclass_t *jcls = type_in; + mp_obj_jclass_t *jcls = MP_OBJ_TO_PTR(type_in); res = JJ(NewObjectArray, size, jcls->cls, NULL); } else if (MP_OBJ_IS_STR(type_in)) { @@ -700,8 +699,8 @@ STATIC mp_obj_t mod_jni_array(mp_obj_t type_in, mp_obj_t size_in) { MP_DEFINE_CONST_FUN_OBJ_2(mod_jni_array_obj, mod_jni_array); -STATIC mp_obj_t mod_jni_env() { - return mp_obj_new_int((mp_int_t)env); +STATIC mp_obj_t mod_jni_env(void) { + return mp_obj_new_int((mp_int_t)(uintptr_t)env); } MP_DEFINE_CONST_FUN_OBJ_0(mod_jni_env_obj, mod_jni_env); diff --git a/ports/unix/modos.c b/ports/unix/modos.c index 57e00fa0c5..43d7590518 100644 --- a/ports/unix/modos.c +++ b/ports/unix/modos.c @@ -37,6 +37,7 @@ #include "py/runtime.h" #include "py/objtuple.h" #include "py/mphal.h" +#include "extmod/vfs.h" #include "extmod/misc.h" #ifdef __ANDROID__ @@ -106,16 +107,21 @@ STATIC mp_obj_t mod_os_statvfs(mp_obj_t path_in) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_os_statvfs_obj, mod_os_statvfs); #endif -STATIC mp_obj_t mod_os_unlink(mp_obj_t path_in) { +STATIC mp_obj_t mod_os_remove(mp_obj_t path_in) { const char *path = mp_obj_str_get_str(path_in); + // Note that POSIX requires remove() to be able to delete a directory + // too (act as rmdir()). This is POSIX extenstion to ANSI C semantics + // of that function. But Python remove() follows ANSI C, and explicitly + // required to raise exception on attempt to remove a directory. Thus, + // call POSIX unlink() here. int r = unlink(path); RAISE_ERRNO(r, errno); return mp_const_none; } -STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_os_unlink_obj, mod_os_unlink); +STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_os_remove_obj, mod_os_remove); STATIC mp_obj_t mod_os_system(mp_obj_t cmd_in) { const char *cmd = mp_obj_str_get_str(cmd_in); @@ -172,12 +178,24 @@ STATIC mp_obj_t listdir_next(mp_obj_t self_in) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL)); t->items[0] = mp_obj_new_str(dirent->d_name, strlen(dirent->d_name)); + #ifdef _DIRENT_HAVE_D_TYPE - t->items[1] = MP_OBJ_NEW_SMALL_INT(dirent->d_type); + #ifdef DTTOIF + t->items[1] = MP_OBJ_NEW_SMALL_INT(DTTOIF(dirent->d_type)); + #else + if (dirent->d_type == DT_DIR) { + t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR); + } else if (dirent->d_type == DT_REG) { + t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFREG); + } else { + t->items[1] = MP_OBJ_NEW_SMALL_INT(dirent->d_type); + } + #endif #else // DT_UNKNOWN should have 0 value on any reasonable system t->items[1] = MP_OBJ_NEW_SMALL_INT(0); #endif + #ifdef _DIRENT_HAVE_D_INO t->items[2] = MP_OBJ_NEW_SMALL_INT(dirent->d_ino); #else @@ -217,7 +235,7 @@ STATIC const mp_rom_map_elem_t mp_module_os_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&mod_os_statvfs_obj) }, #endif { MP_ROM_QSTR(MP_QSTR_system), MP_ROM_PTR(&mod_os_system_obj) }, - { MP_ROM_QSTR(MP_QSTR_unlink), MP_ROM_PTR(&mod_os_unlink_obj) }, + { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&mod_os_remove_obj) }, { MP_ROM_QSTR(MP_QSTR_getenv), MP_ROM_PTR(&mod_os_getenv_obj) }, { MP_ROM_QSTR(MP_QSTR_mkdir), MP_ROM_PTR(&mod_os_mkdir_obj) }, { MP_ROM_QSTR(MP_QSTR_ilistdir), MP_ROM_PTR(&mod_os_ilistdir_obj) }, diff --git a/ports/unix/moduselect.c b/ports/unix/moduselect.c index 4d0fa37c10..d4c6a8e179 100644 --- a/ports/unix/moduselect.c +++ b/ports/unix/moduselect.c @@ -34,6 +34,7 @@ #include #include "py/runtime.h" +#include "py/stream.h" #include "py/obj.h" #include "py/objlist.h" #include "py/objtuple.h" @@ -65,19 +66,15 @@ typedef struct _mp_obj_poll_t { } mp_obj_poll_t; STATIC int get_fd(mp_obj_t fdlike) { - int fd; - // Shortcut for fdfile compatible types - if (MP_OBJ_IS_TYPE(fdlike, &mp_type_fileio) - #if MICROPY_PY_SOCKET - || MP_OBJ_IS_TYPE(fdlike, &mp_type_socket) - #endif - ) { - mp_obj_fdfile_t *fdfile = MP_OBJ_TO_PTR(fdlike); - fd = fdfile->fd; - } else { - fd = mp_obj_get_int(fdlike); + if (MP_OBJ_IS_OBJ(fdlike)) { + const mp_stream_p_t *stream_p = mp_get_stream_raise(fdlike, MP_STREAM_OP_IOCTL); + int err; + mp_uint_t res = stream_p->ioctl(fdlike, MP_STREAM_GET_FILENO, 0, &err); + if (res != MP_STREAM_ERROR) { + return res; + } } - return fd; + return mp_obj_get_int(fdlike); } /// \method register(obj[, eventmask]) @@ -161,13 +158,13 @@ STATIC mp_obj_t poll_modify(mp_obj_t self_in, mp_obj_t obj_in, mp_obj_t eventmas for (int i = self->len - 1; i >= 0; i--) { if (entries->fd == fd) { entries->events = mp_obj_get_int(eventmask_in); - break; + return mp_const_none; } entries++; } - // TODO raise KeyError if obj didn't exist in map - return mp_const_none; + // obj doesn't exist in poller + mp_raise_OSError(MP_ENOENT); } MP_DEFINE_CONST_FUN_OBJ_3(poll_modify_obj, poll_modify); diff --git a/ports/unix/modusocket.c b/ports/unix/modusocket.c index 89480c0cc6..24778b6b55 100644 --- a/ports/unix/modusocket.c +++ b/ports/unix/modusocket.c @@ -37,6 +37,7 @@ #include #include #include +#include #include "py/objtuple.h" #include "py/objstr.h" @@ -67,6 +68,7 @@ typedef struct _mp_obj_socket_t { mp_obj_base_t base; int fd; + bool blocking; } mp_obj_socket_t; const mp_obj_type_t mp_type_socket; @@ -80,6 +82,7 @@ STATIC mp_obj_socket_t *socket_new(int fd) { mp_obj_socket_t *o = m_new_obj(mp_obj_socket_t); o->base.type = &mp_type_socket; o->fd = fd; + o->blocking = true; return o; } @@ -94,7 +97,14 @@ STATIC mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errc mp_obj_socket_t *o = MP_OBJ_TO_PTR(o_in); mp_int_t r = read(o->fd, buf, size); if (r == -1) { - *errcode = errno; + int err = errno; + // On blocking socket, we get EAGAIN in case SO_RCVTIMEO/SO_SNDTIMEO + // timed out, and need to convert that to ETIMEDOUT. + if (err == EAGAIN && o->blocking) { + err = MP_ETIMEDOUT; + } + + *errcode = err; return MP_STREAM_ERROR; } return r; @@ -104,7 +114,14 @@ STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, in mp_obj_socket_t *o = MP_OBJ_TO_PTR(o_in); mp_int_t r = write(o->fd, buf, size); if (r == -1) { - *errcode = errno; + int err = errno; + // On blocking socket, we get EAGAIN in case SO_RCVTIMEO/SO_SNDTIMEO + // timed out, and need to convert that to ETIMEDOUT. + if (err == EAGAIN && o->blocking) { + err = MP_ETIMEDOUT; + } + + *errcode = err; return MP_STREAM_ERROR; } return r; @@ -125,6 +142,9 @@ STATIC mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, i close(self->fd); return 0; + case MP_STREAM_GET_FILENO: + return self->fd; + default: *errcode = MP_EINVAL; return MP_STREAM_ERROR; @@ -309,10 +329,49 @@ STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) { } flags = fcntl(self->fd, F_SETFL, flags); RAISE_ERRNO(flags, errno); + self->blocking = val; return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking); +STATIC mp_obj_t socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) { + mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in); + struct timeval tv = {0,}; + bool new_blocking = true; + + if (timeout_in == mp_const_none) { + setsockopt(self->fd, SOL_SOCKET, SO_RCVTIMEO, NULL, 0); + setsockopt(self->fd, SOL_SOCKET, SO_SNDTIMEO, NULL, 0); + } else { + #if MICROPY_PY_BUILTINS_FLOAT + mp_float_t val = mp_obj_get_float(timeout_in); + double ipart; + tv.tv_usec = round(modf(val, &ipart) * 1000000); + tv.tv_sec = ipart; + #else + tv.tv_sec = mp_obj_get_int(timeout_in); + #endif + + // For SO_RCVTIMEO/SO_SNDTIMEO, zero timeout means infinity, but + // for Python API it means non-blocking. + if (tv.tv_sec == 0 && tv.tv_usec == 0) { + new_blocking = false; + } else { + setsockopt(self->fd, SOL_SOCKET, SO_RCVTIMEO, + &tv, sizeof(struct timeval)); + setsockopt(self->fd, SOL_SOCKET, SO_SNDTIMEO, + &tv, sizeof(struct timeval)); + } + } + + if (self->blocking != new_blocking) { + socket_setblocking(self_in, mp_obj_new_bool(new_blocking)); + } + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_settimeout_obj, socket_settimeout); + STATIC mp_obj_t socket_makefile(size_t n_args, const mp_obj_t *args) { // TODO: CPython explicitly says that closing returned object doesn't close // the original socket (Python2 at all says that fd is dup()ed). But we @@ -368,6 +427,7 @@ STATIC const mp_rom_map_elem_t usocket_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_sendto), MP_ROM_PTR(&socket_sendto_obj) }, { MP_ROM_QSTR(MP_QSTR_setsockopt), MP_ROM_PTR(&socket_setsockopt_obj) }, { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) }, + { MP_ROM_QSTR(MP_QSTR_settimeout), MP_ROM_PTR(&socket_settimeout_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, }; diff --git a/ports/unix/mpconfigport.h b/ports/unix/mpconfigport.h index bae0245d05..01e5876b0b 100644 --- a/ports/unix/mpconfigport.h +++ b/ports/unix/mpconfigport.h @@ -54,7 +54,7 @@ #define MICROPY_DEBUG_PRINTERS (1) // Printing debug to stderr may give tests which // check stdout a chance to pass, etc. -#define MICROPY_DEBUG_PRINTER_DEST mp_stderr_print +#define MICROPY_DEBUG_PRINTER (&mp_stderr_print) #define MICROPY_READER_POSIX (1) #define MICROPY_USE_READLINE_HISTORY (1) #define MICROPY_HELPER_REPL (1) @@ -125,7 +125,9 @@ #define MICROPY_PY_UTIMEQ (1) #define MICROPY_PY_UHASHLIB (1) #if MICROPY_PY_USSL +#define MICROPY_PY_UHASHLIB_MD5 (1) #define MICROPY_PY_UHASHLIB_SHA1 (1) +#define MICROPY_PY_UCRYPTOLIB (1) #endif #define MICROPY_PY_UBINASCII (1) #define MICROPY_PY_UBINASCII_CRC32 (1) @@ -133,9 +135,9 @@ #ifndef MICROPY_PY_USELECT_POSIX #define MICROPY_PY_USELECT_POSIX (1) #endif -#define MICROPY_PY_WEBSOCKET (1) -#define MICROPY_PY_MACHINE (1) -#define MICROPY_PY_MACHINE_PULSE (1) +#define MICROPY_PY_WEBSOCKET (0) +#define MICROPY_PY_MACHINE (0) +#define MICROPY_PY_MACHINE_PULSE (0) #define MICROPY_MACHINE_MEM_GET_READ_ADDR mod_machine_mem_get_addr #define MICROPY_MACHINE_MEM_GET_WRITE_ADDR mod_machine_mem_get_addr @@ -189,6 +191,11 @@ extern const struct _mp_obj_module_t mp_module_jni; #else #define MICROPY_PY_FFI_DEF #endif +#if MICROPY_PY_MACHINE +#define MICROPY_PY_MACHINE_DEF { MP_ROM_QSTR(MP_QSTR_umachine), MP_ROM_PTR(&mp_module_machine) }, +#else +#define MICROPY_PY_MACHINE_DEF +#endif #if MICROPY_PY_JNI #define MICROPY_PY_JNI_DEF { MP_ROM_QSTR(MP_QSTR_jni), MP_ROM_PTR(&mp_module_jni) }, #else @@ -220,7 +227,7 @@ extern const struct _mp_obj_module_t mp_module_jni; MICROPY_PY_JNI_DEF \ MICROPY_PY_UTIME_DEF \ MICROPY_PY_SOCKET_DEF \ - { MP_ROM_QSTR(MP_QSTR_umachine), MP_ROM_PTR(&mp_module_machine) }, \ + MICROPY_PY_MACHINE_DEF \ MICROPY_PY_UOS_DEF \ MICROPY_PY_USELECT_DEF \ MICROPY_PY_TERMIOS_DEF \ diff --git a/ports/unix/mpconfigport.mk b/ports/unix/mpconfigport.mk index 6bb1c9693f..d0e5686024 100644 --- a/ports/unix/mpconfigport.mk +++ b/ports/unix/mpconfigport.mk @@ -24,11 +24,11 @@ MICROPY_PY_SOCKET = 1 MICROPY_PY_FFI = 1 # ussl module requires one of the TLS libraries below -MICROPY_PY_USSL = 1 +MICROPY_PY_USSL = 0 # axTLS has minimal size and fully integrated with MicroPython, but # implements only a subset of modern TLS functionality, so may have # problems with some servers. -MICROPY_SSL_AXTLS = 1 +MICROPY_SSL_AXTLS = 0 # mbedTLS is more up to date and complete implementation, but also # more bloated. Configuring and building of mbedTLS should be done # outside of MicroPython, it can just link with mbedTLS library. diff --git a/ports/unix/mpconfigport_coverage.h b/ports/unix/mpconfigport_coverage.h index 468d69a733..27086a167d 100644 --- a/ports/unix/mpconfigport_coverage.h +++ b/ports/unix/mpconfigport_coverage.h @@ -32,23 +32,32 @@ #include +#define MICROPY_OPT_MATH_FACTORIAL (1) #define MICROPY_FLOAT_HIGH_QUALITY_HASH (1) #define MICROPY_ENABLE_SCHEDULER (1) #define MICROPY_READER_VFS (1) +#define MICROPY_MODULE_GETATTR (1) #define MICROPY_PY_DELATTR_SETATTR (1) #define MICROPY_PY_REVERSE_SPECIAL_METHODS (1) #define MICROPY_PY_BUILTINS_RANGE_BINOP (1) #define MICROPY_PY_BUILTINS_HELP (1) #define MICROPY_PY_BUILTINS_HELP_MODULES (1) #define MICROPY_PY_SYS_GETSIZEOF (1) +#define MICROPY_PY_MATH_FACTORIAL (1) #define MICROPY_PY_URANDOM_EXTRA_FUNCS (1) #define MICROPY_PY_IO_BUFFEREDWRITER (1) #define MICROPY_PY_IO_RESOURCE_STREAM (1) +#define MICROPY_PY_URE_MATCH_GROUPS (1) +#define MICROPY_PY_URE_MATCH_SPAN_START_END (1) +#define MICROPY_PY_URE_SUB (1) #define MICROPY_VFS_POSIX (1) #undef MICROPY_VFS_FAT #define MICROPY_VFS_FAT (1) #define MICROPY_FATFS_USE_LABEL (1) #define MICROPY_PY_FRAMEBUF (1) +#define MICROPY_PY_COLLECTIONS_NAMEDTUPLE__ASDICT (1) +#define MICROPY_PY_COLLECTIONS_ORDEREDDICT (1) +#define MICROPY_PY_UCRYPTOLIB (1) // TODO these should be generic, not bound to fatfs #define mp_type_fileio mp_type_vfs_posix_fileio diff --git a/ports/unix/mpconfigport_minimal.h b/ports/unix/mpconfigport_minimal.h index 1a13d5725b..3977818b03 100644 --- a/ports/unix/mpconfigport_minimal.h +++ b/ports/unix/mpconfigport_minimal.h @@ -65,6 +65,8 @@ #define MICROPY_PY_BUILTINS_REVERSED (0) #define MICROPY_PY_BUILTINS_SET (0) #define MICROPY_PY_BUILTINS_SLICE (0) +#define MICROPY_PY_BUILTINS_STR_COUNT (0) +#define MICROPY_PY_BUILTINS_STR_OP_MODULO (0) #define MICROPY_PY_BUILTINS_STR_UNICODE (0) #define MICROPY_PY_BUILTINS_PROPERTY (0) #define MICROPY_PY_BUILTINS_MIN_MAX (0) diff --git a/py/argcheck.c b/py/argcheck.c index 7fba9dc274..684fb204f0 100644 --- a/py/argcheck.c +++ b/py/argcheck.c @@ -31,27 +31,20 @@ #include "supervisor/shared/translate.h" - -void mp_arg_check_num(size_t n_args, mp_map_t *kw_args, size_t n_args_min, size_t n_args_max, bool takes_kw) { - size_t n_kw = 0; - if (kw_args != NULL) { - n_kw = kw_args->used; - } - mp_arg_check_num_kw_array(n_args, n_kw, n_args_min, n_args_max, takes_kw); -} - -void mp_arg_check_num_kw_array(size_t n_args, size_t n_kw, size_t n_args_min, size_t n_args_max, bool takes_kw) { - // NOTE(tannewt): This prevents this function from being optimized away. - // Without it, functions can crash when reading invalid args. - __asm volatile (""); +void mp_arg_check_num_sig(size_t n_args, size_t n_kw, uint32_t sig) { // TODO maybe take the function name as an argument so we can print nicer error messages - if (n_kw > 0 && !takes_kw) { - #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_arg_error_terse_mismatch(); - #else - mp_raise_TypeError(translate("function does not take keyword arguments")); - #endif + // The reverse of MP_OBJ_FUN_MAKE_SIG + bool takes_kw = sig & 1; + size_t n_args_min = sig >> 17; + size_t n_args_max = (sig >> 1) & 0xffff; + + if (n_kw && !takes_kw) { + if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { + mp_arg_error_terse_mismatch(); + } else { + mp_raise_TypeError(translate("function doesn't take keyword arguments")); + } } if (n_args_min == n_args_max) { @@ -85,6 +78,18 @@ void mp_arg_check_num_kw_array(size_t n_args, size_t n_kw, size_t n_args_min, si } } +inline void mp_arg_check_num(size_t n_args, mp_map_t *kw_args, size_t n_args_min, size_t n_args_max, bool takes_kw) { + size_t n_kw = 0; + if (kw_args != NULL) { + n_kw = kw_args->used; + } + mp_arg_check_num_sig(n_args, n_kw, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, takes_kw)); +} + +inline void mp_arg_check_num_kw_array(size_t n_args, size_t n_kw, size_t n_args_min, size_t n_args_max, bool takes_kw) { + mp_arg_check_num_sig(n_args, n_kw, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, takes_kw)); +} + void mp_arg_parse_all(size_t n_pos, const mp_obj_t *pos, mp_map_t *kws, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals) { size_t pos_found = 0, kws_found = 0; for (size_t i = 0; i < n_allowed; i++) { diff --git a/py/asmarm.c b/py/asmarm.c index 644548cfd4..871f0bb486 100644 --- a/py/asmarm.c +++ b/py/asmarm.c @@ -273,6 +273,21 @@ void asm_arm_mov_reg_local_addr(asm_arm_t *as, uint rd, int local_num) { emit_al(as, asm_arm_op_add_imm(rd, ASM_ARM_REG_SP, local_num << 2)); } +void asm_arm_mov_reg_pcrel(asm_arm_t *as, uint reg_dest, uint label) { + assert(label < as->base.max_num_labels); + mp_uint_t dest = as->base.label_offsets[label]; + mp_int_t rel = dest - as->base.code_offset; + rel -= 12 + 8; // adjust for load of rel, and then PC+8 prefetch of add_reg_reg_reg + + // To load rel int reg_dest, insert immediate into code and jump over it + emit_al(as, 0x59f0000 | (reg_dest << 12)); // ldr rd, [pc] + emit_al(as, 0xa000000); // b pc + emit(as, rel); + + // Do reg_dest += PC + asm_arm_add_reg_reg_reg(as, reg_dest, reg_dest, ASM_ARM_REG_PC); +} + void asm_arm_lsl_reg_reg(asm_arm_t *as, uint rd, uint rs) { // mov rd, rd, lsl rs emit_al(as, 0x1a00010 | (rd << 12) | (rs << 8) | rd); @@ -347,19 +362,15 @@ void asm_arm_b_label(asm_arm_t *as, uint label) { asm_arm_bcc_label(as, ASM_ARM_CC_AL, label); } -void asm_arm_bl_ind(asm_arm_t *as, void *fun_ptr, uint fun_id, uint reg_temp) { - // If the table offset fits into the ldr instruction - if (fun_id < (0x1000 / 4)) { - emit_al(as, asm_arm_op_mov_reg(ASM_ARM_REG_LR, ASM_ARM_REG_PC)); // mov lr, pc - emit_al(as, 0x597f000 | (fun_id << 2)); // ldr pc, [r7, #fun_id*4] - return; - } +void asm_arm_bl_ind(asm_arm_t *as, uint fun_id, uint reg_temp) { + // The table offset should fit into the ldr instruction + assert(fun_id < (0x1000 / 4)); + emit_al(as, asm_arm_op_mov_reg(ASM_ARM_REG_LR, ASM_ARM_REG_PC)); // mov lr, pc + emit_al(as, 0x597f000 | (fun_id << 2)); // ldr pc, [r7, #fun_id*4] +} - emit_al(as, 0x59f0004 | (reg_temp << 12)); // ldr rd, [pc, #4] - // Set lr after fun_ptr - emit_al(as, asm_arm_op_add_imm(ASM_ARM_REG_LR, ASM_ARM_REG_PC, 4)); // add lr, pc, #4 - emit_al(as, asm_arm_op_mov_reg(ASM_ARM_REG_PC, reg_temp)); // mov pc, reg_temp - emit(as, (uint)fun_ptr); +void asm_arm_bx_reg(asm_arm_t *as, uint reg_src) { + emit_al(as, 0x012fff10 | reg_src); } #endif // MICROPY_EMIT_ARM diff --git a/py/asmarm.h b/py/asmarm.h index f63106a9b6..76850cb468 100644 --- a/py/asmarm.h +++ b/py/asmarm.h @@ -98,6 +98,7 @@ void asm_arm_and_reg_reg_reg(asm_arm_t *as, uint rd, uint rn, uint rm); void asm_arm_eor_reg_reg_reg(asm_arm_t *as, uint rd, uint rn, uint rm); void asm_arm_orr_reg_reg_reg(asm_arm_t *as, uint rd, uint rn, uint rm); void asm_arm_mov_reg_local_addr(asm_arm_t *as, uint rd, int local_num); +void asm_arm_mov_reg_pcrel(asm_arm_t *as, uint reg_dest, uint label); void asm_arm_lsl_reg_reg(asm_arm_t *as, uint rd, uint rs); void asm_arm_asr_reg_reg(asm_arm_t *as, uint rd, uint rs); @@ -120,7 +121,11 @@ void asm_arm_pop(asm_arm_t *as, uint reglist); // control flow void asm_arm_bcc_label(asm_arm_t *as, int cond, uint label); void asm_arm_b_label(asm_arm_t *as, uint label); -void asm_arm_bl_ind(asm_arm_t *as, void *fun_ptr, uint fun_id, uint reg_temp); +void asm_arm_bl_ind(asm_arm_t *as, uint fun_id, uint reg_temp); +void asm_arm_bx_reg(asm_arm_t *as, uint reg_src); + +// Holds a pointer to mp_fun_table +#define ASM_ARM_REG_FUN_TABLE ASM_ARM_REG_R7 #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -144,18 +149,21 @@ void asm_arm_bl_ind(asm_arm_t *as, void *fun_ptr, uint fun_id, uint reg_temp); #define REG_LOCAL_3 ASM_ARM_REG_R6 #define REG_LOCAL_NUM (3) +// Holds a pointer to mp_fun_table +#define REG_FUN_TABLE ASM_ARM_REG_FUN_TABLE + #define ASM_T asm_arm_t #define ASM_END_PASS asm_arm_end_pass #define ASM_ENTRY asm_arm_entry #define ASM_EXIT asm_arm_exit #define ASM_JUMP asm_arm_b_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ asm_arm_cmp_reg_i8(as, reg, 0); \ asm_arm_bcc_label(as, ASM_ARM_CC_EQ, label); \ } while (0) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ do { \ asm_arm_cmp_reg_i8(as, reg, 0); \ asm_arm_bcc_label(as, ASM_ARM_CC_NE, label); \ @@ -165,14 +173,15 @@ void asm_arm_bl_ind(asm_arm_t *as, void *fun_ptr, uint fun_id, uint reg_temp); asm_arm_cmp_reg_reg(as, reg1, reg2); \ asm_arm_bcc_label(as, ASM_ARM_CC_EQ, label); \ } while (0) -#define ASM_CALL_IND(as, ptr, idx) asm_arm_bl_ind(as, ptr, idx, ASM_ARM_REG_R3) +#define ASM_JUMP_REG(as, reg) asm_arm_bx_reg((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_arm_bl_ind(as, idx, ASM_ARM_REG_R3) #define ASM_MOV_LOCAL_REG(as, local_num, reg_src) asm_arm_mov_local_reg((as), (local_num), (reg_src)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_arm_mov_reg_i32((as), (reg_dest), (imm)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_arm_mov_reg_i32((as), (reg_dest), (imm)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_arm_mov_reg_local((as), (reg_dest), (local_num)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_arm_mov_reg_reg((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_arm_mov_reg_local_addr((as), (reg_dest), (local_num)) +#define ASM_MOV_REG_PCREL(as, reg_dest, label) asm_arm_mov_reg_pcrel((as), (reg_dest), (label)) #define ASM_LSL_REG_REG(as, reg_dest, reg_shift) asm_arm_lsl_reg_reg((as), (reg_dest), (reg_shift)) #define ASM_ASR_REG_REG(as, reg_dest, reg_shift) asm_arm_asr_reg_reg((as), (reg_dest), (reg_shift)) diff --git a/py/asmthumb.c b/py/asmthumb.c index 33ec420046..df7c88568c 100644 --- a/py/asmthumb.c +++ b/py/asmthumb.c @@ -36,6 +36,8 @@ #include "py/mphal.h" #include "py/asmthumb.h" +#define UNSIGNED_FIT5(x) ((uint32_t)(x) < 32) +#define UNSIGNED_FIT7(x) ((uint32_t)(x) < 128) #define UNSIGNED_FIT8(x) (((x) & 0xffffff00) == 0) #define UNSIGNED_FIT16(x) (((x) & 0xffff0000) == 0) #define SIGNED_FIT8(x) (((x) & 0xffffff80) == 0) || (((x) & 0xffffff80) == 0xffffff80) @@ -43,6 +45,15 @@ #define SIGNED_FIT12(x) (((x) & 0xfffff800) == 0) || (((x) & 0xfffff800) == 0xfffff800) #define SIGNED_FIT23(x) (((x) & 0xffc00000) == 0) || (((x) & 0xffc00000) == 0xffc00000) +// Note: these actually take an imm12 but the high-bit is not encoded here +#define OP_ADD_W_RRI_HI(reg_src) (0xf200 | (reg_src)) +#define OP_ADD_W_RRI_LO(reg_dest, imm11) ((imm11 << 4 & 0x7000) | reg_dest << 8 | (imm11 & 0xff)) +#define OP_SUB_W_RRI_HI(reg_src) (0xf2a0 | (reg_src)) +#define OP_SUB_W_RRI_LO(reg_dest, imm11) ((imm11 << 4 & 0x7000) | reg_dest << 8 | (imm11 & 0xff)) + +#define OP_LDR_W_HI(reg_base) (0xf8d0 | (reg_base)) +#define OP_LDR_W_LO(reg_dest, imm12) ((reg_dest) << 12 | (imm12)) + static inline byte *asm_thumb_get_cur_to_write_bytes(asm_thumb_t *as, int n) { return mp_asm_base_get_cur_to_write_bytes(&as->base, n); } @@ -51,7 +62,7 @@ void asm_thumb_end_pass(asm_thumb_t *as) { (void)as; // could check labels are resolved... - #if defined(MCU_SERIES_F7) + #if defined(__ICACHE_PRESENT) && __ICACHE_PRESENT == 1 if (as->base.pass == MP_ASM_PASS_EMIT) { // flush D-cache, so the code emitted is stored in memory MP_HAL_CLEAN_DCACHE(as->base.code_base, as->base.code_size); @@ -89,6 +100,7 @@ STATIC void asm_thumb_write_word32(asm_thumb_t *as, int w32) { #define OP_POP_RLIST(rlolist) (0xbc00 | (rlolist)) #define OP_POP_RLIST_PC(rlolist) (0xbc00 | 0x0100 | (rlolist)) +// The number of words must fit in 7 unsigned bits #define OP_ADD_SP(num_words) (0xb000 | (num_words)) #define OP_SUB_SP(num_words) (0xb080 | (num_words)) @@ -142,7 +154,11 @@ void asm_thumb_entry(asm_thumb_t *as, int num_locals) { } asm_thumb_op16(as, OP_PUSH_RLIST_LR(reglist)); if (stack_adjust > 0) { - asm_thumb_op16(as, OP_SUB_SP(stack_adjust)); + if (UNSIGNED_FIT7(stack_adjust)) { + asm_thumb_op16(as, OP_SUB_SP(stack_adjust)); + } else { + asm_thumb_op32(as, OP_SUB_W_RRI_HI(ASM_THUMB_REG_SP), OP_SUB_W_RRI_LO(ASM_THUMB_REG_SP, stack_adjust * 4)); + } } as->push_reglist = reglist; as->stack_adjust = stack_adjust; @@ -150,7 +166,11 @@ void asm_thumb_entry(asm_thumb_t *as, int num_locals) { void asm_thumb_exit(asm_thumb_t *as) { if (as->stack_adjust > 0) { - asm_thumb_op16(as, OP_ADD_SP(as->stack_adjust)); + if (UNSIGNED_FIT7(as->stack_adjust)) { + asm_thumb_op16(as, OP_ADD_SP(as->stack_adjust)); + } else { + asm_thumb_op32(as, OP_ADD_W_RRI_HI(ASM_THUMB_REG_SP), OP_ADD_W_RRI_LO(ASM_THUMB_REG_SP, as->stack_adjust * 4)); + } } asm_thumb_op16(as, OP_POP_RLIST_PC(as->push_reglist)); } @@ -269,21 +289,6 @@ void asm_thumb_mov_reg_i32_optimised(asm_thumb_t *as, uint reg_dest, int i32) { } } -// i32 is stored as a full word in the code, and aligned to machine-word boundary -// TODO this is very inefficient, improve it! -void asm_thumb_mov_reg_i32_aligned(asm_thumb_t *as, uint reg_dest, int i32) { - // align on machine-word + 2 - if ((as->base.code_offset & 3) == 0) { - asm_thumb_op16(as, ASM_THUMB_OP_NOP); - } - // jump over the i32 value (instruction prefetch adds 2 to PC) - asm_thumb_op16(as, OP_B_N(2)); - // store i32 on machine-word aligned boundary - mp_asm_base_data(&as->base, 4, i32); - // do the actual load of the i32 value - asm_thumb_mov_reg_i32_optimised(as, reg_dest, i32); -} - #define OP_STR_TO_SP_OFFSET(rlo_dest, word_offset) (0x9000 | ((rlo_dest) << 8) | ((word_offset) & 0x00ff)) #define OP_LDR_FROM_SP_OFFSET(rlo_dest, word_offset) (0x9800 | ((rlo_dest) << 8) | ((word_offset) & 0x00ff)) @@ -310,6 +315,27 @@ void asm_thumb_mov_reg_local_addr(asm_thumb_t *as, uint rlo_dest, int local_num) asm_thumb_op16(as, OP_ADD_REG_SP_OFFSET(rlo_dest, word_offset)); } +void asm_thumb_mov_reg_pcrel(asm_thumb_t *as, uint rlo_dest, uint label) { + mp_uint_t dest = get_label_dest(as, label); + mp_int_t rel = dest - as->base.code_offset; + rel -= 4 + 4; // adjust for mov_reg_i16 and then PC+4 prefetch of add_reg_reg + rel |= 1; // to stay in Thumb state when jumping to this address + asm_thumb_mov_reg_i16(as, ASM_THUMB_OP_MOVW, rlo_dest, rel); // 4 bytes + asm_thumb_add_reg_reg(as, rlo_dest, ASM_THUMB_REG_R15); // 2 bytes +} + +static inline void asm_thumb_ldr_reg_reg_i12(asm_thumb_t *as, uint reg_dest, uint reg_base, uint word_offset) { + asm_thumb_op32(as, OP_LDR_W_HI(reg_base), OP_LDR_W_LO(reg_dest, word_offset * 4)); +} + +void asm_thumb_ldr_reg_reg_i12_optimised(asm_thumb_t *as, uint reg_dest, uint reg_base, uint word_offset) { + if (reg_dest < ASM_THUMB_REG_R8 && reg_base < ASM_THUMB_REG_R8 && UNSIGNED_FIT5(word_offset)) { + asm_thumb_ldr_rlo_rlo_i5(as, reg_dest, reg_base, word_offset); + } else { + asm_thumb_ldr_reg_reg_i12(as, reg_dest, reg_base, word_offset); + } +} + // this could be wrong, because it should have a range of +/- 16MiB... #define OP_BW_HI(byte_offset) (0xf000 | (((byte_offset) >> 12) & 0x07ff)) #define OP_BW_LO(byte_offset) (0xb800 | (((byte_offset) >> 1) & 0x07ff)) @@ -355,25 +381,10 @@ void asm_thumb_bcc_label(asm_thumb_t *as, int cond, uint label) { #define OP_BLX(reg) (0x4780 | ((reg) << 3)) #define OP_SVC(arg) (0xdf00 | (arg)) -void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp) { - /* TODO make this use less bytes - uint rlo_base = ASM_THUMB_REG_R3; - uint rlo_dest = ASM_THUMB_REG_R7; - uint word_offset = 4; - asm_thumb_op16(as, 0x0000); - asm_thumb_op16(as, 0x6800 | (word_offset << 6) | (rlo_base << 3) | rlo_dest); // ldr rlo_dest, [rlo_base, #offset] - asm_thumb_op16(as, 0x4780 | (ASM_THUMB_REG_R9 << 3)); // blx reg - */ - - if (fun_id < 32) { - // load ptr to function from table, indexed by fun_id (must be in range 0-31); 4 bytes - asm_thumb_op16(as, ASM_THUMB_FORMAT_9_10_ENCODE(ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, reg_temp, ASM_THUMB_REG_R7, fun_id)); - asm_thumb_op16(as, OP_BLX(reg_temp)); - } else { - // load ptr to function into register using immediate; 6 bytes - asm_thumb_mov_reg_i32(as, reg_temp, (mp_uint_t)fun_ptr); - asm_thumb_op16(as, OP_BLX(reg_temp)); - } +void asm_thumb_bl_ind(asm_thumb_t *as, uint fun_id, uint reg_temp) { + // Load ptr to function from table, indexed by fun_id, then call it + asm_thumb_ldr_reg_reg_i12_optimised(as, reg_temp, ASM_THUMB_REG_FUN_TABLE, fun_id); + asm_thumb_op16(as, OP_BLX(reg_temp)); } #endif // MICROPY_EMIT_THUMB || MICROPY_EMIT_INLINE_THUMB diff --git a/py/asmthumb.h b/py/asmthumb.h index 6acf305a2d..b4828b125d 100644 --- a/py/asmthumb.h +++ b/py/asmthumb.h @@ -46,6 +46,7 @@ #define ASM_THUMB_REG_R13 (13) #define ASM_THUMB_REG_R14 (14) #define ASM_THUMB_REG_R15 (15) +#define ASM_THUMB_REG_SP (ASM_THUMB_REG_R13) #define ASM_THUMB_REG_LR (REG_R14) #define ASM_THUMB_CC_EQ (0x0) @@ -195,6 +196,26 @@ static inline void asm_thumb_cmp_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rl asm_thumb_format_4(as, ASM_THUMB_FORMAT_4_CMP, rlo_dest, rlo_src); } +// FORMAT 5: hi register operations (add, cmp, mov, bx) +// For add/cmp/mov, at least one of the args must be a high register + +#define ASM_THUMB_FORMAT_5_ADD (0x4400) +#define ASM_THUMB_FORMAT_5_BX (0x4700) + +#define ASM_THUMB_FORMAT_5_ENCODE(op, r_dest, r_src) \ + ((op) | ((r_dest) << 4 & 0x0080) | ((r_src) << 3) | ((r_dest) & 0x0007)) + +static inline void asm_thumb_format_5(asm_thumb_t *as, uint op, uint r_dest, uint r_src) { + asm_thumb_op16(as, ASM_THUMB_FORMAT_5_ENCODE(op, r_dest, r_src)); +} + +static inline void asm_thumb_add_reg_reg(asm_thumb_t *as, uint r_dest, uint r_src) { + asm_thumb_format_5(as, ASM_THUMB_FORMAT_5_ADD, r_dest, r_src); +} +static inline void asm_thumb_bx_reg(asm_thumb_t *as, uint r_src) { + asm_thumb_format_5(as, ASM_THUMB_FORMAT_5_BX, 0, r_src); +} + // FORMAT 9: load/store with immediate offset // For word transfers the offset must be aligned, and >>2 @@ -251,14 +272,19 @@ bool asm_thumb_bl_label(asm_thumb_t *as, uint label); void asm_thumb_mov_reg_i32(asm_thumb_t *as, uint reg_dest, mp_uint_t i32_src); // convenience void asm_thumb_mov_reg_i32_optimised(asm_thumb_t *as, uint reg_dest, int i32_src); // convenience -void asm_thumb_mov_reg_i32_aligned(asm_thumb_t *as, uint reg_dest, int i32); // convenience void asm_thumb_mov_local_reg(asm_thumb_t *as, int local_num_dest, uint rlo_src); // convenience void asm_thumb_mov_reg_local(asm_thumb_t *as, uint rlo_dest, int local_num); // convenience void asm_thumb_mov_reg_local_addr(asm_thumb_t *as, uint rlo_dest, int local_num); // convenience +void asm_thumb_mov_reg_pcrel(asm_thumb_t *as, uint rlo_dest, uint label); + +void asm_thumb_ldr_reg_reg_i12_optimised(asm_thumb_t *as, uint reg_dest, uint reg_base, uint byte_offset); // convenience void asm_thumb_b_label(asm_thumb_t *as, uint label); // convenience: picks narrow or wide branch void asm_thumb_bcc_label(asm_thumb_t *as, int cc, uint label); // convenience: picks narrow or wide branch -void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp); // convenience +void asm_thumb_bl_ind(asm_thumb_t *as, uint fun_id, uint reg_temp); // convenience + +// Holds a pointer to mp_fun_table +#define ASM_THUMB_REG_FUN_TABLE ASM_THUMB_REG_R7 #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -283,18 +309,20 @@ void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp #define REG_LOCAL_3 ASM_THUMB_REG_R6 #define REG_LOCAL_NUM (3) +#define REG_FUN_TABLE ASM_THUMB_REG_FUN_TABLE + #define ASM_T asm_thumb_t #define ASM_END_PASS asm_thumb_end_pass #define ASM_ENTRY asm_thumb_entry #define ASM_EXIT asm_thumb_exit #define ASM_JUMP asm_thumb_b_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ asm_thumb_cmp_rlo_i8(as, reg, 0); \ asm_thumb_bcc_label(as, ASM_THUMB_CC_EQ, label); \ } while (0) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ do { \ asm_thumb_cmp_rlo_i8(as, reg, 0); \ asm_thumb_bcc_label(as, ASM_THUMB_CC_NE, label); \ @@ -304,14 +332,15 @@ void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp asm_thumb_cmp_rlo_rlo(as, reg1, reg2); \ asm_thumb_bcc_label(as, ASM_THUMB_CC_EQ, label); \ } while (0) -#define ASM_CALL_IND(as, ptr, idx) asm_thumb_bl_ind(as, ptr, idx, ASM_THUMB_REG_R3) +#define ASM_JUMP_REG(as, reg) asm_thumb_bx_reg((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_thumb_bl_ind(as, idx, ASM_THUMB_REG_R3) #define ASM_MOV_LOCAL_REG(as, local_num, reg) asm_thumb_mov_local_reg((as), (local_num), (reg)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_thumb_mov_reg_i32_optimised((as), (reg_dest), (imm)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_thumb_mov_reg_i32_aligned((as), (reg_dest), (imm)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_thumb_mov_reg_local((as), (reg_dest), (local_num)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_thumb_mov_reg_reg((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_thumb_mov_reg_local_addr((as), (reg_dest), (local_num)) +#define ASM_MOV_REG_PCREL(as, rlo_dest, label) asm_thumb_mov_reg_pcrel((as), (rlo_dest), (label)) #define ASM_LSL_REG_REG(as, reg_dest, reg_shift) asm_thumb_format_4((as), ASM_THUMB_FORMAT_4_LSL, (reg_dest), (reg_shift)) #define ASM_ASR_REG_REG(as, reg_dest, reg_shift) asm_thumb_format_4((as), ASM_THUMB_FORMAT_4_ASR, (reg_dest), (reg_shift)) @@ -323,7 +352,7 @@ void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp #define ASM_MUL_REG_REG(as, reg_dest, reg_src) asm_thumb_format_4((as), ASM_THUMB_FORMAT_4_MUL, (reg_dest), (reg_src)) #define ASM_LOAD_REG_REG(as, reg_dest, reg_base) asm_thumb_ldr_rlo_rlo_i5((as), (reg_dest), (reg_base), 0) -#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_thumb_ldr_rlo_rlo_i5((as), (reg_dest), (reg_base), (word_offset)) +#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_thumb_ldr_reg_reg_i12_optimised((as), (reg_dest), (reg_base), (word_offset)) #define ASM_LOAD8_REG_REG(as, reg_dest, reg_base) asm_thumb_ldrb_rlo_rlo_i5((as), (reg_dest), (reg_base), 0) #define ASM_LOAD16_REG_REG(as, reg_dest, reg_base) asm_thumb_ldrh_rlo_rlo_i5((as), (reg_dest), (reg_base), 0) #define ASM_LOAD32_REG_REG(as, reg_dest, reg_base) asm_thumb_ldr_rlo_rlo_i5((as), (reg_dest), (reg_base), 0) diff --git a/py/asmx64.c b/py/asmx64.c index 4e45f77a40..b881491121 100644 --- a/py/asmx64.c +++ b/py/asmx64.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George + * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -73,8 +73,10 @@ #define OPCODE_CMP_R64_WITH_RM64 (0x39) /* /r */ // #define OPCODE_CMP_RM32_WITH_R32 (0x3b) #define OPCODE_TEST_R8_WITH_RM8 (0x84) /* /r */ +#define OPCODE_TEST_R64_WITH_RM64 (0x85) /* /r */ #define OPCODE_JMP_REL8 (0xeb) #define OPCODE_JMP_REL32 (0xe9) +#define OPCODE_JMP_RM64 (0xff) /* /4 */ #define OPCODE_JCC_REL8 (0x70) /* | jcc type */ #define OPCODE_JCC_REL32_A (0x0f) #define OPCODE_JCC_REL32_B (0x80) /* | jcc type */ @@ -181,21 +183,22 @@ STATIC void asm_x64_write_word32_to(asm_x64_t *as, int offset, int w32) { */ STATIC void asm_x64_write_r64_disp(asm_x64_t *as, int r64, int disp_r64, int disp_offset) { - assert(disp_r64 != ASM_X64_REG_RSP); - - if (disp_r64 == ASM_X64_REG_R12) { - // special case for r12; not fully implemented - assert(SIGNED_FIT8(disp_offset)); - asm_x64_write_byte_3(as, MODRM_R64(r64) | MODRM_RM_DISP8 | MODRM_RM_R64(disp_r64), 0x24, IMM32_L0(disp_offset)); - return; - } - - if (disp_offset == 0 && disp_r64 != ASM_X64_REG_RBP) { - asm_x64_write_byte_1(as, MODRM_R64(r64) | MODRM_RM_DISP0 | MODRM_RM_R64(disp_r64)); + uint8_t rm_disp; + if (disp_offset == 0 && (disp_r64 & 7) != ASM_X64_REG_RBP) { + rm_disp = MODRM_RM_DISP0; } else if (SIGNED_FIT8(disp_offset)) { - asm_x64_write_byte_2(as, MODRM_R64(r64) | MODRM_RM_DISP8 | MODRM_RM_R64(disp_r64), IMM32_L0(disp_offset)); + rm_disp = MODRM_RM_DISP8; } else { - asm_x64_write_byte_1(as, MODRM_R64(r64) | MODRM_RM_DISP32 | MODRM_RM_R64(disp_r64)); + rm_disp = MODRM_RM_DISP32; + } + asm_x64_write_byte_1(as, MODRM_R64(r64) | rm_disp | MODRM_RM_R64(disp_r64)); + if ((disp_r64 & 7) == ASM_X64_REG_RSP) { + // Special case for rsp and r12, they need a SIB byte + asm_x64_write_byte_1(as, 0x24); + } + if (rm_disp == MODRM_RM_DISP8) { + asm_x64_write_byte_1(as, IMM32_L0(disp_offset)); + } else if (rm_disp == MODRM_RM_DISP32) { asm_x64_write_word32(as, disp_offset); } } @@ -361,15 +364,6 @@ void asm_x64_mov_i64_to_r64_optimised(asm_x64_t *as, int64_t src_i64, int dest_r } } -// src_i64 is stored as a full word in the code, and aligned to machine-word boundary -void asm_x64_mov_i64_to_r64_aligned(asm_x64_t *as, int64_t src_i64, int dest_r64) { - // mov instruction uses 2 bytes for the instruction, before the i64 - while (((as->base.code_offset + 2) & (WORD_SIZE - 1)) != 0) { - asm_x64_nop(as); - } - asm_x64_mov_i64_to_r64(as, src_i64, dest_r64); -} - void asm_x64_and_r64_r64(asm_x64_t *as, int dest_r64, int src_r64) { asm_x64_generic_r64_r64(as, dest_r64, src_r64, OPCODE_AND_R64_TO_RM64); } @@ -465,17 +459,25 @@ void asm_x64_cmp_i32_with_r32(asm_x64_t *as, int src_i32, int src_r32) { */ void asm_x64_test_r8_with_r8(asm_x64_t *as, int src_r64_a, int src_r64_b) { - // TODO implement for other registers - assert(src_r64_a == ASM_X64_REG_RAX); - assert(src_r64_b == ASM_X64_REG_RAX); + assert(src_r64_a < 8); + assert(src_r64_b < 8); asm_x64_write_byte_2(as, OPCODE_TEST_R8_WITH_RM8, MODRM_R64(src_r64_a) | MODRM_RM_REG | MODRM_RM_R64(src_r64_b)); } +void asm_x64_test_r64_with_r64(asm_x64_t *as, int src_r64_a, int src_r64_b) { + asm_x64_generic_r64_r64(as, src_r64_b, src_r64_a, OPCODE_TEST_R64_WITH_RM64); +} + void asm_x64_setcc_r8(asm_x64_t *as, int jcc_type, int dest_r8) { assert(dest_r8 < 8); asm_x64_write_byte_3(as, OPCODE_SETCC_RM8_A, OPCODE_SETCC_RM8_B | jcc_type, MODRM_R64(0) | MODRM_RM_REG | MODRM_RM_R64(dest_r8)); } +void asm_x64_jmp_reg(asm_x64_t *as, int src_r64) { + assert(src_r64 < 8); + asm_x64_write_byte_2(as, OPCODE_JMP_RM64, MODRM_R64(4) | MODRM_RM_REG | MODRM_RM_R64(src_r64)); +} + STATIC mp_uint_t get_label_dest(asm_x64_t *as, mp_uint_t label) { assert(label < as->base.max_num_labels); return as->base.label_offsets[label]; @@ -528,63 +530,72 @@ void asm_x64_jcc_label(asm_x64_t *as, int jcc_type, mp_uint_t label) { void asm_x64_entry(asm_x64_t *as, int num_locals) { assert(num_locals >= 0); asm_x64_push_r64(as, ASM_X64_REG_RBP); - asm_x64_mov_r64_r64(as, ASM_X64_REG_RBP, ASM_X64_REG_RSP); - num_locals |= 1; // make it odd so stack is aligned on 16 byte boundary - asm_x64_sub_r64_i32(as, ASM_X64_REG_RSP, num_locals * WORD_SIZE); asm_x64_push_r64(as, ASM_X64_REG_RBX); asm_x64_push_r64(as, ASM_X64_REG_R12); asm_x64_push_r64(as, ASM_X64_REG_R13); + num_locals |= 1; // make it odd so stack is aligned on 16 byte boundary + asm_x64_sub_r64_i32(as, ASM_X64_REG_RSP, num_locals * WORD_SIZE); as->num_locals = num_locals; } void asm_x64_exit(asm_x64_t *as) { + asm_x64_sub_r64_i32(as, ASM_X64_REG_RSP, -as->num_locals * WORD_SIZE); asm_x64_pop_r64(as, ASM_X64_REG_R13); asm_x64_pop_r64(as, ASM_X64_REG_R12); asm_x64_pop_r64(as, ASM_X64_REG_RBX); - asm_x64_write_byte_1(as, OPCODE_LEAVE); + asm_x64_pop_r64(as, ASM_X64_REG_RBP); asm_x64_ret(as); } // locals: // - stored on the stack in ascending order // - numbered 0 through as->num_locals-1 -// - RBP points above the last local +// - RSP points to the first local // -// | RBP -// v +// | RSP +// v // l0 l1 l2 ... l(n-1) // ^ ^ // | low address | high address in RAM // -STATIC int asm_x64_local_offset_from_ebp(asm_x64_t *as, int local_num) { - return (-as->num_locals + local_num) * WORD_SIZE; +STATIC int asm_x64_local_offset_from_rsp(asm_x64_t *as, int local_num) { + (void)as; + // Stack is full descending, RSP points to local0 + return local_num * WORD_SIZE; } void asm_x64_mov_local_to_r64(asm_x64_t *as, int src_local_num, int dest_r64) { - asm_x64_mov_mem64_to_r64(as, ASM_X64_REG_RBP, asm_x64_local_offset_from_ebp(as, src_local_num), dest_r64); + asm_x64_mov_mem64_to_r64(as, ASM_X64_REG_RSP, asm_x64_local_offset_from_rsp(as, src_local_num), dest_r64); } void asm_x64_mov_r64_to_local(asm_x64_t *as, int src_r64, int dest_local_num) { - asm_x64_mov_r64_to_mem64(as, src_r64, ASM_X64_REG_RBP, asm_x64_local_offset_from_ebp(as, dest_local_num)); + asm_x64_mov_r64_to_mem64(as, src_r64, ASM_X64_REG_RSP, asm_x64_local_offset_from_rsp(as, dest_local_num)); } void asm_x64_mov_local_addr_to_r64(asm_x64_t *as, int local_num, int dest_r64) { - int offset = asm_x64_local_offset_from_ebp(as, local_num); + int offset = asm_x64_local_offset_from_rsp(as, local_num); if (offset == 0) { - asm_x64_mov_r64_r64(as, dest_r64, ASM_X64_REG_RBP); + asm_x64_mov_r64_r64(as, dest_r64, ASM_X64_REG_RSP); } else { - asm_x64_lea_disp_to_r64(as, ASM_X64_REG_RBP, offset, dest_r64); + asm_x64_lea_disp_to_r64(as, ASM_X64_REG_RSP, offset, dest_r64); } } +void asm_x64_mov_reg_pcrel(asm_x64_t *as, int dest_r64, mp_uint_t label) { + mp_uint_t dest = get_label_dest(as, label); + mp_int_t rel = dest - (as->base.code_offset + 7); + asm_x64_write_byte_3(as, REX_PREFIX | REX_W | REX_R_FROM_R64(dest_r64), OPCODE_LEA_MEM_TO_R64, MODRM_R64(dest_r64) | MODRM_RM_R64(5)); + asm_x64_write_word32(as, rel); +} + /* void asm_x64_push_local(asm_x64_t *as, int local_num) { - asm_x64_push_disp(as, ASM_X64_REG_RBP, asm_x64_local_offset_from_ebp(as, local_num)); + asm_x64_push_disp(as, ASM_X64_REG_RSP, asm_x64_local_offset_from_rsp(as, local_num)); } void asm_x64_push_local_addr(asm_x64_t *as, int local_num, int temp_r64) { - asm_x64_mov_r64_r64(as, temp_r64, ASM_X64_REG_RBP); - asm_x64_add_i32_to_r32(as, asm_x64_local_offset_from_ebp(as, local_num), temp_r64); + asm_x64_mov_r64_r64(as, temp_r64, ASM_X64_REG_RSP); + asm_x64_add_i32_to_r32(as, asm_x64_local_offset_from_rsp(as, local_num), temp_r64); asm_x64_push_r64(as, temp_r64); } */ @@ -610,21 +621,10 @@ void asm_x64_call_i1(asm_x64_t *as, void* func, int i1) { } */ -void asm_x64_call_ind(asm_x64_t *as, void *ptr, int temp_r64) { +void asm_x64_call_ind(asm_x64_t *as, size_t fun_id, int temp_r64) { assert(temp_r64 < 8); - #ifdef __LP64__ - asm_x64_mov_i64_to_r64_optimised(as, (int64_t)ptr, temp_r64); - #else - // If we get here, sizeof(int) == sizeof(void*). - asm_x64_mov_i64_to_r64_optimised(as, (int64_t)(unsigned int)ptr, temp_r64); - #endif + asm_x64_mov_mem64_to_r64(as, ASM_X64_REG_FUN_TABLE, fun_id * WORD_SIZE, temp_r64); asm_x64_write_byte_2(as, OPCODE_CALL_RM32, MODRM_R64(2) | MODRM_RM_REG | MODRM_RM_R64(temp_r64)); - // this reduces code size by 2 bytes per call, but doesn't seem to speed it up at all - // doesn't work anymore because calls are 64 bits away - /* - asm_x64_write_byte_1(as, OPCODE_CALL_REL32); - asm_x64_write_word32(as, ptr - (void*)(as->code_base + as->code_offset + 4)); - */ } #endif // MICROPY_EMIT_X64 diff --git a/py/asmx64.h b/py/asmx64.h index 804e3b7098..ceea426d74 100644 --- a/py/asmx64.h +++ b/py/asmx64.h @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George + * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -85,7 +85,6 @@ void asm_x64_pop_r64(asm_x64_t *as, int dest_r64); void asm_x64_mov_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); void asm_x64_mov_i64_to_r64(asm_x64_t *as, int64_t src_i64, int dest_r64); void asm_x64_mov_i64_to_r64_optimised(asm_x64_t *as, int64_t src_i64, int dest_r64); -void asm_x64_mov_i64_to_r64_aligned(asm_x64_t *as, int64_t src_i64, int dest_r64); void asm_x64_mov_r8_to_mem8(asm_x64_t *as, int src_r64, int dest_r64, int dest_disp); void asm_x64_mov_r16_to_mem16(asm_x64_t *as, int src_r64, int dest_r64, int dest_disp); void asm_x64_mov_r32_to_mem32(asm_x64_t *as, int src_r64, int dest_r64, int dest_disp); @@ -104,7 +103,9 @@ void asm_x64_sub_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); void asm_x64_mul_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); void asm_x64_cmp_r64_with_r64(asm_x64_t *as, int src_r64_a, int src_r64_b); void asm_x64_test_r8_with_r8(asm_x64_t *as, int src_r64_a, int src_r64_b); +void asm_x64_test_r64_with_r64(asm_x64_t *as, int src_r64_a, int src_r64_b); void asm_x64_setcc_r8(asm_x64_t *as, int jcc_type, int dest_r8); +void asm_x64_jmp_reg(asm_x64_t *as, int src_r64); void asm_x64_jmp_label(asm_x64_t *as, mp_uint_t label); void asm_x64_jcc_label(asm_x64_t *as, int jcc_type, mp_uint_t label); void asm_x64_entry(asm_x64_t *as, int num_locals); @@ -112,7 +113,11 @@ void asm_x64_exit(asm_x64_t *as); void asm_x64_mov_local_to_r64(asm_x64_t *as, int src_local_num, int dest_r64); void asm_x64_mov_r64_to_local(asm_x64_t *as, int src_r64, int dest_local_num); void asm_x64_mov_local_addr_to_r64(asm_x64_t *as, int local_num, int dest_r64); -void asm_x64_call_ind(asm_x64_t *as, void *ptr, int temp_r32); +void asm_x64_mov_reg_pcrel(asm_x64_t *as, int dest_r64, mp_uint_t label); +void asm_x64_call_ind(asm_x64_t *as, size_t fun_id, int temp_r32); + +// Holds a pointer to mp_fun_table +#define ASM_X64_REG_FUN_TABLE ASM_X64_REG_RBP #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -139,20 +144,31 @@ void asm_x64_call_ind(asm_x64_t *as, void *ptr, int temp_r32); #define REG_LOCAL_3 ASM_X64_REG_R13 #define REG_LOCAL_NUM (3) +// Holds a pointer to mp_fun_table +#define REG_FUN_TABLE ASM_X64_REG_FUN_TABLE + #define ASM_T asm_x64_t #define ASM_END_PASS asm_x64_end_pass #define ASM_ENTRY asm_x64_entry #define ASM_EXIT asm_x64_exit #define ASM_JUMP asm_x64_jmp_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ - asm_x64_test_r8_with_r8(as, reg, reg); \ + if (bool_test) { \ + asm_x64_test_r8_with_r8((as), (reg), (reg)); \ + } else { \ + asm_x64_test_r64_with_r64((as), (reg), (reg)); \ + } \ asm_x64_jcc_label(as, ASM_X64_CC_JZ, label); \ } while (0) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ do { \ - asm_x64_test_r8_with_r8(as, reg, reg); \ + if (bool_test) { \ + asm_x64_test_r8_with_r8((as), (reg), (reg)); \ + } else { \ + asm_x64_test_r64_with_r64((as), (reg), (reg)); \ + } \ asm_x64_jcc_label(as, ASM_X64_CC_JNZ, label); \ } while (0) #define ASM_JUMP_IF_REG_EQ(as, reg1, reg2, label) \ @@ -160,14 +176,15 @@ void asm_x64_call_ind(asm_x64_t *as, void *ptr, int temp_r32); asm_x64_cmp_r64_with_r64(as, reg1, reg2); \ asm_x64_jcc_label(as, ASM_X64_CC_JE, label); \ } while (0) -#define ASM_CALL_IND(as, ptr, idx) asm_x64_call_ind(as, ptr, ASM_X64_REG_RAX) +#define ASM_JUMP_REG(as, reg) asm_x64_jmp_reg((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_x64_call_ind(as, idx, ASM_X64_REG_RAX) #define ASM_MOV_LOCAL_REG(as, local_num, reg_src) asm_x64_mov_r64_to_local((as), (reg_src), (local_num)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_x64_mov_i64_to_r64_optimised((as), (imm), (reg_dest)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_x64_mov_i64_to_r64_aligned((as), (imm), (reg_dest)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_x64_mov_local_to_r64((as), (local_num), (reg_dest)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_x64_mov_r64_r64((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_x64_mov_local_addr_to_r64((as), (local_num), (reg_dest)) +#define ASM_MOV_REG_PCREL(as, reg_dest, label) asm_x64_mov_reg_pcrel((as), (reg_dest), (label)) #define ASM_LSL_REG(as, reg) asm_x64_shl_r64_cl((as), (reg)) #define ASM_ASR_REG(as, reg) asm_x64_sar_r64_cl((as), (reg)) diff --git a/py/asmx86.c b/py/asmx86.c index 05783354ed..b238321bda 100644 --- a/py/asmx86.c +++ b/py/asmx86.c @@ -73,8 +73,10 @@ #define OPCODE_CMP_R32_WITH_RM32 (0x39) // #define OPCODE_CMP_RM32_WITH_R32 (0x3b) #define OPCODE_TEST_R8_WITH_RM8 (0x84) /* /r */ +#define OPCODE_TEST_R32_WITH_RM32 (0x85) /* /r */ #define OPCODE_JMP_REL8 (0xeb) #define OPCODE_JMP_REL32 (0xe9) +#define OPCODE_JMP_RM32 (0xff) /* /4 */ #define OPCODE_JCC_REL8 (0x70) /* | jcc type */ #define OPCODE_JCC_REL32_A (0x0f) #define OPCODE_JCC_REL32_B (0x80) /* | jcc type */ @@ -135,14 +137,22 @@ STATIC void asm_x86_write_word32(asm_x86_t *as, int w32) { } STATIC void asm_x86_write_r32_disp(asm_x86_t *as, int r32, int disp_r32, int disp_offset) { - assert(disp_r32 != ASM_X86_REG_ESP); - + uint8_t rm_disp; if (disp_offset == 0 && disp_r32 != ASM_X86_REG_EBP) { - asm_x86_write_byte_1(as, MODRM_R32(r32) | MODRM_RM_DISP0 | MODRM_RM_R32(disp_r32)); + rm_disp = MODRM_RM_DISP0; } else if (SIGNED_FIT8(disp_offset)) { - asm_x86_write_byte_2(as, MODRM_R32(r32) | MODRM_RM_DISP8 | MODRM_RM_R32(disp_r32), IMM32_L0(disp_offset)); + rm_disp = MODRM_RM_DISP8; } else { - asm_x86_write_byte_1(as, MODRM_R32(r32) | MODRM_RM_DISP32 | MODRM_RM_R32(disp_r32)); + rm_disp = MODRM_RM_DISP32; + } + asm_x86_write_byte_1(as, MODRM_R32(r32) | rm_disp | MODRM_RM_R32(disp_r32)); + if (disp_r32 == ASM_X86_REG_ESP) { + // Special case for esp, it needs a SIB byte + asm_x86_write_byte_1(as, 0x24); + } + if (rm_disp == MODRM_RM_DISP8) { + asm_x86_write_byte_1(as, IMM32_L0(disp_offset)); + } else if (rm_disp == MODRM_RM_DISP32) { asm_x86_write_word32(as, disp_offset); } } @@ -151,9 +161,11 @@ STATIC void asm_x86_generic_r32_r32(asm_x86_t *as, int dest_r32, int src_r32, in asm_x86_write_byte_2(as, op, MODRM_R32(src_r32) | MODRM_RM_REG | MODRM_RM_R32(dest_r32)); } +#if 0 STATIC void asm_x86_nop(asm_x86_t *as) { asm_x86_write_byte_1(as, OPCODE_NOP); } +#endif STATIC void asm_x86_push_r32(asm_x86_t *as, int src_r32) { asm_x86_write_byte_1(as, OPCODE_PUSH_R32 | src_r32); @@ -229,15 +241,6 @@ void asm_x86_mov_i32_to_r32(asm_x86_t *as, int32_t src_i32, int dest_r32) { asm_x86_write_word32(as, src_i32); } -// src_i32 is stored as a full word in the code, and aligned to machine-word boundary -void asm_x86_mov_i32_to_r32_aligned(asm_x86_t *as, int32_t src_i32, int dest_r32) { - // mov instruction uses 1 byte for the instruction, before the i32 - while (((as->base.code_offset + 1) & (WORD_SIZE - 1)) != 0) { - asm_x86_nop(as); - } - asm_x86_mov_i32_to_r32(as, src_i32, dest_r32); -} - void asm_x86_and_r32_r32(asm_x86_t *as, int dest_r32, int src_r32) { asm_x86_generic_r32_r32(as, dest_r32, src_r32, OPCODE_AND_R32_TO_RM32); } @@ -312,7 +315,7 @@ void asm_x86_sar_r32_by_imm(asm_x86_t *as, int r32, int imm) { #endif void asm_x86_cmp_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b) { - asm_x86_write_byte_2(as, OPCODE_CMP_R32_WITH_RM32, MODRM_R32(src_r32_a) | MODRM_RM_REG | MODRM_RM_R32(src_r32_b)); + asm_x86_generic_r32_r32(as, src_r32_b, src_r32_a, OPCODE_CMP_R32_WITH_RM32); } #if 0 @@ -328,16 +331,21 @@ void asm_x86_cmp_i32_with_r32(asm_x86_t *as, int src_i32, int src_r32) { #endif void asm_x86_test_r8_with_r8(asm_x86_t *as, int src_r32_a, int src_r32_b) { - // TODO implement for other registers - assert(src_r32_a == ASM_X86_REG_EAX); - assert(src_r32_b == ASM_X86_REG_EAX); asm_x86_write_byte_2(as, OPCODE_TEST_R8_WITH_RM8, MODRM_R32(src_r32_a) | MODRM_RM_REG | MODRM_RM_R32(src_r32_b)); } +void asm_x86_test_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b) { + asm_x86_generic_r32_r32(as, src_r32_b, src_r32_a, OPCODE_TEST_R32_WITH_RM32); +} + void asm_x86_setcc_r8(asm_x86_t *as, mp_uint_t jcc_type, int dest_r8) { asm_x86_write_byte_3(as, OPCODE_SETCC_RM8_A, OPCODE_SETCC_RM8_B | jcc_type, MODRM_R32(0) | MODRM_RM_REG | MODRM_RM_R32(dest_r8)); } +void asm_x86_jmp_reg(asm_x86_t *as, int src_r32) { + asm_x86_write_byte_2(as, OPCODE_JMP_RM32, MODRM_R32(4) | MODRM_RM_REG | MODRM_RM_R32(src_r32)); +} + STATIC mp_uint_t get_label_dest(asm_x86_t *as, mp_uint_t label) { assert(label < as->base.max_num_labels); return as->base.label_offsets[label]; @@ -390,86 +398,102 @@ void asm_x86_jcc_label(asm_x86_t *as, mp_uint_t jcc_type, mp_uint_t label) { void asm_x86_entry(asm_x86_t *as, int num_locals) { assert(num_locals >= 0); asm_x86_push_r32(as, ASM_X86_REG_EBP); - asm_x86_mov_r32_r32(as, ASM_X86_REG_EBP, ASM_X86_REG_ESP); - if (num_locals > 0) { - asm_x86_sub_r32_i32(as, ASM_X86_REG_ESP, num_locals * WORD_SIZE); - } asm_x86_push_r32(as, ASM_X86_REG_EBX); asm_x86_push_r32(as, ASM_X86_REG_ESI); asm_x86_push_r32(as, ASM_X86_REG_EDI); - // TODO align stack on 16-byte boundary + num_locals |= 1; // make it odd so stack is aligned on 16 byte boundary + asm_x86_sub_r32_i32(as, ASM_X86_REG_ESP, num_locals * WORD_SIZE); as->num_locals = num_locals; } void asm_x86_exit(asm_x86_t *as) { + asm_x86_sub_r32_i32(as, ASM_X86_REG_ESP, -as->num_locals * WORD_SIZE); asm_x86_pop_r32(as, ASM_X86_REG_EDI); asm_x86_pop_r32(as, ASM_X86_REG_ESI); asm_x86_pop_r32(as, ASM_X86_REG_EBX); - asm_x86_write_byte_1(as, OPCODE_LEAVE); + asm_x86_pop_r32(as, ASM_X86_REG_EBP); asm_x86_ret(as); } +STATIC int asm_x86_arg_offset_from_esp(asm_x86_t *as, size_t arg_num) { + // Above esp are: locals, 4 saved registers, return eip, arguments + return (as->num_locals + 4 + 1 + arg_num) * WORD_SIZE; +} + #if 0 void asm_x86_push_arg(asm_x86_t *as, int src_arg_num) { - asm_x86_push_disp(as, ASM_X86_REG_EBP, 2 * WORD_SIZE + src_arg_num * WORD_SIZE); + asm_x86_push_disp(as, ASM_X86_REG_ESP, asm_x86_arg_offset_from_esp(as, src_arg_num)); } #endif void asm_x86_mov_arg_to_r32(asm_x86_t *as, int src_arg_num, int dest_r32) { - asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_EBP, 2 * WORD_SIZE + src_arg_num * WORD_SIZE, dest_r32); + asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_ESP, asm_x86_arg_offset_from_esp(as, src_arg_num), dest_r32); } #if 0 void asm_x86_mov_r32_to_arg(asm_x86_t *as, int src_r32, int dest_arg_num) { - asm_x86_mov_r32_to_mem32(as, src_r32, ASM_X86_REG_EBP, 2 * WORD_SIZE + dest_arg_num * WORD_SIZE); + asm_x86_mov_r32_to_mem32(as, src_r32, ASM_X86_REG_ESP, asm_x86_arg_offset_from_esp(as, dest_arg_num)); } #endif // locals: // - stored on the stack in ascending order // - numbered 0 through as->num_locals-1 -// - EBP points above the last local +// - ESP points to the first local // -// | EBP -// v +// | ESP +// v // l0 l1 l2 ... l(n-1) // ^ ^ // | low address | high address in RAM // -STATIC int asm_x86_local_offset_from_ebp(asm_x86_t *as, int local_num) { - return (-as->num_locals + local_num) * WORD_SIZE; +STATIC int asm_x86_local_offset_from_esp(asm_x86_t *as, int local_num) { + (void)as; + // Stack is full descending, ESP points to local0 + return local_num * WORD_SIZE; } void asm_x86_mov_local_to_r32(asm_x86_t *as, int src_local_num, int dest_r32) { - asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_EBP, asm_x86_local_offset_from_ebp(as, src_local_num), dest_r32); + asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_ESP, asm_x86_local_offset_from_esp(as, src_local_num), dest_r32); } void asm_x86_mov_r32_to_local(asm_x86_t *as, int src_r32, int dest_local_num) { - asm_x86_mov_r32_to_mem32(as, src_r32, ASM_X86_REG_EBP, asm_x86_local_offset_from_ebp(as, dest_local_num)); + asm_x86_mov_r32_to_mem32(as, src_r32, ASM_X86_REG_ESP, asm_x86_local_offset_from_esp(as, dest_local_num)); } void asm_x86_mov_local_addr_to_r32(asm_x86_t *as, int local_num, int dest_r32) { - int offset = asm_x86_local_offset_from_ebp(as, local_num); + int offset = asm_x86_local_offset_from_esp(as, local_num); if (offset == 0) { - asm_x86_mov_r32_r32(as, dest_r32, ASM_X86_REG_EBP); + asm_x86_mov_r32_r32(as, dest_r32, ASM_X86_REG_ESP); } else { - asm_x86_lea_disp_to_r32(as, ASM_X86_REG_EBP, offset, dest_r32); + asm_x86_lea_disp_to_r32(as, ASM_X86_REG_ESP, offset, dest_r32); } } +void asm_x86_mov_reg_pcrel(asm_x86_t *as, int dest_r32, mp_uint_t label) { + asm_x86_write_byte_1(as, OPCODE_CALL_REL32); + asm_x86_write_word32(as, 0); + mp_uint_t dest = get_label_dest(as, label); + mp_int_t rel = dest - as->base.code_offset; + asm_x86_pop_r32(as, dest_r32); + // PC rel is usually a forward reference, so need to assume it's large + asm_x86_write_byte_2(as, OPCODE_ADD_I32_TO_RM32, MODRM_R32(0) | MODRM_RM_REG | MODRM_RM_R32(dest_r32)); + asm_x86_write_word32(as, rel); +} + #if 0 void asm_x86_push_local(asm_x86_t *as, int local_num) { - asm_x86_push_disp(as, ASM_X86_REG_EBP, asm_x86_local_offset_from_ebp(as, local_num)); + asm_x86_push_disp(as, ASM_X86_REG_ESP, asm_x86_local_offset_from_esp(as, local_num)); } void asm_x86_push_local_addr(asm_x86_t *as, int local_num, int temp_r32) { - asm_x86_mov_r32_r32(as, temp_r32, ASM_X86_REG_EBP); - asm_x86_add_i32_to_r32(as, asm_x86_local_offset_from_ebp(as, local_num), temp_r32); + asm_x86_mov_r32_r32(as, temp_r32, ASM_X86_REG_ESP); + asm_x86_add_i32_to_r32(as, asm_x86_local_offset_from_esp(as, local_num), temp_r32); asm_x86_push_r32(as, temp_r32); } #endif -void asm_x86_call_ind(asm_x86_t *as, void *ptr, mp_uint_t n_args, int temp_r32) { +void asm_x86_call_ind(asm_x86_t *as, size_t fun_id, mp_uint_t n_args, int temp_r32) { // TODO align stack on 16-byte boundary before the call assert(n_args <= 5); if (n_args > 4) { @@ -487,20 +511,10 @@ void asm_x86_call_ind(asm_x86_t *as, void *ptr, mp_uint_t n_args, int temp_r32) if (n_args > 0) { asm_x86_push_r32(as, ASM_X86_REG_ARG_1); } - #ifdef __LP64__ - // We wouldn't run x86 code on an x64 machine. This is here to enable - // testing of the x86 emitter only. - asm_x86_mov_i32_to_r32(as, (int32_t)(int64_t)ptr, temp_r32); - #else - // If we get here, sizeof(int) == sizeof(void*). - asm_x86_mov_i32_to_r32(as, (int32_t)ptr, temp_r32); - #endif + + // Load the pointer to the function and make the call + asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_FUN_TABLE, fun_id * WORD_SIZE, temp_r32); asm_x86_write_byte_2(as, OPCODE_CALL_RM32, MODRM_R32(2) | MODRM_RM_REG | MODRM_RM_R32(temp_r32)); - // this reduces code size by 2 bytes per call, but doesn't seem to speed it up at all - /* - asm_x86_write_byte_1(as, OPCODE_CALL_REL32); - asm_x86_write_word32(as, ptr - (void*)(as->code_base + as->base.code_offset + 4)); - */ // the caller must clean up the stack if (n_args > 0) { diff --git a/py/asmx86.h b/py/asmx86.h index 1fa7ff7383..930350d11b 100644 --- a/py/asmx86.h +++ b/py/asmx86.h @@ -84,7 +84,6 @@ static inline void asm_x86_end_pass(asm_x86_t *as) { void asm_x86_mov_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); void asm_x86_mov_i32_to_r32(asm_x86_t *as, int32_t src_i32, int dest_r32); -void asm_x86_mov_i32_to_r32_aligned(asm_x86_t *as, int32_t src_i32, int dest_r32); void asm_x86_mov_r8_to_mem8(asm_x86_t *as, int src_r32, int dest_r32, int dest_disp); void asm_x86_mov_r16_to_mem16(asm_x86_t *as, int src_r32, int dest_r32, int dest_disp); void asm_x86_mov_r32_to_mem32(asm_x86_t *as, int src_r32, int dest_r32, int dest_disp); @@ -101,7 +100,9 @@ void asm_x86_sub_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); void asm_x86_mul_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); void asm_x86_cmp_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b); void asm_x86_test_r8_with_r8(asm_x86_t *as, int src_r32_a, int src_r32_b); +void asm_x86_test_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b); void asm_x86_setcc_r8(asm_x86_t *as, mp_uint_t jcc_type, int dest_r8); +void asm_x86_jmp_reg(asm_x86_t *as, int src_r86); void asm_x86_jmp_label(asm_x86_t *as, mp_uint_t label); void asm_x86_jcc_label(asm_x86_t *as, mp_uint_t jcc_type, mp_uint_t label); void asm_x86_entry(asm_x86_t *as, int num_locals); @@ -110,7 +111,11 @@ void asm_x86_mov_arg_to_r32(asm_x86_t *as, int src_arg_num, int dest_r32); void asm_x86_mov_local_to_r32(asm_x86_t *as, int src_local_num, int dest_r32); void asm_x86_mov_r32_to_local(asm_x86_t *as, int src_r32, int dest_local_num); void asm_x86_mov_local_addr_to_r32(asm_x86_t *as, int local_num, int dest_r32); -void asm_x86_call_ind(asm_x86_t *as, void *ptr, mp_uint_t n_args, int temp_r32); +void asm_x86_mov_reg_pcrel(asm_x86_t *as, int dest_r64, mp_uint_t label); +void asm_x86_call_ind(asm_x86_t *as, size_t fun_id, mp_uint_t n_args, int temp_r32); + +// Holds a pointer to mp_fun_table +#define ASM_X86_REG_FUN_TABLE ASM_X86_REG_EBP #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -137,20 +142,31 @@ void asm_x86_call_ind(asm_x86_t *as, void *ptr, mp_uint_t n_args, int temp_r32); #define REG_LOCAL_3 ASM_X86_REG_EDI #define REG_LOCAL_NUM (3) +// Holds a pointer to mp_fun_table +#define REG_FUN_TABLE ASM_X86_REG_FUN_TABLE + #define ASM_T asm_x86_t #define ASM_END_PASS asm_x86_end_pass #define ASM_ENTRY asm_x86_entry #define ASM_EXIT asm_x86_exit #define ASM_JUMP asm_x86_jmp_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ - asm_x86_test_r8_with_r8(as, reg, reg); \ + if (bool_test) { \ + asm_x86_test_r8_with_r8(as, reg, reg); \ + } else { \ + asm_x86_test_r32_with_r32(as, reg, reg); \ + } \ asm_x86_jcc_label(as, ASM_X86_CC_JZ, label); \ } while (0) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ do { \ - asm_x86_test_r8_with_r8(as, reg, reg); \ + if (bool_test) { \ + asm_x86_test_r8_with_r8(as, reg, reg); \ + } else { \ + asm_x86_test_r32_with_r32(as, reg, reg); \ + } \ asm_x86_jcc_label(as, ASM_X86_CC_JNZ, label); \ } while (0) #define ASM_JUMP_IF_REG_EQ(as, reg1, reg2, label) \ @@ -158,14 +174,15 @@ void asm_x86_call_ind(asm_x86_t *as, void *ptr, mp_uint_t n_args, int temp_r32); asm_x86_cmp_r32_with_r32(as, reg1, reg2); \ asm_x86_jcc_label(as, ASM_X86_CC_JE, label); \ } while (0) -#define ASM_CALL_IND(as, ptr, idx) asm_x86_call_ind(as, ptr, mp_f_n_args[idx], ASM_X86_REG_EAX) +#define ASM_JUMP_REG(as, reg) asm_x86_jmp_reg((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_x86_call_ind(as, idx, mp_f_n_args[idx], ASM_X86_REG_EAX) #define ASM_MOV_LOCAL_REG(as, local_num, reg_src) asm_x86_mov_r32_to_local((as), (reg_src), (local_num)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_x86_mov_i32_to_r32((as), (imm), (reg_dest)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_x86_mov_i32_to_r32_aligned((as), (imm), (reg_dest)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_x86_mov_local_to_r32((as), (local_num), (reg_dest)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_x86_mov_r32_r32((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_x86_mov_local_addr_to_r32((as), (local_num), (reg_dest)) +#define ASM_MOV_REG_PCREL(as, reg_dest, label) asm_x86_mov_reg_pcrel((as), (reg_dest), (label)) #define ASM_LSL_REG(as, reg) asm_x86_shl_r32_cl((as), (reg)) #define ASM_ASR_REG(as, reg) asm_x86_sar_r32_cl((as), (reg)) diff --git a/py/asmxtensa.c b/py/asmxtensa.c index 5678eafd1d..a8e3a2655c 100644 --- a/py/asmxtensa.c +++ b/py/asmxtensa.c @@ -37,6 +37,7 @@ #define WORD_SIZE (4) #define SIGNED_FIT8(x) ((((x) & 0xffffff80) == 0) || (((x) & 0xffffff80) == 0xffffff80)) #define SIGNED_FIT12(x) ((((x) & 0xfffff800) == 0) || (((x) & 0xfffff800) == 0xfffff800)) +#define NUM_REGS_SAVED (5) void asm_xtensa_end_pass(asm_xtensa_t *as) { as->num_const = as->cur_const; @@ -67,26 +68,37 @@ void asm_xtensa_entry(asm_xtensa_t *as, int num_locals) { mp_asm_base_get_cur_to_write_bytes(&as->base, 1); // padding/alignment byte as->const_table = (uint32_t *)mp_asm_base_get_cur_to_write_bytes(&as->base, as->num_const * 4); - // adjust the stack-pointer to store a0, a12, a13, a14 and locals, 16-byte aligned - as->stack_adjust = (((4 + num_locals) * WORD_SIZE) + 15) & ~15; - asm_xtensa_op_addi(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, -as->stack_adjust); + // adjust the stack-pointer to store a0, a12, a13, a14, a15 and locals, 16-byte aligned + as->stack_adjust = (((NUM_REGS_SAVED + num_locals) * WORD_SIZE) + 15) & ~15; + if (SIGNED_FIT8(-as->stack_adjust)) { + asm_xtensa_op_addi(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, -as->stack_adjust); + } else { + asm_xtensa_op_movi(as, ASM_XTENSA_REG_A9, as->stack_adjust); + asm_xtensa_op_sub(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A9); + } - // save return value (a0) and callee-save registers (a12, a13, a14) + // save return value (a0) and callee-save registers (a12, a13, a14, a15) asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A0, ASM_XTENSA_REG_A1, 0); - asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A12, ASM_XTENSA_REG_A1, 1); - asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A13, ASM_XTENSA_REG_A1, 2); - asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A14, ASM_XTENSA_REG_A1, 3); + for (int i = 1; i < NUM_REGS_SAVED; ++i) { + asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A11 + i, ASM_XTENSA_REG_A1, i); + } } void asm_xtensa_exit(asm_xtensa_t *as) { // restore registers - asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A14, ASM_XTENSA_REG_A1, 3); - asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A13, ASM_XTENSA_REG_A1, 2); - asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A12, ASM_XTENSA_REG_A1, 1); + for (int i = NUM_REGS_SAVED - 1; i >= 1; --i) { + asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A11 + i, ASM_XTENSA_REG_A1, i); + } asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A0, ASM_XTENSA_REG_A1, 0); // restore stack-pointer and return - asm_xtensa_op_addi(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, as->stack_adjust); + if (SIGNED_FIT8(as->stack_adjust)) { + asm_xtensa_op_addi(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, as->stack_adjust); + } else { + asm_xtensa_op_movi(as, ASM_XTENSA_REG_A9, as->stack_adjust); + asm_xtensa_op_add_n(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A9); + } + asm_xtensa_op_ret_n(as); } @@ -149,7 +161,8 @@ void asm_xtensa_mov_reg_i32(asm_xtensa_t *as, uint reg_dest, uint32_t i32) { asm_xtensa_op_movi(as, reg_dest, i32); } else { // load the constant - asm_xtensa_op_l32r(as, reg_dest, as->base.code_offset, 4 + as->cur_const * WORD_SIZE); + uint32_t const_table_offset = (uint8_t *)as->const_table - as->base.code_base; + asm_xtensa_op_l32r(as, reg_dest, as->base.code_offset, const_table_offset + as->cur_const * WORD_SIZE); // store the constant in the table if (as->const_table != NULL) { as->const_table[as->cur_const] = i32; @@ -159,16 +172,52 @@ void asm_xtensa_mov_reg_i32(asm_xtensa_t *as, uint reg_dest, uint32_t i32) { } void asm_xtensa_mov_local_reg(asm_xtensa_t *as, int local_num, uint reg_src) { - asm_xtensa_op_s32i(as, reg_src, ASM_XTENSA_REG_A1, 4 + local_num); + asm_xtensa_op_s32i(as, reg_src, ASM_XTENSA_REG_A1, NUM_REGS_SAVED + local_num); } void asm_xtensa_mov_reg_local(asm_xtensa_t *as, uint reg_dest, int local_num) { - asm_xtensa_op_l32i(as, reg_dest, ASM_XTENSA_REG_A1, 4 + local_num); + asm_xtensa_op_l32i(as, reg_dest, ASM_XTENSA_REG_A1, NUM_REGS_SAVED + local_num); } void asm_xtensa_mov_reg_local_addr(asm_xtensa_t *as, uint reg_dest, int local_num) { - asm_xtensa_op_mov_n(as, reg_dest, ASM_XTENSA_REG_A1); - asm_xtensa_op_addi(as, reg_dest, reg_dest, (4 + local_num) * WORD_SIZE); + uint off = (NUM_REGS_SAVED + local_num) * WORD_SIZE; + if (SIGNED_FIT8(off)) { + asm_xtensa_op_addi(as, reg_dest, ASM_XTENSA_REG_A1, off); + } else { + asm_xtensa_op_movi(as, reg_dest, off); + asm_xtensa_op_add_n(as, reg_dest, reg_dest, ASM_XTENSA_REG_A1); + } +} + +void asm_xtensa_mov_reg_pcrel(asm_xtensa_t *as, uint reg_dest, uint label) { + // Get relative offset from PC + uint32_t dest = get_label_dest(as, label); + int32_t rel = dest - as->base.code_offset; + rel -= 3 + 3; // account for 3 bytes of movi instruction, 3 bytes call0 adjustment + asm_xtensa_op_movi(as, reg_dest, rel); // imm has 12-bit range + + // Use call0 to get PC+3 into a0 + // call0 destination must be aligned on 4 bytes: + // - code_offset&3=0: off=0, pad=1 + // - code_offset&3=1: off=0, pad=0 + // - code_offset&3=2: off=1, pad=3 + // - code_offset&3=3: off=1, pad=2 + uint32_t off = as->base.code_offset >> 1 & 1; + uint32_t pad = (5 - as->base.code_offset) & 3; + asm_xtensa_op_call0(as, off); + mp_asm_base_get_cur_to_write_bytes(&as->base, pad); + + // Add PC to relative offset + asm_xtensa_op_add_n(as, reg_dest, reg_dest, ASM_XTENSA_REG_A0); +} + +void asm_xtensa_call_ind(asm_xtensa_t *as, uint idx) { + if (idx < 16) { + asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A0, ASM_XTENSA_REG_FUN_TABLE, idx); + } else { + asm_xtensa_op_l32i(as, ASM_XTENSA_REG_A0, ASM_XTENSA_REG_FUN_TABLE, idx); + } + asm_xtensa_op_callx0(as, ASM_XTENSA_REG_A0); } #endif // MICROPY_EMIT_XTENSA || MICROPY_EMIT_INLINE_XTENSA diff --git a/py/asmxtensa.h b/py/asmxtensa.h index d43824338d..685b3f9492 100644 --- a/py/asmxtensa.h +++ b/py/asmxtensa.h @@ -113,12 +113,12 @@ void asm_xtensa_op24(asm_xtensa_t *as, uint32_t op); // raw instructions -static inline void asm_xtensa_op_add(asm_xtensa_t *as, uint reg_dest, uint reg_src_a, uint reg_src_b) { - asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRR(0, 0, 8, reg_dest, reg_src_a, reg_src_b)); +static inline void asm_xtensa_op_add_n(asm_xtensa_t *as, uint reg_dest, uint reg_src_a, uint reg_src_b) { + asm_xtensa_op16(as, ASM_XTENSA_ENCODE_RRRN(10, reg_dest, reg_src_a, reg_src_b)); } static inline void asm_xtensa_op_addi(asm_xtensa_t *as, uint reg_dest, uint reg_src, int imm8) { - asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRI8(2, 12, reg_dest, reg_src, imm8 & 0xff)); + asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRI8(2, 12, reg_src, reg_dest, imm8 & 0xff)); } static inline void asm_xtensa_op_and(asm_xtensa_t *as, uint reg_dest, uint reg_src_a, uint reg_src_b) { @@ -133,6 +133,10 @@ static inline void asm_xtensa_op_bccz(asm_xtensa_t *as, uint cond, uint reg_src, asm_xtensa_op24(as, ASM_XTENSA_ENCODE_BRI12(6, reg_src, cond, 1, rel12 & 0xfff)); } +static inline void asm_xtensa_op_call0(asm_xtensa_t *as, int32_t rel18) { + asm_xtensa_op24(as, ASM_XTENSA_ENCODE_CALL(5, 0, rel18 & 0x3ffff)); +} + static inline void asm_xtensa_op_callx0(asm_xtensa_t *as, uint reg) { asm_xtensa_op24(as, ASM_XTENSA_ENCODE_CALLX(0, 0, 0, 0, reg, 3, 0)); } @@ -238,6 +242,11 @@ void asm_xtensa_mov_reg_i32(asm_xtensa_t *as, uint reg_dest, uint32_t i32); void asm_xtensa_mov_local_reg(asm_xtensa_t *as, int local_num, uint reg_src); void asm_xtensa_mov_reg_local(asm_xtensa_t *as, uint reg_dest, int local_num); void asm_xtensa_mov_reg_local_addr(asm_xtensa_t *as, uint reg_dest, int local_num); +void asm_xtensa_mov_reg_pcrel(asm_xtensa_t *as, uint reg_dest, uint label); +void asm_xtensa_call_ind(asm_xtensa_t *as, uint idx); + +// Holds a pointer to mp_fun_table +#define ASM_XTENSA_REG_FUN_TABLE ASM_XTENSA_REG_A15 #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -262,30 +271,29 @@ void asm_xtensa_mov_reg_local_addr(asm_xtensa_t *as, uint reg_dest, int local_nu #define REG_LOCAL_3 ASM_XTENSA_REG_A14 #define REG_LOCAL_NUM (3) +#define REG_FUN_TABLE ASM_XTENSA_REG_FUN_TABLE + #define ASM_T asm_xtensa_t #define ASM_END_PASS asm_xtensa_end_pass #define ASM_ENTRY asm_xtensa_entry #define ASM_EXIT asm_xtensa_exit #define ASM_JUMP asm_xtensa_j_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ asm_xtensa_bccz_reg_label(as, ASM_XTENSA_CCZ_EQ, reg, label) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ asm_xtensa_bccz_reg_label(as, ASM_XTENSA_CCZ_NE, reg, label) #define ASM_JUMP_IF_REG_EQ(as, reg1, reg2, label) \ asm_xtensa_bcc_reg_reg_label(as, ASM_XTENSA_CC_EQ, reg1, reg2, label) -#define ASM_CALL_IND(as, ptr, idx) \ - do { \ - asm_xtensa_mov_reg_i32(as, ASM_XTENSA_REG_A0, (uint32_t)ptr); \ - asm_xtensa_op_callx0(as, ASM_XTENSA_REG_A0); \ - } while (0) +#define ASM_JUMP_REG(as, reg) asm_xtensa_op_jx((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_xtensa_call_ind((as), (idx)) #define ASM_MOV_LOCAL_REG(as, local_num, reg_src) asm_xtensa_mov_local_reg((as), (local_num), (reg_src)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_xtensa_mov_reg_i32((as), (reg_dest), (imm)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_xtensa_mov_reg_i32((as), (reg_dest), (imm)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_xtensa_mov_reg_local((as), (reg_dest), (local_num)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_mov_n((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_xtensa_mov_reg_local_addr((as), (reg_dest), (local_num)) +#define ASM_MOV_REG_PCREL(as, reg_dest, label) asm_xtensa_mov_reg_pcrel((as), (reg_dest), (label)) #define ASM_LSL_REG_REG(as, reg_dest, reg_shift) \ do { \ @@ -300,7 +308,7 @@ void asm_xtensa_mov_reg_local_addr(asm_xtensa_t *as, uint reg_dest, int local_nu #define ASM_OR_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_or((as), (reg_dest), (reg_dest), (reg_src)) #define ASM_XOR_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_xor((as), (reg_dest), (reg_dest), (reg_src)) #define ASM_AND_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_and((as), (reg_dest), (reg_dest), (reg_src)) -#define ASM_ADD_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_add((as), (reg_dest), (reg_dest), (reg_src)) +#define ASM_ADD_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_add_n((as), (reg_dest), (reg_dest), (reg_src)) #define ASM_SUB_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_sub((as), (reg_dest), (reg_dest), (reg_src)) #define ASM_MUL_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_mull((as), (reg_dest), (reg_dest), (reg_src)) diff --git a/py/bc.c b/py/bc.c index 40a70fe515..1e2c0bbae1 100644 --- a/py/bc.c +++ b/py/bc.c @@ -302,7 +302,7 @@ void mp_setup_code_state(mp_code_state_t *code_state, size_t n_args, size_t n_kw // MP_BC_MAKE_CLOSURE_DEFARGS // MP_BC_RAISE_VARARGS // There are 4 special opcodes that have an extra byte only when -// MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE is enabled: +// MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE is enabled (and they take a qstr): // MP_BC_LOAD_NAME // MP_BC_LOAD_GLOBAL // MP_BC_LOAD_ATTR @@ -396,18 +396,20 @@ uint mp_opcode_format(const byte *ip, size_t *opcode_size) { uint f = (opcode_format_table[*ip >> 2] >> (2 * (*ip & 3))) & 3; const byte *ip_start = ip; if (f == MP_OPCODE_QSTR) { + if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE_DYNAMIC) { + if (*ip == MP_BC_LOAD_NAME + || *ip == MP_BC_LOAD_GLOBAL + || *ip == MP_BC_LOAD_ATTR + || *ip == MP_BC_STORE_ATTR) { + ip += 1; + } + } ip += 3; } else { int extra_byte = ( *ip == MP_BC_RAISE_VARARGS || *ip == MP_BC_MAKE_CLOSURE || *ip == MP_BC_MAKE_CLOSURE_DEFARGS - #if MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE - || *ip == MP_BC_LOAD_NAME - || *ip == MP_BC_LOAD_GLOBAL - || *ip == MP_BC_LOAD_ATTR - || *ip == MP_BC_STORE_ATTR - #endif ); ip += 1; if (f == MP_OPCODE_VAR_UINT) { diff --git a/py/builtin.h b/py/builtin.h index 2275691fc8..58c4c1e524 100644 --- a/py/builtin.h +++ b/py/builtin.h @@ -106,6 +106,7 @@ extern const mp_obj_module_t mp_module_ujson; extern const mp_obj_module_t mp_module_ure; extern const mp_obj_module_t mp_module_uheapq; extern const mp_obj_module_t mp_module_uhashlib; +extern const mp_obj_module_t mp_module_ucryptolib; extern const mp_obj_module_t mp_module_ubinascii; extern const mp_obj_module_t mp_module_urandom; extern const mp_obj_module_t mp_module_uselect; diff --git a/py/builtinhelp.c b/py/builtinhelp.c index 2e77e6dd93..225126029e 100644 --- a/py/builtinhelp.c +++ b/py/builtinhelp.c @@ -167,13 +167,13 @@ STATIC void mp_help_print_obj(const mp_obj_t obj) { mp_map_t *map = NULL; if (type == &mp_type_module) { - map = mp_obj_dict_get_map(mp_obj_module_get_globals(obj)); + map = &mp_obj_module_get_globals(obj)->map; } else { if (type == &mp_type_type) { type = MP_OBJ_TO_PTR(obj); } - if (type->locals_dict != MP_OBJ_NULL && MP_OBJ_IS_TYPE(type->locals_dict, &mp_type_dict)) { - map = mp_obj_dict_get_map(type->locals_dict); + if (type->locals_dict != NULL) { + map = &type->locals_dict->map; } } if (map != NULL) { diff --git a/py/compile.c b/py/compile.c index 7971690d6d..a484022bb9 100644 --- a/py/compile.c +++ b/py/compile.c @@ -172,7 +172,18 @@ STATIC uint comp_next_label(compiler_t *comp) { return comp->next_label++; } -STATIC void compile_increase_except_level(compiler_t *comp) { +#if MICROPY_EMIT_NATIVE +STATIC void reserve_labels_for_native(compiler_t *comp, int n) { + if (comp->scope_cur->emit_options != MP_EMIT_OPT_BYTECODE) { + comp->next_label += n; + } +} +#else +#define reserve_labels_for_native(comp, n) +#endif + +STATIC void compile_increase_except_level(compiler_t *comp, uint label, int kind) { + EMIT_ARG(setup_block, label, kind); comp->cur_except_level += 1; if (comp->cur_except_level > comp->scope_cur->exc_stack_size) { comp->scope_cur->exc_stack_size = comp->cur_except_level; @@ -182,6 +193,8 @@ STATIC void compile_increase_except_level(compiler_t *comp) { STATIC void compile_decrease_except_level(compiler_t *comp) { assert(comp->cur_except_level > 0); comp->cur_except_level -= 1; + EMIT(end_finally); + reserve_labels_for_native(comp, 1); } STATIC scope_t *scope_new_and_link(compiler_t *comp, scope_kind_t kind, mp_parse_node_t pn, uint emit_options) { @@ -556,6 +569,11 @@ STATIC void close_over_variables_etc(compiler_t *comp, scope_t *this_scope, int } this_scope->num_def_pos_args = n_pos_defaults; + #if MICROPY_EMIT_NATIVE + // When creating a function/closure it will take a reference to the current globals + comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_REFGLOBALS | MP_SCOPE_FLAG_HASCONSTS; + #endif + // make closed over variables, if any // ensure they are closed over in the order defined in the outer scope (mainly to agree with CPython) int nfree = 0; @@ -1173,23 +1191,24 @@ STATIC void compile_import_from(compiler_t *comp, mp_parse_node_struct_t *pns) { } } -STATIC void compile_declare_global(compiler_t *comp, mp_parse_node_t pn, qstr qst, bool added, id_info_t *id_info) { - if (!added && id_info->kind != ID_INFO_KIND_GLOBAL_EXPLICIT) { +STATIC void compile_declare_global(compiler_t *comp, mp_parse_node_t pn, id_info_t *id_info) { + if (id_info->kind != ID_INFO_KIND_UNDECIDED && id_info->kind != ID_INFO_KIND_GLOBAL_EXPLICIT) { compile_syntax_error(comp, pn, translate("identifier redefined as global")); return; } id_info->kind = ID_INFO_KIND_GLOBAL_EXPLICIT; // if the id exists in the global scope, set its kind to EXPLICIT_GLOBAL - id_info = scope_find_global(comp->scope_cur, qst); + id_info = scope_find_global(comp->scope_cur, id_info->qst); if (id_info != NULL) { id_info->kind = ID_INFO_KIND_GLOBAL_EXPLICIT; } } -STATIC void compile_declare_nonlocal(compiler_t *comp, mp_parse_node_t pn, qstr qst, bool added, id_info_t *id_info) { - if (added) { - scope_find_local_and_close_over(comp->scope_cur, id_info, qst); +STATIC void compile_declare_nonlocal(compiler_t *comp, mp_parse_node_t pn, id_info_t *id_info) { + if (id_info->kind == ID_INFO_KIND_UNDECIDED) { + id_info->kind = ID_INFO_KIND_GLOBAL_IMPLICIT; + scope_check_to_close_over(comp->scope_cur, id_info); if (id_info->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { compile_syntax_error(comp, pn, translate("no binding for nonlocal found")); } @@ -1211,12 +1230,11 @@ STATIC void compile_global_nonlocal_stmt(compiler_t *comp, mp_parse_node_struct_ int n = mp_parse_node_extract_list(&pns->nodes[0], PN_name_list, &nodes); for (int i = 0; i < n; i++) { qstr qst = MP_PARSE_NODE_LEAF_ARG(nodes[i]); - bool added; - id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, qst, &added); + id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, qst, ID_INFO_KIND_UNDECIDED); if (is_global) { - compile_declare_global(comp, (mp_parse_node_t)pns, qst, added, id_info); + compile_declare_global(comp, (mp_parse_node_t)pns, id_info); } else { - compile_declare_nonlocal(comp, (mp_parse_node_t)pns, qst, added, id_info); + compile_declare_nonlocal(comp, (mp_parse_node_t)pns, id_info); } } } @@ -1524,8 +1542,7 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ uint l1 = comp_next_label(comp); uint success_label = comp_next_label(comp); - EMIT_ARG(setup_block, l1, MP_EMIT_SETUP_BLOCK_EXCEPT); - compile_increase_except_level(comp); + compile_increase_except_level(comp, l1, MP_EMIT_SETUP_BLOCK_EXCEPT); compile_node(comp, pn_body); // body EMIT(pop_block); @@ -1579,8 +1596,7 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ uint l3 = 0; if (qstr_exception_local != 0) { l3 = comp_next_label(comp); - EMIT_ARG(setup_block, l3, MP_EMIT_SETUP_BLOCK_FINALLY); - compile_increase_except_level(comp); + compile_increase_except_level(comp, l3, MP_EMIT_SETUP_BLOCK_FINALLY); } compile_node(comp, pns_except->nodes[1]); if (qstr_exception_local != 0) { @@ -1595,7 +1611,6 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ compile_delete_id(comp, qstr_exception_local); compile_decrease_except_level(comp); - EMIT(end_finally); } EMIT_ARG(jump, l2); EMIT_ARG(label_assign, end_finally_label); @@ -1603,7 +1618,6 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ } compile_decrease_except_level(comp); - EMIT(end_finally); EMIT(end_except_handler); EMIT_ARG(label_assign, success_label); @@ -1614,8 +1628,7 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ STATIC void compile_try_finally(compiler_t *comp, mp_parse_node_t pn_body, int n_except, mp_parse_node_t *pn_except, mp_parse_node_t pn_else, mp_parse_node_t pn_finally) { uint l_finally_block = comp_next_label(comp); - EMIT_ARG(setup_block, l_finally_block, MP_EMIT_SETUP_BLOCK_FINALLY); - compile_increase_except_level(comp); + compile_increase_except_level(comp, l_finally_block, MP_EMIT_SETUP_BLOCK_FINALLY); if (n_except == 0) { assert(MP_PARSE_NODE_IS_NULL(pn_else)); @@ -1631,7 +1644,6 @@ STATIC void compile_try_finally(compiler_t *comp, mp_parse_node_t pn_body, int n compile_node(comp, pn_finally); compile_decrease_except_level(comp); - EMIT(end_finally); } STATIC void compile_try_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { @@ -1667,30 +1679,24 @@ STATIC void compile_with_stmt_helper(compiler_t *comp, int n, mp_parse_node_t *n compile_node(comp, body); } else { uint l_end = comp_next_label(comp); - if (MICROPY_EMIT_NATIVE && comp->scope_cur->emit_options != MP_EMIT_OPT_BYTECODE) { - // we need to allocate an extra label for the native emitter - // it will use l_end+1 as an auxiliary label - comp_next_label(comp); - } if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes[0], PN_with_item)) { // this pre-bit is of the form "a as b" mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)nodes[0]; compile_node(comp, pns->nodes[0]); - EMIT_ARG(setup_block, l_end, MP_EMIT_SETUP_BLOCK_WITH); + compile_increase_except_level(comp, l_end, MP_EMIT_SETUP_BLOCK_WITH); c_assign(comp, pns->nodes[1], ASSIGN_STORE); } else { // this pre-bit is just an expression compile_node(comp, nodes[0]); - EMIT_ARG(setup_block, l_end, MP_EMIT_SETUP_BLOCK_WITH); + compile_increase_except_level(comp, l_end, MP_EMIT_SETUP_BLOCK_WITH); EMIT(pop_top); } - compile_increase_except_level(comp); // compile additional pre-bits and the body compile_with_stmt_helper(comp, n - 1, nodes + 1, body); // finish this with block EMIT_ARG(with_cleanup, l_end); + reserve_labels_for_native(comp, 3); // used by native's with_cleanup compile_decrease_except_level(comp); - EMIT(end_finally); } } @@ -1708,6 +1714,7 @@ STATIC void compile_yield_from(compiler_t *comp) { EMIT_ARG(get_iter, false); EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); EMIT_ARG(yield, MP_EMIT_YIELD_FROM); + reserve_labels_for_native(comp, 3); } #if MICROPY_PY_ASYNC_AWAIT @@ -1749,8 +1756,7 @@ STATIC void compile_async_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns EMIT_ARG(label_assign, continue_label); - EMIT_ARG(setup_block, try_exception_label, MP_EMIT_SETUP_BLOCK_EXCEPT); - compile_increase_except_level(comp); + compile_increase_except_level(comp, try_exception_label, MP_EMIT_SETUP_BLOCK_EXCEPT); compile_load_id(comp, context); compile_await_object_method(comp, MP_QSTR___anext__); @@ -1771,7 +1777,6 @@ STATIC void compile_async_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns EMIT_ARG(label_assign, try_finally_label); EMIT_ARG(adjust_stack_size, 1); // if we jump here, the exc is on the stack compile_decrease_except_level(comp); - EMIT(end_finally); EMIT(end_except_handler); EMIT_ARG(label_assign, try_else_label); @@ -1792,46 +1797,70 @@ STATIC void compile_async_with_stmt_helper(compiler_t *comp, int n, mp_parse_nod // no more pre-bits, compile the body of the with compile_node(comp, body); } else { - uint try_exception_label = comp_next_label(comp); - uint no_reraise_label = comp_next_label(comp); - uint try_else_label = comp_next_label(comp); - uint end_label = comp_next_label(comp); - qstr context; + uint l_finally_block = comp_next_label(comp); + uint l_aexit_no_exc = comp_next_label(comp); + uint l_ret_unwind_jump = comp_next_label(comp); + uint l_end = comp_next_label(comp); if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes[0], PN_with_item)) { // this pre-bit is of the form "a as b" mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)nodes[0]; compile_node(comp, pns->nodes[0]); - context = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); - compile_store_id(comp, context); - compile_load_id(comp, context); + EMIT(dup_top); compile_await_object_method(comp, MP_QSTR___aenter__); c_assign(comp, pns->nodes[1], ASSIGN_STORE); } else { // this pre-bit is just an expression compile_node(comp, nodes[0]); - context = MP_PARSE_NODE_LEAF_ARG(nodes[0]); - compile_store_id(comp, context); - compile_load_id(comp, context); + EMIT(dup_top); compile_await_object_method(comp, MP_QSTR___aenter__); EMIT(pop_top); } - compile_load_id(comp, context); - EMIT_ARG(load_method, MP_QSTR___aexit__, false); + // To keep the Python stack size down, and because we can't access values on + // this stack further down than 3 elements (via rot_three), we don't preload + // __aexit__ (as per normal with) but rather wait until we need it below. - EMIT_ARG(setup_block, try_exception_label, MP_EMIT_SETUP_BLOCK_EXCEPT); - compile_increase_except_level(comp); - // compile additional pre-bits and the body + // Start the try-finally statement + compile_increase_except_level(comp, l_finally_block, MP_EMIT_SETUP_BLOCK_FINALLY); + + // Compile any additional pre-bits of the "async with", and also the body + EMIT_ARG(adjust_stack_size, 3); // stack adjust for possible UNWIND_JUMP state compile_async_with_stmt_helper(comp, n - 1, nodes + 1, body); - // finish this with block + EMIT_ARG(adjust_stack_size, -3); + + // Finish the "try" block EMIT(pop_block); - EMIT_ARG(jump, try_else_label); // jump over exception handler - EMIT_ARG(label_assign, try_exception_label); // start of exception handler - EMIT(start_except_handler); + // At this point, after the with body has executed, we have 3 cases: + // 1. no exception, we just fall through to this point; stack: (..., ctx_mgr) + // 2. exception propagating out, we get to the finally block; stack: (..., ctx_mgr, exc) + // 3. return or unwind jump, we get to the finally block; stack: (..., ctx_mgr, X, INT) - // at this point the stack contains: ..., __aexit__, self, exc + // Handle case 1: call __aexit__ + // Stack: (..., ctx_mgr) + EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); // to tell end_finally there's no exception + EMIT(rot_two); + EMIT_ARG(jump, l_aexit_no_exc); // jump to code below to call __aexit__ + + // Start of "finally" block + // At this point we have case 2 or 3, we detect which one by the TOS being an exception or not + EMIT_ARG(label_assign, l_finally_block); + + // Detect if TOS an exception or not + EMIT(dup_top); + EMIT_LOAD_GLOBAL(MP_QSTR_Exception); + EMIT_ARG(binary_op, MP_BINARY_OP_EXCEPTION_MATCH); + EMIT_ARG(pop_jump_if, false, l_ret_unwind_jump); // if not an exception then we have case 3 + + // Handle case 2: call __aexit__ and either swallow or re-raise the exception + // Stack: (..., ctx_mgr, exc) + EMIT(dup_top); + EMIT(rot_three); + EMIT(rot_two); + EMIT_ARG(load_method, MP_QSTR___aexit__, false); + EMIT(rot_three); + EMIT(rot_three); EMIT(dup_top); #if MICROPY_CPYTHON_COMPAT EMIT_ARG(attr, MP_QSTR___class__, MP_EMIT_ATTR_LOAD); // get type(exc) @@ -1842,32 +1871,37 @@ STATIC void compile_async_with_stmt_helper(compiler_t *comp, int n, mp_parse_nod #endif EMIT(rot_two); EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); // dummy traceback value - // at this point the stack contains: ..., __aexit__, self, type(exc), exc, None + // Stack: (..., exc, __aexit__, ctx_mgr, type(exc), exc, None) EMIT_ARG(call_method, 3, 0, 0); - compile_yield_from(comp); - EMIT_ARG(pop_jump_if, true, no_reraise_label); - EMIT_ARG(raise_varargs, 0); + EMIT_ARG(pop_jump_if, false, l_end); + EMIT(pop_top); // pop exception + EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); // replace with None to swallow exception + EMIT_ARG(jump, l_end); + EMIT_ARG(adjust_stack_size, 2); - EMIT_ARG(label_assign, no_reraise_label); - EMIT(pop_except); - EMIT_ARG(jump, end_label); - - EMIT_ARG(adjust_stack_size, 3); // adjust for __aexit__, self, exc - compile_decrease_except_level(comp); - EMIT(end_finally); - EMIT(end_except_handler); - - EMIT_ARG(label_assign, try_else_label); // start of try-else handler + // Handle case 3: call __aexit__ + // Stack: (..., ctx_mgr, X, INT) + EMIT_ARG(label_assign, l_ret_unwind_jump); + EMIT(rot_three); + EMIT(rot_three); + EMIT_ARG(label_assign, l_aexit_no_exc); + EMIT_ARG(load_method, MP_QSTR___aexit__, false); EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); EMIT(dup_top); EMIT(dup_top); EMIT_ARG(call_method, 3, 0, 0); compile_yield_from(comp); EMIT(pop_top); + EMIT_ARG(adjust_stack_size, -1); - EMIT_ARG(label_assign, end_label); - + // End of "finally" block + // Stack can have one of three configurations: + // a. (..., None) - from either case 1, or case 2 with swallowed exception + // b. (..., exc) - from case 2 with re-raised exception + // c. (..., X, INT) - from case 3 + EMIT_ARG(label_assign, l_end); + compile_decrease_except_level(comp); } } @@ -2688,6 +2722,7 @@ STATIC void compile_yield_expr(compiler_t *comp, mp_parse_node_struct_t *pns) { if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) { EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); EMIT_ARG(yield, MP_EMIT_YIELD_VALUE); + reserve_labels_for_native(comp, 1); } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_yield_arg_from)) { pns = (mp_parse_node_struct_t *)pns->nodes[0]; #if MICROPY_PY_ASYNC_AWAIT @@ -2701,6 +2736,7 @@ STATIC void compile_yield_expr(compiler_t *comp, mp_parse_node_struct_t *pns) { } else { compile_node(comp, pns->nodes[0]); EMIT_ARG(yield, MP_EMIT_YIELD_VALUE); + reserve_labels_for_native(comp, 1); } } @@ -2733,6 +2769,9 @@ STATIC mp_obj_t get_const_object(mp_parse_node_struct_t *pns) { } STATIC void compile_const_object(compiler_t *comp, mp_parse_node_struct_t *pns) { + #if MICROPY_EMIT_NATIVE + comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_HASCONSTS; + #endif EMIT_ARG(load_const_obj, get_const_object(pns)); } @@ -2755,7 +2794,7 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { } else if (MP_PARSE_NODE_IS_SMALL_INT(pn)) { mp_int_t arg = MP_PARSE_NODE_LEAF_SMALL_INT(pn); #if MICROPY_DYNAMIC_COMPILER - mp_uint_t sign_mask = -(1 << (mp_dynamic_compiler.small_int_bits - 1)); + mp_uint_t sign_mask = -((mp_uint_t)1 << (mp_dynamic_compiler.small_int_bits - 1)); if ((arg & sign_mask) == 0 || (arg & sign_mask) == sign_mask) { // integer fits in target runtime's small-int EMIT_ARG(load_const_small_int, arg); @@ -2767,6 +2806,9 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { } else { EMIT_ARG(load_const_obj, mp_obj_new_int_from_ll(arg)); } + #if MICROPY_EMIT_NATIVE + comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_HASCONSTS; + #endif } #else EMIT_ARG(load_const_small_int, arg); @@ -2789,6 +2831,9 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { const byte *data = qstr_data(arg, &len); EMIT_ARG(load_const_obj, mp_obj_new_bytes(data, len)); } + #if MICROPY_EMIT_NATIVE + comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_HASCONSTS; + #endif break; case MP_PARSE_NODE_TOKEN: default: @@ -2810,6 +2855,25 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { } } +#if MICROPY_EMIT_NATIVE +STATIC int compile_viper_type_annotation(compiler_t *comp, mp_parse_node_t pn_annotation) { + int native_type = MP_NATIVE_TYPE_OBJ; + if (MP_PARSE_NODE_IS_NULL(pn_annotation)) { + // No annotation, type defaults to object + } else if (MP_PARSE_NODE_IS_ID(pn_annotation)) { + qstr type_name = MP_PARSE_NODE_LEAF_ARG(pn_annotation); + native_type = mp_native_type_from_qstr(type_name); + if (native_type < 0) { + comp->compile_error = mp_obj_new_exception_msg_varg(&mp_type_ViperTypeError, translate("unknown type '%q'"), type_name); + native_type = 0; + } + } else { + compile_syntax_error(comp, pn_annotation, translate("annotation must be an identifier")); + } + return native_type; +} +#endif + STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn, pn_kind_t pn_name, pn_kind_t pn_star, pn_kind_t pn_dbl_star) { // check that **kw is last if ((comp->scope_cur->scope_flags & MP_SCOPE_FLAG_VARKEYWORDS) != 0) { @@ -2819,6 +2883,7 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn qstr param_name = MP_QSTR_NULL; uint param_flag = ID_FLAG_IS_PARAM; + mp_parse_node_struct_t *pns = NULL; if (MP_PARSE_NODE_IS_ID(pn)) { param_name = MP_PARSE_NODE_LEAF_ARG(pn); if (comp->have_star) { @@ -2830,8 +2895,9 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn } } else { assert(MP_PARSE_NODE_IS_STRUCT(pn)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; + pns = (mp_parse_node_struct_t *)pn; if (MP_PARSE_NODE_STRUCT_KIND(pns) == pn_name) { + // named parameter with possible annotation param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); if (comp->have_star) { // comes after a star, so counts as a keyword-only parameter @@ -2852,10 +2918,12 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn // bare star // TODO see http://www.python.org/dev/peps/pep-3102/ // assert(comp->scope_cur->num_dict_params == 0); + pns = NULL; } else if (MP_PARSE_NODE_IS_ID(pns->nodes[0])) { // named star comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_VARARGS; param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); + pns = NULL; } else { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_tfpdef)); // should be // named star with possible annotation @@ -2864,6 +2932,7 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); } } else { + // double star with possible annotation assert(MP_PARSE_NODE_STRUCT_KIND(pns) == pn_dbl_star); // should be param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); param_flag = ID_FLAG_IS_PARAM | ID_FLAG_IS_DBL_STAR_PARAM; @@ -2872,14 +2941,21 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn } if (param_name != MP_QSTR_NULL) { - bool added; - id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, param_name, &added); - if (!added) { + id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, param_name, ID_INFO_KIND_UNDECIDED); + if (id_info->kind != ID_INFO_KIND_UNDECIDED) { compile_syntax_error(comp, pn, translate("name reused for argument")); return; } id_info->kind = ID_INFO_KIND_LOCAL; id_info->flags = param_flag; + + #if MICROPY_EMIT_NATIVE + if (comp->scope_cur->emit_options == MP_EMIT_OPT_VIPER && pn_name == PN_typedargslist_name && pns != NULL) { + id_info->flags |= compile_viper_type_annotation(comp, pns->nodes[1]) << ID_FLAG_VIPER_TYPE_POS; + } + #else + (void)pns; + #endif } } @@ -2891,49 +2967,6 @@ STATIC void compile_scope_lambda_param(compiler_t *comp, mp_parse_node_t pn) { compile_scope_func_lambda_param(comp, pn, PN_varargslist_name, PN_varargslist_star, PN_varargslist_dbl_star); } -#if MICROPY_EMIT_NATIVE -STATIC void compile_scope_func_annotations(compiler_t *comp, mp_parse_node_t pn) { - if (!MP_PARSE_NODE_IS_STRUCT(pn)) { - // no annotation - return; - } - - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; - if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_typedargslist_name) { - // named parameter with possible annotation - // fallthrough - } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_typedargslist_star) { - if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_tfpdef)) { - // named star with possible annotation - pns = (mp_parse_node_struct_t *)pns->nodes[0]; - // fallthrough - } else { - // no annotation - return; - } - } else { - assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_typedargslist_dbl_star); - // double star with possible annotation - // fallthrough - } - - mp_parse_node_t pn_annotation = pns->nodes[1]; - - if (!MP_PARSE_NODE_IS_NULL(pn_annotation)) { - qstr param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); - id_info_t *id_info = scope_find(comp->scope_cur, param_name); - assert(id_info != NULL); - - if (MP_PARSE_NODE_IS_ID(pn_annotation)) { - qstr arg_type = MP_PARSE_NODE_LEAF_ARG(pn_annotation); - EMIT_ARG(set_native_type, MP_EMIT_NATIVE_TYPE_ARG, id_info->local_num, arg_type); - } else { - compile_syntax_error(comp, pn_annotation, translate("parameter annotation must be an identifier")); - } - } -} -#endif // MICROPY_EMIT_NATIVE - STATIC void compile_scope_comp_iter(compiler_t *comp, mp_parse_node_struct_t *pns_comp_for, mp_parse_node_t pn_inner_expr, int for_depth) { uint l_top = comp_next_label(comp); uint l_end = comp_next_label(comp); @@ -2948,6 +2981,7 @@ tail_recursion: compile_node(comp, pn_inner_expr); if (comp->scope_cur->kind == SCOPE_GEN_EXPR) { EMIT_ARG(yield, MP_EMIT_YIELD_VALUE); + reserve_labels_for_native(comp, 1); EMIT(pop_top); } else { EMIT_ARG(store_comp, comp->scope_cur->kind, 4 * for_depth + 5); @@ -3022,6 +3056,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { comp->scope_cur = scope; comp->next_label = 0; EMIT_ARG(start_pass, pass, scope); + reserve_labels_for_native(comp, 6); // used by native's start_pass if (comp->pass == MP_PASS_SCOPE) { // reset maximum stack sizes in scope @@ -3053,28 +3088,14 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { if (comp->pass == MP_PASS_SCOPE) { comp->have_star = false; apply_to_single_or_list(comp, pns->nodes[1], PN_typedargslist, compile_scope_func_param); - } - #if MICROPY_EMIT_NATIVE - else if (scope->emit_options == MP_EMIT_OPT_VIPER) { - // compile annotations; only needed on latter compiler passes - // only needed for viper emitter - // argument annotations - apply_to_single_or_list(comp, pns->nodes[1], PN_typedargslist, compile_scope_func_annotations); - - // pns->nodes[2] is return/whole function annotation - mp_parse_node_t pn_annotation = pns->nodes[2]; - if (!MP_PARSE_NODE_IS_NULL(pn_annotation)) { - // nodes[2] can be null or a test-expr - if (MP_PARSE_NODE_IS_ID(pn_annotation)) { - qstr ret_type = MP_PARSE_NODE_LEAF_ARG(pn_annotation); - EMIT_ARG(set_native_type, MP_EMIT_NATIVE_TYPE_RETURN, 0, ret_type); - } else { - compile_syntax_error(comp, pn_annotation, translate("return annotation must be an identifier")); - } + #if MICROPY_EMIT_NATIVE + if (scope->emit_options == MP_EMIT_OPT_VIPER) { + // Compile return type; pns->nodes[2] is return/whole function annotation + scope->scope_flags |= compile_viper_type_annotation(comp, pns->nodes[2]) << MP_SCOPE_FLAG_VIPERRET_POS; } + #endif // MICROPY_EMIT_NATIVE } - #endif // MICROPY_EMIT_NATIVE compile_node(comp, pns->nodes[3]); // 3 is function body // emit return if it wasn't the last opcode @@ -3117,10 +3138,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { // so we use the blank qstr. qstr qstr_arg = MP_QSTR_; if (comp->pass == MP_PASS_SCOPE) { - bool added; - id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, qstr_arg, &added); - assert(added); - id_info->kind = ID_INFO_KIND_LOCAL; + scope_find_or_add_id(comp->scope_cur, qstr_arg, ID_INFO_KIND_LOCAL); scope->num_pos_args = 1; } @@ -3160,10 +3178,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_classdef); if (comp->pass == MP_PASS_SCOPE) { - bool added; - id_info_t *id_info = scope_find_or_add_id(scope, MP_QSTR___class__, &added); - assert(added); - id_info->kind = ID_INFO_KIND_LOCAL; + scope_find_or_add_id(scope, MP_QSTR___class__, ID_INFO_KIND_LOCAL); } compile_load_id(comp, MP_QSTR___name__); @@ -3393,6 +3408,17 @@ STATIC void scope_compute_things(scope_t *scope) { if (SCOPE_IS_FUNC_LIKE(scope->kind) && id->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { id->kind = ID_INFO_KIND_GLOBAL_EXPLICIT; } + #if MICROPY_EMIT_NATIVE + if (id->kind == ID_INFO_KIND_GLOBAL_EXPLICIT) { + // This function makes a reference to a global variable + if (scope->emit_options == MP_EMIT_OPT_VIPER + && mp_native_type_from_qstr(id->qst) >= MP_NATIVE_TYPE_INT) { + // A casting operator in viper mode, not a real global reference + } else { + scope->scope_flags |= MP_SCOPE_FLAG_REFGLOBALS; + } + } + #endif // params always count for 1 local, even if they are a cell if (id->kind == ID_INFO_KIND_LOCAL || (id->flags & ID_FLAG_IS_PARAM)) { id->local_num = scope->num_locals++; @@ -3476,6 +3502,14 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f #endif } else { compile_scope(comp, s, MP_PASS_SCOPE); + + // Check if any implicitly declared variables should be closed over + for (size_t i = 0; i < s->id_info_len; ++i) { + id_info_t *id = &s->id_info[i]; + if (id->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { + scope_check_to_close_over(s, id); + } + } } // update maximim number of labels needed @@ -3530,11 +3564,10 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f case MP_EMIT_OPT_NATIVE_PYTHON: case MP_EMIT_OPT_VIPER: if (emit_native == NULL) { - emit_native = NATIVE_EMITTER(new)(&comp->compile_error, max_num_labels); + emit_native = NATIVE_EMITTER(new)(&comp->compile_error, &comp->next_label, max_num_labels); } comp->emit_method_table = &NATIVE_EMITTER(method_table); comp->emit = emit_native; - EMIT_ARG(set_native_type, MP_EMIT_NATIVE_TYPE_ENABLE, s->emit_options == MP_EMIT_OPT_VIPER, 0); break; #endif // MICROPY_EMIT_NATIVE diff --git a/py/compile.h b/py/compile.h index 0f8d023a25..b9c0c653fa 100644 --- a/py/compile.h +++ b/py/compile.h @@ -30,15 +30,6 @@ #include "py/parse.h" #include "py/emitglue.h" -// These must fit in 8 bits; see scope.h -enum { - MP_EMIT_OPT_NONE, - MP_EMIT_OPT_BYTECODE, - MP_EMIT_OPT_NATIVE_PYTHON, - MP_EMIT_OPT_VIPER, - MP_EMIT_OPT_ASM, -}; - // the compiler will raise an exception if an error occurred // the compiler will clear the parse tree before it returns mp_obj_t mp_compile(mp_parse_tree_t *parse_tree, qstr source_file, uint emit_opt, bool is_repl); diff --git a/py/emit.h b/py/emit.h index b142e0641b..24a31f8e23 100644 --- a/py/emit.h +++ b/py/emit.h @@ -51,10 +51,6 @@ typedef enum { #define MP_EMIT_BREAK_FROM_FOR (0x8000) -#define MP_EMIT_NATIVE_TYPE_ENABLE (0) -#define MP_EMIT_NATIVE_TYPE_RETURN (1) -#define MP_EMIT_NATIVE_TYPE_ARG (2) - // Kind for emit_id_ops->local() #define MP_EMIT_IDOP_LOCAL_FAST (0) #define MP_EMIT_IDOP_LOCAL_DEREF (1) @@ -102,7 +98,6 @@ typedef struct _mp_emit_method_table_id_ops_t { } mp_emit_method_table_id_ops_t; typedef struct _emit_method_table_t { - void (*set_native_type)(emit_t *emit, mp_uint_t op, mp_uint_t arg1, qstr arg2); void (*start_pass)(emit_t *emit, pass_kind_t pass, scope_t *scope); void (*end_pass)(emit_t *emit); bool (*last_emit_was_return_value)(emit_t *emit); @@ -162,7 +157,12 @@ typedef struct _emit_method_table_t { void (*end_except_handler)(emit_t *emit); } emit_method_table_t; -void mp_emit_common_get_id_for_load(scope_t *scope, qstr qst); +int mp_native_type_from_qstr(qstr qst); + +static inline void mp_emit_common_get_id_for_load(scope_t *scope, qstr qst) { + scope_find_or_add_id(scope, qst, ID_INFO_KIND_GLOBAL_IMPLICIT); +} + void mp_emit_common_get_id_for_modification(scope_t *scope, qstr qst); void mp_emit_common_id_op(emit_t *emit, const mp_emit_method_table_id_ops_t *emit_method_table, scope_t *scope, qstr qst); @@ -178,11 +178,11 @@ extern const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_store_id_ops; extern const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_delete_id_ops; emit_t *emit_bc_new(void); -emit_t *emit_native_x64_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); -emit_t *emit_native_x86_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); -emit_t *emit_native_thumb_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); -emit_t *emit_native_arm_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); -emit_t *emit_native_xtensa_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); +emit_t *emit_native_x64_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); +emit_t *emit_native_x86_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); +emit_t *emit_native_thumb_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); +emit_t *emit_native_arm_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); +emit_t *emit_native_xtensa_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); void emit_bc_set_max_num_labels(emit_t *emit, mp_uint_t max_num_labels); diff --git a/py/emitbc.c b/py/emitbc.c index 37960cb6b4..7e2989276f 100644 --- a/py/emitbc.c +++ b/py/emitbc.c @@ -331,6 +331,10 @@ void mp_emit_bc_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scope) { // the highest slot in the state (fastn[0], see vm.c). n_state = 1; } + #if MICROPY_DEBUG_VM_STACK_OVERFLOW + // An extra slot in the stack is needed to detect VM stack overflow + n_state += 1; + #endif emit_write_code_info_uint(emit, n_state); emit_write_code_info_uint(emit, scope->exc_stack_size); } @@ -916,7 +920,6 @@ void mp_emit_bc_end_except_handler(emit_t *emit) { #if MICROPY_EMIT_NATIVE const emit_method_table_t emit_bc_method_table = { - NULL, // set_native_type is never called when emitting bytecode mp_emit_bc_start_pass, mp_emit_bc_end_pass, mp_emit_bc_last_emit_was_return_value, diff --git a/py/emitcommon.c b/py/emitcommon.c index 88c9803a6e..177418c30a 100644 --- a/py/emitcommon.c +++ b/py/emitcommon.c @@ -30,26 +30,10 @@ #if MICROPY_ENABLE_COMPILER -void mp_emit_common_get_id_for_load(scope_t *scope, qstr qst) { - // name adding/lookup - bool added; - id_info_t *id = scope_find_or_add_id(scope, qst, &added); - if (added) { - scope_find_local_and_close_over(scope, id, qst); - } -} - void mp_emit_common_get_id_for_modification(scope_t *scope, qstr qst) { // name adding/lookup - bool added; - id_info_t *id = scope_find_or_add_id(scope, qst, &added); - if (added) { - if (SCOPE_IS_FUNC_LIKE(scope->kind)) { - id->kind = ID_INFO_KIND_LOCAL; - } else { - id->kind = ID_INFO_KIND_GLOBAL_IMPLICIT; - } - } else if (SCOPE_IS_FUNC_LIKE(scope->kind) && id->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { + id_info_t *id = scope_find_or_add_id(scope, qst, ID_INFO_KIND_GLOBAL_IMPLICIT); + if (SCOPE_IS_FUNC_LIKE(scope->kind) && id->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { // rebind as a local variable id->kind = ID_INFO_KIND_LOCAL; } diff --git a/py/emitglue.c b/py/emitglue.c index d0286803e7..4949053410 100644 --- a/py/emitglue.c +++ b/py/emitglue.c @@ -76,6 +76,9 @@ void mp_emit_glue_assign_bytecode(mp_raw_code_t *rc, const byte *code, #endif #ifdef DEBUG_PRINT + #if !MICROPY_DEBUG_PRINTERS + const size_t len = 0; + #endif DEBUG_printf("assign byte code: code=%p len=" UINT_FMT " flags=%x\n", code, len, (uint)scope_flags); #endif #if MICROPY_DEBUG_PRINTERS @@ -131,10 +134,8 @@ mp_obj_t mp_make_function_from_raw_code(const mp_raw_code_t *rc, mp_obj_t def_ar switch (rc->kind) { #if MICROPY_EMIT_NATIVE case MP_CODE_NATIVE_PY: - fun = mp_obj_new_fun_native(def_args, def_kw_args, rc->data.u_native.fun_data, rc->data.u_native.const_table); - break; case MP_CODE_NATIVE_VIPER: - fun = mp_obj_new_fun_viper(rc->n_pos_args, rc->data.u_native.fun_data, rc->data.u_native.type_sig); + fun = mp_obj_new_fun_native(def_args, def_kw_args, rc->data.u_native.fun_data, rc->data.u_native.const_table); break; #endif #if MICROPY_EMIT_INLINE_ASM diff --git a/py/emitglue.h b/py/emitglue.h index 2ddcc3e53e..fc352fdbab 100644 --- a/py/emitglue.h +++ b/py/emitglue.h @@ -30,6 +30,15 @@ // These variables and functions glue the code emitters to the runtime. +// These must fit in 8 bits; see scope.h +enum { + MP_EMIT_OPT_NONE, + MP_EMIT_OPT_BYTECODE, + MP_EMIT_OPT_NATIVE_PYTHON, + MP_EMIT_OPT_VIPER, + MP_EMIT_OPT_ASM, +}; + typedef enum { MP_CODE_UNUSED, MP_CODE_RESERVED, diff --git a/py/emitnarm.c b/py/emitnarm.c index 1b585f821b..8297ad6192 100644 --- a/py/emitnarm.c +++ b/py/emitnarm.c @@ -8,6 +8,11 @@ #define GENERIC_ASM_API (1) #include "py/asmarm.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (3) // r4 +#define NLR_BUF_IDX_LOCAL_2 (4) // r5 +#define NLR_BUF_IDX_LOCAL_3 (5) // r6 + #define N_ARM (1) #define EXPORT_FUN(name) emit_native_arm_##name #include "py/emitnative.c" diff --git a/py/emitnative.c b/py/emitnative.c index 57b75030a4..bcf7793c86 100644 --- a/py/emitnative.c +++ b/py/emitnative.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George + * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -49,8 +49,6 @@ #include "py/emit.h" #include "py/bc.h" -#include "supervisor/shared/translate.h" - #if MICROPY_DEBUG_VERBOSE // print debugging info #define DEBUG_PRINT (1) #define DEBUG_printf DEBUG_printf @@ -59,30 +57,76 @@ #endif #ifndef N_X64 - #define N_X64 (0) +#define N_X64 (0) #endif + #ifndef N_X86 - #define N_X86 (0) +#define N_X86 (0) #endif + #ifndef N_THUMB - #define N_THUMB (0) +#define N_THUMB (0) #endif + #ifndef N_ARM - #define N_ARM (0) +#define N_ARM (0) #endif + #ifndef N_XTENSA - #define N_XTENSA (0) +#define N_XTENSA (0) #endif // wrapper around everything in this file #if N_X64 || N_X86 || N_THUMB || N_ARM || N_XTENSA -// define additional generic helper macros -#define ASM_MOV_LOCAL_IMM_VIA(as, local_num, imm, reg_temp) \ - do { \ - ASM_MOV_REG_IMM((as), (reg_temp), (imm)); \ - ASM_MOV_LOCAL_REG((as), (local_num), (reg_temp)); \ - } while (false) +// C stack layout for native functions: +// 0: nlr_buf_t [optional] +// emit->code_state_start: mp_code_state_t +// emit->stack_start: Python object stack | emit->n_state +// locals (reversed, L0 at end) | +// +// C stack layout for native generator functions: +// 0=emit->stack_start: nlr_buf_t +// +// Then REG_GENERATOR_STATE points to: +// 0=emit->code_state_start: mp_code_state_t +// emit->stack_start: Python object stack | emit->n_state +// locals (reversed, L0 at end) | +// +// C stack layout for viper functions: +// 0: nlr_buf_t [optional] +// emit->code_state_start: fun_obj, old_globals [optional] +// emit->stack_start: Python object stack | emit->n_state +// locals (reversed, L0 at end) | +// (L0-L2 may be in regs instead) + +// Word index of nlr_buf_t.ret_val +#define NLR_BUF_IDX_RET_VAL (1) + +// Whether the viper function needs access to fun_obj +#define NEED_FUN_OBJ(emit) ((emit)->scope->exc_stack_size > 0 \ + || ((emit)->scope->scope_flags & (MP_SCOPE_FLAG_REFGLOBALS | MP_SCOPE_FLAG_HASCONSTS))) + +// Whether the native/viper function needs to be wrapped in an exception handler +#define NEED_GLOBAL_EXC_HANDLER(emit) ((emit)->scope->exc_stack_size > 0 \ + || ((emit)->scope->scope_flags & (MP_SCOPE_FLAG_GENERATOR | MP_SCOPE_FLAG_REFGLOBALS))) + +// Whether registers can be used to store locals (only true if there are no +// exception handlers, because otherwise an nlr_jump will restore registers to +// their state at the start of the function and updates to locals will be lost) +#define CAN_USE_REGS_FOR_LOCALS(emit) ((emit)->scope->exc_stack_size == 0 && !(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) + +// Indices within the local C stack for various variables +#define LOCAL_IDX_EXC_VAL(emit) (NLR_BUF_IDX_RET_VAL) +#define LOCAL_IDX_EXC_HANDLER_PC(emit) (NLR_BUF_IDX_LOCAL_1) +#define LOCAL_IDX_EXC_HANDLER_UNWIND(emit) (NLR_BUF_IDX_LOCAL_2) +#define LOCAL_IDX_RET_VAL(emit) (NLR_BUF_IDX_LOCAL_3) +#define LOCAL_IDX_FUN_OBJ(emit) ((emit)->code_state_start + offsetof(mp_code_state_t, fun_bc) / sizeof(uintptr_t)) +#define LOCAL_IDX_OLD_GLOBALS(emit) ((emit)->code_state_start + offsetof(mp_code_state_t, ip) / sizeof(uintptr_t)) +#define LOCAL_IDX_GEN_PC(emit) ((emit)->code_state_start + offsetof(mp_code_state_t, ip) / sizeof(uintptr_t)) +#define LOCAL_IDX_LOCAL_VAR(emit, local_num) ((emit)->stack_start + (emit)->n_state - 1 - (local_num)) + +#define REG_GENERATOR_STATE (REG_LOCAL_3) #define EMIT_NATIVE_VIPER_TYPE_ERROR(emit, ...) do { \ *emit->error_slot = mp_obj_new_exception_msg_varg(&mp_type_ViperTypeError, __VA_ARGS__); \ @@ -112,6 +156,29 @@ typedef enum { VTYPE_BUILTIN_CAST = 0x70 | MP_NATIVE_TYPE_OBJ, } vtype_kind_t; +int mp_native_type_from_qstr(qstr qst) { + switch (qst) { + case MP_QSTR_object: + return MP_NATIVE_TYPE_OBJ; + case MP_QSTR_bool: + return MP_NATIVE_TYPE_BOOL; + case MP_QSTR_int: + return MP_NATIVE_TYPE_INT; + case MP_QSTR_uint: + return MP_NATIVE_TYPE_UINT; + case MP_QSTR_ptr: + return MP_NATIVE_TYPE_PTR; + case MP_QSTR_ptr8: + return MP_NATIVE_TYPE_PTR8; + case MP_QSTR_ptr16: + return MP_NATIVE_TYPE_PTR16; + case MP_QSTR_ptr32: + return MP_NATIVE_TYPE_PTR32; + default: + return -1; + } +} + STATIC qstr vtype_to_qstr(vtype_kind_t vtype) { switch (vtype) { case VTYPE_PYOBJ: @@ -145,14 +212,24 @@ typedef struct _stack_info_t { } data; } stack_info_t; +#define UNWIND_LABEL_UNUSED (0x7fff) +#define UNWIND_LABEL_DO_FINAL_UNWIND (0x7ffe) + +typedef struct _exc_stack_entry_t { + uint16_t label : 15; + uint16_t is_finally : 1; + uint16_t unwind_label : 15; + uint16_t is_active : 1; +} exc_stack_entry_t; + struct _emit_t { mp_obj_t *error_slot; + uint *label_slot; + uint exit_label; int pass; bool do_viper_types; - vtype_kind_t return_vtype; - mp_uint_t local_vtype_alloc; vtype_kind_t *local_vtype; @@ -160,12 +237,22 @@ struct _emit_t { stack_info_t *stack_info; vtype_kind_t saved_stack_vtype; + size_t exc_stack_alloc; + size_t exc_stack_size; + exc_stack_entry_t *exc_stack; + int prelude_offset; - int const_table_offset; + int start_offset; int n_state; - int stack_start; + uint16_t code_state_start; + uint16_t stack_start; int stack_size; + uint16_t const_table_cur_obj; + uint16_t const_table_num_obj; + uint16_t const_table_cur_raw_code; + mp_uint_t *const_table; + bool last_emit_was_return_value; scope_t *scope; @@ -173,9 +260,19 @@ struct _emit_t { ASM_T *as; }; -emit_t *EXPORT_FUN(new)(mp_obj_t * error_slot, mp_uint_t max_num_labels) { +STATIC const uint8_t reg_local_table[REG_LOCAL_NUM] = {REG_LOCAL_1, REG_LOCAL_2, REG_LOCAL_3}; + +STATIC void emit_native_global_exc_entry(emit_t *emit); +STATIC void emit_native_global_exc_exit(emit_t *emit); + +emit_t *EXPORT_FUN(new)(mp_obj_t * error_slot, uint *label_slot, mp_uint_t max_num_labels) { emit_t *emit = m_new0(emit_t, 1); emit->error_slot = error_slot; + emit->label_slot = label_slot; + emit->stack_info_alloc = 8; + emit->stack_info = m_new(stack_info_t, emit->stack_info_alloc); + emit->exc_stack_alloc = 8; + emit->exc_stack = m_new(exc_stack_entry_t, emit->exc_stack_alloc); emit->as = m_new0(ASM_T, 1); mp_asm_base_init(&emit->as->base, max_num_labels); return emit; @@ -184,72 +281,57 @@ emit_t *EXPORT_FUN(new)(mp_obj_t * error_slot, mp_uint_t max_num_labels) { void EXPORT_FUN(free)(emit_t * emit) { mp_asm_base_deinit(&emit->as->base, false); m_del_obj(ASM_T, emit->as); + m_del(exc_stack_entry_t, emit->exc_stack, emit->exc_stack_alloc); m_del(vtype_kind_t, emit->local_vtype, emit->local_vtype_alloc); m_del(stack_info_t, emit->stack_info, emit->stack_info_alloc); m_del_obj(emit_t, emit); } -STATIC void emit_native_set_native_type(emit_t *emit, mp_uint_t op, mp_uint_t arg1, qstr arg2) { - switch (op) { - case MP_EMIT_NATIVE_TYPE_ENABLE: - emit->do_viper_types = arg1; - break; +STATIC void emit_call_with_imm_arg(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val, int arg_reg); - default: { - vtype_kind_t type; - switch (arg2) { - case MP_QSTR_object: - type = VTYPE_PYOBJ; - break; - case MP_QSTR_bool: - type = VTYPE_BOOL; - break; - case MP_QSTR_int: - type = VTYPE_INT; - break; - case MP_QSTR_uint: - type = VTYPE_UINT; - break; - case MP_QSTR_ptr: - type = VTYPE_PTR; - break; - case MP_QSTR_ptr8: - type = VTYPE_PTR8; - break; - case MP_QSTR_ptr16: - type = VTYPE_PTR16; - break; - case MP_QSTR_ptr32: - type = VTYPE_PTR32; - break; - default: - EMIT_NATIVE_VIPER_TYPE_ERROR(emit, translate("unknown type '%q'"), arg2); - return; - } - if (op == MP_EMIT_NATIVE_TYPE_RETURN) { - emit->return_vtype = type; - } else { - assert(arg1 < emit->local_vtype_alloc); - emit->local_vtype[arg1] = type; - } - break; - } +STATIC void emit_native_mov_reg_const(emit_t *emit, int reg_dest, int const_val) { + ASM_LOAD_REG_REG_OFFSET(emit->as, reg_dest, REG_FUN_TABLE, const_val); +} + +STATIC void emit_native_mov_state_reg(emit_t *emit, int local_num, int reg_src) { + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + ASM_STORE_REG_REG_OFFSET(emit->as, reg_src, REG_GENERATOR_STATE, local_num); + } else { + ASM_MOV_LOCAL_REG(emit->as, local_num, reg_src); } } -STATIC void emit_pre_pop_reg(emit_t *emit, vtype_kind_t *vtype, int reg_dest); -STATIC void emit_post_push_reg(emit_t *emit, vtype_kind_t vtype, int reg); -STATIC void emit_native_load_fast(emit_t *emit, qstr qst, mp_uint_t local_num); -STATIC void emit_native_store_fast(emit_t *emit, qstr qst, mp_uint_t local_num); +STATIC void emit_native_mov_reg_state(emit_t *emit, int reg_dest, int local_num) { + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + ASM_LOAD_REG_REG_OFFSET(emit->as, reg_dest, REG_GENERATOR_STATE, local_num); + } else { + ASM_MOV_REG_LOCAL(emit->as, reg_dest, local_num); + } +} -#define STATE_START (sizeof(mp_code_state_t) / sizeof(mp_uint_t)) +STATIC void emit_native_mov_reg_state_addr(emit_t *emit, int reg_dest, int local_num) { + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + ASM_MOV_REG_IMM(emit->as, reg_dest, local_num * ASM_WORD_SIZE); + ASM_ADD_REG_REG(emit->as, reg_dest, REG_GENERATOR_STATE); + } else { + ASM_MOV_REG_LOCAL_ADDR(emit->as, reg_dest, local_num); + } +} + +#define emit_native_mov_state_imm_via(emit, local_num, imm, reg_temp) \ + do { \ + ASM_MOV_REG_IMM((emit)->as, (reg_temp), (imm)); \ + emit_native_mov_state_reg((emit), (local_num), (reg_temp)); \ + } while (false) STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scope) { DEBUG_printf("start_pass(pass=%u, scope=%p)\n", pass, scope); emit->pass = pass; - emit->stack_start = 0; + emit->do_viper_types = scope->emit_options == MP_EMIT_OPT_VIPER; emit->stack_size = 0; + emit->const_table_cur_obj = 1; // first entry is for mp_fun_table + emit->const_table_cur_raw_code = 0; emit->last_emit_was_return_value = false; emit->scope = scope; @@ -259,17 +341,6 @@ STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop emit->local_vtype_alloc = scope->num_locals; } - // allocate memory for keeping track of the objects on the stack - // XXX don't know stack size on entry, and it should be maximum over all scopes - // XXX this is such a big hack and really needs to be fixed - if (emit->stack_info == NULL) { - emit->stack_info_alloc = scope->stack_size + 200; - emit->stack_info = m_new(stack_info_t, emit->stack_info_alloc); - } - - // set default type for return - emit->return_vtype = VTYPE_PYOBJ; - // set default type for arguments mp_uint_t num_args = emit->scope->num_pos_args + emit->scope->num_kwonly_args; if (scope->scope_flags & MP_SCOPE_FLAG_VARARGS) { @@ -282,6 +353,17 @@ STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop emit->local_vtype[i] = VTYPE_PYOBJ; } + // Set viper type for arguments + if (emit->do_viper_types) { + for (int i = 0; i < emit->scope->id_info_len; ++i) { + id_info_t *id = &emit->scope->id_info[i]; + if (id->flags & ID_FLAG_IS_PARAM) { + assert(id->local_num < emit->local_vtype_alloc); + emit->local_vtype[id->local_num] = id->flags >> ID_FLAG_VIPER_TYPE_POS; + } + } + } + // local variables begin unbound, and have unknown type for (mp_uint_t i = num_args; i < emit->local_vtype_alloc; i++) { emit->local_vtype[i] = VTYPE_UNBOUND; @@ -297,111 +379,171 @@ STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop // generate code for entry to function + // Work out start of code state (mp_code_state_t or reduced version for viper) + emit->code_state_start = 0; + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + emit->code_state_start = sizeof(nlr_buf_t) / sizeof(uintptr_t); + } + if (emit->do_viper_types) { - - // right now we have a restriction of maximum of 4 arguments - if (scope->num_pos_args >= 5) { - EMIT_NATIVE_VIPER_TYPE_ERROR(emit, translate("Viper functions don't currently support more than 4 arguments")); - return; - } - - // entry to function - int num_locals = 0; - if (pass > MP_PASS_SCOPE) { - num_locals = scope->num_locals - REG_LOCAL_NUM; - if (num_locals < 0) { - num_locals = 0; + // Work out size of state (locals plus stack) + // n_state counts all stack and locals, even those in registers + emit->n_state = scope->num_locals + scope->stack_size; + int num_locals_in_regs = 0; + if (CAN_USE_REGS_FOR_LOCALS(emit)) { + num_locals_in_regs = scope->num_locals; + if (num_locals_in_regs > REG_LOCAL_NUM) { + num_locals_in_regs = REG_LOCAL_NUM; + } + // Need a spot for REG_LOCAL_3 if 4 or more args (see below) + if (scope->num_pos_args >= 4) { + --num_locals_in_regs; } - emit->stack_start = num_locals; - num_locals += scope->stack_size; } - ASM_ENTRY(emit->as, num_locals); - // TODO don't load r7 if we don't need it - #if N_THUMB - asm_thumb_mov_reg_i32(emit->as, ASM_THUMB_REG_R7, (mp_uint_t)mp_fun_table); - #elif N_ARM - asm_arm_mov_reg_i32(emit->as, ASM_ARM_REG_R7, (mp_uint_t)mp_fun_table); - #endif + // Work out where the locals and Python stack start within the C stack + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + // Reserve 2 words for function object and old globals + emit->stack_start = emit->code_state_start + 2; + } else if (scope->scope_flags & MP_SCOPE_FLAG_HASCONSTS) { + // Reserve 1 word for function object, to access const table + emit->stack_start = emit->code_state_start + 1; + } else { + emit->stack_start = emit->code_state_start + 0; + } + + // Entry to function + ASM_ENTRY(emit->as, emit->stack_start + emit->n_state - num_locals_in_regs); #if N_X86 - for (int i = 0; i < scope->num_pos_args; i++) { - if (i == 0) { - asm_x86_mov_arg_to_r32(emit->as, i, REG_LOCAL_1); - } else if (i == 1) { - asm_x86_mov_arg_to_r32(emit->as, i, REG_LOCAL_2); - } else if (i == 2) { - asm_x86_mov_arg_to_r32(emit->as, i, REG_LOCAL_3); - } else { - asm_x86_mov_arg_to_r32(emit->as, i, REG_TEMP0); - asm_x86_mov_r32_to_local(emit->as, REG_TEMP0, i - REG_LOCAL_NUM); - } - } - #else - for (int i = 0; i < scope->num_pos_args; i++) { - if (i == 0) { - ASM_MOV_REG_REG(emit->as, REG_LOCAL_1, REG_ARG_1); - } else if (i == 1) { - ASM_MOV_REG_REG(emit->as, REG_LOCAL_2, REG_ARG_2); - } else if (i == 2) { - ASM_MOV_REG_REG(emit->as, REG_LOCAL_3, REG_ARG_3); - } else { - assert(i == 3); // should be true; max 4 args is checked above - ASM_MOV_LOCAL_REG(emit->as, i - REG_LOCAL_NUM, REG_ARG_4); - } - } + asm_x86_mov_arg_to_r32(emit->as, 0, REG_ARG_1); #endif + // Load REG_FUN_TABLE with a pointer to mp_fun_table, found in the const_table + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_LOCAL_3, REG_ARG_1, offsetof(mp_obj_fun_bc_t, const_table) / sizeof(uintptr_t)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_FUN_TABLE, REG_LOCAL_3, 0); + + // Store function object (passed as first arg) to stack if needed + if (NEED_FUN_OBJ(emit)) { + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_FUN_OBJ(emit), REG_ARG_1); + } + + // Put n_args in REG_ARG_1, n_kw in REG_ARG_2, args array in REG_LOCAL_3 + #if N_X86 + asm_x86_mov_arg_to_r32(emit->as, 1, REG_ARG_1); + asm_x86_mov_arg_to_r32(emit->as, 2, REG_ARG_2); + asm_x86_mov_arg_to_r32(emit->as, 3, REG_LOCAL_3); + #else + ASM_MOV_REG_REG(emit->as, REG_ARG_1, REG_ARG_2); + ASM_MOV_REG_REG(emit->as, REG_ARG_2, REG_ARG_3); + ASM_MOV_REG_REG(emit->as, REG_LOCAL_3, REG_ARG_4); + #endif + + // Check number of args matches this function, and call mp_arg_check_num_sig if not + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_ARG_2, *emit->label_slot + 4, true); + ASM_MOV_REG_IMM(emit->as, REG_ARG_3, scope->num_pos_args); + ASM_JUMP_IF_REG_EQ(emit->as, REG_ARG_1, REG_ARG_3, *emit->label_slot + 5); + mp_asm_base_label_assign(&emit->as->base, *emit->label_slot + 4); + ASM_MOV_REG_IMM(emit->as, REG_ARG_3, MP_OBJ_FUN_MAKE_SIG(scope->num_pos_args, scope->num_pos_args, false)); + ASM_CALL_IND(emit->as, MP_F_ARG_CHECK_NUM_SIG); + mp_asm_base_label_assign(&emit->as->base, *emit->label_slot + 5); + + // Store arguments into locals (reg or stack), converting to native if needed + for (int i = 0; i < emit->scope->num_pos_args; i++) { + int r = REG_ARG_1; + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_ARG_1, REG_LOCAL_3, i); + if (emit->local_vtype[i] != VTYPE_PYOBJ) { + emit_call_with_imm_arg(emit, MP_F_CONVERT_OBJ_TO_NATIVE, emit->local_vtype[i], REG_ARG_2); + r = REG_RET; + } + // REG_LOCAL_3 points to the args array so be sure not to overwrite it if it's still needed + if (i < REG_LOCAL_NUM && CAN_USE_REGS_FOR_LOCALS(emit) && (i != 2 || emit->scope->num_pos_args == 3)) { + ASM_MOV_REG_REG(emit->as, reg_local_table[i], r); + } else { + emit_native_mov_state_reg(emit, LOCAL_IDX_LOCAL_VAR(emit, i), r); + } + } + // Get 3rd local from the stack back into REG_LOCAL_3 if this reg couldn't be written to above + if (emit->scope->num_pos_args >= 4 && CAN_USE_REGS_FOR_LOCALS(emit)) { + ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_3, LOCAL_IDX_LOCAL_VAR(emit, 2)); + } + + emit_native_global_exc_entry(emit); + } else { // work out size of state (locals plus stack) emit->n_state = scope->num_locals + scope->stack_size; - // allocate space on C-stack for code_state structure, which includes state - ASM_ENTRY(emit->as, STATE_START + emit->n_state); + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + emit->code_state_start = 0; + emit->stack_start = sizeof(mp_code_state_t) / sizeof(mp_uint_t); + mp_asm_base_data(&emit->as->base, ASM_WORD_SIZE, (uintptr_t)emit->prelude_offset); + mp_asm_base_data(&emit->as->base, ASM_WORD_SIZE, (uintptr_t)emit->start_offset); + ASM_ENTRY(emit->as, sizeof(nlr_buf_t) / sizeof(uintptr_t)); - // TODO don't load r7 if we don't need it - #if N_THUMB - asm_thumb_mov_reg_i32(emit->as, ASM_THUMB_REG_R7, (mp_uint_t)mp_fun_table); - #elif N_ARM - asm_arm_mov_reg_i32(emit->as, ASM_ARM_REG_R7, (mp_uint_t)mp_fun_table); - #endif + // Put address of code_state into REG_GENERATOR_STATE + #if N_X86 + asm_x86_mov_arg_to_r32(emit->as, 0, REG_GENERATOR_STATE); + #else + ASM_MOV_REG_REG(emit->as, REG_GENERATOR_STATE, REG_ARG_1); + #endif - // prepare incoming arguments for call to mp_setup_code_state + // Put throw value into LOCAL_IDX_EXC_VAL slot, for yield/yield-from + #if N_X86 + asm_x86_mov_arg_to_r32(emit->as, 1, REG_ARG_2); + #endif + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_ARG_2); - #if N_X86 - asm_x86_mov_arg_to_r32(emit->as, 0, REG_ARG_1); - asm_x86_mov_arg_to_r32(emit->as, 1, REG_ARG_2); - asm_x86_mov_arg_to_r32(emit->as, 2, REG_ARG_3); - asm_x86_mov_arg_to_r32(emit->as, 3, REG_ARG_4); - #endif + // Load REG_FUN_TABLE with a pointer to mp_fun_table, found in the const_table + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_TEMP0, REG_GENERATOR_STATE, LOCAL_IDX_FUN_OBJ(emit)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_TEMP0, REG_TEMP0, offsetof(mp_obj_fun_bc_t, const_table) / sizeof(uintptr_t)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_FUN_TABLE, REG_TEMP0, emit->scope->num_pos_args + emit->scope->num_kwonly_args); + } else { + // The locals and stack start after the code_state structure + emit->stack_start = emit->code_state_start + sizeof(mp_code_state_t) / sizeof(mp_uint_t); - // set code_state.fun_bc - ASM_MOV_LOCAL_REG(emit->as, offsetof(mp_code_state_t, fun_bc) / sizeof(uintptr_t), REG_ARG_1); + // Allocate space on C-stack for code_state structure, which includes state + ASM_ENTRY(emit->as, emit->stack_start + emit->n_state); - // set code_state.ip (offset from start of this function to prelude info) - // XXX this encoding may change size - ASM_MOV_LOCAL_IMM_VIA(emit->as, offsetof(mp_code_state_t, ip) / sizeof(uintptr_t), emit->prelude_offset, REG_ARG_1); + // Prepare incoming arguments for call to mp_setup_code_state - // put address of code_state into first arg - ASM_MOV_REG_LOCAL_ADDR(emit->as, REG_ARG_1, 0); + #if N_X86 + asm_x86_mov_arg_to_r32(emit->as, 0, REG_ARG_1); + asm_x86_mov_arg_to_r32(emit->as, 1, REG_ARG_2); + asm_x86_mov_arg_to_r32(emit->as, 2, REG_ARG_3); + asm_x86_mov_arg_to_r32(emit->as, 3, REG_ARG_4); + #endif - // call mp_setup_code_state to prepare code_state structure - #if N_THUMB - asm_thumb_bl_ind(emit->as, mp_fun_table[MP_F_SETUP_CODE_STATE], MP_F_SETUP_CODE_STATE, ASM_THUMB_REG_R4); - #elif N_ARM - asm_arm_bl_ind(emit->as, mp_fun_table[MP_F_SETUP_CODE_STATE], MP_F_SETUP_CODE_STATE, ASM_ARM_REG_R4); - #else - ASM_CALL_IND(emit->as, mp_fun_table[MP_F_SETUP_CODE_STATE], MP_F_SETUP_CODE_STATE); - #endif + // Load REG_FUN_TABLE with a pointer to mp_fun_table, found in the const_table + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_LOCAL_3, REG_ARG_1, offsetof(mp_obj_fun_bc_t, const_table) / sizeof(uintptr_t)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_FUN_TABLE, REG_LOCAL_3, emit->scope->num_pos_args + emit->scope->num_kwonly_args); - // cache some locals in registers - if (scope->num_locals > 0) { - ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_1, STATE_START + emit->n_state - 1 - 0); - if (scope->num_locals > 1) { - ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_2, STATE_START + emit->n_state - 1 - 1); - if (scope->num_locals > 2) { - ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_3, STATE_START + emit->n_state - 1 - 2); - } + // Set code_state.fun_bc + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_FUN_OBJ(emit), REG_ARG_1); + + // Set code_state.ip (offset from start of this function to prelude info) + // TODO this encoding may change size in the final pass, need to make it fixed + emit_native_mov_state_imm_via(emit, emit->code_state_start + offsetof(mp_code_state_t, ip) / sizeof(uintptr_t), emit->prelude_offset, REG_ARG_1); + + // Put address of code_state into first arg + ASM_MOV_REG_LOCAL_ADDR(emit->as, REG_ARG_1, emit->code_state_start); + + // Call mp_setup_code_state to prepare code_state structure + #if N_THUMB + asm_thumb_bl_ind(emit->as, MP_F_SETUP_CODE_STATE, ASM_THUMB_REG_R4); + #elif N_ARM + asm_arm_bl_ind(emit->as, MP_F_SETUP_CODE_STATE, ASM_ARM_REG_R4); + #else + ASM_CALL_IND(emit->as, MP_F_SETUP_CODE_STATE); + #endif + } + + emit_native_global_exc_entry(emit); + + // cache some locals in registers, but only if no exception handlers + if (CAN_USE_REGS_FOR_LOCALS(emit)) { + for (int i = 0; i < REG_LOCAL_NUM && i < scope->num_locals; ++i) { + ASM_MOV_REG_LOCAL(emit->as, reg_local_table[i], LOCAL_IDX_LOCAL_VAR(emit, i)); } } @@ -412,14 +554,28 @@ STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop emit->local_vtype[id->local_num] = VTYPE_PYOBJ; } } + + if (pass == MP_PASS_EMIT) { + // write argument names as qstr objects + // see comment in corresponding part of emitbc.c about the logic here + for (int i = 0; i < scope->num_pos_args + scope->num_kwonly_args; i++) { + qstr qst = MP_QSTR__star_; + for (int j = 0; j < scope->id_info_len; ++j) { + id_info_t *id = &scope->id_info[j]; + if ((id->flags & ID_FLAG_IS_PARAM) && id->local_num == i) { + qst = id->qst; + break; + } + } + emit->const_table[i] = (mp_uint_t)MP_OBJ_NEW_QSTR(qst); + } + } } } STATIC void emit_native_end_pass(emit_t *emit) { - if (!emit->last_emit_was_return_value) { - ASM_EXIT(emit->as); - } + emit_native_global_exc_exit(emit); if (!emit->do_viper_types) { emit->prelude_offset = mp_asm_base_get_code_pos(&emit->as->base); @@ -451,49 +607,38 @@ STATIC void emit_native_end_pass(emit_t *emit) { } } mp_asm_base_data(&emit->as->base, 1, 255); // end of list sentinel - - mp_asm_base_align(&emit->as->base, ASM_WORD_SIZE); - emit->const_table_offset = mp_asm_base_get_code_pos(&emit->as->base); - - // write argument names as qstr objects - // see comment in corresponding part of emitbc.c about the logic here - for (int i = 0; i < emit->scope->num_pos_args + emit->scope->num_kwonly_args; i++) { - qstr qst = MP_QSTR__star_; - for (int j = 0; j < emit->scope->id_info_len; ++j) { - id_info_t *id = &emit->scope->id_info[j]; - if ((id->flags & ID_FLAG_IS_PARAM) && id->local_num == i) { - qst = id->qst; - break; - } - } - mp_asm_base_data(&emit->as->base, ASM_WORD_SIZE, (mp_uint_t)MP_OBJ_NEW_QSTR(qst)); - } - } ASM_END_PASS(emit->as); // check stack is back to zero size assert(emit->stack_size == 0); + assert(emit->exc_stack_size == 0); + + // Deal with const table accounting + assert(emit->pass <= MP_PASS_STACK_SIZE || (emit->const_table_num_obj == emit->const_table_cur_obj)); + emit->const_table_num_obj = emit->const_table_cur_obj; + if (emit->pass == MP_PASS_CODE_SIZE) { + size_t const_table_alloc = emit->const_table_num_obj + emit->const_table_cur_raw_code; + size_t nqstr = 0; + if (!emit->do_viper_types) { + // Add room for qstr names of arguments + nqstr = emit->scope->num_pos_args + emit->scope->num_kwonly_args; + const_table_alloc += nqstr; + } + emit->const_table = m_new(mp_uint_t, const_table_alloc); + // Store mp_fun_table pointer just after qstrs + emit->const_table[nqstr] = (mp_uint_t)(uintptr_t)mp_fun_table; + } if (emit->pass == MP_PASS_EMIT) { void *f = mp_asm_base_get_code(&emit->as->base); mp_uint_t f_len = mp_asm_base_get_code_size(&emit->as->base); - // compute type signature - // note that the lower 4 bits of a vtype are tho correct MP_NATIVE_TYPE_xxx - mp_uint_t type_sig = emit->return_vtype & 0xf; - for (mp_uint_t i = 0; i < emit->scope->num_pos_args; i++) { - type_sig |= (emit->local_vtype[i] & 0xf) << (i * 4 + 4); - } - - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wcast-align" mp_emit_glue_assign_native(emit->scope->raw_code, emit->do_viper_types ? MP_CODE_NATIVE_VIPER : MP_CODE_NATIVE_PY, - f, f_len, (mp_uint_t *)((byte *)f + emit->const_table_offset), - emit->scope->num_pos_args, emit->scope->scope_flags, type_sig); - #pragma GCC diagnostic pop + f, f_len, emit->const_table, + emit->scope->num_pos_args, emit->scope->scope_flags, 0); } } @@ -501,8 +646,17 @@ STATIC bool emit_native_last_emit_was_return_value(emit_t *emit) { return emit->last_emit_was_return_value; } +STATIC void ensure_extra_stack(emit_t *emit, size_t delta) { + if (emit->stack_size + delta > emit->stack_info_alloc) { + size_t new_alloc = (emit->stack_size + delta + 8) & ~3; + emit->stack_info = m_renew(stack_info_t, emit->stack_info, emit->stack_info_alloc, new_alloc); + emit->stack_info_alloc = new_alloc; + } +} + STATIC void adjust_stack(emit_t *emit, mp_int_t stack_size_delta) { assert((mp_int_t)emit->stack_size + stack_size_delta >= 0); + assert((mp_int_t)emit->stack_size + stack_size_delta <= (mp_int_t)emit->stack_info_alloc); emit->stack_size += stack_size_delta; if (emit->pass > MP_PASS_SCOPE && emit->stack_size > emit->scope->stack_size) { emit->scope->stack_size = emit->stack_size; @@ -519,6 +673,9 @@ STATIC void adjust_stack(emit_t *emit, mp_int_t stack_size_delta) { STATIC void emit_native_adjust_stack_size(emit_t *emit, mp_int_t delta) { DEBUG_printf("adjust_stack_size(" INT_FMT ")\n", delta); + if (delta > 0) { + ensure_extra_stack(emit, delta); + } // If we are adjusting the stack in a positive direction (pushing) then we // need to fill in values for the stack kind and vtype of the newly-pushed // entries. These should be set to "value" (ie not reg or imm) because we @@ -555,7 +712,12 @@ STATIC stack_info_t *peek_stack(emit_t *emit, mp_uint_t depth) { // depth==0 is top, depth==1 is before top, etc STATIC vtype_kind_t peek_vtype(emit_t *emit, mp_uint_t depth) { - return peek_stack(emit, depth)->vtype; + if (emit->do_viper_types) { + return peek_stack(emit, depth)->vtype; + } else { + // Type is always PYOBJ even if the intermediate stored value is not + return VTYPE_PYOBJ; + } } // pos=1 is TOS, pos=2 is next, etc @@ -567,7 +729,7 @@ STATIC void need_reg_single(emit_t *emit, int reg_needed, int skip_stack_pos) { stack_info_t *si = &emit->stack_info[i]; if (si->kind == STACK_REG && si->data.u_reg == reg_needed) { si->kind = STACK_VALUE; - ASM_MOV_LOCAL_REG(emit->as, emit->stack_start + i, si->data.u_reg); + emit_native_mov_state_reg(emit, emit->stack_start + i, si->data.u_reg); } } } @@ -578,11 +740,31 @@ STATIC void need_reg_all(emit_t *emit) { stack_info_t *si = &emit->stack_info[i]; if (si->kind == STACK_REG) { si->kind = STACK_VALUE; - ASM_MOV_LOCAL_REG(emit->as, emit->stack_start + i, si->data.u_reg); + emit_native_mov_state_reg(emit, emit->stack_start + i, si->data.u_reg); } } } +STATIC vtype_kind_t load_reg_stack_imm(emit_t *emit, int reg_dest, const stack_info_t *si, bool convert_to_pyobj) { + if (!convert_to_pyobj && emit->do_viper_types) { + ASM_MOV_REG_IMM(emit->as, reg_dest, si->data.u_imm); + return si->vtype; + } else { + if (si->vtype == VTYPE_PYOBJ) { + ASM_MOV_REG_IMM(emit->as, reg_dest, si->data.u_imm); + } else if (si->vtype == VTYPE_BOOL) { + emit_native_mov_reg_const(emit, reg_dest, MP_F_CONST_FALSE_OBJ + si->data.u_imm); + } else if (si->vtype == VTYPE_INT || si->vtype == VTYPE_UINT) { + ASM_MOV_REG_IMM(emit->as, reg_dest, (uintptr_t)MP_OBJ_NEW_SMALL_INT(si->data.u_imm)); + } else if (si->vtype == VTYPE_PTR_NONE) { + emit_native_mov_reg_const(emit, reg_dest, MP_F_CONST_NONE_OBJ); + } else { + mp_raise_NotImplementedError(translate("conversion to object")); + } + return VTYPE_PYOBJ; + } +} + STATIC void need_stack_settled(emit_t *emit) { DEBUG_printf(" need_stack_settled; stack_size=%d\n", emit->stack_size); for (int i = 0; i < emit->stack_size; i++) { @@ -590,7 +772,7 @@ STATIC void need_stack_settled(emit_t *emit) { if (si->kind == STACK_REG) { DEBUG_printf(" reg(%u) to local(%u)\n", si->data.u_reg, emit->stack_start + i); si->kind = STACK_VALUE; - ASM_MOV_LOCAL_REG(emit->as, emit->stack_start + i, si->data.u_reg); + emit_native_mov_state_reg(emit, emit->stack_start + i, si->data.u_reg); } } for (int i = 0; i < emit->stack_size; i++) { @@ -598,7 +780,8 @@ STATIC void need_stack_settled(emit_t *emit) { if (si->kind == STACK_IMM) { DEBUG_printf(" imm(" INT_FMT ") to local(%u)\n", si->data.u_imm, emit->stack_start + i); si->kind = STACK_VALUE; - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + i, si->data.u_imm, REG_TEMP0); + si->vtype = load_reg_stack_imm(emit, REG_TEMP0, si, false); + emit_native_mov_state_reg(emit, emit->stack_start + i, REG_TEMP0); } } } @@ -610,7 +793,7 @@ STATIC void emit_access_stack(emit_t *emit, int pos, vtype_kind_t *vtype, int re *vtype = si->vtype; switch (si->kind) { case STACK_VALUE: - ASM_MOV_REG_LOCAL(emit->as, reg_dest, emit->stack_start + emit->stack_size - pos); + emit_native_mov_reg_state(emit, reg_dest, emit->stack_start + emit->stack_size - pos); break; case STACK_REG: @@ -620,7 +803,7 @@ STATIC void emit_access_stack(emit_t *emit, int pos, vtype_kind_t *vtype, int re break; case STACK_IMM: - ASM_MOV_REG_IMM(emit->as, reg_dest, si->data.u_imm); + *vtype = load_reg_stack_imm(emit, reg_dest, si, false); break; } } @@ -632,7 +815,7 @@ STATIC void emit_fold_stack_top(emit_t *emit, int reg_dest) { si[0] = si[1]; if (si->kind == STACK_VALUE) { // if folded element was on the stack we need to put it in a register - ASM_MOV_REG_LOCAL(emit->as, reg_dest, emit->stack_start + emit->stack_size - 1); + emit_native_mov_reg_state(emit, reg_dest, emit->stack_start + emit->stack_size - 1); si->kind = STACK_REG; si->data.u_reg = reg_dest; } @@ -686,6 +869,7 @@ STATIC void emit_post_top_set_vtype(emit_t *emit, vtype_kind_t new_vtype) { } STATIC void emit_post_push_reg(emit_t *emit, vtype_kind_t vtype, int reg) { + ensure_extra_stack(emit, 1); stack_info_t *si = &emit->stack_info[emit->stack_size]; si->vtype = vtype; si->kind = STACK_REG; @@ -694,6 +878,7 @@ STATIC void emit_post_push_reg(emit_t *emit, vtype_kind_t vtype, int reg) { } STATIC void emit_post_push_imm(emit_t *emit, vtype_kind_t vtype, mp_int_t imm) { + ensure_extra_stack(emit, 1); stack_info_t *si = &emit->stack_info[emit->stack_size]; si->vtype = vtype; si->kind = STACK_IMM; @@ -721,36 +906,20 @@ STATIC void emit_post_push_reg_reg_reg_reg(emit_t *emit, vtype_kind_t vtypea, in STATIC void emit_call(emit_t *emit, mp_fun_kind_t fun_kind) { need_reg_all(emit); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); + ASM_CALL_IND(emit->as, fun_kind); } STATIC void emit_call_with_imm_arg(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val, int arg_reg) { need_reg_all(emit); ASM_MOV_REG_IMM(emit->as, arg_reg, arg_val); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); -} - -// the first arg is stored in the code aligned on a mp_uint_t boundary -STATIC void emit_call_with_imm_arg_aligned(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val, int arg_reg) { - need_reg_all(emit); - ASM_MOV_REG_ALIGNED_IMM(emit->as, arg_reg, arg_val); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); + ASM_CALL_IND(emit->as, fun_kind); } STATIC void emit_call_with_2_imm_args(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val1, int arg_reg1, mp_int_t arg_val2, int arg_reg2) { need_reg_all(emit); ASM_MOV_REG_IMM(emit->as, arg_reg1, arg_val1); ASM_MOV_REG_IMM(emit->as, arg_reg2, arg_val2); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); -} - -// the first arg is stored in the code aligned on a mp_uint_t boundary -STATIC void emit_call_with_3_imm_args_and_first_aligned(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val1, int arg_reg1, mp_int_t arg_val2, int arg_reg2, mp_int_t arg_val3, int arg_reg3) { - need_reg_all(emit); - ASM_MOV_REG_ALIGNED_IMM(emit->as, arg_reg1, arg_val1); - ASM_MOV_REG_IMM(emit->as, arg_reg2, arg_val2); - ASM_MOV_REG_IMM(emit->as, arg_reg3, arg_val3); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); + ASM_CALL_IND(emit->as, fun_kind); } // vtype of all n_pop objects is VTYPE_PYOBJ @@ -767,27 +936,8 @@ STATIC void emit_get_stack_pointer_to_reg_for_pop(emit_t *emit, mp_uint_t reg_de // must convert them to VTYPE_PYOBJ for viper code if (si->kind == STACK_IMM) { si->kind = STACK_VALUE; - switch (si->vtype) { - case VTYPE_PYOBJ: - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + emit->stack_size - 1 - i, si->data.u_imm, reg_dest); - break; - case VTYPE_BOOL: - if (si->data.u_imm == 0) { - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + emit->stack_size - 1 - i, (mp_uint_t)mp_const_false, reg_dest); - } else { - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + emit->stack_size - 1 - i, (mp_uint_t)mp_const_true, reg_dest); - } - si->vtype = VTYPE_PYOBJ; - break; - case VTYPE_INT: - case VTYPE_UINT: - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + emit->stack_size - 1 - i, (uintptr_t)MP_OBJ_NEW_SMALL_INT(si->data.u_imm), reg_dest); - si->vtype = VTYPE_PYOBJ; - break; - default: - // not handled - mp_raise_NotImplementedError(translate("conversion to object")); - } + si->vtype = load_reg_stack_imm(emit, reg_dest, si, true); + emit_native_mov_state_reg(emit, emit->stack_start + emit->stack_size - 1 - i, reg_dest); } // verify that this value is on the stack @@ -799,9 +949,9 @@ STATIC void emit_get_stack_pointer_to_reg_for_pop(emit_t *emit, mp_uint_t reg_de stack_info_t *si = &emit->stack_info[emit->stack_size - 1 - i]; if (si->vtype != VTYPE_PYOBJ) { mp_uint_t local_num = emit->stack_start + emit->stack_size - 1 - i; - ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, local_num); + emit_native_mov_reg_state(emit, REG_ARG_1, local_num); emit_call_with_imm_arg(emit, MP_F_CONVERT_NATIVE_TO_OBJ, si->vtype, REG_ARG_2); // arg2 = type - ASM_MOV_LOCAL_REG(emit->as, local_num, REG_RET); + emit_native_mov_state_reg(emit, local_num, REG_RET); si->vtype = VTYPE_PYOBJ; DEBUG_printf(" convert_native_to_obj(local_num=" UINT_FMT ")\n", local_num); } @@ -809,59 +959,266 @@ STATIC void emit_get_stack_pointer_to_reg_for_pop(emit_t *emit, mp_uint_t reg_de // Adujust the stack for a pop of n_pop items, and load the stack pointer into reg_dest. adjust_stack(emit, -n_pop); - ASM_MOV_REG_LOCAL_ADDR(emit->as, reg_dest, emit->stack_start + emit->stack_size); + emit_native_mov_reg_state_addr(emit, reg_dest, emit->stack_start + emit->stack_size); } // vtype of all n_push objects is VTYPE_PYOBJ STATIC void emit_get_stack_pointer_to_reg_for_push(emit_t *emit, mp_uint_t reg_dest, mp_uint_t n_push) { need_reg_all(emit); + ensure_extra_stack(emit, n_push); for (mp_uint_t i = 0; i < n_push; i++) { emit->stack_info[emit->stack_size + i].kind = STACK_VALUE; emit->stack_info[emit->stack_size + i].vtype = VTYPE_PYOBJ; } - ASM_MOV_REG_LOCAL_ADDR(emit->as, reg_dest, emit->stack_start + emit->stack_size); + emit_native_mov_reg_state_addr(emit, reg_dest, emit->stack_start + emit->stack_size); adjust_stack(emit, n_push); } +STATIC void emit_native_push_exc_stack(emit_t *emit, uint label, bool is_finally) { + if (emit->exc_stack_size + 1 > emit->exc_stack_alloc) { + size_t new_alloc = emit->exc_stack_alloc + 4; + emit->exc_stack = m_renew(exc_stack_entry_t, emit->exc_stack, emit->exc_stack_alloc, new_alloc); + emit->exc_stack_alloc = new_alloc; + } + + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size++]; + e->label = label; + e->is_finally = is_finally; + e->unwind_label = UNWIND_LABEL_UNUSED; + e->is_active = true; + + ASM_MOV_REG_PCREL(emit->as, REG_RET, label); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_RET); +} + +STATIC void emit_native_leave_exc_stack(emit_t *emit, bool start_of_handler) { + assert(emit->exc_stack_size > 0); + + // Get current exception handler and deactivate it + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1]; + e->is_active = false; + + // Find next innermost active exception handler, to restore as current handler + for (--e; e >= emit->exc_stack && !e->is_active; --e) { + } + + // Update the PC of the new exception handler + if (e < emit->exc_stack) { + // No active handler, clear handler PC to zero + if (start_of_handler) { + // Optimisation: PC is already cleared by global exc handler + return; + } + ASM_XOR_REG_REG(emit->as, REG_RET, REG_RET); + } else { + // Found new active handler, get its PC + ASM_MOV_REG_PCREL(emit->as, REG_RET, e->label); + } + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_RET); +} + +STATIC exc_stack_entry_t *emit_native_pop_exc_stack(emit_t *emit) { + assert(emit->exc_stack_size > 0); + exc_stack_entry_t *e = &emit->exc_stack[--emit->exc_stack_size]; + assert(e->is_active == false); + return e; +} + +STATIC void emit_load_reg_with_ptr(emit_t *emit, int reg, mp_uint_t ptr, size_t table_off) { + if (!emit->do_viper_types) { + // Skip qstr names of arguments + table_off += emit->scope->num_pos_args + emit->scope->num_kwonly_args; + } + if (emit->pass == MP_PASS_EMIT) { + emit->const_table[table_off] = ptr; + } + emit_native_mov_reg_state(emit, REG_TEMP0, LOCAL_IDX_FUN_OBJ(emit)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_TEMP0, REG_TEMP0, offsetof(mp_obj_fun_bc_t, const_table) / sizeof(uintptr_t)); + ASM_LOAD_REG_REG_OFFSET(emit->as, reg, REG_TEMP0, table_off); +} + +STATIC void emit_load_reg_with_object(emit_t *emit, int reg, mp_obj_t obj) { + size_t table_off = emit->const_table_cur_obj++; + emit_load_reg_with_ptr(emit, reg, (mp_uint_t)obj, table_off); +} + +STATIC void emit_load_reg_with_raw_code(emit_t *emit, int reg, mp_raw_code_t *rc) { + size_t table_off = emit->const_table_num_obj + emit->const_table_cur_raw_code++; + emit_load_reg_with_ptr(emit, reg, (mp_uint_t)rc, table_off); +} + STATIC void emit_native_label_assign(emit_t *emit, mp_uint_t l) { DEBUG_printf("label_assign(" UINT_FMT ")\n", l); + + bool is_finally = false; + if (emit->exc_stack_size > 0) { + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1]; + is_finally = e->is_finally && e->label == l; + } + + if (is_finally) { + // Label is at start of finally handler: store TOS into exception slot + vtype_kind_t vtype; + emit_pre_pop_reg(emit, &vtype, REG_TEMP0); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_TEMP0); + } + emit_native_pre(emit); // need to commit stack because we can jump here from elsewhere need_stack_settled(emit); mp_asm_base_label_assign(&emit->as->base, l); emit_post(emit); + + if (is_finally) { + // Label is at start of finally handler: pop exception stack + emit_native_leave_exc_stack(emit, false); + } +} + +STATIC void emit_native_global_exc_entry(emit_t *emit) { + // Note: 4 labels are reserved for this function, starting at *emit->label_slot + + emit->exit_label = *emit->label_slot; + + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + mp_uint_t nlr_label = *emit->label_slot + 1; + mp_uint_t start_label = *emit->label_slot + 2; + mp_uint_t global_except_label = *emit->label_slot + 3; + + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + // Set new globals + emit_native_mov_reg_state(emit, REG_ARG_1, LOCAL_IDX_FUN_OBJ(emit)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_ARG_1, REG_ARG_1, offsetof(mp_obj_fun_bc_t, globals) / sizeof(uintptr_t)); + emit_call(emit, MP_F_NATIVE_SWAP_GLOBALS); + + // Save old globals (or NULL if globals didn't change) + emit_native_mov_state_reg(emit, LOCAL_IDX_OLD_GLOBALS(emit), REG_RET); + } + + if (emit->scope->exc_stack_size == 0) { + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + // Optimisation: if globals didn't change don't push the nlr context + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, start_label, false); + } + + // Wrap everything in an nlr context + ASM_MOV_REG_LOCAL_ADDR(emit->as, REG_ARG_1, 0); + emit_call(emit, MP_F_NLR_PUSH); + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, start_label, true); + } else { + // Clear the unwind state + ASM_XOR_REG_REG(emit->as, REG_TEMP0, REG_TEMP0); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_UNWIND(emit), REG_TEMP0); + + // Put PC of start code block into REG_LOCAL_1 + ASM_MOV_REG_PCREL(emit->as, REG_LOCAL_1, start_label); + + // Wrap everything in an nlr context + emit_native_label_assign(emit, nlr_label); + ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_2, LOCAL_IDX_EXC_HANDLER_UNWIND(emit)); + ASM_MOV_REG_LOCAL_ADDR(emit->as, REG_ARG_1, 0); + emit_call(emit, MP_F_NLR_PUSH); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_UNWIND(emit), REG_LOCAL_2); + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, global_except_label, true); + + // Clear PC of current code block, and jump there to resume execution + ASM_XOR_REG_REG(emit->as, REG_TEMP0, REG_TEMP0); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_TEMP0); + ASM_JUMP_REG(emit->as, REG_LOCAL_1); + + // Global exception handler: check for valid exception handler + emit_native_label_assign(emit, global_except_label); + ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_1, LOCAL_IDX_EXC_HANDLER_PC(emit)); + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_LOCAL_1, nlr_label, false); + } + + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + // Restore old globals + emit_native_mov_reg_state(emit, REG_ARG_1, LOCAL_IDX_OLD_GLOBALS(emit)); + emit_call(emit, MP_F_NATIVE_SWAP_GLOBALS); + } + + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + // Store return value in state[0] + ASM_MOV_REG_LOCAL(emit->as, REG_TEMP0, LOCAL_IDX_EXC_VAL(emit)); + ASM_STORE_REG_REG_OFFSET(emit->as, REG_TEMP0, REG_GENERATOR_STATE, offsetof(mp_code_state_t, state) / sizeof(uintptr_t)); + + // Load return kind + ASM_MOV_REG_IMM(emit->as, REG_RET, MP_VM_RETURN_EXCEPTION); + + ASM_EXIT(emit->as); + } else { + // Re-raise exception out to caller + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); + emit_call(emit, MP_F_NATIVE_RAISE); + } + + // Label for start of function + emit_native_label_assign(emit, start_label); + + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + emit_native_mov_reg_state(emit, REG_TEMP0, LOCAL_IDX_GEN_PC(emit)); + ASM_JUMP_REG(emit->as, REG_TEMP0); + emit->start_offset = mp_asm_base_get_code_pos(&emit->as->base); + + // This is the first entry of the generator + + // Check LOCAL_IDX_EXC_VAL for any injected value + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); + emit_call(emit, MP_F_NATIVE_RAISE); + } + } +} + +STATIC void emit_native_global_exc_exit(emit_t *emit) { + // Label for end of function + emit_native_label_assign(emit, emit->exit_label); + + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + // Get old globals + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + emit_native_mov_reg_state(emit, REG_ARG_1, LOCAL_IDX_OLD_GLOBALS(emit)); + + if (emit->scope->exc_stack_size == 0) { + // Optimisation: if globals didn't change then don't restore them and don't do nlr_pop + ASM_JUMP_IF_REG_ZERO(emit->as, REG_ARG_1, emit->exit_label + 1, false); + } + + // Restore old globals + emit_call(emit, MP_F_NATIVE_SWAP_GLOBALS); + } + + // Pop the nlr context + emit_call(emit, MP_F_NLR_POP); + + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + if (emit->scope->exc_stack_size == 0) { + // Destination label for above optimisation + emit_native_label_assign(emit, emit->exit_label + 1); + } + } + + // Load return value + ASM_MOV_REG_LOCAL(emit->as, REG_RET, LOCAL_IDX_RET_VAL(emit)); + } + + ASM_EXIT(emit->as); } STATIC void emit_native_import_name(emit_t *emit, qstr qst) { DEBUG_printf("import_name %s\n", qstr_str(qst)); // get arguments from stack: arg2 = fromlist, arg3 = level - // if using viper types these arguments must be converted to proper objects - if (emit->do_viper_types) { - // fromlist should be None or a tuple - stack_info_t *top = peek_stack(emit, 0); - if (top->vtype == VTYPE_PTR_NONE) { - emit_pre_pop_discard(emit); - ASM_MOV_REG_IMM(emit->as, REG_ARG_2, (mp_uint_t)mp_const_none); - } else { - vtype_kind_t vtype_fromlist; - emit_pre_pop_reg(emit, &vtype_fromlist, REG_ARG_2); - assert(vtype_fromlist == VTYPE_PYOBJ); - } - - // level argument should be an immediate integer - top = peek_stack(emit, 0); - assert(top->vtype == VTYPE_INT && top->kind == STACK_IMM); - ASM_MOV_REG_IMM(emit->as, REG_ARG_3, (mp_uint_t)MP_OBJ_NEW_SMALL_INT(top->data.u_imm)); - emit_pre_pop_discard(emit); - - } else { - vtype_kind_t vtype_fromlist; - vtype_kind_t vtype_level; - emit_pre_pop_reg_reg(emit, &vtype_fromlist, REG_ARG_2, &vtype_level, REG_ARG_3); - assert(vtype_fromlist == VTYPE_PYOBJ); - assert(vtype_level == VTYPE_PYOBJ); - } + // If using viper types these arguments must be converted to proper objects, and + // to accomplish this viper types are turned off for the emit_pre_pop_reg_reg call. + bool orig_do_viper_types = emit->do_viper_types; + emit->do_viper_types = false; + vtype_kind_t vtype_fromlist; + vtype_kind_t vtype_level; + emit_pre_pop_reg_reg(emit, &vtype_fromlist, REG_ARG_2, &vtype_level, REG_ARG_3); + assert(vtype_fromlist == VTYPE_PYOBJ); + assert(vtype_level == VTYPE_PYOBJ); + emit->do_viper_types = orig_do_viper_types; emit_call_with_imm_arg(emit, MP_F_IMPORT_NAME, qst, REG_ARG_1); // arg1 = import name emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); @@ -898,58 +1255,22 @@ STATIC void emit_native_import(emit_t *emit, qstr qst, int kind) { STATIC void emit_native_load_const_tok(emit_t *emit, mp_token_kind_t tok) { DEBUG_printf("load_const_tok(tok=%u)\n", tok); - emit_native_pre(emit); - vtype_kind_t vtype; - mp_uint_t val; - if (emit->do_viper_types) { - switch (tok) { - case MP_TOKEN_KW_NONE: - vtype = VTYPE_PTR_NONE; - val = 0; - break; - case MP_TOKEN_KW_FALSE: - vtype = VTYPE_BOOL; - val = 0; - break; - case MP_TOKEN_KW_TRUE: - vtype = VTYPE_BOOL; - val = 1; - break; - default: - assert(tok == MP_TOKEN_ELLIPSIS); - vtype = VTYPE_PYOBJ; - val = (mp_uint_t)&mp_const_ellipsis_obj; - break; - } + if (tok == MP_TOKEN_ELLIPSIS) { + emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)MP_OBJ_FROM_PTR(&mp_const_ellipsis_obj)); } else { - vtype = VTYPE_PYOBJ; - switch (tok) { - case MP_TOKEN_KW_NONE: - val = (mp_uint_t)mp_const_none; - break; - case MP_TOKEN_KW_FALSE: - val = (mp_uint_t)mp_const_false; - break; - case MP_TOKEN_KW_TRUE: - val = (mp_uint_t)mp_const_true; - break; - default: - assert(tok == MP_TOKEN_ELLIPSIS); - val = (mp_uint_t)&mp_const_ellipsis_obj; - break; + emit_native_pre(emit); + if (tok == MP_TOKEN_KW_NONE) { + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); + } else { + emit_post_push_imm(emit, VTYPE_BOOL, tok == MP_TOKEN_KW_FALSE ? 0 : 1); } } - emit_post_push_imm(emit, vtype, val); } STATIC void emit_native_load_const_small_int(emit_t *emit, mp_int_t arg) { DEBUG_printf("load_const_small_int(int=" INT_FMT ")\n", arg); emit_native_pre(emit); - if (emit->do_viper_types) { - emit_post_push_imm(emit, VTYPE_INT, arg); - } else { - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)MP_OBJ_NEW_SMALL_INT(arg)); - } + emit_post_push_imm(emit, VTYPE_INT, arg); } STATIC void emit_native_load_const_str(emit_t *emit, qstr qst) { @@ -970,7 +1291,7 @@ STATIC void emit_native_load_const_str(emit_t *emit, qstr qst) { STATIC void emit_native_load_const_obj(emit_t *emit, mp_obj_t obj) { emit_native_pre(emit); need_reg_single(emit, REG_RET, 0); - ASM_MOV_REG_ALIGNED_IMM(emit->as, REG_RET, (mp_uint_t)obj); + emit_load_reg_with_object(emit, REG_RET, obj); emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } @@ -986,19 +1307,11 @@ STATIC void emit_native_load_fast(emit_t *emit, qstr qst, mp_uint_t local_num) { EMIT_NATIVE_VIPER_TYPE_ERROR(emit, translate("local '%q' used before type known"), qst); } emit_native_pre(emit); - if (local_num == 0) { - emit_post_push_reg(emit, vtype, REG_LOCAL_1); - } else if (local_num == 1) { - emit_post_push_reg(emit, vtype, REG_LOCAL_2); - } else if (local_num == 2) { - emit_post_push_reg(emit, vtype, REG_LOCAL_3); + if (local_num < REG_LOCAL_NUM && CAN_USE_REGS_FOR_LOCALS(emit)) { + emit_post_push_reg(emit, vtype, reg_local_table[local_num]); } else { need_reg_single(emit, REG_TEMP0, 0); - if (emit->do_viper_types) { - ASM_MOV_REG_LOCAL(emit->as, REG_TEMP0, local_num - REG_LOCAL_NUM); - } else { - ASM_MOV_REG_LOCAL(emit->as, REG_TEMP0, STATE_START + emit->n_state - 1 - local_num); - } + emit_native_mov_reg_state(emit, REG_TEMP0, LOCAL_IDX_LOCAL_VAR(emit, local_num)); emit_post_push_reg(emit, vtype, REG_TEMP0); } } @@ -1033,23 +1346,9 @@ STATIC void emit_native_load_global(emit_t *emit, qstr qst, int kind) { DEBUG_printf("load_global(%s)\n", qstr_str(qst)); if (emit->do_viper_types) { // check for builtin casting operators - if (qst == MP_QSTR_int) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_INT); - return; - } else if (qst == MP_QSTR_uint) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_UINT); - return; - } else if (qst == MP_QSTR_ptr) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_PTR); - return; - } else if (qst == MP_QSTR_ptr8) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_PTR8); - return; - } else if (qst == MP_QSTR_ptr16) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_PTR16); - return; - } else if (qst == MP_QSTR_ptr32) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_PTR32); + int native_type = mp_native_type_from_qstr(qst); + if (native_type >= MP_NATIVE_TYPE_INT) { + emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, native_type); return; } } @@ -1227,19 +1526,11 @@ STATIC void emit_native_load_subscr(emit_t *emit) { STATIC void emit_native_store_fast(emit_t *emit, qstr qst, mp_uint_t local_num) { vtype_kind_t vtype; - if (local_num == 0) { - emit_pre_pop_reg(emit, &vtype, REG_LOCAL_1); - } else if (local_num == 1) { - emit_pre_pop_reg(emit, &vtype, REG_LOCAL_2); - } else if (local_num == 2) { - emit_pre_pop_reg(emit, &vtype, REG_LOCAL_3); + if (local_num < REG_LOCAL_NUM && CAN_USE_REGS_FOR_LOCALS(emit)) { + emit_pre_pop_reg(emit, &vtype, reg_local_table[local_num]); } else { emit_pre_pop_reg(emit, &vtype, REG_TEMP0); - if (emit->do_viper_types) { - ASM_MOV_LOCAL_REG(emit->as, local_num - REG_LOCAL_NUM, REG_TEMP0); - } else { - ASM_MOV_LOCAL_REG(emit->as, STATE_START + emit->n_state - 1 - local_num, REG_TEMP0); - } + emit_native_mov_state_reg(emit, LOCAL_IDX_LOCAL_VAR(emit, local_num), REG_TEMP0); } emit_post(emit); @@ -1387,10 +1678,6 @@ STATIC void emit_native_store_subscr(emit_t *emit) { } #endif ASM_MOV_REG_IMM(emit->as, reg_index, index_value << 1); - #if N_ARM - asm_arm_strh_reg_reg_reg(emit->as, reg_value, reg_base, reg_index); - return; - #endif ASM_ADD_REG_REG(emit->as, reg_index, reg_base); // add 2*index to base reg_base = reg_index; } @@ -1407,11 +1694,12 @@ STATIC void emit_native_store_subscr(emit_t *emit) { break; } #endif - ASM_MOV_REG_IMM(emit->as, reg_index, index_value << 2); #if N_ARM + ASM_MOV_REG_IMM(emit->as, reg_index, index_value); asm_arm_str_reg_reg_reg(emit->as, reg_value, reg_base, reg_index); return; #endif + ASM_MOV_REG_IMM(emit->as, reg_index, index_value << 2); ASM_ADD_REG_REG(emit->as, reg_index, reg_base); // add 4*index to base reg_base = reg_index; } @@ -1587,7 +1875,7 @@ STATIC void emit_native_jump(emit_t *emit, mp_uint_t label) { emit_post(emit); } -STATIC void emit_native_jump_helper(emit_t *emit, bool pop) { +STATIC void emit_native_jump_helper(emit_t *emit, bool cond, mp_uint_t label, bool pop) { vtype_kind_t vtype = peek_vtype(emit, 0); if (vtype == VTYPE_PYOBJ) { emit_pre_pop_reg(emit, &vtype, REG_ARG_1); @@ -1612,34 +1900,69 @@ STATIC void emit_native_jump_helper(emit_t *emit, bool pop) { } // need to commit stack because we may jump elsewhere need_stack_settled(emit); + // Emit the jump + if (cond) { + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label, vtype == VTYPE_PYOBJ); + } else { + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label, vtype == VTYPE_PYOBJ); + } + if (!pop) { + adjust_stack(emit, -1); + } + emit_post(emit); } STATIC void emit_native_pop_jump_if(emit_t *emit, bool cond, mp_uint_t label) { DEBUG_printf("pop_jump_if(cond=%u, label=" UINT_FMT ")\n", cond, label); - emit_native_jump_helper(emit, true); - if (cond) { - ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label); - } else { - ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label); - } - emit_post(emit); + emit_native_jump_helper(emit, cond, label, true); } STATIC void emit_native_jump_if_or_pop(emit_t *emit, bool cond, mp_uint_t label) { DEBUG_printf("jump_if_or_pop(cond=%u, label=" UINT_FMT ")\n", cond, label); - emit_native_jump_helper(emit, false); - if (cond) { - ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label); - } else { - ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label); - } - adjust_stack(emit, -1); - emit_post(emit); + emit_native_jump_helper(emit, cond, label, false); } STATIC void emit_native_unwind_jump(emit_t *emit, mp_uint_t label, mp_uint_t except_depth) { - (void)except_depth; - emit_native_jump(emit, label & ~MP_EMIT_BREAK_FROM_FOR); // TODO properly + if (except_depth > 0) { + exc_stack_entry_t *first_finally = NULL; + exc_stack_entry_t *prev_finally = NULL; + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1]; + for (; except_depth > 0; --except_depth, --e) { + if (e->is_finally && e->is_active) { + // Found an active finally handler + if (first_finally == NULL) { + first_finally = e; + } + if (prev_finally != NULL) { + // Mark prev finally as needed to unwind a jump + prev_finally->unwind_label = e->label; + } + prev_finally = e; + } + } + if (prev_finally == NULL) { + // No finally, handle the jump ourselves + // First, restore the exception handler address for the jump + if (e < emit->exc_stack) { + ASM_XOR_REG_REG(emit->as, REG_RET, REG_RET); + } else { + ASM_MOV_REG_PCREL(emit->as, REG_RET, e->label); + } + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_RET); + } else { + // Last finally should do our jump for us + // Mark finally as needing to decide the type of jump + prev_finally->unwind_label = UNWIND_LABEL_DO_FINAL_UNWIND; + ASM_MOV_REG_PCREL(emit->as, REG_RET, label & ~MP_EMIT_BREAK_FROM_FOR); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_UNWIND(emit), REG_RET); + // Cancel any active exception (see also emit_native_pop_except) + emit_native_mov_reg_const(emit, REG_RET, MP_F_CONST_NONE_OBJ); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_RET); + // Jump to the innermost active finally + label = first_finally->label; + } + } + emit_native_jump(emit, label & ~MP_EMIT_BREAK_FROM_FOR); } STATIC void emit_native_setup_with(emit_t *emit, mp_uint_t label) { @@ -1675,13 +1998,10 @@ STATIC void emit_native_setup_with(emit_t *emit, mp_uint_t label) { // need to commit stack because we may jump elsewhere need_stack_settled(emit); - emit_get_stack_pointer_to_reg_for_push(emit, REG_ARG_1, sizeof(nlr_buf_t) / sizeof(mp_uint_t)); // arg1 = pointer to nlr buf - emit_call(emit, MP_F_NLR_PUSH); - ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label); + emit_native_push_exc_stack(emit, label, true); - emit_access_stack(emit, sizeof(nlr_buf_t) / sizeof(mp_uint_t) + 1, &vtype, REG_RET); // access return value of __enter__ - emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); // push return value of __enter__ - // stack: (..., __exit__, self, as_value, nlr_buf, as_value) + emit_native_dup_top(emit); + // stack: (..., __exit__, self, as_value, as_value) } STATIC void emit_native_setup_block(emit_t *emit, mp_uint_t label, int kind) { @@ -1690,82 +2010,78 @@ STATIC void emit_native_setup_block(emit_t *emit, mp_uint_t label, int kind) { } else { // Set up except and finally emit_native_pre(emit); - // need to commit stack because we may jump elsewhere need_stack_settled(emit); - emit_get_stack_pointer_to_reg_for_push(emit, REG_ARG_1, sizeof(nlr_buf_t) / sizeof(mp_uint_t)); // arg1 = pointer to nlr buf - emit_call(emit, MP_F_NLR_PUSH); - ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label); + emit_native_push_exc_stack(emit, label, kind == MP_EMIT_SETUP_BLOCK_FINALLY); emit_post(emit); } } STATIC void emit_native_with_cleanup(emit_t *emit, mp_uint_t label) { - // note: label+1 is available as an auxiliary label + // Note: 3 labels are reserved for this function, starting at *emit->label_slot - // stack: (..., __exit__, self, as_value, nlr_buf) + // stack: (..., __exit__, self, as_value) emit_native_pre(emit); - emit_call(emit, MP_F_NLR_POP); - adjust_stack(emit, -(mp_int_t)(sizeof(nlr_buf_t) / sizeof(mp_uint_t)) - 1); + emit_native_leave_exc_stack(emit, false); + adjust_stack(emit, -1); // stack: (..., __exit__, self) + // Label for case where __exit__ is called from an unwind jump + emit_native_label_assign(emit, *emit->label_slot + 2); + // call __exit__ - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_3, 5); emit_call_with_2_imm_args(emit, MP_F_CALL_METHOD_N_KW, 3, REG_ARG_1, 0, REG_ARG_2); - // jump to after with cleanup nlr_catch block - adjust_stack(emit, 1); // dummy nlr_buf.prev - emit_native_load_const_tok(emit, MP_TOKEN_KW_NONE); // nlr_buf.ret_val = no exception - emit_native_jump(emit, label + 1); + // Replace exc with None and finish + emit_native_jump(emit, *emit->label_slot); // nlr_catch - emit_native_label_assign(emit, label); + // Don't use emit_native_label_assign because this isn't a real finally label + mp_asm_base_label_assign(&emit->as->base, label); - // adjust stack counter for: __exit__, self, as_value - adjust_stack(emit, 3); - // stack: (..., __exit__, self, as_value, nlr_buf.prev, nlr_buf.ret_val) + // Leave with's exception handler + emit_native_leave_exc_stack(emit, true); - vtype_kind_t vtype; - emit_pre_pop_reg(emit, &vtype, REG_ARG_1); // get the thrown value (exc) - adjust_stack(emit, -2); // discard nlr_buf.prev and as_value + // Adjust stack counter for: __exit__, self (implicitly discard as_value which is above self) + emit_native_adjust_stack_size(emit, 2); // stack: (..., __exit__, self) - // REG_ARG_1=exc - emit_pre_pop_reg(emit, &vtype, REG_ARG_2); // self - emit_pre_pop_reg(emit, &vtype, REG_ARG_3); // __exit__ - adjust_stack(emit, 1); // dummy nlr_buf.prev - emit_post_push_reg(emit, vtype, REG_ARG_1); // push exc to save it for later - emit_post_push_reg(emit, vtype, REG_ARG_3); // __exit__ - emit_post_push_reg(emit, vtype, REG_ARG_2); // self - // stack: (..., exc, __exit__, self) - // REG_ARG_1=exc + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); // get exc + + // Check if exc is None and jump to non-exc handler if it is + emit_native_mov_reg_const(emit, REG_ARG_2, MP_F_CONST_NONE_OBJ); + ASM_JUMP_IF_REG_EQ(emit->as, REG_ARG_1, REG_ARG_2, *emit->label_slot + 2); ASM_LOAD_REG_REG_OFFSET(emit->as, REG_ARG_2, REG_ARG_1, 0); // get type(exc) emit_post_push_reg(emit, VTYPE_PYOBJ, REG_ARG_2); // push type(exc) emit_post_push_reg(emit, VTYPE_PYOBJ, REG_ARG_1); // push exc value - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); // traceback info - // stack: (..., exc, __exit__, self, type(exc), exc, traceback) + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); // traceback info + // Stack: (..., __exit__, self, type(exc), exc, traceback) // call __exit__ method emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_3, 5); emit_call_with_2_imm_args(emit, MP_F_CALL_METHOD_N_KW, 3, REG_ARG_1, 0, REG_ARG_2); - // stack: (..., exc) + // Stack: (...) - // if REG_RET is true then we need to replace top-of-stack with None (swallow exception) + // If REG_RET is true then we need to replace exception with None (swallow exception) if (REG_ARG_1 != REG_RET) { ASM_MOV_REG_REG(emit->as, REG_ARG_1, REG_RET); } emit_call(emit, MP_F_OBJ_IS_TRUE); - ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label + 1); + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, *emit->label_slot + 1, true); - // replace exc with None - emit_pre_pop_discard(emit); - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); + // Replace exception with None + emit_native_label_assign(emit, *emit->label_slot); + emit_native_mov_reg_const(emit, REG_TEMP0, MP_F_CONST_NONE_OBJ); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_TEMP0); // end of with cleanup nlr_catch block - emit_native_label_assign(emit, label + 1); + emit_native_label_assign(emit, *emit->label_slot + 1); + + // Exception is in nlr_buf.ret_val slot } STATIC void emit_native_end_finally(emit_t *emit) { @@ -1774,10 +2090,23 @@ STATIC void emit_native_end_finally(emit_t *emit) { // if exc == None: pass // else: raise exc // the check if exc is None is done in the MP_F_NATIVE_RAISE stub - vtype_kind_t vtype; - emit_pre_pop_reg(emit, &vtype, REG_ARG_1); // get nlr_buf.ret_val - emit_pre_pop_discard(emit); // discard nlr_buf.prev + emit_native_pre(emit); + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); emit_call(emit, MP_F_NATIVE_RAISE); + + // Get state for this finally and see if we need to unwind + exc_stack_entry_t *e = emit_native_pop_exc_stack(emit); + if (e->unwind_label != UNWIND_LABEL_UNUSED) { + ASM_MOV_REG_LOCAL(emit->as, REG_RET, LOCAL_IDX_EXC_HANDLER_UNWIND(emit)); + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, *emit->label_slot, false); + if (e->unwind_label == UNWIND_LABEL_DO_FINAL_UNWIND) { + ASM_JUMP_REG(emit->as, REG_RET); + } else { + emit_native_jump(emit, e->unwind_label); + } + emit_native_label_assign(emit, *emit->label_slot); + } + emit_post(emit); } @@ -1804,8 +2133,13 @@ STATIC void emit_native_for_iter(emit_t *emit, mp_uint_t label) { emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_1, MP_OBJ_ITER_BUF_NSLOTS); adjust_stack(emit, MP_OBJ_ITER_BUF_NSLOTS); emit_call(emit, MP_F_NATIVE_ITERNEXT); + #ifdef NDEBUG + MP_STATIC_ASSERT(MP_OBJ_STOP_ITERATION == 0); + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label, false); + #else ASM_MOV_REG_IMM(emit->as, REG_TEMP1, (mp_uint_t)MP_OBJ_STOP_ITERATION); ASM_JUMP_IF_REG_EQ(emit->as, REG_RET, REG_TEMP1, label); + #endif emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } @@ -1818,13 +2152,16 @@ STATIC void emit_native_for_iter_end(emit_t *emit) { STATIC void emit_native_pop_block(emit_t *emit) { emit_native_pre(emit); - emit_call(emit, MP_F_NLR_POP); - adjust_stack(emit, -(mp_int_t)(sizeof(nlr_buf_t) / sizeof(mp_uint_t)) + 1); + if (!emit->exc_stack[emit->exc_stack_size - 1].is_finally) { + emit_native_leave_exc_stack(emit, false); + } emit_post(emit); } STATIC void emit_native_pop_except(emit_t *emit) { - (void)emit; + // Cancel any active exception so subsequent handlers don't see it + emit_native_mov_reg_const(emit, REG_TEMP0, MP_F_CONST_NONE_OBJ); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_TEMP0); } STATIC void emit_native_unary_op(emit_t *emit, mp_unary_op_t op) { @@ -2061,8 +2398,7 @@ STATIC void emit_native_build_slice(emit_t *emit, mp_uint_t n_args) { emit_pre_pop_reg_reg(emit, &vtype_stop, REG_ARG_2, &vtype_start, REG_ARG_1); // arg1 = start, arg2 = stop assert(vtype_start == VTYPE_PYOBJ); assert(vtype_stop == VTYPE_PYOBJ); - emit_call_with_imm_arg(emit, MP_F_NEW_SLICE, (mp_uint_t)mp_const_none, REG_ARG_3); // arg3 = step - emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); + emit_native_mov_reg_const(emit, REG_ARG_3, MP_F_CONST_NONE_OBJ); // arg3 = step } else { assert(n_args == 3); vtype_kind_t vtype_start, vtype_stop, vtype_step; @@ -2070,9 +2406,9 @@ STATIC void emit_native_build_slice(emit_t *emit, mp_uint_t n_args) { assert(vtype_start == VTYPE_PYOBJ); assert(vtype_stop == VTYPE_PYOBJ); assert(vtype_step == VTYPE_PYOBJ); - emit_call(emit, MP_F_NEW_SLICE); - emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } + emit_call(emit, MP_F_NEW_SLICE); + emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } #endif @@ -2127,14 +2463,18 @@ STATIC void emit_native_make_function(emit_t *emit, scope_t *scope, mp_uint_t n_ // call runtime, with type info for args, or don't support dict/default params, or only support Python objects for them emit_native_pre(emit); if (n_pos_defaults == 0 && n_kw_defaults == 0) { - emit_call_with_3_imm_args_and_first_aligned(emit, MP_F_MAKE_FUNCTION_FROM_RAW_CODE, (mp_uint_t)scope->raw_code, REG_ARG_1, (mp_uint_t)MP_OBJ_NULL, REG_ARG_2, (mp_uint_t)MP_OBJ_NULL, REG_ARG_3); + need_reg_all(emit); + ASM_MOV_REG_IMM(emit->as, REG_ARG_2, (mp_uint_t)MP_OBJ_NULL); + ASM_MOV_REG_IMM(emit->as, REG_ARG_3, (mp_uint_t)MP_OBJ_NULL); } else { vtype_kind_t vtype_def_tuple, vtype_def_dict; emit_pre_pop_reg_reg(emit, &vtype_def_dict, REG_ARG_3, &vtype_def_tuple, REG_ARG_2); assert(vtype_def_tuple == VTYPE_PYOBJ); assert(vtype_def_dict == VTYPE_PYOBJ); - emit_call_with_imm_arg_aligned(emit, MP_F_MAKE_FUNCTION_FROM_RAW_CODE, (mp_uint_t)scope->raw_code, REG_ARG_1); + need_reg_all(emit); } + emit_load_reg_with_raw_code(emit, REG_ARG_1, scope->raw_code); + ASM_CALL_IND(emit->as, MP_F_MAKE_FUNCTION_FROM_RAW_CODE); emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } @@ -2147,8 +2487,8 @@ STATIC void emit_native_make_closure(emit_t *emit, scope_t *scope, mp_uint_t n_c emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_3, n_closed_over + 2); ASM_MOV_REG_IMM(emit->as, REG_ARG_2, 0x100 | n_closed_over); } - ASM_MOV_REG_ALIGNED_IMM(emit->as, REG_ARG_1, (mp_uint_t)scope->raw_code); - ASM_CALL_IND(emit->as, mp_fun_table[MP_F_MAKE_CLOSURE_FROM_RAW_CODE], MP_F_MAKE_CLOSURE_FROM_RAW_CODE); + emit_load_reg_with_raw_code(emit, REG_ARG_1, scope->raw_code); + ASM_CALL_IND(emit->as, MP_F_MAKE_CLOSURE_FROM_RAW_CODE); emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } @@ -2222,30 +2562,54 @@ STATIC void emit_native_call_method(emit_t *emit, mp_uint_t n_positional, mp_uin STATIC void emit_native_return_value(emit_t *emit) { DEBUG_printf("return_value\n"); + + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + // Save pointer to current stack position for caller to access return value + emit_get_stack_pointer_to_reg_for_pop(emit, REG_TEMP0, 1); + emit_native_mov_state_reg(emit, offsetof(mp_code_state_t, sp) / sizeof(uintptr_t), REG_TEMP0); + + // Put return type in return value slot + ASM_MOV_REG_IMM(emit->as, REG_TEMP0, MP_VM_RETURN_NORMAL); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_RET_VAL(emit), REG_TEMP0); + + // Do the unwinding jump to get to the return handler + emit_native_unwind_jump(emit, emit->exit_label, emit->exc_stack_size); + emit->last_emit_was_return_value = true; + return; + } + if (emit->do_viper_types) { + vtype_kind_t return_vtype = emit->scope->scope_flags >> MP_SCOPE_FLAG_VIPERRET_POS; if (peek_vtype(emit, 0) == VTYPE_PTR_NONE) { emit_pre_pop_discard(emit); - if (emit->return_vtype == VTYPE_PYOBJ) { - ASM_MOV_REG_IMM(emit->as, REG_RET, (mp_uint_t)mp_const_none); + if (return_vtype == VTYPE_PYOBJ) { + emit_native_mov_reg_const(emit, REG_RET, MP_F_CONST_NONE_OBJ); } else { - ASM_MOV_REG_IMM(emit->as, REG_RET, 0); + ASM_MOV_REG_IMM(emit->as, REG_ARG_1, 0); } } else { vtype_kind_t vtype; - emit_pre_pop_reg(emit, &vtype, REG_RET); - if (vtype != emit->return_vtype) { + emit_pre_pop_reg(emit, &vtype, return_vtype == VTYPE_PYOBJ ? REG_RET : REG_ARG_1); + if (vtype != return_vtype) { EMIT_NATIVE_VIPER_TYPE_ERROR(emit, translate("return expected '%q' but got '%q'"), - vtype_to_qstr(emit->return_vtype), vtype_to_qstr(vtype)); + vtype_to_qstr(return_vtype), vtype_to_qstr(vtype)); } } + if (return_vtype != VTYPE_PYOBJ) { + emit_call_with_imm_arg(emit, MP_F_CONVERT_NATIVE_TO_OBJ, return_vtype, REG_ARG_2); + } } else { vtype_kind_t vtype; emit_pre_pop_reg(emit, &vtype, REG_RET); assert(vtype == VTYPE_PYOBJ); } + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + // Save return value for the global exception handler to use + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_RET_VAL(emit), REG_RET); + } + emit_native_unwind_jump(emit, emit->exit_label, emit->exc_stack_size); emit->last_emit_was_return_value = true; - ASM_EXIT(emit->as); } STATIC void emit_native_raise_varargs(emit_t *emit, mp_uint_t n_args) { @@ -2260,29 +2624,101 @@ STATIC void emit_native_raise_varargs(emit_t *emit, mp_uint_t n_args) { } STATIC void emit_native_yield(emit_t *emit, int kind) { - // not supported (for now) - (void)emit; - (void)kind; - mp_raise_NotImplementedError(translate("native yield")); + // Note: 1 (yield) or 3 (yield from) labels are reserved for this function, starting at *emit->label_slot + + if (emit->do_viper_types) { + mp_raise_NotImplementedError(translate("native yield")); + } + emit->scope->scope_flags |= MP_SCOPE_FLAG_GENERATOR; + + need_stack_settled(emit); + + if (kind == MP_EMIT_YIELD_FROM) { + + // Top of yield-from loop, conceptually implementing: + // for item in generator: + // yield item + + // Jump to start of loop + emit_native_jump(emit, *emit->label_slot + 2); + + // Label for top of loop + emit_native_label_assign(emit, *emit->label_slot + 1); + } + + // Save pointer to current stack position for caller to access yielded value + emit_get_stack_pointer_to_reg_for_pop(emit, REG_TEMP0, 1); + emit_native_mov_state_reg(emit, offsetof(mp_code_state_t, sp) / sizeof(uintptr_t), REG_TEMP0); + + // Put return type in return value slot + ASM_MOV_REG_IMM(emit->as, REG_TEMP0, MP_VM_RETURN_YIELD); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_RET_VAL(emit), REG_TEMP0); + + // Save re-entry PC + ASM_MOV_REG_PCREL(emit->as, REG_TEMP0, *emit->label_slot); + emit_native_mov_state_reg(emit, LOCAL_IDX_GEN_PC(emit), REG_TEMP0); + + // Jump to exit handler + ASM_JUMP(emit->as, emit->exit_label); + + // Label re-entry point + mp_asm_base_label_assign(&emit->as->base, *emit->label_slot); + + // Re-open any active exception handler + if (emit->exc_stack_size > 0) { + // Find innermost active exception handler, to restore as current handler + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1]; + for (; e >= emit->exc_stack; --e) { + if (e->is_active) { + // Found active handler, get its PC + ASM_MOV_REG_PCREL(emit->as, REG_RET, e->label); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_RET); + } + } + } + + emit_native_adjust_stack_size(emit, 1); // send_value + + if (kind == MP_EMIT_YIELD_VALUE) { + // Check LOCAL_IDX_EXC_VAL for any injected value + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); + emit_call(emit, MP_F_NATIVE_RAISE); + } else { + // Label loop entry + emit_native_label_assign(emit, *emit->label_slot + 2); + + // Get the next item from the delegate generator + vtype_kind_t vtype; + emit_pre_pop_reg(emit, &vtype, REG_ARG_2); // send_value + emit_access_stack(emit, 1, &vtype, REG_ARG_1); // generator + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_3, LOCAL_IDX_EXC_VAL(emit)); // throw_value + emit_post_push_reg(emit, VTYPE_PYOBJ, REG_ARG_3); + emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_3, 1); // ret_value + emit_call(emit, MP_F_NATIVE_YIELD_FROM); + + // If returned non-zero then generator continues + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, *emit->label_slot + 1, true); + + // Pop exhausted gen, replace with ret_value + emit_native_adjust_stack_size(emit, 1); // ret_value + emit_fold_stack_top(emit, REG_ARG_1); + } } STATIC void emit_native_start_except_handler(emit_t *emit) { - // This instruction follows an nlr_pop, so the stack counter is back to zero, when really - // it should be up by a whole nlr_buf_t. We then want to pop the nlr_buf_t here, but save - // the first 2 elements, so we can get the thrown value. - adjust_stack(emit, 1); - vtype_kind_t vtype_nlr; - emit_pre_pop_reg(emit, &vtype_nlr, REG_ARG_1); // get the thrown value - emit_pre_pop_discard(emit); // discard the linked-list pointer in the nlr_buf - emit_post_push_reg_reg_reg(emit, VTYPE_PYOBJ, REG_ARG_1, VTYPE_PYOBJ, REG_ARG_1, VTYPE_PYOBJ, REG_ARG_1); // push the 3 exception items + // Protected block has finished so leave the current exception handler + emit_native_leave_exc_stack(emit, true); + + // Get and push nlr_buf.ret_val + ASM_MOV_REG_LOCAL(emit->as, REG_TEMP0, LOCAL_IDX_EXC_VAL(emit)); + emit_post_push_reg(emit, VTYPE_PYOBJ, REG_TEMP0); } STATIC void emit_native_end_except_handler(emit_t *emit) { - adjust_stack(emit, -1); + adjust_stack(emit, -1); // pop the exception (end_finally didn't use it) } const emit_method_table_t EXPORT_FUN(method_table) = { - emit_native_set_native_type, emit_native_start_pass, emit_native_end_pass, emit_native_last_emit_was_return_value, diff --git a/py/emitnthumb.c b/py/emitnthumb.c index 2b68ca3a13..1c33e7a68b 100644 --- a/py/emitnthumb.c +++ b/py/emitnthumb.c @@ -8,6 +8,11 @@ #define GENERIC_ASM_API (1) #include "py/asmthumb.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (3) // r4 +#define NLR_BUF_IDX_LOCAL_2 (4) // r5 +#define NLR_BUF_IDX_LOCAL_3 (5) // r6 + #define N_THUMB (1) #define EXPORT_FUN(name) emit_native_thumb_##name #include "py/emitnative.c" diff --git a/py/emitnx64.c b/py/emitnx64.c index b9800f636e..4abb3ecad3 100644 --- a/py/emitnx64.c +++ b/py/emitnx64.c @@ -8,6 +8,11 @@ #define GENERIC_ASM_API (1) #include "py/asmx64.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (5) // rbx +#define NLR_BUF_IDX_LOCAL_2 (6) // r12 +#define NLR_BUF_IDX_LOCAL_3 (7) // r13 + #define N_X64 (1) #define EXPORT_FUN(name) emit_native_x64_##name #include "py/emitnative.c" diff --git a/py/emitnx86.c b/py/emitnx86.c index 5d2bbb267a..7c96c3b82b 100644 --- a/py/emitnx86.c +++ b/py/emitnx86.c @@ -9,10 +9,16 @@ #define GENERIC_ASM_API (1) #include "py/asmx86.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (5) // ebx +#define NLR_BUF_IDX_LOCAL_2 (7) // esi +#define NLR_BUF_IDX_LOCAL_3 (6) // edi + // x86 needs a table to know how many args a given function has STATIC byte mp_f_n_args[MP_F_NUMBER_OF] = { [MP_F_CONVERT_OBJ_TO_NATIVE] = 2, [MP_F_CONVERT_NATIVE_TO_OBJ] = 2, + [MP_F_NATIVE_SWAP_GLOBALS] = 1, [MP_F_LOAD_NAME] = 1, [MP_F_LOAD_GLOBAL] = 1, [MP_F_LOAD_BUILD_CLASS] = 0, @@ -56,9 +62,11 @@ STATIC byte mp_f_n_args[MP_F_NUMBER_OF] = { [MP_F_DELETE_GLOBAL] = 1, [MP_F_NEW_CELL] = 1, [MP_F_MAKE_CLOSURE_FROM_RAW_CODE] = 3, - [MP_F_SETUP_CODE_STATE] = 5, + [MP_F_ARG_CHECK_NUM_SIG] = 3, + [MP_F_SETUP_CODE_STATE] = 4, [MP_F_SMALL_INT_FLOOR_DIVIDE] = 2, [MP_F_SMALL_INT_MODULO] = 2, + [MP_F_NATIVE_YIELD_FROM] = 3, }; #define N_X86 (1) diff --git a/py/emitnxtensa.c b/py/emitnxtensa.c index 1a423e21eb..34089e90dc 100644 --- a/py/emitnxtensa.c +++ b/py/emitnxtensa.c @@ -8,6 +8,11 @@ #define GENERIC_ASM_API (1) #include "py/asmxtensa.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (8) // a12 +#define NLR_BUF_IDX_LOCAL_2 (9) // a13 +#define NLR_BUF_IDX_LOCAL_3 (10) // a14 + #define N_XTENSA (1) #define EXPORT_FUN(name) emit_native_xtensa_##name #include "py/emitnative.c" diff --git a/py/gc.c b/py/gc.c index cb7e454193..c29624c3af 100644 --- a/py/gc.c +++ b/py/gc.c @@ -480,7 +480,8 @@ bool gc_alloc_possible(void) { // We place long lived objects at the end of the heap rather than the start. This reduces // fragmentation by localizing the heap churn to one portion of memory (the start of the heap.) -void *gc_alloc(size_t n_bytes, bool has_finaliser, bool long_lived) { +void *gc_alloc(size_t n_bytes, unsigned int alloc_flags, bool long_lived) { + bool has_finaliser = alloc_flags & GC_ALLOC_FLAG_HAS_FINALISER; size_t n_blocks = ((n_bytes + BYTES_PER_BLOCK - 1) & (~(BYTES_PER_BLOCK - 1))) / BYTES_PER_BLOCK; DEBUG_printf("gc_alloc(" UINT_FMT " bytes -> " UINT_FMT " blocks)\n", n_bytes, n_blocks); @@ -1153,7 +1154,8 @@ void gc_dump_alloc_table(void) { GC_EXIT(); } -#if DEBUG_PRINT +#if 0 +// For testing the GC functions void gc_test(void) { mp_uint_t len = 500; mp_uint_t *heap = malloc(len); diff --git a/py/gc.h b/py/gc.h index ddbaeb40a6..0cc432b94e 100644 --- a/py/gc.h +++ b/py/gc.h @@ -60,11 +60,15 @@ void gc_collect_end(void); // Is the gc heap available? bool gc_alloc_possible(void); -void *gc_alloc(size_t n_bytes, bool has_finaliser, bool long_lived); // Use this function to sweep the whole heap and run all finalisers void gc_sweep_all(void); +enum { + GC_ALLOC_FLAG_HAS_FINALISER = 1, +}; + +void *gc_alloc(size_t n_bytes, unsigned int alloc_flags, bool long_lived); void gc_free(void *ptr); // does not call finaliser size_t gc_nbytes(const void *ptr); bool gc_has_finaliser(const void *ptr); diff --git a/py/malloc.c b/py/malloc.c index e06d20e956..5c09a2d283 100644 --- a/py/malloc.c +++ b/py/malloc.c @@ -62,6 +62,13 @@ #define realloc(ptr, n) gc_realloc(ptr, n, true) #define realloc_ext(ptr, n, mv) gc_realloc(ptr, n, mv) #else + +// GC is disabled. Use system malloc/realloc/free. + +#if MICROPY_ENABLE_FINALISER +#error MICROPY_ENABLE_FINALISER requires MICROPY_ENABLE_GC +#endif + #define malloc_ll(b, ll) malloc(b) #define malloc_with_finaliser(b) malloc((b)) @@ -75,6 +82,7 @@ STATIC void *realloc_ext(void *ptr, size_t n_bytes, bool allow_move) { return NULL; } } + #endif // MICROPY_ENABLE_GC void *m_malloc(size_t num_bytes, bool long_lived) { diff --git a/py/map.c b/py/map.c index a37a3c984d..06695c8de8 100644 --- a/py/map.c +++ b/py/map.c @@ -425,13 +425,13 @@ void mp_set_clear(mp_set_t *set) { #if defined(DEBUG_PRINT) && DEBUG_PRINT void mp_map_dump(mp_map_t *map) { for (size_t i = 0; i < map->alloc; i++) { - if (map->table[i].key != NULL) { + if (map->table[i].key != MP_OBJ_NULL) { mp_obj_print(map->table[i].key, PRINT_REPR); } else { - printf("(nil)"); + DEBUG_printf("(nil)"); } - printf(": %p\n", map->table[i].value); + DEBUG_printf(": %p\n", map->table[i].value); } - printf("---\n"); + DEBUG_printf("---\n"); } #endif diff --git a/py/mkrules.mk b/py/mkrules.mk index 549b0e5e42..2721d293e0 100644 --- a/py/mkrules.mk +++ b/py/mkrules.mk @@ -107,7 +107,7 @@ endif ifneq ($(FROZEN_MPY_DIRS),) # to build the MicroPython cross compiler # Currently not used, because the wrong mpy-cross may be left over from a previous build. Build by hand to make sure. -$(MPY_CROSS): $(TOP)/py/*.[ch] $(TOP)/mpy-cross/*.[ch] $(TOP)/ports/windows/fmode.c +$(MPY_CROSS): $(TOP)/py/*.[ch] $(TOP)/mpy-cross/*.[ch] $(TOP)/mpy-cross/fmode.c $(Q)$(MAKE) -C $(TOP)/mpy-cross # Copy all the modules and single python files to freeze to a common area, omitting top-level dirs (the repo names). diff --git a/py/modbuiltins.c b/py/modbuiltins.c index ccf29cfe1c..49d88f728e 100644 --- a/py/modbuiltins.c +++ b/py/modbuiltins.c @@ -220,7 +220,12 @@ STATIC mp_obj_t mp_builtin_hash(mp_obj_t o_in) { MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_hash_obj, mp_builtin_hash); STATIC mp_obj_t mp_builtin_hex(mp_obj_t o_in) { + #if MICROPY_PY_BUILTINS_STR_OP_MODULO return mp_binary_op(MP_BINARY_OP_MODULO, MP_OBJ_NEW_QSTR(MP_QSTR__percent__hash_x), o_in); + #else + mp_obj_t args[] = { MP_OBJ_NEW_QSTR(MP_QSTR__brace_open__colon__hash_x_brace_close_), o_in }; + return mp_obj_str_format(MP_ARRAY_SIZE(args), args, NULL); + #endif } MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_hex_obj, mp_builtin_hex); @@ -325,7 +330,12 @@ STATIC mp_obj_t mp_builtin_next(mp_obj_t o) { MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_next_obj, mp_builtin_next); STATIC mp_obj_t mp_builtin_oct(mp_obj_t o_in) { + #if MICROPY_PY_BUILTINS_STR_OP_MODULO return mp_binary_op(MP_BINARY_OP_MODULO, MP_OBJ_NEW_QSTR(MP_QSTR__percent__hash_o), o_in); + #else + mp_obj_t args[] = { MP_OBJ_NEW_QSTR(MP_QSTR__brace_open__colon__hash_o_brace_close_), o_in }; + return mp_obj_str_format(MP_ARRAY_SIZE(args), args, NULL); + #endif } MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_oct_obj, mp_builtin_oct); diff --git a/py/modio.c b/py/modio.c index 01cb65af59..e88a9b04f3 100644 --- a/py/modio.c +++ b/py/modio.c @@ -44,7 +44,7 @@ extern const mp_obj_type_t mp_type_textio; STATIC const mp_obj_type_t mp_type_iobase; -STATIC mp_obj_base_t iobase_singleton = {&mp_type_iobase}; +STATIC const mp_obj_base_t iobase_singleton = {&mp_type_iobase}; STATIC mp_obj_t iobase_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { (void)type; diff --git a/py/modmath.c b/py/modmath.c index 2e271aed3d..9df345a564 100644 --- a/py/modmath.c +++ b/py/modmath.c @@ -238,6 +238,70 @@ STATIC mp_obj_t mp_math_degrees(mp_obj_t x_obj) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_degrees_obj, mp_math_degrees); +#if MICROPY_PY_MATH_FACTORIAL + +#if MICROPY_OPT_MATH_FACTORIAL + +// factorial(x): slightly efficient recursive implementation +STATIC mp_obj_t mp_math_factorial_inner(mp_uint_t start, mp_uint_t end) { + if (start == end) { + return mp_obj_new_int(start); + } else if (end - start == 1) { + return mp_binary_op(MP_BINARY_OP_MULTIPLY, MP_OBJ_NEW_SMALL_INT(start), MP_OBJ_NEW_SMALL_INT(end)); + } else if (end - start == 2) { + mp_obj_t left = MP_OBJ_NEW_SMALL_INT(start); + mp_obj_t middle = MP_OBJ_NEW_SMALL_INT(start + 1); + mp_obj_t right = MP_OBJ_NEW_SMALL_INT(end); + mp_obj_t tmp = mp_binary_op(MP_BINARY_OP_MULTIPLY, left, middle); + return mp_binary_op(MP_BINARY_OP_MULTIPLY, tmp, right); + } else { + mp_uint_t middle = start + ((end - start) >> 1); + mp_obj_t left = mp_math_factorial_inner(start, middle); + mp_obj_t right = mp_math_factorial_inner(middle + 1, end); + return mp_binary_op(MP_BINARY_OP_MULTIPLY, left, right); + } +} +STATIC mp_obj_t mp_math_factorial(mp_obj_t x_obj) { + mp_int_t max = mp_obj_get_int(x_obj); + if (max < 0) { + mp_raise_msg(&mp_type_ValueError, translate("negative factorial")); + } else if (max == 0) { + return MP_OBJ_NEW_SMALL_INT(1); + } + return mp_math_factorial_inner(1, max); +} + +#else + +// factorial(x): squared difference implementation +// based on http://www.luschny.de/math/factorial/index.html +STATIC mp_obj_t mp_math_factorial(mp_obj_t x_obj) { + mp_int_t max = mp_obj_get_int(x_obj); + if (max < 0) { + mp_raise_msg(&mp_type_ValueError, translate("negative factorial")); + } else if (max <= 1) { + return MP_OBJ_NEW_SMALL_INT(1); + } + mp_int_t h = max >> 1; + mp_int_t q = h * h; + mp_int_t r = q << 1; + if (max & 1) { + r *= max; + } + mp_obj_t prod = MP_OBJ_NEW_SMALL_INT(r); + for (mp_int_t num = 1; num < max - 2; num += 2) { + q -= num; + prod = mp_binary_op(MP_BINARY_OP_MULTIPLY, prod, MP_OBJ_NEW_SMALL_INT(q)); + } + return prod; +} + +#endif + +STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_factorial_obj, mp_math_factorial); + +#endif + STATIC const mp_rom_map_elem_t mp_module_math_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_math) }, { MP_ROM_QSTR(MP_QSTR_e), mp_const_float_e }, @@ -280,6 +344,9 @@ STATIC const mp_rom_map_elem_t mp_module_math_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_trunc), MP_ROM_PTR(&mp_math_trunc_obj) }, { MP_ROM_QSTR(MP_QSTR_radians), MP_ROM_PTR(&mp_math_radians_obj) }, { MP_ROM_QSTR(MP_QSTR_degrees), MP_ROM_PTR(&mp_math_degrees_obj) }, + #if MICROPY_PY_MATH_FACTORIAL + { MP_ROM_QSTR(MP_QSTR_factorial), MP_ROM_PTR(&mp_math_factorial_obj) }, + #endif #if MICROPY_PY_MATH_SPECIAL_FUNCTIONS { MP_ROM_QSTR(MP_QSTR_erf), MP_ROM_PTR(&mp_math_erf_obj) }, { MP_ROM_QSTR(MP_QSTR_erfc), MP_ROM_PTR(&mp_math_erfc_obj) }, diff --git a/py/mpconfig.h b/py/mpconfig.h index 043386d7c0..6badacaf6c 100644 --- a/py/mpconfig.h +++ b/py/mpconfig.h @@ -111,6 +111,15 @@ #define MICROPY_ALLOC_GC_STACK_SIZE (64) #endif +// The C-type to use for entries in the GC stack. By default it allows the +// heap to be as large as the address space, but the bit-width of this type can +// be reduced to save memory when the heap is small enough. The type must be +// big enough to index all blocks in the heap, which is set by +// heap-size-in-bytes / MICROPY_BYTES_PER_GC_BLOCK. +#ifndef MICROPY_GC_STACK_ENTRY_TYPE +#define MICROPY_GC_STACK_ENTRY_TYPE size_t +#endif + // Be conservative and always clear to zero newly (re)allocated memory in the GC. // This helps eliminate stray pointers that hold on to memory that's no longer // used. It decreases performance due to unnecessary memory clearing. @@ -390,6 +399,11 @@ #define MICROPY_MEM_STATS (0) #endif +// The mp_print_t printer used for debugging output +#ifndef MICROPY_DEBUG_PRINTER +#define MICROPY_DEBUG_PRINTER (&mp_plat_print) +#endif + // Whether to build functions that print debugging info: // mp_bytecode_print // mp_parse_node_print @@ -402,6 +416,11 @@ #define MICROPY_DEBUG_VERBOSE (0) #endif +// Whether to enable a simple VM stack overflow check +#ifndef MICROPY_DEBUG_VM_STACK_OVERFLOW +#define MICROPY_DEBUG_VM_STACK_OVERFLOW (0) +#endif + /*****************************************************************************/ /* Optimisations */ @@ -434,6 +453,12 @@ #define MICROPY_OPT_MPZ_BITWISE (0) #endif + +// Whether math.factorial is large, fast and recursive (1) or small and slow (0). +#ifndef MICROPY_OPT_MATH_FACTORIAL +#define MICROPY_OPT_MATH_FACTORIAL (0) +#endif + /*****************************************************************************/ /* Python internal features */ @@ -664,6 +689,11 @@ typedef double mp_float_t; #define MICROPY_MODULE_BUILTIN_INIT (0) #endif +// Whether to support module-level __getattr__ (see PEP 562) +#ifndef MICROPY_MODULE_GETATTR +#define MICROPY_MODULE_GETATTR (0) +#endif + // Whether module weak links are supported #ifndef MICROPY_MODULE_WEAK_LINKS #define MICROPY_MODULE_WEAK_LINKS (0) @@ -796,6 +826,16 @@ typedef double mp_float_t; #define MICROPY_PY_BUILTINS_STR_CENTER (0) #endif +// Whether str.count() method provided +#ifndef MICROPY_PY_BUILTINS_STR_COUNT +#define MICROPY_PY_BUILTINS_STR_COUNT (1) +#endif + +// Whether str % (...) formatting operator provided +#ifndef MICROPY_PY_BUILTINS_STR_OP_MODULO +#define MICROPY_PY_BUILTINS_STR_OP_MODULO (1) +#endif + // Whether str.partition()/str.rpartition() method provided #ifndef MICROPY_PY_BUILTINS_STR_PARTITION #define MICROPY_PY_BUILTINS_STR_PARTITION (0) @@ -811,6 +851,11 @@ typedef double mp_float_t; #define MICROPY_PY_BUILTINS_BYTEARRAY (1) #endif +// Whether to support dict.fromkeys() class method +#ifndef MICROPY_PY_BUILTINS_DICT_FROMKEYS +#define MICROPY_PY_BUILTINS_DICT_FROMKEYS (1) +#endif + // Whether to support memoryview object #ifndef MICROPY_PY_BUILTINS_MEMORYVIEW #define MICROPY_PY_BUILTINS_MEMORYVIEW (0) @@ -1026,6 +1071,11 @@ typedef double mp_float_t; #define MICROPY_PY_MATH_SPECIAL_FUNCTIONS (0) #endif +// Whether to provide math.factorial function +#ifndef MICROPY_PY_MATH_FACTORIAL +#define MICROPY_PY_MATH_FACTORIAL (0) +#endif + // Whether to provide "cmath" module #ifndef MICROPY_PY_CMATH #define MICROPY_PY_CMATH (0) @@ -1178,6 +1228,12 @@ typedef double mp_float_t; #define MICROPY_PY_UCTYPES (0) #endif +// Whether to provide SHORT, INT, LONG, etc. types in addition to +// exact-bitness types like INT16, INT32, etc. +#ifndef MICROPY_PY_UCTYPES_NATIVE_C_TYPES +#define MICROPY_PY_UCTYPES_NATIVE_C_TYPES (1) +#endif + #ifndef MICROPY_PY_UZLIB #define MICROPY_PY_UZLIB (0) #endif @@ -1219,6 +1275,10 @@ typedef double mp_float_t; #define MICROPY_PY_UHASHLIB (0) #endif +#ifndef MICROPY_PY_UHASHLIB_MD5 +#define MICROPY_PY_UHASHLIB_MD5 (0) +#endif + #ifndef MICROPY_PY_UHASHLIB_SHA1 #define MICROPY_PY_UHASHLIB_SHA1 (0) #endif @@ -1227,6 +1287,14 @@ typedef double mp_float_t; #define MICROPY_PY_UHASHLIB_SHA256 (1) #endif +#ifndef MICROPY_PY_UCRYPTOLIB +#define MICROPY_PY_UCRYPTOLIB (0) +#endif + +#ifndef MICROPY_PY_UCRYPTOLIB_CONSTS +#define MICROPY_PY_UCRYPTOLIB_CONSTS (0) +#endif + #ifndef MICROPY_PY_UBINASCII #define MICROPY_PY_UBINASCII (0) #endif diff --git a/py/mpstate.h b/py/mpstate.h index 1f6a2d00a1..0c57563acc 100644 --- a/py/mpstate.h +++ b/py/mpstate.h @@ -79,7 +79,7 @@ typedef struct _mp_state_mem_t { void *gc_lowest_long_lived_ptr; int gc_stack_overflow; - size_t gc_stack[MICROPY_ALLOC_GC_STACK_SIZE]; + MICROPY_GC_STACK_ENTRY_TYPE gc_stack[MICROPY_ALLOC_GC_STACK_SIZE]; uint16_t gc_lock_depth; // This variable controls auto garbage collection. If set to false then the diff --git a/py/nativeglue.c b/py/nativeglue.c index 05e257ab02..7662aaeaf6 100644 --- a/py/nativeglue.c +++ b/py/nativeglue.c @@ -89,6 +89,20 @@ mp_obj_t mp_convert_native_to_obj(mp_uint_t val, mp_uint_t type) { #if MICROPY_EMIT_NATIVE +mp_obj_dict_t *mp_native_swap_globals(mp_obj_dict_t *new_globals) { + if (new_globals == NULL) { + // Globals were the originally the same so don't restore them + return NULL; + } + mp_obj_dict_t *old_globals = mp_globals_get(); + if (old_globals == new_globals) { + // Don't set globals if they are the same, and return NULL to indicate this + return NULL; + } + mp_globals_set(new_globals); + return old_globals; +} + // wrapper that accepts n_args and n_kw in one argument // (native emitter can only pass at most 3 arguments to a function) mp_obj_t mp_native_call_function_n_kw(mp_obj_t fun_in, size_t n_args_kw, const mp_obj_t *args) { @@ -98,7 +112,7 @@ mp_obj_t mp_native_call_function_n_kw(mp_obj_t fun_in, size_t n_args_kw, const m // wrapper that makes raise obj and raises it // END_FINALLY opcode requires that we don't raise if o==None void mp_native_raise(mp_obj_t o) { - if (o != mp_const_none) { + if (o != MP_OBJ_NULL && o != mp_const_none) { nlr_raise(mp_make_raise_obj(o)); } } @@ -129,10 +143,50 @@ STATIC mp_obj_t mp_native_iternext(mp_obj_iter_buf_t *iter) { return mp_iternext(obj); } +STATIC bool mp_native_yield_from(mp_obj_t gen, mp_obj_t send_value, mp_obj_t *ret_value) { + mp_vm_return_kind_t ret_kind; + nlr_buf_t nlr_buf; + mp_obj_t throw_value = *ret_value; + if (nlr_push(&nlr_buf) == 0) { + if (throw_value != MP_OBJ_NULL) { + send_value = MP_OBJ_NULL; + } + ret_kind = mp_resume(gen, send_value, throw_value, ret_value); + nlr_pop(); + } else { + ret_kind = MP_VM_RETURN_EXCEPTION; + *ret_value = nlr_buf.ret_val; + } + + if (ret_kind == MP_VM_RETURN_YIELD) { + return true; + } else if (ret_kind == MP_VM_RETURN_NORMAL) { + if (*ret_value == MP_OBJ_STOP_ITERATION) { + *ret_value = mp_const_none; + } + } else { + assert(ret_kind == MP_VM_RETURN_EXCEPTION); + if (!mp_obj_exception_match(*ret_value, MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { + nlr_raise(*ret_value); + } + *ret_value = mp_obj_exception_get_value(*ret_value); + } + + if (throw_value != MP_OBJ_NULL && mp_obj_exception_match(throw_value, MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { + nlr_raise(mp_make_raise_obj(throw_value)); + } + + return false; +} + // these must correspond to the respective enum in runtime0.h -void *const mp_fun_table[MP_F_NUMBER_OF] = { +const void *const mp_fun_table[MP_F_NUMBER_OF] = { + &mp_const_none_obj, + &mp_const_false_obj, + &mp_const_true_obj, mp_convert_obj_to_native, mp_convert_native_to_obj, + mp_native_swap_globals, mp_load_name, mp_load_global, mp_load_build_class, @@ -176,9 +230,11 @@ void *const mp_fun_table[MP_F_NUMBER_OF] = { mp_delete_global, mp_obj_new_cell, mp_make_closure_from_raw_code, + mp_arg_check_num_sig, mp_setup_code_state, mp_small_int_floor_divide, mp_small_int_modulo, + mp_native_yield_from, }; /* diff --git a/py/obj.c b/py/obj.c index b271362536..6b2dded57e 100644 --- a/py/obj.c +++ b/py/obj.c @@ -269,12 +269,8 @@ mp_int_t mp_obj_get_int(mp_const_obj_t arg) { } else if (MP_OBJ_IS_TYPE(arg, &mp_type_int)) { return mp_obj_int_get_checked(arg); } else { - #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError_varg(translate("can't convert to %q"), MP_QSTR_int); - #else - mp_raise_TypeError_varg( - translate("can't convert %q to %q"), mp_obj_get_type_qstr(arg), MP_QSTR_int); - #endif + mp_obj_t res = mp_unary_op(MP_UNARY_OP_INT, (mp_obj_t)arg); + return mp_obj_int_get_checked(res); } } diff --git a/py/obj.h b/py/obj.h index fcea402c63..4e32ce8b0e 100644 --- a/py/obj.h +++ b/py/obj.h @@ -149,6 +149,7 @@ static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) { #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)(o)) >> 1) #define MP_OBJ_NEW_SMALL_INT(small_int) ((mp_obj_t)((((mp_uint_t)(small_int)) << 1) | 1)) +#if MICROPY_PY_BUILTINS_FLOAT #define mp_const_float_e MP_ROM_PTR((mp_obj_t)(((0x402df854 & ~3) | 2) + 0x80800000)) #define mp_const_float_pi MP_ROM_PTR((mp_obj_t)(((0x40490fdb & ~3) | 2) + 0x80800000)) @@ -169,6 +170,7 @@ static inline mp_obj_t mp_obj_new_float(mp_float_t f) { } num = {.f = f}; return (mp_obj_t)(((num.u & ~0x3) | 2) + 0x80800000); } +#endif static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) { return (((mp_uint_t)(o)) & 0xff800007) == 0x00000006; @@ -183,18 +185,23 @@ static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) { #elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) { - return (((mp_int_t)(o)) & 0xffff000000000000) == 0x0001000000000000; + return (((uint64_t)(o)) & 0xffff000000000000) == 0x0001000000000000; } #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)((o) << 16)) >> 17) #define MP_OBJ_NEW_SMALL_INT(small_int) (((((uint64_t)(small_int)) & 0x7fffffffffff) << 1) | 0x0001000000000001) static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) { - return (((mp_int_t)(o)) & 0xffff000000000000) == 0x0002000000000000; + return (((uint64_t)(o)) & 0xffff000000000000) == 0x0002000000000000; } #define MP_OBJ_QSTR_VALUE(o) ((((uint32_t)(o)) >> 1) & 0xffffffff) #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 1) | 0x0002000000000001)) #if MICROPY_PY_BUILTINS_FLOAT + +#if MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_DOUBLE +#error MICROPY_OBJ_REPR_D requires MICROPY_FLOAT_IMPL_DOUBLE +#endif + #define mp_const_float_e {((mp_obj_t)((uint64_t)0x4005bf0a8b145769 + 0x8004000000000000))} #define mp_const_float_pi {((mp_obj_t)((uint64_t)0x400921fb54442d18 + 0x8004000000000000))} @@ -290,6 +297,9 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; #define MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(obj_name) extern const mp_obj_fun_builtin_var_t obj_name #define MP_DECLARE_CONST_FUN_OBJ_KW(obj_name) extern const mp_obj_fun_builtin_var_t obj_name +#define MP_OBJ_FUN_ARGS_MAX (0xffff) // to set maximum value in n_args_max below +#define MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, takes_kw) ((uint32_t)((((uint32_t)(n_args_min)) << 17) | (((uint32_t)(n_args_max)) << 1) | ((takes_kw) ? 1 : 0))) + #define MP_DEFINE_CONST_FUN_OBJ_0(obj_name, fun_name) \ const mp_obj_fun_builtin_fixed_t obj_name = \ {{&mp_type_fun_builtin_0}, .fun._0 = fun_name} @@ -304,13 +314,14 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; {{&mp_type_fun_builtin_3}, .fun._3 = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_VAR(obj_name, n_args_min, fun_name) \ const mp_obj_fun_builtin_var_t obj_name = \ - {{&mp_type_fun_builtin_var}, false, n_args_min, MP_OBJ_FUN_ARGS_MAX, .fun.var = fun_name} + {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, false), .fun.var = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(obj_name, n_args_min, n_args_max, fun_name) \ const mp_obj_fun_builtin_var_t obj_name = \ - {{&mp_type_fun_builtin_var}, false, n_args_min, n_args_max, .fun.var = fun_name} + {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, false), .fun.var = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_KW(obj_name, n_args_min, fun_name) \ const mp_obj_fun_builtin_var_t obj_name = \ - {{&mp_type_fun_builtin_var}, true, n_args_min, MP_OBJ_FUN_ARGS_MAX, .fun.kw = fun_name} + {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, true), .fun.kw = fun_name} + #define MP_DEFINE_CONST_PROP_GET(obj_name, fun_name) \ const mp_obj_fun_builtin_fixed_t fun_name##_obj = {{&mp_type_fun_builtin_1}, .fun._1 = fun_name}; \ const mp_obj_property_t obj_name = { \ @@ -610,6 +621,8 @@ extern const mp_obj_type_t mp_type_slice; extern const mp_obj_type_t mp_type_zip; extern const mp_obj_type_t mp_type_array; extern const mp_obj_type_t mp_type_super; +extern const mp_obj_type_t mp_type_gen_wrap; +extern const mp_obj_type_t mp_type_native_gen_wrap; extern const mp_obj_type_t mp_type_gen_instance; extern const mp_obj_type_t mp_type_fun_builtin_0; extern const mp_obj_type_t mp_type_fun_builtin_1; @@ -617,6 +630,9 @@ extern const mp_obj_type_t mp_type_fun_builtin_2; extern const mp_obj_type_t mp_type_fun_builtin_3; extern const mp_obj_type_t mp_type_fun_builtin_var; extern const mp_obj_type_t mp_type_fun_bc; +#if MICROPY_EMIT_NATIVE +extern const mp_obj_type_t mp_type_fun_native; +#endif extern const mp_obj_type_t mp_type_module; extern const mp_obj_type_t mp_type_staticmethod; extern const mp_obj_type_t mp_type_classmethod; @@ -841,7 +857,9 @@ size_t mp_obj_dict_len(mp_obj_t self_in); mp_obj_t mp_obj_dict_get(mp_obj_t self_in, mp_obj_t index); mp_obj_t mp_obj_dict_store(mp_obj_t self_in, mp_obj_t key, mp_obj_t value); mp_obj_t mp_obj_dict_delete(mp_obj_t self_in, mp_obj_t key); -mp_map_t *mp_obj_dict_get_map(mp_obj_t self_in); +static inline mp_map_t *mp_obj_dict_get_map(mp_obj_t dict) { + return &((mp_obj_dict_t *)MP_OBJ_TO_PTR(dict))->map; +} // set void mp_obj_set_store(mp_obj_t self_in, mp_obj_t item); @@ -861,12 +879,9 @@ typedef struct _mp_obj_fun_builtin_fixed_t { } fun; } mp_obj_fun_builtin_fixed_t; -#define MP_OBJ_FUN_ARGS_MAX (0xffff) // to set maximum value in n_args_max below typedef struct _mp_obj_fun_builtin_var_t { mp_obj_base_t base; - bool is_kw : 1; - mp_uint_t n_args_min : 15; // inclusive - mp_uint_t n_args_max : 16; // inclusive + uint32_t sig; // see MP_OBJ_FUN_MAKE_SIG union { mp_fun_var_t var; mp_fun_kw_t kw; diff --git a/py/objarray.c b/py/objarray.c index e6024f720c..7864d79867 100644 --- a/py/objarray.c +++ b/py/objarray.c @@ -52,11 +52,14 @@ // Note that we don't handle the case where the original buffer might change // size due to a resize of the original parent object. -// make (& TYPECODE_MASK) a null operation if memorview not enabled #if MICROPY_PY_BUILTINS_MEMORYVIEW #define TYPECODE_MASK (0x7f) +#define memview_offset free #else +// make (& TYPECODE_MASK) a null operation if memorview not enabled #define TYPECODE_MASK (~(size_t)0) +// memview_offset should not be accessed if memoryview is not enabled, +// so not defined to catch errors #endif STATIC mp_obj_t array_iterator_new(mp_obj_t array_in, mp_obj_iter_buf_t *iter_buf); @@ -186,7 +189,7 @@ STATIC mp_obj_t array_make_new(const mp_obj_type_t *type_in, size_t n_args, cons #if MICROPY_PY_BUILTINS_BYTEARRAY STATIC mp_obj_t bytearray_make_new(const mp_obj_type_t *type_in, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { (void)type_in; - mp_arg_check_num(n_args, kw_args, 0, 1, false); + mp_arg_check_num(n_args, kw_args, 0, 3, false); if (n_args == 0) { // no args: construct an empty bytearray @@ -210,7 +213,7 @@ mp_obj_t mp_obj_new_memoryview(byte typecode, size_t nitems, void *items) { mp_obj_array_t *self = m_new_obj(mp_obj_array_t); self->base.type = &mp_type_memoryview; self->typecode = typecode; - self->free = 0; + self->memview_offset = 0; self->len = nitems; self->items = items; return MP_OBJ_FROM_PTR(self); @@ -338,10 +341,10 @@ STATIC mp_obj_t array_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs } case MP_BINARY_OP_CONTAINS: { + #if MICROPY_PY_BUILTINS_BYTEARRAY + // Can search string only in bytearray mp_buffer_info_t lhs_bufinfo; mp_buffer_info_t rhs_bufinfo; - - // Can search string only in bytearray if (mp_get_buffer(rhs_in, &rhs_bufinfo, MP_BUFFER_READ)) { if (!MP_OBJ_IS_TYPE(lhs_in, &mp_type_bytearray)) { return mp_const_false; @@ -350,6 +353,7 @@ STATIC mp_obj_t array_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs return mp_obj_new_bool( find_subbytes(lhs_bufinfo.buf, lhs_bufinfo.len, rhs_bufinfo.buf, rhs_bufinfo.len, 1) != NULL); } + #endif // Otherwise, can only look for a scalar numeric value in an array if (MP_OBJ_IS_INT(rhs_in) || mp_obj_is_float(rhs_in)) { @@ -522,7 +526,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value src_items = src_slice->items; #if MICROPY_PY_BUILTINS_MEMORYVIEW if (MP_OBJ_IS_TYPE(value, &mp_type_memoryview)) { - src_items = (uint8_t *)src_items + (src_slice->free * item_sz); + src_items = (uint8_t *)src_items + (src_slice->memview_offset * item_sz); } #endif } else if (MP_OBJ_IS_TYPE(value, &mp_type_bytes)) { @@ -549,7 +553,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value if (len_adj != 0) { goto compat_error; } - dest_items += o->free * item_sz; + dest_items += o->memview_offset * item_sz; } #endif if (len_adj > 0) { @@ -587,7 +591,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value } else if (o->base.type == &mp_type_memoryview) { res = m_new_obj(mp_obj_array_t); *res = *o; - res->free += slice.start; + res->memview_offset += slice.start; res->len = slice.stop - slice.start; #endif } else { @@ -600,7 +604,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value size_t index = mp_get_index(o->base.type, o->len, index_in, false); #if MICROPY_PY_BUILTINS_MEMORYVIEW if (o->base.type == &mp_type_memoryview) { - index += o->free; + index += o->memview_offset; if (value != MP_OBJ_SENTINEL && !(o->typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW)) { // store to read-only memoryview return MP_OBJ_NULL; @@ -631,7 +635,7 @@ STATIC mp_int_t array_get_buffer(mp_obj_t o_in, mp_buffer_info_t *bufinfo, mp_ui // read-only memoryview return 1; } - bufinfo->buf = (uint8_t *)bufinfo->buf + (size_t)o->free * sz; + bufinfo->buf = (uint8_t *)bufinfo->buf + (size_t)o->memview_offset * sz; } #else (void)flags; @@ -806,7 +810,7 @@ STATIC mp_obj_t array_iterator_new(mp_obj_t array_in, mp_obj_iter_buf_t *iter_bu o->cur = 0; #if MICROPY_PY_BUILTINS_MEMORYVIEW if (array->base.type == &mp_type_memoryview) { - o->offset = array->free; + o->offset = array->memview_offset; } #endif return MP_OBJ_FROM_PTR(o); diff --git a/py/objarray.h b/py/objarray.h index 7ad5328f0e..062de8b577 100644 --- a/py/objarray.h +++ b/py/objarray.h @@ -32,11 +32,18 @@ // Used only for memoryview types, set in "typecode" to indicate a writable memoryview #define MP_OBJ_ARRAY_TYPECODE_FLAG_RW (0x80) +// This structure is used for all of bytearray, array.array, memoryview +// objects. Note that memoryview has different meaning for some fields, +// see comment at the beginning of objarray.c. typedef struct _mp_obj_array_t { mp_obj_base_t base; size_t typecode : 8; // free is number of unused elements after len used elements // alloc size = len + free + // But for memoryview, 'free' is reused as offset (in elements) into the + // parent object. (Union is not used to not go into a complication of + // union-of-bitfields with different toolchains). See comments in + // objarray.c. size_t free : (8 * sizeof(size_t) - 8); size_t len; // in elements void *items; diff --git a/py/objboundmeth.c b/py/objboundmeth.c index cdb7257973..995e058735 100644 --- a/py/objboundmeth.c +++ b/py/objboundmeth.c @@ -89,13 +89,9 @@ STATIC void bound_meth_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { // not load attribute return; } - if (attr == MP_QSTR___name__) { - mp_obj_bound_meth_t *o = MP_OBJ_TO_PTR(self_in); - dest[0] = MP_OBJ_NEW_QSTR(mp_obj_fun_get_name(o->meth)); - } else if (attr == MP_QSTR___func__) { - mp_obj_bound_meth_t *o = MP_OBJ_TO_PTR(self_in); - dest[0] = o->meth; - } + // Delegate the load to the method object + mp_obj_bound_meth_t *self = MP_OBJ_TO_PTR(self_in); + mp_load_method_maybe(self->meth, attr, dest); } #endif diff --git a/py/objdict.c b/py/objdict.c index 24484566f3..4394af9edb 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -167,7 +167,7 @@ STATIC mp_obj_t dict_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_ } } -// TODO: Make sure this is inlined in dict_subscr() below. +// Note: Make sure this is inlined in load part of dict_subscr() below. mp_obj_t mp_obj_dict_get(mp_obj_t self_in, mp_obj_t index) { mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in); mp_map_elem_t *elem = mp_map_lookup(&self->map, index, MP_MAP_LOOKUP); @@ -234,6 +234,7 @@ STATIC mp_obj_t dict_copy(mp_obj_t self_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(dict_copy_obj, dict_copy); +#if MICROPY_PY_BUILTINS_DICT_FROMKEYS // this is a classmethod STATIC mp_obj_t dict_fromkeys(size_t n_args, const mp_obj_t *args) { mp_obj_t iter = mp_getiter(args[1], NULL); @@ -263,6 +264,7 @@ STATIC mp_obj_t dict_fromkeys(size_t n_args, const mp_obj_t *args) { } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_fromkeys_fun_obj, 2, 3, dict_fromkeys); STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(dict_fromkeys_obj, MP_ROM_PTR(&dict_fromkeys_fun_obj)); +#endif STATIC mp_obj_t dict_get_helper(size_t n_args, const mp_obj_t *args, mp_map_lookup_kind_t lookup_kind) { mp_check_self(MP_OBJ_IS_DICT_TYPE(args[0])); @@ -535,7 +537,9 @@ STATIC mp_obj_t dict_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) { STATIC const mp_rom_map_elem_t dict_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_clear), MP_ROM_PTR(&dict_clear_obj) }, { MP_ROM_QSTR(MP_QSTR_copy), MP_ROM_PTR(&dict_copy_obj) }, + #if MICROPY_PY_BUILTINS_DICT_FROMKEYS { MP_ROM_QSTR(MP_QSTR_fromkeys), MP_ROM_PTR(&dict_fromkeys_obj) }, + #endif { MP_ROM_QSTR(MP_QSTR_get), MP_ROM_PTR(&dict_get_obj) }, { MP_ROM_QSTR(MP_QSTR_items), MP_ROM_PTR(&dict_items_obj) }, { MP_ROM_QSTR(MP_QSTR_keys), MP_ROM_PTR(&dict_keys_obj) }, @@ -607,9 +611,3 @@ mp_obj_t mp_obj_dict_delete(mp_obj_t self_in, mp_obj_t key) { dict_get_helper(2, args, MP_MAP_LOOKUP_REMOVE_IF_FOUND); return self_in; } - -mp_map_t *mp_obj_dict_get_map(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_DICT_TYPE(self_in)); - mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in); - return &self->map; -} diff --git a/py/objexcept.c b/py/objexcept.c index fb6424fa48..2ea1dc7c79 100644 --- a/py/objexcept.c +++ b/py/objexcept.c @@ -43,12 +43,23 @@ // Number of items per traceback entry (file, line, block) #define TRACEBACK_ENTRY_LEN (3) -// Number of traceback entries to reserve in the emergency exception buffer -#define EMG_TRACEBACK_ALLOC (2 * TRACEBACK_ENTRY_LEN) - -// Optionally allocated buffer for storing the first argument of an exception -// allocated when the heap is locked. +// Optionally allocated buffer for storing some traceback, the tuple argument, +// and possible string object and data, for when the heap is locked. #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF + +// When used the layout of the emergency exception buffer is: +// - traceback entry (file, line, block) +// - traceback entry (file, line, block) +// - mp_obj_tuple_t object +// - n_args * mp_obj_t for tuple +// - mp_obj_str_t object +// - string data +#define EMG_BUF_TRACEBACK_OFFSET (0) +#define EMG_BUF_TRACEBACK_SIZE (2 * TRACEBACK_ENTRY_LEN * sizeof(size_t)) +#define EMG_BUF_TUPLE_OFFSET (EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE) +#define EMG_BUF_TUPLE_SIZE(n_args) (sizeof(mp_obj_tuple_t) + n_args * sizeof(mp_obj_t)) +#define EMG_BUF_STR_OFFSET (EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(1)) + #if MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE > 0 #define mp_emergency_exception_buf_size MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE @@ -162,9 +173,9 @@ mp_obj_t mp_obj_exception_make_new(const mp_obj_type_t *type, size_t n_args, con // reserved room (after the traceback data) for a tuple with 1 element. // Otherwise we are free to use the whole buffer after the traceback data. if (o_tuple == NULL && mp_emergency_exception_buf_size >= - EMG_TRACEBACK_ALLOC * sizeof(size_t) + sizeof(mp_obj_tuple_t) + n_args * sizeof(mp_obj_t)) { + EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(n_args)) { o_tuple = (mp_obj_tuple_t *) - ((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + EMG_TRACEBACK_ALLOC * sizeof(size_t)); + ((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + EMG_BUF_TUPLE_OFFSET); } #endif @@ -414,11 +425,10 @@ mp_obj_t mp_obj_new_exception_msg_vlist(const mp_obj_type_t *exc_type, const com // that buffer to store the string object and its data (at least 16 bytes for // the string data), reserving room at the start for the traceback and 1-tuple. if ((o_str == NULL || o_str_buf == NULL) - && mp_emergency_exception_buf_size >= EMG_TRACEBACK_ALLOC * sizeof(size_t) - + sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t) + sizeof(mp_obj_str_t) + 16) { + && mp_emergency_exception_buf_size >= EMG_BUF_STR_OFFSET + sizeof(mp_obj_str_t) + 16) { used_emg_buf = true; o_str = (mp_obj_str_t *)((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) - + EMG_TRACEBACK_ALLOC * sizeof(size_t) + sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t)); + + EMG_BUF_STR_OFFSET); o_str_buf = (byte *)&o_str[1]; o_str_alloc = (uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + mp_emergency_exception_buf_size - o_str_buf; @@ -510,11 +520,12 @@ void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qs self->traceback_data = m_new_maybe(size_t, TRACEBACK_ENTRY_LEN); if (self->traceback_data == NULL) { #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF - if (mp_emergency_exception_buf_size >= EMG_TRACEBACK_ALLOC * sizeof(size_t)) { + if (mp_emergency_exception_buf_size >= EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE) { // There is room in the emergency buffer for traceback data - size_t *tb = (size_t *)MP_STATE_VM(mp_emergency_exception_buf); + size_t *tb = (size_t *)((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + + EMG_BUF_TRACEBACK_OFFSET); self->traceback_data = tb; - self->traceback_alloc = EMG_TRACEBACK_ALLOC; + self->traceback_alloc = EMG_BUF_TRACEBACK_SIZE / sizeof(size_t); } else { // Can't allocate and no room in emergency buffer return; diff --git a/py/objfloat.c b/py/objfloat.c index 5c0a87ea3d..3bdfa0b757 100644 --- a/py/objfloat.c +++ b/py/objfloat.c @@ -172,8 +172,7 @@ STATIC mp_obj_t float_unary_op(mp_unary_op_t op, mp_obj_t o_in) { case MP_UNARY_OP_NEGATIVE: return mp_obj_new_float(-val); case MP_UNARY_OP_ABS: { - // TODO check for NaN etc - if (val < 0) { + if (signbit(val)) { return mp_obj_new_float(-val); } else { return o_in; diff --git a/py/objfun.c b/py/objfun.c index 69045c6323..5e4792a7dd 100644 --- a/py/objfun.c +++ b/py/objfun.c @@ -112,9 +112,9 @@ STATIC mp_obj_t fun_builtin_var_call(mp_obj_t self_in, size_t n_args, size_t n_k mp_obj_fun_builtin_var_t *self = MP_OBJ_TO_PTR(self_in); // check number of arguments - mp_arg_check_num_kw_array(n_args, n_kw, self->n_args_min, self->n_args_max, self->is_kw); + mp_arg_check_num_sig(n_args, n_kw, self->sig); - if (self->is_kw) { + if (self->sig & 1) { // function allows keywords // we create a map directly from the given args array @@ -149,10 +149,6 @@ qstr mp_obj_code_get_name(const byte *code_info) { #endif } -#if MICROPY_EMIT_NATIVE -STATIC const mp_obj_type_t mp_type_fun_native; -#endif - qstr mp_obj_fun_get_name(mp_const_obj_t fun_in) { const mp_obj_fun_bc_t *fun = MP_OBJ_TO_PTR(fun_in); #if MICROPY_EMIT_NATIVE @@ -197,17 +193,12 @@ STATIC void dump_args(const mp_obj_t *a, size_t sz) { // than this will try to use the heap, with fallback to stack allocation. #define VM_MAX_STATE_ON_STACK (11 * sizeof(mp_uint_t)) -// Set this to 1 to enable a simple stack overflow check. -#define VM_DETECT_STACK_OVERFLOW (0) - #define DECODE_CODESTATE_SIZE(bytecode, n_state_out_var, state_size_out_var) \ { \ /* bytecode prelude: state size and exception stack size */ \ n_state_out_var = mp_decode_uint_value(bytecode); \ size_t n_exc_stack = mp_decode_uint_value(mp_decode_uint_skip(bytecode)); \ \ - n_state_out_var += VM_DETECT_STACK_OVERFLOW; \ - \ /* state size in bytes */ \ state_size_out_var = n_state_out_var * sizeof(mp_obj_t) \ + n_exc_stack * sizeof(mp_exc_stack_t); \ @@ -259,8 +250,8 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size dump_args(args, n_args); DEBUG_printf("Input kw args: "); dump_args(args + n_args, n_kw * 2); + mp_obj_fun_bc_t *self = MP_OBJ_TO_PTR(self_in); - DEBUG_printf("Func n_def_args: %d\n", self->n_def_args); size_t n_state, state_size; DECODE_CODESTATE_SIZE(self->bytecode, n_state, state_size); @@ -272,9 +263,17 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size #else if (state_size > VM_MAX_STATE_ON_STACK) { code_state = m_new_obj_var_maybe(mp_code_state_t, byte, state_size); + #if MICROPY_DEBUG_VM_STACK_OVERFLOW + if (code_state != NULL) { + memset(code_state->state, 0, state_size); + } + #endif } if (code_state == NULL) { code_state = alloca(sizeof(mp_code_state_t) + state_size); + #if MICROPY_DEBUG_VM_STACK_OVERFLOW + memset(code_state->state, 0, state_size); + #endif state_size = 0; // indicate that we allocated using alloca } #endif @@ -286,27 +285,30 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size mp_vm_return_kind_t vm_return_kind = mp_execute_bytecode(code_state, MP_OBJ_NULL); mp_globals_set(code_state->old_globals); - #if VM_DETECT_STACK_OVERFLOW + #if MICROPY_DEBUG_VM_STACK_OVERFLOW if (vm_return_kind == MP_VM_RETURN_NORMAL) { if (code_state->sp < code_state->state) { - printf("VM stack underflow: " INT_FMT "\n", code_state->sp - code_state->state); + mp_printf(MICROPY_DEBUG_PRINTER, "VM stack underflow: " INT_FMT "\n", code_state->sp - code_state->state); assert(0); } } - // We can't check the case when an exception is returned in state[n_state - 1] + const byte *bytecode_ptr = mp_decode_uint_skip(mp_decode_uint_skip(self->bytecode)); + size_t n_pos_args = bytecode_ptr[1]; + size_t n_kwonly_args = bytecode_ptr[2]; + // We can't check the case when an exception is returned in state[0] // and there are no arguments, because in this case our detection slot may have // been overwritten by the returned exception (which is allowed). - if (!(vm_return_kind == MP_VM_RETURN_EXCEPTION && self->n_pos_args + self->n_kwonly_args == 0)) { + if (!(vm_return_kind == MP_VM_RETURN_EXCEPTION && n_pos_args + n_kwonly_args == 0)) { // Just check to see that we have at least 1 null object left in the state. bool overflow = true; - for (size_t i = 0; i < n_state - self->n_pos_args - self->n_kwonly_args; i++) { + for (size_t i = 0; i < n_state - n_pos_args - n_kwonly_args; ++i) { if (code_state->state[i] == MP_OBJ_NULL) { overflow = false; break; } } if (overflow) { - printf("VM stack overflow state=%p n_state+1=" UINT_FMT "\n", code_state->state, n_state); + mp_printf(MICROPY_DEBUG_PRINTER, "VM stack overflow state=%p n_state+1=" UINT_FMT "\n", code_state->state, n_state); assert(0); } } @@ -319,8 +321,8 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size } else { // must be an exception because normal functions can't yield assert(vm_return_kind == MP_VM_RETURN_EXCEPTION); - // return value is in fastn[0]==state[n_state - 1] - result = code_state->state[n_state - 1]; + // returned exception is in state[0] + result = code_state->state[0]; } #if MICROPY_ENABLE_PYSTACK @@ -340,7 +342,7 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size } #if MICROPY_PY_FUNCTION_ATTRS -STATIC void fun_bc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { +void mp_obj_fun_bc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { if (dest[0] != MP_OBJ_NULL) { // not load attribute return; @@ -360,7 +362,7 @@ const mp_obj_type_t mp_type_fun_bc = { .call = fun_bc_call, .unary_op = mp_generic_unary_op, #if MICROPY_PY_FUNCTION_ATTRS - .attr = fun_bc_attr, + .attr = mp_obj_fun_bc_attr, #endif }; @@ -402,7 +404,7 @@ STATIC mp_obj_t fun_native_call(mp_obj_t self_in, size_t n_args, size_t n_kw, co return fun(self_in, n_args, n_kw, args); } -STATIC const mp_obj_type_t mp_type_fun_native = { +const mp_obj_type_t mp_type_fun_native = { { &mp_type_type }, .name = MP_QSTR_function, .call = fun_native_call, @@ -417,72 +419,6 @@ mp_obj_t mp_obj_new_fun_native(mp_obj_t def_args_in, mp_obj_t def_kw_args, const #endif // MICROPY_EMIT_NATIVE -/******************************************************************************/ -/* viper functions */ - -#if MICROPY_EMIT_NATIVE - -typedef struct _mp_obj_fun_viper_t { - mp_obj_base_t base; - size_t n_args; - void *fun_data; // GC must be able to trace this pointer - mp_uint_t type_sig; -} mp_obj_fun_viper_t; - -typedef mp_uint_t (*viper_fun_0_t)(void); -typedef mp_uint_t (*viper_fun_1_t)(mp_uint_t); -typedef mp_uint_t (*viper_fun_2_t)(mp_uint_t, mp_uint_t); -typedef mp_uint_t (*viper_fun_3_t)(mp_uint_t, mp_uint_t, mp_uint_t); -typedef mp_uint_t (*viper_fun_4_t)(mp_uint_t, mp_uint_t, mp_uint_t, mp_uint_t); - -STATIC mp_obj_t fun_viper_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - mp_obj_fun_viper_t *self = self_in; - - mp_arg_check_num_kw_array(n_args, n_kw, self->n_args, self->n_args, false); - - void *fun = MICROPY_MAKE_POINTER_CALLABLE(self->fun_data); - - mp_uint_t ret; - if (n_args == 0) { - ret = ((viper_fun_0_t)fun)(); - } else if (n_args == 1) { - ret = ((viper_fun_1_t)fun)(mp_convert_obj_to_native(args[0], self->type_sig >> 4)); - } else if (n_args == 2) { - ret = ((viper_fun_2_t)fun)(mp_convert_obj_to_native(args[0], self->type_sig >> 4), mp_convert_obj_to_native(args[1], self->type_sig >> 8)); - } else if (n_args == 3) { - ret = ((viper_fun_3_t)fun)(mp_convert_obj_to_native(args[0], self->type_sig >> 4), mp_convert_obj_to_native(args[1], self->type_sig >> 8), mp_convert_obj_to_native(args[2], self->type_sig >> 12)); - } else { - // compiler allows at most 4 arguments - assert(n_args == 4); - ret = ((viper_fun_4_t)fun)( - mp_convert_obj_to_native(args[0], self->type_sig >> 4), - mp_convert_obj_to_native(args[1], self->type_sig >> 8), - mp_convert_obj_to_native(args[2], self->type_sig >> 12), - mp_convert_obj_to_native(args[3], self->type_sig >> 16) - ); - } - - return mp_convert_native_to_obj(ret, self->type_sig); -} - -STATIC const mp_obj_type_t mp_type_fun_viper = { - { &mp_type_type }, - .name = MP_QSTR_function, - .call = fun_viper_call, - .unary_op = mp_generic_unary_op, -}; - -mp_obj_t mp_obj_new_fun_viper(size_t n_args, void *fun_data, mp_uint_t type_sig) { - mp_obj_fun_viper_t *o = m_new_obj(mp_obj_fun_viper_t); - o->base.type = &mp_type_fun_viper; - o->n_args = n_args; - o->fun_data = fun_data; - o->type_sig = type_sig; - return o; -} - -#endif // MICROPY_EMIT_NATIVE - /******************************************************************************/ /* inline assembler functions */ diff --git a/py/objfun.h b/py/objfun.h index 457c3cf48c..ba533fd329 100644 --- a/py/objfun.h +++ b/py/objfun.h @@ -41,4 +41,6 @@ typedef struct _mp_obj_fun_bc_t { mp_obj_t extra_args[]; } mp_obj_fun_bc_t; +void mp_obj_fun_bc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest); + #endif // MICROPY_INCLUDED_PY_OBJFUN_H diff --git a/py/objgenerator.c b/py/objgenerator.c index 9ca5812d84..5336f7f36a 100644 --- a/py/objgenerator.c +++ b/py/objgenerator.c @@ -52,7 +52,51 @@ typedef struct _mp_obj_gen_instance_t { mp_code_state_t code_state; } mp_obj_gen_instance_t; -STATIC mp_obj_t gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { +/******************************************************************************/ +// native generator wrapper + +#if MICROPY_EMIT_NATIVE + +STATIC mp_obj_t native_gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_obj_gen_wrap_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_fun_bc_t *self_fun = (mp_obj_fun_bc_t *)self->fun; + + // Determine start of prelude, and extract n_state from it +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-align" + uintptr_t prelude_offset = ((uintptr_t *)self_fun->bytecode)[0]; +#pragma GCC diagnostic pop + size_t n_state = mp_decode_uint_value(self_fun->bytecode + prelude_offset); + size_t n_exc_stack = 0; + + // Allocate the generator object, with room for local stack and exception stack + mp_obj_gen_instance_t *o = m_new_obj_var(mp_obj_gen_instance_t, byte, + n_state * sizeof(mp_obj_t) + n_exc_stack * sizeof(mp_exc_stack_t)); + o->base.type = &mp_type_gen_instance; + + // Parse the input arguments and set up the code state + o->coroutine_generator = self->coroutine_generator; + o->globals = self_fun->globals; + o->code_state.fun_bc = self_fun; + o->code_state.ip = (const byte *)prelude_offset; + mp_setup_code_state(&o->code_state, n_args, n_kw, args); + + // Indicate we are a native function, which doesn't use this variable + o->code_state.exc_sp = NULL; + + // Prepare the generator instance for execution +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-align" + uintptr_t start_offset = ((uintptr_t *)self_fun->bytecode)[1]; +#pragma GCC diagnostic pop + o->code_state.ip = MICROPY_MAKE_POINTER_CALLABLE((void *)(self_fun->bytecode + start_offset)); + + return MP_OBJ_FROM_PTR(o); +} + +#endif // MICROPY_EMIT_NATIVE + +STATIC mp_obj_t bc_gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_obj_gen_wrap_t *self = MP_OBJ_TO_PTR(self_in); mp_obj_fun_bc_t *self_fun = (mp_obj_fun_bc_t *)self->fun; assert(self_fun->base.type == &mp_type_fun_bc); @@ -74,13 +118,37 @@ STATIC mp_obj_t gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, cons return MP_OBJ_FROM_PTR(o); } +STATIC mp_obj_t gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_obj_gen_wrap_t *self = MP_OBJ_TO_PTR(self_in); + + #if MICROPY_EMIT_NATIVE + mp_obj_fun_bc_t *self_fun = (mp_obj_fun_bc_t *)self->fun; + if (self_fun->base.type == &mp_type_fun_native) { + return native_gen_wrap_call(self, n_args, n_kw, args); + } + #endif + return bc_gen_wrap_call(self, n_args, n_kw, args); +} + +#if MICROPY_PY_FUNCTION_ATTRS +static void gen_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { + mp_obj_gen_wrap_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_fun_bc_t *self_fun = (mp_obj_fun_bc_t *)self->fun; + mp_obj_fun_bc_attr(self_fun, attr, dest); +} +#endif + const mp_obj_type_t mp_type_gen_wrap = { { &mp_type_type }, .name = MP_QSTR_generator, .call = gen_wrap_call, .unary_op = mp_generic_unary_op, + #if MICROPY_PY_FUNCTION_ATTRS + .attr = gen_attr, + #endif }; + mp_obj_t mp_obj_new_gen_wrap(mp_obj_t fun, bool is_coroutine) { mp_obj_gen_wrap_t *o = m_new_obj(mp_obj_gen_wrap_t); o->base.type = &mp_type_gen_wrap; @@ -140,7 +208,22 @@ mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_ self->code_state.old_globals = mp_globals_get(); mp_globals_set(self->globals); self->globals = NULL; - mp_vm_return_kind_t ret_kind = mp_execute_bytecode(&self->code_state, throw_value); + + mp_vm_return_kind_t ret_kind; + + #if MICROPY_EMIT_NATIVE + if (self->code_state.exc_sp == NULL) { + // A native generator, with entry point 2 words into the "bytecode" pointer + typedef uintptr_t (*mp_fun_native_gen_t)(void *, mp_obj_t); + mp_fun_native_gen_t fun = MICROPY_MAKE_POINTER_CALLABLE((const void *)(self->code_state.fun_bc->bytecode + 2 * sizeof(uintptr_t))); + ret_kind = fun((void *)&self->code_state, throw_value); + } else + #endif + { + // A bytecode generator + ret_kind = mp_execute_bytecode(&self->code_state, throw_value); + } + self->globals = mp_globals_get(); mp_globals_set(self->code_state.old_globals); @@ -150,8 +233,6 @@ mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_ // Explicitly mark generator as completed. If we don't do this, // subsequent next() may re-execute statements after last yield // again and again, leading to side effects. - // TODO: check how return with value behaves under such conditions - // in CPython. self->code_state.ip = 0; *ret_val = *self->code_state.sp; break; @@ -164,9 +245,12 @@ mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_ break; case MP_VM_RETURN_EXCEPTION: { - size_t n_state = mp_decode_uint_value(self->code_state.fun_bc->bytecode); self->code_state.ip = 0; - *ret_val = self->code_state.state[n_state - 1]; + *ret_val = self->code_state.state[0]; + // PEP479: if StopIteration is raised inside a generator it is replaced with RuntimeError + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(*ret_val)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { + *ret_val = mp_obj_new_exception_msg(&mp_type_RuntimeError, translate("generator raised StopIteration")); + } break; } } @@ -190,15 +274,6 @@ STATIC mp_obj_t gen_resume_and_raise(mp_obj_t self_in, mp_obj_t send_value, mp_o return ret; case MP_VM_RETURN_EXCEPTION: - // TODO: Optimization of returning MP_OBJ_STOP_ITERATION is really part - // of mp_iternext() protocol, but this function is called by other methods - // too, which may not handled MP_OBJ_STOP_ITERATION. - if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { - mp_obj_t val = mp_obj_exception_get_value(ret); - if (val == mp_const_none) { - return MP_OBJ_STOP_ITERATION; - } - } nlr_raise(ret); } } @@ -260,11 +335,10 @@ STATIC mp_obj_t gen_instance_close(mp_obj_t self_in) { case MP_VM_RETURN_YIELD: mp_raise_RuntimeError(translate("generator ignored GeneratorExit")); - // Swallow StopIteration & GeneratorExit (== successful close), and re-raise any other + // Swallow GeneratorExit (== successful close), and re-raise any other case MP_VM_RETURN_EXCEPTION: // ret should always be an instance of an exception class - if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit)) || - mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { return mp_const_none; } nlr_raise(ret); diff --git a/py/objint.c b/py/objint.c index 50062351e6..ac9eb70591 100644 --- a/py/objint.c +++ b/py/objint.c @@ -64,14 +64,12 @@ STATIC mp_obj_t mp_obj_int_make_new(const mp_obj_type_t *type_in, size_t n_args, return mp_obj_new_int_from_float(mp_obj_float_get(args[0])); #endif } else { - // try to convert to small int (eg from bool) - return MP_OBJ_NEW_SMALL_INT(mp_obj_get_int(args[0])); + return mp_unary_op(MP_UNARY_OP_INT, args[0]); } case 2: default: { // should be a string, parse it - // TODO proper error checking of argument types size_t l; const char *s = mp_obj_str_get_data(args[0], &l); return mp_parse_num_integer(s, l, mp_obj_get_int(args[1]), NULL); diff --git a/py/objmodule.c b/py/objmodule.c index 0ac40229d4..efe4650157 100644 --- a/py/objmodule.c +++ b/py/objmodule.c @@ -64,6 +64,13 @@ STATIC void module_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { mp_map_elem_t *elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP); if (elem != NULL) { dest[0] = elem->value; + #if MICROPY_MODULE_GETATTR + } else if (attr != MP_QSTR___getattr__) { + elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(MP_QSTR___getattr__), MP_MAP_LOOKUP); + if (elem != NULL) { + dest[0] = mp_call_function_1(elem->value, MP_OBJ_NEW_QSTR(attr)); + } + #endif } } else { // delete/store attribute diff --git a/py/objnamedtuple.c b/py/objnamedtuple.c index 15b50c2d19..d1ca17c502 100644 --- a/py/objnamedtuple.c +++ b/py/objnamedtuple.c @@ -4,7 +4,7 @@ * The MIT License (MIT) * * SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2014 Paul Sokolovsky + * SPDX-FileCopyrightText: Copyright (c) 2014 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -46,15 +46,21 @@ size_t mp_obj_namedtuple_find_field(const mp_obj_namedtuple_type_t *type, qstr n return (size_t)-1; } -#if MICROPY_PY_COLLECTIONS_ORDEREDDICT +#if MICROPY_PY_COLLECTIONS_NAMEDTUPLE__ASDICT STATIC mp_obj_t namedtuple_asdict(mp_obj_t self_in) { mp_obj_namedtuple_t *self = MP_OBJ_TO_PTR(self_in); const qstr *fields = ((mp_obj_namedtuple_type_t *)self->tuple.base.type)->fields; mp_obj_t dict = mp_obj_new_dict(self->tuple.len); - // make it an OrderedDict mp_obj_dict_t *dictObj = MP_OBJ_TO_PTR(dict); + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + // make it an OrderedDict dictObj->base.type = &mp_type_ordereddict; dictObj->map.is_ordered = 1; + #else + dictObj->base.type = &mp_type_dict; + dictObj->map.is_ordered = 0; + #endif + for (size_t i = 0; i < self->tuple.len; ++i) { mp_obj_dict_store(dict, MP_OBJ_NEW_QSTR(fields[i]), self->tuple.items[i]); } diff --git a/py/objslice.c b/py/objslice.c index a2beb7dd21..9bccde76db 100644 --- a/py/objslice.c +++ b/py/objslice.c @@ -38,8 +38,6 @@ #if MICROPY_PY_BUILTINS_SLICE -// TODO: This implements only variant of slice with 2 integer args only. -// CPython supports 3rd arg (step), plus args can be arbitrary Python objects. typedef struct _mp_obj_slice_t { mp_obj_base_t base; mp_obj_t start; diff --git a/py/objstr.c b/py/objstr.c index e3c0e78e31..a1c611e381 100644 --- a/py/objstr.c +++ b/py/objstr.c @@ -37,7 +37,9 @@ #include "supervisor/shared/translate.h" +#if MICROPY_PY_BUILTINS_STR_OP_MODULO STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict); +#endif STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf); STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in); @@ -317,6 +319,7 @@ const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { // check for modulo if (op == MP_BINARY_OP_MODULO) { + #if MICROPY_PY_BUILTINS_STR_OP_MODULO mp_obj_t *args = &rhs_in; size_t n_args = 1; mp_obj_t dict = MP_OBJ_NULL; @@ -327,6 +330,9 @@ mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i dict = rhs_in; } return str_modulo_format(lhs_in, n_args, args, dict); + #else + return MP_OBJ_NULL; + #endif } // from now on we need lhs type and data, so extract them @@ -947,6 +953,7 @@ STATIC bool arg_looks_numeric(mp_obj_t arg) { ; } +#if MICROPY_PY_BUILTINS_STR_OP_MODULO STATIC mp_obj_t arg_as_int(mp_obj_t arg) { #if MICROPY_PY_BUILTINS_FLOAT if (mp_obj_is_float(arg)) { @@ -955,6 +962,7 @@ STATIC mp_obj_t arg_as_int(mp_obj_t arg) { #endif return arg; } +#endif #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE STATIC NORETURN void terse_str_format_value_error(void) { @@ -1416,10 +1424,11 @@ mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs GET_STR_DATA_LEN(args[0], str, len); int arg_i = 0; vstr_t vstr = mp_obj_str_format_helper((const char *)str, (const char *)str + len, &arg_i, n_args, args, kwargs); - return mp_obj_new_str_from_vstr(&mp_type_str, &vstr); + return mp_obj_new_str_from_vstr(mp_obj_get_type(args[0]), &vstr); } MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format); +#if MICROPY_PY_BUILTINS_STR_OP_MODULO STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict) { mp_check_self(MP_OBJ_IS_STR_OR_BYTES(pattern)); @@ -1620,6 +1629,7 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ return mp_obj_new_str_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr); } +#endif // The implementation is optimized, returning the original string if there's // nothing to replace. @@ -1729,6 +1739,7 @@ STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) { } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace); +#if MICROPY_PY_BUILTINS_STR_COUNT STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) { const mp_obj_type_t *self_type = mp_obj_get_type(args[0]); mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0])); @@ -1769,6 +1780,7 @@ STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) { return MP_OBJ_NEW_SMALL_INT(num_occurrences); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count); +#endif #if MICROPY_PY_BUILTINS_STR_PARTITION STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) { @@ -1979,7 +1991,9 @@ STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) }, { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) }, { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) }, + #if MICROPY_PY_BUILTINS_STR_COUNT { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) }, + #endif #if MICROPY_PY_BUILTINS_STR_PARTITION { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) }, { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) }, diff --git a/py/objstringio.c b/py/objstringio.c index cc853aba6d..793ec84f31 100644 --- a/py/objstringio.c +++ b/py/objstringio.c @@ -196,22 +196,18 @@ STATIC mp_obj_t stringio_make_new(const mp_obj_type_t *type_in, size_t n_args, c mp_obj_stringio_t *o = stringio_new(type_in); if (n_args > 0) { - if (MP_OBJ_IS_INT(args[0])) { - sz = mp_obj_get_int(args[0]); - } else { - mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); + mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); - if (MP_OBJ_IS_STR_OR_BYTES(args[0])) { - o->vstr = m_new_obj(vstr_t); - vstr_init_fixed_buf(o->vstr, bufinfo.len, bufinfo.buf); - o->vstr->len = bufinfo.len; - o->ref_obj = args[0]; - return MP_OBJ_FROM_PTR(o); - } - - sz = bufinfo.len; - initdata = true; + if (MP_OBJ_IS_STR_OR_BYTES(args[0])) { + o->vstr = m_new_obj(vstr_t); + vstr_init_fixed_buf(o->vstr, bufinfo.len, bufinfo.buf); + o->vstr->len = bufinfo.len; + o->ref_obj = args[0]; + return MP_OBJ_FROM_PTR(o); } + + sz = bufinfo.len; + initdata = true; } o->vstr = vstr_new(sz); diff --git a/py/objstrunicode.c b/py/objstrunicode.c index c86d48e63c..d77bbeebcd 100644 --- a/py/objstrunicode.c +++ b/py/objstrunicode.c @@ -264,7 +264,9 @@ STATIC const mp_rom_map_elem_t struni_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) }, { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) }, { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) }, + #if MICROPY_PY_BUILTINS_STR_COUNT { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) }, + #endif #if MICROPY_PY_BUILTINS_STR_PARTITION { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) }, { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) }, diff --git a/py/objtype.c b/py/objtype.c index b7b2d156b2..1f9bc386ad 100644 --- a/py/objtype.c +++ b/py/objtype.c @@ -190,11 +190,13 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_t mp_convert_member_lookup(MP_OBJ_FROM_PTR(obj), type, elem->value, lookup->dest); } #if DEBUG_PRINT - printf("mp_obj_class_lookup: Returning: "); - mp_obj_print(lookup->dest[0], PRINT_REPR); - printf(" "); - // Don't try to repr() lookup->dest[1], as we can be called recursively - printf("<%q @%p>\n", mp_obj_get_type_qstr(lookup->dest[1]), lookup->dest[1]); + DEBUG_printf("mp_obj_class_lookup: Returning: "); + mp_obj_print_helper(MICROPY_DEBUG_PRINTER, lookup->dest[0], PRINT_REPR); + if (lookup->dest[1] != MP_OBJ_NULL) { + // Don't try to repr() lookup->dest[1], as we can be called recursively + DEBUG_printf(" <%s @%p>", mp_obj_get_type_str(lookup->dest[1]), MP_OBJ_TO_PTR(lookup->dest[1])); + } + DEBUG_printf("\n"); #endif return; } @@ -399,6 +401,7 @@ const byte mp_unary_op_method_name[MP_UNARY_OP_NUM_RUNTIME] = { [MP_UNARY_OP_BOOL] = MP_QSTR___bool__, [MP_UNARY_OP_LEN] = MP_QSTR___len__, [MP_UNARY_OP_HASH] = MP_QSTR___hash__, + [MP_UNARY_OP_INT] = MP_QSTR___int__, #if MICROPY_PY_ALL_SPECIAL_METHODS [MP_UNARY_OP_POSITIVE] = MP_QSTR___pos__, [MP_UNARY_OP_NEGATIVE] = MP_QSTR___neg__, @@ -444,9 +447,21 @@ STATIC mp_obj_t instance_unary_op(mp_unary_op_t op, mp_obj_t self_in) { return mp_unary_op(op, self->subobj[0]); } else if (member[0] != MP_OBJ_NULL) { mp_obj_t val = mp_call_function_1(member[0], self_in); - // __hash__ must return a small int - if (op == MP_UNARY_OP_HASH) { - val = MP_OBJ_NEW_SMALL_INT(mp_obj_get_int_truncated(val)); + + switch (op) { + case MP_UNARY_OP_HASH: + // __hash__ must return a small int + val = MP_OBJ_NEW_SMALL_INT(mp_obj_get_int_truncated(val)); + break; + case MP_UNARY_OP_INT: + // Must return int + if (!MP_OBJ_IS_INT(val)) { + mp_raise_TypeError(NULL); + } + break; + default: + // No need to do anything + ; } return val; } else { @@ -483,8 +498,7 @@ const byte mp_binary_op_method_name[MP_BINARY_OP_NUM_RUNTIME] = { // MP_BINARY_OP_NOT_EQUAL, // a != b calls a == b and inverts result [MP_BINARY_OP_CONTAINS] = MP_QSTR___contains__, - // All inplace methods are optional, and normal methods will be used - // as a fallback. + // If an inplace method is not found a normal method will be used as a fallback [MP_BINARY_OP_INPLACE_ADD] = MP_QSTR___iadd__, [MP_BINARY_OP_INPLACE_SUBTRACT] = MP_QSTR___isub__, #if MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS @@ -679,7 +693,6 @@ STATIC void mp_obj_instance_load_attr(mp_obj_t self_in, qstr attr, mp_obj_t *des mp_load_method_maybe(self_in, MP_QSTR___getattr__, dest2); if (dest2[0] != MP_OBJ_NULL) { // __getattr__ exists, call it and return its result - // XXX if this fails to load the requested attr, should we catch the attribute error and return silently? dest2[2] = MP_OBJ_NEW_QSTR(attr); dest[0] = mp_call_method_n_kw(1, 0, dest2); return; @@ -822,41 +835,32 @@ STATIC void mp_obj_instance_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { STATIC mp_obj_t instance_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in); - mp_obj_t member[2] = {MP_OBJ_NULL}; + mp_obj_t member[4] = {MP_OBJ_NULL, MP_OBJ_NULL, index, value}; struct class_lookup_data lookup = { .obj = self, .meth_offset = offsetof(mp_obj_type_t, subscr), .dest = member, .is_type = false, }; - size_t meth_args; if (value == MP_OBJ_NULL) { // delete item lookup.attr = MP_QSTR___delitem__; - mp_obj_class_lookup(&lookup, self->base.type); - meth_args = 2; } else if (value == MP_OBJ_SENTINEL) { // load item lookup.attr = MP_QSTR___getitem__; - mp_obj_class_lookup(&lookup, self->base.type); - meth_args = 2; } else { // store item lookup.attr = MP_QSTR___setitem__; - mp_obj_class_lookup(&lookup, self->base.type); - meth_args = 3; } - if (member[0] == MP_OBJ_SENTINEL) { // native base subscr exists - mp_obj_type_t *subobj_type = mp_obj_get_type(self->subobj[0]); - // return mp_obj_subscr(self->subobj[0], index, value, instance); - mp_obj_t ret = subobj_type->subscr(self_in, index, value); + mp_obj_class_lookup(&lookup, self->base.type); + if (member[0] == MP_OBJ_SENTINEL) { + mp_obj_t ret = mp_obj_subscr(self->subobj[0], index, value); // May have called port specific C code. Make sure it didn't mess up the heap. assert_heap_ok(); return ret; } else if (member[0] != MP_OBJ_NULL) { - mp_obj_t args[3] = {self_in, index, value}; - // TODO probably need to call mp_convert_member_lookup, and use mp_call_method_n_kw - mp_obj_t ret = mp_call_function_n_kw(member[0], meth_args, 0, args); + size_t n_args = value == MP_OBJ_NULL || value == MP_OBJ_SENTINEL ? 1 : 2; + mp_obj_t ret = mp_call_method_n_kw(n_args, 0, member); if (value == MP_OBJ_SENTINEL) { return ret; } else { @@ -1064,8 +1068,6 @@ STATIC void type_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { } else { // delete/store attribute - // TODO CPython allows STORE_ATTR to a class, but is this the correct implementation? - if (self->locals_dict != NULL) { assert(self->locals_dict->base.type == &mp_type_dict); // MicroPython restriction, for now mp_map_t *locals_map = &self->locals_dict->map; diff --git a/py/parsenum.c b/py/parsenum.c index 96f05ff82e..ec27d04e43 100644 --- a/py/parsenum.c +++ b/py/parsenum.c @@ -177,14 +177,20 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool // DEC_VAL_MAX only needs to be rough and is used to retain precision while not overflowing // SMALL_NORMAL_VAL is the smallest power of 10 that is still a normal float +// EXACT_POWER_OF_10 is the largest value of x so that 10^x can be stored exactly in a float +// Note: EXACT_POWER_OF_10 is at least floor(log_5(2^mantissa_length)). Indeed, 10^n = 2^n * 5^n +// so we only have to store the 5^n part in the mantissa (the 2^n part will go into the float's +// exponent). #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT #define DEC_VAL_MAX 1e20F #define SMALL_NORMAL_VAL (1e-37F) #define SMALL_NORMAL_EXP (-37) +#define EXACT_POWER_OF_10 (9) #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE #define DEC_VAL_MAX 1e200 #define SMALL_NORMAL_VAL (1e-307) #define SMALL_NORMAL_EXP (-307) +#define EXACT_POWER_OF_10 (22) #endif const char *top = str + len; @@ -297,7 +303,17 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool exp_val -= SMALL_NORMAL_EXP; dec_val *= SMALL_NORMAL_VAL; } - dec_val *= MICROPY_FLOAT_C_FUN(pow)(10, exp_val); + + // At this point, we need to multiply the mantissa by its base 10 exponent. If possible, + // we would rather manipulate numbers that have an exact representation in IEEE754. It + // turns out small positive powers of 10 do, whereas small negative powers of 10 don't. + // So in that case, we'll yield a division of exact values rather than a multiplication + // of slightly erroneous values. + if (exp_val < 0 && exp_val >= -EXACT_POWER_OF_10) { + dec_val /= MICROPY_FLOAT_C_FUN(pow)(10, -exp_val); + } else { + dec_val *= MICROPY_FLOAT_C_FUN(pow)(10, exp_val); + } } // negate value if needed diff --git a/py/py.mk b/py/py.mk index ae12e1976d..f61bad1faf 100644 --- a/py/py.mk +++ b/py/py.mk @@ -79,7 +79,7 @@ endif ifeq ($(MICROPY_PY_BTREE),1) BTREE_DIR = lib/berkeley-db-1.xx -BTREE_DEFS = -D__DBINTERFACE_PRIVATE=1 -Dmpool_error=printf -Dabort=abort_ -Dvirt_fd_t=mp_obj_t "-DVIRT_FD_T_HEADER=" $(BTREE_DEFS_EXTRA) +BTREE_DEFS = -D__DBINTERFACE_PRIVATE=1 -Dmpool_error=printf -Dabort=abort_ "-Dvirt_fd_t=void*" $(BTREE_DEFS_EXTRA) INC += -I$(TOP)/$(BTREE_DIR)/PORT/include SRC_MOD += extmod/modbtree.c SRC_MOD += $(addprefix $(BTREE_DIR)/,\ @@ -261,12 +261,8 @@ PY_EXTMOD_O_BASENAME = \ extmod/moduhashlib.o \ extmod/modubinascii.o \ extmod/virtpin.o \ - extmod/modussl_axtls.o \ - extmod/modussl_mbedtls.o \ extmod/modurandom.o \ extmod/moduselect.o \ - extmod/modwebsocket.o \ - extmod/modwebrepl.o \ extmod/modframebuf.o \ extmod/vfs.o \ extmod/vfs_reader.o \ @@ -379,7 +375,7 @@ endif # may require disabling tail jump optimization. This will make sure that # each opcode has its own dispatching jump which will improve branch # branch predictor efficiency. -# http://article.gmane.org/gmane.comp.lang.lua.general/75426 +# https://marc.info/?l=lua-l&m=129778596120851 # http://hg.python.org/cpython/file/b127046831e2/Python/ceval.c#l828 # http://www.emulators.com/docs/nx25_nostradamus.htm #-fno-crossjumping diff --git a/py/qstr.c b/py/qstr.c index af5ea58686..a10adc578a 100644 --- a/py/qstr.c +++ b/py/qstr.c @@ -57,6 +57,10 @@ #define QSTR_EXIT() #endif +// Initial number of entries for qstr pool, set so that the first dynamically +// allocated pool is twice this size. The value here must be <= MP_QSTRnumber_of. +#define MICROPY_ALLOC_QSTR_ENTRIES_INIT (10) + // this must match the equivalent function in makeqstrdata.py mp_uint_t qstr_compute_hash(const byte *data, size_t len) { // djb2 algorithm; see http://www.cse.yorku.ca/~oz/hash.html @@ -85,7 +89,7 @@ const qstr_attr_t mp_qstr_const_attr[] = { const qstr_pool_t mp_qstr_const_pool = { NULL, // no previous pool 0, // no previous pool - 10, // set so that the first dynamically allocated pool is twice this size; must be <= the len (just below) + MICROPY_ALLOC_QSTR_ENTRIES_INIT, MP_QSTRnumber_of, // corresponds to number of strings in array just below (qstr_attr_t *)mp_qstr_const_attr, { @@ -138,6 +142,12 @@ STATIC qstr qstr_add(mp_uint_t hash, mp_uint_t len, const char *q_ptr) { if (new_pool_length > MICROPY_QSTR_POOL_MAX_ENTRIES) { new_pool_length = MICROPY_QSTR_POOL_MAX_ENTRIES; } + #ifdef MICROPY_QSTR_EXTRA_POOL + // Put a lower bound on the allocation size in case the extra qstr pool has few entries + if (new_pool_length < MICROPY_ALLOC_QSTR_ENTRIES_INIT) { + new_pool_length = MICROPY_ALLOC_QSTR_ENTRIES_INIT; + } + #endif mp_uint_t pool_size = sizeof(qstr_pool_t) + sizeof(const char *) * new_pool_length; void *chunk = m_malloc_maybe(pool_size + sizeof(qstr_attr_t) * new_pool_length, true); if (chunk == NULL) { diff --git a/py/qstrdefs.h b/py/qstrdefs.h index 04ee03d737..6337399d16 100644 --- a/py/qstrdefs.h +++ b/py/qstrdefs.h @@ -39,8 +39,13 @@ Q() Q(*) Q(_) Q(/) +#if MICROPY_PY_BUILTINS_STR_OP_MODULO Q(%#o) Q(%#x) +#else +Q({:#o}) +Q({:#x}) +#endif Q({:#b}) Q( ) Q(\n) diff --git a/py/runtime.c b/py/runtime.c index 28ecddd786..72eb2fa4c5 100644 --- a/py/runtime.c +++ b/py/runtime.c @@ -139,11 +139,13 @@ void mp_init(void) { } void mp_deinit(void) { + MP_THREAD_GIL_EXIT(); + // mp_obj_dict_free(&dict_main); // mp_map_deinit(&MP_STATE_VM(mp_loaded_modules_map)); // call port specific deinitialization if any - #ifdef MICROPY_PORT_INIT_FUNC + #ifdef MICROPY_PORT_DEINIT_FUNC MICROPY_PORT_DEINIT_FUNC; #endif } @@ -238,6 +240,7 @@ mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) { case MP_UNARY_OP_HASH: return arg; case MP_UNARY_OP_POSITIVE: + case MP_UNARY_OP_INT: return arg; case MP_UNARY_OP_NEGATIVE: // check for overflow @@ -275,13 +278,22 @@ mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) { return result; } } - #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("unsupported type for operator")); - #else - mp_raise_TypeError_varg( - translate("unsupported type for %q: '%q'"), - mp_unary_op_method_name[op], mp_obj_get_type_qstr(arg)); - #endif + // With MP_UNARY_OP_INT, mp_unary_op() becomes a fallback for mp_obj_get_int(). + // In this case provide a more focused error message to not confuse, e.g. chr(1.0) + if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { + if (op == MP_UNARY_OP_INT) { + mp_raise_TypeError(translate("can't convert to int")); + } else { + mp_raise_TypeError(translate("unsupported type for operator")); + } + } else { + if (op == MP_UNARY_OP_INT) { + mp_raise_TypeError_varg(translate("can't convert %q to int"), mp_obj_get_type_qstr(arg)); + } else { + mp_raise_TypeError_varg(translate("unsupported type for %q: '%q'"), + mp_unary_op_method_name[op], mp_obj_get_type_qstr(arg)); + } + } } } @@ -520,11 +532,11 @@ mp_obj_t PLACE_IN_ITCM(mp_binary_op)(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t r default: goto unsupported_op; } - // TODO: We just should make mp_obj_new_int() inline and use that + // This is an inlined version of mp_obj_new_int, for speed if (MP_SMALL_INT_FITS(lhs_val)) { return MP_OBJ_NEW_SMALL_INT(lhs_val); } else { - return mp_obj_new_int(lhs_val); + return mp_obj_new_int_from_ll(lhs_val); } #if MICROPY_PY_BUILTINS_FLOAT } else if (mp_obj_is_float(rhs)) { @@ -1322,15 +1334,8 @@ mp_vm_return_kind_t mp_resume(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t th if (send_value == mp_const_none) { mp_load_method_maybe(self_in, MP_QSTR___next__, dest); if (dest[0] != MP_OBJ_NULL) { - nlr_buf_t nlr; - if (nlr_push(&nlr) == 0) { - *ret_val = mp_call_method_n_kw(0, 0, dest); - nlr_pop(); - return MP_VM_RETURN_YIELD; - } else { - *ret_val = MP_OBJ_FROM_PTR(nlr.ret_val); - return MP_VM_RETURN_EXCEPTION; - } + *ret_val = mp_call_method_n_kw(0, 0, dest); + return MP_VM_RETURN_YIELD; } } @@ -1339,10 +1344,6 @@ mp_vm_return_kind_t mp_resume(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t th if (send_value != MP_OBJ_NULL) { mp_load_method(self_in, MP_QSTR_send, dest); dest[2] = send_value; - // TODO: This should have exception wrapping like __next__ case - // above. Not done right away to think how to optimize native - // generators better, see: - // https://github.com/micropython/micropython/issues/2628 *ret_val = mp_call_method_n_kw(1, 0, dest); return MP_VM_RETURN_YIELD; } @@ -1404,7 +1405,7 @@ mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) { args[1] = mp_const_none; // TODO should be globals args[2] = mp_const_none; // TODO should be locals args[3] = fromlist; - args[4] = level; // must be 0; we don't yet support other values + args[4] = level; // TODO lookup __import__ and call that instead of going straight to builtin implementation return mp_builtin___import__(5, args); @@ -1446,15 +1447,8 @@ mp_obj_t mp_import_from(mp_obj_t module, qstr name) { qstr dot_name_q = qstr_from_strn(dot_name, dot_name_len); mp_local_free(dot_name); - mp_obj_t args[5]; - args[0] = MP_OBJ_NEW_QSTR(dot_name_q); - args[1] = mp_const_none; // TODO should be globals - args[2] = mp_const_none; // TODO should be locals - args[3] = mp_const_true; // Pass sentinel "non empty" value to force returning of leaf module - args[4] = MP_OBJ_NEW_SMALL_INT(0); - - // TODO lookup __import__ and call that instead of going straight to builtin implementation - return mp_builtin___import__(5, args); + // For fromlist, pass sentinel "non empty" value to force returning of leaf module + return mp_import_name(dot_name_q, mp_const_true, MP_OBJ_NEW_SMALL_INT(0)); #else @@ -1468,12 +1462,16 @@ void mp_import_all(mp_obj_t module) { DEBUG_printf("import all %p\n", module); // TODO: Support __all__ - mp_map_t *map = mp_obj_dict_get_map(MP_OBJ_FROM_PTR(mp_obj_module_get_globals(module))); + mp_map_t *map = &mp_obj_module_get_globals(module)->map; for (size_t i = 0; i < map->alloc; i++) { if (MP_MAP_SLOT_IS_FILLED(map, i)) { - qstr name = MP_OBJ_QSTR_VALUE(map->table[i].key); - if (*qstr_str(name) != '_') { - mp_store_name(name, map->table[i].value); + // Entry in module global scope may be generated programmatically + // (and thus be not a qstr for longer names). Avoid turning it in + // qstr if it has '_' and was used exactly to save memory. + const char *name = mp_obj_str_get_str(map->table[i].key); + if (*name != '_') { + qstr qname = mp_obj_str_get_qstr(map->table[i].key); + mp_store_name(qname, map->table[i].value); } } } diff --git a/py/runtime.h b/py/runtime.h index 74307d87cb..c30252a946 100644 --- a/py/runtime.h +++ b/py/runtime.h @@ -81,9 +81,10 @@ bool mp_sched_schedule(mp_obj_t function, mp_obj_t arg); // extra printing method specifically for mp_obj_t's which are integral type int mp_print_mp_int(const mp_print_t *print, mp_obj_t x, int base, int base_char, int flags, char fill, int width, int prec); +void mp_arg_check_num_sig(size_t n_args, size_t n_kw, uint32_t sig); void mp_arg_check_num(size_t n_args, mp_map_t *kw_args, size_t n_args_min, size_t n_args_max, bool takes_kw); -void mp_arg_parse_all(size_t n_pos, const mp_obj_t *pos, mp_map_t *kws, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals); void mp_arg_check_num_kw_array(size_t n_args, size_t n_kw, size_t n_args_min, size_t n_args_max, bool takes_kw); +void mp_arg_parse_all(size_t n_pos, const mp_obj_t *pos, mp_map_t *kws, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals); void mp_arg_parse_all_kw_array(size_t n_pos, size_t n_kw, const mp_obj_t *args, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals); NORETURN void mp_arg_error_terse_mismatch(void); NORETURN void mp_arg_error_unimpl_kw(void); @@ -198,6 +199,7 @@ NORETURN void mp_raise_recursion_depth(void); // helper functions for native/viper code mp_uint_t mp_convert_obj_to_native(mp_obj_t obj, mp_uint_t type); mp_obj_t mp_convert_native_to_obj(mp_uint_t val, mp_uint_t type); +mp_obj_dict_t *mp_native_swap_globals(mp_obj_dict_t *new_globals); mp_obj_t mp_native_call_function_n_kw(mp_obj_t fun_in, size_t n_args_kw, const mp_obj_t *args); void mp_native_raise(mp_obj_t o); diff --git a/py/runtime0.h b/py/runtime0.h index 566cec566a..33c92830ce 100644 --- a/py/runtime0.h +++ b/py/runtime0.h @@ -25,15 +25,18 @@ */ #ifndef MICROPY_INCLUDED_PY_RUNTIME0_H #define MICROPY_INCLUDED_PY_RUNTIME0_H - #include "mpconfig.h" -// These must fit in 8 bits; see scope.h +// The first four must fit in 8 bits, see emitbc.c +// The remaining must fit in 16 bits, see scope.h #define MP_SCOPE_FLAG_VARARGS (0x01) #define MP_SCOPE_FLAG_VARKEYWORDS (0x02) #define MP_SCOPE_FLAG_GENERATOR (0x04) #define MP_SCOPE_FLAG_DEFKWARGS (0x08) #define MP_SCOPE_FLAG_ASYNC (0x10) +#define MP_SCOPE_FLAG_REFGLOBALS (0x20) // used only if native emitter enabled +#define MP_SCOPE_FLAG_HASCONSTS (0x40) // used only if native emitter enabled +#define MP_SCOPE_FLAG_VIPERRET_POS (7) // 3 bits used for viper return type // types for native (viper) function signature #define MP_NATIVE_TYPE_OBJ (0x00) @@ -60,6 +63,7 @@ typedef enum { MP_UNARY_OP_LEN, // __len__ MP_UNARY_OP_HASH, // __hash__; must return a small int MP_UNARY_OP_ABS, // __abs__ + MP_UNARY_OP_INT, // __int__ MP_UNARY_OP_SIZEOF, // for sys.getsizeof() MP_UNARY_OP_NUM_RUNTIME, @@ -146,8 +150,12 @@ typedef enum { } mp_binary_op_t; typedef enum { - MP_F_CONVERT_OBJ_TO_NATIVE = 0, + MP_F_CONST_NONE_OBJ = 0, + MP_F_CONST_FALSE_OBJ, + MP_F_CONST_TRUE_OBJ, + MP_F_CONVERT_OBJ_TO_NATIVE, MP_F_CONVERT_NATIVE_TO_OBJ, + MP_F_NATIVE_SWAP_GLOBALS, MP_F_LOAD_NAME, MP_F_LOAD_GLOBAL, MP_F_LOAD_BUILD_CLASS, @@ -191,12 +199,14 @@ typedef enum { MP_F_DELETE_GLOBAL, MP_F_NEW_CELL, MP_F_MAKE_CLOSURE_FROM_RAW_CODE, + MP_F_ARG_CHECK_NUM_SIG, MP_F_SETUP_CODE_STATE, MP_F_SMALL_INT_FLOOR_DIVIDE, MP_F_SMALL_INT_MODULO, + MP_F_NATIVE_YIELD_FROM, MP_F_NUMBER_OF, } mp_fun_kind_t; -extern void *const mp_fun_table[MP_F_NUMBER_OF]; +extern const void *const mp_fun_table[MP_F_NUMBER_OF]; #endif // MICROPY_INCLUDED_PY_RUNTIME0_H diff --git a/py/scope.c b/py/scope.c index 4adf09afc4..1244240c8d 100644 --- a/py/scope.c +++ b/py/scope.c @@ -64,10 +64,9 @@ void scope_free(scope_t *scope) { m_del(scope_t, scope, 1); } -id_info_t *scope_find_or_add_id(scope_t *scope, qstr qst, bool *added) { +id_info_t *scope_find_or_add_id(scope_t *scope, qstr qst, scope_kind_t kind) { id_info_t *id_info = scope_find(scope, qst); if (id_info != NULL) { - *added = false; return id_info; } @@ -82,11 +81,10 @@ id_info_t *scope_find_or_add_id(scope_t *scope, qstr qst, bool *added) { // handled by the compiler because it adds arguments before compiling the body id_info = &scope->id_info[scope->id_info_len++]; - id_info->kind = 0; + id_info->kind = kind; id_info->flags = 0; id_info->local_num = 0; id_info->qst = qst; - *added = true; return id_info; } @@ -110,9 +108,8 @@ STATIC void scope_close_over_in_parents(scope_t *scope, qstr qst) { assert(scope->parent != NULL); // we should have at least 1 parent for (scope_t *s = scope->parent;; s = s->parent) { assert(s->parent != NULL); // we should not get to the outer scope - bool added; - id_info_t *id = scope_find_or_add_id(s, qst, &added); - if (added) { + id_info_t *id = scope_find_or_add_id(s, qst, ID_INFO_KIND_UNDECIDED); + if (id->kind == ID_INFO_KIND_UNDECIDED) { // variable not previously declared in this scope, so declare it as free and keep searching parents id->kind = ID_INFO_KIND_FREE; } else { @@ -130,21 +127,19 @@ STATIC void scope_close_over_in_parents(scope_t *scope, qstr qst) { } } -void scope_find_local_and_close_over(scope_t *scope, id_info_t *id, qstr qst) { +void scope_check_to_close_over(scope_t *scope, id_info_t *id) { if (scope->parent != NULL) { for (scope_t *s = scope->parent; s->parent != NULL; s = s->parent) { - id_info_t *id2 = scope_find(s, qst); + id_info_t *id2 = scope_find(s, id->qst); if (id2 != NULL) { if (id2->kind == ID_INFO_KIND_LOCAL || id2->kind == ID_INFO_KIND_CELL || id2->kind == ID_INFO_KIND_FREE) { id->kind = ID_INFO_KIND_FREE; - scope_close_over_in_parents(scope, qst); - return; + scope_close_over_in_parents(scope, id->qst); } break; } } } - id->kind = ID_INFO_KIND_GLOBAL_IMPLICIT; } #endif // MICROPY_ENABLE_COMPILER diff --git a/py/scope.h b/py/scope.h index c92a39e5e6..485a964abe 100644 --- a/py/scope.h +++ b/py/scope.h @@ -30,6 +30,7 @@ #include "py/emitglue.h" enum { + ID_INFO_KIND_UNDECIDED, ID_INFO_KIND_GLOBAL_IMPLICIT, ID_INFO_KIND_GLOBAL_EXPLICIT, ID_INFO_KIND_LOCAL, // in a function f, written and only referenced by f @@ -41,6 +42,7 @@ enum { ID_FLAG_IS_PARAM = 0x01, ID_FLAG_IS_STAR_PARAM = 0x02, ID_FLAG_IS_DBL_STAR_PARAM = 0x04, + ID_FLAG_VIPER_TYPE_POS = 4, }; typedef struct _id_info_t { @@ -71,11 +73,11 @@ typedef struct _scope_t { struct _scope_t *parent; struct _scope_t *next; mp_parse_node_t pn; + mp_raw_code_t *raw_code; uint16_t source_file; // a qstr uint16_t simple_name; // a qstr - mp_raw_code_t *raw_code; - uint8_t scope_flags; // see runtime0.h - uint8_t emit_options; // see compile.h + uint16_t scope_flags; // see runtime0.h + uint16_t emit_options; // see emitglue.h uint16_t num_pos_args; uint16_t num_kwonly_args; uint16_t num_def_pos_args; @@ -89,9 +91,9 @@ typedef struct _scope_t { scope_t *scope_new(scope_kind_t kind, mp_parse_node_t pn, qstr source_file, mp_uint_t emit_options); void scope_free(scope_t *scope); -id_info_t *scope_find_or_add_id(scope_t *scope, qstr qstr, bool *added); +id_info_t *scope_find_or_add_id(scope_t *scope, qstr qstr, scope_kind_t kind); id_info_t *scope_find(scope_t *scope, qstr qstr); id_info_t *scope_find_global(scope_t *scope, qstr qstr); -void scope_find_local_and_close_over(scope_t *scope, id_info_t *id, qstr qst); +void scope_check_to_close_over(scope_t *scope, id_info_t *id); #endif // MICROPY_INCLUDED_PY_SCOPE_H diff --git a/py/stream.c b/py/stream.c index 159d32ffb4..35cbc4e211 100644 --- a/py/stream.c +++ b/py/stream.c @@ -561,7 +561,7 @@ off_t mp_stream_posix_lseek(mp_obj_t stream, off_t offset, int whence) { struct mp_stream_seek_t seek_s; seek_s.offset = offset; seek_s.whence = whence; - mp_uint_t res = stream_p->ioctl(stream, MP_STREAM_SEEK, (mp_uint_t)(uintptr_t)&seek_s, &mp_stream_errno); + mp_uint_t res = stream_p->ioctl(MP_OBJ_FROM_PTR(stream), MP_STREAM_SEEK, (mp_uint_t)(uintptr_t)&seek_s, &mp_stream_errno); if (res == MP_STREAM_ERROR) { return -1; } diff --git a/py/stream.h b/py/stream.h index be0b4ace72..3aa0245be1 100644 --- a/py/stream.h +++ b/py/stream.h @@ -42,6 +42,7 @@ #define MP_STREAM_SET_OPTS (7) // Set stream options #define MP_STREAM_GET_DATA_OPTS (8) // Get data/message options #define MP_STREAM_SET_DATA_OPTS (9) // Set data/message options +#define MP_STREAM_GET_FILENO (10) // Get fileno of underlying file // These poll ioctl values are compatible with Linux #define MP_STREAM_POLL_RD (0x0001) @@ -121,10 +122,11 @@ mp_obj_t mp_stream_flush(mp_obj_t self); #if MICROPY_STREAMS_POSIX_API // Functions with POSIX-compatible signatures -ssize_t mp_stream_posix_write(mp_obj_t stream, const void *buf, size_t len); -ssize_t mp_stream_posix_read(mp_obj_t stream, void *buf, size_t len); -off_t mp_stream_posix_lseek(mp_obj_t stream, off_t offset, int whence); -int mp_stream_posix_fsync(mp_obj_t stream); +// "stream" is assumed to be a pointer to a concrete object with the stream protocol +ssize_t mp_stream_posix_write(void *stream, const void *buf, size_t len); +ssize_t mp_stream_posix_read(void *stream, void *buf, size_t len); +off_t mp_stream_posix_lseek(void *stream, off_t offset, int whence); +int mp_stream_posix_fsync(void *stream); #endif #if MICROPY_STREAMS_NON_BLOCK diff --git a/py/unicode.c b/py/unicode.c index 17f05861ca..1e41821d51 100644 --- a/py/unicode.c +++ b/py/unicode.c @@ -182,7 +182,7 @@ bool utf8_check(const byte *p, size_t len) { for (; p < end; p++) { byte c = *p; if (need) { - if (c >= 0x80) { + if (UTF8_IS_CONT(c)) { need--; } else { // mismatch diff --git a/py/vm.c b/py/vm.c index 21a9528b2b..615a550304 100644 --- a/py/vm.c +++ b/py/vm.c @@ -117,7 +117,7 @@ // returns: // MP_VM_RETURN_NORMAL, sp valid, return value in *sp // MP_VM_RETURN_YIELD, ip, sp valid, yielded value in *sp -// MP_VM_RETURN_EXCEPTION, exception in fastn[0] +// MP_VM_RETURN_EXCEPTION, exception in state[0] mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_state, volatile mp_obj_t inject_exc) { #define SELECTIVE_EXC_IP (0) #if SELECTIVE_EXC_IP @@ -830,17 +830,14 @@ mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_st #if MICROPY_PY_BUILTINS_SLICE ENTRY(MP_BC_BUILD_SLICE) : { MARK_EXC_IP_SELECTIVE(); - DECODE_UINT; - if (unum == 2) { - mp_obj_t stop = POP(); - mp_obj_t start = TOP(); - SET_TOP(mp_obj_new_slice(start, stop, mp_const_none)); - } else { - mp_obj_t step = POP(); - mp_obj_t stop = POP(); - mp_obj_t start = TOP(); - SET_TOP(mp_obj_new_slice(start, stop, step)); + mp_obj_t step = mp_const_none; + if (*ip++ == 3) { + // 3-argument slice includes step + step = POP(); } + mp_obj_t stop = POP(); + mp_obj_t start = TOP(); + SET_TOP(mp_obj_new_slice(start, stop, step)); DISPATCH(); } #endif @@ -1076,17 +1073,11 @@ mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_st ENTRY(MP_BC_RETURN_VALUE) : MARK_EXC_IP_SELECTIVE(); - // These next 3 lines pop a try-finally exception handler, if one - // is there on the exception stack. Without this the finally block - // is executed a second time when the return is executed, because - // the try-finally exception handler is still on the stack. - // TODO Possibly find a better way to handle this case. - if (currently_in_except_block) { - POP_EXC_BLOCK(); - } unwind_return: + // Search for and execute finally handlers that aren't already active while (exc_sp >= exc_stack) { - if (MP_TAGPTR_TAG1(exc_sp->val_sp)) { + if (!currently_in_except_block && MP_TAGPTR_TAG1(exc_sp->val_sp)) { + // Found a finally handler that isn't active. // Getting here the stack looks like: // (..., X, [iter0, iter1, ...,] ret_val) // where X is pointed to by exc_sp->val_sp and in the case @@ -1105,10 +1096,10 @@ mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_st // done (when WITH_CLEANUP or END_FINALLY reached). PUSH(MP_OBJ_NEW_SMALL_INT(-1)); ip = exc_sp->handler; - exc_sp--; + POP_EXC_BLOCK(); goto dispatch_loop; } - exc_sp--; + POP_EXC_BLOCK(); } nlr_pop(); code_state->sp = sp; @@ -1174,7 +1165,7 @@ mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_st MARK_EXC_IP_SELECTIVE(); // #define EXC_MATCH(exc, type) MP_OBJ_IS_TYPE(exc, type) #define EXC_MATCH(exc, type) mp_obj_exception_match(exc, type) -#define GENERATOR_EXIT_IF_NEEDED(t) if (t != MP_OBJ_NULL && EXC_MATCH(t, MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { RAISE(t); \ +#define GENERATOR_EXIT_IF_NEEDED(t) if (t != MP_OBJ_NULL && EXC_MATCH(t, MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { mp_obj_t raise_t = mp_make_raise_obj(t); RAISE(raise_t); \ } mp_vm_return_kind_t ret_kind; mp_obj_t send_value = POP(); @@ -1297,7 +1288,7 @@ mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_st { mp_obj_t obj = mp_obj_new_exception_msg(&mp_type_NotImplementedError, translate("byte code not implemented")); nlr_pop(); - fastn[0] = obj; + code_state->state[0] = obj; return MP_VM_RETURN_EXCEPTION; } @@ -1490,8 +1481,8 @@ mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_st #endif } else { // propagate exception to higher level - // TODO what to do about ip and sp? they don't really make sense at this point - fastn[0] = MP_OBJ_FROM_PTR(nlr.ret_val); // must put exception here because sp is invalid + // Note: ip and sp don't have usable values at this point + code_state->state[0] = MP_OBJ_FROM_PTR(nlr.ret_val); // put exception here because sp is invalid return MP_VM_RETURN_EXCEPTION; } } diff --git a/tests/basics/async_with_break.py b/tests/basics/async_with_break.py new file mode 100644 index 0000000000..39bcbccb02 --- /dev/null +++ b/tests/basics/async_with_break.py @@ -0,0 +1,59 @@ +# test async with, escaped by a break + +class AContext: + async def __aenter__(self): + print('enter') + return 1 + async def __aexit__(self, exc_type, exc, tb): + print('exit', exc_type, exc) + +async def f1(): + while 1: + async with AContext(): + print('body') + break + print('no 1') + print('no 2') + +o = f1() +try: + print(o.send(None)) +except StopIteration: + print('finished') + +async def f2(): + while 1: + try: + async with AContext(): + print('body') + break + print('no 1') + finally: + print('finally') + print('no 2') + +o = f2() +try: + print(o.send(None)) +except StopIteration: + print('finished') + +async def f3(): + while 1: + try: + try: + async with AContext(): + print('body') + break + print('no 1') + finally: + print('finally inner') + finally: + print('finally outer') + print('no 2') + +o = f3() +try: + print(o.send(None)) +except StopIteration: + print('finished') diff --git a/tests/basics/async_with_break.py.exp b/tests/basics/async_with_break.py.exp new file mode 100644 index 0000000000..d077a88fad --- /dev/null +++ b/tests/basics/async_with_break.py.exp @@ -0,0 +1,15 @@ +enter +body +exit None None +finished +enter +body +exit None None +finally +finished +enter +body +exit None None +finally inner +finally outer +finished diff --git a/tests/basics/async_with_return.py b/tests/basics/async_with_return.py new file mode 100644 index 0000000000..9af88b839f --- /dev/null +++ b/tests/basics/async_with_return.py @@ -0,0 +1,50 @@ +# test async with, escaped by a return + +class AContext: + async def __aenter__(self): + print('enter') + return 1 + async def __aexit__(self, exc_type, exc, tb): + print('exit', exc_type, exc) + +async def f1(): + async with AContext(): + print('body') + return + +o = f1() +try: + o.send(None) +except StopIteration: + print('finished') + +async def f2(): + try: + async with AContext(): + print('body') + return + finally: + print('finally') + +o = f2() +try: + o.send(None) +except StopIteration: + print('finished') + +async def f3(): + try: + try: + async with AContext(): + print('body') + return + finally: + print('finally inner') + finally: + print('finally outer') + +o = f3() +try: + o.send(None) +except StopIteration: + print('finished') diff --git a/tests/basics/async_with_return.py.exp b/tests/basics/async_with_return.py.exp new file mode 100644 index 0000000000..d077a88fad --- /dev/null +++ b/tests/basics/async_with_return.py.exp @@ -0,0 +1,15 @@ +enter +body +exit None None +finished +enter +body +exit None None +finally +finished +enter +body +exit None None +finally inner +finally outer +finished diff --git a/tests/basics/bytearray_construct.py b/tests/basics/bytearray_construct.py index 9c8f3adaaa..75fdc41178 100644 --- a/tests/basics/bytearray_construct.py +++ b/tests/basics/bytearray_construct.py @@ -1,6 +1,7 @@ # test construction of bytearray from different objects -# bytes, tuple, list print(bytearray(b'123')) +print(bytearray('1234', 'utf-8')) +print(bytearray('12345', 'utf-8', 'strict')) print(bytearray((1, 2))) print(bytearray([1, 2])) diff --git a/tests/basics/bytes_count.py b/tests/basics/bytes_count.py index 95bcfe310e..5fa0730f5c 100644 --- a/tests/basics/bytes_count.py +++ b/tests/basics/bytes_count.py @@ -1,3 +1,9 @@ +try: + bytes.count +except AttributeError: + print("SKIP") + raise SystemExit + print(b"".count(b"")) print(b"".count(b"a")) print(b"a".count(b"")) diff --git a/tests/basics/class_getattr.py b/tests/basics/class_getattr.py index 1f875ce538..eadf2b209f 100644 --- a/tests/basics/class_getattr.py +++ b/tests/basics/class_getattr.py @@ -1,4 +1,4 @@ -# test that __getattr__, __getattrribute__ and instance members don't override builtins +# test that __getattr__ and instance members don't override builtins class C: def __init__(self): self.__add__ = lambda: print('member __add__') @@ -7,10 +7,8 @@ class C: def __getattr__(self, attr): print('__getattr__', attr) return None - def __getattrribute__(self, attr): - print('__getattrribute__', attr) - return None c = C() -c.__add__ -c + 1 # should call __add__ +c.add # should call __getattr__ +c.__add__() # should load __add__ instance directly +c + 1 # should call __add__ method directly diff --git a/tests/basics/class_staticclassmethod.py b/tests/basics/class_staticclassmethod.py index 1cb59d5c7b..edde419271 100644 --- a/tests/basics/class_staticclassmethod.py +++ b/tests/basics/class_staticclassmethod.py @@ -17,9 +17,24 @@ class C: def __add__(self, rhs): print('add', rhs) + # subscript special methods wrapped in staticmethod + @staticmethod + def __getitem__(item): + print('static get', item) + return 'item' + @staticmethod + def __setitem__(item, value): + print('static set', item, value) + @staticmethod + def __delitem__(item): + print('static del', item) + c = C() c.f(0) c.g(0) c - 1 c + 2 +print(c[1]) +c[1] = 2 +del c[3] diff --git a/tests/basics/core_class_superproperty.py b/tests/basics/core_class_superproperty.py index 69db10046a..3095ab51da 100644 --- a/tests/basics/core_class_superproperty.py +++ b/tests/basics/core_class_superproperty.py @@ -1,15 +1,19 @@ """ test that calling super() getter property in subclass will return the value """ + + class A: @property def p(self): - return {"a":10} + return {"a": 10} + class AA(A): @property def p(self): return super().p + a = AA() print(a.p) diff --git a/tests/basics/fun_name.py b/tests/basics/fun_name.py index a724f41118..53ca935616 100644 --- a/tests/basics/fun_name.py +++ b/tests/basics/fun_name.py @@ -15,3 +15,10 @@ try: except AttributeError: print('SKIP') raise SystemExit + +# __name__ of a bound native method is not implemented in uPy +# the test here is to make sure it doesn't crash +try: + str((1).to_bytes.__name__) +except AttributeError: + pass diff --git a/tests/basics/gen_yield_from.py b/tests/basics/gen_yield_from.py index 4e68aec63b..037644e1ec 100644 --- a/tests/basics/gen_yield_from.py +++ b/tests/basics/gen_yield_from.py @@ -13,34 +13,6 @@ g = gen2() print(list(g)) -# Like above, but terminate subgen using StopIteration -def gen3(): - yield 1 - yield 2 - raise StopIteration - -def gen4(): - print("here1") - print((yield from gen3())) - print("here2") - -g = gen4() -print(list(g)) - -# Like above, but terminate subgen using StopIteration with value -def gen5(): - yield 1 - yield 2 - raise StopIteration(123) - -def gen6(): - print("here1") - print((yield from gen5())) - print("here2") - -g = gen6() -print(list(g)) - # StopIteration from within a Python function, within a native iterator (map), within a yield from def gen7(x): if x < 3: diff --git a/tests/basics/gen_yield_from.py.exp b/tests/basics/gen_yield_from.py.exp deleted file mode 100644 index 507f2b9caf..0000000000 --- a/tests/basics/gen_yield_from.py.exp +++ /dev/null @@ -1,14 +0,0 @@ -here1 -3 -here2 -[1, 2] -here1 -None -here2 -[1, 2] -here1 -123 -here2 -[1, 2] -444 -[0, 1, 2] diff --git a/tests/basics/gen_yield_from_close.py b/tests/basics/gen_yield_from_close.py index 8339861056..e3e0116ff7 100644 --- a/tests/basics/gen_yield_from_close.py +++ b/tests/basics/gen_yield_from_close.py @@ -55,14 +55,14 @@ except StopIteration: # Yet another variation - leaf generator gets GeneratorExit, -# but raises StopIteration instead. This still should close chain properly. +# and reraises a new GeneratorExit. This still should close chain properly. def gen5(): yield 1 try: yield 2 except GeneratorExit: - print("leaf caught GeneratorExit and raised StopIteration instead") - raise StopIteration(123) + print("leaf caught GeneratorExit and reraised GeneratorExit") + raise GeneratorExit(123) yield 3 yield 4 diff --git a/tests/basics/gen_yield_from_close.py.exp b/tests/basics/gen_yield_from_close.py.exp deleted file mode 100644 index a44d1353df..0000000000 --- a/tests/basics/gen_yield_from_close.py.exp +++ /dev/null @@ -1,20 +0,0 @@ --1 -1 -StopIteration --1 -1 -2 -leaf caught GeneratorExit and swallowed it -delegating caught GeneratorExit -StopIteration --1 -1 -2 -leaf caught GeneratorExit and raised StopIteration instead -delegating caught GeneratorExit -StopIteration -123 -RuntimeError -0 -1 -close diff --git a/tests/basics/gen_yield_from_throw.py b/tests/basics/gen_yield_from_throw.py index d6754d5cd1..703158f4d4 100644 --- a/tests/basics/gen_yield_from_throw.py +++ b/tests/basics/gen_yield_from_throw.py @@ -16,15 +16,3 @@ try: print(next(g)) except TypeError: print("got TypeError from downstream!") - -# case where generator doesn't intercept the thrown/injected exception -def gen3(): - yield 123 - yield 456 - -g3 = gen3() -print(next(g3)) -try: - g3.throw(StopIteration) -except StopIteration: - print('got StopIteration from downstream!') diff --git a/tests/basics/gen_yield_from_throw.py.exp b/tests/basics/gen_yield_from_throw.py.exp deleted file mode 100644 index 6ce97ad86e..0000000000 --- a/tests/basics/gen_yield_from_throw.py.exp +++ /dev/null @@ -1,6 +0,0 @@ -1 -got ValueError from upstream! -str1 -got TypeError from downstream! -123 -got StopIteration from downstream! diff --git a/tests/basics/gen_yield_from_throw2.py b/tests/basics/gen_yield_from_throw2.py index 5c0fc7dbc9..6b59a7835a 100644 --- a/tests/basics/gen_yield_from_throw2.py +++ b/tests/basics/gen_yield_from_throw2.py @@ -1,18 +1,24 @@ -# generator ignores a thrown GeneratorExit (this is allowed) +# outer generator ignores a thrown GeneratorExit (this is allowed) def gen(): try: yield 123 except GeneratorExit: print('GeneratorExit') - yield 456 + +def gen2(): + try: + yield from gen() + except GeneratorExit: + print('GeneratorExit outer') + yield 789 # thrown a class -g = gen() +g = gen2() print(next(g)) print(g.throw(GeneratorExit)) # thrown an instance -g = gen() +g = gen2() print(next(g)) print(g.throw(GeneratorExit())) diff --git a/tests/basics/generator_close.py b/tests/basics/generator_close.py index aa563f2a8a..1ccc78dbe4 100644 --- a/tests/basics/generator_close.py +++ b/tests/basics/generator_close.py @@ -31,13 +31,14 @@ except StopIteration: print("StopIteration") -# Throwing StopIteration in response to close() is ok +# Throwing GeneratorExit in response to close() is ok def gen2(): try: yield 1 yield 2 except: - raise StopIteration + print('raising GeneratorExit') + raise GeneratorExit g = gen2() next(g) diff --git a/tests/basics/generator_close.py.exp b/tests/basics/generator_close.py.exp deleted file mode 100644 index fcd5839357..0000000000 --- a/tests/basics/generator_close.py.exp +++ /dev/null @@ -1,10 +0,0 @@ -None -StopIteration -1 -None -StopIteration -[1, 2] -None -StopIteration -None -ValueError diff --git a/tests/basics/generator_name.py b/tests/basics/generator_name.py new file mode 100644 index 0000000000..77259a8218 --- /dev/null +++ b/tests/basics/generator_name.py @@ -0,0 +1,16 @@ +# test __name__ on generator functions + +def Fun(): + yield + +class A: + def Fun(self): + yield + +try: + print(Fun.__name__) + print(A.Fun.__name__) + print(A().Fun.__name__) +except AttributeError: + print('SKIP') + raise SystemExit diff --git a/tests/basics/generator_pep479.py b/tests/basics/generator_pep479.py new file mode 100644 index 0000000000..e422c349e7 --- /dev/null +++ b/tests/basics/generator_pep479.py @@ -0,0 +1,29 @@ +# tests for correct PEP479 behaviour (introduced in Python 3.5) + +# basic case: StopIteration is converted into a RuntimeError +def gen(): + yield 1 + raise StopIteration +g = gen() +print(next(g)) +try: + next(g) +except RuntimeError: + print('RuntimeError') + +# trying to continue a failed generator now raises StopIteration +try: + next(g) +except StopIteration: + print('StopIteration') + +# throwing a StopIteration which is uncaught will be converted into a RuntimeError +def gen(): + yield 1 + yield 2 +g = gen() +print(next(g)) +try: + g.throw(StopIteration) +except RuntimeError: + print('RuntimeError') diff --git a/tests/basics/generator_pep479.py.exp b/tests/basics/generator_pep479.py.exp new file mode 100644 index 0000000000..c64fe49561 --- /dev/null +++ b/tests/basics/generator_pep479.py.exp @@ -0,0 +1,5 @@ +1 +RuntimeError +StopIteration +1 +RuntimeError diff --git a/tests/basics/generator_return.py b/tests/basics/generator_return.py index 5814ce8379..2b3464a02a 100644 --- a/tests/basics/generator_return.py +++ b/tests/basics/generator_return.py @@ -8,3 +8,9 @@ try: print(next(g)) except StopIteration as e: print(type(e), e.args) + +# trying next again should raise StopIteration with no arguments +try: + print(next(g)) +except StopIteration as e: + print(type(e), e.args) diff --git a/tests/basics/generator_throw.py b/tests/basics/generator_throw.py new file mode 100644 index 0000000000..1a390f399d --- /dev/null +++ b/tests/basics/generator_throw.py @@ -0,0 +1,43 @@ +# case where generator doesn't intercept the thrown/injected exception +def gen(): + yield 123 + yield 456 + +g = gen() +print(next(g)) +try: + g.throw(KeyError) +except KeyError: + print('got KeyError from downstream!') + +# case where a thrown exception is caught and stops the generator +def gen(): + try: + yield 1 + yield 2 + except: + pass +g = gen() +print(next(g)) +try: + g.throw(ValueError) +except StopIteration: + print('got StopIteration') + +# generator ignores a thrown GeneratorExit (this is allowed) +def gen(): + try: + yield 123 + except GeneratorExit: + print('GeneratorExit') + yield 456 + +# thrown a class +g = gen() +print(next(g)) +print(g.throw(GeneratorExit)) + +# thrown an instance +g = gen() +print(next(g)) +print(g.throw(GeneratorExit())) diff --git a/tests/basics/getattr.py b/tests/basics/getattr.py index a021e38fb0..2257da3bf9 100644 --- a/tests/basics/getattr.py +++ b/tests/basics/getattr.py @@ -9,3 +9,20 @@ class A: a = A({'a':1, 'b':2}) print(a.a, a.b) + +# test that any exception raised in __getattr__ propagates out +class A: + def __getattr__(self, attr): + if attr == "value": + raise ValueError(123) + else: + raise AttributeError(456) +a = A() +try: + a.value +except ValueError as er: + print(er) +try: + a.attr +except AttributeError as er: + print(er) diff --git a/tests/io/buffered_writer.py b/tests/basics/io_buffered_writer.py similarity index 100% rename from tests/io/buffered_writer.py rename to tests/basics/io_buffered_writer.py diff --git a/tests/io/buffered_writer.py.exp b/tests/basics/io_buffered_writer.py.exp similarity index 100% rename from tests/io/buffered_writer.py.exp rename to tests/basics/io_buffered_writer.py.exp diff --git a/tests/io/bytesio_cow.py b/tests/basics/io_bytesio_cow.py similarity index 100% rename from tests/io/bytesio_cow.py rename to tests/basics/io_bytesio_cow.py diff --git a/tests/io/bytesio_ext.py b/tests/basics/io_bytesio_ext.py similarity index 100% rename from tests/io/bytesio_ext.py rename to tests/basics/io_bytesio_ext.py diff --git a/tests/io/bytesio_ext2.py b/tests/basics/io_bytesio_ext2.py similarity index 100% rename from tests/io/bytesio_ext2.py rename to tests/basics/io_bytesio_ext2.py diff --git a/tests/io/bytesio_ext2.py.exp b/tests/basics/io_bytesio_ext2.py.exp similarity index 100% rename from tests/io/bytesio_ext2.py.exp rename to tests/basics/io_bytesio_ext2.py.exp diff --git a/tests/io/iobase.py b/tests/basics/io_iobase.py similarity index 100% rename from tests/io/iobase.py rename to tests/basics/io_iobase.py diff --git a/tests/io/stringio1.py b/tests/basics/io_stringio1.py similarity index 100% rename from tests/io/stringio1.py rename to tests/basics/io_stringio1.py diff --git a/tests/io/stringio_with.py b/tests/basics/io_stringio_with.py similarity index 100% rename from tests/io/stringio_with.py rename to tests/basics/io_stringio_with.py diff --git a/tests/io/write_ext.py b/tests/basics/io_write_ext.py similarity index 100% rename from tests/io/write_ext.py rename to tests/basics/io_write_ext.py diff --git a/tests/io/write_ext.py.exp b/tests/basics/io_write_ext.py.exp similarity index 100% rename from tests/io/write_ext.py.exp rename to tests/basics/io_write_ext.py.exp diff --git a/tests/basics/namedtuple_asdict.py b/tests/basics/namedtuple_asdict.py index c5681376fd..34c4e6f713 100644 --- a/tests/basics/namedtuple_asdict.py +++ b/tests/basics/namedtuple_asdict.py @@ -1,8 +1,8 @@ try: try: - from collections import namedtuple - except ImportError: from ucollections import namedtuple + except ImportError: + from collections import namedtuple except ImportError: print("SKIP") raise SystemExit diff --git a/tests/basics/op_precedence.py b/tests/basics/op_precedence.py index 519a2a1137..7d8302ba4d 100644 --- a/tests/basics/op_precedence.py +++ b/tests/basics/op_precedence.py @@ -37,7 +37,7 @@ print(2 + 2 * 2) # BAD: (-2)**2 = 4 print(-2**2) # OK: 2**(-1) = 0.5 -print(2**-1) +print(2**-0) # (expr...) print((2 + 2) * 2) diff --git a/tests/basics/scope_implicit.py b/tests/basics/scope_implicit.py new file mode 100644 index 0000000000..aecda77156 --- /dev/null +++ b/tests/basics/scope_implicit.py @@ -0,0 +1,31 @@ +# test implicit scoping rules + +# implicit nonlocal, with variable defined after closure +def f(): + def g(): + return x # implicit nonlocal + x = 3 # variable defined after function that closes over it + return g +print(f()()) + +# implicit nonlocal at inner level, with variable defined after closure +def f(): + def g(): + def h(): + return x # implicit nonlocal + return h + x = 4 # variable defined after function that closes over it + return g +print(f()()()) + +# local variable which should not be implicitly made nonlocal +def f(): + x = 0 + def g(): + x # local because next statement assigns to it + x = 1 + g() +try: + f() +except NameError: + print('NameError') diff --git a/tests/basics/special_methods.py b/tests/basics/special_methods.py index 9f57247c12..b56bc1c9c4 100644 --- a/tests/basics/special_methods.py +++ b/tests/basics/special_methods.py @@ -93,6 +93,9 @@ class Cud(): print("__isub__ called") return self + def __int__(self): + return 42 + cud1 = Cud() cud2 = Cud() @@ -104,5 +107,16 @@ cud1 >= cud2 cud1 > cud2 cud1 + cud2 cud1 - cud2 +print(int(cud1)) + +class BadInt: + def __int__(self): + print("__int__ called") + return None + +try: + int(BadInt()) +except TypeError: + print("TypeError") # more in special_methods2.py diff --git a/tests/basics/special_methods2.py b/tests/basics/special_methods2.py index c21618e93d..c72c8cf00f 100644 --- a/tests/basics/special_methods2.py +++ b/tests/basics/special_methods2.py @@ -134,6 +134,6 @@ print('a' in dir(Cud)) # ne is not supported, !(eq) is called instead #cud1 != cud2 # -# in the followin test, cpython still calls __eq__ +# in the following test, cpython still calls __eq__ # cud3=cud1 # cud3==cud1 diff --git a/tests/basics/string_count.py b/tests/basics/string_count.py index 462ccb8299..8fb5c98f82 100644 --- a/tests/basics/string_count.py +++ b/tests/basics/string_count.py @@ -1,3 +1,9 @@ +try: + str.count +except AttributeError: + print("SKIP") + raise SystemExit + print("".count("")) print("".count("a")) print("a".count("")) diff --git a/tests/basics/subclass_native_call.py b/tests/basics/subclass_native_call.py deleted file mode 100644 index c645575225..0000000000 --- a/tests/basics/subclass_native_call.py +++ /dev/null @@ -1,30 +0,0 @@ -# test calling a subclass of a native class that supports calling - -# For this test we need a native class that can be subclassed (has make_new) -# and is callable (has call). The only one available is machine.Signal, which -# in turns needs PinBase. -try: - import umachine as machine -except ImportError: - import machine -try: - machine.PinBase - machine.Signal -except AttributeError: - print("SKIP") - raise SystemExit - -class Pin(machine.PinBase): - #def __init__(self): - # self.v = 0 - - def value(self, v=None): - return 42 - -class MySignal(machine.Signal): - pass - -s = MySignal(Pin()) - -# apply call to the subclass, which should call the native base -print(s()) diff --git a/tests/basics/subclass_native_call.py.exp b/tests/basics/subclass_native_call.py.exp deleted file mode 100644 index d81cc0710e..0000000000 --- a/tests/basics/subclass_native_call.py.exp +++ /dev/null @@ -1 +0,0 @@ -42 diff --git a/tests/basics/try_finally1.py b/tests/basics/try_finally1.py index 2416f6d188..67ebe0b590 100644 --- a/tests/basics/try_finally1.py +++ b/tests/basics/try_finally1.py @@ -69,3 +69,28 @@ try: # top-level catch-all except to not fail script except: print("catch-all except") print() + +# case where a try-except within a finally cancels the exception +print("exc-finally-subexcept") +try: + print("try1") +finally: + try: + print("try2") + foo + except: + print("except2") + print("finally1") +print() + +# case where exception is raised after a finally has finished (tests that the finally doesn't run again) +def func(): + try: + print("try") + finally: + print("finally") + foo +try: + func() +except: + print("except") diff --git a/tests/basics/try_finally_return3.py b/tests/basics/try_finally_return3.py new file mode 100644 index 0000000000..a2a06ee975 --- /dev/null +++ b/tests/basics/try_finally_return3.py @@ -0,0 +1,103 @@ +# test 'return' within the finally block, with nested finally's +# only inactive finally's should be executed, and only once + +# basic nested finally's, the print should only be executed once +def f(): + try: + raise TypeError + finally: + print(1) + try: + raise ValueError + finally: + return 42 +print(f()) + +# similar to above but more nesting +def f(): + try: + raise ValueError + finally: + print(1) + try: + raise TypeError + finally: + print(2) + try: + pass + finally: + return 42 +print(f()) + +# similar to above but even more nesting +def f(): + try: + raise ValueError + finally: + print(1) + try: + raise TypeError + finally: + print(2) + try: + raise Exception + finally: + print(3) + return 42 +print(f()) + +# upon return some try's are active, some finally's are active, some inactive +def f(): + try: + try: + pass + finally: + print(2) + return 42 + finally: + print(1) +print(f()) + +# same as above but raise instead of pass +def f(): + try: + try: + raise ValueError + finally: + print(2) + return 42 + finally: + print(1) +print(f()) + +# upon return exception stack holds: active finally, inactive finally, active finally +def f(): + try: + raise Exception + finally: + print(1) + try: + try: + pass + finally: + print(3) + return 42 + finally: + print(2) +print(f()) + +# same as above but raise instead of pass in innermost try block +def f(): + try: + raise Exception + finally: + print(1) + try: + try: + raise Exception + finally: + print(3) + return 42 + finally: + print(2) +print(f()) diff --git a/tests/basics/try_finally_return4.py b/tests/basics/try_finally_return4.py new file mode 100644 index 0000000000..8b54fe92ce --- /dev/null +++ b/tests/basics/try_finally_return4.py @@ -0,0 +1,83 @@ +# test try-finally with return, where unwinding return has to go through +# another try-finally which may affect the behaviour of the return + +# case where a simple try-finally executes during an unwinding return +def f(x): + try: + try: + if x: + return 42 + finally: + try: + print(1) + finally: + print(2) + print(3) + print(4) + finally: + print(5) +print(f(0)) +print(f(1)) + +# case where an unwinding return is replaced by another one +def f(x): + try: + try: + if x: + return 42 + finally: + try: + print(1) + return 43 + finally: + print(2) + print(3) + print(4) + finally: + print(5) +print(f(0)) +print(f(1)) + +# case where an unwinding return is cancelled by an exception +def f(x): + try: + try: + if x: + return 42 + finally: + try: + print(1) + raise ValueError # cancels any active return + finally: + print(2) + print(3) + print(4) + finally: + print(5) +try: + print(f(0)) +except: + print('caught') +try: + print(f(1)) +except: + print('caught') + +# case where an unwinding return is cancelled then resumed +def f(x): + try: + try: + if x: + return 42 + finally: + try: + print(1) + raise Exception # cancels any active return + except: # cancels the exception and resumes any active return + print(2) + print(3) + print(4) + finally: + print(5) +print(f(0)) +print(f(1)) diff --git a/tests/basics/with_raise.py b/tests/basics/with_raise.py new file mode 100644 index 0000000000..67eab09b41 --- /dev/null +++ b/tests/basics/with_raise.py @@ -0,0 +1,44 @@ +# test with when context manager raises in __enter__/__exit__ + +class CtxMgr: + def __init__(self, id): + self.id = id + + def __enter__(self): + print("__enter__", self.id) + if 10 <= self.id < 20: + raise Exception('enter', self.id) + return self + + def __exit__(self, a, b, c): + print("__exit__", self.id, repr(a), repr(b)) + if 15 <= self.id < 25: + raise Exception('exit', self.id) + +# no raising +try: + with CtxMgr(1): + pass +except Exception as e: + print(e) + +# raise in enter +try: + with CtxMgr(10): + pass +except Exception as e: + print(e) + +# raise in enter and exit +try: + with CtxMgr(15): + pass +except Exception as e: + print(e) + +# raise in exit +try: + with CtxMgr(20): + pass +except Exception as e: + print(e) diff --git a/tests/cmdline/cmd_showbc.py b/tests/cmdline/cmd_showbc.py index 58f8a7f70d..326f2373f6 100644 --- a/tests/cmdline/cmd_showbc.py +++ b/tests/cmdline/cmd_showbc.py @@ -2,6 +2,7 @@ # test printing of all bytecodes # fmt: off + def f(): # constants a = None + False + True @@ -15,9 +16,9 @@ def f(): c = [1, 2] d = {1, 2} e = {} - f = {1:2} - g = 'a' - h = b'a' + f = {1: 2} + g = "a" + h = b"a" # unary/binary ops i = 1 @@ -59,7 +60,7 @@ def f(): # comprehensions a = (b for c in d if e) a = [b for c in d if e] - a = {b:b for c in d if e} + a = {b: b for c in d if e} # function calls a() @@ -108,7 +109,9 @@ def f(): # closed over variables x = 1 + def closure(): + nonlocal x a = x + 1 x = 1 del x @@ -126,12 +129,14 @@ def f(): return return 1 + # function with lots of locals def f(): l1 = l2 = l3 = l4 = l5 = l6 = l7 = l8 = l9 = l10 = 1 m1 = m2 = m3 = m4 = m5 = m6 = m7 = m8 = m9 = m10 = 2 l10 + m10 + # functions with default args def f(a=1): pass @@ -139,16 +144,19 @@ def f(a=1): def f(b=2): return b + a + # function which yields def f(): yield yield 1 yield from 1 + # class class Class: pass + # delete name del Class diff --git a/tests/cmdline/cmd_showbc.py.exp b/tests/cmdline/cmd_showbc.py.exp index 6ae5fa20ec..ac4cedd340 100644 --- a/tests/cmdline/cmd_showbc.py.exp +++ b/tests/cmdline/cmd_showbc.py.exp @@ -7,7 +7,7 @@ arg names: (N_EXC_STACK 0) bc=-1 line=1 ######## - bc=\\d\+ line=156 + bc=\\d\+ line=164 00 MAKE_FUNCTION \.\+ \\d\+ STORE_NAME f \\d\+ MAKE_FUNCTION \.\+ @@ -40,7 +40,7 @@ Raw bytecode (code_info_size=\\d\+, bytecode_size=\\d\+): (INIT_CELL 16) bc=-4 line=1 ######## - bc=\\d\+ line=127 + bc=\\d\+ line=130 00 LOAD_CONST_NONE 01 LOAD_CONST_FALSE 02 BINARY_OP 26 __add__ @@ -326,7 +326,7 @@ Raw bytecode (code_info_size=\\d\+, bytecode_size=\\d\+): (N_EXC_STACK 0) bc=-1 line=1 ######## - bc=\\d\+ line=133 + bc=\\d\+ line=137 00 LOAD_CONST_SMALL_INT 1 01 DUP_TOP 02 STORE_FAST 0 @@ -382,7 +382,7 @@ arg names: a (N_EXC_STACK 0) (INIT_CELL 0) ######## - bc=\\d\+ line=139 + bc=\\d\+ line=144 00 LOAD_CONST_SMALL_INT 2 01 BUILD_TUPLE 1 03 LOAD_NULL @@ -399,9 +399,9 @@ arg names: (N_STATE 2) (N_EXC_STACK 0) bc=-1 line=1 - bc=0 line=144 - bc=3 line=145 - bc=6 line=146 + bc=0 line=150 + bc=3 line=151 + bc=6 line=152 00 LOAD_CONST_NONE 01 YIELD_VALUE 02 POP_TOP @@ -423,7 +423,7 @@ arg names: (N_STATE 1) (N_EXC_STACK 0) bc=-1 line=1 - bc=13 line=150 + bc=13 line=157 00 LOAD_NAME __name__ (cache=0) 04 STORE_NAME __module__ 07 LOAD_CONST_STRING 'Class' @@ -438,7 +438,7 @@ arg names: self (N_STATE 4) (N_EXC_STACK 0) bc=-1 line=1 - bc=0 line=157 + bc=0 line=165 00 LOAD_GLOBAL super (cache=0) \\d\+ LOAD_GLOBAL __class__ (cache=0) \\d\+ LOAD_FAST 0 @@ -518,7 +518,7 @@ arg names: * (N_EXC_STACK 0) bc=-\\d\+ line=1 ######## - bc=\\d\+ line=114 + bc=\\d\+ line=117 00 LOAD_DEREF 0 02 LOAD_CONST_SMALL_INT 1 03 BINARY_OP 26 __add__ @@ -537,7 +537,7 @@ arg names: * b (N_EXC_STACK 0) bc=-\\d\+ line=1 ######## - bc=\\d\+ line=140 + bc=\\d\+ line=145 00 LOAD_FAST 1 01 LOAD_DEREF 0 03 BINARY_OP 26 __add__ diff --git a/tests/cpydiff/types_bytes_format.py b/tests/cpydiff/types_bytes_format.py new file mode 100644 index 0000000000..ad04987711 --- /dev/null +++ b/tests/cpydiff/types_bytes_format.py @@ -0,0 +1,7 @@ +""" +categories: Types,bytes +description: bytes objects support .format() method +cause: MicroPython strives to be a more regular implementation, so if both `str` and `bytes` support ``__mod__()`` (the % operator), it makes sense to support ``format()`` for both too. Support for ``__mod__`` can also be compiled out, which leaves only ``format()`` for bytes formatting. +workaround: If you are interested in CPython compatibility, don't use ``.format()`` on bytes objects. +""" +print(b"{}".format(1)) diff --git a/tests/extmod/machine1.py b/tests/extmod/machine1.py deleted file mode 100644 index 6ff38cc051..0000000000 --- a/tests/extmod/machine1.py +++ /dev/null @@ -1,28 +0,0 @@ -# test machine module - -try: - try: - import umachine as machine - except ImportError: - import machine - machine.mem8 -except: - print("SKIP") - raise SystemExit - -print(machine.mem8) - -try: - machine.mem16[1] -except ValueError: - print("ValueError") - -try: - machine.mem16[1] = 1 -except ValueError: - print("ValueError") - -try: - del machine.mem8[0] -except TypeError: - print("TypeError") diff --git a/tests/extmod/machine1.py.exp b/tests/extmod/machine1.py.exp deleted file mode 100644 index bb421ea5cf..0000000000 --- a/tests/extmod/machine1.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -<8-bit memory> -ValueError -ValueError -TypeError diff --git a/tests/extmod/machine_pinbase.py b/tests/extmod/machine_pinbase.py deleted file mode 100644 index f6b27d1d1d..0000000000 --- a/tests/extmod/machine_pinbase.py +++ /dev/null @@ -1,30 +0,0 @@ -try: - import umachine as machine -except ImportError: - import machine -try: - machine.PinBase -except AttributeError: - print("SKIP") - raise SystemExit - - -class MyPin(machine.PinBase): - def __init__(self): - print("__init__") - self.v = False - - def value(self, v=None): - print("value:", v) - if v is None: - self.v = not self.v - return int(self.v) - - -p = MyPin() - -print(p.value()) -print(p.value()) -print(p.value()) -p.value(1) -p.value(0) diff --git a/tests/extmod/machine_pinbase.py.exp b/tests/extmod/machine_pinbase.py.exp deleted file mode 100644 index b31cd98308..0000000000 --- a/tests/extmod/machine_pinbase.py.exp +++ /dev/null @@ -1,9 +0,0 @@ -__init__ -value: None -1 -value: None -0 -value: None -1 -value: 1 -value: 0 diff --git a/tests/extmod/machine_pulse.py b/tests/extmod/machine_pulse.py deleted file mode 100644 index 7a8fe14d06..0000000000 --- a/tests/extmod/machine_pulse.py +++ /dev/null @@ -1,44 +0,0 @@ -try: - import umachine as machine -except ImportError: - import machine -try: - machine.PinBase - machine.time_pulse_us -except AttributeError: - print("SKIP") - raise SystemExit - - -class ConstPin(machine.PinBase): - def __init__(self, value): - self.v = value - - def value(self, v=None): - if v is None: - return self.v - else: - self.v = v - - -class TogglePin(machine.PinBase): - def __init__(self): - self.v = 0 - - def value(self, v=None): - if v is None: - self.v = 1 - self.v - print("value:", self.v) - return self.v - - -p = TogglePin() - -t = machine.time_pulse_us(p, 1) -print(type(t)) -t = machine.time_pulse_us(p, 0) -print(type(t)) - -p = ConstPin(0) -print(machine.time_pulse_us(p, 1, 10)) -print(machine.time_pulse_us(p, 0, 10)) diff --git a/tests/extmod/machine_pulse.py.exp b/tests/extmod/machine_pulse.py.exp deleted file mode 100644 index 20d4c10431..0000000000 --- a/tests/extmod/machine_pulse.py.exp +++ /dev/null @@ -1,9 +0,0 @@ -value: 1 -value: 0 - -value: 1 -value: 0 -value: 1 - --2 --1 diff --git a/tests/extmod/machine_signal.py b/tests/extmod/machine_signal.py deleted file mode 100644 index c453098402..0000000000 --- a/tests/extmod/machine_signal.py +++ /dev/null @@ -1,40 +0,0 @@ -# test machine.Signal class - -try: - import umachine as machine -except ImportError: - import machine -try: - machine.PinBase - machine.Signal -except AttributeError: - print("SKIP") - raise SystemExit - - -class Pin(machine.PinBase): - def __init__(self): - self.v = 0 - - def value(self, v=None): - if v is None: - return self.v - else: - self.v = int(v) - - -# test non-inverted -p = Pin() -s = machine.Signal(p) -s.value(0) -print(p.value(), s.value()) -s.value(1) -print(p.value(), s.value()) - -# test inverted, and using on/off methods -p = Pin() -s = machine.Signal(p, invert=True) -s.off() -print(p.value(), s.value()) -s.on() -print(p.value(), s.value()) diff --git a/tests/extmod/machine_signal.py.exp b/tests/extmod/machine_signal.py.exp deleted file mode 100644 index 7e9dd67966..0000000000 --- a/tests/extmod/machine_signal.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -0 0 -1 1 -1 0 -0 1 diff --git a/tests/extmod/ubinascii_a2b_base64.py b/tests/extmod/ubinascii_a2b_base64.py index 39b85274b6..c65d69ddbe 100644 --- a/tests/extmod/ubinascii_a2b_base64.py +++ b/tests/extmod/ubinascii_a2b_base64.py @@ -29,7 +29,7 @@ print(binascii.a2b_base64(b"Zm9v===")) print(binascii.a2b_base64(b"Zm9v===YmFy")) # Unicode strings can be decoded -print(binascii.a2b_base64(u"Zm9v===YmFy")) +print(binascii.a2b_base64("Zm9v===YmFy")) try: print(binascii.a2b_base64(b"abc")) diff --git a/tests/extmod/ucryptolib_aes128_cbc.py b/tests/extmod/ucryptolib_aes128_cbc.py new file mode 100644 index 0000000000..d861d2c6bf --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_cbc.py @@ -0,0 +1,16 @@ +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 2, b"5678" * 4) +enc = crypto.encrypt(bytes(range(32))) +print(enc) +crypto = aes(b"1234" * 4, 2, b"5678" * 4) +print(crypto.decrypt(enc)) diff --git a/tests/extmod/ucryptolib_aes128_cbc.py.exp b/tests/extmod/ucryptolib_aes128_cbc.py.exp new file mode 100644 index 0000000000..cc73553b2a --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_cbc.py.exp @@ -0,0 +1,2 @@ +b'\x1d\x84\xfa\xaa%\x0e9\x143\x8b6\xf8\xdf^yh\xd0\x94g\xf4\xcf\x1d\xa0I)\x8a\xa0\x00u0+C' +b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' diff --git a/tests/extmod/ucryptolib_aes128_ecb.py b/tests/extmod/ucryptolib_aes128_ecb.py new file mode 100644 index 0000000000..5c0e179986 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb.py @@ -0,0 +1,16 @@ +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 1) +enc = crypto.encrypt(bytes(range(32))) +print(enc) +crypto = aes(b"1234" * 4, 1) +print(crypto.decrypt(enc)) diff --git a/tests/extmod/ucryptolib_aes128_ecb.py.exp b/tests/extmod/ucryptolib_aes128_ecb.py.exp new file mode 100644 index 0000000000..b0fd15b447 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb.py.exp @@ -0,0 +1,2 @@ +b'Iz\xfe9\x17\xac\xa4X\x12\x04\x10\xf5K~#\xc7\xac;\xf9\xc6E\xa8\xca~\xf1\xee\xd3f%\xf1\x8d\xfe' +b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' diff --git a/tests/extmod/ucryptolib_aes128_ecb_enc.py b/tests/extmod/ucryptolib_aes128_ecb_enc.py new file mode 100644 index 0000000000..1d4484b0bc --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_enc.py @@ -0,0 +1,17 @@ +# This tests minimal configuration of ucrypto module, which is +# AES128 encryption (anything else, including AES128 decryption, +# is optional). +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 1) +enc = crypto.encrypt(bytes(range(32))) +print(enc) diff --git a/tests/extmod/ucryptolib_aes128_ecb_enc.py.exp b/tests/extmod/ucryptolib_aes128_ecb_enc.py.exp new file mode 100644 index 0000000000..9921d4b83a --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_enc.py.exp @@ -0,0 +1 @@ +b'Iz\xfe9\x17\xac\xa4X\x12\x04\x10\xf5K~#\xc7\xac;\xf9\xc6E\xa8\xca~\xf1\xee\xd3f%\xf1\x8d\xfe' diff --git a/tests/extmod/ucryptolib_aes128_ecb_inpl.py b/tests/extmod/ucryptolib_aes128_ecb_inpl.py new file mode 100644 index 0000000000..88ccb02daf --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_inpl.py @@ -0,0 +1,15 @@ +# Inplace operations (input and output buffer is the same) +try: + from ucryptolib import aes +except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 1) +buf = bytearray(bytes(range(32))) +crypto.encrypt(buf, buf) +print(buf) + +crypto = aes(b"1234" * 4, 1) +crypto.decrypt(buf, buf) +print(buf) diff --git a/tests/extmod/ucryptolib_aes128_ecb_inpl.py.exp b/tests/extmod/ucryptolib_aes128_ecb_inpl.py.exp new file mode 100644 index 0000000000..b7f7bf5409 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_inpl.py.exp @@ -0,0 +1,2 @@ +bytearray(b'Iz\xfe9\x17\xac\xa4X\x12\x04\x10\xf5K~#\xc7\xac;\xf9\xc6E\xa8\xca~\xf1\xee\xd3f%\xf1\x8d\xfe') +bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f') diff --git a/tests/extmod/ucryptolib_aes128_ecb_into.py b/tests/extmod/ucryptolib_aes128_ecb_into.py new file mode 100644 index 0000000000..ff832d7ef3 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_into.py @@ -0,0 +1,16 @@ +# Operations with pre-allocated output buffer +try: + from ucryptolib import aes +except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 1) +enc = bytearray(32) +crypto.encrypt(bytes(range(32)), enc) +print(enc) + +crypto = aes(b"1234" * 4, 1) +dec = bytearray(32) +crypto.decrypt(enc, dec) +print(dec) diff --git a/tests/extmod/ucryptolib_aes128_ecb_into.py.exp b/tests/extmod/ucryptolib_aes128_ecb_into.py.exp new file mode 100644 index 0000000000..b7f7bf5409 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_into.py.exp @@ -0,0 +1,2 @@ +bytearray(b'Iz\xfe9\x17\xac\xa4X\x12\x04\x10\xf5K~#\xc7\xac;\xf9\xc6E\xa8\xca~\xf1\xee\xd3f%\xf1\x8d\xfe') +bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f') diff --git a/tests/extmod/ucryptolib_aes256_cbc.py b/tests/extmod/ucryptolib_aes256_cbc.py new file mode 100644 index 0000000000..c01846f199 --- /dev/null +++ b/tests/extmod/ucryptolib_aes256_cbc.py @@ -0,0 +1,16 @@ +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 8, 2, b"5678" * 4) +enc = crypto.encrypt(bytes(range(32))) +print(enc) +crypto = aes(b"1234" * 8, 2, b"5678" * 4) +print(crypto.decrypt(enc)) diff --git a/tests/extmod/ucryptolib_aes256_cbc.py.exp b/tests/extmod/ucryptolib_aes256_cbc.py.exp new file mode 100644 index 0000000000..51262db9c6 --- /dev/null +++ b/tests/extmod/ucryptolib_aes256_cbc.py.exp @@ -0,0 +1,2 @@ +b'\xb4\x0b\xff\xdd\xfc\xb5\x03\x88[m\xc1\x01+:\x03M\x18\xb03\x0f\x971g\x10\xb1\x98>\x9b\x17\xb7-\xb2' +b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' diff --git a/tests/extmod/ucryptolib_aes256_ecb.py b/tests/extmod/ucryptolib_aes256_ecb.py new file mode 100644 index 0000000000..0760063c14 --- /dev/null +++ b/tests/extmod/ucryptolib_aes256_ecb.py @@ -0,0 +1,16 @@ +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 8, 1) +enc = crypto.encrypt(bytes(range(32))) +print(enc) +crypto = aes(b"1234" * 8, 1) +print(crypto.decrypt(enc)) diff --git a/tests/extmod/ucryptolib_aes256_ecb.py.exp b/tests/extmod/ucryptolib_aes256_ecb.py.exp new file mode 100644 index 0000000000..a00a4eb2f5 --- /dev/null +++ b/tests/extmod/ucryptolib_aes256_ecb.py.exp @@ -0,0 +1,2 @@ +b'\xe2\xe0\xdd\xef\xc3\xcd\x88/!>\xf6\xa2\xef/\xd15z+`\xb2\xb2\xd7}!:V>\xeb\x19\xbf|\xea' +b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' diff --git a/tests/extmod/uctypes_error.py b/tests/extmod/uctypes_error.py index fb876de6d9..d429562615 100644 --- a/tests/extmod/uctypes_error.py +++ b/tests/extmod/uctypes_error.py @@ -35,3 +35,9 @@ try: S.x = 1 except TypeError: print("TypeError") + +# unsupported unary op +try: + hash(S) +except TypeError: + print("TypeError") diff --git a/tests/extmod/uctypes_error.py.exp b/tests/extmod/uctypes_error.py.exp index 802c260d2b..f2e9c12f7f 100644 --- a/tests/extmod/uctypes_error.py.exp +++ b/tests/extmod/uctypes_error.py.exp @@ -2,3 +2,4 @@ TypeError TypeError TypeError TypeError +TypeError diff --git a/tests/extmod/uctypes_le.py b/tests/extmod/uctypes_le.py index f69da30b61..466191c27a 100644 --- a/tests/extmod/uctypes_le.py +++ b/tests/extmod/uctypes_le.py @@ -6,7 +6,13 @@ except ImportError: desc = { "s0": uctypes.UINT16 | 0, - "sub": (0, {"b0": uctypes.UINT8 | 0, "b1": uctypes.UINT8 | 1}), + "sub": ( + 0, + { + "b0": uctypes.UINT8 | 0, + "b1": uctypes.UINT8 | 1, + }, + ), "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "bitf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 8 << uctypes.BF_LEN, diff --git a/tests/extmod/uctypes_native_le.py b/tests/extmod/uctypes_native_le.py index 7958e5c22a..10477e6694 100644 --- a/tests/extmod/uctypes_native_le.py +++ b/tests/extmod/uctypes_native_le.py @@ -16,7 +16,13 @@ if sys.byteorder != "little": desc = { "s0": uctypes.UINT16 | 0, - "sub": (0, {"b0": uctypes.UINT8 | 0, "b1": uctypes.UINT8 | 1}), + "sub": ( + 0, + { + "b0": uctypes.UINT8 | 0, + "b1": uctypes.UINT8 | 1, + }, + ), "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "bitf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 8 << uctypes.BF_LEN, diff --git a/tests/extmod/uctypes_ptr_le.py b/tests/extmod/uctypes_ptr_le.py index a69467e62c..5d8094ee48 100644 --- a/tests/extmod/uctypes_ptr_le.py +++ b/tests/extmod/uctypes_ptr_le.py @@ -23,6 +23,9 @@ buf = addr.to_bytes(uctypes.sizeof(desc), "little") S = uctypes.struct(uctypes.addressof(buf), desc, uctypes.LITTLE_ENDIAN) +print(addr == int(S.ptr)) +print(addr == int(S.ptr2)) + print(S.ptr[0]) assert S.ptr[0] == ord("0") print(S.ptr[1]) diff --git a/tests/extmod/uctypes_ptr_le.py.exp b/tests/extmod/uctypes_ptr_le.py.exp index 30d159edd1..92f6caa069 100644 --- a/tests/extmod/uctypes_ptr_le.py.exp +++ b/tests/extmod/uctypes_ptr_le.py.exp @@ -1,3 +1,5 @@ +True +True 48 49 0x3130 diff --git a/tests/extmod/uctypes_sizeof_layout.py b/tests/extmod/uctypes_sizeof_layout.py new file mode 100644 index 0000000000..2108e81502 --- /dev/null +++ b/tests/extmod/uctypes_sizeof_layout.py @@ -0,0 +1,27 @@ +try: + import uctypes +except ImportError: + print("SKIP") + raise SystemExit + +desc = { + "f1": 0 | uctypes.UINT32, + "f2": 4 | uctypes.UINT8, +} + + +# uctypes.NATIVE is default +print(uctypes.sizeof(desc) == uctypes.sizeof(desc, uctypes.NATIVE)) + +# Here we assume that that we run on a platform with convential ABI +# (which rounds up structure size based on max alignment). For platforms +# where that doesn't hold, this tests should be just disabled in the runner. +print(uctypes.sizeof(desc, uctypes.NATIVE) > uctypes.sizeof(desc, uctypes.LITTLE_ENDIAN)) + +# When taking sizeof of instantiated structure, layout type param +# is prohibited (because structure already has its layout type). +s = uctypes.struct(0, desc, uctypes.LITTLE_ENDIAN) +try: + uctypes.sizeof(s, uctypes.LITTLE_ENDIAN) +except TypeError: + print("TypeError") diff --git a/tests/extmod/uctypes_sizeof_layout.py.exp b/tests/extmod/uctypes_sizeof_layout.py.exp new file mode 100644 index 0000000000..281f20856e --- /dev/null +++ b/tests/extmod/uctypes_sizeof_layout.py.exp @@ -0,0 +1,3 @@ +True +True +TypeError diff --git a/tests/extmod/uctypes_sizeof_native.py b/tests/extmod/uctypes_sizeof_native.py index 9aa5d84ec6..991cd25f52 100644 --- a/tests/extmod/uctypes_sizeof_native.py +++ b/tests/extmod/uctypes_sizeof_native.py @@ -10,10 +10,17 @@ assert uctypes.sizeof(S1) == 0 S2 = {"a": uctypes.UINT8 | 0} assert uctypes.sizeof(S2) == 1 -S3 = {"a": uctypes.UINT8 | 0, "b": uctypes.UINT8 | 1} +S3 = { + "a": uctypes.UINT8 | 0, + "b": uctypes.UINT8 | 1, +} assert uctypes.sizeof(S3) == 2 -S4 = {"a": uctypes.UINT8 | 0, "b": uctypes.UINT32 | 4, "c": uctypes.UINT8 | 8} +S4 = { + "a": uctypes.UINT8 | 0, + "b": uctypes.UINT32 | 4, + "c": uctypes.UINT8 | 8, +} assert uctypes.sizeof(S4) == 12 S5 = { @@ -21,7 +28,13 @@ S5 = { "b": uctypes.UINT32 | 4, "c": uctypes.UINT8 | 8, "d": uctypes.UINT32 | 0, - "sub": (4, {"b0": uctypes.UINT8 | 0, "b1": uctypes.UINT8 | 1}), + "sub": ( + 4, + { + "b0": uctypes.UINT8 | 0, + "b1": uctypes.UINT8 | 1, + }, + ), } assert uctypes.sizeof(S5) == 12 @@ -30,12 +43,18 @@ s5 = uctypes.struct(0, S5) assert uctypes.sizeof(s5) == 12 assert uctypes.sizeof(s5.sub) == 2 -S6 = {"ptr": (uctypes.PTR | 0, uctypes.UINT8)} +S6 = { + "ptr": (uctypes.PTR | 0, uctypes.UINT8), +} # As if there're no other arch bitnesses assert uctypes.sizeof(S6) in (4, 8) -S7 = {"arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 5)} +S7 = { + "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 5), +} assert uctypes.sizeof(S7) == 5 -S8 = {"arr": (uctypes.ARRAY | 0, 3, {"a": uctypes.UINT32 | 0, "b": uctypes.UINT8 | 4})} +S8 = { + "arr": (uctypes.ARRAY | 0, 3, {"a": uctypes.UINT32 | 0, "b": uctypes.UINT8 | 4}), +} assert uctypes.sizeof(S8) == 24 diff --git a/tests/extmod/uctypes_sizeof_od.py b/tests/extmod/uctypes_sizeof_od.py new file mode 100644 index 0000000000..2f070095b5 --- /dev/null +++ b/tests/extmod/uctypes_sizeof_od.py @@ -0,0 +1,53 @@ +try: + from ucollections import OrderedDict + import uctypes +except ImportError: + print("SKIP") + raise SystemExit + +desc = OrderedDict( + { + # arr is array at offset 0, of UINT8 elements, array size is 2 + "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), + # arr2 is array at offset 0, size 2, of structures defined recursively + "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), + "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), + "arr4": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0, "w": uctypes.UINT16 | 1}), + "sub": ( + 0, + { + "b1": uctypes.BFUINT8 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "b2": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + }, + ), + } +) + +data = bytearray(b"01234567") + +S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) + +print(uctypes.sizeof(S.arr)) +assert uctypes.sizeof(S.arr) == 2 + +print(uctypes.sizeof(S.arr2)) +assert uctypes.sizeof(S.arr2) == 2 + +print(uctypes.sizeof(S.arr3)) + +try: + print(uctypes.sizeof(S.arr3[0])) +except TypeError: + print("TypeError") + +print(uctypes.sizeof(S.arr4)) +assert uctypes.sizeof(S.arr4) == 6 + +print(uctypes.sizeof(S.sub)) +assert uctypes.sizeof(S.sub) == 1 + +# invalid descriptor +try: + print(uctypes.sizeof([])) +except TypeError: + print("TypeError") diff --git a/tests/extmod/uctypes_sizeof_od.py.exp b/tests/extmod/uctypes_sizeof_od.py.exp new file mode 100644 index 0000000000..b35b11aa0c --- /dev/null +++ b/tests/extmod/uctypes_sizeof_od.py.exp @@ -0,0 +1,7 @@ +2 +2 +4 +TypeError +6 +1 +TypeError diff --git a/tests/extmod/uhashlib_md5.py b/tests/extmod/uhashlib_md5.py new file mode 100644 index 0000000000..07d5f31692 --- /dev/null +++ b/tests/extmod/uhashlib_md5.py @@ -0,0 +1,21 @@ +try: + import uhashlib as hashlib +except ImportError: + try: + import hashlib + except ImportError: + # This is neither uPy, nor cPy, so must be uPy with + # uhashlib module disabled. + print("SKIP") + raise SystemExit + +try: + hashlib.md5 +except AttributeError: + # MD5 is only available on some ports + print("SKIP") + raise SystemExit + +md5 = hashlib.md5(b"hello") +md5.update(b"world") +print(md5.digest()) diff --git a/tests/extmod/ujson_dump_iobase.py b/tests/extmod/ujson_dump_iobase.py index c51994ef5d..7ecf23afb6 100644 --- a/tests/extmod/ujson_dump_iobase.py +++ b/tests/extmod/ujson_dump_iobase.py @@ -25,6 +25,7 @@ class S(io.IOBase): # uPy passes a bytearray, CPython passes a str buf = str(buf, "ascii") self.buf += buf + return len(buf) # dump to the user stream diff --git a/tests/extmod/urandom_extra.py b/tests/extmod/urandom_extra.py index 636a225394..78e17379dc 100644 --- a/tests/extmod/urandom_extra.py +++ b/tests/extmod/urandom_extra.py @@ -67,13 +67,3 @@ try: random.choice([]) except IndexError: print("IndexError") - -print("random") -for i in range(50): - assert 0 <= random.random() < 1 - -print("uniform") -for i in range(50): - assert 0 <= random.uniform(0, 4) <= 4 - assert 2 <= random.uniform(2, 6) <= 6 - assert -2 <= random.uniform(-2, 2) <= 2 diff --git a/tests/extmod/urandom_extra_float.py b/tests/extmod/urandom_extra_float.py new file mode 100644 index 0000000000..65918da136 --- /dev/null +++ b/tests/extmod/urandom_extra_float.py @@ -0,0 +1,24 @@ +try: + import urandom as random +except ImportError: + try: + import random + except ImportError: + print("SKIP") + raise SystemExit + +try: + random.randint +except AttributeError: + print("SKIP") + raise SystemExit + +print("random") +for i in range(50): + assert 0 <= random.random() < 1 + +print("uniform") +for i in range(50): + assert 0 <= random.uniform(0, 4) <= 4 + assert 2 <= random.uniform(2, 6) <= 6 + assert -2 <= random.uniform(-2, 2) <= 2 diff --git a/tests/extmod/uselect_poll_basic.py b/tests/extmod/uselect_poll_basic.py new file mode 100644 index 0000000000..ab750078d3 --- /dev/null +++ b/tests/extmod/uselect_poll_basic.py @@ -0,0 +1,36 @@ +try: + import usocket as socket, uselect as select, uerrno as errno +except ImportError: + try: + import socket, select, errno + + select.poll # Raises AttributeError for CPython implementations without poll() + except (ImportError, AttributeError): + print("SKIP") + raise SystemExit + + +poller = select.poll() + +s = socket.socket() + +poller.register(s) +# https://docs.python.org/3/library/select.html#select.poll.register +# "Registering a file descriptor that’s already registered is not an error, +# and has the same effect as registering the descriptor exactly once." +poller.register(s) + +# 2 args are mandatory unlike register() +try: + poller.modify(s) +except TypeError: + print("modify:TypeError") + +poller.modify(s, select.POLLIN) + +poller.unregister(s) + +try: + poller.modify(s, select.POLLIN) +except OSError as e: + assert e.args[0] == errno.ENOENT diff --git a/tests/extmod/vfs_fat_more.py b/tests/extmod/vfs_fat_more.py index acae8c5844..d5ecd50467 100644 --- a/tests/extmod/vfs_fat_more.py +++ b/tests/extmod/vfs_fat_more.py @@ -1,5 +1,3 @@ -import uerrno - try: import uos except ImportError: diff --git a/tests/extmod/vfs_userfs.py b/tests/extmod/vfs_userfs.py index 60bf4d0997..06e546b081 100644 --- a/tests/extmod/vfs_userfs.py +++ b/tests/extmod/vfs_userfs.py @@ -1,9 +1,11 @@ # test VFS functionality with a user-defined filesystem # also tests parts of uio.IOBase implementation -import sys, uio +import sys try: + import uio + uio.IOBase import uos diff --git a/tests/float/builtin_float_abs.py b/tests/float/builtin_float_abs.py new file mode 100644 index 0000000000..f7ce9e156f --- /dev/null +++ b/tests/float/builtin_float_abs.py @@ -0,0 +1,13 @@ +# test builtin abs function with float args + +for val in ( + "1.0", + "-1.0", + "0.0", + "-0.0", + "nan", + "-nan", + "inf", + "-inf", +): + print(val, abs(float(val))) diff --git a/tests/float/builtin_float_hash.py b/tests/float/builtin_float_hash.py index f77b1a1834..1388bb0e83 100644 --- a/tests/float/builtin_float_hash.py +++ b/tests/float/builtin_float_hash.py @@ -1,9 +1,25 @@ # test builtin hash function with float args # these should hash to an integer with a specific value -for val in ("0.0", "-0.0", "1.0", "2.0", "-12.0", "12345.0"): +for val in ( + "0.0", + "-0.0", + "1.0", + "2.0", + "-12.0", + "12345.0", +): print(val, hash(float(val))) # just check that these values are hashable -for val in ("0.1", "-0.1", "10.3", "0.4e3", "1e16", "inf", "-inf", "nan"): +for val in ( + "0.1", + "-0.1", + "10.3", + "0.4e3", + "1e16", + "inf", + "-inf", + "nan", +): print(val, type(hash(float(val)))) diff --git a/tests/float/cmath_fun.py b/tests/float/cmath_fun.py index 26f6c227cf..5622918282 100644 --- a/tests/float/cmath_fun.py +++ b/tests/float/cmath_fun.py @@ -22,7 +22,9 @@ for r in base_values: test_values_non_zero.append(complex(r, -i)) if r != 0.0 and i != 0.0: test_values_non_zero.append(complex(-r, -i)) -test_values = [complex(0.0, 0.0)] + test_values_non_zero +test_values = [ + complex(0.0, 0.0), +] + test_values_non_zero print(test_values) functions = [ @@ -54,6 +56,6 @@ for f_name, f, test_vals in functions: else: # some test (eg cmath.sqrt(-0.5)) disagree with CPython with tiny real part real = ret.real - if abs(real) < 1e15: + if abs(real) < 1e-6: real = 0.0 print("complex(%.5g, %.5g)" % (real, ret.imag)) diff --git a/tests/float/cmath_fun_special.py b/tests/float/cmath_fun_special.py index 1d9abac6b4..33b94d04db 100644 --- a/tests/float/cmath_fun_special.py +++ b/tests/float/cmath_fun_special.py @@ -21,7 +21,9 @@ for r in base_values: if r != 0.0 and i != 0.0: test_values_non_zero.append(complex(-r, -i)) -functions = [("log10", log10, test_values_non_zero)] +functions = [ + ("log10", log10, test_values_non_zero), +] for f_name, f, test_vals in functions: print(f_name) diff --git a/tests/float/float_parse.py b/tests/float/float_parse.py index bef1122ac0..de27c33e7b 100644 --- a/tests/float/float_parse.py +++ b/tests/float/float_parse.py @@ -30,3 +30,7 @@ print(float("1e4294967301")) print(float("1e-4294967301")) print(float("1e18446744073709551621")) print(float("1e-18446744073709551621")) + +# check small decimals are as close to their true value as possible +for n in range(1, 10): + print(float("0.%u" % n) == n / 10) diff --git a/tests/float/math_domain_special.py b/tests/float/math_domain_special.py index e5bfa9f032..880594dce2 100644 --- a/tests/float/math_domain_special.py +++ b/tests/float/math_domain_special.py @@ -27,7 +27,7 @@ for name, f, args in ( ("gamma", math.gamma, (-2, -1, 0, 1)), ("lgamma", math.lgamma, (-2, -1, 0, 1)), ): - for x in args + (inf, nan): + for x in args + (inf, -inf, nan): try: ans = f(x) print("%.4f" % ans) diff --git a/tests/float/math_factorial_intbig.py b/tests/float/math_factorial_intbig.py new file mode 100644 index 0000000000..a4694b3d68 --- /dev/null +++ b/tests/float/math_factorial_intbig.py @@ -0,0 +1,15 @@ +try: + import math + + math.factorial +except (ImportError, AttributeError): + print("SKIP") + raise SystemExit + + +for fun in (math.factorial,): + for x in range(-1, 30): + try: + print("%d" % fun(x)) + except ValueError as e: + print("ValueError") diff --git a/tests/float/math_fun.py b/tests/float/math_fun.py index dac57d7822..f43216c6fb 100644 --- a/tests/float/math_fun.py +++ b/tests/float/math_fun.py @@ -45,7 +45,10 @@ for function_name, function, test_vals in functions: except ValueError as e: print(str(e)) -tuple_functions = [("frexp", frexp, test_values), ("modf", modf, test_values)] +tuple_functions = [ + ("frexp", frexp, test_values), + ("modf", modf, test_values), +] for function_name, function, test_vals in tuple_functions: print(function_name) @@ -59,10 +62,64 @@ binary_functions = [ copysign, [(23.0, 42.0), (-23.0, 42.0), (23.0, -42.0), (-23.0, -42.0), (1.0, 0.0), (1.0, -0.0)], ), - ("pow", pow, ((1.0, 0.0), (0.0, 1.0), (2.0, 0.5), (-3.0, 5.0), (-3.0, -4.0))), - ("atan2", atan2, ((1.0, 0.0), (0.0, 1.0), (2.0, 0.5), (-3.0, 5.0), (-3.0, -4.0))), - ("fmod", fmod, ((1.0, 1.0), (0.0, 1.0), (2.0, 0.5), (-3.0, 5.0), (-3.0, -4.0))), - ("ldexp", ldexp, ((1.0, 0), (0.0, 1), (2.0, 2), (3.0, -2), (-3.0, -4))), + ( + "pow", + pow, + ( + (1.0, 0.0), + (0.0, 1.0), + (2.0, 0.5), + (-3.0, 5.0), + (-3.0, -4.0), + ), + ), + ( + "atan2", + atan2, + ( + (1.0, 0.0), + (0.0, 1.0), + (2.0, 0.5), + (-3.0, 5.0), + (-3.0, -4.0), + ), + ), + ( + "fmod", + fmod, + ( + (1.0, 1.0), + (0.0, 1.0), + (2.0, 0.5), + (-3.0, 5.0), + (-3.0, -4.0), + ), + ), + ( + "ldexp", + ldexp, + ( + (1.0, 0), + (0.0, 1), + (2.0, 2), + (3.0, -2), + (-3.0, -4), + ), + ), + ( + "log", + log, + ( + (2.0, 2.0), + (3.0, 2.0), + (4.0, 5.0), + (0.0, 1.0), + (1.0, 0.0), + (-1.0, 1.0), + (1.0, -1.0), + (2.0, 1.0), + ), + ), ] for function_name, function, test_vals in binary_functions: diff --git a/tests/float/math_fun_special.py b/tests/float/math_fun_special.py index f4e53e8914..8f51b29acb 100644 --- a/tests/float/math_fun_special.py +++ b/tests/float/math_fun_special.py @@ -8,8 +8,24 @@ except (ImportError, NameError): print("SKIP") raise SystemExit -test_values = [-8.0, -2.5, -1, -0.5, 0.0, 0.5, 2.5, 8.0] -pos_test_values = [0.001, 0.1, 0.5, 1.0, 1.5, 10.0] +test_values = [ + -8.0, + -2.5, + -1, + -0.5, + 0.0, + 0.5, + 2.5, + 8.0, +] +pos_test_values = [ + 0.001, + 0.1, + 0.5, + 1.0, + 1.5, + 10.0, +] functions = [ ("expm1", expm1, test_values), @@ -17,14 +33,22 @@ functions = [ ("log10", log10, test_values), ("cosh", cosh, test_values), ("sinh", sinh, test_values), - ("tanh", tanh, test_values), + ("tanh", tanh, [-1e6, -100] + test_values + [100, 1e6]), ("acosh", acosh, [1.0, 5.0, 1.0]), ("asinh", asinh, test_values), ("atanh", atanh, [-0.99, -0.5, 0.0, 0.5, 0.99]), ("erf", erf, test_values), ("erfc", erfc, test_values), ("gamma", gamma, pos_test_values), - ("lgamma", lgamma, pos_test_values + [50.0, 100.0]), + ( + "lgamma", + lgamma, + pos_test_values + + [ + 50.0, + 100.0, + ], + ), ] for function_name, function, test_vals in functions: diff --git a/tests/import/import_long_dyn.py b/tests/import/import_long_dyn.py new file mode 100644 index 0000000000..709e019f31 --- /dev/null +++ b/tests/import/import_long_dyn.py @@ -0,0 +1 @@ +from import_long_dyn2 import * diff --git a/tests/import/import_long_dyn2.py b/tests/import/import_long_dyn2.py new file mode 100644 index 0000000000..c3cb1f2469 --- /dev/null +++ b/tests/import/import_long_dyn2.py @@ -0,0 +1 @@ +globals()["long_long_very_long_long_name"] = 1 diff --git a/tests/import/module_getattr.py b/tests/import/module_getattr.py new file mode 100644 index 0000000000..df7a621815 --- /dev/null +++ b/tests/import/module_getattr.py @@ -0,0 +1,24 @@ +# test __getattr__ on module + +# ensure that does_not_exist doesn't exist to start with +this = __import__(__name__) +try: + this.does_not_exist + assert False +except AttributeError: + pass + +# define __getattr__ +def __getattr__(attr): + if attr == "does_not_exist": + return False + raise AttributeError + + +# do feature test (will also test functionality if the feature exists) +if not hasattr(this, "does_not_exist"): + print("SKIP") + raise SystemExit + +# check that __getattr__ works as expected +print(this.does_not_exist) diff --git a/tests/pyb/switch.py.exp b/tests/import/module_getattr.py.exp similarity index 100% rename from tests/pyb/switch.py.exp rename to tests/import/module_getattr.py.exp diff --git a/tests/io/open_append.py b/tests/io/open_append.py index a696823bc5..49cdd094b3 100644 --- a/tests/io/open_append.py +++ b/tests/io/open_append.py @@ -3,13 +3,13 @@ try: except ImportError: import os -if not hasattr(os, "unlink"): +if not hasattr(os, "remove"): print("SKIP") raise SystemExit # cleanup in case testfile exists try: - os.unlink("testfile") + os.remove("testfile") except OSError: pass @@ -32,6 +32,6 @@ f.close() # cleanup try: - os.unlink("testfile") + os.remove("testfile") except OSError: pass diff --git a/tests/io/open_plus.py b/tests/io/open_plus.py index bba96fa2f9..3cb2330eed 100644 --- a/tests/io/open_plus.py +++ b/tests/io/open_plus.py @@ -3,13 +3,13 @@ try: except ImportError: import os -if not hasattr(os, "unlink"): +if not hasattr(os, "remove"): print("SKIP") raise SystemExit # cleanup in case testfile exists try: - os.unlink("testfile") + os.remove("testfile") except OSError: pass @@ -42,6 +42,6 @@ f.close() # cleanup try: - os.unlink("testfile") + os.remove("testfile") except OSError: pass diff --git a/tests/micropython/heapalloc_bytesio.py b/tests/micropython/heapalloc_bytesio.py deleted file mode 100644 index 4aae2abf06..0000000000 --- a/tests/micropython/heapalloc_bytesio.py +++ /dev/null @@ -1,18 +0,0 @@ -try: - import uio -except ImportError: - print("SKIP") - raise SystemExit - -import micropython - -data = b"1234" * 16 -buf = uio.BytesIO(64) - -micropython.heap_lock() - -buf.write(data) - -micropython.heap_unlock() - -print(buf.getvalue()) diff --git a/tests/micropython/heapalloc_bytesio.py.exp b/tests/micropython/heapalloc_bytesio.py.exp deleted file mode 100644 index 675761c2bb..0000000000 --- a/tests/micropython/heapalloc_bytesio.py.exp +++ /dev/null @@ -1 +0,0 @@ -b'1234123412341234123412341234123412341234123412341234123412341234' diff --git a/tests/micropython/native_const.py b/tests/micropython/native_const.py new file mode 100644 index 0000000000..b48499550e --- /dev/null +++ b/tests/micropython/native_const.py @@ -0,0 +1,21 @@ +# test loading constants in native functions + + +@micropython.native +def f(): + return b"bytes" + + +print(f()) + + +@micropython.native +def f(): + @micropython.native + def g(): + return 123 + + return g + + +print(f()()) diff --git a/tests/micropython/native_const.py.exp b/tests/micropython/native_const.py.exp new file mode 100644 index 0000000000..9002a0c2e5 --- /dev/null +++ b/tests/micropython/native_const.py.exp @@ -0,0 +1,2 @@ +b'bytes' +123 diff --git a/tests/micropython/native_try.py b/tests/micropython/native_try.py new file mode 100644 index 0000000000..492b59085c --- /dev/null +++ b/tests/micropython/native_try.py @@ -0,0 +1,45 @@ +# test native try handling + +# basic try-finally +@micropython.native +def f(): + try: + fail + finally: + print("finally") + + +try: + f() +except NameError: + print("NameError") + +# nested try-except with try-finally +@micropython.native +def f(): + try: + try: + fail + finally: + print("finally") + except NameError: + print("NameError") + + +f() + +# check that locals written to in try blocks keep their values +@micropython.native +def f(): + a = 100 + try: + print(a) + a = 200 + fail + except NameError: + print(a) + a = 300 + print(a) + + +f() diff --git a/tests/micropython/native_try.py.exp b/tests/micropython/native_try.py.exp new file mode 100644 index 0000000000..96596ce5f5 --- /dev/null +++ b/tests/micropython/native_try.py.exp @@ -0,0 +1,7 @@ +finally +NameError +finally +NameError +100 +200 +300 diff --git a/tests/micropython/native_try_deep.py b/tests/micropython/native_try_deep.py new file mode 100644 index 0000000000..3d31248df0 --- /dev/null +++ b/tests/micropython/native_try_deep.py @@ -0,0 +1,36 @@ +# test native try handling + +# deeply nested try (9 deep) +@micropython.native +def f(): + try: + try: + try: + try: + try: + try: + try: + try: + try: + raise ValueError + finally: + print(8) + finally: + print(7) + finally: + print(6) + finally: + print(5) + finally: + print(4) + finally: + print(3) + finally: + print(2) + finally: + print(1) + except ValueError: + print("ValueError") + + +f() diff --git a/tests/micropython/native_try_deep.py.exp b/tests/micropython/native_try_deep.py.exp new file mode 100644 index 0000000000..84c6beae31 --- /dev/null +++ b/tests/micropython/native_try_deep.py.exp @@ -0,0 +1,9 @@ +8 +7 +6 +5 +4 +3 +2 +1 +ValueError diff --git a/tests/micropython/native_with.py b/tests/micropython/native_with.py new file mode 100644 index 0000000000..4e20b23856 --- /dev/null +++ b/tests/micropython/native_with.py @@ -0,0 +1,36 @@ +# test with handling within a native function + + +class C: + def __init__(self): + print("__init__") + + def __enter__(self): + print("__enter__") + + def __exit__(self, a, b, c): + print("__exit__", a, b, c) + + +# basic with +@micropython.native +def f(): + with C(): + print(1) + + +f() + +# nested with and try-except +@micropython.native +def f(): + try: + with C(): + print(1) + fail + print(2) + except NameError: + print("NameError") + + +f() diff --git a/tests/micropython/native_with.py.exp b/tests/micropython/native_with.py.exp new file mode 100644 index 0000000000..6eef7822fb --- /dev/null +++ b/tests/micropython/native_with.py.exp @@ -0,0 +1,9 @@ +__init__ +__enter__ +1 +__exit__ None None None +__init__ +__enter__ +1 +__exit__ name 'fail' is not defined None +NameError diff --git a/tests/micropython/viper_args.py b/tests/micropython/viper_args.py index 223026b963..8e3225331a 100644 --- a/tests/micropython/viper_args.py +++ b/tests/micropython/viper_args.py @@ -40,7 +40,21 @@ def f4(x1: int, x2: int, x3: int, x4: int): f4(1, 2, 3, 4) -# only up to 4 arguments currently supported + +@micropython.viper +def f5(x1: int, x2: int, x3: int, x4: int, x5: int): + print(x1, x2, x3, x4, x5) + + +f5(1, 2, 3, 4, 5) + + +@micropython.viper +def f6(x1: int, x2: int, x3: int, x4: int, x5: int, x6: int): + print(x1, x2, x3, x4, x5, x6) + + +f6(1, 2, 3, 4, 5, 6) # test compiling *x, **x, * args (currently unsupported at runtime) @micropython.viper diff --git a/tests/micropython/viper_args.py.exp b/tests/micropython/viper_args.py.exp index 0ca0f4e906..6d64c584a5 100644 --- a/tests/micropython/viper_args.py.exp +++ b/tests/micropython/viper_args.py.exp @@ -3,3 +3,5 @@ 1 2 1 2 3 1 2 3 4 +1 2 3 4 5 +1 2 3 4 5 6 diff --git a/tests/micropython/viper_cond.py b/tests/micropython/viper_cond.py index d31a5f3cf8..d5ebf837bd 100644 --- a/tests/micropython/viper_cond.py +++ b/tests/micropython/viper_cond.py @@ -29,3 +29,13 @@ def g(): g() + +# using an int as a conditional that has the lower 16-bits clear +@micropython.viper +def h(): + z = 0x10000 + if z: + print("z", z) + + +h() diff --git a/tests/micropython/viper_cond.py.exp b/tests/micropython/viper_cond.py.exp index dff7103934..beacd48fe6 100644 --- a/tests/micropython/viper_cond.py.exp +++ b/tests/micropython/viper_cond.py.exp @@ -1,3 +1,4 @@ not x False x True y 1 +z 65536 diff --git a/tests/micropython/viper_const.py b/tests/micropython/viper_const.py new file mode 100644 index 0000000000..230b282f23 --- /dev/null +++ b/tests/micropython/viper_const.py @@ -0,0 +1,21 @@ +# test loading constants in viper functions + + +@micropython.viper +def f(): + return b"bytes" + + +print(f()) + + +@micropython.viper +def f(): + @micropython.viper + def g() -> int: + return 123 + + return g + + +print(f()()) diff --git a/tests/micropython/viper_const.py.exp b/tests/micropython/viper_const.py.exp new file mode 100644 index 0000000000..9002a0c2e5 --- /dev/null +++ b/tests/micropython/viper_const.py.exp @@ -0,0 +1,2 @@ +b'bytes' +123 diff --git a/tests/micropython/viper_const_intbig.py b/tests/micropython/viper_const_intbig.py new file mode 100644 index 0000000000..42574820a3 --- /dev/null +++ b/tests/micropython/viper_const_intbig.py @@ -0,0 +1,9 @@ +# check loading constants + + +@micropython.viper +def f(): + return 123456789012345678901234567890 + + +print(f()) diff --git a/tests/micropython/viper_const_intbig.py.exp b/tests/micropython/viper_const_intbig.py.exp new file mode 100644 index 0000000000..1d52d220f8 --- /dev/null +++ b/tests/micropython/viper_const_intbig.py.exp @@ -0,0 +1 @@ +123456789012345678901234567890 diff --git a/tests/micropython/viper_error.py b/tests/micropython/viper_error.py index fa136197d7..790f3d75c4 100644 --- a/tests/micropython/viper_error.py +++ b/tests/micropython/viper_error.py @@ -15,9 +15,6 @@ test("@micropython.viper\ndef f() -> 1: pass") # unknown type test("@micropython.viper\ndef f(x:unknown_type): pass") -# too many arguments -test("@micropython.viper\ndef f(a, b, c, d, e): pass") - # local used before type known test( """ diff --git a/tests/micropython/viper_error.py.exp b/tests/micropython/viper_error.py.exp index 3a8cb02994..da9a0ca93e 100644 --- a/tests/micropython/viper_error.py.exp +++ b/tests/micropython/viper_error.py.exp @@ -1,7 +1,6 @@ -SyntaxError('parameter annotation must be an identifier',) -SyntaxError('return annotation must be an identifier',) +SyntaxError('annotation must be an identifier',) +SyntaxError('annotation must be an identifier',) ViperTypeError("unknown type 'unknown_type'",) -ViperTypeError("Viper functions don't currently support more than 4 arguments",) ViperTypeError("local 'x' used before type known",) ViperTypeError("local 'x' has type 'int' but source is 'object'",) ViperTypeError("can't implicitly convert 'ptr' to 'bool'",) diff --git a/tests/micropython/viper_globals.py b/tests/micropython/viper_globals.py new file mode 100644 index 0000000000..9532dfd895 --- /dev/null +++ b/tests/micropython/viper_globals.py @@ -0,0 +1,22 @@ +# test that viper functions capture their globals context + +gl = {} + +exec( + """ +@micropython.viper +def f(): + return x +""", + gl, +) + +# x is not yet in the globals, f should not see it +try: + print(gl["f"]()) +except NameError: + print("NameError") + +# x is in globals, f should now see it +gl["x"] = 123 +print(gl["f"]()) diff --git a/tests/micropython/viper_globals.py.exp b/tests/micropython/viper_globals.py.exp new file mode 100644 index 0000000000..5731b89c1b --- /dev/null +++ b/tests/micropython/viper_globals.py.exp @@ -0,0 +1,2 @@ +NameError +123 diff --git a/tests/micropython/viper_try.py b/tests/micropython/viper_try.py new file mode 100644 index 0000000000..61335af221 --- /dev/null +++ b/tests/micropython/viper_try.py @@ -0,0 +1,45 @@ +# test try handling within a viper function + +# basic try-finally +@micropython.viper +def f(): + try: + fail + finally: + print("finally") + + +try: + f() +except NameError: + print("NameError") + +# nested try-except with try-finally +@micropython.viper +def f(): + try: + try: + fail + finally: + print("finally") + except NameError: + print("NameError") + + +f() + +# check that locals written to in try blocks keep their values +@micropython.viper +def f(): + a = 100 + try: + print(a) + a = 200 + fail + except NameError: + print(a) + a = 300 + print(a) + + +f() diff --git a/tests/micropython/viper_try.py.exp b/tests/micropython/viper_try.py.exp new file mode 100644 index 0000000000..96596ce5f5 --- /dev/null +++ b/tests/micropython/viper_try.py.exp @@ -0,0 +1,7 @@ +finally +NameError +finally +NameError +100 +200 +300 diff --git a/tests/micropython/viper_with.py b/tests/micropython/viper_with.py new file mode 100644 index 0000000000..d640c8ae0f --- /dev/null +++ b/tests/micropython/viper_with.py @@ -0,0 +1,36 @@ +# test with handling within a viper function + + +class C: + def __init__(self): + print("__init__") + + def __enter__(self): + print("__enter__") + + def __exit__(self, a, b, c): + print("__exit__", a, b, c) + + +# basic with +@micropython.viper +def f(): + with C(): + print(1) + + +f() + +# nested with and try-except +@micropython.viper +def f(): + try: + with C(): + print(1) + fail + print(2) + except NameError: + print("NameError") + + +f() diff --git a/tests/micropython/viper_with.py.exp b/tests/micropython/viper_with.py.exp new file mode 100644 index 0000000000..6eef7822fb --- /dev/null +++ b/tests/micropython/viper_with.py.exp @@ -0,0 +1,9 @@ +__init__ +__enter__ +1 +__exit__ None None None +__init__ +__enter__ +1 +__exit__ name 'fail' is not defined None +NameError diff --git a/tests/misc/features.py b/tests/misc/features.py index 419d8795f9..455b44fb1e 100644 --- a/tests/misc/features.py +++ b/tests/misc/features.py @@ -1,3 +1,9 @@ +try: + str.count +except AttributeError: + print("SKIP") + raise SystemExit + # mad.py # Alf Clement 27-Mar-2014 # diff --git a/tests/misc/print_exception.py b/tests/misc/print_exception.py index 11ed320f60..edb3045878 100644 --- a/tests/misc/print_exception.py +++ b/tests/misc/print_exception.py @@ -35,7 +35,7 @@ def print_exc(e): # basic exception message try: - 1 / 0 + raise Exception("msg") except Exception as e: print("caught") print_exc(e) @@ -46,7 +46,7 @@ def f(): def g(): - 2 / 0 + raise Exception("fail") try: @@ -58,7 +58,7 @@ except Exception as e: # Here we have a function with lots of bytecode generated for a single source-line, and # there is an error right at the end of the bytecode. It should report the correct line. def f(): - f([1, 2], [1, 2], [1, 2], {1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: X}) + f([1, 2], [1, 2], [1, 2], {1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: f.X}) return 1 diff --git a/tests/pyb/accel.py b/tests/pyb/accel.py deleted file mode 100644 index e5a1a2ed7a..0000000000 --- a/tests/pyb/accel.py +++ /dev/null @@ -1,9 +0,0 @@ -import pyb - -accel = pyb.Accel() -print(accel) -accel.x() -accel.y() -accel.z() -accel.tilt() -accel.filtered_xyz() diff --git a/tests/pyb/accel.py.exp b/tests/pyb/accel.py.exp deleted file mode 100644 index 28070be177..0000000000 --- a/tests/pyb/accel.py.exp +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/pyb/adc.py b/tests/pyb/adc.py deleted file mode 100644 index fff5a3019e..0000000000 --- a/tests/pyb/adc.py +++ /dev/null @@ -1,63 +0,0 @@ -from pyb import ADC, Timer - -adct = ADC(16) # Temperature 930 -> 20C -print(adct) -adcv = ADC(17) # Voltage 1500 -> 3.3V -print(adcv) - -# read single sample; 2.5V-5V is pass range -val = adcv.read() -assert val > 1000 and val < 2000 - -# timer for read_timed -tim = Timer(5, freq=500) - -# read into bytearray -buf = bytearray(b"\xff" * 50) -adcv.read_timed(buf, tim) -print(len(buf)) -for i in buf: - assert i > 50 and i < 150 - -# read into arrays with different element sizes -import array - -arv = array.array("h", 25 * [0x7FFF]) -adcv.read_timed(arv, tim) -print(len(arv)) -for i in arv: - assert i > 1000 and i < 2000 - -arv = array.array("i", 30 * [-1]) -adcv.read_timed(arv, tim) -print(len(arv)) -for i in arv: - assert i > 1000 and i < 2000 - -# Test read_timed_multi -arv = bytearray(b"\xff" * 50) -art = bytearray(b"\xff" * 50) -ADC.read_timed_multi((adcv, adct), (arv, art), tim) -for i in arv: - assert i > 60 and i < 125 -# Wide range: unsure of accuracy of temp sensor. -for i in art: - assert i > 15 and i < 200 - -arv = array.array("i", 25 * [-1]) -art = array.array("i", 25 * [-1]) -ADC.read_timed_multi((adcv, adct), (arv, art), tim) -for i in arv: - assert i > 1000 and i < 2000 -# Wide range: unsure of accuracy of temp sensor. -for i in art: - assert i > 50 and i < 2000 - -arv = array.array("h", 25 * [0x7FFF]) -art = array.array("h", 25 * [0x7FFF]) -ADC.read_timed_multi((adcv, adct), (arv, art), tim) -for i in arv: - assert i > 1000 and i < 2000 -# Wide range: unsure of accuracy of temp sensor. -for i in art: - assert i > 50 and i < 2000 diff --git a/tests/pyb/adc.py.exp b/tests/pyb/adc.py.exp deleted file mode 100644 index 1aae16fb01..0000000000 --- a/tests/pyb/adc.py.exp +++ /dev/null @@ -1,5 +0,0 @@ - - -50 -25 -30 diff --git a/tests/pyb/adcall.py b/tests/pyb/adcall.py deleted file mode 100644 index cfe179a97b..0000000000 --- a/tests/pyb/adcall.py +++ /dev/null @@ -1,31 +0,0 @@ -from pyb import Pin, ADCAll - -pins = [Pin.cpu.A0, Pin.cpu.A1, Pin.cpu.A2, Pin.cpu.A3] - -# set pins to IN mode, init ADCAll, then check pins are ANALOG -for p in pins: - p.init(p.IN) -adc = ADCAll(12) -for p in pins: - print(p) - -# set pins to IN mode, init ADCAll with mask, then check some pins are ANALOG -for p in pins: - p.init(p.IN) -adc = ADCAll(12, 0x70003) -for p in pins: - print(p) - -# init all pins to ANALOG -adc = ADCAll(12) -print(adc) - -# read all channels -for c in range(19): - print(type(adc.read_channel(c))) - -# call special reading functions -print(0 < adc.read_core_temp() < 100) -print(0 < adc.read_core_vbat() < 4) -print(0 < adc.read_core_vref() < 2) -print(0 < adc.read_vref() < 4) diff --git a/tests/pyb/adcall.py.exp b/tests/pyb/adcall.py.exp deleted file mode 100644 index 5a85ba770e..0000000000 --- a/tests/pyb/adcall.py.exp +++ /dev/null @@ -1,32 +0,0 @@ -Pin(Pin.cpu.A0, mode=Pin.ANALOG) -Pin(Pin.cpu.A1, mode=Pin.ANALOG) -Pin(Pin.cpu.A2, mode=Pin.ANALOG) -Pin(Pin.cpu.A3, mode=Pin.ANALOG) -Pin(Pin.cpu.A0, mode=Pin.ANALOG) -Pin(Pin.cpu.A1, mode=Pin.ANALOG) -Pin(Pin.cpu.A2, mode=Pin.IN) -Pin(Pin.cpu.A3, mode=Pin.IN) - - - - - - - - - - - - - - - - - - - - -True -True -True -True diff --git a/tests/pyb/can.py b/tests/pyb/can.py deleted file mode 100644 index 7d27318d86..0000000000 --- a/tests/pyb/can.py +++ /dev/null @@ -1,314 +0,0 @@ -try: - from pyb import CAN -except ImportError: - print("SKIP") - raise SystemExit - -from array import array -import micropython -import pyb - -# test we can correctly create by id or name -for bus in (-1, 0, 1, 2, 3, "YA", "YB", "YC"): - try: - CAN(bus, CAN.LOOPBACK) - print("CAN", bus) - except ValueError: - print("ValueError", bus) -CAN(1).deinit() - -CAN.initfilterbanks(14) -can = CAN(1) -print(can) - -# Test state when de-init'd -print(can.state() == can.STOPPED) - -can.init(CAN.LOOPBACK) -print(can) -print(can.any(0)) - -# Test state when freshly created -print(can.state() == can.ERROR_ACTIVE) - -# Test that restart can be called -can.restart() - -# Test info returns a sensible value -print(can.info()) - -# Catch all filter -can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) - -can.send("abcd", 123, timeout=5000) -print(can.any(0), can.info()) -print(can.recv(0)) - -can.send("abcd", -1, timeout=5000) -print(can.recv(0)) - -can.send("abcd", 0x7FF + 1, timeout=5000) -print(can.recv(0)) - -# Test too long message -try: - can.send("abcdefghi", 0x7FF, timeout=5000) -except ValueError: - print("passed") -else: - print("failed") - -# Test that recv can work without allocating memory on the heap - -buf = bytearray(10) -l = [0, 0, 0, memoryview(buf)] -l2 = None - -micropython.heap_lock() - -can.send("", 42) -l2 = can.recv(0, l) -assert l is l2 -print(l, len(l[3]), buf) - -can.send("1234", 42) -l2 = can.recv(0, l) -assert l is l2 -print(l, len(l[3]), buf) - -can.send("01234567", 42) -l2 = can.recv(0, l) -assert l is l2 -print(l, len(l[3]), buf) - -can.send("abc", 42) -l2 = can.recv(0, l) -assert l is l2 -print(l, len(l[3]), buf) - -micropython.heap_unlock() - -# Test that recv can work with different arrays behind the memoryview -can.send("abc", 1) -print(bytes(can.recv(0, [0, 0, 0, memoryview(array("B", range(8)))])[3])) -can.send("def", 1) -print(bytes(can.recv(0, [0, 0, 0, memoryview(array("b", range(8)))])[3])) - -# Test for non-list passed as second arg to recv -can.send("abc", 1) -try: - can.recv(0, 1) -except TypeError: - print("TypeError") - -# Test for too-short-list passed as second arg to recv -can.send("abc", 1) -try: - can.recv(0, [0, 0, 0]) -except ValueError: - print("ValueError") - -# Test for non-memoryview passed as 4th element to recv -can.send("abc", 1) -try: - can.recv(0, [0, 0, 0, 0]) -except TypeError: - print("TypeError") - -# Test for read-only-memoryview passed as 4th element to recv -can.send("abc", 1) -try: - can.recv(0, [0, 0, 0, memoryview(bytes(8))]) -except ValueError: - print("ValueError") - -# Test for bad-typecode-memoryview passed as 4th element to recv -can.send("abc", 1) -try: - can.recv(0, [0, 0, 0, memoryview(array("i", range(8)))]) -except ValueError: - print("ValueError") - -del can - -# Testing extended IDs -can = CAN(1, CAN.LOOPBACK, extframe=True) -# Catch all filter -can.setfilter(0, CAN.MASK32, 0, (0, 0)) - -print(can) - -try: - can.send("abcde", 0x7FF + 1, timeout=5000) -except ValueError: - print("failed") -else: - r = can.recv(0) - if r[0] == 0x7FF + 1 and r[3] == b"abcde": - print("passed") - else: - print("failed, wrong data received") - -# Test filters -for n in [0, 8, 16, 24]: - filter_id = 0b00001000 << n - filter_mask = 0b00011100 << n - id_ok = 0b00001010 << n - id_fail = 0b00011010 << n - - can.clearfilter(0) - can.setfilter(0, pyb.CAN.MASK32, 0, (filter_id, filter_mask)) - - can.send("ok", id_ok, timeout=3) - if can.any(0): - msg = can.recv(0) - print((hex(filter_id), hex(filter_mask), hex(msg[0]), msg[3])) - - can.send("fail", id_fail, timeout=3) - if can.any(0): - msg = can.recv(0) - print((hex(filter_id), hex(filter_mask), hex(msg[0]), msg[3])) - -del can - -# Test RxCallbacks -can = CAN(1, CAN.LOOPBACK) -can.setfilter(0, CAN.LIST16, 0, (1, 2, 3, 4)) -can.setfilter(1, CAN.LIST16, 1, (5, 6, 7, 8)) - - -def cb0(bus, reason): - print("cb0") - if reason == 0: - print("pending") - if reason == 1: - print("full") - if reason == 2: - print("overflow") - - -def cb1(bus, reason): - print("cb1") - if reason == 0: - print("pending") - if reason == 1: - print("full") - if reason == 2: - print("overflow") - - -def cb0a(bus, reason): - print("cb0a") - if reason == 0: - print("pending") - if reason == 1: - print("full") - if reason == 2: - print("overflow") - - -def cb1a(bus, reason): - print("cb1a") - if reason == 0: - print("pending") - if reason == 1: - print("full") - if reason == 2: - print("overflow") - - -can.rxcallback(0, cb0) -can.rxcallback(1, cb1) - -can.send("11111111", 1, timeout=5000) -can.send("22222222", 2, timeout=5000) -can.send("33333333", 3, timeout=5000) -can.rxcallback(0, cb0a) -can.send("44444444", 4, timeout=5000) - -can.send("55555555", 5, timeout=5000) -can.send("66666666", 6, timeout=5000) -can.send("77777777", 7, timeout=5000) -can.rxcallback(1, cb1a) -can.send("88888888", 8, timeout=5000) - -print(can.recv(0)) -print(can.recv(0)) -print(can.recv(0)) -print(can.recv(1)) -print(can.recv(1)) -print(can.recv(1)) - -can.send("11111111", 1, timeout=5000) -can.send("55555555", 5, timeout=5000) - -print(can.recv(0)) -print(can.recv(1)) - -del can - -# Testing asynchronous send -can = CAN(1, CAN.LOOPBACK) -can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) - -while can.any(0): - can.recv(0) - -can.send("abcde", 1, timeout=0) -print(can.any(0)) -while not can.any(0): - pass - -print(can.recv(0)) - -try: - can.send("abcde", 2, timeout=0) - can.send("abcde", 3, timeout=0) - can.send("abcde", 4, timeout=0) - can.send("abcde", 5, timeout=0) -except OSError as e: - if str(e) == "16": - print("passed") - else: - print("failed") - -pyb.delay(500) -while can.any(0): - print(can.recv(0)) - -# Testing rtr messages -bus1 = CAN(1, CAN.LOOPBACK) -bus2 = CAN(2, CAN.LOOPBACK, extframe=True) -while bus1.any(0): - bus1.recv(0) -while bus2.any(0): - bus2.recv(0) -bus1.setfilter(0, CAN.LIST16, 0, (1, 2, 3, 4)) -bus1.setfilter(1, CAN.LIST16, 0, (5, 6, 7, 8), rtr=(True, True, True, True)) -bus1.setfilter(2, CAN.MASK16, 0, (64, 64, 32, 32), rtr=(False, True)) -bus2.setfilter(0, CAN.LIST32, 0, (1, 2), rtr=(True, True)) -bus2.setfilter(1, CAN.LIST32, 0, (3, 4), rtr=(True, False)) -bus2.setfilter(2, CAN.MASK32, 0, (16, 16), rtr=(False,)) -bus2.setfilter(2, CAN.MASK32, 0, (32, 32), rtr=(True,)) - -bus1.send("", 1, rtr=True) -print(bus1.any(0)) -bus1.send("", 5, rtr=True) -print(bus1.recv(0)) -bus1.send("", 6, rtr=True) -print(bus1.recv(0)) -bus1.send("", 7, rtr=True) -print(bus1.recv(0)) -bus1.send("", 16, rtr=True) -print(bus1.any(0)) -bus1.send("", 32, rtr=True) -print(bus1.recv(0)) - -bus2.send("", 1, rtr=True) -print(bus2.recv(0)) -bus2.send("", 2, rtr=True) -print(bus2.recv(0)) -bus2.send("", 3, rtr=True) -print(bus2.recv(0)) -bus2.send("", 4, rtr=True) -print(bus2.any(0)) diff --git a/tests/pyb/can.py.exp b/tests/pyb/can.py.exp deleted file mode 100644 index 687935e7f4..0000000000 --- a/tests/pyb/can.py.exp +++ /dev/null @@ -1,76 +0,0 @@ -ValueError -1 -ValueError 0 -CAN 1 -CAN 2 -ValueError 3 -CAN YA -CAN YB -ValueError YC -CAN(1) -True -CAN(1, CAN.LOOPBACK, extframe=False, auto_restart=False) -False -True -[0, 0, 0, 0, 0, 0, 0, 0] -True [0, 0, 0, 0, 0, 0, 1, 0] -(123, False, 0, b'abcd') -(2047, False, 0, b'abcd') -(0, False, 0, b'abcd') -passed -[42, False, 0, ] 0 bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') -[42, False, 0, ] 4 bytearray(b'1234\x00\x00\x00\x00\x00\x00') -[42, False, 0, ] 8 bytearray(b'01234567\x00\x00') -[42, False, 0, ] 3 bytearray(b'abc34567\x00\x00') -b'abc' -b'def' -TypeError -ValueError -TypeError -ValueError -ValueError -CAN(1, CAN.LOOPBACK, extframe=True, auto_restart=False) -passed -('0x8', '0x1c', '0xa', b'ok') -('0x800', '0x1c00', '0xa00', b'ok') -('0x80000', '0x1c0000', '0xa0000', b'ok') -('0x8000000', '0x1c000000', '0xa000000', b'ok') -cb0 -pending -cb0 -full -cb0a -overflow -cb1 -pending -cb1 -full -cb1a -overflow -(1, False, 0, b'11111111') -(2, False, 1, b'22222222') -(4, False, 3, b'44444444') -(5, False, 0, b'55555555') -(6, False, 1, b'66666666') -(8, False, 3, b'88888888') -cb0a -pending -cb1a -pending -(1, False, 0, b'11111111') -(5, False, 0, b'55555555') -False -(1, False, 0, b'abcde') -passed -(2, False, 0, b'abcde') -(3, False, 0, b'abcde') -(4, False, 0, b'abcde') -False -(5, True, 4, b'') -(6, True, 5, b'') -(7, True, 6, b'') -False -(32, True, 9, b'') -(1, True, 0, b'') -(2, True, 1, b'') -(3, True, 2, b'') -False diff --git a/tests/pyb/dac.py b/tests/pyb/dac.py deleted file mode 100644 index 506cf272b3..0000000000 --- a/tests/pyb/dac.py +++ /dev/null @@ -1,18 +0,0 @@ -import pyb - -if not hasattr(pyb, "DAC"): - print("SKIP") - raise SystemExit - -dac = pyb.DAC(1) -print(dac) -dac.noise(100) -dac.triangle(100) -dac.write(0) -dac.write_timed(bytearray(10), 100, mode=pyb.DAC.NORMAL) -pyb.delay(20) -dac.write(0) - -# test buffering arg -dac = pyb.DAC(1, buffering=True) -dac.write(0) diff --git a/tests/pyb/dac.py.exp b/tests/pyb/dac.py.exp deleted file mode 100644 index 7ee99652a8..0000000000 --- a/tests/pyb/dac.py.exp +++ /dev/null @@ -1 +0,0 @@ -DAC(1, bits=8) diff --git a/tests/pyb/extint.py b/tests/pyb/extint.py deleted file mode 100644 index 927b2bceba..0000000000 --- a/tests/pyb/extint.py +++ /dev/null @@ -1,17 +0,0 @@ -import pyb - -# test basic functionality -ext = pyb.ExtInt("Y1", pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l: print("line:", l)) -ext.disable() -ext.enable() -print(ext.line()) -ext.swint() - -# test swint while disabled, then again after re-enabled -ext.disable() -ext.swint() -ext.enable() -ext.swint() - -# disable now that the test is finished -ext.disable() diff --git a/tests/pyb/extint.py.exp b/tests/pyb/extint.py.exp deleted file mode 100644 index 1f9da9844a..0000000000 --- a/tests/pyb/extint.py.exp +++ /dev/null @@ -1,3 +0,0 @@ -6 -line: 6 -line: 6 diff --git a/tests/pyb/halerror.py.exp b/tests/pyb/halerror.py.exp deleted file mode 100644 index 0f3f26253d..0000000000 --- a/tests/pyb/halerror.py.exp +++ /dev/null @@ -1,2 +0,0 @@ -OSError(5,) -OSError(110,) diff --git a/tests/pyb/i2c_error.py.exp b/tests/pyb/i2c_error.py.exp deleted file mode 100644 index bd403f7f47..0000000000 --- a/tests/pyb/i2c_error.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -OSError(5,) -OSError(5,) -OSError(5,) -OSError(5,) diff --git a/tests/pyb/irq.py b/tests/pyb/irq.py deleted file mode 100644 index 04e70a7b79..0000000000 --- a/tests/pyb/irq.py +++ /dev/null @@ -1,24 +0,0 @@ -import pyb - - -def test_irq(): - # test basic disable/enable - i1 = pyb.disable_irq() - print(i1) - pyb.enable_irq() # by default should enable IRQ - - # check that interrupts are enabled by waiting for ticks - pyb.delay(10) - - # check nested disable/enable - i1 = pyb.disable_irq() - i2 = pyb.disable_irq() - print(i1, i2) - pyb.enable_irq(i2) - pyb.enable_irq(i1) - - # check that interrupts are enabled by waiting for ticks - pyb.delay(10) - - -test_irq() diff --git a/tests/pyb/irq.py.exp b/tests/pyb/irq.py.exp deleted file mode 100644 index aea065f045..0000000000 --- a/tests/pyb/irq.py.exp +++ /dev/null @@ -1,2 +0,0 @@ -True -True False diff --git a/tests/pyb/led.py b/tests/pyb/led.py deleted file mode 100644 index d2a17ebc9a..0000000000 --- a/tests/pyb/led.py +++ /dev/null @@ -1,40 +0,0 @@ -import pyb -from pyb import LED - -l1 = pyb.LED(1) -l2 = pyb.LED(2) -l3 = pyb.LED(3) -l4 = pyb.LED(4) - -leds = [LED(i) for i in range(1, 5)] -pwm_leds = leds[2:] - -# test printing -for l in leds: - print(l) - -# test on and off -for l in leds: - l.on() - assert l.intensity() == 255 - pyb.delay(100) - l.off() - assert l.intensity() == 0 - pyb.delay(100) - -# test toggle -for l in 2 * leds: - l.toggle() - assert l.intensity() in (0, 255) - pyb.delay(100) - -# test intensity -for l in pwm_leds: - for i in range(256): - l.intensity(i) - assert l.intensity() == i - pyb.delay(1) - for i in range(255, -1, -1): - l.intensity(i) - assert l.intensity() == i - pyb.delay(1) diff --git a/tests/pyb/led.py.exp b/tests/pyb/led.py.exp deleted file mode 100644 index 4e8d856cd9..0000000000 --- a/tests/pyb/led.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -LED(1) -LED(2) -LED(3) -LED(4) diff --git a/tests/pyb/modstm.py b/tests/pyb/modstm.py deleted file mode 100644 index f1e147c052..0000000000 --- a/tests/pyb/modstm.py +++ /dev/null @@ -1,13 +0,0 @@ -# test stm module - -import stm -import pyb - -# test storing a full 32-bit number -# turn on then off the A15(=yellow) LED -BSRR = 0x18 -stm.mem32[stm.GPIOA + BSRR] = 0x00008000 -pyb.delay(100) -print(hex(stm.mem32[stm.GPIOA + stm.GPIO_ODR] & 0x00008000)) -stm.mem32[stm.GPIOA + BSRR] = 0x80000000 -print(hex(stm.mem32[stm.GPIOA + stm.GPIO_ODR] & 0x00008000)) diff --git a/tests/pyb/modstm.py.exp b/tests/pyb/modstm.py.exp deleted file mode 100644 index a24c9f8657..0000000000 --- a/tests/pyb/modstm.py.exp +++ /dev/null @@ -1,2 +0,0 @@ -0x8000 -0x0 diff --git a/tests/pyb/modtime.py b/tests/pyb/modtime.py deleted file mode 100644 index 1f5b5f32fe..0000000000 --- a/tests/pyb/modtime.py +++ /dev/null @@ -1,76 +0,0 @@ -import time - -DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] - - -def is_leap(year): - return (year % 4) == 0 - - -def test(): - seconds = 0 - wday = 5 # Jan 1, 2000 was a Saturday - for year in range(2000, 2034): - print("Testing %d" % year) - yday = 1 - for month in range(1, 13): - if month == 2 and is_leap(year): - DAYS_PER_MONTH[2] = 29 - else: - DAYS_PER_MONTH[2] = 28 - for day in range(1, DAYS_PER_MONTH[month] + 1): - secs = time.mktime((year, month, day, 0, 0, 0, 0, 0)) - if secs != seconds: - print( - "mktime failed for %d-%02d-%02d got %d expected %d" - % (year, month, day, secs, seconds) - ) - tuple = time.localtime(seconds) - secs = time.mktime(tuple) - if secs != seconds: - print( - "localtime failed for %d-%02d-%02d got %d expected %d" - % (year, month, day, secs, seconds) - ) - return - seconds += 86400 - if yday != tuple[7]: - print( - "locatime for %d-%02d-%02d got yday %d, expecting %d" - % (year, month, day, tuple[7], yday) - ) - return - if wday != tuple[6]: - print( - "locatime for %d-%02d-%02d got wday %d, expecting %d" - % (year, month, day, tuple[6], wday) - ) - return - yday += 1 - wday = (wday + 1) % 7 - - -def spot_test(seconds, expected_time): - actual_time = time.localtime(seconds) - for i in range(len(actual_time)): - if actual_time[i] != expected_time[i]: - print( - "time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time - ) - return - print("time.localtime(", seconds, ") returned", actual_time, "(pass)") - - -test() -spot_test(0, (2000, 1, 1, 0, 0, 0, 5, 1)) -spot_test(1, (2000, 1, 1, 0, 0, 1, 5, 1)) -spot_test(59, (2000, 1, 1, 0, 0, 59, 5, 1)) -spot_test(60, (2000, 1, 1, 0, 1, 0, 5, 1)) -spot_test(3599, (2000, 1, 1, 0, 59, 59, 5, 1)) -spot_test(3600, (2000, 1, 1, 1, 0, 0, 5, 1)) -spot_test(-1, (1999, 12, 31, 23, 59, 59, 4, 365)) -spot_test(447549467, (2014, 3, 7, 23, 17, 47, 4, 66)) -spot_test(-940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) -spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) -spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) -spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) diff --git a/tests/pyb/modtime.py.exp b/tests/pyb/modtime.py.exp deleted file mode 100644 index 3e1f6e920c..0000000000 --- a/tests/pyb/modtime.py.exp +++ /dev/null @@ -1,46 +0,0 @@ -Testing 2000 -Testing 2001 -Testing 2002 -Testing 2003 -Testing 2004 -Testing 2005 -Testing 2006 -Testing 2007 -Testing 2008 -Testing 2009 -Testing 2010 -Testing 2011 -Testing 2012 -Testing 2013 -Testing 2014 -Testing 2015 -Testing 2016 -Testing 2017 -Testing 2018 -Testing 2019 -Testing 2020 -Testing 2021 -Testing 2022 -Testing 2023 -Testing 2024 -Testing 2025 -Testing 2026 -Testing 2027 -Testing 2028 -Testing 2029 -Testing 2030 -Testing 2031 -Testing 2032 -Testing 2033 -time.localtime( 0 ) returned (2000, 1, 1, 0, 0, 0, 5, 1) (pass) -time.localtime( 1 ) returned (2000, 1, 1, 0, 0, 1, 5, 1) (pass) -time.localtime( 59 ) returned (2000, 1, 1, 0, 0, 59, 5, 1) (pass) -time.localtime( 60 ) returned (2000, 1, 1, 0, 1, 0, 5, 1) (pass) -time.localtime( 3599 ) returned (2000, 1, 1, 0, 59, 59, 5, 1) (pass) -time.localtime( 3600 ) returned (2000, 1, 1, 1, 0, 0, 5, 1) (pass) -time.localtime( -1 ) returned (1999, 12, 31, 23, 59, 59, 4, 365) (pass) -time.localtime( 447549467 ) returned (2014, 3, 7, 23, 17, 47, 4, 66) (pass) -time.localtime( -940984933 ) returned (1970, 3, 7, 23, 17, 47, 5, 66) (pass) -time.localtime( -1072915199 ) returned (1966, 1, 1, 0, 0, 1, 5, 1) (pass) -time.localtime( -1072915200 ) returned (1966, 1, 1, 0, 0, 0, 5, 1) (pass) -time.localtime( -1072915201 ) returned (1965, 12, 31, 23, 59, 59, 4, 365) (pass) diff --git a/tests/pyb/pin.py b/tests/pyb/pin.py deleted file mode 100644 index c5a4443321..0000000000 --- a/tests/pyb/pin.py +++ /dev/null @@ -1,33 +0,0 @@ -from pyb import Pin - -p = Pin("Y1", Pin.IN) -print(p) -print(p.name()) -print(p.pin()) -print(p.port()) - -p = Pin("Y1", Pin.IN, Pin.PULL_UP) -p = Pin("Y1", Pin.IN, pull=Pin.PULL_UP) -p = Pin("Y1", mode=Pin.IN, pull=Pin.PULL_UP) -print(p) -print(p.value()) - -p.init(p.IN, p.PULL_DOWN) -p.init(p.IN, pull=p.PULL_DOWN) -p.init(mode=p.IN, pull=p.PULL_DOWN) -print(p) -print(p.value()) - -p.init(p.OUT_PP) -p.low() -print(p.value()) -p.high() -print(p.value()) -p.value(0) -print(p.value()) -p.value(1) -print(p.value()) -p.value(False) -print(p.value()) -p.value(True) -print(p.value()) diff --git a/tests/pyb/pin.py.exp b/tests/pyb/pin.py.exp deleted file mode 100644 index f2f7038fd4..0000000000 --- a/tests/pyb/pin.py.exp +++ /dev/null @@ -1,14 +0,0 @@ -Pin(Pin.cpu.C6, mode=Pin.IN) -C6 -6 -2 -Pin(Pin.cpu.C6, mode=Pin.IN, pull=Pin.PULL_UP) -1 -Pin(Pin.cpu.C6, mode=Pin.IN, pull=Pin.PULL_DOWN) -0 -0 -1 -0 -1 -0 -1 diff --git a/tests/pyb/pyb1.py b/tests/pyb/pyb1.py deleted file mode 100644 index e9626ecf4e..0000000000 --- a/tests/pyb/pyb1.py +++ /dev/null @@ -1,39 +0,0 @@ -# basic tests of pyb module - -import pyb - -# test delay - -pyb.delay(-1) -pyb.delay(0) -pyb.delay(1) - -start = pyb.millis() -pyb.delay(17) -print((pyb.millis() - start) // 5) # should print 3 - -# test udelay - -pyb.udelay(-1) -pyb.udelay(0) -pyb.udelay(1) - -start = pyb.millis() -pyb.udelay(17000) -print((pyb.millis() - start) // 5) # should print 3 - -# other - -pyb.disable_irq() -pyb.enable_irq() - -print(pyb.have_cdc()) - -pyb.sync() - -print(len(pyb.unique_id())) - -pyb.wfi() - -pyb.fault_debug(True) -pyb.fault_debug(False) diff --git a/tests/pyb/pyb1.py.exp b/tests/pyb/pyb1.py.exp deleted file mode 100644 index 5816ea967b..0000000000 --- a/tests/pyb/pyb1.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -3 -3 -True -12 diff --git a/tests/pyb/pyb_f405.py b/tests/pyb/pyb_f405.py deleted file mode 100644 index 6ca943dcea..0000000000 --- a/tests/pyb/pyb_f405.py +++ /dev/null @@ -1,10 +0,0 @@ -# test pyb module on F405 MCUs - -import os, pyb - -if not "STM32F405" in os.uname().machine: - print("SKIP") - raise SystemExit - -print(pyb.freq()) -print(type(pyb.rng())) diff --git a/tests/pyb/pyb_f405.py.exp b/tests/pyb/pyb_f405.py.exp deleted file mode 100644 index a90aa02686..0000000000 --- a/tests/pyb/pyb_f405.py.exp +++ /dev/null @@ -1,2 +0,0 @@ -(168000000, 168000000, 42000000, 84000000) - diff --git a/tests/pyb/pyb_f411.py b/tests/pyb/pyb_f411.py deleted file mode 100644 index 58d5fa2d41..0000000000 --- a/tests/pyb/pyb_f411.py +++ /dev/null @@ -1,9 +0,0 @@ -# test pyb module on F411 MCUs - -import os, pyb - -if not "STM32F411" in os.uname().machine: - print("SKIP") - raise SystemExit - -print(pyb.freq()) diff --git a/tests/pyb/pyb_f411.py.exp b/tests/pyb/pyb_f411.py.exp deleted file mode 100644 index 79e0a10621..0000000000 --- a/tests/pyb/pyb_f411.py.exp +++ /dev/null @@ -1 +0,0 @@ -(96000000, 96000000, 24000000, 48000000) diff --git a/tests/pyb/rtc.py b/tests/pyb/rtc.py deleted file mode 100644 index 41b52f260d..0000000000 --- a/tests/pyb/rtc.py +++ /dev/null @@ -1,84 +0,0 @@ -import pyb, stm -from pyb import RTC - -rtc = RTC() -rtc.init() -print(rtc) - -# make sure that 1 second passes correctly -rtc.datetime((2014, 1, 1, 1, 0, 0, 0, 0)) -pyb.delay(1002) -print(rtc.datetime()[:7]) - - -def set_and_print(datetime): - rtc.datetime(datetime) - print(rtc.datetime()[:7]) - - -# make sure that setting works correctly -set_and_print((2000, 1, 1, 1, 0, 0, 0, 0)) -set_and_print((2000, 1, 31, 1, 0, 0, 0, 0)) -set_and_print((2000, 12, 31, 1, 0, 0, 0, 0)) -set_and_print((2016, 12, 31, 1, 0, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 0, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 1, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 12, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 13, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 23, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 23, 1, 0, 0)) -set_and_print((2016, 12, 31, 7, 23, 59, 0, 0)) -set_and_print((2016, 12, 31, 7, 23, 59, 1, 0)) -set_and_print((2016, 12, 31, 7, 23, 59, 59, 0)) -set_and_print((2099, 12, 31, 7, 23, 59, 59, 0)) - -# check that calibration works correctly -# save existing calibration value: -cal_tmp = rtc.calibration() - - -def set_and_print_calib(cal): - rtc.calibration(cal) - print(rtc.calibration()) - - -set_and_print_calib(512) -set_and_print_calib(511) -set_and_print_calib(345) -set_and_print_calib(1) -set_and_print_calib(0) -set_and_print_calib(-1) -set_and_print_calib(-123) -set_and_print_calib(-510) -set_and_print_calib(-511) - -# restore existing calibration value -rtc.calibration(cal_tmp) - -# Check register settings for wakeup -def set_and_print_wakeup(ms): - try: - rtc.wakeup(ms) - wucksel = stm.mem32[stm.RTC + stm.RTC_CR] & 7 - wut = stm.mem32[stm.RTC + stm.RTC_WUTR] & 0xFFFF - except ValueError: - wucksel = -1 - wut = -1 - print((wucksel, wut)) - - -set_and_print_wakeup(0) -set_and_print_wakeup(1) -set_and_print_wakeup(4000) -set_and_print_wakeup(4001) -set_and_print_wakeup(8000) -set_and_print_wakeup(8001) -set_and_print_wakeup(16000) -set_and_print_wakeup(16001) -set_and_print_wakeup(32000) -set_and_print_wakeup(32001) -set_and_print_wakeup(0x10000 * 1000) -set_and_print_wakeup(0x10001 * 1000) -set_and_print_wakeup(0x1FFFF * 1000) -set_and_print_wakeup(0x20000 * 1000) -set_and_print_wakeup(0x20001 * 1000) # exception diff --git a/tests/pyb/rtc.py.exp b/tests/pyb/rtc.py.exp deleted file mode 100644 index 7d3aaf6af7..0000000000 --- a/tests/pyb/rtc.py.exp +++ /dev/null @@ -1,40 +0,0 @@ - -(2014, 1, 1, 1, 0, 0, 1) -(2000, 1, 1, 1, 0, 0, 0) -(2000, 1, 31, 1, 0, 0, 0) -(2000, 12, 31, 1, 0, 0, 0) -(2016, 12, 31, 1, 0, 0, 0) -(2016, 12, 31, 7, 0, 0, 0) -(2016, 12, 31, 7, 1, 0, 0) -(2016, 12, 31, 7, 12, 0, 0) -(2016, 12, 31, 7, 13, 0, 0) -(2016, 12, 31, 7, 23, 0, 0) -(2016, 12, 31, 7, 23, 1, 0) -(2016, 12, 31, 7, 23, 59, 0) -(2016, 12, 31, 7, 23, 59, 1) -(2016, 12, 31, 7, 23, 59, 59) -(2099, 12, 31, 7, 23, 59, 59) -512 -511 -345 -1 -0 --1 --123 --510 --511 -(3, 0) -(3, 15) -(3, 65535) -(2, 32775) -(2, 65535) -(1, 32771) -(1, 65535) -(0, 32769) -(0, 65535) -(4, 31) -(4, 65535) -(6, 0) -(6, 65534) -(6, 65535) -(-1, -1) diff --git a/tests/pyb/servo.py b/tests/pyb/servo.py deleted file mode 100644 index d15cafe483..0000000000 --- a/tests/pyb/servo.py +++ /dev/null @@ -1,16 +0,0 @@ -from pyb import Servo - -servo = Servo(1) -print(servo) - -servo.angle(0) -servo.angle(10, 100) - -servo.speed(-10) -servo.speed(10, 100) - -servo.pulse_width(1500) -print(servo.pulse_width()) - -servo.calibration(630, 2410, 1490, 2460, 2190) -print(servo.calibration()) diff --git a/tests/pyb/servo.py.exp b/tests/pyb/servo.py.exp deleted file mode 100644 index ac6032ba5f..0000000000 --- a/tests/pyb/servo.py.exp +++ /dev/null @@ -1,3 +0,0 @@ - -1500 -(630, 2410, 1490, 2460, 2190) diff --git a/tests/pyb/switch.py b/tests/pyb/switch.py deleted file mode 100644 index 7c44adb136..0000000000 --- a/tests/pyb/switch.py +++ /dev/null @@ -1,6 +0,0 @@ -from pyb import Switch - -sw = Switch() -print(sw()) -sw.callback(print) -sw.callback(None) diff --git a/tests/pyb/timer.py b/tests/pyb/timer.py deleted file mode 100644 index 61320690a6..0000000000 --- a/tests/pyb/timer.py +++ /dev/null @@ -1,13 +0,0 @@ -# check basic functionality of the timer class - -import pyb -from pyb import Timer - -tim = Timer(4) -tim = Timer(4, prescaler=100, period=200) -print(tim.prescaler()) -print(tim.period()) -tim.prescaler(300) -print(tim.prescaler()) -tim.period(400) -print(tim.period()) diff --git a/tests/pyb/timer.py.exp b/tests/pyb/timer.py.exp deleted file mode 100644 index 5c46230303..0000000000 --- a/tests/pyb/timer.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -100 -200 -300 -400 diff --git a/tests/pyb/timer_callback.py b/tests/pyb/timer_callback.py deleted file mode 100644 index 51242fba4b..0000000000 --- a/tests/pyb/timer_callback.py +++ /dev/null @@ -1,54 +0,0 @@ -# check callback feature of the timer class - -import pyb -from pyb import Timer - -# callback function that disables the callback when called -def cb1(t): - print("cb1") - t.callback(None) - - -# callback function that disables the timer when called -def cb2(t): - print("cb2") - t.deinit() - - -# callback where cb4 closes over cb3.y -def cb3(x): - y = x - - def cb4(t): - print("cb4", y) - t.callback(None) - - return cb4 - - -# create a timer with a callback, using callback(None) to stop -tim = Timer(1, freq=100, callback=cb1) -pyb.delay(5) -print("before cb1") -pyb.delay(15) - -# create a timer with a callback, using deinit to stop -tim = Timer(2, freq=100, callback=cb2) -pyb.delay(5) -print("before cb2") -pyb.delay(15) - -# create a timer, then set the freq, then set the callback -tim = Timer(4) -tim.init(freq=100) -tim.callback(cb1) -pyb.delay(5) -print("before cb1") -pyb.delay(15) - -# test callback with a closure -tim.init(freq=100) -tim.callback(cb3(3)) -pyb.delay(5) -print("before cb4") -pyb.delay(15) diff --git a/tests/pyb/timer_callback.py.exp b/tests/pyb/timer_callback.py.exp deleted file mode 100644 index 9be7cf5b90..0000000000 --- a/tests/pyb/timer_callback.py.exp +++ /dev/null @@ -1,8 +0,0 @@ -before cb1 -cb1 -before cb2 -cb2 -before cb1 -cb1 -before cb4 -cb4 3 diff --git a/tests/pyb/uart.py b/tests/pyb/uart.py deleted file mode 100644 index afa7b8b340..0000000000 --- a/tests/pyb/uart.py +++ /dev/null @@ -1,32 +0,0 @@ -from pyb import UART - -# test we can correctly create by id or name -for bus in (-1, 0, 1, 2, 3, 4, 5, 6, 7, "XA", "XB", "YA", "YB", "Z"): - try: - UART(bus, 9600) - print("UART", bus) - except ValueError: - print("ValueError", bus) - -uart = UART(1) -uart = UART(1, 9600) -uart = UART(1, 9600, bits=8, parity=None, stop=1) -print(uart) - -uart.init(2400) -print(uart) - -print(uart.any()) -print(uart.write("123")) -print(uart.write(b"abcd")) -print(uart.writechar(1)) - -# make sure this method exists -uart.sendbreak() - -# non-blocking mode -uart = UART(1, 9600, timeout=0) -print(uart.write(b"1")) -print(uart.write(b"abcd")) -print(uart.writechar(1)) -print(uart.read(100)) diff --git a/tests/pyb/uart.py.exp b/tests/pyb/uart.py.exp deleted file mode 100644 index b5fe0cd0bd..0000000000 --- a/tests/pyb/uart.py.exp +++ /dev/null @@ -1,24 +0,0 @@ -ValueError -1 -ValueError 0 -UART 1 -UART 2 -UART 3 -UART 4 -ValueError 5 -UART 6 -ValueError 7 -UART XA -UART XB -UART YA -UART YB -ValueError Z -UART(1, baudrate=9600, bits=8, parity=None, stop=1, timeout=1000, timeout_char=3, read_buf_len=64) -UART(1, baudrate=2400, bits=8, parity=None, stop=1, timeout=1000, timeout_char=7, read_buf_len=64) -0 -3 -4 -None -1 -4 -None -None diff --git a/tests/run-tests b/tests/run-tests index e28600361b..e00d6930f0 100755 --- a/tests/run-tests +++ b/tests/run-tests @@ -149,13 +149,15 @@ def run_micropython(pyb, args, test_file, is_special=False): else: # run on pyboard - import pyboard pyb.enter_raw_repl() try: output_mupy = pyb.execfile(test_file) - except pyboard.PyboardError: + except pyboard.PyboardError as e: had_crash = True - output_mupy = b'CRASH' + if not is_special and e.args[0] == 'exception': + output_mupy = e.args[1] + e.args[2] + b'CRASH' + else: + output_mupy = b'CRASH' # canonical form for all ports/platforms is to use \n for end-of-line output_mupy = output_mupy.replace(b'\r\n', b'\n') @@ -298,8 +300,12 @@ def run_tests(pyb, tests, args, base_path=".", num_threads=1): skip_tests.add('thread/stress_recurse.py') # has reliability issues if upy_float_precision == 0: + skip_tests.add('extmod/uctypes_le_float.py') + skip_tests.add('extmod/uctypes_native_float.py') + skip_tests.add('extmod/uctypes_sizeof_float.py') skip_tests.add('extmod/ujson_dumps_float.py') skip_tests.add('extmod/ujson_loads_float.py') + skip_tests.add('extmod/urandom_extra_float.py') skip_tests.add('misc/rge_sm.py') if upy_float_precision < 32: skip_tests.add('float/float2int_intbig.py') # requires fp32, there's float2int_fp30_intbig.py instead @@ -348,6 +354,16 @@ def run_tests(pyb, tests, args, base_path=".", num_threads=1): skip_tests.add('basics/subclass_native_init.py')# native subclassing corner cases not support skip_tests.add('misc/rge_sm.py') # too large skip_tests.add('micropython/opt_level.py') # don't assume line numbers are stored + elif args.target == 'nrf': + skip_tests.add('basics/memoryview1.py') # no item assignment for memoryview + skip_tests.add('extmod/ticks_diff.py') # unimplemented: utime.ticks_diff + skip_tests.add('extmod/time_ms_us.py') # unimplemented: utime.ticks_ms + skip_tests.add('extmod/urandom_basic.py') # unimplemented: urandom.seed + skip_tests.add('micropython/opt_level.py') # no support for line numbers + skip_tests.add('misc/non_compliant.py') # no item assignment for bytearray + for t in tests: + if t.startswith('basics/io_'): + skip_tests.add(t) # Some tests are known to fail on 64-bit machines if pyb is None and platform.architecture()[0] == '64bit': @@ -360,31 +376,21 @@ def run_tests(pyb, tests, args, base_path=".", num_threads=1): # Some tests are known to fail with native emitter # Remove them from the below when they work if args.emit == 'native': - skip_tests.update({'basics/%s.py' % t for t in 'gen_yield_from gen_yield_from_close gen_yield_from_ducktype gen_yield_from_exc gen_yield_from_executing gen_yield_from_iter gen_yield_from_send gen_yield_from_stopped gen_yield_from_throw gen_yield_from_throw2 gen_yield_from_throw3 generator1 generator2 generator_args generator_close generator_closure generator_exc generator_pend_throw generator_return generator_send'.split()}) # require yield + skip_tests.update({'basics/%s.py' % t for t in 'gen_yield_from gen_yield_from_close gen_yield_from_ducktype gen_yield_from_exc gen_yield_from_executing gen_yield_from_iter gen_yield_from_send gen_yield_from_stopped gen_yield_from_throw gen_yield_from_throw2 gen_yield_from_throw3 generator1 generator2 generator_args generator_close generator_closure generator_exc generator_name generator_pend_throw generator_return generator_send'.split()}) # require yield skip_tests.update({'basics/%s.py' % t for t in 'bytes_gen class_store_class globals_del string_join gen_stack_overflow'.split()}) # require yield - skip_tests.update({'basics/async_%s.py' % t for t in 'def await await2 for for2 with with2 coroutine'.split()}) # require yield + skip_tests.update({'basics/async_%s.py' % t for t in 'def await await2 for for2 with with2 with_break with_return coroutine'.split()}) # require yield skip_tests.update({'basics/%s.py' % t for t in 'try_reraise try_reraise2'.split()}) # require raise_varargs - skip_tests.update({'basics/%s.py' % t for t in 'with_break with_continue with_return'.split()}) # require complete with support - skip_tests.add('basics/array_construct2.py') # requires generators - skip_tests.add('basics/bool1.py') # seems to randomly fail - skip_tests.add('basics/builtin_hash_gen.py') # requires yield - skip_tests.add('basics/class_bind_self.py') # requires yield skip_tests.add('basics/del_deref.py') # requires checking for unbound local skip_tests.add('basics/del_local.py') # requires checking for unbound local skip_tests.add('basics/exception_chain.py') # raise from is not supported - skip_tests.add('basics/for_range.py') # requires yield_value - skip_tests.add('basics/try_finally_loops.py') # requires proper try finally code - skip_tests.add('basics/try_finally_return.py') # requires proper try finally code - skip_tests.add('basics/try_finally_return2.py') # requires proper try finally code + skip_tests.add('basics/scope_implicit.py') # requires checking for unbound local + skip_tests.add('basics/try_finally_return2.py') # requires raise_varargs skip_tests.add('basics/unboundlocal.py') # requires checking for unbound local - skip_tests.add('import/gen_context.py') # requires yield_value skip_tests.add('misc/features.py') # requires raise_varargs - skip_tests.add('misc/rge_sm.py') # requires yield skip_tests.add('misc/print_exception.py') # because native doesn't have proper traceback info skip_tests.add('misc/sys_exc_info.py') # sys.exc_info() is not supported for native skip_tests.add('micropython/emg_exc.py') # because native doesn't have proper traceback info skip_tests.add('micropython/heapalloc_traceback.py') # because native doesn't have proper traceback info - skip_tests.add('micropython/heapalloc_iter.py') # requires generators skip_tests.add('micropython/schedule.py') # native code doesn't check pending events skip_tests.add('stress/gc_trace.py') # requires yield skip_tests.add('stress/recursive_gen.py') # requires yield @@ -403,8 +409,8 @@ def run_tests(pyb, tests, args, base_path=".", num_threads=1): if verdict == "exclude": return - test_basename = os.path.basename(test_file) - test_name = os.path.splitext(test_basename)[0] + test_basename = test_file.replace('..', '_').replace('./', '').replace('/', '_') + test_name = os.path.splitext(os.path.basename(test_file))[0] is_native = test_name.startswith("native_") or test_name.startswith("viper_") is_endian = test_name.endswith("_endian") is_int_big = test_name.startswith("int_big") or test_name.endswith("_intbig") @@ -560,10 +566,12 @@ the last matching regex is used: cmd_parser.add_argument('files', nargs='*', help='input test files') args = cmd_parser.parse_args() - EXTERNAL_TARGETS = ('pyboard', 'wipy', 'esp8266', 'esp32', 'minimal') + EXTERNAL_TARGETS = ('pyboard', 'wipy', 'esp8266', 'esp32', 'minimal', 'nrf') if args.target == 'unix' or args.list_tests: pyb = None elif args.target in EXTERNAL_TARGETS: + global pyboard + sys.path.append('../tools') import pyboard pyb = pyboard.Pyboard(args.device, args.baudrate, args.user, args.password) pyb.enter_raw_repl() @@ -575,7 +583,7 @@ the last matching regex is used: if args.target == 'pyboard': # run pyboard tests test_dirs = ('basics', 'micropython', 'float', 'misc', 'stress', 'extmod', 'pyb', 'pybnative', 'inlineasm') - elif args.target in ('esp8266', 'esp32', 'minimal'): + elif args.target in ('esp8266', 'esp32', 'minimal', 'nrf'): test_dirs = ('basics', 'micropython', 'float', 'misc', 'extmod') elif args.target == 'wipy': # run WiPy tests diff --git a/tests/unicode/unicode.py b/tests/unicode/unicode.py index f5af9cfff4..072e049fde 100644 --- a/tests/unicode/unicode.py +++ b/tests/unicode/unicode.py @@ -47,3 +47,7 @@ try: str(bytearray(b"ab\xc0a"), "utf8") except UnicodeError: print("UnicodeError") +try: + str(b"\xf0\xe0\xed\xe8", "utf8") +except UnicodeError: + print("UnicodeError") diff --git a/tests/unix/ffi_float.py b/tests/unix/ffi_float.py index b12bce9682..d039398965 100644 --- a/tests/unix/ffi_float.py +++ b/tests/unix/ffi_float.py @@ -19,7 +19,14 @@ def ffi_open(names): libc = ffi_open(("libc.so", "libc.so.0", "libc.so.6", "libc.dylib")) -strtof = libc.func("f", "strtof", "sp") +try: + strtof = libc.func("f", "strtof", "sp") +except OSError: + # Some libc's (e.g. Android's Bionic) define strtof as macro/inline func + # in terms of strtod(). + print("SKIP") + raise SystemExit + print("%.6f" % strtof("1.23", None)) strtod = libc.func("d", "strtod", "sp") diff --git a/tests/wipy/adc.py b/tests/wipy/adc.py deleted file mode 100644 index 73264113f3..0000000000 --- a/tests/wipy/adc.py +++ /dev/null @@ -1,115 +0,0 @@ -""" -ADC test for the CC3200 based boards. -""" - -from machine import ADC -import os - -mch = os.uname().machine -if "LaunchPad" in mch: - adc_pin = "GP5" - adc_channel = 3 -elif "WiPy" in mch: - adc_pin = "GP3" - adc_channel = 1 -else: - raise Exception("Board not supported!") - -adc = ADC(0) -print(adc) -adc = ADC() -print(adc) -adc = ADC(0, bits=12) -print(adc) - -apin = adc.channel(adc_channel) -print(apin) -apin = adc.channel(id=adc_channel) -print(apin) -apin = adc.channel(adc_channel, pin=adc_pin) -print(apin) -apin = adc.channel(id=adc_channel, pin=adc_pin) -print(apin) - -print(apin.value() > 3000) -print(apin() > 3000) - -# de-init must work -apin.deinit() -print(apin) - -adc.deinit() -print(adc) -print(apin) -adc.init() -print(adc) -print(apin) -apin.init() -print(apin) -print(apin() > 3000) - -# check for memory leaks... -for i in range(0, 1000): - adc = ADC() - apin = adc.channel(adc_channel) - -# next ones should raise -try: - adc = ADC(bits=17) -except: - print("Exception") - -try: - adc = ADC(id=1) -except: - print("Exception") - -try: - adc = ADC(0, 16) -except: - print("Exception") - -adc = ADC() -try: - apin = adc.channel(4) -except: - print("Exception") - -try: - apin = adc.channel(-1) -except: - print("Exception") - -try: - apin = adc.channel(0, pin="GP3") -except: - print("Exception") - -apin = adc.channel(1) -apin.deinit() -try: - apin() -except: - print("Exception") - -try: - apin.value() -except: - print("Exception") - -adc.deinit() -try: - apin.value() -except: - print("Exception") - -try: - apin = adc.channel(1) -except: - print("Exception") - -# re-init must work -adc.init() -apin.init() -print(apin) -print(apin() > 3000) diff --git a/tests/wipy/adc.py.exp b/tests/wipy/adc.py.exp deleted file mode 100644 index a65cf4963b..0000000000 --- a/tests/wipy/adc.py.exp +++ /dev/null @@ -1,28 +0,0 @@ -ADC(0, bits=12) -ADC(0, bits=12) -ADC(0, bits=12) -ADCChannel(1, pin=GP3) -ADCChannel(1, pin=GP3) -ADCChannel(1, pin=GP3) -ADCChannel(1, pin=GP3) -True -True -ADCChannel(1) -ADC(0) -ADCChannel(1) -ADC(0, bits=12) -ADCChannel(1) -ADCChannel(1, pin=GP3) -True -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -ADCChannel(1, pin=GP3) -True diff --git a/tests/wipy/modwipy.py b/tests/wipy/modwipy.py deleted file mode 100644 index 59df3ae90a..0000000000 --- a/tests/wipy/modwipy.py +++ /dev/null @@ -1,21 +0,0 @@ -""" -wipy module test for the CC3200 based boards -""" - -import os -import wipy - -mch = os.uname().machine -if not "LaunchPad" in mch and not "WiPy" in mch: - raise Exception("Board not supported!") - -print(wipy.heartbeat() == True) -wipy.heartbeat(False) -print(wipy.heartbeat() == False) -wipy.heartbeat(True) -print(wipy.heartbeat() == True) - -try: - wipy.heartbeat(True, 1) -except: - print("Exception") diff --git a/tests/wipy/modwipy.py.exp b/tests/wipy/modwipy.py.exp deleted file mode 100644 index 52eeb534ee..0000000000 --- a/tests/wipy/modwipy.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -True -True -True -Exception diff --git a/tests/wipy/os.py b/tests/wipy/os.py deleted file mode 100644 index 1f4debcade..0000000000 --- a/tests/wipy/os.py +++ /dev/null @@ -1,164 +0,0 @@ -""" -os module test for the CC3200 based boards -""" - -from machine import SD -import os - -mch = os.uname().machine -if "LaunchPad" in mch: - sd_pins = ("GP16", "GP17", "GP15") -elif "WiPy" in mch: - sd_pins = ("GP10", "GP11", "GP15") -else: - raise Exception("Board not supported!") - -sd = SD(pins=sd_pins) - -os.mount(sd, "/sd") -os.mkfs("/sd") -os.chdir("/flash") -print(os.listdir()) - -os.chdir("/sd") -print(os.listdir()) - -# create a test directory in flash -os.mkdir("/flash/test") -os.chdir("/flash/test") -print(os.getcwd()) -os.chdir("..") -print(os.getcwd()) -os.chdir("test") -print(os.getcwd()) -# create a new file -f = open("test.txt", "w") -test_bytes = os.urandom(1024) -n_w = f.write(test_bytes) -print(n_w == len(test_bytes)) -f.close() -f = open("test.txt", "r") -r = bytes(f.read(), "ascii") -# check that we can write and read it correctly -print(r == test_bytes) -f.close() -os.rename("test.txt", "newtest.txt") -print(os.listdir()) -os.rename("/flash/test", "/flash/newtest") -print(os.listdir("/flash")) -os.remove("newtest.txt") -os.chdir("..") -os.rmdir("newtest") - -# create a test directory in the sd card -os.mkdir("/sd/test") -os.chdir("/sd/test") -print(os.getcwd()) -os.chdir("..") -print(os.getcwd()) -os.chdir("test") -print(os.getcwd()) -# create a new file -f = open("test.txt", "w") -test_bytes = os.urandom(1024) -n_w = f.write(test_bytes) -print(n_w == len(test_bytes)) -f.close() -f = open("test.txt", "r") -r = bytes(f.read(), "ascii") -# check that we can write and read it correctly -print(r == test_bytes) -f.close() - -print("CC3200" in os.uname().machine) -print("WiPy" == os.uname().sysname) - -os.sync() -os.stat("/flash") -os.stat("/flash/sys") -os.stat("/flash/boot.py") -os.stat("/sd") -os.stat("/") -os.chdir("/sd/test") -os.remove("test.txt") -os.chdir("/sd") -os.rmdir("test") -os.listdir("/sd") -print(os.listdir("/")) -os.unmount("/sd") -print(os.listdir("/")) -os.mkfs(sd) -os.mount(sd, "/sd") -print(os.listdir("/")) -os.chdir("/flash") - -# next ones must raise -sd.deinit() -try: - os.listdir("/sd") -except: - print("Exception") - -# re-initialization must work -sd.init() -print(os.listdir("/sd")) - -try: - os.mount(sd, "/sd") -except: - print("Exception") - -try: - os.mount(sd, "/sd2") -except: - print("Exception") - -os.unmount("/sd") -try: - os.listdir("/sd") -except: - print("Exception") - -try: - os.unmount("/flash") -except: - print("Exception") - -try: - os.unmount("/something") -except: - print("Exception") - -try: - os.unmount("something") -except: - print("Exception") - -try: - os.mkfs("flash") # incorrect path format -except: - print("Exception") - -try: - os.remove("/flash/nofile.txt") -except: - print("Exception") - -try: - os.rename("/flash/nofile.txt", "/flash/nofile2.txt") -except: - print("Exception") - -try: - os.chdir("/flash/nodir") -except: - print("Exception") - -try: - os.listdir("/flash/nodir") -except: - print("Exception") - -os.mount(sd, "/sd") -print(os.listdir("/")) -os.unmount("/sd") diff --git a/tests/wipy/os.py.exp b/tests/wipy/os.py.exp deleted file mode 100644 index a0f01e35e1..0000000000 --- a/tests/wipy/os.py.exp +++ /dev/null @@ -1,32 +0,0 @@ -['main.py', 'sys', 'lib', 'cert', 'boot.py'] -[] -/flash/test -/flash -/flash/test -True -True -['newtest.txt'] -['main.py', 'sys', 'lib', 'cert', 'boot.py', 'newtest'] -/sd/test -/sd -/sd/test -True -True -True -True -['flash', 'sd'] -['flash'] -['flash', 'sd'] -[] -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -['flash', 'sd'] diff --git a/tests/wipy/pin.py b/tests/wipy/pin.py deleted file mode 100644 index 43537bba5c..0000000000 --- a/tests/wipy/pin.py +++ /dev/null @@ -1,217 +0,0 @@ -""" -This test need a set of pins which can be set as inputs and have no external -pull up or pull down connected. -GP12 and GP17 must be connected together -""" -from machine import Pin -import os - -mch = os.uname().machine -if "LaunchPad" in mch: - pin_map = [ - "GP24", - "GP12", - "GP14", - "GP15", - "GP16", - "GP17", - "GP28", - "GP8", - "GP6", - "GP30", - "GP31", - "GP3", - "GP0", - "GP4", - "GP5", - ] - max_af_idx = 15 -elif "WiPy" in mch: - pin_map = [ - "GP23", - "GP24", - "GP12", - "GP13", - "GP14", - "GP9", - "GP17", - "GP28", - "GP22", - "GP8", - "GP30", - "GP31", - "GP0", - "GP4", - "GP5", - ] - max_af_idx = 15 -else: - raise Exception("Board not supported!") - -# test initial value -p = Pin("GP12", Pin.IN) -Pin("GP17", Pin.OUT, value=1) -print(p() == 1) -Pin("GP17", Pin.OUT, value=0) -print(p() == 0) - - -def test_noinit(): - for p in pin_map: - pin = Pin(p) - pin.value() - - -def test_pin_read(pull): - # enable the pull resistor on all pins, then read the value - for p in pin_map: - pin = Pin(p, mode=Pin.IN, pull=pull) - for p in pin_map: - print(pin()) - - -def test_pin_af(): - for p in pin_map: - for af in Pin(p).alt_list(): - if af[1] <= max_af_idx: - Pin(p, mode=Pin.ALT, alt=af[1]) - Pin(p, mode=Pin.ALT_OPEN_DRAIN, alt=af[1]) - - -# test un-initialized pins -test_noinit() -# test with pull-up and pull-down -test_pin_read(Pin.PULL_UP) -test_pin_read(Pin.PULL_DOWN) - -# test all constructor combinations -pin = Pin(pin_map[0]) -pin = Pin(pin_map[0], mode=Pin.IN) -pin = Pin(pin_map[0], mode=Pin.OUT) -pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.PULL_DOWN) -pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.PULL_UP) -pin = Pin(pin_map[0], mode=Pin.OPEN_DRAIN, pull=Pin.PULL_UP) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_DOWN) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=None) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.LOW_POWER) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.MED_POWER) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.HIGH_POWER) -pin = Pin(pin_map[0], mode=Pin.OUT, drive=pin.LOW_POWER) -pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_DOWN) -pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP) -pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP) -test_pin_af() # try the entire af range on all pins - -# test pin init and printing -pin = Pin(pin_map[0]) -pin.init(mode=Pin.IN) -print(pin) -pin.init(Pin.IN, Pin.PULL_DOWN) -print(pin) -pin.init(mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.LOW_POWER) -print(pin) -pin.init(mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.HIGH_POWER) -print(pin) - -# test value in OUT mode -pin = Pin(pin_map[0], mode=Pin.OUT) -pin.value(0) -pin.toggle() # test toggle -print(pin()) -pin.toggle() # test toggle again -print(pin()) -# test different value settings -pin(1) -print(pin.value()) -pin(0) -print(pin.value()) -pin.value(1) -print(pin()) -pin.value(0) -print(pin()) - -# test all getters and setters -pin = Pin(pin_map[0], mode=Pin.OUT) -# mode -print(pin.mode() == Pin.OUT) -pin.mode(Pin.IN) -print(pin.mode() == Pin.IN) -# pull -pin.pull(None) -print(pin.pull() == None) -pin.pull(Pin.PULL_DOWN) -print(pin.pull() == Pin.PULL_DOWN) -# drive -pin.drive(Pin.MED_POWER) -print(pin.drive() == Pin.MED_POWER) -pin.drive(Pin.HIGH_POWER) -print(pin.drive() == Pin.HIGH_POWER) -# id -print(pin.id() == pin_map[0]) - -# all the next ones MUST raise -try: - pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.IN) # incorrect drive value -except Exception: - print("Exception") - -try: - pin = Pin(pin_map[0], mode=Pin.LOW_POWER, pull=Pin.PULL_UP) # incorrect mode value -except Exception: - print("Exception") - -try: - pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.HIGH_POWER) # incorrect pull value -except Exception: - print("Exception") - -try: - pin = Pin("A0", Pin.OUT, Pin.PULL_DOWN) # incorrect pin id -except Exception: - print("Exception") - -try: - pin = Pin(pin_map[0], Pin.IN, Pin.PULL_UP, alt=0) # af specified in GPIO mode -except Exception: - print("Exception") - -try: - pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_UP, alt=7) # af specified in GPIO mode -except Exception: - print("Exception") - -try: - pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP, alt=0) # incorrect af -except Exception: - print("Exception") - -try: - pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=-1) # incorrect af -except Exception: - print("Exception") - -try: - pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=16) # incorrect af -except Exception: - print("Exception") - -try: - pin.mode(Pin.PULL_UP) # incorrect pin mode -except Exception: - print("Exception") - -try: - pin.pull(Pin.OUT) # incorrect pull -except Exception: - print("Exception") - -try: - pin.drive(Pin.IN) # incorrect drive strength -except Exception: - print("Exception") - -try: - pin.id("ABC") # id cannot be set -except Exception: - print("Exception") diff --git a/tests/wipy/pin.py.exp b/tests/wipy/pin.py.exp deleted file mode 100644 index 0e3dddcf2b..0000000000 --- a/tests/wipy/pin.py.exp +++ /dev/null @@ -1,60 +0,0 @@ -True -True -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -Pin('GP23', mode=Pin.IN, pull=None, drive=Pin.MED_POWER, alt=-1) -Pin('GP23', mode=Pin.IN, pull=Pin.PULL_DOWN, drive=Pin.MED_POWER, alt=-1) -Pin('GP23', mode=Pin.OUT, pull=Pin.PULL_UP, drive=Pin.LOW_POWER, alt=-1) -Pin('GP23', mode=Pin.OUT, pull=Pin.PULL_UP, drive=Pin.HIGH_POWER, alt=-1) -1 -0 -1 -0 -1 -0 -True -True -True -True -True -True -True -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception diff --git a/tests/wipy/pin_irq.py b/tests/wipy/pin_irq.py deleted file mode 100644 index be5e1f426c..0000000000 --- a/tests/wipy/pin_irq.py +++ /dev/null @@ -1,120 +0,0 @@ -""" -Pin IRQ test for the CC3200 based boards. -""" - -from machine import Pin -import machine -import os -import time - -mch = os.uname().machine -if "LaunchPad" in mch: - pins = ["GP16", "GP13"] -elif "WiPy" in mch: - pins = ["GP16", "GP13"] -else: - raise Exception("Board not supported!") - -pin0 = Pin(pins[0], mode=Pin.OUT, value=1) -pin1 = Pin(pins[1], mode=Pin.IN, pull=Pin.PULL_UP) - - -def pin_handler(pin_o): - global pin_irq_count_trigger - global pin_irq_count_total - global _trigger - if _trigger & pin1_irq.flags(): - pin_irq_count_trigger += 1 - pin_irq_count_total += 1 - - -pin_irq_count_trigger = 0 -pin_irq_count_total = 0 -_trigger = Pin.IRQ_FALLING -pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) -for i in range(0, 10): - pin0.toggle() - time.sleep_ms(5) -print(pin_irq_count_trigger == 5) -print(pin_irq_count_total == 5) - -pin_irq_count_trigger = 0 -pin_irq_count_total = 0 -_trigger = Pin.IRQ_RISING -pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) -for i in range(0, 200): - pin0.toggle() - time.sleep_ms(5) -print(pin_irq_count_trigger == 100) -print(pin_irq_count_total == 100) - -pin1_irq.disable() -pin0(1) -pin_irq_count_trigger = 0 -pin_irq_count_total = 0 -_trigger = Pin.IRQ_FALLING -pin1_irq.init(trigger=_trigger, handler=pin_handler) -pin0(0) -time.sleep_us(50) -print(pin_irq_count_trigger == 1) -print(pin_irq_count_total == 1) -pin0(1) -time.sleep_us(50) -print(pin_irq_count_trigger == 1) -print(pin_irq_count_total == 1) - -# check the call method -pin1_irq() -print(pin_irq_count_trigger == 1) # no flags since the irq was manually triggered -print(pin_irq_count_total == 2) - -pin1_irq.disable() -pin_irq_count_trigger = 0 -pin_irq_count_total = 0 -for i in range(0, 10): - pin0.toggle() - time.sleep_ms(5) -print(pin_irq_count_trigger == 0) -print(pin_irq_count_total == 0) - -# test waking up from suspended mode on low level -pin0(0) -t0 = time.ticks_ms() -pin1_irq.init(trigger=Pin.IRQ_LOW_LEVEL, wake=machine.SLEEP) -machine.sleep() -print(time.ticks_ms() - t0 < 10) -print("Awake") - -# test waking up from suspended mode on high level -pin0(1) -t0 = time.ticks_ms() -pin1_irq.init(trigger=Pin.IRQ_HIGH_LEVEL, wake=machine.SLEEP) -machine.sleep() -print(time.ticks_ms() - t0 < 10) -print("Awake") - -# check for memory leaks -for i in range(0, 1000): - pin0_irq = pin0.irq(trigger=_trigger, handler=pin_handler) - pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) - -# next ones must raise -try: - pin1_irq.init(trigger=123456, handler=pin_handler) -except: - print("Exception") - -try: - pin1_irq.init(trigger=Pin.IRQ_LOW_LEVEL, wake=1789456) -except: - print("Exception") - -try: - pin0_irq = pin0.irq( - trigger=Pin.IRQ_RISING, wake=machine.SLEEP - ) # GP16 can't wake up from DEEPSLEEP -except: - print("Exception") - -pin0_irq.disable() -pin1_irq.disable() diff --git a/tests/wipy/pin_irq.py.exp b/tests/wipy/pin_irq.py.exp deleted file mode 100644 index 458bd95668..0000000000 --- a/tests/wipy/pin_irq.py.exp +++ /dev/null @@ -1,19 +0,0 @@ -True -True -True -True -True -True -True -True -True -True -True -True -True -Awake -True -Awake -Exception -Exception -Exception diff --git a/tests/wipy/reset/reset.py b/tests/wipy/reset/reset.py deleted file mode 100644 index 8d314f3b49..0000000000 --- a/tests/wipy/reset/reset.py +++ /dev/null @@ -1,17 +0,0 @@ -""" -Reset script for the cc3200 boards -This is needed to force the board to reboot -with the default WLAN AP settings -""" - -from machine import WDT -import time -import os - -mch = os.uname().machine -if not "LaunchPad" in mch and not "WiPy" in mch: - raise Exception("Board not supported!") - -wdt = WDT(timeout=1000) -print(wdt) -time.sleep_ms(900) diff --git a/tests/wipy/reset/reset.py.exp b/tests/wipy/reset/reset.py.exp deleted file mode 100644 index 4b6cc11e0d..0000000000 --- a/tests/wipy/reset/reset.py.exp +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/wipy/rtc.py b/tests/wipy/rtc.py deleted file mode 100644 index c62e400fe3..0000000000 --- a/tests/wipy/rtc.py +++ /dev/null @@ -1,119 +0,0 @@ -""" -RTC test for the CC3200 based boards. -""" - -from machine import RTC -import os -import time - -mch = os.uname().machine -if not "LaunchPad" in mch and not "WiPy" in mch: - raise Exception("Board not supported!") - -rtc = RTC() -print(rtc) -print(rtc.now()[:6]) - -rtc = RTC(datetime=(2015, 8, 29, 9, 0, 0, 0, None)) -print(rtc.now()[:6]) - -rtc.deinit() -print(rtc.now()[:6]) - -rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) -print(rtc.now()[:6]) -seconds = rtc.now()[5] -time.sleep_ms(1000) -print(rtc.now()[5] - seconds == 1) -seconds = rtc.now()[5] -time.sleep_ms(2000) -print(rtc.now()[5] - seconds == 2) - -# initialization with shorter tuples -rtc.init((2015, 9, 19, 8, 0, 0, 0)) -print(rtc.now()[5]) -rtc.init((2015, 9, 19, 8, 0, 0)) -print(rtc.now()[5]) -rtc.init((2015, 9, 19, 8, 0)) -print(rtc.now()[5]) -rtc.init((2015, 9, 19, 8)) -print(rtc.now()[4]) -rtc.init((2015, 9, 19)) -print(rtc.now()[3]) - - -def set_and_print(datetime): - rtc.init(datetime) - print(rtc.now()[:6]) - - -# make sure that setting works correctly -set_and_print((2000, 1, 1, 0, 0, 0, 0, None)) -set_and_print((2000, 1, 31, 0, 0, 0, 0, None)) -set_and_print((2000, 12, 31, 0, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 0, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 0, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 1, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 12, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 13, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 23, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 23, 1, 0, 0, None)) -set_and_print((2016, 12, 31, 23, 59, 0, 50, None)) -set_and_print((2016, 12, 31, 23, 59, 1, 900, None)) -set_and_print((2016, 12, 31, 23, 59, 59, 100, None)) -set_and_print((2048, 12, 31, 23, 59, 59, 99999, None)) - -rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) -rtc.alarm(0, 5000) -rtc.alarm(time=2000) -time.sleep_ms(1000) -left = rtc.alarm_left() -print(abs(left - 1000) <= 10) -time.sleep_ms(1000) -print(rtc.alarm_left() == 0) -time.sleep_ms(100) -print(rtc.alarm_left(0) == 0) - -rtc.alarm(time=1000, repeat=True) -time.sleep_ms(1500) -left = rtc.alarm_left() -print(abs(left - 500) <= 15) - -rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) -rtc.alarm(time=(2015, 8, 29, 9, 0, 45)) -time.sleep_ms(1000) -left = rtc.alarm_left() -print(abs(left - 44000) <= 90) -rtc.alarm_cancel() -rtc.deinit() - -# next ones must raise -try: - rtc.alarm(5000) -except: - print("Exception") - -try: - rtc.alarm_left(1) -except: - print("Exception") - -try: - rtc.alarm_cancel(1) -except: - print("Exception") - -try: - rtc.alarm(5000) -except: - print("Exception") - -try: - rtc = RTC(200000000) -except: - print("Exception") - -try: - rtc = RTC((2015, 8, 29, 9, 0, 0, 0, None)) -except: - print("Exception") diff --git a/tests/wipy/rtc.py.exp b/tests/wipy/rtc.py.exp deleted file mode 100644 index 44f8f8b81c..0000000000 --- a/tests/wipy/rtc.py.exp +++ /dev/null @@ -1,37 +0,0 @@ - -(2015, 1, 1, 0, 0, 0) -(2015, 8, 29, 9, 0, 0) -(2015, 1, 1, 0, 0, 0) -(2015, 8, 29, 9, 0, 0) -True -True -0 -0 -0 -0 -0 -(2000, 1, 1, 0, 0, 0) -(2000, 1, 31, 0, 0, 0) -(2000, 12, 31, 0, 0, 0) -(2016, 12, 31, 0, 0, 0) -(2016, 12, 31, 0, 0, 0) -(2016, 12, 31, 1, 0, 0) -(2016, 12, 31, 12, 0, 0) -(2016, 12, 31, 13, 0, 0) -(2016, 12, 31, 23, 0, 0) -(2016, 12, 31, 23, 1, 0) -(2016, 12, 31, 23, 59, 0) -(2016, 12, 31, 23, 59, 1) -(2016, 12, 31, 23, 59, 59) -(2048, 12, 31, 23, 59, 59) -True -True -True -True -True -Exception -Exception -Exception -Exception -Exception -Exception diff --git a/tests/wipy/sd.py b/tests/wipy/sd.py deleted file mode 100644 index 381d46f30a..0000000000 --- a/tests/wipy/sd.py +++ /dev/null @@ -1,45 +0,0 @@ -""" -SD card test for the CC3200 based boards. -""" - -from machine import SD -import os - -mch = os.uname().machine -if "LaunchPad" in mch: - sd_pins = ("GP16", "GP17", "GP15") -elif "WiPy" in mch: - sd_pins = ("GP10", "GP11", "GP15") -else: - raise Exception("Board not supported!") - -sd = SD(pins=sd_pins) -print(sd) -sd.deinit() -print(sd) -sd.init(sd_pins) -print(sd) - -sd = SD(0, pins=sd_pins) -sd = SD(id=0, pins=sd_pins) -sd = SD(0, sd_pins) - -# check for memory leaks -for i in range(0, 1000): - sd = sd = SD(0, pins=sd_pins) - -# next ones should raise -try: - sd = SD(pins=()) -except Exception: - print("Exception") - -try: - sd = SD(pins=("GP10", "GP11", "GP8")) -except Exception: - print("Exception") - -try: - sd = SD(pins=("GP10", "GP11")) -except Exception: - print("Exception") diff --git a/tests/wipy/sd.py.exp b/tests/wipy/sd.py.exp deleted file mode 100644 index eaa5f08efb..0000000000 --- a/tests/wipy/sd.py.exp +++ /dev/null @@ -1,6 +0,0 @@ - - - -Exception -Exception -Exception diff --git a/tests/wipy/skipped/rtc_irq.py b/tests/wipy/skipped/rtc_irq.py deleted file mode 100644 index 99712f8d18..0000000000 --- a/tests/wipy/skipped/rtc_irq.py +++ /dev/null @@ -1,93 +0,0 @@ -""" -RTC IRQ test for the CC3200 based boards. -""" - -from machine import RTC -import machine -import os -import time - -mch = os.uname().machine -if not "LaunchPad" in mch and not "WiPy" in mch: - raise Exception("Board not supported!") - - -def rtc_ticks_ms(rtc): - timedate = rtc.now() - return (timedate[5] * 1000) + (timedate[6] // 1000) - - -rtc_irq_count = 0 - - -def alarm_handler(rtc_o): - global rtc_irq - global rtc_irq_count - if rtc_irq.flags() & RTC.ALARM0: - rtc_irq_count += 1 - - -rtc = RTC() -rtc.alarm(time=500, repeat=True) -rtc_irq = rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler) - -# active mode -time.sleep_ms(1000) -rtc.alarm_cancel() -print(rtc_irq_count == 2) -rtc_irq_count = 0 -rtc.alarm(time=200, repeat=True) -time.sleep_ms(1000) -rtc.alarm_cancel() -print(rtc_irq_count == 5) - -rtc_irq_count = 0 -rtc.alarm(time=100, repeat=True) -time.sleep_ms(1000) -rtc.alarm_cancel() -print(rtc_irq_count == 10) - -# deep sleep mode -rtc.alarm_cancel() -rtc_irq_count = 0 -rtc.alarm(time=50, repeat=True) -rtc_irq.init(trigger=RTC.ALARM0, handler=alarm_handler, wake=machine.SLEEP | machine.IDLE) -while rtc_irq_count < 3: - machine.sleep() -print(rtc_irq_count == 3) - -# no repetition -rtc.alarm_cancel() -rtc_irq_count = 0 -rtc.alarm(time=100, repeat=False) -time.sleep_ms(250) -print(rtc_irq_count == 1) - -rtc.alarm_cancel() -t0 = rtc_ticks_ms(rtc) -rtc.alarm(time=500, repeat=False) -machine.sleep() -t1 = rtc_ticks_ms(rtc) -print(abs(t1 - t0 - 500) < 20) - -# deep sleep repeated mode -rtc.alarm_cancel() -rtc_irq_count = 0 -rtc.alarm(time=500, repeat=True) -t0 = rtc_ticks_ms(rtc) -rtc_irq = rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler, wake=machine.SLEEP) -while rtc_irq_count < 3: - machine.sleep() - t1 = rtc_ticks_ms(rtc) - print(abs(t1 - t0 - (500 * rtc_irq_count)) < 25) - -# next ones must raise -try: - rtc_irq = rtc.irq(trigger=10, handler=alarm_handler) -except: - print("Exception") - -try: - rtc_irq = rtc.irq(trigger=RTC.ALARM0, wake=1789456) -except: - print("Exception") diff --git a/tests/wipy/skipped/rtc_irq.py.exp b/tests/wipy/skipped/rtc_irq.py.exp deleted file mode 100644 index a3eebc2d11..0000000000 --- a/tests/wipy/skipped/rtc_irq.py.exp +++ /dev/null @@ -1,11 +0,0 @@ -True -True -True -True -True -True -True -True -True -Exception -Exception diff --git a/tests/wipy/time.py b/tests/wipy/time.py deleted file mode 100644 index c1d105d64d..0000000000 --- a/tests/wipy/time.py +++ /dev/null @@ -1,93 +0,0 @@ -import time - -DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] - - -def is_leap(year): - return (year % 4) == 0 - - -def test(): - seconds = 0 - wday = 5 # Jan 1, 2000 was a Saturday - for year in range(2000, 2049): - print("Testing %d" % year) - yday = 1 - for month in range(1, 13): - if month == 2 and is_leap(year): - DAYS_PER_MONTH[2] = 29 - else: - DAYS_PER_MONTH[2] = 28 - for day in range(1, DAYS_PER_MONTH[month] + 1): - secs = time.mktime((year, month, day, 0, 0, 0, 0, 0)) - if secs != seconds: - print( - "mktime failed for %d-%02d-%02d got %d expected %d" - % (year, month, day, secs, seconds) - ) - tuple = time.localtime(seconds) - secs = time.mktime(tuple) - if secs != seconds: - print( - "localtime failed for %d-%02d-%02d got %d expected %d" - % (year, month, day, secs, seconds) - ) - return - seconds += 86400 - if yday != tuple[7]: - print( - "locatime for %d-%02d-%02d got yday %d, expecting %d" - % (year, month, day, tuple[7], yday) - ) - return - if wday != tuple[6]: - print( - "locatime for %d-%02d-%02d got wday %d, expecting %d" - % (year, month, day, tuple[6], wday) - ) - return - yday += 1 - wday = (wday + 1) % 7 - - -def spot_test(seconds, expected_time): - actual_time = time.localtime(seconds) - for i in range(len(actual_time)): - if actual_time[i] != expected_time[i]: - print( - "time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time - ) - return - print("time.localtime(", seconds, ") returned", actual_time, "(pass)") - - -test() -spot_test(0, (2000, 1, 1, 0, 0, 0, 5, 1)) -spot_test(1, (2000, 1, 1, 0, 0, 1, 5, 1)) -spot_test(59, (2000, 1, 1, 0, 0, 59, 5, 1)) -spot_test(60, (2000, 1, 1, 0, 1, 0, 5, 1)) -spot_test(3599, (2000, 1, 1, 0, 59, 59, 5, 1)) -spot_test(3600, (2000, 1, 1, 1, 0, 0, 5, 1)) -spot_test(-1, (1999, 12, 31, 23, 59, 59, 4, 365)) -spot_test(447549467, (2014, 3, 7, 23, 17, 47, 4, 66)) -spot_test(-940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) -spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) -spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) -spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) - -t1 = time.time() -time.sleep(2) -t2 = time.time() -print(abs(time.ticks_diff(t1, t2) - 2) <= 1) - -t1 = time.ticks_ms() -time.sleep_ms(50) -t2 = time.ticks_ms() -print(abs(time.ticks_diff(t1, t2) - 50) <= 1) - -t1 = time.ticks_us() -time.sleep_us(1000) -t2 = time.ticks_us() -print(time.ticks_diff(t1, t2) < 1500) - -print(time.ticks_diff(time.ticks_cpu(), time.ticks_cpu()) < 16384) diff --git a/tests/wipy/time.py.exp b/tests/wipy/time.py.exp deleted file mode 100644 index 24d798f929..0000000000 --- a/tests/wipy/time.py.exp +++ /dev/null @@ -1,65 +0,0 @@ -Testing 2000 -Testing 2001 -Testing 2002 -Testing 2003 -Testing 2004 -Testing 2005 -Testing 2006 -Testing 2007 -Testing 2008 -Testing 2009 -Testing 2010 -Testing 2011 -Testing 2012 -Testing 2013 -Testing 2014 -Testing 2015 -Testing 2016 -Testing 2017 -Testing 2018 -Testing 2019 -Testing 2020 -Testing 2021 -Testing 2022 -Testing 2023 -Testing 2024 -Testing 2025 -Testing 2026 -Testing 2027 -Testing 2028 -Testing 2029 -Testing 2030 -Testing 2031 -Testing 2032 -Testing 2033 -Testing 2034 -Testing 2035 -Testing 2036 -Testing 2037 -Testing 2038 -Testing 2039 -Testing 2040 -Testing 2041 -Testing 2042 -Testing 2043 -Testing 2044 -Testing 2045 -Testing 2046 -Testing 2047 -Testing 2048 -time.localtime( 0 ) returned (2000, 1, 1, 0, 0, 0, 5, 1) (pass) -time.localtime( 1 ) returned (2000, 1, 1, 0, 0, 1, 5, 1) (pass) -time.localtime( 59 ) returned (2000, 1, 1, 0, 0, 59, 5, 1) (pass) -time.localtime( 60 ) returned (2000, 1, 1, 0, 1, 0, 5, 1) (pass) -time.localtime( 3599 ) returned (2000, 1, 1, 0, 59, 59, 5, 1) (pass) -time.localtime( 3600 ) returned (2000, 1, 1, 1, 0, 0, 5, 1) (pass) -time.localtime( -1 ) returned (1999, 12, 31, 23, 59, 59, 4, 365) (pass) -time.localtime( 447549467 ) returned (2014, 3, 7, 23, 17, 47, 4, 66) (pass) -time.localtime( -940984933 ) returned (1970, 3, 7, 23, 17, 47, 5, 66) (pass) -time.localtime( -1072915199 ) returned (1966, 1, 1, 0, 0, 1, 5, 1) (pass) -time.localtime( -1072915200 ) returned (1966, 1, 1, 0, 0, 0, 5, 1) (pass) -time.localtime( -1072915201 ) returned (1965, 12, 31, 23, 59, 59, 4, 365) (pass) -True -True -True -True diff --git a/tests/wipy/timer.py b/tests/wipy/timer.py deleted file mode 100644 index db25870db0..0000000000 --- a/tests/wipy/timer.py +++ /dev/null @@ -1,118 +0,0 @@ -""" -Timer test for the CC3200 based boards. -""" - -from machine import Timer -import os -import time - -mch = os.uname().machine -if "LaunchPad" in mch: - pwm_pin = "GP24" -elif "WiPy" in mch: - pwm_pin = "GP24" -else: - raise Exception("Board not supported!") - -for i in range(4): - tim = Timer(i, mode=Timer.PERIODIC) - print(tim) - ch = tim.channel(Timer.A, freq=5) - print(ch) - ch = tim.channel(Timer.B, freq=5) - print(ch) - tim = Timer(i, mode=Timer.ONE_SHOT) - print(tim) - ch = tim.channel(Timer.A, freq=50) - print(ch) - ch = tim.channel(Timer.B, freq=50) - print(ch) - tim = Timer(i, mode=Timer.PWM) - print(tim) - ch = tim.channel(Timer.A, freq=50000, duty_cycle=2000, polarity=Timer.POSITIVE) - print(ch) - ch = tim.channel(Timer.B, freq=50000, duty_cycle=8000, polarity=Timer.NEGATIVE) - print(ch) - tim.deinit() - print(tim) - -for i in range(4): - tim = Timer(i, mode=Timer.PERIODIC) - tim.deinit() - - -class TimerTest: - def __init__(self): - self.tim = Timer(0, mode=Timer.PERIODIC) - self.int_count = 0 - - def timer_isr(self, tim_ch): - self.int_count += 1 - - -timer_test = TimerTest() -ch = timer_test.tim.channel(Timer.A, freq=5) -print(ch.freq() == 5) -ch.irq(handler=timer_test.timer_isr, trigger=Timer.TIMEOUT) -time.sleep_ms(1001) -print(timer_test.int_count == 5) - -ch.freq(100) -timer_test.int_count = 0 -time.sleep_ms(1001) -print(timer_test.int_count == 100) - -ch.freq(1000) -time.sleep_ms(1500) -timer_test.int_count = 0 -time.sleep_ms(2000) -print(timer_test.int_count == 2000) - -timer_test.tim.deinit() -timer_test.tim.init(mode=Timer.ONE_SHOT) -ch = timer_test.tim.channel(Timer.A, period=100000) -ch.irq(handler=timer_test.timer_isr, trigger=Timer.TIMEOUT) -timer_test.int_count = 0 -time.sleep_ms(101) -print(timer_test.int_count == 1) -time.sleep_ms(101) -print(timer_test.int_count == 1) -timer_test.tim.deinit() -print(timer_test.tim) - -# 32 bit modes -tim = Timer(0, mode=Timer.PERIODIC, width=32) -ch = tim.channel(Timer.A | Timer.B, period=5000000) - -# check for memory leaks... -for i in range(1000): - tim = Timer(0, mode=Timer.PERIODIC) - ch = tim.channel(Timer.A, freq=5) - -# next ones must fail -try: - tim = Timer(0, mode=12) -except: - print("Exception") - -try: - tim = Timer(4, mode=Timer.ONE_SHOT) -except: - print("Exception") - -try: - tim = Timer(0, mode=Timer.PWM, width=32) -except: - print("Exception") - -tim = Timer(0, mode=Timer.PWM) - -try: - ch = tim.channel(TIMER_A | TIMER_B, freq=10) -except: - print("Exception") - -try: - ch = tim.channel(TIMER_A, freq=4) -except: - print("Exception") diff --git a/tests/wipy/timer.py.exp b/tests/wipy/timer.py.exp deleted file mode 100644 index 972d8198cc..0000000000 --- a/tests/wipy/timer.py.exp +++ /dev/null @@ -1,52 +0,0 @@ -Timer(0, mode=Timer.PERIODIC) -timer.channel(Timer.A, freq=5) -timer.channel(Timer.B, freq=5) -Timer(0, mode=Timer.ONE_SHOT) -timer.channel(Timer.A, freq=50) -timer.channel(Timer.B, freq=50) -Timer(0, mode=Timer.PWM) -timer.channel(Timer.A, freq=50000, polarity=Timer.POSITIVE, duty_cycle=20.00) -timer.channel(Timer.B, freq=50000, polarity=Timer.NEGATIVE, duty_cycle=80.00) -Timer(0, mode=Timer.PWM) -Timer(1, mode=Timer.PERIODIC) -timer.channel(Timer.A, freq=5) -timer.channel(Timer.B, freq=5) -Timer(1, mode=Timer.ONE_SHOT) -timer.channel(Timer.A, freq=50) -timer.channel(Timer.B, freq=50) -Timer(1, mode=Timer.PWM) -timer.channel(Timer.A, freq=50000, polarity=Timer.POSITIVE, duty_cycle=20.00) -timer.channel(Timer.B, freq=50000, polarity=Timer.NEGATIVE, duty_cycle=80.00) -Timer(1, mode=Timer.PWM) -Timer(2, mode=Timer.PERIODIC) -timer.channel(Timer.A, freq=5) -timer.channel(Timer.B, freq=5) -Timer(2, mode=Timer.ONE_SHOT) -timer.channel(Timer.A, freq=50) -timer.channel(Timer.B, freq=50) -Timer(2, mode=Timer.PWM) -timer.channel(Timer.A, freq=50000, polarity=Timer.POSITIVE, duty_cycle=20.00) -timer.channel(Timer.B, freq=50000, polarity=Timer.NEGATIVE, duty_cycle=80.00) -Timer(2, mode=Timer.PWM) -Timer(3, mode=Timer.PERIODIC) -timer.channel(Timer.A, freq=5) -timer.channel(Timer.B, freq=5) -Timer(3, mode=Timer.ONE_SHOT) -timer.channel(Timer.A, freq=50) -timer.channel(Timer.B, freq=50) -Timer(3, mode=Timer.PWM) -timer.channel(Timer.A, freq=50000, polarity=Timer.POSITIVE, duty_cycle=20.00) -timer.channel(Timer.B, freq=50000, polarity=Timer.NEGATIVE, duty_cycle=80.00) -Timer(3, mode=Timer.PWM) -True -True -True -True -True -True -Timer(0, mode=Timer.ONE_SHOT) -Exception -Exception -Exception -Exception -Exception diff --git a/tests/wipy/uart.py b/tests/wipy/uart.py deleted file mode 100644 index 0b1744d4ff..0000000000 --- a/tests/wipy/uart.py +++ /dev/null @@ -1,164 +0,0 @@ -""" -UART test for the CC3200 based boards. -UART0 and UART1 must be connected together for this test to pass. -""" - -from machine import UART -from machine import Pin -import os -import time - -mch = os.uname().machine -if "LaunchPad" in mch: - uart_id_range = range(0, 2) - uart_pins = [ - [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], - [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], - ] -elif "WiPy" in mch: - uart_id_range = range(0, 2) - uart_pins = [ - [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], - [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], - ] -else: - raise Exception("Board not supported!") - -# just in case we have the repl duplicated on any of the uarts -os.dupterm(None) - -for uart_id in uart_id_range: - uart = UART(uart_id, 38400) - print(uart) - uart.init(57600, 8, None, 1, pins=uart_pins[uart_id][0]) - uart.init(baudrate=9600, stop=2, parity=UART.EVEN, pins=uart_pins[uart_id][1]) - uart.init(baudrate=115200, parity=UART.ODD, stop=0, pins=uart_pins[uart_id][0]) - uart = UART(baudrate=1000000) - uart.sendbreak() - -uart = UART(baudrate=1000000) -uart = UART() -print(uart) -uart = UART(baudrate=38400, pins=("GP12", "GP13")) -print(uart) -uart = UART(pins=("GP12", "GP13")) -print(uart) -uart = UART(pins=(None, "GP17")) -print(uart) -uart = UART(baudrate=57600, pins=("GP16", "GP17")) -print(uart) - -# now it's time for some loopback tests between the uarts -uart0 = UART(0, 1000000, pins=uart_pins[0][0]) -print(uart0) -uart1 = UART(1, 1000000, pins=uart_pins[1][0]) -print(uart1) - -print(uart0.write(b"123456") == 6) -print(uart1.read() == b"123456") - -print(uart1.write(b"123") == 3) -print(uart0.read(1) == b"1") -print(uart0.read(2) == b"23") -print(uart0.read() == None) - -uart0.write(b"123") -buf = bytearray(3) -print(uart1.readinto(buf, 1) == 1) -print(buf) -print(uart1.readinto(buf) == 2) -print(buf) - -# try initializing without the id -uart0 = UART(baudrate=1000000, pins=uart_pins[0][0]) -uart0.write(b"1234567890") -time.sleep_ms(2) # because of the fifo interrupt levels -print(uart1.any() == 10) -print(uart1.readline() == b"1234567890") -print(uart1.any() == 0) - -uart0.write(b"1234567890") -print(uart1.read() == b"1234567890") - -# tx only mode -uart0 = UART(0, 1000000, pins=("GP12", None)) -print(uart0.write(b"123456") == 6) -print(uart1.read() == b"123456") -print(uart1.write(b"123") == 3) -print(uart0.read() == None) - -# rx only mode -uart0 = UART(0, 1000000, pins=(None, "GP13")) -print(uart0.write(b"123456") == 6) -print(uart1.read() == None) -print(uart1.write(b"123") == 3) -print(uart0.read() == b"123") - -# leave pins as they were (rx only mode) -uart0 = UART(0, 1000000, pins=None) -print(uart0.write(b"123456") == 6) -print(uart1.read() == None) -print(uart1.write(b"123") == 3) -print(uart0.read() == b"123") - -# no pin assignment -uart0 = UART(0, 1000000, pins=(None, None)) -print(uart0.write(b"123456789") == 9) -print(uart1.read() == None) -print(uart1.write(b"123456789") == 9) -print(uart0.read() == None) -print(Pin.board.GP12) -print(Pin.board.GP13) - -# check for memory leaks... -for i in range(0, 1000): - uart0 = UART(0, 1000000) - uart1 = UART(1, 1000000) - -# next ones must raise -try: - UART(0, 9600, parity=None, pins=("GP12", "GP13", "GP7")) -except Exception: - print("Exception") - -try: - UART(0, 9600, parity=UART.ODD, pins=("GP12", "GP7")) -except Exception: - print("Exception") - -uart0 = UART(0, 1000000) -uart0.deinit() -try: - uart0.any() -except Exception: - print("Exception") - -try: - uart0.read() -except Exception: - print("Exception") - -try: - uart0.write("abc") -except Exception: - print("Exception") - -try: - uart0.sendbreak("abc") -except Exception: - print("Exception") - -try: - UART(2, 9600) -except Exception: - print("Exception") - -for uart_id in uart_id_range: - uart = UART(uart_id, 1000000) - uart.deinit() - # test printing an unitialized uart - print(uart) - # initialize it back and check that it works again - uart.init(115200) - print(uart) - uart.read() diff --git a/tests/wipy/uart.py.exp b/tests/wipy/uart.py.exp deleted file mode 100644 index c8aeb77eff..0000000000 --- a/tests/wipy/uart.py.exp +++ /dev/null @@ -1,52 +0,0 @@ -UART(0, baudrate=38400, bits=8, parity=None, stop=1) -UART(1, baudrate=38400, bits=8, parity=None, stop=1) -UART(0, baudrate=9600, bits=8, parity=None, stop=1) -UART(0, baudrate=38400, bits=8, parity=None, stop=1) -UART(0, baudrate=9600, bits=8, parity=None, stop=1) -UART(1, baudrate=9600, bits=8, parity=None, stop=1) -UART(1, baudrate=57600, bits=8, parity=None, stop=1) -UART(0, baudrate=1000000, bits=8, parity=None, stop=1) -UART(1, baudrate=1000000, bits=8, parity=None, stop=1) -True -True -True -True -True -True -True -bytearray(b'1\x00\x00') -True -bytearray(b'23\x00') -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -Pin('GP12', mode=Pin.IN, pull=None, drive=Pin.MED_POWER, alt=-1) -Pin('GP13', mode=Pin.IN, pull=None, drive=Pin.MED_POWER, alt=-1) -Exception -Exception -Exception -Exception -Exception -Exception -Exception -UART(0) -UART(0, baudrate=115200, bits=8, parity=None, stop=1) -UART(1) -UART(1, baudrate=115200, bits=8, parity=None, stop=1) diff --git a/tests/wipy/uart_irq.py b/tests/wipy/uart_irq.py deleted file mode 100644 index e631e46a9c..0000000000 --- a/tests/wipy/uart_irq.py +++ /dev/null @@ -1,157 +0,0 @@ -""" -UART IRQ test for the CC3200 based boards. -""" - -from machine import UART -import os -import time - -mch = os.uname().machine -if "LaunchPad" in mch: - uart_pins = [ - [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], - [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], - ] -elif "WiPy" in mch: - uart_pins = [ - [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], - [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], - ] -else: - raise Exception("Board not supported!") - -# just in case we have stdio duplicated on any of the uarts -os.dupterm(None) - -uart0 = UART(0, 1000000, pins=uart_pins[0][0]) -uart1 = UART(1, 1000000, pins=uart_pins[1][0]) - -uart0_int_count = 0 -uart1_int_count = 0 - - -def uart0_handler(uart_o): - global uart0_irq - global uart0_int_count - if uart0_irq.flags() & UART.RX_ANY: - uart0_int_count += 1 - - -def uart1_handler(uart_o): - global uart1_irq - global uart1_int_count - if uart1_irq.flags() & UART.RX_ANY: - uart1_int_count += 1 - - -uart0_irq = uart0.irq(trigger=UART.RX_ANY, handler=uart0_handler) -uart1_irq = uart1.irq(trigger=UART.RX_ANY, handler=uart1_handler) - -uart0.write(b"123") -# wait for the characters to be received -while not uart1.any(): - pass - -time.sleep_us(100) -print(uart1.any() == 3) -print(uart1_int_count > 0) -print(uart1_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b"123") - -uart1.write(b"12345") -# wait for the characters to be received -while not uart0.any(): - pass - -time.sleep_us(100) -print(uart0.any() == 5) -print(uart0_int_count > 0) -print(uart0_irq.flags() == 0) -print(uart1_irq.flags() == 0) -print(uart0.read() == b"12345") - -# do it again -uart1_int_count = 0 -uart0.write(b"123") -# wait for the characters to be received -while not uart1.any(): - pass - -time.sleep_us(100) -print(uart1.any() == 3) -print(uart1_int_count > 0) -print(uart1_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b"123") - -# disable the interrupt -uart1_irq.disable() -# do it again -uart1_int_count = 0 -uart0.write(b"123") -# wait for the characters to be received -while not uart1.any(): - pass - -time.sleep_us(100) -print(uart1.any() == 3) -print(uart1_int_count == 0) # no interrupt triggered this time -print(uart1_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b"123") - -# enable the interrupt -uart1_irq.enable() -# do it again -uart1_int_count = 0 -uart0.write(b"123") -# wait for the characters to be received -while not uart1.any(): - pass - -time.sleep_us(100) -print(uart1.any() == 3) -print(uart1_int_count > 0) -print(uart1_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b"123") - -uart1_irq.init(trigger=UART.RX_ANY, handler=None) # No handler -# do it again -uart1_int_count = 0 -uart0.write(b"123") -# wait for the characters to be received -while not uart1.any(): - pass - -time.sleep_us(100) -print(uart1.any() == 3) -print(uart1_int_count == 0) # no interrupt handler called -print(uart1_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b"123") - -# check for memory leaks -for i in range(0, 1000): - uart0_irq = uart0.irq(trigger=UART.RX_ANY, handler=uart0_handler) - uart1_irq = uart1.irq(trigger=UART.RX_ANY, handler=uart1_handler) - -# next ones must raise -try: - uart0_irq = uart0.irq(trigger=100, handler=uart0_handler) -except: - print("Exception") - -try: - uart0_irq = uart0.irq(trigger=0) -except: - print("Exception") - -try: - uart0_irq = uart0.irq(trigger=UART.RX_ANY, wake=Sleep.SUSPENDED) -except: - print("Exception") - -uart0_irq.disable() -uart1_irq.disable() diff --git a/tests/wipy/uart_irq.py.exp b/tests/wipy/uart_irq.py.exp deleted file mode 100644 index b165e824a0..0000000000 --- a/tests/wipy/uart_irq.py.exp +++ /dev/null @@ -1,33 +0,0 @@ -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -Exception -Exception -Exception diff --git a/tests/wipy/wdt.py b/tests/wipy/wdt.py deleted file mode 100644 index 56f6ea8d95..0000000000 --- a/tests/wipy/wdt.py +++ /dev/null @@ -1,38 +0,0 @@ -""" -WDT test for the CC3200 based boards -""" - -from machine import WDT -import time - -# test the invalid cases first -try: - wdt = WDT(1) -except Exception: - print("Exception") - -try: - wdt = WDT(0, 500) -except Exception: - print("Exception") - -try: - wdt = WDT(1, timeout=2000) -except Exception: - print("Exception") - -wdt = WDT(timeout=1000) -print(wdt) - -try: - wdt = WDT(0, timeout=2000) -except Exception: - print("Exception") - -time.sleep_ms(500) -wdt.feed() -print(wdt) -time.sleep_ms(900) -wdt.feed() -print(wdt) -time.sleep_ms(950) diff --git a/tests/wipy/wdt.py.exp b/tests/wipy/wdt.py.exp deleted file mode 100644 index 71f5e13b53..0000000000 --- a/tests/wipy/wdt.py.exp +++ /dev/null @@ -1,7 +0,0 @@ -Exception -Exception -Exception - -Exception - - diff --git a/tests/wipy/wlan/machine.py b/tests/wipy/wlan/machine.py deleted file mode 100644 index f69b117b74..0000000000 --- a/tests/wipy/wlan/machine.py +++ /dev/null @@ -1,42 +0,0 @@ -""" -machine test for the CC3200 based boards. -""" - -import machine -import os -from network import WLAN - -mch = os.uname().machine -if not "LaunchPad" in mch and not "WiPy" in mch: - raise Exception("Board not supported!") - -wifi = WLAN() - -print(machine) -machine.idle() -print(machine.freq() == (80000000,)) -print(machine.unique_id() == wifi.mac()) - -machine.main("main.py") - -rand_nums = [] -for i in range(0, 100): - rand = machine.rng() - if rand not in rand_nums: - rand_nums.append(rand) - else: - print("RNG number repeated") - break - -for i in range(0, 10): - machine.idle() - -print("Active") - -print(machine.reset_cause() >= 0) -print(machine.wake_reason() >= 0) - -try: - machine.main(123456) -except: - print("Exception") diff --git a/tests/wipy/wlan/machine.py.exp b/tests/wipy/wlan/machine.py.exp deleted file mode 100644 index cc5b3f61da..0000000000 --- a/tests/wipy/wlan/machine.py.exp +++ /dev/null @@ -1,7 +0,0 @@ - -True -True -Active -True -True -Exception diff --git a/tests/wipy/wlan/server.py b/tests/wipy/wlan/server.py deleted file mode 100644 index 40f56745c9..0000000000 --- a/tests/wipy/wlan/server.py +++ /dev/null @@ -1,41 +0,0 @@ -""" -network server test for the CC3200 based boards. -""" - -import os -import network - -mch = os.uname().machine -if not "LaunchPad" in mch and not "WiPy" in mch: - raise Exception("Board not supported!") - -server = network.Server() - -print(server.timeout() == 300) -print(server.isrunning() == True) -server.deinit() -print(server.isrunning() == False) - -server.init(login=("test-user", "test-password"), timeout=60) -print(server.isrunning() == True) -print(server.timeout() == 60) - -server.deinit() -print(server.isrunning() == False) -server.init() -print(server.isrunning() == True) - -try: - server.init(1) -except: - print("Exception") - -try: - server.init(0, login=("0000000000011111111111222222222222333333", "abc")) -except: - print("Exception") - -try: - server.timeout(1) -except: - print("Exception") diff --git a/tests/wipy/wlan/server.py.exp b/tests/wipy/wlan/server.py.exp deleted file mode 100644 index a125ec934d..0000000000 --- a/tests/wipy/wlan/server.py.exp +++ /dev/null @@ -1,10 +0,0 @@ -True -True -True -True -True -True -True -Exception -Exception -Exception diff --git a/tests/wipy/wlan/wlan.py b/tests/wipy/wlan/wlan.py deleted file mode 100644 index dd85c86967..0000000000 --- a/tests/wipy/wlan/wlan.py +++ /dev/null @@ -1,183 +0,0 @@ -""" -WLAN test for the CC3200 based boards. -""" - -from network import WLAN -import os -import time -import testconfig - -mch = os.uname().machine -if not "LaunchPad" in mch and not "WiPy" in mch: - raise Exception("Board not supported!") - - -def wait_for_connection(wifi, timeout=10): - while not wifi.isconnected() and timeout > 0: - time.sleep(1) - timeout -= 1 - if wifi.isconnected(): - print("Connected") - else: - print("Connection failed!") - - -wifi = WLAN(0, WLAN.STA) -print(wifi.mode() == WLAN.STA) -print(wifi.antenna() == WLAN.INT_ANT) - -wifi = WLAN(mode=WLAN.AP) -print(wifi.mode() == WLAN.AP) -print(wifi.channel() == 1) -print(wifi.auth() == None) -print(wifi.antenna() == WLAN.INT_ANT) -wifi = WLAN(0, mode=WLAN.AP, ssid="test-wlan", auth=(WLAN.WPA, "123456abc"), channel=7) -print(wifi.mode() == WLAN.AP) -print(wifi.channel() == 7) -print(wifi.ssid() == "test-wlan") -print(wifi.auth() == (WLAN.WPA, "123456abc")) -print(wifi.antenna() == WLAN.INT_ANT) - -wifi = WLAN(mode=WLAN.STA) -print(wifi.mode() == WLAN.STA) -time.sleep(5) # this ensures a full network scan -scan_r = wifi.scan() -print(len(scan_r) > 3) -for net in scan_r: - if net.ssid == testconfig.wlan_ssid: - # test that the scan results contains the desired params - print(len(net.bssid) == 6) - print(net.channel == None) - print(net.sec == testconfig.wlan_auth[0]) - print(net.rssi < 0) - print("Network found") - break - -wifi.mode(WLAN.STA) -print(wifi.mode() == WLAN.STA) -wifi.channel(7) -print(wifi.channel() == 7) -wifi.ssid("t-wlan") -print(wifi.ssid() == "t-wlan") -wifi.auth(None) -print(wifi.auth() == None) -wifi.auth((WLAN.WEP, "11223344556677889900")) -print(wifi.auth() == (WLAN.WEP, "11223344556677889900")) -wifi.antenna(WLAN.INT_ANT) -print(wifi.antenna() == WLAN.INT_ANT) - -wifi.antenna(WLAN.EXT_ANT) -print(wifi.antenna() == WLAN.EXT_ANT) -time.sleep(2) # this ensures a full network scan -scan_r = wifi.scan() -print(len(scan_r) > 3) -for net in scan_r: - if net.ssid == testconfig.wlan_ssid: - print("Network found") - break - -wifi.antenna(WLAN.INT_ANT) -wifi.mode(WLAN.STA) -print(wifi.mode() == WLAN.STA) -wifi.connect(testconfig.wlan_ssid, auth=testconfig.wlan_auth, timeout=10000) -wait_for_connection(wifi) - -wifi.ifconfig(config="dhcp") -wait_for_connection(wifi) -print("0.0.0.0" not in wifi.ifconfig()) -wifi.ifconfig(0, ("192.168.178.109", "255.255.255.0", "192.168.178.1", "8.8.8.8")) -wait_for_connection(wifi) -print(wifi.ifconfig(0) == ("192.168.178.109", "255.255.255.0", "192.168.178.1", "8.8.8.8")) -wait_for_connection(wifi) - -print(wifi.isconnected() == True) -wifi.disconnect() -print(wifi.isconnected() == False) - -t0 = time.ticks_ms() -wifi.connect(testconfig.wlan_ssid, auth=testconfig.wlan_auth, timeout=0) -print(time.ticks_ms() - t0 < 500) - -wifi.disconnect() -print(wifi.isconnected() == False) - -# test init again -wifi.init(WLAN.AP, ssid="www.wipy.io", auth=None, channel=5, antenna=WLAN.INT_ANT) -print(wifi.mode() == WLAN.AP) - -# get the current instance without re-init -wifi = WLAN() -print(wifi.mode() == WLAN.AP) -wifi = WLAN(0) -print(wifi.mode() == WLAN.AP) - -# test the MAC address length -print(len(wifi.mac()) == 6) - -# next ones MUST raise -try: - wifi.init(mode=12345) -except: - print("Exception") - -try: - wifi.init(1, mode=WLAN.AP) -except: - print("Exception") - -try: - wifi.init(mode=WLAN.AP, ssid=None) -except: - print("Exception") - -try: - wifi = WLAN(mode=WLAN.AP, channel=12) -except: - print("Exception") - -try: - wifi.antenna(2) -except: - print("Exception") - -try: - wifi.mode(10) -except: - print("Exception") - -try: - wifi.ssid( - "11111sdfasdfasdfasdf564sdf654asdfasdf123451245ssdgfsdf1111111111111111111111111234123412341234asdfasdf" - ) -except: - print("Exception") - -try: - wifi.auth((0)) -except: - print("Exception") - -try: - wifi.auth((0, None)) -except: - print("Exception") - -try: - wifi.auth((10, 10)) -except: - print("Exception") - -try: - wifi.channel(0) -except: - print("Exception") - -try: - wifi.ifconfig(1, "dhcp") -except: - print("Exception") - -try: - wifi.ifconfig(config=()) -except: - print("Exception") diff --git a/tests/wipy/wlan/wlan.py.exp b/tests/wipy/wlan/wlan.py.exp deleted file mode 100644 index 2bb3537a22..0000000000 --- a/tests/wipy/wlan/wlan.py.exp +++ /dev/null @@ -1,55 +0,0 @@ -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -Network found -True -True -True -True -True -True -True -True -Network found -True -Connected -Connected -True -Connected -True -Connected -True -True -True -True -True -True -True -True -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception diff --git a/tools/mpy-tool.py b/tools/mpy-tool.py index 42d62fdf11..9572f8f2aa 100755 --- a/tools/mpy-tool.py +++ b/tools/mpy-tool.py @@ -59,9 +59,9 @@ MP_BC_MAKE_CLOSURE = 0x62 MP_BC_MAKE_CLOSURE_DEFARGS = 0x63 MP_BC_RAISE_VARARGS = 0x5C # extra byte if caching enabled: -MP_BC_LOAD_NAME = 0x1C -MP_BC_LOAD_GLOBAL = 0x1D -MP_BC_LOAD_ATTR = 0x1E +MP_BC_LOAD_NAME = 0x1B +MP_BC_LOAD_GLOBAL = 0x1C +MP_BC_LOAD_ATTR = 0x1D MP_BC_STORE_ATTR = 0x26 # load opcode names @@ -163,6 +163,14 @@ def mp_opcode_format(bytecode, ip, opcode_format=make_opcode_format()): ip_start = ip f = (opcode_format[opcode >> 2] >> (2 * (opcode & 3))) & 3 if f == MP_OPCODE_QSTR: + if config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE: + if ( + opcode == MP_BC_LOAD_NAME + or opcode == MP_BC_LOAD_GLOBAL + or opcode == MP_BC_LOAD_ATTR + or opcode == MP_BC_STORE_ATTR + ): + ip += 1 ip += 3 else: extra_byte = ( @@ -319,7 +327,8 @@ class RawCode: opcode = "0x%02x" % opcode if f == 1: qst = self._unpack_qstr(ip + 1).qstr_id - print(" {}, {} & 0xff, {} >> 8,".format(opcode, qst, qst)) + extra = "" if sz == 3 else " 0x%02x," % self.bytecode[ip + 3] + print(" {}, {} & 0xff, {} >> 8,{}".format(opcode, qst, qst, extra)) else: print( " {},{}".format( @@ -419,10 +428,10 @@ class RawCode: n = struct.unpack("